在线代码实验室
离线实测 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()
本例需在 Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。
入口文件:projects/langchain-structured-output-lab/explore-structured-output.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-structured-output.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联37章) · 含当前章节或实例 · mbskycom202612a509.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a536.zip