datawhalechina/hello-agents · error · AgentException
缺少必需字段: {field}
Error message
缺少必需字段: {field} What it means
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.
Source
Thrown at Co-creation-projects/Apricity-InnocoreAI/agents/base.py:160
def get_status(self) -> Dict[str, Any]:
"""获取智能体状态"""
return {
"name": self.name,
"state": self.state,
"created_at": self.created_at.isoformat(),
"history_count": len(self.history),
"tools_count": len(self.tools),
"max_steps": self.max_steps,
"timeout": self.timeout
}
async def validate_input(self, input_data: Dict[str, Any]) -> bool:
"""验证输入数据"""
required_fields = self.get_required_fields()
for field in required_fields:
if field not in input_data:
raise AgentException(f"缺少必需字段: {field}")
return True
@abstractmethod
def get_required_fields(self) -> List[str]:
"""获取必需的输入字段"""
pass
def __str__(self) -> str:
return f"{self.__class__.__name__}(name='{self.name}', state='{self.state}')"
def __repr__(self) -> str:
return self.__str__()View on GitHub (pinned to 606a07d341)
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.
Example fix
# before
await hunter_agent.run({"keyword": ["llm agents"]})
# -> AgentException: 缺少必需字段: keywords
# after — validate at the boundary with a schema
from pydantic import BaseModel
class HunterInput(BaseModel):
keywords: list[str]
max_papers: int = 20
payload = HunterInput.model_validate(request_json) # raises 422 with all missing fields
await hunter_agent.run(payload.model_dump()) Defensive patterns
Strategy: validation
Validate before calling
# Caller-side pre-check against the agent's own contract
missing = [f for f in agent.get_required_fields() if f not in input_data]
if missing:
raise ValueError(f"payload missing fields: {missing}") # before agent.run() Type guard
def has_required_fields(agent, input_data: dict) -> bool:
return isinstance(input_data, dict) and all(
f in input_data for f in agent.get_required_fields()
) Try / catch
try:
await agent.run(input_data)
except AgentException as e:
if '缺少必需字段' in str(e):
return HTTP 422 with str(e) # client error, not server
raise Prevention
- 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.
When it happens
Trigger: 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'.
Common situations: 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.
Related errors
- 工具 '{tool_name}' 不存在
- 不支持的任务类型: {task_type}
- 论文不存在: {paper_id}
- 工具 '{tool_name}' 执行超时
- 工具 '{tool_name}' 执行失败: {str(e)}
AI-assisted analysis of datawhalechina/hello-agents@606a07d341 (2026-08-14).
Data as JSON: /api/errors/7bea80a3ecdb640a.
Report an issue: GitHub.