Skip to content

上下文工程

上下文工程是构建动态系统的实践,旨在为 AI 应用提供正确的信息和工具,并以合适的格式使其能够完成任务。上下文可以通过两个关键维度来刻画:

  1. 按可变性划分

    • 静态上下文:在运行过程中不发生变化的不可变数据(如用户元数据、数据库连接、工具)
    • 动态上下文:随着应用的运行而演变的可变数据(如对话历史、中间结果、工具调用观察)
  2. 按生命周期划分

    • 运行时上下文:作用域限于单次运行或调用的数据
    • 跨对话上下文:在多个对话或会话之间持久存在的数据

什么是运行时上下文? 运行时上下文指的是局部上下文:你的代码运行所需的数据和依赖。它不是指 LLM 上下文(传入 LLM 提示的数据)或上下文窗口(可传入 LLM 的最大 token 数量)。运行时上下文是一种依赖注入形式,用于优化 LLM 上下文。它允许你在运行时而非硬编码地提供依赖(如数据库连接、用户 ID 或 API 客户端)给工具和节点。

LangGraph 提供了三种上下文管理方式:

上下文类型描述可变性生命周期访问方式
静态运行时上下文启动时传入的用户元数据、工具、数据库连接静态单次运行context 参数传递给 invoke/stream
动态运行时上下文(状态)单次运行中演变的可变数据动态单次运行LangGraph state 对象
动态跨对话上下文(Store)跨对话共享的持久化数据动态跨对话LangGraph store

静态运行时上下文

静态运行时上下文表示在运行开始时通过 context 参数传递给应用的不可变数据,如用户元数据、工具和数据库连接。这些数据在运行过程中不会改变。

python
from dataclasses import dataclass

@dataclass
class ContextSchema:
    user_name: str

graph.invoke(
    {"messages": [{"role": "user", "content": "hi!"}]},
    context={"user_name": "John Smith"}  
)

在 Agent 中使用

python
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-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"),
)

在工具中使用

python
from langchain.tools import tool, ToolRuntime


@dataclass
class ContextSchema:
    user_name: str


@tool
def get_user_email(runtime: ToolRuntime[ContextSchema]) -> str:
    """根据用户 ID 检索用户信息。"""
    email = get_user_email_from_db(runtime.context.user_name)
    return email


agent = create_agent(
    model="claude-sonnet-4-6",
    tools=[get_user_email],
    context_schema=ContextSchema,
)

在工作流节点中使用

python
from langgraph.runtime import Runtime


@dataclass
class ContextSchema:
    user_name: str


def node(state: State, runtime: Runtime[ContextSchema]):
    user_name = runtime.context.user_name
    ...

Runtime 对象可用于访问静态上下文以及其他实用工具,如活动的 store 和 stream writer。详情请参阅 Runtime 文档。

动态运行时上下文

动态运行时上下文表示在单次运行中可以演变的可变数据,通过 LangGraph state 对象管理。这包括对话历史、中间结果以及从工具或 LLM 输出中派生的值。在 LangGraph 中,state 对象在运行期间充当短期记忆

在 Agent 中访问状态

python
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-6",
    tools=[search_knowledge],
    state_schema=CustomState,
    middleware=[personalized_prompt],
)

agent.invoke({
    "messages": "hi!",
    "user_name": "John Smith",
})

在工作流中访问状态

python
from typing_extensions import TypedDict
from langchain.messages import AnyMessage
from langgraph.graph import StateGraph


class CustomState(TypedDict):
    messages: list[AnyMessage]
    extra_field: int


def node(state: CustomState):
    messages = state["messages"]
    ...
    return {
        "extra_field": state["extra_field"] + 1,
    }


builder = StateGraph(CustomState)
builder.add_node(node)
builder.set_entry_point("node")
graph = builder.compile()

启用记忆 请参阅记忆指南了解如何启用记忆。这是一个强大的功能,允许你将 Agent 的状态跨多次调用持久化。否则,状态仅作用域于单次运行。

动态跨对话上下文

动态跨对话上下文表示跨多个对话或会话的持久化、可变数据,通过 LangGraph store 管理。这包括用户资料、偏好和历史交互。LangGraph store 充当跨多次运行的长期记忆。它可用于读取或更新持久化的事实(如用户资料、偏好、先前的交互)。

python
from langgraph.store.memory import InMemoryStore
from langgraph.checkpoint.memory import InMemorySaver
from langchain.agents import create_agent
from langchain.agents.middleware import dynamic_prompt, ModelRequest


store = InMemoryStore(...)


@dynamic_prompt
def memory_prompt(request: ModelRequest) -> str:
    """从 store 中读取用户偏好并将其注入提示。"""
    user_id = request.runtime.context.user_id
    user_prefs = request.store.get(("user_prefs", user_id))
    if user_prefs:
        return f"You are a helpful assistant. User preferences: {user_prefs}"
    return "You are a helpful assistant."


agent = create_agent(
    model="claude-sonnet-4-6",
    tools=[get_weather],
    middleware=[memory_prompt],
    checkpointer=InMemorySaver(),
    store=store,
)

下一步

本站为非官方中文学习站点,不代表 LangChain 官方。部分内容参考官方文档并重新整理为中文学习笔记。