在线代码实验室
离线实测 ToolStrategy 3 消息机制、handle_errors 六模式与非插值验证、ProviderStrategy strict 及 AutoStrategy profile 路由
"""Offline deterministic runtime lab for LangChain Chapter 20 (structured-output-strategies)."""
import json
import platform
from typing import Any, Literal
from langchain.agents import create_agent
from langchain.agents.structured_output import (
AutoStrategy,
MultipleStructuredOutputsError,
ProviderStrategy,
StructuredOutputValidationError,
ToolStrategy,
)
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import AIMessage, BaseMessage, ToolMessage
from langchain_core.outputs import ChatGeneration, ChatResult
from pydantic import BaseModel, Field
class ScriptedChatModel(BaseChatModel):
responses: list[AIMessage] = Field(default_factory=list)
call_index: int = 0
bound_tool_count: int = 0
@property
def _llm_type(self) -> str:
return "scripted-offline-strategies"
def bind_tools(self, tools, **kwargs):
self.bound_tool_count = len(list(tools))
return self
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_tool_strategy_messages_and_custom_tool_message() -> dict:
class WeatherReport(BaseModel):
"""从文本中提取天气信息。"""
city: str = Field(description="城市名称")
temperature: float = Field(description="摄氏温度")
condition: str = Field(description="天气状况")
humidity: int = Field(ge=0, le=100, description="湿度百分比")
m_default = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[
{
"name": "WeatherReport",
"args": {"city": "杭州", "temperature": 25.0, "condition": "晴天", "humidity": 60},
"id": "w1",
"type": "tool_call",
}
],
)
]
)
r_def = create_agent(
model=m_default,
tools=[],
response_format=ToolStrategy(WeatherReport),
).invoke({"messages": [{"role": "user", "content": "杭州晴天,温度25度,湿度60%。"}]})
m_custom = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[
{
"name": "WeatherReport",
"args": {"city": "杭州", "temperature": 25.0, "condition": "晴天", "humidity": 60},
"id": "w2",
"type": "tool_call",
}
],
)
]
)
r_cust = create_agent(
model=m_custom,
tools=[],
response_format=ToolStrategy(WeatherReport, tool_message_content="天气描述已成功提取。"),
).invoke({"messages": [{"role": "user", "content": "杭州晴天,温度25度,湿度60%。"}]})
actual = {
"default_model_calls": m_default.call_index,
"default_msg_count": len(r_def["messages"]),
"default_msg_types": [x.type for x in r_def["messages"]],
"default_structured": r_def["structured_response"].model_dump(),
"custom_tool_msg_content": r_cust["messages"][-1].content,
"custom_structured_unchanged": r_cust["structured_response"].model_dump()
== r_def["structured_response"].model_dump(),
}
expected = {
"default_model_calls": 1,
"default_msg_count": 3,
"default_msg_types": ["human", "ai", "tool"],
"default_structured": {"city": "杭州", "temperature": 25.0, "condition": "晴天", "humidity": 60},
"custom_tool_msg_content": "天气描述已成功提取。",
"custom_structured_unchanged": True,
}
return {
"name": "tool_strategy_messages_and_custom_tool_message",
"passed": actual == expected,
"expected": expected,
"actual": actual,
}
def case_handle_errors_variants() -> dict:
class ProductRating(BaseModel):
rating: int = Field(ge=1, le=5)
comment: str
bad_call = AIMessage(
content="",
tool_calls=[
{"name": "ProductRating", "args": {"rating": 10, "comment": "越界"}, "id": "b1", "type": "tool_call"}
],
)
good_call = AIMessage(
content="",
tool_calls=[
{"name": "ProductRating", "args": {"rating": 4, "comment": "好评"}, "id": "g1", "type": "tool_call"}
],
)
dup_call = AIMessage(
content="",
tool_calls=[
{"name": "ProductRating", "args": {"rating": 4, "comment": "A"}, "id": "d1", "type": "tool_call"},
{"name": "ProductRating", "args": {"rating": 5, "comment": "B"}, "id": "d2", "type": "tool_call"},
],
)
# 1) default True -> retries and succeeds
m_true = ScriptedChatModel(responses=[bad_call, good_call])
r_true = create_agent(model=m_true, tools=[], response_format=ToolStrategy(ProductRating)).invoke(
{"messages": [{"role": "user", "content": "评分"}]}
)
# 2) False -> raises StructuredOutputValidationError
m_false = ScriptedChatModel(responses=[bad_call])
false_err = None
try:
create_agent(
model=m_false, tools=[], response_format=ToolStrategy(ProductRating, handle_errors=False)
).invoke({"messages": [{"role": "user", "content": "评分"}]})
except StructuredOutputValidationError as exc:
false_err = type(exc).__name__
# 3) literal str -> does NOT interpolate {error}
m_str = ScriptedChatModel(responses=[bad_call, good_call])
r_str = create_agent(
model=m_str,
tools=[],
response_format=ToolStrategy(ProductRating, handle_errors="格式有误:{error}"),
).invoke({"messages": [{"role": "user", "content": "评分"}]})
str_feedback = next(x.content for x in r_str["messages"] if isinstance(x, ToolMessage))
# 4) exception type -> catches ValidationError, lets MultipleStructuredOutputsError propagate
m_exc = ScriptedChatModel(responses=[dup_call])
unhandled_dup = None
try:
create_agent(
model=m_exc,
tools=[],
response_format=ToolStrategy(ProductRating, handle_errors=StructuredOutputValidationError),
).invoke({"messages": [{"role": "user", "content": "评分"}]})
except MultipleStructuredOutputsError as exc:
unhandled_dup = type(exc).__name__
# 5) Callable -> distinguishes error types
def handle_format_error(error: Exception) -> str:
if isinstance(error, StructuredOutputValidationError):
return "字段格式或取值不符合要求,请修正。"
if isinstance(error, MultipleStructuredOutputsError):
return "只能返回一种结构化结果。"
return "未知结构化错误。"
m_cb = ScriptedChatModel(responses=[dup_call, good_call])
r_cb = create_agent(
model=m_cb,
tools=[],
response_format=ToolStrategy(ProductRating, handle_errors=handle_format_error),
).invoke({"messages": [{"role": "user", "content": "评分"}]})
cb_feedback = next(x.content for x in r_cb["messages"] if isinstance(x, ToolMessage))
actual = {
"default_retry_calls": m_true.call_index,
"default_retry_msg_count": len(r_true["messages"]),
"default_retry_rating": r_true["structured_response"].rating,
"false_raises": false_err,
"str_not_interpolated": str_feedback,
"typed_handler_propagates_dup": unhandled_dup,
"callable_dup_feedback": cb_feedback,
"callable_final_rating": r_cb["structured_response"].rating,
}
expected = {
"default_retry_calls": 2,
"default_retry_msg_count": 5,
"default_retry_rating": 4,
"false_raises": "StructuredOutputValidationError",
"str_not_interpolated": "格式有误:{error}",
"typed_handler_propagates_dup": "MultipleStructuredOutputsError",
"callable_dup_feedback": "只能返回一种结构化结果。",
"callable_final_rating": 4,
}
return {
"name": "handle_errors_variants",
"passed": actual == expected,
"expected": expected,
"actual": actual,
}
def case_provider_strategy_and_strict_flag() -> dict:
class CourseInfo(BaseModel):
name: str
level: Literal["入门", "进阶", "高级"]
price: str
s_default = ProviderStrategy(CourseInfo)
s_strict = ProviderStrategy(CourseInfo, strict=True)
m_native = ScriptedChatModel(
profile={"structured_output": True, "tool_calling": True},
responses=[AIMessage(content='{"name": "Python3 基础教程", "level": "入门", "price": "免费"}')],
)
res = create_agent(model=m_native, tools=[], response_format=s_strict).invoke(
{"messages": [{"role": "user", "content": "提取课程资料"}]}
)
actual = {
"default_strict": s_default.schema_spec.strict,
"explicit_strict": s_strict.schema_spec.strict,
"bound_tool_count": m_native.bound_tool_count,
"msg_types": [x.type for x in res["messages"]],
"structured": res["structured_response"].model_dump(),
}
expected = {
"default_strict": None,
"explicit_strict": True,
"bound_tool_count": 0,
"msg_types": ["human", "ai"],
"structured": {"name": "Python3 基础教程", "level": "入门", "price": "免费"},
}
return {
"name": "provider_strategy_and_strict_flag",
"passed": actual == expected,
"expected": expected,
"actual": actual,
}
def case_auto_strategy_and_model_profile_routing() -> dict:
class Analysis(BaseModel):
summary: str
score: int = Field(ge=1, le=10)
pros: list[str]
cons: list[str]
payload = {
"summary": "内容系统、示例较多,但高级专题有限",
"score": 8,
"pros": ["内容系统", "示例丰富"],
"cons": ["高级专题相对较少"],
}
m_nat = ScriptedChatModel(
profile={"structured_output": True, "tool_calling": True},
responses=[AIMessage(content=json.dumps(payload, ensure_ascii=False))],
)
r_nat = create_agent(model=m_nat, tools=[], response_format=Analysis).invoke(
{"messages": [{"role": "user", "content": "分析评价"}]}
)
m_tool = ScriptedChatModel(
profile={"structured_output": False, "tool_calling": True},
responses=[
AIMessage(
content="",
tool_calls=[{"name": "Analysis", "args": payload, "id": "a1", "type": "tool_call"}],
)
],
)
r_tool = create_agent(model=m_tool, tools=[], response_format=AutoStrategy(Analysis)).invoke(
{"messages": [{"role": "user", "content": "分析评价"}]}
)
m_empty = ScriptedChatModel(
profile={},
responses=[
AIMessage(
content="",
tool_calls=[{"name": "Analysis", "args": payload, "id": "a2", "type": "tool_call"}],
)
],
)
r_empty = create_agent(model=m_empty, tools=[], response_format=Analysis).invoke(
{"messages": [{"role": "user", "content": "分析评价"}]}
)
actual = {
"native_profile_flag": (m_nat.profile or {}).get("structured_output"),
"native_bound_tools": m_nat.bound_tool_count,
"native_msg_types": [x.type for x in r_nat["messages"]],
"tool_profile_flag": (m_tool.profile or {}).get("structured_output"),
"tool_bound_tools": m_tool.bound_tool_count,
"tool_msg_types": [x.type for x in r_tool["messages"]],
"empty_profile_bound_tools": m_empty.bound_tool_count,
"empty_profile_msg_types": [x.type for x in r_empty["messages"]],
"all_scores_equal": (
r_nat["structured_response"].score
== r_tool["structured_response"].score
== r_empty["structured_response"].score
== 8
),
}
expected = {
"native_profile_flag": True,
"native_bound_tools": 0,
"native_msg_types": ["human", "ai"],
"tool_profile_flag": False,
"tool_bound_tools": 1,
"tool_msg_types": ["human", "ai", "tool"],
"empty_profile_bound_tools": 1,
"empty_profile_msg_types": ["human", "ai", "tool"],
"all_scores_equal": True,
}
return {
"name": "auto_strategy_and_model_profile_routing",
"passed": actual == expected,
"expected": expected,
"actual": actual,
}
def case_json_schema_caveat_and_dynamic_builder() -> dict:
course_schema = {
"title": "CourseInfo",
"description": "课程信息",
"type": "object",
"properties": {
"name": {"type": "string"},
"hours": {"type": "integer", "minimum": 1},
},
"required": ["name", "hours"],
}
m_js = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[
{"name": "CourseInfo", "args": {"name": "Python", "hours": -5}, "id": "j1", "type": "tool_call"}
],
)
]
)
r_js = create_agent(model=m_js, tools=[], response_format=ToolStrategy(course_schema)).invoke(
{"messages": [{"role": "user", "content": "提取"}]}
)
class ReviewResult(BaseModel):
sentiment: Literal["积极", "消极", "中性"]
score: int = Field(ge=1, le=10)
advantages: list[str]
disadvantages: list[str]
def build_agent(model: BaseChatModel, strategy: str = "auto"):
rf = ReviewResult if strategy == "auto" else ToolStrategy(ReviewResult, handle_errors=True)
return create_agent(model=model, tools=[], response_format=rf)
sample = {
"sentiment": "积极",
"score": 8,
"advantages": ["内容清晰", "实例丰富"],
"disadvantages": ["高级主题覆盖较少"],
}
m_auto = ScriptedChatModel(
profile={"structured_output": True, "tool_calling": True},
responses=[AIMessage(content=json.dumps(sample, ensure_ascii=False))],
)
m_tool = ScriptedChatModel(
profile={"structured_output": False, "tool_calling": True},
responses=[
AIMessage(
content="",
tool_calls=[{"name": "ReviewResult", "args": sample, "id": "rv1", "type": "tool_call"}],
)
],
)
r_auto = build_agent(m_auto, "auto").invoke({"messages": [{"role": "user", "content": "分析评价"}]})
r_tool = build_agent(m_tool, "tool").invoke({"messages": [{"role": "user", "content": "分析评价"}]})
actual = {
"raw_json_schema_hours_not_validated": r_js["structured_response"]["hours"],
"auto_ai_msg_count": sum(x.type == "ai" for x in r_auto["messages"]),
"tool_ai_msg_count": sum(x.type == "ai" for x in r_tool["messages"]),
"auto_review": r_auto["structured_response"].model_dump(),
"tool_review": r_tool["structured_response"].model_dump(),
}
expected = {
"raw_json_schema_hours_not_validated": -5,
"auto_ai_msg_count": 1,
"tool_ai_msg_count": 1,
"auto_review": sample,
"tool_review": sample,
}
return {
"name": "json_schema_caveat_and_dynamic_builder",
"passed": actual == expected,
"expected": expected,
"actual": actual,
}
def main() -> None:
cases = [
case_tool_strategy_messages_and_custom_tool_message(),
case_handle_errors_variants(),
case_provider_strategy_and_strict_flag(),
case_auto_strategy_and_model_profile_routing(),
case_json_schema_caveat_and_dynamic_builder(),
]
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-strategies-lab/explore-structured-output-strategies.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-structured-output-strategies.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联37章) · 含当前章节或实例 · mbskycom202612a509.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a537.zip