File size: 12,378 Bytes
e3c2163
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# Issue Analysis and Resolution Plan

## Executive Summary

This document analyzes the multiple issues observed in the application logs, identifies root causes, and provides a comprehensive resolution plan with file-level and line-level tasks.

## Issues Identified

### 0. Web Search Implementation Issues (FIXED βœ…)

**Problems**:
1. DuckDuckGo used by default instead of Serper (even when Serper API key available)
2. Serper used invalid `source="serper"` (should be `source="web"`)
3. SearchXNG used invalid `source="searchxng"` (should be `source="web"`)
4. Serper and SearchXNG missing title truncation (would cause validation errors)
5. Missing tool name mappings in SearchHandler

**Root Causes**:
- Default `web_search_provider` was `"duckduckgo"` instead of `"auto"`
- No auto-detection logic to prefer Serper when API key available
- Source type mismatches with SourceName literal
- Missing title truncation in Serper/SearchXNG implementations

**Fixes Applied**:
- βœ… Changed default to `"auto"` with auto-detection logic
- βœ… Fixed Serper to use `source="web"` and add title truncation
- βœ… Fixed SearchXNG to use `source="web"` and add title truncation
- βœ… Added tool name mappings in SearchHandler
- βœ… Improved factory to auto-detect best available provider

**Status**: βœ… **FIXED** - All web search issues resolved

---

### 1. Citation Title Validation Error (FIXED βœ…)

**Error**: `1 validation error for Citation\ntitle\n  String should have at most 500 characters`

**Root Cause**: DuckDuckGo search results can return titles longer than 500 characters, but the `Citation` model enforces a maximum length of 500 characters.

**Location**: `src/tools/web_search.py:61`

**Fix Applied**: Added title truncation to 500 characters before creating Citation objects.

**Status**: βœ… **FIXED** - Code updated in `src/tools/web_search.py`

---

### 2. 403 Forbidden Errors on HuggingFace Inference API

**Error**: `status_code: 403, model_name: Qwen/Qwen3-Next-80B-A3B-Thinking, body: Forbidden`

**Root Causes**:
1. **OAuth Scope Missing**: The OAuth token may not have the `inference-api` scope required for accessing HuggingFace Inference API
2. **Model Access Restrictions**: Some models (e.g., `Qwen/Qwen3-Next-80B-A3B-Thinking`) may require:
   - Gated model access approval
   - Specific provider access
   - Account-level permissions
3. **Provider Selection**: Pydantic AI's `HuggingFaceProvider` doesn't support explicit provider selection (e.g., "nebius", "hyperbolic"), which may be required for certain models
4. **Token Format**: The OAuth token might not be correctly extracted or formatted

**Evidence from Logs**:
- OAuth authentication succeeds: `OAuth user authenticated username=Tonic`
- Token is extracted: `OAuth token extracted from oauth_token.token attribute`
- But API calls fail: `status_code: 403, model_name: Qwen/Qwen3-Next-80B-A3B-Thinking, body: Forbidden`

**Impact**: All LLM operations fail, causing:
- Planner agent execution failures
- Observation generation failures
- Knowledge gap evaluation failures
- Tool selection failures
- Judge assessment failures
- Report writing failures

**Status**: ⚠️ **INVESTIGATION REQUIRED**

---

### 3. 422 Unprocessable Entity Errors

**Error**: `status_code: 422, model_name: meta-llama/Llama-3.1-70B-Instruct, body: Unprocessable Entity`

**Root Cause**: 
- Model/provider compatibility issues
- The model `meta-llama/Llama-3.1-70B-Instruct` on provider `hyperbolic` may be in staging mode or have specific requirements
- Request format may not match provider expectations

**Evidence from Logs**:
- `Model meta-llama/Llama-3.1-70B-Instruct is in staging mode for provider hyperbolic. Meant for test purposes only.`
- Followed by: `status_code: 422, model_name: meta-llama/Llama-3.1-70B-Instruct, body: Unprocessable Entity`

**Impact**: Judge assessment fails, causing research loops to continue indefinitely with low confidence scores.

**Status**: ⚠️ **INVESTIGATION REQUIRED**

---

### 4. MCP Server Warning

**Warning**: `This MCP server includes a tool that has a gr.State input, which will not be updated between tool calls.`

