From ac6ef5672f55bd59e62ddd6147a6d808b4d77ca5 Mon Sep 17 00:00:00 2001 From: Purestone Date: Thu, 15 Jan 2026 04:14:42 +0800 Subject: [PATCH] feat: centralize JSON parsing with automatic repair fallback - Create reusable parse_json_response() utility in src/utils/json_parser.py - Replace hardcoded json.loads() calls across 6 question module files - Implement three-tier parsing strategy: 1. Extract JSON from markdown code blocks 2. Direct JSON parsing 3. Automated repair using json-repair library Files updated: - coordinator.py (7 json.loads calls) - generation_agent.py (2 json.loads calls) - validation_workflow.py (3 json.loads calls) - base_agent.py (1 json.loads call) - validation_agent.py (1 json.loads call) - question_extractor.py (1 json.loads call) Benefits: - Eliminates code duplication across agents - Consistent error handling and logging - Handles LLM responses in markdown code blocks - Gracefully repairs malformed JSON - Improves maintainability and testability --- src/agents/question/agents/base_agent.py | 3 +- .../question/agents/generation_agent.py | 17 ++- .../question/agents/validation_agent.py | 3 +- src/agents/question/coordinator.py | 30 ++--- .../question/tools/question_extractor.py | 7 +- src/agents/question/validation_workflow.py | 7 +- src/utils/json_parser.py | 110 ++++++++++++++++++ 7 files changed, 153 insertions(+), 24 deletions(-) create mode 100644 src/utils/json_parser.py diff --git a/src/agents/question/agents/base_agent.py b/src/agents/question/agents/base_agent.py index a8535d016..ec7c6a900 100644 --- a/src/agents/question/agents/base_agent.py +++ b/src/agents/question/agents/base_agent.py @@ -32,6 +32,7 @@ from src.services.config import get_agent_params from src.services.llm import complete as llm_complete from src.services.llm.capabilities import supports_response_format from src.services.llm.config import get_llm_config +from src.utils.json_parser import parse_json_response # Module logger _logger = get_logger("QuestionAgent") @@ -385,7 +386,7 @@ Output JSON format: level="DEBUG", ) - result = json.loads(response_content) + result = parse_json_response(response_content, logger_instance=_logger, fallback={}) # Record thought thought = result.get("thought", "") diff --git a/src/agents/question/agents/generation_agent.py b/src/agents/question/agents/generation_agent.py index 674cc5434..fc22f89e0 100644 --- a/src/agents/question/agents/generation_agent.py +++ b/src/agents/question/agents/generation_agent.py @@ -17,6 +17,7 @@ from src.logging import get_logger from src.services.config import load_config_with_main from src.services.prompt import get_prompt_manager from src.tools.rag_tool import rag_search +from src.utils.json_parser import parse_json_response from .base_agent import Action, BaseAgent, Message, Observation @@ -223,9 +224,13 @@ class QuestionGenerationAgent(BaseAgent): # Parse JSON with error handling try: - question = json.loads(response_content) + question = parse_json_response(response_content, logger_instance=_logger, fallback=None) + if question is None: + return Observation( + success=False, result=None, message="Failed to parse question JSON" + ) self.current_question = question - except json.JSONDecodeError as e: + except Exception as e: error_msg = ( f"[generate_question] Failed to parse JSON response: {e}\n" f"Response content: {response_content[:500]}..." @@ -360,9 +365,13 @@ class QuestionGenerationAgent(BaseAgent): # Parse JSON with error handling try: - question = json.loads(response_content) + question = parse_json_response(response_content, logger_instance=_logger, fallback=None) + if question is None: + return Observation( + success=False, result=None, message="Failed to parse question JSON" + ) self.current_question = question - except json.JSONDecodeError as e: + except Exception as e: error_msg = ( f"[refine_question] Failed to parse JSON response: {e}\n" f"Response content: {response_content[:500]}..." diff --git a/src/agents/question/agents/validation_agent.py b/src/agents/question/agents/validation_agent.py index 840433ff1..f4782a021 100644 --- a/src/agents/question/agents/validation_agent.py +++ b/src/agents/question/agents/validation_agent.py @@ -16,6 +16,7 @@ from src.logging import get_logger from src.services.config import load_config_with_main from src.services.prompt import get_prompt_manager from src.tools.rag_tool import rag_search +from src.utils.json_parser import parse_json_response from .base_agent import Action, BaseAgent, Message, Observation @@ -170,7 +171,7 @@ class QuestionValidationAgent(BaseAgent): response_format={"type": "json_object"}, ) - result = json.loads(response.choices[0].message.content) + result = parse_json_response(response.choices[0].message.content, logger_instance=_logger, fallback={}) self.validation_result = result # Ensure issues and suggestions are lists diff --git a/src/agents/question/coordinator.py b/src/agents/question/coordinator.py index 5460a3efe..87409694f 100644 --- a/src/agents/question/coordinator.py +++ b/src/agents/question/coordinator.py @@ -25,6 +25,7 @@ sys.path.insert(0, str(project_root)) from src.logging import Logger, get_logger from src.services.config import load_config_with_main from src.tools.rag_tool import rag_search +from src.utils.json_parser import parse_json_response def ensure_list(value: Any, default: list | None = None) -> list: @@ -411,7 +412,7 @@ class AgentCoordinator: try: content = await self._call_llm(system_prompt=system_prompt, user_prompt=user_prompt) - data = json.loads(content) + data = parse_json_response(content, logger_instance=self.logger, fallback={}) # Ensure queries is a list queries_raw = data.get("queries", []) @@ -592,7 +593,7 @@ class AgentCoordinator: ) try: content = await self._call_llm(system_prompt=system_prompt, user_prompt=user_prompt) - parsed = json.loads(content) + parsed = parse_json_response(content, logger_instance=self.logger, fallback={"relevant": False}) return bool(parsed.get("relevant")) except Exception as e: self.logger.warning(f"Failed to check retrieval relevance: {e}") @@ -616,7 +617,7 @@ class AgentCoordinator: ) try: content = await self._call_llm(system_prompt=system_prompt, user_prompt=user_prompt) - parsed = json.loads(content) + parsed = parse_json_response(content, logger_instance=self.logger, fallback={}) # Ensure requirements is a list requirements_raw = parsed.get("requirements", []) @@ -648,7 +649,7 @@ class AgentCoordinator: user_prompt = f"Requirement:\n{requirement_text}\n\nReturn JSON only." try: content = await self._call_llm(system_prompt=system_prompt, user_prompt=user_prompt) - parsed = json.loads(content) + parsed = parse_json_response(content, logger_instance=self.logger, fallback={}) except Exception as e: self.logger.warning(f"Failed to interpret requirement text: {e}") parsed = {} @@ -1206,7 +1207,7 @@ class AgentCoordinator: content = await self._call_llm( system_prompt=system_prompt, user_prompt=user_prompt, stage="plan_sub_focuses" ) - parsed = json.loads(content) + parsed = parse_json_response(content, logger_instance=self.logger, fallback={}) focuses = parsed.get("focuses", []) if not isinstance(focuses, list): focuses = [] @@ -1746,13 +1747,12 @@ class AgentCoordinator: focuses = [] else: try: - # Extract JSON from markdown code blocks if present - json_content = self._extract_json_from_markdown(content) - parsed = json.loads(json_content) + # Use the new utility function for robust JSON parsing + parsed = parse_json_response(content, logger_instance=self.logger, fallback={}) focuses = parsed.get("focuses", []) if not isinstance(focuses, list): focuses = [] - except json.JSONDecodeError as json_err: + except Exception 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 = [] @@ -1966,15 +1966,19 @@ class AgentCoordinator: } try: - # Extract JSON from markdown code blocks if present - json_content = self._extract_json_from_markdown(content) - question = json.loads(json_content) + # Use robust JSON parsing utility + question = parse_json_response(content, logger_instance=self.logger, fallback=None) + if question is None: + return { + "success": False, + "error": "Failed to parse question JSON", + } question["knowledge_point"] = knowledge_point return { "success": True, "question": question, } - except json.JSONDecodeError as json_err: + except Exception 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 { diff --git a/src/agents/question/tools/question_extractor.py b/src/agents/question/tools/question_extractor.py index 03b654351..bf0859320 100644 --- a/src/agents/question/tools/question_extractor.py +++ b/src/agents/question/tools/question_extractor.py @@ -27,6 +27,7 @@ from src.services.config import get_agent_params from src.services.llm import complete as llm_complete from src.services.llm.capabilities import supports_response_format from src.services.llm.config import get_llm_config +from src.utils.json_parser import parse_json_response def load_parsed_paper(paper_dir: Path) -> tuple[str | None, list[dict] | None, Path]: @@ -243,8 +244,10 @@ Please analyze the above exam paper content, extract all question information, a try: if not result_text: raise ValueError("LLM returned empty or None response") - result = json.loads(result_text) - except json.JSONDecodeError as e: + result = parse_json_response(result_text, logger_instance=None, fallback={}) + if result is None: + raise ValueError("JSON parsing returned None") + except Exception as e: print(f"✗ JSON parsing error: {e!s}") print(f"LLM response content: {result_text[:500]}...") raise ValueError( diff --git a/src/agents/question/validation_workflow.py b/src/agents/question/validation_workflow.py index bf727e5e2..f710107ae 100644 --- a/src/agents/question/validation_workflow.py +++ b/src/agents/question/validation_workflow.py @@ -27,6 +27,7 @@ from src.services.llm.capabilities import supports_response_format from src.services.llm.config import get_llm_config from src.services.prompt import get_prompt_manager from src.tools.rag_tool import rag_search +from src.utils.json_parser import parse_json_response # Module logger logger = get_logger("QuestionValidation") @@ -329,7 +330,7 @@ Output the retrieval query directly, no additional content. level="DEBUG", ) - result = json.loads(response_content) + result = parse_json_response(response_content, logger_instance=logger, fallback={}) # Ensure issues and suggestions are lists (handle case where LLM returns dict) issues = result.get("issues", []) @@ -465,7 +466,7 @@ Output only the JSON, no additional text.""" input_tokens=input_tokens, output_tokens=output_tokens, model=self.model ) - result = json.loads(response_content) + result = parse_json_response(response_content, logger_instance=logger, fallback={}) logger.info("Extension analysis completed") @@ -588,7 +589,7 @@ Output only the JSON, no additional text.""" level="DEBUG", ) - result = json.loads(response_content) + result = parse_json_response(response_content, logger_instance=logger, fallback={}) relevance = result.get("relevance", "partial") if relevance not in ["high", "partial"]: diff --git a/src/utils/json_parser.py b/src/utils/json_parser.py new file mode 100644 index 000000000..31aae0358 --- /dev/null +++ b/src/utils/json_parser.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Robust JSON parsing utilities with automatic repair and markdown extraction. + +Provides safe JSON parsing that handles: +- Markdown code block wrapping (```json...```) +- Malformed JSON (missing commas, trailing commas, etc.) +- Unescaped newlines and control characters +- Empty responses +""" + +import json +import logging +import re +from typing import Any + +try: + from json_repair import repair_json +except ImportError: + repair_json = None + +logger = logging.getLogger(__name__) + + +def parse_json_response( + response: str, + logger_instance: logging.Logger | None = None, + fallback: Any = None, +) -> Any: + """ + Safely parse JSON from LLM responses with automatic repair. + + Implements a three-tier parsing strategy: + 1. Extract JSON from markdown code blocks if present + 2. Direct JSON parsing + 3. Automated repair using json-repair library with fallback + + Args: + response: Raw string response from LLM + logger_instance: Logger instance for debugging (optional) + fallback: Value to return if all parsing fails (default: {}) + + Returns: + Parsed JSON object, or fallback value if parsing fails + + Example: + >>> response = '```json\\n{"key": "value"}\\n```' + >>> data = parse_json_response(response) + >>> data + {'key': 'value'} + """ + log = logger_instance or logger + + if fallback is None: + fallback = {} + + # Handle empty response + if not response or not response.strip(): + log.warning("LLM returned empty response") + return fallback + + # Extract from markdown code blocks if present + extracted_response = response + if "```" in response: + json_match = re.search(r"```(?:json)?\s*\n?(.*?)```", response, re.DOTALL) + if json_match: + extracted_response = json_match.group(1).strip() + log.debug("Extracted JSON from markdown code block") + + # Strategy 1: Direct parsing + try: + return json.loads(extracted_response) + except json.JSONDecodeError as parse_error: + log.debug(f"Direct JSON parse failed: {parse_error}") + + # Strategy 2: Try json-repair if available + if repair_json is None: + log.warning("json-repair library not installed, cannot repair malformed JSON") + log.debug(f"Response: {extracted_response[:200]}") + return fallback + + try: + log.debug("Attempting JSON repair") + repaired = repair_json(extracted_response) + result = json.loads(repaired) + log.info("Successfully repaired malformed JSON") + return result + except Exception as repair_error: + log.error(f"JSON repair failed: {repair_error}") + log.debug(f"Response: {extracted_response[:200]}") + return fallback + + +def safe_json_loads(data: str, fallback: Any = None) -> Any: + """ + Simple wrapper for safe JSON loading. + + Args: + data: JSON string + fallback: Value to return on failure (default: {}) + + Returns: + Parsed JSON or fallback value + """ + try: + return json.loads(data) + except json.JSONDecodeError as e: + logger.warning(f"JSON parse error: {e}") + return fallback if fallback is not None else {}