概览

LangChain 的 create_agent 底层运行在 LangGraph runtime 之上。 LangGraph 暴露一个 Runtime 对象,其中包含以下信息:
  1. Context:代理调用的静态信息,例如用户 ID、数据库连接或其他依赖
  2. Store:用于 long-term memoryBaseStore 实例
  3. Stream writer:用于通过 "custom" stream mode 流式传输信息的对象
  4. Execution info:当前执行的身份和重试信息(thread ID、run ID、attempt number)
  5. Server info:在 LangGraph Server 上运行时的服务器特定元数据(assistant ID、graph ID、authenticated user)
Runtime context 为你的工具和 middleware 提供依赖注入。不要硬编码值或使用全局状态,而是在调用代理时注入运行时依赖(例如数据库连接、用户 ID 或配置)。这会让你的工具更容易测试、复用且更灵活。
你可以在 toolsmiddleware 中访问 runtime 信息。

访问

使用 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")
)

在工具中

你可以在工具中访问 runtime 信息,用于:
  • 访问 context
  • 读取或写入长期记忆
  • 写入 custom stream(例如工具进度/更新)
使用 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

工具中的 execution info 和 server info

在 LangGraph Server 上运行时,通过 runtime.execution_info 访问执行身份(thread ID、run ID),并通过 runtime.server_info 访问服务器特定元数据(assistant ID、authenticated user):
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
runtime.execution_inforuntime.server_info 需要 deepagents>=0.5.0(或 langgraph>=1.1.5)。

在 middleware 中

你可以在 middleware 中访问 runtime 信息,以创建动态 prompts、修改消息,或根据用户 context 控制代理行为。 使用 Runtime 参数在 node-style hooks 中访问 Runtime 对象。对于 wrap-style hooksRuntime 对象可在 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")
)

Middleware 中的 execution info 和 server info

Middleware hooks 也可以访问 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)。