蓝色天空.知识 · 实践 · 创造
我的收藏
LangChain 教程目录 37章
LangChain / LEARN BY DOING

LangChain Chat Model 高级用法

深入讲解 bind_tools() 四种工具定义与手动闭环调度、with_structured_output() 扁平/嵌套 Pydantic 与 JSON Schema 解析、include_raw=True 错误捕获及可配置模型声明式组合。

学完这一章,你能够

  • 深入讲解 bind_tools() 四种工具定义与手动闭环调度、with_structured_output() 扁平/嵌套 Pydantic 与 JSON Schema 解析、include_raw=True 错误捕获及可配置模型声明式组合。

Chat Model 两大高阶能力与环境准备

除基础文本对话外,LangChain Chat Model 提供两项核心工程能力:bind_tools() 向模型声明外部工具定义以生成工具调用请求,with_structured_output() 按给定 Schema 将模型响应解析为强类型数据结构。两者定位不同,但底层常共用模型的结构化函数调用能力。

依赖包含 langchain、langchain-deepseek、pydantic 与 python-dotenv,通过 .env 加载密钥并用 init_chat_model("deepseek:deepseek-flash") 初始化基础模型。具体可用特性仍取决于目标模型版本与集成实现。

bind_tools() 四类工具定义与手动 Tool Calling 闭环

bind_tools(tools) 只负责向模型声明可用工具及其参数模式,绝不会自动执行 Python 函数。LangChain 支持四种定义形式:@tool 装饰器工具、普通 Python 函数、Pydantic BaseModel 类以及 OpenAI Function Calling 格式字典。模型决策调用工具后,LangChain 将其标准化至 AIMessage.tool_calls(字段见表 1);若参数解析损坏则会出现在 invalid_tool_calls,工程上不能假定每次调用必然合法或必然触发。

需实际执行代码时推荐 @tool 装饰器(由函数名、类型注解与 docstring 自动生成工具定义);参数较复杂时可用 Pydantic 类(如 GetWeather、Calculate)声明带 Field 描述的入参结构,但注意 Pydantic 类仅描述参数而不含执行逻辑,且默认工具名为类名本身(GetWeather 而非 get_weather)。本站离线实测一次传入全部四种工具定义,convert_to_openai_tool 准确产出 ['get_weather', 'get_weather_dict', 'plain_add', 'GetWeather', 'Calculate'],且 invoke 后工具执行计数器仍为 0,证实不会自动执行。

不借助 Agent 时,手动工具闭环包含:追加模型返回的 AIMessage → 遍历 response.tool_calls 查 tool_map 执行 Python 工具并捕获异常 → 封装为带匹配 tool_call_id 的 ToolMessage 追加至消息列表 → 二次调用模型汇总最终回答。本站离线实测完整闭环:get_weather 仅在手动分发阶段执行 1 次,最终基于 ToolMessage 生成 "杭州的模拟天气为:晴,25°C。"。若需多轮循环建议改用 create_agent(),执行写库/文件/网络工具前务必做参数与权限校验。

with_structured_output():Pydantic、嵌套结构与 JSON Schema

with_structured_output(schema) 支持 Pydantic 模型、JSON Schema 字典与 TypedDict,使模型响应直接转为程序可用结构(底层可能借助 Tool Calling、JSON Mode 或原生 JSON Schema)。使用 Pydantic(如 PersonInfo)解析成功时返回对应模型实例,可直接属性访问并调用 .model_dump(),同时获得字段类型验证——但切记类型合法不等于事实准确,高敏场景仍须业务核验。

表 2 对比了 bind_tools() 与 with_structured_output() 的职责边界:前者让模型决策下一步「要做什么动作」,返回 AIMessage 交由程序/Agent 执行;后者约束模型按程序要求的「数据结构」产出结果,返回 Pydantic 实例或 dict。

