上下文工程 是构建动态系统的实践,这些系统以正确的格式提供正确的信息和工具,使 AI 应用程序能够完成任务。上下文可以沿两个关键维度进行表征:
1. By **可变性**: * **静态上下文**:在执行期间不会改变的不可变数据(例如,用户元数据、数据库连接、工具) * **动态上下文**:随应用程序运行而演变的可变数据(例如,对话历史、中间结果、工具调用观察) 2. By **生命周期**: * **运行时上下文**:限定于单次运行或调用的数据 * **跨对话上下文**:在多个对话或会话之间持续存在的数据
LangGraph 提供了三种管理上下文的方式,这些方式结合了可变性和生命周期的维度:
| 上下文类型 | 描述 | 可变性 | 生命周期 | 访问方法 |
|---|---|---|---|---|
| **静态运行时上下文** | 启动时传递的用户元数据、工具、数据库连接 | 静态 | 单次运行 | context 的实参 invoke/stream |
| **动态运行时上下文(状态)** | 在单次运行期间演变的可变数据 | 动态 | 单次运行 | LangGraph 状态对象 |
| **动态跨对话上下文(存储)** | 跨对话共享的持久数据 | 动态 | 跨对话 | LangGraph 存储 |
静态运行时上下文
静态运行时上下文 表示不可变数据,如用户元数据、工具和数据库连接,这些数据在运行时开始时通过 context 的实参传递给应用程序 invoke/stream。此数据在执行期间不会改变。
@dataclass
class ContextSchema:
user_name: str
graph.invoke(
{"messages": [{"role": "user", "content": "hi!"}]},
context={"user_name": "John Smith"} # [!code highlight]
)
Agent prompt
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 # [!code highlight]
def personalized_prompt(request: ModelRequest) -> str: # [!code highlight]
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-6",
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") # [!code highlight]
)
详见 代理 。
Workflow node
from langgraph.runtime import Runtime
def node(state: State, runtime: Runtime[ContextSchema]): # [!code highlight]
user_name = runtime.context.user_name
...
* 详见 Graph API 详见。
In a tool
from langchain.tools import tool, ToolRuntime
@tool
def get_user_email(runtime: ToolRuntime[ContextSchema]) -> str:
"""Retrieve user information based on user ID."""
# simulate fetching user info from a database
email = get_user_email_from_db(runtime.context.user_name) # [!code highlight]
return email
请参阅 工具调用指南 了解更多详情。
动态运行时上下文
动态运行时上下文 表示在单次运行中可变化的mutable数据,通过 LangGraph 状态对象进行管理。这包括对话历史、中间结果以及从工具或 LLM 输出中获取的值。在 LangGraph 中,状态对象充当运行期间的 短期记忆 。
In an agent
示例展示了如何将状态整合到智能体的 **提示词**.
中。状态也可以由智能体的 **工具**访问,这些工具可以根据需要读取或更新状态。请参阅 工具调用指南 了解更多详情。
from langchain.agents import create_agent
from langchain.agents.middleware import dynamic_prompt, ModelRequest
from langchain.agents import AgentState
class CustomState(AgentState): # [!code highlight]
user_name: str
@dynamic_prompt # [!code highlight]
def personalized_prompt(request: ModelRequest) -> str: # [!code highlight]
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-6",
tools=[...],
state_schema=CustomState, # [!code highlight]
middleware=[personalized_prompt], # [!code highlight]
)
agent.invoke({
"messages": "hi!",
"user_name": "John Smith"
})
In a workflow
from typing_extensions import TypedDict
from langchain.messages import AnyMessage
from langgraph.graph import StateGraph
class CustomState(TypedDict): # [!code highlight]
messages: list[AnyMessage]
extra_field: int
def node(state: CustomState): # [!code highlight]
messages = state["messages"]
...
return { # [!code highlight]
"extra_field": state["extra_field"] + 1 # [!code highlight]
}
builder = StateGraph(State)
builder.add_node(node)
builder.set_entry_point("node")
graph = builder.compile()
动态跨对话上下文
动态跨对话上下文 表示跨多个对话或会话持久存在、可变化的数据,通过 LangGraph 存储进行管理。这包括用户画像、偏好设置和历史交互记录。LangGraph 存储充当 长期记忆 跨多次运行。这可用于读取或更新持久化事实(例如,用户档案、偏好设置、先前交互)。