{"record":{"id":"7bea80a3ecdb640a","repo":"datawhalechina/hello-agents","slug":"field","errorCode":null,"errorMessage":"缺少必需字段: {field}","messagePattern":"缺少必需字段: (.+?)","errorType":"validation","errorClass":"AgentException","httpStatus":500,"severity":"error","filePath":"Co-creation-projects/Apricity-InnocoreAI/agents/base.py","lineNumber":160,"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 __str__(self) -> str:\n        return f\"{self.__class__.__name__}(name='{self.name}', state='{self.state}')\"\n    \n    def __repr__(self) -> str:\n        return self.__str__()","sourceCodeStart":142,"sourceCodeEnd":173,"githubUrl":"https://github.com/datawhalechina/hello-agents/blob/606a07d341a47be773fab7f4b71177f53f96b2c3/Co-creation-projects/Apricity-InnocoreAI/agents/base.py#L142-L173","documentation":"Validation error from BaseAgent.validate_input: it iterates the agent subclass's get_required_fields() and raises on the first key absent from the input dict. It is the first check inside every agent's run(), so it fires before any state change or tool call. The missing field name is included in the message.","triggerScenarios":"Calling controller.execute_task / agent.run with input_data missing a declared field, e.g. hunter.run({'keyword':...}) instead of {'keywords':[...]} (hunter requires 'keywords'), miner.run without 'paper_id', coach.run without 'user_id'/'task_type'/'content', validator.run without 'paper_info'.","commonSituations":"API clients sending camelCase JSON (paperId) to snake_case fields; hand-written test payloads drifting from get_required_fields; upstream task composers constructing dicts incrementally and skipping a key on an early-exit branch.","solutions":["Match your payload keys exactly to the agent's get_required_fields() (hunter: keywords; miner: paper_id; coach: user_id, task_type, content; validator: paper_info).","Log the full input_data keys alongside the error to catch casing/typo mismatches instantly.","Validate at the API boundary with a Pydantic model mirroring required fields so 422s return before reaching agents.","Add a shared test asserting each agent's required fields against example payloads in fixtures."],"exampleFix":"# before\nawait hunter_agent.run({\"keyword\": [\"llm agents\"]})\n# -> AgentException: 缺少必需字段: keywords\n\n# after — validate at the boundary with a schema\nfrom pydantic import BaseModel\nclass HunterInput(BaseModel):\n    keywords: list[str]\n    max_papers: int = 20\n\npayload = HunterInput.model_validate(request_json)  # raises 422 with all missing fields\nawait hunter_agent.run(payload.model_dump())","handlingStrategy":"validation","validationCode":"# Caller-side pre-check against the agent's own contract\nmissing = [f for f in agent.get_required_fields() if f not in input_data]\nif missing:\n    raise ValueError(f\"payload missing fields: {missing}\")  # before agent.run()","typeGuard":"def has_required_fields(agent, input_data: dict) -> bool:\n    return isinstance(input_data, dict) and all(\n        f in input_data for f in agent.get_required_fields()\n    )","tryCatchPattern":"try:\n    await agent.run(input_data)\nexcept AgentException as e:\n    if '缺少必需字段' in str(e):\n        return HTTP 422 with str(e)  # client error, not server\n    raise","preventionTips":["Validate with a Pydantic model at the API boundary mirroring required fields.","Keep an example payload per agent in fixtures and assert it passes get_required_fields in CI.","Watch for camelCase/snake_case mismatches between frontend JSON and agent fields."],"tags":["python","validation","agent","api-contract"],"backgroundTag":null,"analyzedSha":"606a07d341a47be773fab7f4b71177f53f96b2c3","analyzedAt":"2026-08-14T22:57:27.446Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}