蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PYTHONWindows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。explore-model-advanced.py
explore-model-advanced.py459 行
"""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()
本例需在 Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。

入口文件:projects/langchain-model-advanced-lab/explore-model-advanced.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-model-advanced.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:LangChain

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

下载课程关联工程包:LangChain

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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