上下文工程是构建动态系统的实践,这些系统以正确的格式提供正确的信息和工具,以便 AI 应用程序可以完成任务。上下文可以沿两个关键维度表征:
- 按可变性:
- 静态上下文:在执行期间不会更改的不可变数据(例如,用户元数据、数据库连接、工具)
- 动态上下文:随着应用程序运行而演变的可变数据(例如,对话历史、中间结果、工具调用观察)
- 按生命周期:
- 运行时上下文:范围限定为单次运行或调用的数据
- 跨对话上下文:跨多个对话或会话持久化的数据
运行时上下文指的是本地上下文:您的代码运行所需的数据和依赖项。它不指:
- LLM 上下文,即传递到 LLM 提示中的数据。
- “上下文窗口”,即可以传递给 LLM 的最大令牌数。
运行时上下文可用于优化 LLM 上下文。例如,您可以在运行时上下文中使用用户元数据
来获取用户偏好并将它们馈送到上下文窗口中。
LangGraph 提供三种管理上下文的方法,结合了可变性和生命周期维度:
| 上下文类型 | 描述 | 可变性 | 生命周期 | 访问方法 |
|---|
| 静态运行时上下文 | 启动时传递的用户元数据、工具、数据库连接 | 静态 | 单次运行 | invoke/stream 的 context 参数 |
| 动态运行时上下文(状态) | 在单次运行期间演变的可变数据 | 动态 | 单次运行 | LangGraph 状态对象 |
| 动态跨对话上下文(存储) | 跨对话共享的持久数据 | 动态 | 跨对话 | LangGraph 存储 |
静态运行时上下文
静态运行时上下文表示不可变数据,如用户元数据、工具和数据库连接,这些数据通过 invoke/stream 的 context 参数在运行开始时传递给应用程序。此数据在执行期间不会更改。
@dataclass
class ContextSchema:
user_name: str
graph.invoke(
{"messages": [{"role": "user", "content": "hi!"}]},
context={"user_name": "John Smith"}
)
Agent prompt
Workflow node
In a tool
from dataclasses import dataclass
from langchain.agents import create_agent
from langchain.agents.middleware import dynamic_prompt, ModelRequest
@dataclass
class ContextSchema:
user_name: str
@dynamic_prompt
def personalized_prompt(request: ModelRequest) -> str:
user_name = request.runtime.context.user_name
return f"You are a helpful assistant. Address the user as {user_name}."
agent = create_agent(
model="claude-sonnet-4-5-20250929",
tools=[get_weather],
middleware=[personalized_prompt],
context_schema=ContextSchema
)
agent.invoke(
{"messages": [{"role": "user", "content": "what is the weather in sf"}]},
context=ContextSchema(user_name="John Smith")
)
See Agents for details.
The Runtime object can be used to access static context and other utilities like the active store and stream writer.
See the @[Runtime][langgraph.runtime.Runtime] documentation for details.
动态运行时上下文
动态运行时上下文表示可以在单次运行期间演变的可变数据,并通过 LangGraph 状态对象进行管理。这包括对话历史、中间结果以及从工具或 LLM 输出派生的值。在 LangGraph 中,状态对象在运行期间充当短期内存。
In an agent
In a workflow
示例展示如何将状态纳入智能体提示中。智能体的工具也可以访问状态,这些工具可以根据需要读取或更新状态。有关详细信息,请参阅工具调用指南。from langchain.agents import create_agent
from langchain.agents.middleware import dynamic_prompt, ModelRequest
from langchain.agents import AgentState
class CustomState(AgentState):
user_name: str
@dynamic_prompt
def personalized_prompt(request: ModelRequest) -> str:
user_name = request.state.get("user_name", "User")
return f"You are a helpful assistant. User's name is {user_name}"
agent = create_agent(
model="claude-sonnet-4-5-20250929",
tools=[...],
state_schema=CustomState,
middleware=[personalized_prompt],
)
agent.invoke({
"messages": "hi!",
"user_name": "John Smith"
})
启用内存
有关如何启用内存的更多详细信息,请参阅内存指南。这是一个强大的功能,允许您跨多个调用持久化智能体的状态。否则,状态仅范围限定为单次运行。
动态跨对话上下文
动态跨对话上下文表示跨多个对话或会话的持久、可变数据,并通过 LangGraph 存储进行管理。这包括用户配置文件、偏好和历史交互。LangGraph 存储在多次运行中充当长期内存。这可用于读取或更新持久事实(例如,用户配置文件、偏好、先前交互)。
另请参阅