上下文¶
“上下文工程”(Context engineering)是构建动态系统的实践,这些系统以正确的格式向 AI 应用提供正确的信息与工具,从而使其能够完成任务。上下文可从两个关键维度来刻画:
- 按照“可变性”:
- “静态上下文”:在执行期间不变的不可变数据(如:用户元数据、数据库连接、工具)
- “动态上下文”:随应用运行而演化的可变数据(如:对话历史、 中间结果、工具调用观测)
- 按照“生命周期”:
- “运行时上下文”:作用域限定在单次运行或调用
- “跨会话上下文”:跨多次对话或会话持久存在的数据
运行时上下文 vs LLM 上下文
运行时上下文指的是本地上下文:你的代码在运行时所需的数据与依赖。它不指:
- LLM 上下文,即传入 LLM 提示词中的数据。
- “上下文窗口”,即可传入 LLM 的最大 token 数。
运行时上下文可用于优化 LLM 上下文。例如,你可以在运行时上下文中使用用户元数据来获取用户偏好,并将其注入上下文窗口。
LangGraph 提供三种管理上下文的方式,结合了可变性与生命周期这两个维度:
上下文类型 | 描述 | 可变性 | 生命周期 | 访问方式 |
---|---|---|---|---|
静态运行时上下文 | 启动时传入的用户元数据、工具、数据库连接 | 静态 | 单次运行 | 传递给 invoke /stream 的 context 参数 |
动态运行时上下文(state) | 在单次运行中不断演化的可变数据 | 动态 | 单次运行 | LangGraph 状态对象 |
动态跨会话上下文(store) | 跨会话共享的持久化数据 | 动态 | 跨会话 | LangGraph 存储 |
静态运行时上下文¶
“静态运行时上下文”表示在运行开始时通过 invoke
/stream
的 context
参数传给应用的不可变数据,如用户元数据、工具和数据库连接。这些数据在执行过程中不会改变。
LangGraph v0.6 新增:context
替代 config['configurable']
运行时上下文现在通过 invoke
/stream
的 context
参数传递,
取代了此前将应用配置传入 config['configurable']
的模式。
@dataclass
class ContextSchema:
user_name: str
graph.invoke( # (1)!
{"messages": [{"role": "user", "content": "hi!"}]}, # (2)!
context={"user_name": "John Smith"} # (3)!
)
- 这是对代理或图的调用。
invoke
方法会用提供的输入运行底层图。 - 此示例使用消息作为输入,这很常见,但你的应用可能使用不同的输入结构。
- 这里传入运行时数据。
context
参数允许你提供代理在执行期间可使用的附加依赖。
from langchain_core.messages import AnyMessage
from langgraph.runtime import get_runtime
from langgraph.prebuilt.chat_agent_executor import AgentState
from langgraph.prebuilt import create_react_agent
def prompt(state: AgentState) -> list[AnyMessage]:
runtime = get_runtime(ContextSchema)
system_msg = f"You are a helpful assistant. Address the user as {runtime.context.user_name}."
return [{"role": "system", "content": system_msg}] + state["messages"]
agent = create_react_agent(
model="anthropic:claude-3-7-sonnet-latest",
tools=[get_weather],
prompt=prompt,
context_schema=ContextSchema
)
agent.invoke(
{"messages": [{"role": "user", "content": "what is the weather in sf"}]},
context={"user_name": "John Smith"}
)
- 参见 代理 了解详情。
from langgraph.runtime import Runtime
def node(state: State, config: Runtime[ContextSchema]):
user_name = runtime.context.user_name
...
- 参见 Graph API 了解详情。
from langgraph.runtime import get_runtime
@tool
def get_user_email() -> str:
"""Retrieve user information based on user ID."""
# simulate fetching user info from a database
runtime = get_runtime(ContextSchema)
email = get_user_email_from_db(runtime.context.user_name)
return email
参见 工具调用指南 了解详情。
Tip
Runtime
对象可用于访问静态上下文,以及活跃的 store、流写入器等其他实用工具。
请参阅 Runtime 文档获取详情。
动态运行时上下文(state)¶
“动态运行时上下文”表示在单次运行过程中可演化的可变数据,通过 LangGraph 的状态对象进行管理。这包括对话历史、中间结果,以及由工具或 LLM 输出派生的值。在 LangGraph 中,状态对象在一次运行期间充当短期记忆。
以下示例展示如何在代理“提示词”中纳入 state。
代理的“工具”也可以访问 state,并按需读取或更新。参见工具调用指南了解详情。
from langchain_core.messages import AnyMessage
from langchain_core.runnables import RunnableConfig
from langgraph.prebuilt import create_react_agent
from langgraph.prebuilt.chat_agent_executor import AgentState
class CustomState(AgentState): # (1)!
user_name: str
def prompt(
state: CustomState
) -> list[AnyMessage]:
user_name = state["user_name"]
system_msg = f"You are a helpful assistant. User's name is {user_name}"
return [{"role": "system", "content": system_msg}] + state["messages"]
agent = create_react_agent(
model="anthropic:claude-3-7-sonnet-latest",
tools=[...],
state_schema=CustomState, # (2)!
prompt=prompt
)
agent.invoke({
"messages": "hi!",
"user_name": "John Smith"
})
- 定义一个自定义 state 模式,扩展自
AgentState
或MessagesState
。 - 将自定义 state 模式传给代理。这允许代理在执行期间访问并修改 state。
from typing_extensions import TypedDict
from langchain_core.messages import AnyMessage
from langgraph.graph import StateGraph
class CustomState(TypedDict): # (1)!
messages: list[AnyMessage]
extra_field: int
def node(state: CustomState): # (2)!
messages = state["messages"]
...
return { # (3)!
"extra_field": state["extra_field"] + 1
}
builder = StateGraph(State)
builder.add_node(node)
builder.set_entry_point("node")
graph = builder.compile()
- 定义自定义 state
- 在任意节点或工具中访问 state
- Graph API 设计为尽可能方便地与 state 协作。节点的返回值表示对 state 的请求更新。
开启记忆
请参阅记忆指南了解如何启用记忆功能。这是一个强大的功能,允许你在多次调用之间持久化代理的状态。否则,state 仅在单次运行内生效。
动态跨会话上下文(store)¶
“动态跨会话上下文”表示跨多个对话或会话的持久、可变数据,通过 LangGraph 的 store 进行管理。这包括用户画像、偏好和历史交互。LangGraph 的 store 在多次运行之间充当长期记忆。它可用于读取或更新持久化事实(如用户画像、偏好、先前交互)。
欲了解更多信息,参见记忆指南。