Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix: Add comprehensive error handling and JSON parsing for question generation

Tushar Khatri4b5d55ae7013
diff --git a/src/agents/question/agents/generation_agent.py b/src/agents/question/agents/generation_agent.py
index a65aa0c92..4d0740215 100644
--- a/src/agents/question/agents/generation_agent.py
+++ b/src/agents/question/agents/generation_agent.py
@@ -221,8 +221,21 @@ class QuestionGenerationAgent(BaseAgent):
level="DEBUG",
)
- question = json.loads(response_content)
- self.current_question = question
+ # Parse JSON with error handling
+ try:
+ question = json.loads(response_content)
+ self.current_question = question
+ except json.JSONDecodeError as e:
+ error_msg = (
+ f"[generate_question] Failed to parse JSON response: {e}\n"
+ f"Response content: {response_content[:500]}..."
+ )
+ _logger.error(error_msg)
+ return Observation(
+ success=False,
+ result=None,
+ message=f"Failed to parse question JSON: {e}"
+ )
# Automatically submit after generation
submit_result = await self._action_submit_question()
@@ -269,20 +282,71 @@ class QuestionGenerationAgent(BaseAgent):
knowledge=knowledge_str,
)
- response = await self.client.chat.completions.create(
- model=self.model,
- messages=[
- {"role": "system", "content": "You are a professional question designer"},
- {"role": "user", "content": prompt},
- ],
- temperature=self._agent_params["temperature"],
- max_tokens=self._agent_params["max_tokens"],
- response_format={"type": "json_object"},
+ # Log request details
+ _logger.debug(
+ f"[refine_question] Calling LLM: model={self.model}, "
+ f"prompt_len={len(prompt)}, temperature={self._agent_params['temperature']}"
)
- # Extract response content
+ try:
+ response = await self.client.chat.completions.create(
+ model=self.model,
+ messages=[
+ {"role": "system", "content": "You are a professional question designer"},
+ {"role": "user", "content": prompt},
+ ],
+ temperature=self._agent_params["temperature"],
+ max_tokens=self._agent_params["max_tokens"],
+ response_format={"type": "json_object"},
+ timeout=180.0, # Add timeout
+ )
+ except Exception as e:
+ error_msg = f"[refine_question] LLM API call failed: {type(e).__name__}: {e}"
+ _logger.error(error_msg)
+ return Observation(
+ success=False,
+ result=None,
+ message=f"Failed to refine question: {e}"
+ )
+
+ # Validate response structure
+ if not response or not response.choices:
+ error_msg = "[refine_question] LLM returned empty response or no choices"
+ _logger.error(error_msg)
+ return Observation(
+ success=False,
+ result=None,
+ message="LLM returned empty response"
+ )
+
+ # Extract response content with validation
response_content = response.choices[0].message.content
+ # Validate content is not None or empty
+ if response_content is None:
+ error_msg = f"[refine_question] LLM returned None content. Response: {response}"
+ _logger.error(error_msg)
+ return Observation(
+ success=False,
+ result=None,
+ message="LLM returned None content"
+ )
+
+ if not response_content.strip():
+ error_msg = f"[refine_question] LLM returned empty string. Response: {response}"
+ _logger.error(error_msg)
+ return Observation(
+ success=False,
+ result=None,
+ message="LLM returned empty string"
+ )
+
+ # Log successful response
+ _logger.debug(
+ f"[refine_question] LLM response received: "
+ f"length={len(response_content)}, preview={response_content[:200]}..."
+ )
+
# Update token statistics if callback is available
input_tokens = 0
output_tokens = 0
@@ -310,8 +374,21 @@ class QuestionGenerationAgent(BaseAgent):
level="DEBUG",
)
- question = json.loads(response_content)
- self.current_question = question
+ # Parse JSON with error handling
+ try:
+ question = json.loads(response_content)
+ self.current_question = question
+ except json.JSONDecodeError as e:
+ error_msg = (
+ f"[refine_question] Failed to parse JSON response: {e}\n"
+ f"Response content: {response_content[:500]}..."
+ )
+ _logger.error(error_msg)
+ return Observation(
+ success=False,
+ result=None,
+ message=f"Failed to parse question JSON: {e}"
+ )
# Remove the processed feedback message
self.inbox.remove(feedback_msg)
diff --git a/src/agents/question/coordinator.py b/src/agents/question/coordinator.py
index c79a47f65..9822ec79d 100644
--- a/src/agents/question/coordinator.py
+++ b/src/agents/question/coordinator.py
@@ -248,6 +248,29 @@ class AgentCoordinator:
logging.getLogger(logger_name).propagate = False
self._logging_suppressed = True
+ def _extract_json_from_markdown(self, content: str) -> str:
+ """Extract JSON from markdown code blocks.
+
+ LLMs often wrap JSON in ```json ... ``` blocks. This method strips
+ the markdown formatting and any surrounding text.
+ """
+ if not content:
+ return content
+
+ # Remove leading explanatory text (look for the first ```json or ```)
+ import re
+
+ # Try to find JSON code block
+ json_block_pattern = r'```(?:json)?\s*\n?(.*?)```'
+ matches = re.findall(json_block_pattern, content, re.DOTALL)
+
+ if matches:
+ # Return the content inside the first code block
+ return matches[0].strip()
+
+ # If no code blocks found, return as-is (might already be valid JSON)
+ return content.strip()
+
async def _call_llm(
self,
system_prompt: str,
@@ -266,15 +289,58 @@ class AgentCoordinator:
{"role": "user", "content": user_prompt},
],
"temperature": 0.2,
+ "timeout": 180.0, # Add timeout to prevent hanging
}
if response_format:
kwargs["response_format"] = response_format
- response = await client.chat.completions.create(**kwargs)
+ # Log the request details for debugging
+ self.logger.debug(
+ f"[{stage or 'coordinator'}] Calling LLM: model={model}, "
+ f"system_prompt_len={len(system_prompt)}, user_prompt_len={len(user_prompt)}, "
+ f"response_format={response_format}"
+ )
+
+ try:
+ response = await client.chat.completions.create(**kwargs)
+ except Exception as e:
+ self.logger.error(
+ f"[{stage or 'coordinator'}] LLM API call failed: {type(e).__name__}: {e}"
+ )
+ self.logger.error(f"Request kwargs: {kwargs}")
+ raise RuntimeError(f"LLM call failed in stage '{stage}': {e}") from e
+
+ # Extract response content with validation
+ if not response or not response.choices:
+ error_msg = f"[{stage or 'coordinator'}] LLM returned empty response or no choices"
+ self.logger.error(error_msg)
+ raise ValueError(error_msg)
- # Extract response content
response_content = response.choices[0].message.content
+ # Validate content is not None or empty
+ if response_content is None:
+ error_msg = (
+ f"[{stage or 'coordinator'}] LLM returned None content. "
+ f"Response: {response}"
+ )
+ self.logger.error(error_msg)
+ raise ValueError(error_msg)
+
+ if not response_content.strip():
+ error_msg = (
+ f"[{stage or 'coordinator'}] LLM returned empty string. "
+ f"Response object: {response}"
+ )
+ self.logger.error(error_msg)
+ raise ValueError(error_msg)
+
+ # Log successful response
+ self.logger.debug(
+ f"[{stage or 'coordinator'}] LLM response received: "
+ f"length={len(response_content)}, preview={response_content[:200]}..."
+ )
+
# Track token usage
input_tokens = 0
output_tokens = 0
@@ -1647,6 +1713,9 @@ class AgentCoordinator:
"2. Be distinct from other focuses (different scenarios, applications, or perspectives)\n"
"3. Match the specified difficulty level\n"
"4. Be achievable with the provided background knowledge\n\n"
+ "CRITICAL: Return ONLY valid JSON. Do not wrap in markdown code blocks (```json). "
+ "Do not include any explanatory text before or after the JSON. "
+ "Your response must start with { and end with }.\n\n"
'Output JSON with key "focuses" containing an array of objects, each with:\n'
'- "id": string like "q_1", "q_2", etc.\n'
'- "focus": string describing what specific aspect this question will test\n'
@@ -1666,10 +1735,24 @@ class AgentCoordinator:
content = await self._call_llm(
system_prompt=system_prompt, user_prompt=user_prompt, stage="generate_question_plan"
)
- parsed = json.loads(content)
- focuses = parsed.get("focuses", [])
- if not isinstance(focuses, list):
+
+ # Validate content before JSON parsing
+ if not content or content.strip() == "":
+ self.logger.error("LLM returned empty content for question plan generation")
+ self.logger.error(f"Response content: {repr(content)}")
focuses = []
+ else:
+ try:
+ # Extract JSON from markdown code blocks if present
+ json_content = self._extract_json_from_markdown(content)
+ parsed = json.loads(json_content)
+ focuses = parsed.get("focuses", [])
+ if not isinstance(focuses, list):
+ focuses = []
+ except json.JSONDecodeError as json_err:
+ self.logger.error(f"JSON parsing failed for question plan: {json_err}")
+ self.logger.error(f"Response content (first 500 chars): {content[:500]}")
+ focuses = []
except Exception as e:
self.logger.warning(f"Failed to generate question plan: {e}")
focuses = []
@@ -1830,7 +1913,10 @@ class AgentCoordinator:
"1. The question must align with the specified focus\n"
"2. Use the background knowledge to ensure accuracy\n"
"3. Match the difficulty level\n"
- "4. Provide a detailed explanation\n"
+ "4. Provide a detailed explanation\n\n"
+ "CRITICAL: Return ONLY valid JSON. Do not wrap in markdown code blocks (```json). "
+ "Do not include any explanatory text before or after the JSON. "
+ "Your response must start with { and end with }.\n"
)
if question_type == "choice":
@@ -1866,12 +1952,32 @@ class AgentCoordinator:
user_prompt=user_prompt,
stage=f"generate_question_{question_id}",
)
- question = json.loads(content)
- question["knowledge_point"] = knowledge_point
- return {
- "success": True,
- "question": question,
- }
+
+ # Validate content before JSON parsing
+ if not content or content.strip() == "":
+ self.logger.error(f"LLM returned empty content for question {question_id}")
+ self.logger.error(f"Response content: {repr(content)}")
+ return {
+ "success": False,
+ "error": "LLM returned empty response",
+ }
+
+ try:
+ # Extract JSON from markdown code blocks if present
+ json_content = self._extract_json_from_markdown(content)
+ question = json.loads(json_content)
+ question["knowledge_point"] = knowledge_point
+ return {
+ "success": True,
+ "question": question,
+ }
+ except json.JSONDecodeError as json_err:
+ self.logger.error(f"JSON parsing failed for question {question_id}: {json_err}")
+ self.logger.error(f"Response content (first 500 chars): {content[:500]}")
+ return {
+ "success": False,
+ "error": f"Invalid JSON response: {str(json_err)}",
+ }
except Exception as e:
self.logger.error(f"Failed to generate question {question_id}: {e}")
return {