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

离线实测 return_direct 批量规则、InjectedToolCallId 隐藏、ToolException 四策略与课程登记 Agent

PYTHONWindows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。explore-tool-advanced.py
explore-tool-advanced.py460 行
"""Offline deterministic runtime lab for LangChain Chapter 12 (tool-advanced)."""
import json
import platform
from typing import Annotated, Any

from langchain.agents import create_agent
from langchain.tools import InjectedToolCallId, ToolException, tool
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 Field, ValidationError


class ScriptedChatModel(BaseChatModel):
    responses: list[AIMessage] = Field(default_factory=list)
    call_index: int = 0

    @property
    def _llm_type(self) -> str:
        return "scripted-offline-chat"

    def bind_tools(self, tools, **kwargs):
        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_return_direct_single_and_batch() -> dict:
    @tool
    def search_normal(keyword: str) -> str:
        """搜索指定关键词的模拟编程课程。"""
        courses = {"python": "Python 基础、Python 数据分析", "java": "Java 基础、Java 面向对象"}
        return courses.get(keyword.lower(), "没有找到匹配的模拟课程")

    @tool(return_direct=True)
    def search_direct(keyword: str) -> str:
        """搜索模拟课程并直接返回搜索结果。"""
        courses = {"python": "Python 基础、Python 数据分析", "java": "Java 基础、Java 面向对象"}
        return courses.get(keyword.lower(), "没有找到匹配的模拟课程")

    @tool(return_direct=True)
    def get_direct_tip(topic: str) -> str:
        """直接返回学习提示。"""
        return f"提示:{topic} 从基础练起"

    m_norm = ScriptedChatModel(
        responses=[
            AIMessage(
                content="",
                tool_calls=[
                    {"name": "search_normal", "args": {"keyword": "python"}, "id": "c1", "type": "tool_call"}
                ],
            ),
            AIMessage(content="为你找到:Python 基础、Python 数据分析。"),
        ]
    )
    r_norm = create_agent(model=m_norm, tools=[search_normal]).invoke(
        {"messages": [{"role": "user", "content": "搜索 python"}]}
    )

    m_dir = ScriptedChatModel(
        responses=[
            AIMessage(
                content="",
                tool_calls=[
                    {"name": "search_direct", "args": {"keyword": "python"}, "id": "c2", "type": "tool_call"}
                ],
            ),
            AIMessage(content="不应再调用模型"),
        ]
    )
    r_dir = create_agent(model=m_dir, tools=[search_direct]).invoke(
        {"messages": [{"role": "user", "content": "搜索 python"}]}
    )

    m_both = ScriptedChatModel(
        responses=[
            AIMessage(
                content="",
                tool_calls=[
                    {"name": "search_direct", "args": {"keyword": "python"}, "id": "c3", "type": "tool_call"},
                    {"name": "get_direct_tip", "args": {"topic": "Python"}, "id": "c4", "type": "tool_call"},
                ],
            ),
            AIMessage(content="不应再调用模型"),
        ]
    )
    r_both = create_agent(model=m_both, tools=[search_direct, get_direct_tip]).invoke(
        {"messages": [{"role": "user", "content": "查询与提示"}]}
    )

    m_mix = ScriptedChatModel(
        responses=[
            AIMessage(
                content="",
                tool_calls=[
                    {"name": "search_direct", "args": {"keyword": "python"}, "id": "c5", "type": "tool_call"},
                    {"name": "search_normal", "args": {"keyword": "java"}, "id": "c6", "type": "tool_call"},
                ],
            ),
            AIMessage(content="汇总 Python 与 Java 模拟课程结果。"),
        ]
    )
    r_mix = create_agent(model=m_mix, tools=[search_direct, search_normal]).invoke(
        {"messages": [{"role": "user", "content": "混合查询"}]}
    )

    actual = {
        "flags": [search_normal.return_direct, search_direct.return_direct],
        "normal_calls": m_norm.call_index,
        "normal_last_type": r_norm["messages"][-1].type,
        "direct_calls": m_dir.call_index,
        "direct_last_type": r_dir["messages"][-1].type,
        "direct_last_content": r_dir["messages"][-1].content,
        "both_direct_calls": m_both.call_index,
        "both_direct_last_type": r_both["messages"][-1].type,
        "mixed_calls": m_mix.call_index,
        "mixed_last_type": r_mix["messages"][-1].type,
    }
    expected = {
        "flags": [False, True],
        "normal_calls": 2,
        "normal_last_type": "ai",
        "direct_calls": 1,
        "direct_last_type": "tool",
        "direct_last_content": "Python 基础、Python 数据分析",
        "both_direct_calls": 1,
        "both_direct_last_type": "tool",
        "mixed_calls": 2,
        "mixed_last_type": "ai",
    }
    return {
        "name": "return_direct_single_and_batch",
        "passed": actual == expected,
        "expected": expected,
        "actual": actual,
    }


