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

离线实测 Subagents 上下文隔离、Pydantic Router、Handoffs 状态图、工具过滤与并发共享 Store

PYTHONWindows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。explore-multi-agent.py
explore-multi-agent.py405 行
"""Offline runtime lab for LangChain Ch 29: multi-agent."""
from __future__ import annotations

import asyncio
from dataclasses import dataclass
import json
import platform
from typing import Any, Literal, TypedDict

from langchain.agents import create_agent
from langchain.agents.middleware import ModelRequest, wrap_model_call
from langchain.messages import AIMessage
from langchain.tools import ToolRuntime, tool
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.outputs import ChatGeneration, ChatResult
from langgraph.graph import END, START, StateGraph
from langgraph.store.memory import InMemoryStore
from pydantic import BaseModel, Field, ValidationError


@dataclass
class AdminUserContext:
    is_admin: bool = False


@dataclass
class StoreUserContext:
    user_id: str


class HandoffState(TypedDict):
    intent: str
    authorized_refund: bool
    active_agent: str
    trace: list[str]
    outcome: str


class ScriptedChatModel(BaseChatModel):
    responses: list[Any] = Field(default_factory=list)
    cursor: list[int] = Field(default_factory=lambda: [0])
    seen_histories: list[int] = Field(default_factory=list)
    seen_bound_tools: list[list[str]] = Field(default_factory=list)
    bound_names: list[str] = Field(default_factory=list)

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

    def bind_tools(self, tools: Any, **kwargs: Any) -> "ScriptedChatModel":
        names = [getattr(t, "name", str(t)) for t in tools]
        return self.model_copy(update={"bound_names": names})

    def _generate(self, messages: list[Any], stop: Any = None, run_manager: Any = None, **kwargs: Any) -> ChatResult:
        self.seen_histories.append(len(messages))
        self.seen_bound_tools.append(list(self.bound_names))
        idx = self.cursor[0]
        self.cursor[0] += 1
        item = self.responses[idx] if idx < len(self.responses) else AIMessage(content="done")
        msg = item(messages) if callable(item) else item
        return ChatResult(generations=[ChatGeneration(message=msg)])

    async def _agenerate(self, messages: list[Any], stop: Any = None, run_manager: Any = None, **kwargs: Any) -> ChatResult:
        return self._generate(messages, stop=stop, run_manager=run_manager, **kwargs)