结构化输出支持复杂嵌套对象列表(例如 Recipe 内嵌 list[Ingredient] 与 list[CookingStep]),也支持跨语言通用的 JSON Schema 字典(例如情感分析 SentimentAnalysis,注意模型输出的 confidence 只是估计值而非统计校准概率,且传入 JSON Schema 时返回普通 dict,LangChain 未必执行全量 JSON Schema 规则校验)。本站离线实测:PersonInfo 与 Recipe(5 种食材、4 个步骤共 15 分钟)均返回强类型 Pydantic 实例,而 SentimentAnalysis JSON Schema 返回原生 dict。

include_raw=True、底层机制、失败兜底与可配置模型组合

启用 include_raw=True 后,返回值变为含 raw、parsed、parsing_error 三键的字典(见表 3),方便同时观测原始 AIMessage、Token 统计与解析异常(但网络/鉴权异常仍需外层 try/except 捕获)。

底层实现常见 function_calling、json_mode 与 json_schema 三类方式(见表 4)。使用 DeepSeek 原生 JSON Output(response_format={'type': 'json_object'})时必须在提示词中显式要求输出 JSON 并给示例,且需防范 JSON Mode 仅保语法不保字段类型以及偶发空输出/截断问题。本站离线实测 UserInfo(age: int = Field(ge=0, le=150)) 配合 include_raw=True:合法输入(28)返回 parsing_error=None,而非法类型("未知")与超界值(200)均在 parsed=None 下捕获为 Pydantic ValidationError,演示了双层兜底检查。

通过 init_chat_model(..., configurable_fields=["model"]) 创建的可配置模型同样支持声明式叠加 bind_tools() 与 with_structured_output()。本站离线实测确认两项操作均登记于 _ConfigurableModel._queued_declarative_operations,按运行时 config 解析至 deepseek-v4-pro 时分别生成 _ChatModelBinding 与 RunnableSequence;实际跨模型切换前务必核验目标模型兼容性。

完整信息提取实战、常见问题与总结

结合 ArticleInfo(title, summary, keywords) 与 include_raw=True 可搭建健壮的文章元数据提取程序(如 chat_model_advanced.py),并通过 result.model_dump_json(indent=2) 导出标准 JSON(本站已离线验证 ArticleInfo 解析与 JSON 往返),适用于摘要生成、关键词提取、内容分类与入库。

常见问题速览:bind_tools() 不自动执行工具;tool_calls 为空需检查是否确实需要工具、描述质量与模型支持(强制 tool_choice 并非所有厂商支持);Pydantic 工具类仅描述入参结构;structured output 报错可简化嵌套并开 include_raw=True 查 parsing_error;Python 内部优选 Pydantic,跨语言共享选 JSON Schema;返回 dict 与 Pydantic 实例由 Schema 与 include_raw 决定;需同时用工具与结构化输出时优先在 create_agent() 中组合 response_format,勿盲目链式叠加。

AIMessage.tool_calls 标准化字段说明

字段说明
name被模型选中的工具名称
args解析后的工具入参字典
id本次工具调用唯一标识,供 ToolMessage.tool_call_id 关联
type调用条目类型标记(固定为 tool_call)

bind_tools() 与 with_structured_output() 核心对比

对比项目bind_tools()with_structured_output()
主要用途向模型声明工具以生成调用请求约束模型按指定 Schema 输出并解析结构化数据
典型返回值AIMessage(含 tool_calls / invalid_tool_calls)Pydantic 模型实例或 dict(include_raw=True 时为三键字典)
工具执行须由业务代码或 create_agent() 显式执行聚焦数据抽取与校验,不执行外部业务动作
典型场景Agent、搜索、天气查询、数据库读写信息提取、情感分类、元数据与 JSON 生成
底层机制依赖模型原生 Tool Calling 能力可能经由 function_calling、json_mode 或 json_schema 实现

with_structured_output(..., include_raw=True) 返回字段

字段含义
raw模型返回的原始 AIMessage 响应(含元数据与 Token 统计)
parsed校验成功后的 Pydantic 实例或字典,失败时为 None
parsing_error解析或 Pydantic 校验阶段的异常对象,成功时为 None

