[langchain 内部数据传递层级]

@dynamic_prompt
def dynamic_system_prompt(request: ModelRequest) -> str:
    user_name = request.runtime.context.user_name  
    system_prompt = f"You are a helpful assistant. Address the user as {user_name}."
    return system_prompt

官方 ⬆️

是的,完全正确!你的理解非常精准。

不同的函数(或装饰器)就像是系统中的不同职能部门,它们根据自己的职责,在数据结构树的不同层级进行介入和操作。

我们可以这样对应:

  1. @dynamic_prompt (总控层 - Request 级)

    • 介入层级request (最顶层)。
    • 原因:它不仅需要读数据(Runtime),还需要读/改当前的输入消息(Request.messages)来构造 Prompt。它需要看到“全貌”。
  2. @before_model / Tools (执行层 - Runtime 级)

    • 介入层级runtime (中间层)。
    • 原因:它不需要关心“这一次请求的消息是什么”,它只关心“我有多少资源可以用”(比如读写数据库 store、流式输出 stream_writer)。
  3. 业务逻辑 / 简单工具 (业务层 - Context 级)

    • 介入层级context (最底层)。
    • 原因:绝大多数简单的业务代码(比如你的 weather01.py)根本不关心数据库连接或流式写入器,它只关心“当前用户是谁 (user_id)”或者“当前偏好是什么”。

总结图示

Request (ModelRequest)  <-- @dynamic_prompt 在这里介入 (我要看全局,还要改消息)
 └── runtime (Runtime)  <-- @before_model / Tools 在这里介入 (我要用资源,存数据库)
     └── context        <-- 普通业务逻辑 在这里介入 (我只要知道用户是谁)

这就是为什么你会看到参数类型不一样,因为它们是在不同层级上工作的。这种设计让底层的业务代码保持干净(只依赖 Context),而上层的框架代码拥有更多权限(依赖 Runtime 或 Request)。

runtime 测试

from typing import Any
from langgraph.store.memory import InMemoryStore
from langchain.agents import create_agent
from langchain.tools import tool, ToolRuntime
from model_glm import model




@tool
def test_runtime(runtime: ToolRuntime) -> str:
    """Test runtime.看一下 runtime 下面有啥"""
    print(f"====> runtime type: {type(runtime)}")
    
    # 检测是否为 Pydantic 模型
    if hasattr(runtime, "model_dump"):
        print("---》It's a Pydantic v2 Model!")
    elif hasattr(runtime, "dict"):
        print("---》It's a Pydantic v1 Model!")
    
    # 检测是否为 Dataclass
    from dataclasses import is_dataclass, asdict
    if is_dataclass(runtime):
        print("---》It's a Dataclass!")
      # 转为字典以便遍历或序列化
    runtime_dict = vars(runtime)
             
    for key, value in runtime_dict.items():
        print(f"{key}")
    # print(f"====> runtime: {runtime}")
    return str(runtime)


agent = create_agent(
    model,
    tools=[test_runtime],
    system_prompt="你是一个测试用的智能体, 需要调用 test_runtime 工具",
)

agent.invoke({
    "messages": [{"role": "user", "content": "测试一下 test_runtime"}]
})
====> runtime type: <class 'langgraph.prebuilt.tool_node.ToolRuntime'>
---》It's a Dataclass!
state
context
config
stream_writer
tool_call_id
store
(langchain_py312) 
posted @ 2026-01-21 23:42  十三山入秋  阅读(1)  评论(1)    收藏  举报