{"record":{"id":"b9c65e0be70dcd62","repo":"datawhalechina/hello-agents","slug":"error-b9c65e","errorCode":null,"errorMessage":"缺少健康指标分析结果","messagePattern":"缺少健康指标分析结果","errorType":"exception","errorClass":"AgentException","httpStatus":null,"severity":"error","filePath":"Co-creation-projects/Shawnxyxy-HealthRecordAgent/backend/agents/risk_assess.py","lineNumber":17,"sourceCode":"\"\"\"\n健康风险评估 Agent\n\"\"\"\nimport json\nfrom typing import Dict, Any, List\nfrom agents.base import BaseAgent\nfrom core.exceptions import AgentException\n\nclass RiskAssessmentAgent(BaseAgent):\n    def __init__(self, task_id=None, llm=None):\n        super().__init__(name=\"RiskAssessment\", task_id=task_id, llm=llm)\n\n    async def run(self, input_data: Dict[str, Any]) -> Dict[str, Any]:\n        try:\n            indicator_results = input_data[\"indicator_results\"]\n            if not indicator_results:\n                raise AgentException(\"缺少健康指标分析结果\")\n            self.set_state(\"running\")\n\n            result = await self._assess_risk(indicator_results)\n\n            self.set_state(\"completed\")\n            return result\n        except Exception as e:\n            self.set_state(\"error\")\n            raise AgentException(f\"RiskAssessmentAgent 执行失败: {str(e)}\")\n\n    async def _assess_risk(self, indicator_results: Dict[str, Any]) -> Dict[str, Any]:\n        risk_prompt = f\"\"\"\n你是一名专业的健康风险评估专家。\n\n以下是某用户的健康指标分析结果（已由其他智能体完成分析）：\n{indicator_results}\n\n请你完成以下任务：","sourceCodeStart":1,"sourceCodeEnd":35,"githubUrl":"https://github.com/datawhalechina/hello-agents/blob/606a07d341a47be773fab7f4b71177f53f96b2c3/Co-creation-projects/Shawnxyxy-HealthRecordAgent/backend/agents/risk_assess.py#L1-L35","documentation":"Raised by RiskAssessmentAgent.run when the 'indicator_results' key in input_data is missing, empty, or falsy. This is a pipeline precondition check: the risk-assessment agent refuses to run without the upstream health-indicator analysis output. It is thrown before any state transition to 'running', so no LLM call is wasted.","triggerScenarios":"Calling RiskAssessmentAgent.run(input_data) where input_data lacks the 'indicator_results' key, or where its value is an empty dict/list, None, or empty string. Typically happens when the upstream IndicatorAgent failed or its output key name doesn't match ('indicator_results' vs e.g. 'result').","commonSituations":"Multi-agent pipeline wiring mistakes (upstream agent returns {'result': ...} but downstream expects 'indicator_results'); upstream agent silently returned an empty result on parse failure; orchestrator passes the wrong dict.","solutions":["Inspect the orchestrator/pipeline code that builds input_data and confirm the upstream agent's output dict uses the exact key 'indicator_results'.","Check the upstream IndicatorAgent for silent empty returns (JSON parse failures often yield {}); log its raw output.","Add a guard before dispatch: only run RiskAssessmentAgent when indicator_results is non-empty, and route to an error state otherwise.","Note that the bare except at line 26 will re-wrap this as 'RiskAssessmentAgent 执行失败: 缺少健康指标分析结果' — read the inner message for the real cause."],"exampleFix":"// before\nresult = await risk_agent.run({})  # KeyError-free but empty -> raises\n\n// after\nindicator_results = upstream.get('indicator_results')\nif not indicator_results:\n    raise AgentException('upstream indicator analysis missing; run IndicatorAgent first')\nresult = await risk_agent.run({'indicator_results': indicator_results})","handlingStrategy":"validation","validationCode":"def has_indicator_results(input_data: dict) -> bool:\n    return bool(isinstance(input_data, dict) and input_data.get(\"indicator_results\"))","typeGuard":"from typing import Dict, Any\n\ndef is_valid_risk_input(input_data: Dict[str, Any]) -> bool:\n    \"\"\"Narrows input to the shape RiskAssessmentAgent.run requires.\"\"\"\n    return (\n        isinstance(input_data, dict)\n        and isinstance(input_data.get(\"indicator_results\"), (dict, list))\n        and len(input_data[\"indicator_results\"]) > 0\n    )","tryCatchPattern":"try:\n    result = await risk_agent.run(input_data)\nexcept AgentException as e:\n    if \"缺少健康指标分析结果\" in str(e):\n        # upstream produced nothing; do not retry with same input\n        log.warning(\"indicator stage empty; routing to error flow\")\n    else:\n        raise","preventionTips":["Define a shared constant for the 'indicator_results' key used by both the producer and consumer agents.","Have the upstream indicator agent raise loudly on empty output instead of returning {}.","Assert pipeline preconditions in the orchestrator before dispatching each agent."],"tags":["agent-pipeline","validation","python","health-record-agent"],"backgroundTag":null,"analyzedSha":"606a07d341a47be773fab7f4b71177f53f96b2c3","analyzedAt":"2026-08-14T22:57:27.446Z","schemaVersion":2},"datasetVersion":"2026-08-16T03:17:38.424Z"}