with_structured_output() 三类底层实现方式

方式说明
function_calling借助工具/函数调用参数约束输出目标结构(本站离线实测通道)
json_mode开启服务端 JSON 输出模式(须配合提示词说明并在程序端做类型校验)
json_schema调用支持服务端原生 JSON Schema 约束的高级接口

离线验证 bind_tools 四种定义、手动工具闭环、嵌套 Pydantic/JSON Schema 与 include_raw 错误捕获

含完整源码 · 459 行
展开查看收起
python
"""Independent offline lab for LangChain Ch 09: bind_tools() & with_structured_output()."""
import json
import platform
from typing import Any

from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage, ToolMessage
from langchain.tools import tool
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import AIMessage
from langchain_core.outputs import ChatGeneration, ChatResult
from langchain_core.utils.function_calling import convert_to_openai_tool
from pydantic import BaseModel, Field, ValidationError


class OfflineAdvancedModel(BaseChatModel):
    """Offline chat model supporting bind_tools and with_structured_output."""

    responder: Any = None

    @property
    def _llm_type(self) -> str:
        return "offline-advanced-model"

    def _generate(self, messages, stop=None, run_manager=None, **kwargs):
        msg = self.responder(messages, kwargs)
        return ChatResult(generations=[ChatGeneration(message=msg)])

    def bind_tools(self, tools, *, tool_choice=None, **kwargs):
        formatted = [convert_to_openai_tool(t) for t in tools]
        return self.bind(tools=formatted, tool_choice=tool_choice, **kwargs)


class GetWeather(BaseModel):
    """查询指定城市的模拟天气。"""

    city: str = Field(description="城市名称,例如杭州、北京")
    unit: str = Field(default="celsius", description="温度单位:celsius 或 fahrenheit")


class Calculate(BaseModel):
    """计算简单的数学表达式。"""

    expression: str = Field(description="数学表达式,例如 123 * 456")


class PersonInfo(BaseModel):
    """从文本中提取人物信息。"""

    name: str = Field(description="人物姓名")
    age: int = Field(description="年龄")
    occupation: str = Field(description="职业")
    skills: list[str] = Field(description="技能列表")


class Ingredient(BaseModel):
    """食材信息。"""

    name: str = Field(description="食材名称")
    amount: str = Field(description="食材用量")


class CookingStep(BaseModel):
    """烹饪步骤。"""

    step_number: int = Field(description="步骤编号")
    description: str = Field(description="步骤说明")
    duration_minutes: int = Field(description="步骤所需分钟数")


class Recipe(BaseModel):
    """菜谱信息。"""

    dish_name: str = Field(description="菜名")
    difficulty: str = Field(description="难度")
    ingredients: list[Ingredient] = Field(description="食材列表")
    steps: list[CookingStep] = Field(description="烹饪步骤")


class UserInfo(BaseModel):
    """带范围校验的用户信息。"""

    name: str = Field(description="用户姓名")
    age: int = Field(ge=0, le=150, description="用户年龄")


class ArticleInfo(BaseModel):
    """文章信息。"""

    title: str = Field(description="文章标题")
    summary: str = Field(description="100字以内的文章摘要")
    keywords: list[str] = Field(description="文章关键词")


class SummaryInfo(BaseModel):
    """文本摘要信息。"""

    title: str = Field(description="标题")
    summary: str = Field(description="简短摘要")


