datawhalechina/hello-agents · error · AgentException
缺少必需字段: {field}
Error message
缺少必需字段: {field} What it means
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.
Source
Thrown at Co-creation-projects/Shawnxyxy-HealthRecordAgent/backend/agents/base.py:243
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 trace(self, title: str, data: Any, level: TraceLevel = TraceLevel.DEBUG):
"""统一Agent调试输出"""
event = {
"agent": self.name,
"title": title,
"timestamp": datetime.now().isoformat(),
"data": data
}
self.traces.append({View on GitHub (pinned to 606a07d341)
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.
Example fix
# before
await agent.run({'goals': '体检报告分析'}) # wrong key name
# after
required = agent.get_required_fields() # ['goal']
await agent.run({'goal': '体检报告分析', **{k: v for k, v in payload.items() if k in required}}) Defensive patterns
Strategy: validation
Validate before calling
def has_required_fields(agent, input_data):
missing = [f for f in agent.get_required_fields() if f not in input_data]
return not missing, missing
ok, missing = has_required_fields(agent, payload)
if not ok:
raise ValueError(f'missing fields: {missing}') Type guard
from typing import Dict, Any, List
def is_valid_agent_input(agent, data) -> bool:
required: List[str] = agent.get_required_fields()
return isinstance(data, dict) and all(f in data for f in required) Try / catch
try:
await agent.validate_input(input_data)
except AgentException as e:
field = str(e).split(':')[-1].strip()
input_data[field] = default_for(field) # fill and retry Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
AI-assisted analysis of datawhalechina/hello-agents@606a07d341 (2026-08-14).
Data as JSON: /api/errors/7e2f2a5649031a6d.
Report an issue: GitHub.