**Root Cause**: Gradio MCP integration issue with state management.

**Impact**: Minor - functionality may be affected but not critical.

**Status**: ℹ️ **INFORMATIONAL**

---

### 5. Modal TTS Function Setup Failure

**Error**: `modal_tts_function_setup_failed error='Local state is not initialized - app is not locally available'`

**Root Cause**: Modal TTS function requires local Modal app initialization, which isn't available in HuggingFace Spaces environment.

**Impact**: Text-to-speech functionality unavailable, but not critical for core functionality.

**Status**: ℹ️ **INFORMATIONAL**

---

## Root Cause Analysis

### OAuth Token Flow

1. **Token Extraction** (`src/app.py:617-628`):
   ```python
   if hasattr(oauth_token, "token"):
       token_value = oauth_token.token
   ```
   βœ… **Working correctly** - Logs confirm token extraction

2. **Token Passing** (`src/app.py:125`, `src/agent_factory/judges.py:54`):
   ```python
   effective_api_key = oauth_token or os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACE_API_KEY")
   hf_provider = HuggingFaceProvider(api_key=effective_api_key)
   ```
   βœ… **Working correctly** - Token is passed to HuggingFaceProvider

3. **API Calls** (Pydantic AI internal):
   - Pydantic AI's `HuggingFaceProvider` uses `AsyncInferenceClient` internally
   - The `api_key` parameter should be passed to the underlying client
   - ❓ **Unknown**: Whether the token format or scope is correct

### HuggingFaceProvider Limitations

**Key Finding**: The code comments indicate:
```python
# Note: The hf_provider parameter is accepted but not used here because HuggingFaceProvider
# from pydantic-ai doesn't support provider selection. Provider selection happens at the
# InferenceClient level (used in HuggingFaceChatClient for advanced mode).
```

This means:
- `HuggingFaceProvider` doesn't support explicit provider selection (e.g., "nebius", "hyperbolic")
- Provider selection is automatic or uses default HuggingFace Inference API endpoint
- Some models may require specific providers, which can't be specified

### Model Access Issues

The logs show attempts to use:
- `Qwen/Qwen3-Next-80B-A3B-Thinking` - May require gated access
- `meta-llama/Llama-3.1-70B-Instruct` - May have provider-specific restrictions
- `Qwen/Qwen3-235B-A22B-Instruct-2507` - May require special permissions

---

## Resolution Plan

### Phase 1: Immediate Fixes (Completed)

βœ… **Task 1.1**: Fix Citation title validation error
- **File**: `src/tools/web_search.py`
- **Line**: 60-61
- **Change**: Add title truncation to 500 characters
- **Status**: βœ… **COMPLETED**

---

### Phase 2: OAuth Token Investigation and Fixes

#### Task 2.1: Add Token Validation and Debugging

**Files to Modify**:
- `src/utils/llm_factory.py`
- `src/agent_factory/judges.py`
- `src/app.py`

**Subtasks**:
1. Add token format validation (check if token is a valid string)
2. Add token length logging (without exposing actual token)
3. Add scope verification (if possible via API)
4. Add detailed error logging for 403 errors

**Line-Level Tasks**:
- `src/utils/llm_factory.py:139`: Add token validation before creating HuggingFaceProvider
- `src/agent_factory/judges.py:54`: Add token validation and logging
- `src/app.py:125`: Add token format validation

#### Task 2.2: Improve Error Handling for 403 Errors

**Files to Modify**:
- `src/agent_factory/judges.py`
- `src/agents/*.py` (all agent files)

**Subtasks**:
1. Catch `ModelHTTPError` with status_code 403 specifically
2. Provide user-friendly error messages
3. Suggest solutions (re-authenticate, check scope, use alternative model)
4. Log detailed error information for debugging

**Line-Level Tasks**:
- `src/agent_factory/judges.py:159`: Add specific 403 error handling
- `src/agents/knowledge_gap.py`: Add error handling in agent execution
- `src/agents/tool_selector.py`: Add error handling in agent execution
- `src/agents/thinking.py`: Add error handling in agent execution
- `src/agents/writer.py`: Add error handling in agent execution

#### Task 2.3: Add Fallback Mechanisms

**Files to Modify**:
- `src/agent_factory/judges.py`
- `src/utils/llm_factory.py`