def main():
    cases = []

    # 1. bind_tools with all 4 definition styles (dict, @tool, plain function, Pydantic) & proving no auto execution
    exec_counter = {"count": 0}

    @tool
    def get_weather(city: str) -> str:
        """查询指定城市的模拟天气。

        Args:
            city: 城市名称,如杭州、北京。
        """
        exec_counter["count"] += 1
        return {"杭州": "晴,25°C", "北京": "多云,18°C", "上海": "小雨,22°C"}.get(city, f"没有找到{city}的模拟天气")

    def plain_add(a: int, b: int) -> int:
        """计算两整数之和。"""
        return a + b

    dict_tool = {
        "type": "function",
        "function": {
            "name": "get_weather_dict",
            "description": "查询指定城市的模拟天气",
            "parameters": {
                "type": "object",
                "properties": {"city": {"type": "string", "description": "城市名称"}},
                "required": ["city"],
            },
        },
    }

    def tool_call_only(messages, kwargs):
        names = [t["function"]["name"] for t in kwargs["tools"]]
        return AIMessage(
            content="",
            tool_calls=[
                {"name": names[0], "args": {"city": "杭州"}, "id": "call_bind_01", "type": "tool_call"}
            ],
        )

    m_bind = OfflineAdvancedModel(responder=tool_call_only)
    bound_all = m_bind.bind_tools([get_weather, dict_tool, plain_add, GetWeather, Calculate])
    bound_names = [t["function"]["name"] for t in bound_all.kwargs["tools"]]
    resp_bind = bound_all.invoke("请使用 get_weather 查询杭州模拟天气。")

    c1_ok = (
        bound_names == ["get_weather", "get_weather_dict", "plain_add", "GetWeather", "Calculate"]
        and resp_bind.tool_calls[0]["name"] == "get_weather"
        and resp_bind.tool_calls[0]["args"] == {"city": "杭州"}
        and exec_counter["count"] == 0  # bind_tools MUST NOT execute Python tool
    )
    cases.append(
        dict(
            name="bind_tools_four_definitions_and_no_auto_exec",
            inputs=dict(tool_styles=["@tool", "openai_dict", "plain_function", "Pydantic"]),
            prerequisites="向 bind_tools 同时传入 @tool、OpenAI 字典、普通函数及 Pydantic 类(GetWeather/Calculate)。",
            action="验证 4 种定义统一转为 OpenAI tool schema(Pydantic 工具名保留类名 GetWeather),且 invoke 后不自动执行函数。",
            expected=dict(
                converted_names=["get_weather", "get_weather_dict", "plain_add", "GetWeather", "Calculate"],
                tool_not_auto_executed=True,
                returned_call_name="get_weather",
            ),
            actual=dict(
                converted_names=bound_names,
                tool_not_auto_executed=(exec_counter["count"] == 0),
                returned_call_name=resp_bind.tool_calls[0]["name"],
            ),
            measurements=dict(
                tool_call_id=resp_bind.tool_calls[0]["id"],
                tool_call_type=resp_bind.tool_calls[0]["type"],
            ),
            passed=c1_ok,
        )
    )

    # 2. Manual Tool Calling loop (HumanMessage -> AIMessage -> ToolMessage -> final AIMessage) + invalid_tool_calls check
    def loop_responder(messages, kwargs):
        if any(m.type == "tool" for m in messages):
            tool_res = next(m.content for m in reversed(messages) if m.type == "tool")
            return AIMessage(content=f"杭州的模拟天气为:{tool_res}。")
        return AIMessage(
            content="",
            tool_calls=[
                {"name": "get_weather", "args": {"city": "杭州"}, "id": "call_manual_01", "type": "tool_call"}
            ],
        )

    m_loop = OfflineAdvancedModel(responder=loop_responder).bind_tools([get_weather])
    messages = [HumanMessage(content="请调用工具查询杭州的模拟天气。")]
    first_resp = m_loop.invoke(messages)
    messages.append(first_resp)

    tool_map = {"get_weather": get_weather}
    for tc in first_resp.tool_calls:
        tname = tc["name"]
        tool_result = tool_map[tname].invoke(tc["args"]) if tname in tool_map else f"未知工具:{tname}"
        messages.append(ToolMessage(content=str(tool_result), tool_call_id=tc["id"]))

    final_resp = m_loop.invoke(messages)
    invalid_ai = AIMessage(
        content="",
        invalid_tool_calls=[{"name": "get_weather", "args": "{bad json", "id": "call_bad", "error": "JSONDecodeError", "type": "invalid_tool_call"}],
    )

    c2_ok = (
        exec_counter["count"] == 1
        and [m.type for m in messages] == ["human", "ai", "tool"]
        and messages[2].tool_call_id == "call_manual_01"
        and final_resp.content == "杭州的模拟天气为:晴,25°C。"
        and len(invalid_ai.invalid_tool_calls) == 1
    )
    cases.append(
        dict(
            name="manual_tool_calling_loop_with_validation",
            inputs=dict(city="杭州"),
            prerequisites="手动完成 bind_tools -> invoke -> tool_map 分发 -> ToolMessage 回传 -> 二次 invoke 闭环,并核对 invalid_tool_calls 字段。",
            action="确认 get_weather 被显式执行 1 次,ToolMessage 通过 tool_call_id 关联请求,最终生成自然语言总结。",
            expected=dict(
                tool_exec_count=1,
                history_before_second_call=["human", "ai", "tool"],
                final_answer="杭州的模拟天气为:晴,25°C。",
                invalid_calls_recorded=1,
            ),
            actual=dict(
                tool_exec_count=exec_counter["count"],
                history_before_second_call=[m.type for m in messages],
                final_answer=final_resp.content,
                invalid_calls_recorded=len(invalid_ai.invalid_tool_calls),
            ),
            measurements=dict(
                tool_output=messages[2].content,
            ),
            passed=c2_ok,
        )
    )

    # 3. with_structured_output: flat Pydantic, nested Recipe, JSON Schema dict, ArticleInfo JSON dump
    def structured_responder(messages, kwargs):
        tname = kwargs["tools"][0]["function"]["name"]
        payloads = {
            "PersonInfo": {
                "name": "张三",
                "age": 28,
                "occupation": "全栈工程师",
                "skills": ["Python", "React", "Docker"],
            },
            "Recipe": {
                "dish_name": "番茄炒蛋",
                "difficulty": "简单",
                "ingredients": [
                    {"name": "番茄", "amount": "2个"},
                    {"name": "鸡蛋", "amount": "3个"},
                    {"name": "葱花", "amount": "少许"},
                    {"name": "盐", "amount": "适量"},
                    {"name": "糖", "amount": "少许"},
                ],
                "steps": [
                    {"step_number": 1, "description": "番茄切块,鸡蛋打散", "duration_minutes": 5},
                    {"step_number": 2, "description": "将鸡蛋炒熟盛出", "duration_minutes": 3},
                    {"step_number": 3, "description": "炒番茄至出汁,加盐和糖", "duration_minutes": 5},
                    {"step_number": 4, "description": "加入鸡蛋翻炒,撒上葱花", "duration_minutes": 2},
                ],
            },
            "SentimentAnalysis": {
                "sentiment": "positive",
                "confidence": 0.95,
                "keywords": ["简洁", "推荐"],
            },
            "ArticleInfo": {
                "title": "Python 编程语言简介",
                "summary": "Python 语法简洁,广泛用于 Web 开发、数据分析与人工智能。",
                "keywords": ["Python", "Web开发", "数据分析", "人工智能"],
            },
        }
        return AIMessage(
            content="",
            tool_calls=[{"name": tname, "args": payloads[tname], "id": f"call_{tname}", "type": "tool_call"}],
        )

    m_struct = OfflineAdvancedModel(responder=structured_responder)
    person = m_struct.with_structured_output(PersonInfo).invoke("张三28岁全栈工程师")
    recipe = m_struct.with_structured_output(Recipe).invoke("番茄炒蛋菜谱")

    sentiment_schema = {
        "title": "SentimentAnalysis",
        "description": "文本情感分析结果",
        "type": "object",
        "properties": {
            "sentiment": {"type": "string", "enum": ["positive", "negative", "neutral"]},
            "confidence": {"type": "number", "minimum": 0, "maximum": 1},
            "keywords": {"type": "array", "items": {"type": "string"}},
        },
        "required": ["sentiment", "confidence", "keywords"],
    }
    sentiment = m_struct.with_structured_output(sentiment_schema).invoke("这套教程简洁清晰,强烈推荐!")
    article = m_struct.with_structured_output(ArticleInfo).invoke("Python 文章")
    article_json = json.loads(article.model_dump_json())

    c3_ok = (
        isinstance(person, PersonInfo)
        and person.model_dump() == {"name": "张三", "age": 28, "occupation": "全栈工程师", "skills": ["Python", "React", "Docker"]}
        and isinstance(recipe, Recipe)
        and len(recipe.ingredients) == 5
        and len(recipe.steps) == 4
        and sum(s.duration_minutes for s in recipe.steps) == 15
        and type(sentiment) is dict
        and sentiment["sentiment"] == "positive"
        and isinstance(article, ArticleInfo)
        and article_json["title"] == "Python 编程语言简介"
    )
    cases.append(
        dict(
            name="structured_output_pydantic_nested_and_json_schema",
            inputs=dict(schemas=["PersonInfo", "Recipe", "SentimentAnalysis(JSON Schema)", "ArticleInfo"]),
            prerequisites="分别使用扁平 Pydantic、嵌套 Pydantic(含食材与步骤子模型)和 JSON Schema 字典调用 with_structured_output。",
            action="验证 Pydantic 返回强类型模型实例且支持 model_dump/model_dump_json,而 JSON Schema 返回普通 dict。",
            expected=dict(
                person_is_pydantic=True,
                recipe_ingredients=5,
                recipe_steps=4,
                recipe_total_minutes=15,
                json_schema_returns_dict=True,
                article_title="Python 编程语言简介",
            ),
            actual=dict(
                person_is_pydantic=isinstance(person, PersonInfo),
                recipe_ingredients=len(recipe.ingredients),
                recipe_steps=len(recipe.steps),
                recipe_total_minutes=sum(s.duration_minutes for s in recipe.steps),
                json_schema_returns_dict=(type(sentiment) is dict),
                article_title=article_json["title"],
            ),
            measurements=dict(
                person_dump=person.model_dump(),
                sentiment_dict=sentiment,
            ),
            passed=c3_ok,
        )
    )

    # 4. include_raw=True success and Pydantic ValidationError capture (bad type & out-of-range)
    def user_responder(messages, kwargs):
        prompt_text = str(messages[-1].content)
        tname = kwargs["tools"][0]["function"]["name"]
        if "非法类型" in prompt_text:
            args = {"name": "张三", "age": "未知"}
        elif "越界" in prompt_text:
            args = {"name": "张三", "age": 200}
        else:
            args = {"name": "张三", "age": 28}
        return AIMessage(
            content="",
            tool_calls=[{"name": tname, "args": args, "id": "call_user_1", "type": "tool_call"}],
        )

    m_raw = OfflineAdvancedModel(responder=user_responder).with_structured_output(UserInfo, include_raw=True)
    res_ok = m_raw.invoke("正常:张三28岁")
    res_bad_type = m_raw.invoke("非法类型:张三年龄未知")
    res_bad_range = m_raw.invoke("越界:张三200岁")

    c4_ok = (
        set(res_ok.keys()) == {"raw", "parsed", "parsing_error"}
        and isinstance(res_ok["raw"], AIMessage)
        and isinstance(res_ok["parsed"], UserInfo)
        and res_ok["parsed"].age == 28
        and res_ok["parsing_error"] is None
        and res_bad_type["parsed"] is None
        and isinstance(res_bad_type["parsing_error"], ValidationError)
        and res_bad_range["parsed"] is None
        and isinstance(res_bad_range["parsing_error"], ValidationError)
    )
    cases.append(
        dict(
            name="include_raw_and_validation_error_capture",
            inputs=dict(valid_age=28, invalid_type="未知", invalid_range=200),
            prerequisites="启用 with_structured_output(UserInfo, include_raw=True)(age 限制 0<=age<=150)测试合法、错类型与超界三种返回。",
            action="验证返回包含 raw/parsed/parsing_error 三键,合法样本 parsing_error 为 None,非法类型与越界均捕获为 ValidationError。",
            expected=dict(
                keys_exact=True,
                valid_age=28,
                valid_err_none=True,
                bad_type_error="ValidationError",
                bad_range_error="ValidationError",
            ),
            actual=dict(
                keys_exact=(set(res_ok.keys()) == {"raw", "parsed", "parsing_error"}),
                valid_age=res_ok["parsed"].age,
                valid_err_none=(res_ok["parsing_error"] is None),
                bad_type_error=type(res_bad_type["parsing_error"]).__name__,
                bad_range_error=type(res_bad_range["parsing_error"]).__name__,
            ),
            measurements=dict(
                raw_type=type(res_ok["raw"]).__name__,
            ),
            passed=c4_ok,
        )
    )

    # 5. ConfigurableModel declarative bind_tools() & with_structured_output()
    cfg_model = init_chat_model(
        "deepseek:deepseek-flash",
        configurable_fields=["model"],
        api_key="sk-offline-dummy",
    )
    cfg_tools = cfg_model.bind_tools([get_weather])
    cfg_struct = cfg_model.with_structured_output(SummaryInfo)
    resolved_pro_tools = cfg_tools._model({"configurable": {"model": "deepseek:deepseek-v4-pro"}})
    resolved_pro_struct = cfg_struct._model({"configurable": {"model": "deepseek:deepseek-v4-pro"}})

    c5_ok = (
        type(cfg_tools).__name__ == "_ConfigurableModel"
        and cfg_tools._queued_declarative_operations[0][0] == "bind_tools"
        and type(cfg_struct).__name__ == "_ConfigurableModel"
        and cfg_struct._queued_declarative_operations[0][0] == "with_structured_output"
        and resolved_pro_tools is not None
        and resolved_pro_struct is not None
    )
    cases.append(
        dict(
            name="configurable_model_declarative_ops",
            inputs=dict(default_model="deepseek:deepseek-flash", runtime_model="deepseek:deepseek-v4-pro"),
            prerequisites="在 init_chat_model(..., configurable_fields=['model']) 返回的可配置模型上叠加声明式 bind_tools 与 with_structured_output。",
            action="确认两项操作均记录于 _queued_declarative_operations,并可按运行时 config 解析出目标模型流水线。",
            expected=dict(
                tools_op_queued="bind_tools",
                struct_op_queued="with_structured_output",
                resolved_pro_runnables_ok=True,
            ),
            actual=dict(
                tools_op_queued=cfg_tools._queued_declarative_operations[0][0],
                struct_op_queued=cfg_struct._queued_declarative_operations[0][0],
                resolved_pro_runnables_ok=(resolved_pro_tools is not None and resolved_pro_struct is not None),
            ),
            measurements=dict(
                resolved_tools_type=type(resolved_pro_tools).__name__,
                resolved_struct_type=type(resolved_pro_struct).__name__,
            ),
            passed=c5_ok,
        )
    )

    print(
        json.dumps(
            dict(
                version=platform.python_version(),
                system=platform.system(),
                cases=cases,
            ),
            ensure_ascii=False,
        )
    )


if __name__ == "__main__":
    main()
核对 4 类工具定义转 schema 且不自动执行、手动闭环执行 1 次工具、扁平/嵌套 Pydantic 实例与 JSON Schema dict 差异、include_raw 捕获 ValidationError,以及可配置模型声明式绑定。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a509.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:LangChain

课程关联工程包(登记关联37章) · 含当前章节或实例 · mbskycom202612a509.zip

下载课程关联工程包:LangChain

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a526.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

不会直接中断:解析与 Pydantic 校验失败会被捕获放入 result['parsing_error'],同时 result['parsed'] 为 None、result['raw'] 保留原始消息;但网络超时、401 鉴权等底层请求异常仍会直接抛出,必须由外层 try/except 处理。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习