Skip to main content

概述

LangChain 的 create_agent 在底层运行于 LangGraph 的运行时之上。 LangGraph 公开了一个 Runtime 对象,其中包含以下信息:
  1. 上下文:静态信息,如用户 ID、数据库连接或其他用于代理调用的依赖项
  2. 存储:一个 BaseStore 实例,用于长期记忆
  3. 流写入器:一个用于通过 "custom" 流模式流式传输信息的对象
  4. 执行信息:当前执行的身份和重试信息(线程 ID、运行 ID、尝试次数)
  5. 服务器信息:在 LangGraph Server 上运行时的服务器特定元数据(助手 ID、图 ID、已认证用户)
运行时上下文为您的工具和中间件提供依赖注入。您可以在调用代理时注入运行时依赖项(如数据库连接、用户 ID 或配置),而不是硬编码值或使用全局状态。这使得您的工具更易于测试、重用和灵活。
您可以在工具中间件中访问运行时信息。

访问

使用 create_agent 创建代理时,可以指定 context_schema 来定义存储在代理 Runtime 中的 context 结构。 调用代理时,传递包含相关运行配置的 context 参数:
from dataclasses import dataclass

from langchain.agents import create_agent


@dataclass
class Context:
    user_name: str

agent = create_agent(
    model="gpt-5-nano",
    tools=[...],
    context_schema=Context  
)

agent.invoke(
    {"messages": [{"role": "user", "content": "What's my name?"}]},
    context=Context(user_name="John Smith")
)

在工具内部

您可以在工具内部访问运行时信息,以:
  • 访问上下文
  • 读取或写入长期记忆
  • 写入自定义流(例如,工具进度/更新)
使用 ToolRuntime 参数在工具内部访问 Runtime 对象。
from dataclasses import dataclass
from langchain.tools import tool, ToolRuntime  

@dataclass
class Context:
    user_id: str

@tool
def fetch_user_email_preferences(runtime: ToolRuntime[Context]) -> str:
    """Fetch the user's email preferences from the store."""
    user_id = runtime.context.user_id  

    preferences: str = "The user prefers you to write a brief and polite email."
    if runtime.store:
        if memory := runtime.store.get(("users",), user_id):
            preferences = memory.value["preferences"]

    return preferences

在工具内部的执行信息和服务器信息

通过 runtime.execution_info 访问执行身份(线程 ID、运行 ID),并通过 runtime.server_info 访问服务器特定元数据(助手 ID、已认证用户),当在 LangGraph Server 上运行时:
from langchain.tools import tool, ToolRuntime

@tool
def context_aware_tool(runtime: ToolRuntime) -> str:
    """A tool that uses execution and server info."""
    # Access thread and run IDs
    info = runtime.execution_info
    print(f"Thread: {info.thread_id}, Run: {info.run_id}")

    # Access server info (only available on LangGraph Server)
    server = runtime.server_info
    if server is not None:
        print(f"Assistant: {server.assistant_id}")
        if server.user is not None:
            print(f"User: {server.user.identity}")

    return "done"
当不在 LangGraph Server 上运行时(例如,在本地开发期间),server_infoNone
需要 deepagents>=0.5.0(或 langgraph>=1.1.5)才能使用 runtime.execution_inforuntime.server_info

在中间件内部

您可以在中间件中访问运行时信息,以创建动态提示、修改消息或根据用户上下文控制代理行为。 使用 Runtime 参数在节点式钩子内部访问 Runtime 对象。对于包装式钩子Runtime 对象在 ModelRequest 参数内部可用。
from dataclasses import dataclass

from langchain.messages import AnyMessage
from langchain.agents import create_agent, AgentState
from langchain.agents.middleware import dynamic_prompt, ModelRequest, before_model, after_model
from langgraph.runtime import Runtime


@dataclass
class Context:
    user_name: str

# Dynamic prompts
@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

# Before model hook
@before_model
def log_before_model(state: AgentState, runtime: Runtime[Context]) -> dict | None:
    print(f"Processing request for user: {runtime.context.user_name}")
    return None

# After model hook
@after_model
def log_after_model(state: AgentState, runtime: Runtime[Context]) -> dict | None:
    print(f"Completed request for user: {runtime.context.user_name}")
    return None

agent = create_agent(
    model="gpt-5-nano",
    tools=[...],
    middleware=[dynamic_system_prompt, log_before_model, log_after_model],
    context_schema=Context
)

agent.invoke(
    {"messages": [{"role": "user", "content": "What's my name?"}]},
    context=Context(user_name="John Smith")
)

在中间件内部的执行信息和服务器信息

中间件钩子也可以访问 runtime.execution_inforuntime.server_info
from langchain.agents import AgentState
from langchain.agents.middleware import before_model
from langgraph.runtime import Runtime


@before_model
def auth_gate(state: AgentState, runtime: Runtime) -> dict | None:
    """Block unauthenticated users when running on LangGraph Server."""
    server = runtime.server_info
    if server is not None and server.user is None:
        raise ValueError("Authentication required")
    print(f"Thread: {runtime.execution_info.thread_id}")
    return None
需要 deepagents>=0.5.0(或 langgraph>=1.1.5)。