{"record":{"id":"7e2f2a5649031a6d","repo":"datawhalechina/hello-agents","slug":"field-7e2f2a","errorCode":null,"errorMessage":"缺少必需字段: {field}","messagePattern":"缺少必需字段: (.+?)","errorType":"exception","errorClass":"AgentException","httpStatus":null,"severity":"error","filePath":"Co-creation-projects/Shawnxyxy-HealthRecordAgent/backend/agents/base.py","lineNumber":243,"sourceCode":"    def get_status(self) -> Dict[str, Any]:\n        \"\"\"获取智能体状态\"\"\"\n        return {\n            \"name\": self.name,\n            \"state\": self.state,\n            \"created_at\": self.created_at.isoformat(),\n            \"history_count\": len(self.history),\n            \"tools_count\": len(self.tools),\n            \"max_steps\": self.max_steps,\n            \"timeout\": self.timeout\n        }\n\n    async def validate_input(self, input_data: Dict[str, Any]) -> bool:\n        \"\"\"验证输入数据\"\"\"\n        required_fields = self.get_required_fields()\n        \n        for field in required_fields:\n            if field not in input_data:\n                raise AgentException(f\"缺少必需字段: {field}\")\n        \n        return True\n    \n    @abstractmethod\n    def get_required_fields(self) -> List[str]:\n        \"\"\"获取必需的输入字段\"\"\"\n        pass\n\n    def trace(self, title: str, data: Any, level: TraceLevel = TraceLevel.DEBUG):\n        \"\"\"统一Agent调试输出\"\"\"\n        event = {\n        \"agent\": self.name,\n        \"title\": title,\n        \"timestamp\": datetime.now().isoformat(),\n        \"data\": data\n        }\n\n        self.traces.append({","sourceCodeStart":225,"sourceCodeEnd":261,"githubUrl":"https://github.com/datawhalechina/hello-agents/blob/606a07d341a47be773fab7f4b71177f53f96b2c3/Co-creation-projects/Shawnxyxy-HealthRecordAgent/backend/agents/base.py#L225-L261","documentation":"BaseAgent.validate_input iterates the subclass-declared get_required_fields() and raises AgentException('缺少必需字段: <field>') for the first key absent from input_data. It is a schema gate that concrete agents (each declaring their own required fields, e.g. PlannerAgent requires 'goal') run before processing.","triggerScenarios":"Awaiting agent.validate_input({'symptom': '...'}) on an agent whose get_required_fields() returns ['goal']; frontend omitting a key; key present but misspelled so the membership check fails.","commonSituations":"API clients built against an older agent contract; nested payloads where the dict passed is the envelope instead of the inner fields; conditional fields the caller assumed optional.","solutions":["Inspect agent.get_required_fields() and include every listed key in the input dict.","Standardize on one place (Pydantic model or shared constants) that defines both the agent's required fields and the client payload.","Catch the AgentException and surface which field is missing to the caller instead of a generic 500."],"exampleFix":"# before\nawait agent.run({'goals': '体检报告分析'})  # wrong key name\n\n# after\nrequired = agent.get_required_fields()  # ['goal']\nawait agent.run({'goal': '体检报告分析', **{k: v for k, v in payload.items() if k in required}})","handlingStrategy":"validation","validationCode":"def has_required_fields(agent, input_data):\n    missing = [f for f in agent.get_required_fields() if f not in input_data]\n    return not missing, missing\n\nok, missing = has_required_fields(agent, payload)\nif not ok:\n    raise ValueError(f'missing fields: {missing}')","typeGuard":"from typing import Dict, Any, List\n\ndef is_valid_agent_input(agent, data) -> bool:\n    required: List[str] = agent.get_required_fields()\n    return isinstance(data, dict) and all(f in data for f in required)","tryCatchPattern":"try:\n    await agent.validate_input(input_data)\nexcept AgentException as e:\n    field = str(e).split(':')[-1].strip()\n    input_data[field] = default_for(field)  # fill and retry","preventionTips":["Derive the client payload builder from agent.get_required_fields(), not from memory.","Catch the exception and report the exact missing field to the API caller.","Cover get_required_fields() with a contract test per agent subclass."],"tags":["agent","validation","schema","required-fields"],"backgroundTag":null,"analyzedSha":"606a07d341a47be773fab7f4b71177f53f96b2c3","analyzedAt":"2026-08-14T22:57:27.446Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}