**Subtasks**:
1. Define fallback model list (publicly available models)
2. Implement automatic fallback when primary model fails with 403
3. Log fallback model selection
4. Continue with fallback model if available

**Line-Level Tasks**:
- `src/agent_factory/judges.py:30-66`: Add fallback model logic in `get_model()`
- `src/utils/llm_factory.py:121-153`: Add fallback model logic in `get_pydantic_ai_model()`

#### Task 2.4: Document OAuth Scope Requirements

**Files to Create/Modify**:
- `docs/troubleshooting/oauth_403_errors.md` βœ… **CREATED**
- `README.md`: Add OAuth setup instructions
- `src/app.py:114-120`: Enhance existing comments

**Subtasks**:
1. Document required OAuth scopes
2. Provide troubleshooting steps
3. Add examples of correct OAuth configuration
4. Link to HuggingFace documentation

---

### Phase 3: 422 Error Handling

#### Task 3.1: Add 422 Error Handling

**Files to Modify**:
- `src/agent_factory/judges.py`
- `src/utils/llm_factory.py`

**Subtasks**:
1. Catch 422 errors specifically
2. Detect staging mode warnings
3. Automatically switch to alternative provider or model
4. Log provider/model compatibility issues

**Line-Level Tasks**:
- `src/agent_factory/judges.py:159`: Add 422 error handling
- `src/utils/llm_factory.py`: Add provider fallback logic

#### Task 3.2: Provider Selection Enhancement

**Files to Modify**:
- `src/utils/huggingface_chat_client.py`
- `src/app.py`

**Subtasks**:
1. Investigate if HuggingFaceProvider can be configured with provider
2. If not, use HuggingFaceChatClient for provider selection
3. Add provider fallback chain
4. Log provider selection and failures

**Line-Level Tasks**:
- `src/utils/huggingface_chat_client.py:29-64`: Enhance provider selection
- `src/app.py:154`: Consider using HuggingFaceChatClient for provider support

---

### Phase 4: Enhanced Logging and Monitoring

#### Task 4.1: Add Comprehensive Error Logging

**Files to Modify**:
- All agent files
- `src/agent_factory/judges.py`
- `src/utils/llm_factory.py`

**Subtasks**:
1. Log token presence (not value) at key points
2. Log model selection and provider
3. Log HTTP status codes and error bodies
4. Log fallback attempts and results

#### Task 4.2: Add User-Friendly Error Messages

**Files to Modify**:
- `src/app.py`
- `src/orchestrator/graph_orchestrator.py`

**Subtasks**:
1. Convert technical errors to user-friendly messages
2. Provide actionable solutions
3. Link to documentation
4. Suggest alternative models or configurations

---

## Implementation Priority

### High Priority (Blocking Issues)
1. βœ… Citation title validation (COMPLETED)
2. OAuth token validation and debugging
3. 403 error handling with fallback
4. User-friendly error messages

### Medium Priority (Quality Improvements)
5. 422 error handling
6. Provider selection enhancement
7. Comprehensive logging

### Low Priority (Nice to Have)
8. MCP server warning fix
9. Modal TTS setup (environment-specific)

---

## Testing Plan

### Unit Tests
- Test Citation title truncation with various lengths
- Test token validation logic
- Test fallback model selection
- Test error handling for 403, 422 errors

### Integration Tests
- Test OAuth token flow end-to-end
- Test model fallback chain
- Test provider selection
- Test error recovery

### Manual Testing
- Verify OAuth login with correct scope
- Test with various models
- Test error scenarios
- Verify user-friendly error messages

---

## Success Criteria

1. βœ… Citation validation errors eliminated
2. 403 errors handled gracefully with fallback
3. 422 errors handled with provider/model fallback
4. Clear error messages for users
5. Comprehensive logging for debugging
6. Documentation updated with troubleshooting steps

---

## References

- [HuggingFace OAuth Scopes](https://huggingface.co/docs/hub/oauth#currently-supported-scopes)
- [Pydantic AI HuggingFace Provider](https://ai.pydantic.dev/models/huggingface/)
- [HuggingFace Inference API](https://huggingface.co/docs/api-inference/index)
- [HuggingFace Inference Providers](https://huggingface.co/docs/api-inference/inference_providers)