LangChain 结构化输出
核对 LangChain 1.x 与 Pydantic 2 结构化输出:create_agent(response_format=...)、ProviderStrategy/ToolStrategy、嵌套模型与 model_validator、TypedDict 与 JSON Schema 字典差异、可选字段与 extra='forbid'、with_structured_output(include_raw=True) 及 handle_errors 纠错实测。
学完这一章,你能够
- 核对 LangChain 1.x 与 Pydantic 2 结构化输出:create_agent(response_format=...)、ProviderStrategy/ToolStrategy、嵌套模型与 model_validator、TypedDict 与 JSON Schema 字典差异、可选字段与 extra='forbid'、with_structured_output(include_raw=True) 及 handle_errors 纠错实测。
结构化输出价值、环境准备与 Pydantic 基础用法
相比需要正则或人工解析的自然语言文本,结构化输出(Structured Output)让模型直接产出符合既定字段与约束的 Pydantic 实例或字典(对比见下表),便于无缝对接数据库、接口与前端组件。但必须牢记:Schema 只保证数据格式与局部校验关系,绝不能证明业务事实真实无误。
实际接入在线模型(如 ChatDeepSeek(model='deepseek-flash') 或 init_chat_model('deepseek:deepseek-flash'))需 Python 3.10+、LangChain 1.2+ 与 Pydantic 2;若使用思考模式做多轮工具调用需按文档保留 reasoning_content,不能误以为思考模型无法输出结构化数据。本站使用离线可复现模型在 langchain 1.4.9 与 pydantic 2.14.3 上逐项实测框架行为。
将 Pydantic BaseModel 搭配 ToolStrategy 传给 create_agent(response_format=...) 后,解析结果存于 result['structured_response'],可直接属性访问并调用 model_dump() 转字典或 model_dump_json() 转 JSON。本站实测 CourseInfo(含 Literal 难度与 Field(ge=1) 时长):Pydantic 默认会将字符串 '20' 自动转为 int 20,而加设 Field(strict=True) 后则直接抛出 ValidationError 拒绝隐式转换。原文未给出的信息不应令模型臆测,应设为可选字段。
输出策略、JSON Schema 字典与普通工具共存
Agent 结构化输出提供三类配置(详见策略表):直接传 Schema 时 LangChain 1.1+ 读取 model.profile 自动决定走原生 ProviderStrategy 或工具调用 ToolStrategy;显式 ToolStrategy 借助 Tool Calling 传递结构(并不代表执行真实业务函数);显式 ProviderStrategy(schema, strict=True) 仅适用于服务端原生支持严格 Schema 的提供商(其 strict 控制服务端约束,与 Pydantic Field(strict=True) 不是同一回事)。若使用原始 JSON Schema 字典,须显式包在策略对象内;本站实测 ToolStrategy(person_schema) 返回字典且**放行了 age=-3**(未触发本地校验),印证了原始 JSON Schema 字典在 ToolStrategy 中不会自动执行完整客户端 Schema 验证,需要本地强校验应首选 Pydantic。
结构化输出可与普通业务工具共存。本站实测同时注册 search_course 工具与 response_format=ToolStrategy(CourseRecommendation):Agent 先调用 search_course('python') 获模拟课程信息,再调用结构化输出工具填充 CourseRecommendation。检查 result['messages'] 可见两条 ToolMessage(name 分别为 'search_course' 与 'CourseRecommendation'),因此排查业务查询结果时必须按 msg.name == 'search_course' 过滤,不可把结构化输出工具消息混作业务工具调用。
嵌套校验、TypedDict、可选字段与 with_structured_output()
Pydantic 支持嵌套模型与跨字段自定义验证器(@model_validator(mode='after'))。本站实测 LearningPlan(嵌套 list[Topic],校验各主题分钟数之和/60 与 total_hours 误差 <= 0.01):首轮模型给出总时长 3.0 小时而两主题合计 120 分钟(2.0 小时),本地验证器拦截失败并经 ToolStrategy(handle_errors=True) 反馈给模型,第 2 次调用修正为 2.0 小时后解析成功。需注意自定义验证器只在 Python 本地运行,不会自动变成服务端 JSON Schema 规则。
使用 TypedDict(如 PersonInfo)配合 ToolStrategy 时,Agent 通过 Pydantic TypeAdapter 解析并返回普通 dict(本站实测返回 dict {'name': '张三', 'age': 28, 'job': 'Python工程师'},与 Pydantic 对比见下表;但直接调模型 with_structured_output(TypedDict) 不可假定具有相同本地校验)。面对不完整输入,应将字段设为可空且带默认值(如 str | None = None,JSON 序列化为 null):本站实测验证在 Pydantic 2 中仅写 name: str | None 而无 = None 仍是必填字段(缺键抛 ValidationError);配置 ConfigDict(extra='forbid') 可拦截未声明的额外字段,但仍须在提示词中要求缺失返回 null 并在应用层核实事实。
纯文本提取或情感分类无需工具循环时,可直接用 model.with_structured_output(Schema, method='function_calling')(与 create_agent 及 json_mode 的对比见下表;情感 score 并非统计校准概率,且直调不会自动启动 Agent 纠错循环)。开启 include_raw=True 返回含 raw、parsed、parsing_error 三键的字典(见字段表)。本站实测三分支:(1)正常解析时 parsed 为 SentimentResult 且 parsing_error 为 None;(2)score=1.8 越界时 parsed 为 None 且 parsing_error 为 ValidationError;(3)模型仅返普通文本未发起工具调用时,parsed 为 None 且 parsing_error 亦为 None——因此业务代码必须同时检查 parsing_error 与 parsed is None(且网络/鉴权错误仍直接抛异常)。
错误处理、完整案例、常见问题与参考资料
结构化输出常见失败包括缺字段、类型/枚举/范围越界以及单轮返回多个结构化结果触发 MultipleStructuredOutputsError。ToolStrategy.handle_errors 默认为 True,支持五类配置(详见下表,且区别于普通工具的 BaseTool.handle_tool_error)。本站实测:自定义错误字符串在 rating=10 越界时准确反馈“评分必须为1到5的整数,并且需要提供评论。”并促使第 2 次调用返回 rating=4;当 handle_errors=False 且单轮返回两个 ProductRating 工具调用时,精准抛出 MultipleStructuredOutputsError;同时验证 ProviderStrategy(ContactInfo, strict=True) 在原生支持模型上经 ['human', 'ai'] 两消息返回 ContactInfo。工程上配合 recursion_limit 限制图执行步数上限(区别于请求层 max_retries),并在完整案例 structured_output_demo.py 中结合 extra='forbid'、全可空业务字段与分类型异常捕获兜底。
排障与选型汇总:structured_response 对 Pydantic 返模型实例、对 TypedDict/JSON Schema 返 dict(非 JSON 字符串);读取不到该键时需确认配置了 response_format、读的是 invoke() 最终状态而非单个流事件,且区分 with_structured_output() 直接返回解析值;反复重试时应检查 Schema 约束是否自相矛盾、用 handle_errors=False 暴露原始错因并设 recursion_limit。核心原则:Schema 管格式,Pydantic 管校验,可信数据源管事实核验;延伸接口细则可参阅文末列出的 LangChain 与 DeepSeek 官方参考文档。
普通文本输出与结构化输出对比
| 方式 | 返回内容 | 后续处理 |
| 普通文本 | 自由自然语言段落。 | 需编写正则或额外解析逻辑提取字段。 |
| 结构化输出 | Pydantic 实例或 Python 字典。 | 直接按属性/键访问并经 Schema 自动校验。 |
Agent 结构化输出策略概览
| 策略 | 实现方式 | 适用场景 |
| ProviderStrategy | 调用模型服务商原生结构化输出能力。 | 模型、端点与集成均支持原生 Schema 约束。 |
| ToolStrategy | 利用模型 Tool Calling 传递并校验结构化载荷。 | 支持工具调用的模型,支持 handle_errors 自动纠错。 |
| 直接传 Schema | 由 LangChain 依据 model.profile 自动择优策略。 | 常规结构化提取的默认推荐入口。 |
Pydantic 与 TypedDict 定义方式对比
| 方式 | 返回类型 | 主要特点 |
| Pydantic | BaseModel 实例。 | 支持字段约束、strict、extra='forbid' 与自定义 @model_validator。 |
| TypedDict | 普通 Python dict。 | 语法轻便(Agent 路径由 TypeAdapter 解析,复杂规则宜选 Pydantic)。 |
Agent 结构化输出与模型直调对比
| 方式 | 返回值 | 适用场景 |
| create_agent(response_format=...) | 完整 Agent 状态字典,含 structured_response 键。 | 需结合工具调用、多步骤纠错与中间件编排。 |
| model.with_structured_output(...) | 直接返回解析后对象(或 include_raw 字典)。 | 单步文本分类、实体抽取与轻量解析。 |
function_calling、json_mode 与 ProviderStrategy 对比
| 方式 | 主要作用 | 本地校验 |
| method="function_calling" | 将 Schema 转为工具参数协议提取结构。 | 传入 Pydantic 时自动执行本地字段校验。 |
| method="json_mode" | 约束返回合法 JSON(需在提示词写明字段格式)。 | 传入 Pydantic 可校验解析结果,但不等同服务端强制 Schema。 |
| ProviderStrategy | 由原生支持结构化输出的服务商在服务端约束 Schema。 | 仍须在本地执行无法用 JSON Schema 表达的跨字段业务校验。 |
include_raw=True 返回字典字段说明
| 字段 | 说明 |
| raw | 模型返回的原始 AIMessage 对象。 |
| parsed | 解析成功的结构化对象;校验失败或未生成预期工具调用时为 None。 |
| parsing_error | 捕获到的解析/校验异常(如 ValidationError);无异常时为 None。 |
ToolStrategy(handle_errors=...) 配置选项说明
| 配置 | 行为 |
| True | 默认开启:捕获受支持的结构化输出错误并反馈模型尝试修正。 |
| False | 关闭自动恢复,遇到校验或多输出错误直接向外抛出异常。 |
| 字符串 | 向模型返回固定提示文本请求修正。 |
| 异常类型或异常类型元组 | 仅捕获并反馈指定异常子类,其余异常继续抛出。 |
| Callable | 将异常传入自定义函数动态生成纠错提示语。 |
离线实测 Pydantic 校验与 strict、嵌套 model_validator 重试、TypedDict/JSON Schema 差异、with_structured_output(include_raw=True) 与多输出异常
展开查看收起
"""Offline deterministic runtime lab for LangChain Chapter 19 (structured-output)."""
import json
import platform
from typing import Any, Literal
from langchain.agents import create_agent
from langchain.agents.structured_output import (
MultipleStructuredOutputsError,
ProviderStrategy,
ToolStrategy,
)
from langchain.tools import tool
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, ToolMessage
from langchain_core.outputs import ChatGeneration, ChatResult
from langchain_core.runnables import RunnableLambda
from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
from typing_extensions import TypedDict
class ScriptedChatModel(BaseChatModel):
responses: list[AIMessage] = Field(default_factory=list)
call_index: int = 0
@property
def _llm_type(self) -> str:
return "scripted-offline-structured"
def bind_tools(self, tools, **kwargs):
return self
def with_structured_output(
self,
schema: Any,
*,
method: str = "function_calling",
include_raw: bool = False,
**kwargs: Any,
):
def _invoke(inp: Any) -> Any:
msgs = [HumanMessage(content=inp)] if isinstance(inp, str) else list(inp)
raw_msg = self._generate(msgs).generations[0].message
parsed = None
parsing_error = None
try:
if method == "function_calling":
if raw_msg.tool_calls:
args = raw_msg.tool_calls[0]["args"]
parsed = (
schema.model_validate(args)
if isinstance(schema, type) and issubclass(schema, BaseModel)
else args
)
elif method == "json_mode":
data = json.loads(str(raw_msg.content))
parsed = (
schema.model_validate(data)
if isinstance(schema, type) and issubclass(schema, BaseModel)
else data
)
except Exception as exc:
parsing_error = exc
if not include_raw:
raise
if include_raw:
return {"raw": raw_msg, "parsed": parsed, "parsing_error": parsing_error}
return parsed
return RunnableLambda(_invoke)
def _generate(
self,
messages: list[BaseMessage],
stop: list[str] | None = None,
run_manager: Any = None,
**kwargs: Any,
) -> ChatResult:
idx = min(self.call_index, len(self.responses) - 1)
self.call_index += 1
return ChatResult(generations=[ChatGeneration(message=self.responses[idx])])
def case_pydantic_tool_strategy_and_strict_coercion() -> dict:
class CourseInfo(BaseModel):
"""从文本中提取课程信息。"""
course_name: str = Field(description="课程名称")
difficulty: Literal["入门", "进阶", "高级"]
estimated_hours: int = Field(ge=1, description="预计学习小时数")
is_free: bool = Field(description="是否免费")
class StrictCourseInfo(BaseModel):
estimated_hours: int = Field(ge=1, strict=True)
m = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[
{
"name": "CourseInfo",
"args": {
"course_name": "Python3 基础教程",
"difficulty": "入门",
"estimated_hours": "20",
"is_free": True,
},
"id": "c1",
"type": "tool_call",
}
],
)
]
)
res = create_agent(
model=m,
tools=[],
response_format=ToolStrategy(CourseInfo),
).invoke({"messages": [{"role": "user", "content": "提取课程信息"}]})
course = res["structured_response"]
strict_err = None
try:
StrictCourseInfo.model_validate({"estimated_hours": "20"})
except ValidationError as exc:
strict_err = type(exc).__name__
actual = {
"obj_type": type(course).__name__,
"coerced_hours_type": type(course.estimated_hours).__name__,
"model_dump": course.model_dump(),
"json_roundtrip": json.loads(course.model_dump_json()),
"strict_field_rejects_str": strict_err,
}
expected = {
"obj_type": "CourseInfo",
"coerced_hours_type": "int",
"model_dump": {
"course_name": "Python3 基础教程",
"difficulty": "入门",
"estimated_hours": 20,
"is_free": True,
},
"json_roundtrip": {
"course_name": "Python3 基础教程",
"difficulty": "入门",
"estimated_hours": 20,
"is_free": True,
},
"strict_field_rejects_str": "ValidationError",
}
return {
"name": "pydantic_tool_strategy_and_strict_coercion",
"passed": actual == expected,
"expected": expected,
"actual": actual,
}
def case_nested_validator_optional_and_extra_forbid() -> dict:
class Topic(BaseModel):
name: str
order: int = Field(ge=1)
minutes: int = Field(gt=0)
class LearningPlan(BaseModel):
goal: str
level: Literal["入门", "进阶", "高级"]
total_hours: float = Field(gt=0, le=10)
topics: list[Topic] = Field(min_length=1)
@model_validator(mode="after")
def check_duration(self):
total = sum(t.minutes for t in self.topics)
if abs(total / 60 - self.total_hours) > 0.01:
raise ValueError("total_hours 必须等于全部主题分钟数之和除以60")
return self
m_plan = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[
{
"name": "LearningPlan",
"args": {
"goal": "掌握 Python 基础语法",
"level": "入门",
"total_hours": 3.0,
"topics": [
{"name": "变量", "order": 1, "minutes": 60},
{"name": "循环", "order": 2, "minutes": 60},
],
},
"id": "lp_bad",
"type": "tool_call",
}
],
),
AIMessage(
content="",
tool_calls=[
{
"name": "LearningPlan",
"args": {
"goal": "掌握 Python 基础语法",
"level": "入门",
"total_hours": 2.0,
"topics": [
{"name": "变量", "order": 1, "minutes": 60},
{"name": "循环", "order": 2, "minutes": 60},
],
},
"id": "lp_ok",
"type": "tool_call",
}
],
),
]
)
r_plan = create_agent(
model=m_plan,
tools=[],
response_format=ToolStrategy(LearningPlan, handle_errors=True),
).invoke({"messages": [{"role": "user", "content": "制定学习计划"}]})
plan = r_plan["structured_response"]
class OptionalCourseInfo(BaseModel):
model_config = ConfigDict(extra="forbid")
course_name: str | None = Field(default=None, min_length=1)
difficulty: Literal["入门", "进阶", "高级"] | None = None
estimated_hours: int | None = Field(default=None, ge=1, le=1000)
is_free: bool | None = None
class NullableButRequired(BaseModel):
name: str | None
partial_obj = OptionalCourseInfo.model_validate({"course_name": "HTML 基础教程"})
extra_err = None
try:
OptionalCourseInfo.model_validate({"course_name": "HTML", "unexpected": 1})
except ValidationError as exc:
extra_err = type(exc).__name__
missing_required_nullable_err = None
try:
NullableButRequired.model_validate({})
except ValidationError as exc:
missing_required_nullable_err = type(exc).__name__
actual = {
"plan_model_calls_after_retry": m_plan.call_index,
"plan_total_hours": plan.total_hours,
"plan_topic_count": len(plan.topics),
"partial_json": json.loads(partial_obj.model_dump_json()),
"extra_forbid_error": extra_err,
"nullable_without_default_still_required": missing_required_nullable_err,
}
expected = {
"plan_model_calls_after_retry": 2,
"plan_total_hours": 2.0,
"plan_topic_count": 2,
"partial_json": {
"course_name": "HTML 基础教程",
"difficulty": None,
"estimated_hours": None,
"is_free": None,
},
"extra_forbid_error": "ValidationError",
"nullable_without_default_still_required": "ValidationError",
}
return {
"name": "nested_validator_optional_and_extra_forbid",
"passed": actual == expected,
"expected": expected,
"actual": actual,
}
def case_typeddict_json_schema_and_tool_coexistence() -> dict:
class PersonInfo(TypedDict):
name: str
age: int
job: str
m_td = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[
{
"name": "PersonInfo",
"args": {"name": "张三", "age": 28, "job": "Python工程师"},
"id": "td1",
"type": "tool_call",
}
],
)
]
)
r_td = create_agent(model=m_td, tools=[], response_format=ToolStrategy(PersonInfo)).invoke(
{"messages": [{"role": "user", "content": "张三今年28岁,Python工程师"}]}
)
person_schema = {
"title": "PersonSchema",
"description": "提取姓名与年龄",
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer", "minimum": 0},
},
"required": ["name", "age"],
"additionalProperties": False,
}
m_js = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[
{
"name": "PersonSchema",
"args": {"name": "测试", "age": -3},
"id": "js1",
"type": "tool_call",
}
],
)
]
)
r_js = create_agent(model=m_js, tools=[], response_format=ToolStrategy(person_schema)).invoke(
{"messages": [{"role": "user", "content": "提取"}]}
)
@tool
def search_course(keyword: str) -> str:
"""根据编程语言查询模拟课程。"""
return {"python": "Python3 基础教程,入门,模拟学习时长20小时"}.get(keyword.lower(), "未找到")
class CourseRecommendation(BaseModel):
course_name: str
reason: str
difficulty: str
m_co = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[
{"name": "search_course", "args": {"keyword": "python"}, "id": "sc1", "type": "tool_call"}
],
),
AIMessage(
content="",
tool_calls=[
{
"name": "CourseRecommendation",
"args": {
"course_name": "Python3 基础教程",
"reason": "适合零基础学习者",
"difficulty": "入门",
},
"id": "rec1",
"type": "tool_call",
}
],
),
]
)
r_co = create_agent(
model=m_co,
tools=[search_course],
response_format=ToolStrategy(CourseRecommendation),
).invoke({"messages": [{"role": "user", "content": "查 Python 课程并推荐"}]})
all_tool_names = [m.name for m in r_co["messages"] if isinstance(m, ToolMessage)]
biz_tool_contents = [
m.content for m in r_co["messages"] if isinstance(m, ToolMessage) and m.name == "search_course"
]
actual = {
"typeddict_type": type(r_td["structured_response"]).__name__,
"typeddict_value": r_td["structured_response"],
"raw_json_schema_type": type(r_js["structured_response"]).__name__,
"raw_json_schema_passes_negative_age": r_js["structured_response"]["age"],
"coexist_all_tool_msg_names": all_tool_names,
"coexist_biz_tool_contents": biz_tool_contents,
"coexist_structured": r_co["structured_response"].model_dump(),
}
expected = {
"typeddict_type": "dict",
"typeddict_value": {"name": "张三", "age": 28, "job": "Python工程师"},
"raw_json_schema_type": "dict",
"raw_json_schema_passes_negative_age": -3,
"coexist_all_tool_msg_names": ["search_course", "CourseRecommendation"],
"coexist_biz_tool_contents": ["Python3 基础教程,入门,模拟学习时长20小时"],
"coexist_structured": {
"course_name": "Python3 基础教程",
"reason": "适合零基础学习者",
"difficulty": "入门",
},
}
return {
"name": "typeddict_json_schema_and_tool_coexistence",
"passed": actual == expected,
"expected": expected,
"actual": actual,
}
def case_with_structured_output_and_include_raw() -> dict:
class SentimentResult(BaseModel):
sentiment: Literal["积极", "消极", "中性"]
score: float = Field(ge=0, le=1)
keywords: list[str]
m = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[
{
"name": "SentimentResult",
"args": {"sentiment": "积极", "score": 0.95, "keywords": ["好用", "推荐"]},
"id": "w1",
"type": "tool_call",
}
],
),
AIMessage(
content="",
tool_calls=[
{
"name": "SentimentResult",
"args": {"sentiment": "积极", "score": 1.8, "keywords": ["越界"]},
"id": "w2",
"type": "tool_call",
}
],
),
AIMessage(content="普通文本回复,未发起工具调用"),
]
)
sm_raw = m.with_structured_output(SentimentResult, method="function_calling", include_raw=True)
ok_res = sm_raw.invoke("很好用,强烈推荐!")
err_res = sm_raw.invoke("评分越界测试")
none_res = sm_raw.invoke("无工具调用测试")
actual = {
"ok_keys": sorted(ok_res.keys()),
"ok_parsed": ok_res["parsed"].model_dump(),
"ok_error_is_none": ok_res["parsing_error"] is None,
"err_parsed_is_none": err_res["parsed"] is None,
"err_type": type(err_res["parsing_error"]).__name__,
"no_call_parsed_is_none": none_res["parsed"] is None,
"no_call_error_is_none": none_res["parsing_error"] is None,
}
expected = {
"ok_keys": ["parsed", "parsing_error", "raw"],
"ok_parsed": {"sentiment": "积极", "score": 0.95, "keywords": ["好用", "推荐"]},
"ok_error_is_none": True,
"err_parsed_is_none": True,
"err_type": "ValidationError",
"no_call_parsed_is_none": True,
"no_call_error_is_none": True,
}
return {
"name": "with_structured_output_and_include_raw",
"passed": actual == expected,
"expected": expected,
"actual": actual,
}
def case_handle_errors_multiple_outputs_and_provider_strategy() -> dict:
class ProductRating(BaseModel):
rating: int = Field(ge=1, le=5)
comment: str
m_retry = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[
{"name": "ProductRating", "args": {"rating": 10, "comment": "越界"}, "id": "r1", "type": "tool_call"}
],
),
AIMessage(
content="",
tool_calls=[
{"name": "ProductRating", "args": {"rating": 4, "comment": "不错"}, "id": "r2", "type": "tool_call"}
],
),
]
)
r_retry = create_agent(
model=m_retry,
tools=[],
response_format=ToolStrategy(
ProductRating,
handle_errors="评分必须为1到5的整数,并且需要提供评论。",
),
).invoke({"messages": [{"role": "user", "content": "给商品评分"}]})
feedback_msg = next(m.content for m in r_retry["messages"] if isinstance(m, ToolMessage))
m_dup = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[
{"name": "ProductRating", "args": {"rating": 4, "comment": "A"}, "id": "d1", "type": "tool_call"},
{"name": "ProductRating", "args": {"rating": 4, "comment": "A"}, "id": "d2", "type": "tool_call"},
],
)
]
)
dup_err = None
try:
create_agent(
model=m_dup,
tools=[],
response_format=ToolStrategy(ProductRating, handle_errors=False),
).invoke({"messages": [{"role": "user", "content": "重复输出"}]})
except MultipleStructuredOutputsError as exc:
dup_err = type(exc).__name__
class ContactInfo(BaseModel):
name: str
email: str
m_prov = ScriptedChatModel(
profile={"structured_output": True, "tool_calling": True},
responses=[AIMessage(content='{"name": "张三", "email": "zhangsan@example.com"}')],
)
r_prov = create_agent(
model=m_prov,
tools=[],
response_format=ProviderStrategy(ContactInfo, strict=True),
).invoke({"messages": [{"role": "user", "content": "张三邮箱 zhangsan@example.com"}]})
actual = {
"retry_calls": m_retry.call_index,
"custom_feedback_msg": feedback_msg,
"retry_result": r_retry["structured_response"].model_dump(),
"duplicate_error_type": dup_err,
"provider_result": r_prov["structured_response"].model_dump(),
"provider_msg_types": [m.type for m in r_prov["messages"]],
}
expected = {
"retry_calls": 2,
"custom_feedback_msg": "评分必须为1到5的整数,并且需要提供评论。",
"retry_result": {"rating": 4, "comment": "不错"},
"duplicate_error_type": "MultipleStructuredOutputsError",
"provider_result": {"name": "张三", "email": "zhangsan@example.com"},
"provider_msg_types": ["human", "ai"],
}
return {
"name": "handle_errors_multiple_outputs_and_provider_strategy",
"passed": actual == expected,
"expected": expected,
"actual": actual,
}
def main() -> None:
cases = [
case_pydantic_tool_strategy_and_strict_coercion(),
case_nested_validator_optional_and_extra_forbid(),
case_typeddict_json_schema_and_tool_coexistence(),
case_with_structured_output_and_include_raw(),
case_handle_errors_multiple_outputs_and_provider_strategy(),
]
print(
json.dumps(
{
"version": platform.python_version(),
"system": platform.system(),
"cases": cases,
},
ensure_ascii=False,
indent=2,
)
)
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
本站实测证实:当模型未发起预期工具调用而直接回复普通文本时,不会触发 Pydantic 校验异常,因此 `parsing_error` 为 `None`,但同时 `parsed` 也为 `None`;必须同时检查 `parsing_error is None` 且 `parsed is not None`。