上下文工程(Context Engineering)对于 Agent 得出正确的结果至关重要。模型回答不好,很多时候不是因为能力不足,而是因为没有获得足以推断出正确结果的上下文信息。通过上下文工程,增强 Agent 获取和管理上下文的能力,是很有必要的。
LangGraph 将上下文分为三种类型:
模型上下文(Model Context)
工具上下文(Tool Context)
生命周期上下文(Life-cycle Context)
无论哪种 Context,都需要定义它的 Schema。在这方面,LangGraph 提供了相当高的自由度,你可以使用 dataclasses、pydantic、TypedDict 这些包的任意一个创建你的 Context Schema.
# !pip install ipynbnameimport os
import uuid
import sqlite3
from typing import Callable
from dotenv import load_dotenv
from dataclasses import dataclass
from langchain_openai import ChatOpenAI
from langchain.tools import tool, ToolRuntime
from langchain.agents import create_agent
from langchain.agents.middleware import dynamic_prompt, wrap_model_call, ModelRequest, ModelResponse, SummarizationMiddleware
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.store.memory import InMemoryStore
from langgraph.store.sqlite import SqliteStore
# 加载模型配置
_ = load_dotenv()
# 加载模型
llm = ChatOpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url=os.getenv("DASHSCOPE_BASE_URL"),
model="qwen3-coder-plus",
temperature=0.7,
)一、动态修改系统提示词¶
上下文工程与前序章节的中间件(middleware)和记忆(memory)密不可分。上下文的具体实现依赖中间件,而上下文的存储则依赖记忆系统。具体来讲,LangGraph 预置了 @dynamic_prompt 中间件,用于动态修改系统提示词。
既然是动态修改,肯定需要某个条件来触发修改。除了开发触发逻辑,我们还需要从智能体中获取触发逻辑所需的即时变量。这些变量通常存储在以下三个存储介质中:
运行时(Runtime)- 所有节点共享一个 Runtime。同一时刻,所有节点取到的 Runtime 的值是相同的。一般用于存储时效性要求较高的信息。
短期记忆(State)- 在节点之间按顺序传递,每个节点接收上一个节点处理后的 State。主要用于存储 Prompt 和 AI Message。
长期记忆(Store)- 负责持久化存储,可以跨 Workflow / Agent 保存信息。可以用来存用户偏好、以前算过的统计值等。
以下三个例子,分别演示如何使用来自 Runtime、State、Store 中的上下文,编写触发条件。
1)使用 State 加载上下文¶
利用 State 中蕴含的信息操纵 system prompt.
@dynamic_prompt
def state_aware_prompt(request: ModelRequest) -> str:
# request.messages is a shortcut for request.state["messages"]
message_count = len(request.messages)
base = "You are a helpful assistant."
if message_count > 6:
base += "\nThis is a long conversation - be extra concise."
# 临时打印base看效果
print(base)
return base
agent = create_agent(
model=llm,
middleware=[state_aware_prompt]
)
result = agent.invoke(
{"messages": [
{"role": "user", "content": "广州今天的天气怎么样?"},
{"role": "assistant", "content": "广州天气很好"},
{"role": "user", "content": "吃点什么好呢"},
{"role": "assistant", "content": "要不要吃香茅鳗鱼煲"},
{"role": "user", "content": "香茅是什么"},
{"role": "assistant", "content": "香茅又名柠檬草,常见于泰式冬阴功汤、越南烤肉"},
{"role": "user", "content": "auv 那还等什么,咱吃去吧"},
]},
)
for message in result['messages']:
message.pretty_print()You are a helpful assistant.
This is a long conversation - be extra concise.
================================ Human Message =================================
广州今天的天气怎么样?
================================== Ai Message ==================================
广州天气很好
================================ Human Message =================================
吃点什么好呢
================================== Ai Message ==================================
要不要吃香茅鳗鱼煲
================================ Human Message =================================
香茅是什么
================================== Ai Message ==================================
香茅又名柠檬草,常见于泰式冬阴功汤、越南烤肉
================================ Human Message =================================
auv 那还等什么,咱吃去吧
================================== Ai Message ==================================
好主意!香茅鳗鱼煲听起来很美味,走吧!
把 message_count > 6 里的 6 改成 7,试试看会发生什么。
2)使用 Store 加载上下文¶
@dataclass
class Context:
user_id: str
@dynamic_prompt
def store_aware_prompt(request: ModelRequest) -> str:
user_id = request.runtime.context.user_id
# Read from Store: get user preferences
store = request.runtime.store
user_prefs = store.get(("preferences",), user_id)
base = "You are a helpful assistant."
if user_prefs:
style = user_prefs.value.get("communication_style", "balanced")
base += f"\nUser prefers {style} responses."
return base
store = InMemoryStore()
agent = create_agent(
model=llm,
middleware=[store_aware_prompt],
context_schema=Context,
store=store,
)
# 预置两条偏好信息
store.put(("preferences",), "user_1", {"communication_style": "Chinese"})
store.put(("preferences",), "user_2", {"communication_style": "Korean"})# 用户1喜欢中文回复
result = agent.invoke(
{"messages": [
{"role": "system", "content": "You are a helpful assistant. Please be extra concise."},
{"role": "user", "content": 'What is a "hold short line"?'}
]},
context=Context(user_id="user_1"),
)
for message in result['messages']:
message.pretty_print()================================ System Message ================================
You are a helpful assistant. Please be extra concise.
================================ Human Message =================================
What is a "hold short line"?
================================== Ai Message ==================================
"Hold short line" 是航空术语,指跑道或滑行道上的一条标记线,要求飞机在此线前停止,不得越过。通常用于:
1. **跑道等待线** - 等待起飞许可
2. **滑行道等待线** - 等待进入跑道或其他区域
这是飞行安全的重要程序。
# 用户2喜欢韩文回复
result = agent.invoke(
{"messages": [
{"role": "system", "content": "You are a helpful assistant. Please be extra concise."},
{"role": "user", "content": 'What is a "hold short line"?'}
]},
context=Context(user_id="user_2"),
)
for message in result['messages']:
message.pretty_print()================================ System Message ================================
You are a helpful assistant. Please be extra concise.
================================ Human Message =================================
What is a "hold short line"?
================================== Ai Message ==================================
"홀드 쇼트 라인(Hold Short Line)"은 공항 활주로에서 항공기가 특정 지점까지만 진입하도록 지시하는 선입니다. 이 선을 넘어서는 것은 금지되어 있으며, 관제소의 허가를 받아야만 진입할 수 있습니다. 주로 활주로와 교차하는 지점이나 활주로 진입 전에 설치되어 안전을 확보합니다.
3)使用 Runtime 加载上下文¶
@dataclass
class Context:
user_role: str
deployment_env: str
@dynamic_prompt
def context_aware_prompt(request: ModelRequest) -> str:
# Read from Runtime Context: user role and environment
user_role = request.runtime.context.user_role
env = request.runtime.context.deployment_env
base = "You are a helpful assistant."
if user_role == "admin":
base += "\nYou can use the get_weather tool."
else:
base += "\nYou are prohibited from using the get_weather tool."
if env == "production":
base += "\nBe extra careful with any data modifications."
return base
@tool
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
agent = create_agent(
model=llm,
tools=[get_weather],
middleware=[context_aware_prompt],
context_schema=Context,
checkpointer=InMemorySaver(),
)# 利用 Runtime 中的两个变量,动态控制 System prompt
# 将 user_role 设为 admin,允许使用天气查询工具
config = {'configurable': {'thread_id': str(uuid.uuid4())}}
result = agent.invoke(
{"messages": [{"role": "user", "content": "广州今天的天气怎么样?"}]},
context=Context(user_role="admin", deployment_env="production"),
config=config,
)
for message in result['messages']:
message.pretty_print()================================ Human Message =================================
广州今天的天气怎么样?
================================== Ai Message ==================================
Tool Calls:
get_weather (call_b7a1beefd02f4703a3d0caaa)
Call ID: call_b7a1beefd02f4703a3d0caaa
Args:
city: 广州
================================= Tool Message =================================
Name: get_weather
It's always sunny in 广州!
================================== Ai Message ==================================
根据我获取的信息,广州今天是晴天!气温适宜,阳光明媚。如果你在广州,记得做好防晒措施,享受美好的一天!
# 若将 user_role 改为 viewer,则无法使用天气查询工具
config = {'configurable': {'thread_id': str(uuid.uuid4())}}
result = agent.invoke(
{"messages": [{"role": "user", "content": "广州今天的天气怎么样?"}]},
context=Context(user_role="viewer", deployment_env="production"),
config=config,
)
for message in result['messages']:
message.pretty_print()================================ Human Message =================================
广州今天的天气怎么样?
================================== Ai Message ==================================
抱歉,我无法获取天气信息。您可以通过其他途径查询广州今天的天气,例如使用天气应用或访问天气网站。
result['messages'][HumanMessage(content='广州今天的天气怎么样?', additional_kwargs={}, response_metadata={}, id='58493935-80a8-4f05-818d-4fa3ef684657'),
AIMessage(content='抱歉,我无法获取天气信息。您可以通过其他途径查询广州今天的天气,例如使用天气应用或访问天气网站。', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 26, 'prompt_tokens': 287, 'total_tokens': 313, 'completion_tokens_details': None, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0}}, 'model_provider': 'openai', 'model_name': 'qwen3-coder-plus', 'system_fingerprint': None, 'id': 'chatcmpl-b3da39f7-8f49-4a63-9794-06bd7578354f', 'finish_reason': 'stop', 'logprobs': None}, id='lc_run--5c17667c-38c3-4856-9610-9d6f4cfd4d16-0', usage_metadata={'input_tokens': 287, 'output_tokens': 26, 'total_tokens': 313, 'input_token_details': {'cache_read': 0}, 'output_token_details': {}})]二、动态修改消息列表¶
LangGraph 预制了动态修改消息列表(Messages)的中间件 @wrap_model_call。上一节已经演示如何从 State、Store、Runtime 中获取上下文,本节将不再一一演示。在下面这个例子中,我们主要演示如何使用 Runtime 将本地文件的内容注入消息列表。
@dataclass
class FileContext:
uploaded_files: list[dict]
@wrap_model_call
def inject_file_context(
request: ModelRequest,
handler: Callable[[ModelRequest], ModelResponse]
) -> ModelResponse:
"""Inject context about files user has uploaded this session."""
uploaded_files = request.runtime.context.uploaded_files
try:
base_dir = os.path.dirname(os.path.abspath(__file__))
except Exception as e:
import ipynbname
import os
notebook_path = ipynbname.path()
base_dir = os.path.dirname(notebook_path)
file_sections = []
for file in uploaded_files:
name, ftype = "", ""
path = file.get("path")
if path:
base_filename = os.path.basename(path)
stem, ext = os.path.splitext(base_filename)
name = stem or base_filename
ftype = (ext.lstrip(".") if ext else None)
# 构建文件描述内容
content_list = [f"名称: {name}"]
if ftype:
content_list.append(f"类型: {ftype}")
# 解析相对路径为绝对路径
abs_path = path if os.path.isabs(path) else os.path.join(base_dir, path)
# 读取文件内容
content_block = ""
if abs_path and os.path.exists(abs_path):
try:
with open(abs_path, "r", encoding="utf-8") as f:
content_block = f.read()
except Exception as e:
content_block = f"[读取文件错误 '{abs_path}': {e}]"
else:
content_block = "[文件路径缺失或未找到]"
section = (
f"---\n"
f"{chr(10).join(content_list)}\n\n"
f"{content_block}\n"
f"---"
)
file_sections.append(section)
file_context = (
"已加载的会话文件:\n"
f"{chr(10).join(file_sections)}"
"\n回答问题时请参考这些文件。"
)
# Inject file context before recent messages
messages = [
*request.messages,
{"role": "user", "content": file_context},
]
request = request.override(messages=messages)
return handler(request)
agent = create_agent(
model=llm,
middleware=[inject_file_context],
context_schema=FileContext,
)result = agent.invoke(
{
"messages": [{
"role": "user",
"content": "关于上海地铁的无脸乘客,有什么需要注意的?",
}],
},
context=FileContext(uploaded_files=[{"path": "./docs/rule_horror.md"}]),
)
for message in result['messages']:
message.pretty_print()================================ Human Message =================================
关于上海地铁的无脸乘客,有什么需要注意的?
================================== Ai Message ==================================
根据《上海规则怪谈》中的描述,关于上海地铁的“无脸乘客”,你需要特别注意以下几点:
---
### 🚇 **地铁上的陌生人(无脸乘客)规则:**
> **“地铁运营结束后,若你仍身处车厢内,会出现一位无脸乘客。他会低声问:‘你要去哪?’只能报一个真实存在的上海地名。说出不存在的地名或保持沉默,你会在车厢内看到自己的尸体。”**
---
### ⚠️ 注意事项:
1. **时间点:**
该现象发生在**地铁运营结束之后**,如果你因某种原因滞留在地铁车厢内,请提高警惕。
2. **无脸乘客的出现:**
他会主动靠近你,并低声询问:“**你要去哪?**”
3. **正确应对方式:**
- 必须回答一个**真实存在于上海的地名**,例如“人民广场”、“徐家汇”、“陆家嘴”等。
- 回答要清晰、准确,不能犹豫或说错。
4. **错误行为及后果:**
- 若你回答一个**不存在的地名**(如“新宿”、“王府井”),或**保持沉默**,你将会在车厢中看到**自己的尸体**。
- 这意味着你将无法逃脱死亡的命运。
---
### 🧠 小贴士:
- 如果你不确定某个地名是否属于上海,建议提前了解一些真实地名以防万一。
- 若真的遭遇此情景,保持冷静,迅速回忆一个确切的上海地名作答。
- 切勿试图欺骗、开玩笑或沉默不语。
---
**记住:规则是生存的底线,违者——后果自负。**
三、在工具中使用上下文¶
下面,我们尝试在工具中使用存储在 SqliteStore 中的上下文信息。
# 删除SQLite数据库
if os.path.exists("user-info.db"):
os.remove("user-info.db")
# 创建SQLite存储
conn = sqlite3.connect("user-info.db", check_same_thread=False, isolation_level=None)
conn.execute("PRAGMA journal_mode=WAL;")
conn.execute("PRAGMA busy_timeout = 30000;")
store = SqliteStore(conn)
# 预置两条用户信息
store.put(("user_info",), "柳如烟", {"description": "清冷才女,身怀绝技,为寻身世之谜踏入江湖。", "birthplace": "吴兴县"})
store.put(("user_info",), "苏慕白", {"description": "孤傲剑客,剑法超群,背负家族血仇,隐于市井追寻真相。", "birthplace": "杭县"})1)基础用例¶
使用 ToolRuntime
@tool
def fetch_user_data(
user_id: str,
runtime: ToolRuntime
) -> str:
"""
Fetch user information from the in-memory store.
:param user_id: The unique identifier of the user.
:param runtime: The tool runtime context injected by the framework.
:return: The user's description string if found; an empty string otherwise.
"""
store = runtime.store
user_info = store.get(("user_info",), user_id)
user_desc = ""
if user_info:
user_desc = user_info.value.get("description", "")
return user_desc
agent = create_agent(
model=llm,
tools=[fetch_user_data],
store=store,
)result = agent.invoke({
"messages": [{
"role": "user",
"content": "五分钟之内,我要柳如烟的全部信息"
}]
})
for message in result['messages']:
message.pretty_print()================================ Human Message =================================
五分钟之内,我要柳如烟的全部信息
================================== Ai Message ==================================
Tool Calls:
fetch_user_data (call_bb5059c893d74cebac0f7727)
Call ID: call_bb5059c893d74cebac0f7727
Args:
user_id: 柳如烟
================================= Tool Message =================================
Name: fetch_user_data
清冷才女,身怀绝技,为寻身世之谜踏入江湖。
================================== Ai Message ==================================
根据我目前掌握的信息,柳如烟是一位清冷才女,身怀绝技,为了探寻自己的身世之谜而踏入江湖。不过,这仅仅是她的一部分信息,更多详细资料可能需要进一步调查才能获得。你对她有什么特别的兴趣或目的吗?或许我可以帮你了解更多。
2)复杂一点的例子¶
使用 ToolRuntime[Context]
@dataclass
class Context:
key: str
@tool
def fetch_user_data(
user_id: str,
runtime: ToolRuntime[Context]
) -> str:
"""
Fetch user information from the in-memory store.
:param user_id: The unique identifier of the user.
:param runtime: The tool runtime context injected by the framework.
:return: The user's description string if found; an empty string otherwise.
"""
key = runtime.context.key
store = runtime.store
user_info = store.get(("user_info",), user_id)
user_desc = ""
if user_info:
user_desc = user_info.value.get(key, "")
return f"{key}: {user_desc}"
agent = create_agent(
model=llm,
tools=[fetch_user_data],
store=store,
)result = agent.invoke(
{"messages": [{"role": "user", "content": "五分钟之内,我要柳如烟的全部信息"}]},
context=Context(key="birthplace"),
)
for message in result['messages']:
message.pretty_print()================================ Human Message =================================
五分钟之内,我要柳如烟的全部信息
================================== Ai Message ==================================
Tool Calls:
fetch_user_data (call_5373b11fd735425990cc9748)
Call ID: call_5373b11fd735425990cc9748
Args:
user_id: 柳如烟
================================= Tool Message =================================
Name: fetch_user_data
birthplace: 吴兴县
================================== Ai Message ==================================
柳如烟的基本信息如下:
- **出生地**:吴兴县
由于时间限制,目前仅获取到以上信息。如需更详细的资料,请提供更多线索或延长查询时间。
四、压缩上下文¶
LangChain 提供了内置的中间件 SummarizationMiddleware 用于压缩上下文。该中间件维护的是典型的 生命周期上下文,与 模型上下文 和 工具上下文 的瞬态更新不同,生命周期上下文会持续更新:持续将旧消息替换为摘要。
除非上下文超长,导致模型能力降低,否则不需要使用 SummarizationMiddleware。一般来说,触发摘要得值可以设得较大。比如:
max_tokens_before_summary: 3000messages_to_keep: 20
如果你想了解更多关于上下文腐坏(Context Rot)的信息,Chroma 团队在 2025 年 7 月 14 日发布的 Context Rot: How Increasing Input Tokens Impacts LLM Performance,系统性地揭示了长上下文导致模型性能退化的现象。
# 创建短期记忆
checkpointer = InMemorySaver()
# 创建带内置摘要中间件的Agent
# 为了让配置能在我们的例子里生效,这里的触发值设得很小
agent = create_agent(
model=llm,
middleware=[
SummarizationMiddleware(
model=llm,
max_tokens_before_summary=40, # Trigger summarization at 40 tokens
messages_to_keep=1, # Keep last 1 messages after summary
),
],
)result = agent.invoke(
{"messages": [
{"role": "user", "content": "广州今天的天气怎么样?"},
{"role": "assistant", "content": "广州天气很好"},
{"role": "user", "content": "吃点什么好呢"},
{"role": "assistant", "content": "要不要吃香茅鳗鱼煲"},
{"role": "user", "content": "香茅是什么"},
{"role": "assistant", "content": "香茅又名柠檬草,常见于泰式冬阴功汤、越南烤肉"},
{"role": "user", "content": "auv 那还等什么,咱吃去吧"},
]},
checkpointer=checkpointer,
)
for message in result['messages']:
message.pretty_print()================================ Human Message =================================
Here is a summary of the conversation to date:
广州天气很好;建议吃香茅鳗鱼煲;香茅又名柠檬草,常见于泰式冬阴功汤、越南烤肉。
================================ Human Message =================================
auv 那还等什么,咱吃去吧
================================== Ai Message ==================================
哈哈,看起来你已经迫不及待了!😄
既然广州天气这么好,香茅鳗鱼煲听起来确实是个不错的选择。你提到的香茅(柠檬草)确实是东南亚料理中的经典香料,能为鳗鱼增添独特的清香。
不过我得提醒一下,作为AI,我无法真正和你一起去吃饭。如果你真的要去品尝这道菜,记得选择食材新鲜、口碑好的餐厅哦!
你是在广州吗?还是在其他地方想尝试这道菜?