Skip to main content

Documentation Index

Fetch the complete documentation index at: https://nvd-54.mintlify.app/llms.txt

Use this file to discover all available pages before exploring further.

上下文工程是构建动态系统的实践,为 AI 应用提供正确格式的正确信息和工具,使其能够完成任务。上下文可以沿两个关键维度来描述:
  1. 可变性
    • 静态上下文:在执行过程中不变的不可变数据(例如用户元数据、数据库连接、工具)
    • 动态上下文:随应用运行而演变的可变数据(例如对话历史、中间结果、工具调用观察)
  2. 生命周期
    • 运行时上下文:限定于单次运行或调用的数据
    • 跨对话上下文:跨多个对话或会话持久存在的数据
运行时上下文是指本地上下文:你的代码运行所需的数据和依赖。它是指:
  • LLM 上下文,即传递给 LLM 提示的数据。
  • “上下文窗口”,即可传递给 LLM 的最大 Token 数。
运行时上下文是一种依赖注入形式,可用于优化 LLM 上下文。它允许你在运行时向工具和节点提供依赖(如数据库连接、用户 ID 或 API 客户端),而不是将它们硬编码。例如,你可以使用运行时上下文中的用户元数据来获取用户偏好并将其送入上下文窗口。
LangGraph 提供三种管理上下文的方式,结合了可变性和生命周期维度:
上下文类型描述可变性生命周期访问方式
静态运行时上下文启动时传入的用户元数据、工具、数据库连接静态单次运行invoke/streamcontext 参数
动态运行时上下文(状态)单次运行中演变的可变数据动态单次运行LangGraph 状态对象
动态跨对话上下文(存储)跨对话共享的持久数据动态跨对话LangGraph 存储

静态运行时上下文

静态运行时上下文代表不可变数据,如用户元数据、工具和数据库连接,通过 invoke/streamcontext 参数在运行开始时传递给应用。此数据在执行期间不会改变。
@dataclass
class ContextSchema:
    user_name: str

graph.invoke(
    {"messages": [{"role": "user", "content": "hi!"}]},
    context={"user_name": "John Smith"}
)
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")
)
参见智能体了解详情。
Runtime 对象可用于访问静态上下文和其他工具,如活动存储和流写入器。 参见 Runtime 文档了解详情。

动态运行时上下文

动态运行时上下文代表可在单次运行期间演变的可变数据,通过 LangGraph 状态对象管理。这包括对话历史、中间结果以及从工具或 LLM 输出派生的值。在 LangGraph 中,状态对象在运行期间充当短期记忆
示例展示了如何将状态纳入智能体提示状态也可以被智能体的工具访问,工具可以根据需要读取或更新状态。参见工具调用指南了解详情。
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=[...],
    state_schema=CustomState,
    middleware=[personalized_prompt],
)

agent.invoke({
    "messages": "hi!",
    "user_name": "John Smith"
})
启用记忆 请参见记忆指南了解如何启用记忆的更多详情。这是一个强大的功能,允许你在多次调用之间持久化智能体的状态。否则,状态仅限于单次运行。

动态跨对话上下文

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

了解更多