Documentation Index
Fetch the complete documentation index at: https://langchain.idochub.dev/llms.txt
Use this file to discover all available pages before exploring further.
LangChain 的 create_agent 在底层运行于 LangGraph 的运行时之上。
LangGraph 提供了一个 Runtime 对象,包含以下信息:
- 上下文(Context):静态信息,如用户 ID、数据库连接或其他用于代理调用的依赖项。
- 存储(Store):用于长期记忆的
BaseStore 实例。
- 流写入器(Stream writer):一个对象,用于通过
"custom" 流模式流式传输信息。
您可以在 工具、提示词 以及 模型前/后钩子 中访问运行时信息。
访问方式
使用 create_agent 创建代理时,您可以指定 context_schema 来定义存储在代理运行时中的 context 结构。
调用代理时,请传递 context 参数,其中包含本次运行的相关配置:
from dataclasses import dataclass
from langchain_core.messages import AnyMessage
from langchain.agents import create_agent
from langgraph.runtime import get_runtime
@dataclass
class Context:
user_name: str
agent = create_agent(
model="openai:gpt-5-nano",
tools=[...],
context_schema=Context
)
agent.invoke(
{"messages": [{"role": "user", "content": "我叫什么名字?"}]},
context=Context(user_name="John Smith")
)
在工具内部
您可以在工具内部访问运行时信息,以实现:
- 访问上下文
- 读取或写入长期记忆
- 写入 自定义流(例如,工具进度/更新)
在工具内部使用 langgraph.runtime 中的 get_runtime 函数访问 Runtime 对象。
from typing import Any
from langchain_core.tools import tool
@tool
def fetch_user_email_preferences() -> str:
runtime = get_runtime(Context)
user_id = runtime.context.user_id
preferences: str = "用户希望你写一封简洁礼貌的邮件。"
if runtime.store:
if memory := runtime.store.get(("users",), user_id):
preferences = memory.value["preferences"]
return preferences
在提示词内部
在提示词函数内部使用 langgraph.runtime 中的 get_runtime 函数访问 Runtime 对象。
from dataclasses import dataclass
from langchain_core.messages import AnyMessage
from langchain.agents import create_agent
from langgraph.runtime import get_runtime
@dataclass
class Context:
user_name: str
def my_prompt(state: State) -> list[AnyMessage]:
runtime = get_runtime(Context)
system_msg = (
"你是一个乐于助人的助手。"
f"请称呼用户为 {runtime.context.user_name}。"
)
return [{"role": "system", "content": system_msg}] + state["messages"]
agent = create_agent(
model="openai:gpt-5-nano",
tools=[...],
prompt=my_prompt,
context_schema=Context
)
agent.invoke(
{"messages": [{"role": "user", "content": "我叫什么名字?"}]},
context=Context(user_name="John Smith")
)
在模型前/后钩子内部
要在模型前/后钩子中访问底层图的运行时信息,您可以:
- 使用
langgraph.runtime 中的 get_runtime 函数在钩子内部访问 Runtime 对象。
- 通过钩子签名直接注入
Runtime 对象。
以上两种方式仅为偏好选择,功能上并无差异。
from langgraph.runtime import get_runtime
def pre_model_hook(state: State) -> State:
runtime = get_runtime(Context)
...
from langgraph.runtime import Runtime
def pre_model_hook(state: State, runtime: Runtime[Context]):
...