结构化输出

  |   0 评论   |   0 浏览

你将学会: 让 Agent 返回可校验的对象(姓名、邮箱),而不是一段散文。
前置: L02。

下游代码需要 email 字段时,不要用正则去「猜」模型的自然语言。response_format 会把 schema 变成必须填写的结构,结果在 structured_response

DeepSeek 不支持厂商原生 json_schema。本教程一律用 ToolStrategy(通过工具调用产出结构)。

完整代码

from dotenv import load_dotenv

load_dotenv()

from langchain.agents import create_agent
from langchain.agents.factory import ToolStrategy
from langchain.chat_models import init_chat_model
from pydantic import BaseModel, Field

model = init_chat_model(
    "deepseek:deepseek-chat",
    temperature=0.5,
    max_tokens=2500,
    timeout=300,
    max_retries=6,
)


class ContactInfo(BaseModel):
    """一个人的联系信息。"""

    name: str = Field(description="姓名")
    email: str = Field(description="邮箱地址")
    phone: str = Field(description="电话号码")


agent = create_agent(
    model=model,
    response_format=ToolStrategy(schema=ContactInfo),
)
result = agent.invoke({
    "messages": [{
        "role": "user",
        "content": "提取:李四,lisi@example.com,139-0000-8888",
    }]
})
info = result["structured_response"]
print(type(info).__name__, info)
print("可直接用字段 =>", info.email)

写工具时一并记住

@tool 的函数名、参数名、docstring 都会进提示词。写得像给同事看的 API。

常见翻车

现象处理
This response_format type is unavailable不要把 Pydantic 类直接丢给 DeepSeek 的 json_schema,用 ToolStrategy
thinking 模式报 tool_choicedeepseek-chat

练习

  1. ContactInfo 加字段 city: str,输入里带上城市,确认能解析出来。
  2. 输入故意缺电话,观察模型或校验如何表现(失败也是学习)。

本章验收

  •  能独立写出 ToolStrategy + Pydantic 并读 structured_response
  •  知道为什么本教程不用 ProviderStrategy

对照仓库:02-核心概念/Structured-output结构化输出.py

阶段 1 过关: 合上文档,新建一个空白 scratch.py,写出「天气工具 + 两轮记忆」。能跑再进入阶段 2。

下一课:RAG 检索


标题:结构化输出
作者:llp
地址:https://llinp.cn/articles/2026/08/23/1787492806810.html