目标

让 Agent 在调用工具后,最终输出固定结构,例如:

{"summary": "...", "confidence": 0.8, "next_action": "done"}

官方 create_agent 支持 response_format= 接 Pydantic 模型。

最小例子

from pydantic import BaseModel
from langchain.agents import create_agent

class Answer(BaseModel):
    summary: str
    confidence: float
    next_action: str

agent = create_agent(
    model="openai:gpt-4o",
    tools=[],
    response_format=Answer,
)

result = agent.invoke({
    "messages": [{"role": "user", "content": "总结今天实验结论"}]
})
print(result["structured_response"])

容易误判的点

  1. schema 过大:字段一多,模型开始瞎填
  2. 语义模糊字段:note、info 这种不如删掉
  3. 和工具结果打架:工具返回很长文本,却要求一句话摘要却无约束

我的用法

  • 字段尽量少:3–6 个够用
  • 枚举优先于自由文本(next_action 用 Literal)
  • 置信度若没有校准,就别假装精确
  • 工具链很长时,中间步骤不要强行结构化,只在最终步结构化

限制

结构化输出保证「形状」,不保证「事实正确」。
它解决接口稳定,不解决幻觉。

结论

把 response_format 当契约,不当魔法。
先收窄任务,再固定 schema。