def case_injected_tool_call_id_and_schema_hiding() -> dict:
    @tool
    def log_user_action(
        action: str,
        tool_call_id: Annotated[str, InjectedToolCallId],
    ) -> str:
        """记录一条模拟操作日志。"""
        return f"操作:{action};工具调用 ID:{tool_call_id}"

    public_props = sorted(log_user_action.tool_call_schema.model_json_schema().get("properties", {}).keys())
    msg = log_user_action.invoke(
        {
            "name": "log_user_action",
            "args": {"action": "查询 Python 课程"},
            "id": "call_log_001",
            "type": "tool_call",
        }
    )

    actual = {
        "public_schema_props": public_props,
        "result_type": type(msg).__name__,
        "result_content": msg.content,
        "result_tool_call_id": msg.tool_call_id,
    }
    expected = {
        "public_schema_props": ["action"],
        "result_type": "ToolMessage",
        "result_content": "操作:查询 Python 课程;工具调用 ID:call_log_001",
        "result_tool_call_id": "call_log_001",
    }
    return {
        "name": "injected_tool_call_id_and_schema_hiding",
        "passed": actual == expected,
        "expected": expected,
        "actual": actual,
    }


def case_tool_exception_and_handle_tool_error_modes() -> dict:
    decorator_kwarg_error = None
    try:
        @tool(handle_tool_error=True)  # type: ignore[call-overload]
        def bad_deco(x: str) -> str:
            """测试错误写法。"""
            return x
    except TypeError as exc:
        decorator_kwarg_error = type(exc).__name__

    @tool
    def get_weather(city: str) -> str:
        """查询指定城市的模拟天气。"""
        data = {"杭州": "晴,25°C", "北京": "多云,18°C", "上海": "小雨,22°C"}
        if city not in data:
            raise ToolException(f"未收录城市:{city}。可查询杭州、北京和上海。")
        return f"{city}的模拟天气:{data[city]}"

    default_flag = get_weather.handle_tool_error
    raised_default = None
    try:
        get_weather.invoke({"city": "北境"})
    except ToolException as exc:
        raised_default = str(exc)

    with_config_raised = None
    try:
        get_weather.with_config(handle_tool_errors=True).invoke({"city": "北境"})
    except ToolException as exc:
        with_config_raised = type(exc).__name__

    get_weather.handle_tool_error = True
    true_str_out = get_weather.invoke({"city": "北境"})
    true_tc_msg = get_weather.invoke(
        {"name": "get_weather", "args": {"city": "北境"}, "id": "call_weather_001", "type": "tool_call"}
    )

    get_weather.handle_tool_error = "天气查询失败,请检查城市名称。"
    fixed_str_out = get_weather.invoke({"city": "北境"})

    def safe_handler(error: ToolException) -> str:
        return f"安全提示:无法查询({len(str(error))}字错误已记录)。"

    get_weather.handle_tool_error = safe_handler
    callable_out = get_weather.invoke({"city": "北境"})

    actual = {
        "decorator_kwarg_error": decorator_kwarg_error,
        "default_flag": default_flag,
        "raised_default": raised_default,
        "with_config_still_raises": with_config_raised,
        "true_str_out": true_str_out,
        "true_tc_type": type(true_tc_msg).__name__,
        "true_tc_status": true_tc_msg.status,
        "true_tc_id": true_tc_msg.tool_call_id,
        "fixed_str_out": fixed_str_out,
        "callable_out": callable_out,
    }
    expected = {
        "decorator_kwarg_error": "TypeError",
        "default_flag": False,
        "raised_default": "未收录城市:北境。可查询杭州、北京和上海。",
        "with_config_still_raises": "ToolException",
        "true_str_out": "未收录城市:北境。可查询杭州、北京和上海。",
        "true_tc_type": "ToolMessage",
        "true_tc_status": "error",
        "true_tc_id": "call_weather_001",
        "fixed_str_out": "天气查询失败,请检查城市名称。",
        "callable_out": "安全提示:无法查询(21字错误已记录)。",
    }
    return {
        "name": "tool_exception_and_handle_tool_error_modes",
        "passed": actual == expected,
        "expected": expected,
        "actual": actual,
    }