def case_subagents_supervisor_and_context_isolation() -> dict[str, Any]:
    @tool
    def search_course(keyword: str) -> str:
        """按语言关键词查询模拟编程课程。"""
        courses = {"python": "Python3 基础教程,入门", "java": "Java 基础教程,入门"}
        return courses.get(keyword.strip().lower(), "没有找到匹配的模拟课程")

    @tool
    def celsius_to_fahrenheit(celsius: float) -> float:
        """安全数值工具:将摄氏温度转换为华氏温度(禁用 eval)。"""
        return round(celsius * 9 / 5 + 32, 2)

    m_course = ScriptedChatModel(
        responses=[
            AIMessage(content="", tool_calls=[{"name": "search_course", "args": {"keyword": "python"}, "id": "tc_c", "type": "tool_call"}]),
            AIMessage(content="推荐:Python3 基础教程,入门"),
        ]
    )
    m_math = ScriptedChatModel(
        responses=[
            AIMessage(content="", tool_calls=[{"name": "celsius_to_fahrenheit", "args": {"celsius": 25.0}, "id": "tc_m", "type": "tool_call"}]),
            AIMessage(content="25 摄氏度等于 77.0 华氏度"),
        ]
    )

    course_agent = create_agent(model=m_course, tools=[search_course], name="course_expert")
    math_agent = create_agent(model=m_math, tools=[celsius_to_fahrenheit], name="math_expert")

    @tool
    def ask_course_expert(question: str) -> str:
        """委派编程课程查询给课程专家。"""
        res = course_agent.invoke({"messages": [{"role": "user", "content": question}]})
        return str(res["messages"][-1].content)

    @tool
    def ask_math_expert(question: str) -> str:
        """委派数值计算给数学专家。"""
        res = math_agent.invoke({"messages": [{"role": "user", "content": question}]})
        return str(res["messages"][-1].content)

    m_coord = ScriptedChatModel(
        responses=[
            AIMessage(
                content="",
                tool_calls=[
                    {"name": "ask_course_expert", "args": {"question": "推荐 Python 入门课"}, "id": "tc_1", "type": "tool_call"},
                    {"name": "ask_math_expert", "args": {"question": "25 摄氏度等于多少华氏度"}, "id": "tc_2", "type": "tool_call"},
                ],
            ),
            AIMessage(content="汇总:推荐 Python3 基础教程,入门;25 摄氏度等于 77.0 华氏度。"),
        ]
    )
    coordinator = create_agent(model=m_coord, tools=[ask_course_expert, ask_math_expert], name="coordinator")
    # Simulate multi-message parent history to verify subagents only see 1 isolated message
    res = coordinator.invoke(
        {
            "messages": [
                {"role": "user", "content": "之前聊过数据库优化"},
                {"role": "assistant", "content": "好的"},
                {"role": "user", "content": "推荐一门 Python 入门课程,并计算 25 摄氏度等于多少华氏度。"},
            ]
        }
    )

    actual = {
        "graph_names": [course_agent.name, math_agent.name, coordinator.name],
        "parent_first_call_msgs": m_coord.seen_histories[0],
        "course_subagent_first_call_msgs": m_course.seen_histories[0],
        "math_subagent_first_call_msgs": m_math.seen_histories[0],
        "final_contains_both": ("Python3 基础教程" in res["messages"][-1].content and "77.0" in res["messages"][-1].content),
        "parent_only_got_tool_summaries": len(res["messages"]) == 7,
    }
    expected = {
        "graph_names": ["course_expert", "math_expert", "coordinator"],
        "parent_first_call_msgs": 3,
        "course_subagent_first_call_msgs": 1,
        "math_subagent_first_call_msgs": 1,
        "final_contains_both": True,
        "parent_only_got_tool_summaries": True,
    }
    return {
        "name": "subagents_supervisor_and_context_isolation",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_router_pydantic_dispatch() -> dict[str, Any]:
    class RouteDecision(BaseModel):
        category: Literal["course", "math", "general"]

    agents = {
        "course": create_agent(model=ScriptedChatModel(responses=[AIMessage(content="课程专家回答")]), tools=[], name="course_agent"),
        "math": create_agent(model=ScriptedChatModel(responses=[AIMessage(content="数学专家回答")]), tools=[], name="math_agent"),
        "general": create_agent(model=ScriptedChatModel(responses=[AIMessage(content="通用助手回答")]), tools=[], name="general_agent"),
    }

    def deterministic_classify(question: str) -> RouteDecision:
        if "课程" in question or "Python" in question:
            return RouteDecision(category="course")
        if "摄氏度" in question or "计算" in question:
            return RouteDecision(category="math")
        return RouteDecision(category="general")

    def route_question(question: str) -> tuple[str, str]:
        decision = deterministic_classify(question)
        res = agents[decision.category].invoke({"messages": [{"role": "user", "content": question}]})
        return decision.category, str(res["messages"][-1].content)

    r_course = route_question("Python 有哪些入门课程?")
    r_math = route_question("计算 25 摄氏度")
    r_gen = route_question("你好")

    invalid_rejected = False
    try:
        RouteDecision(category="unknown")  # type: ignore[arg-type]
    except ValidationError:
        invalid_rejected = True

    actual = {
        "course_route": list(r_course),
        "math_route": list(r_math),
        "general_route": list(r_gen),
        "invalid_category_rejected": invalid_rejected,
    }
    expected = {
        "course_route": ["course", "课程专家回答"],
        "math_route": ["math", "数学专家回答"],
        "general_route": ["general", "通用助手回答"],
        "invalid_category_rejected": True,
    }
    return {
        "name": "router_pydantic_dispatch",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_sequential_workflow_and_handoffs_state_graph() -> dict[str, Any]:
    # 1) Deterministic sequential workflow: Writer -> Reviewer
    writer = create_agent(
        model=ScriptedChatModel(responses=[AIMessage(content="Python 装饰器用于在不修改原函数代码时增强函数功能。")]),
        tools=[],
        name="writer",
    )
    reviewer = create_agent(
        model=ScriptedChatModel(responses=[AIMessage(content="审稿意见:建议补充 @functools.wraps 说明。")]),
        tools=[],
        name="reviewer",
    )
    draft = str(writer.invoke({"messages": [{"role": "user", "content": "写一段 Python 装饰器教程"}]})["messages"][-1].content)
    review = str(reviewer.invoke({"messages": [{"role": "user", "content": f"审核:\n{draft}"}]})["messages"][-1].content)

    # 2) Handoffs StateGraph: support -> refund -> done (with backend permission check)
    def support_node(state: HandoffState) -> dict[str, Any]:
        tr = list(state["trace"]) + ["support"]
        if state["intent"] == "refund":
            return {"active_agent": "refund", "trace": tr}
        return {"active_agent": "done", "trace": tr, "outcome": "普通客服已解答"}

    def refund_node(state: HandoffState) -> dict[str, Any]:
        tr = list(state["trace"]) + ["refund"]
        if not state["authorized_refund"]:
            return {"active_agent": "done", "trace": tr, "outcome": "退款需后端鉴权与人工审批"}
        return {"active_agent": "done", "trace": tr, "outcome": "退款申请已受理"}

    def route_after_support(state: HandoffState) -> str:
        return "refund" if state["active_agent"] == "refund" else END

    g = StateGraph(HandoffState)
    g.add_node("support", support_node)
    g.add_node("refund", refund_node)
    g.add_edge(START, "support")
    g.add_conditional_edges("support", route_after_support, {"refund": "refund", END: END})
    g.add_edge("refund", END)
    handoff_app = g.compile()

    r_unauth = handoff_app.invoke(
        {"intent": "refund", "authorized_refund": False, "active_agent": "support", "trace": [], "outcome": ""}
    )
    r_auth = handoff_app.invoke(
        {"intent": "refund", "authorized_refund": True, "active_agent": "support", "trace": [], "outcome": ""}
    )

    actual = {
        "sequential_draft_ok": "装饰器" in draft,
        "sequential_review_ok": "wraps" in review,
        "handoff_unauth_trace": r_unauth["trace"],
        "handoff_unauth_outcome": r_unauth["outcome"],
        "handoff_auth_outcome": r_auth["outcome"],
    }
    expected = {
        "sequential_draft_ok": True,
        "sequential_review_ok": True,
        "handoff_unauth_trace": ["support", "refund"],
        "handoff_unauth_outcome": "退款需后端鉴权与人工审批",
        "handoff_auth_outcome": "退款申请已受理",
    }
    return {
        "name": "sequential_workflow_and_handoffs_state_graph",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_middleware_dynamic_tool_filtering() -> dict[str, Any]:
    @tool
    def search_course(keyword: str) -> str:
        """查询模拟课程。"""
        return f"查询:{keyword}"

    @tool
    def delete_course(course_id: str, runtime: ToolRuntime[AdminUserContext]) -> str:
        """带执行层鉴权的模拟删除工具。"""
        if not runtime.context.is_admin:
            return "拒绝:无管理员权限"
        return f"模拟删除:{course_id}"

    @wrap_model_call
    def select_tools(request: ModelRequest[AdminUserContext], handler: Any) -> Any:
        if request.runtime.context.is_admin:
            return handler(request)
        allowed = [t for t in request.tools if getattr(t, "name", "") != "delete_course"]
        return handler(request.override(tools=allowed))

    m = ScriptedChatModel(responses=[AIMessage(content="普通用户回答"), AIMessage(content="管理员回答")])
    ag = create_agent(
        model=m,
        tools=[search_course, delete_course],
        context_schema=AdminUserContext,
        middleware=[select_tools],
    )
    ag.invoke({"messages": [{"role": "user", "content": "查课程"}]}, context=AdminUserContext(is_admin=False))
    ag.invoke({"messages": [{"role": "user", "content": "删课程"}]}, context=AdminUserContext(is_admin=True))

    actual = {
        "guest_visible_tools": m.seen_bound_tools[0],
        "admin_visible_tools": m.seen_bound_tools[1],
    }
    expected = {
        "guest_visible_tools": ["search_course"],
        "admin_visible_tools": ["search_course", "delete_course"],
    }
    return {
        "name": "middleware_dynamic_tool_filtering",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_parallel_async_subagents_and_shared_store() -> dict[str, Any]:
    shared_store = InMemoryStore()
    shared_store.put(("users", "u-100"), "profile", {"level": "入门", "lang": "Python"})

    @tool
    def read_profile(runtime: ToolRuntime[StoreUserContext]) -> str:
        """读取跨 Agent 共享的用户长期配置。"""
        item = runtime.store.get(("users", runtime.context.user_id), "profile")
        return f"{item.value['lang']}/{item.value['level']}" if item else "none"

    ag1 = create_agent(
        model=ScriptedChatModel(
            responses=[
                AIMessage(content="", tool_calls=[{"name": "read_profile", "args": {}, "id": "tc_p1", "type": "tool_call"}]),
                AIMessage(content="课程专家:Python 入门路径"),
            ]
        ),
        tools=[read_profile],
        store=shared_store,
        context_schema=StoreUserContext,
        name="course_async",
    )
    ag2 = create_agent(
        model=ScriptedChatModel(
            responses=[
                AIMessage(content="", tool_calls=[{"name": "read_profile", "args": {}, "id": "tc_p2", "type": "tool_call"}]),
                AIMessage(content="规划专家:按 Python 入门安排周计划"),
            ]
        ),
        tools=[read_profile],
        store=shared_store,
        context_schema=StoreUserContext,
        name="planner_async",
    )

    async def run_parallel() -> list[str]:
        ctx = StoreUserContext(user_id="u-100")
        r1, r2 = await asyncio.gather(
            ag1.ainvoke({"messages": [{"role": "user", "content": "查课程"}]}, context=ctx),
            ag2.ainvoke({"messages": [{"role": "user", "content": "做计划"}]}, context=ctx),
        )
        return [
            next(x.content for x in r1["messages"] if x.type == "tool"),
            next(x.content for x in r2["messages"] if x.type == "tool"),
            str(r1["messages"][-1].content),
            str(r2["messages"][-1].content),
        ]

    res_list = asyncio.run(run_parallel())
    actual = {
        "shared_store_reads": res_list[:2],
        "parallel_replies": res_list[2:],
    }
    expected = {
        "shared_store_reads": ["Python/入门", "Python/入门"],
        "parallel_replies": ["课程专家:Python 入门路径", "规划专家:按 Python 入门安排周计划"],
    }
    return {
        "name": "parallel_async_subagents_and_shared_store",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main() -> None:
    cases = [
        case_subagents_supervisor_and_context_isolation(),
        case_router_pydantic_dispatch(),
        case_sequential_workflow_and_handoffs_state_graph(),
        case_middleware_dynamic_tool_filtering(),
        case_parallel_async_subagents_and_shared_store(),
    ]
    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-multi-agent-lab/explore-multi-agent.py

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

下载课程关联工程包:LangChain

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

下载课程关联工程包:LangChain

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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