LangChain 的 create_agent 底层运行在 LangGraph 的运行时之上。
LangGraph 暴露了一个 Runtime 对象,包含以下信息:
Context(上下文) :静态信息,如用户 ID、数据库连接或智能体调用的其他依赖项
Store(存储) :用于长期记忆 的 BaseStore 实例
Stream writer(流写入器) :通过 "custom" 流模式进行信息流式传输的对象
运行时上下文为你的工具和中间件提供依赖注入 。与其硬编码值或使用全局状态,你可以在调用智能体时注入运行时依赖项(如数据库连接、用户 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 参数访问 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" )
)
将这些文档连接 到 Claude、VSCode 等,通过 MCP 获取实时答案。