def case_handle_tool_error_vs_validation_error() -> dict:
    @tool
    def get_user_info(user_id: int) -> str:
        """查询指定用户的模拟资料。"""
        if user_id <= 0:
            raise ToolException("用户 ID 必须是正整数")
        users = {1: "张三,普通用户", 2: "李四,普通用户"}
        if user_id not in users:
            raise ToolException(f"未找到 ID 为 {user_id} 的用户")
        return users[user_id]

    get_user_info.handle_tool_error = True
    ok_out = get_user_info.invoke({"user_id": 1})
    tool_err_out = get_user_info.invoke({"user_id": -1})

    val_err_uncaught = None
    try:
        get_user_info.invoke({"user_id": "invalid_int"})
    except ValidationError as exc:
        val_err_uncaught = type(exc).__name__

    get_user_info.handle_validation_error = True
    val_err_handled = get_user_info.invoke({"user_id": "invalid_int"})

    actual = {
        "ok_out": ok_out,
        "tool_err_out": tool_err_out,
        "val_err_uncaught": val_err_uncaught,
        "val_err_handled_is_str": isinstance(val_err_handled, str),
        "val_err_handled_text": val_err_handled,
    }
    expected = {
        "ok_out": "张三,普通用户",
        "tool_err_out": "用户 ID 必须是正整数",
        "val_err_uncaught": "ValidationError",
        "val_err_handled_is_str": True,
        "val_err_handled_text": "Tool input validation error",
    }
    return {
        "name": "handle_tool_error_vs_validation_error",
        "passed": actual == expected,
        "expected": expected,
        "actual": actual,
    }


