题目
如何实现一个支持工具调用、状态保存、失败处理和终止条件的最小 Agent?
答案
最小结构可以分成模型适配器、工具注册表、状态存储和控制循环。工具注册表同时保存 Schema、处理函数、权限和副作用信息。
下面是控制流程的伪代码,函数需要由应用实现:
```text
state = load_or_create(task_id)
while state.steps < step_limit:
check_cancel_deadline_and_budget(state)
reply = call_model(build_context(state))
save_model_reply(state, reply)
if reply.needs_user_input:
save_waiting_state(state)
return
if reply.has_tool_calls:
for call in reply.tool_calls:
result = validate_authorize_and_execute(call, state)
save_and_append_tool_result(state, call.id, result)
else:
return validate_and_finish(state, reply)
state.steps += 1
save_stopped_state(state, reason="step_limit")
```
执行工具时区分参数错误、可重试故障和结果未知;写操作保存稳定幂等键。每个退出分支都保存状态,无法通过最终验收时不能标记成功。演示可以使用内存存储,生产恢复必须依赖持久化存储,并补齐并发、重试和异常退出处理。
