幕府之争内置MOD菜单
93.28MB · 2025-11-13
LangChain的create_agent本质上运行在LangGraph的运行时(Runtime)之上。LangGraph会暴露一个包含以下信息的运行时对象(Runtime object):
你可以在工具和中间件内部访问运行时信息。
运行时上下文(Runtime Context)为工具(tools)和中间件(middleware)提供依赖注入功能。无需硬编码值或使用全局状态,你可以在调用智能体时注入运行时依赖项(如数据库连接、用户ID或配置)。这使得你的工具更易于测试、更具可复用性且灵活性更高。 使用create_agent创建智能体时,你可以指定一个context_schema(上下文模式),用于定义存储在智能体运行时(Runtime)中的上下文结构。调用智能体时,需传入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
你可以在中间件中访问运行时信息,从而根据用户上下文创建动态提示词、修改消息或控制智能体行为。
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")
)