def case_agent_registration_recovery_and_direct_error_stop() -> dict:
    users = {"张三", "李四", "王五"}
    courses = {"Python3 基础教程", "HTML 基础教程", "Java 面向对象"}
    registrations: set[tuple[str, str]] = set()

    @tool
    def register_course(user_name: str, course_name: str) -> str:
        """为指定用户登记一门模拟课程。"""
        if user_name not in users:
            raise ToolException(f"用户不存在:{user_name}")
        if course_name not in courses:
            raise ToolException(f"课程不存在:{course_name}")
        rec = (user_name, course_name)
        if rec in registrations:
            raise ToolException("该用户已经登记过这门课程")
        registrations.add(rec)
        return f"模拟登记成功:{user_name} - {course_name}"

    register_course.handle_tool_error = "课程登记未完成。请检查用户、课程名称或重复登记情况。"

    m_reg = ScriptedChatModel(
        responses=[
            AIMessage(
                content="",
                tool_calls=[
                    {
                        "name": "register_course",
                        "args": {"user_name": "张三", "course_name": "Python3 基础教程"},
                        "id": "r1",
                        "type": "tool_call",
                    }
                ],
            ),
            AIMessage(content="已为张三完成模拟登记。"),
            AIMessage(
                content="",
                tool_calls=[
                    {
                        "name": "register_course",
                        "args": {"user_name": "赵六", "course_name": "Python3 基础教程"},
                        "id": "r2",
                        "type": "tool_call",
                    }
                ],
            ),
            AIMessage(content="赵六登记未成功,请核对用户信息。"),
            AIMessage(
                content="",
                tool_calls=[
                    {
                        "name": "register_course",
                        "args": {"user_name": "张三", "course_name": "Python3 基础教程"},
                        "id": "r3",
                        "type": "tool_call",
                    }
                ],
            ),
            AIMessage(content="重复登记未通过,原有记录保持不变。"),
        ]
    )
    ag_reg = create_agent(model=m_reg, tools=[register_course])
    res1 = ag_reg.invoke({"messages": [{"role": "user", "content": "为张三登记"}]})
    res2 = ag_reg.invoke({"messages": [{"role": "user", "content": "为赵六登记"}]})
    res3 = ag_reg.invoke({"messages": [{"role": "user", "content": "再次为张三登记"}]})

    t1 = next(m for m in res1["messages"] if isinstance(m, ToolMessage))
    t2 = next(m for m in res2["messages"] if isinstance(m, ToolMessage))
    t3 = next(m for m in res3["messages"] if isinstance(m, ToolMessage))

    @tool(return_direct=True)
    def lookup_course_direct(course_name: str) -> str:
        """直接返回课程查询结果。"""
        if course_name != "Python3 基础教程":
            raise ToolException("课程不存在")
        return "课程:Python3 基础教程"

    lookup_course_direct.handle_tool_error = True
    m_de = ScriptedChatModel(
        responses=[
            AIMessage(
                content="",
                tool_calls=[
                    {
                        "name": "lookup_course_direct",
                        "args": {"course_name": "未知课程"},
                        "id": "d1",
                        "type": "tool_call",
                    }
                ],
            ),
            AIMessage(content="若触发直接返回则不会执行此处"),
        ]
    )
    r_de = create_agent(model=m_de, tools=[lookup_course_direct]).invoke(
        {"messages": [{"role": "user", "content": "查询未知课程"}]}
    )

    actual = {
        "turn1_tool": [t1.status, t1.content],
        "turn2_tool": [t2.status, t2.content],
        "turn3_tool": [t3.status, t3.content],
        "registrations": sorted([list(x) for x in registrations]),
        "direct_err_model_calls": m_de.call_index,
        "direct_err_last_type": r_de["messages"][-1].type,
        "direct_err_last_status": r_de["messages"][-1].status,
        "direct_err_last_content": r_de["messages"][-1].content,
    }
    expected = {
        "turn1_tool": ["success", "模拟登记成功:张三 - Python3 基础教程"],
        "turn2_tool": ["error", "课程登记未完成。请检查用户、课程名称或重复登记情况。"],
        "turn3_tool": ["error", "课程登记未完成。请检查用户、课程名称或重复登记情况。"],
        "registrations": [["张三", "Python3 基础教程"]],
        "direct_err_model_calls": 1,
        "direct_err_last_type": "tool",
        "direct_err_last_status": "error",
        "direct_err_last_content": "课程不存在",
    }
    return {
        "name": "agent_registration_recovery_and_direct_error_stop",
        "passed": actual == expected,
        "expected": expected,
        "actual": actual,
    }


def main() -> None:
    cases = [
        case_return_direct_single_and_batch(),
        case_injected_tool_call_id_and_schema_hiding(),
        case_tool_exception_and_handle_tool_error_modes(),
        case_handle_tool_error_vs_validation_error(),
        case_agent_registration_recovery_and_direct_error_stop(),
    ]
    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-tool-advanced-lab/explore-tool-advanced.py

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

下载课程关联工程包:LangChain

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

下载课程关联工程包:LangChain

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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