> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-zh.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 上下文概述

**上下文工程** 是一种构建动态系统的实践，旨在以正确的格式提供恰当的信息和工具，使 AI 应用程序能够完成任务。上下文可以从两个关键维度来表征：

1. 按**可变性**划分：
   * **静态上下文**：在执行过程中不会改变的不可变数据（例如，用户元数据、数据库连接、工具）
   * **动态上下文**：随着应用程序运行而演变的可变数据（例如，对话历史、中间结果、工具调用观察）
2. 按**生命周期**划分：
   * **运行时上下文**：限定于单次运行或调用的数据
   * **跨对话上下文**：在多次对话或会话间持久存在的数据

<Tip>
  运行时上下文指的是本地上下文：你的代码运行所需的数据和依赖项。它**不**指代：

  * LLM 上下文，即传入 LLM 提示的数据。
  * "上下文窗口"，即可以传递给 LLM 的最大令牌数。

  运行时上下文是依赖注入的一种形式，可用于优化 LLM 上下文。它允许你在运行时向工具和节点提供依赖项（如数据库连接、用户 ID 或 API 客户端），而不是硬编码它们。例如，你可以使用运行时上下文中的用户元数据来获取用户偏好，并将其输入到上下文窗口中。
</Tip>

LangGraph 提供了三种管理上下文的方式，结合了可变性和生命周期两个维度：

| 上下文类型                                                         | 描述                   | 可变性 | 生命周期 | 访问方法                             |
| ------------------------------------------------------------- | -------------------- | --- | ---- | -------------------------------- |
| [**静态运行时上下文**](#static-runtime-context)                       | 启动时传递的用户元数据、工具、数据库连接 | 静态  | 单次运行 | `invoke`/`stream` 的 `context` 参数 |
| [**动态运行时上下文（状态）**](#dynamic-runtime-context-state)            | 在单次运行期间演变的可变数据       | 动态  | 单次运行 | LangGraph 状态对象                   |
| [**动态跨对话上下文（存储）**](#dynamic-cross-conversation-context-store) | 跨对话共享的持久化数据          | 动态  | 跨对话  | LangGraph 存储                     |

## 静态运行时上下文

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

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
@dataclass
class ContextSchema:
    user_name: str

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

<Tabs>
  <Tab title="智能体提示">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    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]
    )
    ```

    详情请参阅 [智能体](/oss/python/langchain/agents)。
  </Tab>

  <Tab title="工作流节点">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from langgraph.runtime import Runtime

    def node(state: State, runtime: Runtime[ContextSchema]):  # [!code highlight]
        user_name = runtime.context.user_name
        ...
    ```

    * 详情请参阅 [Graph API](/oss/python/langgraph/graph-api#add-runtime-configuration)。
  </Tab>

  <Tab title="在工具中">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from langchain.tools import tool, ToolRuntime

    @tool
    def get_user_email(runtime: ToolRuntime[ContextSchema]) -> str:
        """基于用户 ID 检索用户信息。"""
        # 模拟从数据库获取用户信息
        email = get_user_email_from_db(runtime.context.user_name)  # [!code highlight]
        return email
    ```

    详情请参阅 [工具调用指南](/oss/python/langchain/tools#configuration)。
  </Tab>
</Tabs>

<Tip>
  `Runtime` 对象可用于访问静态上下文和其他实用程序，如活动存储和流写入器。
  详情请参阅 [`Runtime`](https://reference.langchain.com/python/langgraph/runtime/Runtime) 文档。
</Tip>

<a id="state" />

## 动态运行时上下文

**动态运行时上下文** 表示在单次运行期间可以演变的可变数据，并通过 LangGraph 状态对象进行管理。这包括对话历史、中间结果以及来自工具或 LLM 输出的值。在 LangGraph 中，状态对象在运行期间充当 [短期记忆](/oss/python/concepts/memory)。

<Tabs>
  <Tab title="在智能体中">
    示例展示了如何将状态整合到智能体**提示**中。

    状态也可以被智能体的**工具**访问，这些工具可以根据需要读取或更新状态。详情请参阅 [工具调用指南](/oss/python/langchain/tools#short-term-memory)。

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    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"
    })
    ```
  </Tab>

  <Tab title="在工作流中">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    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()
    ```
  </Tab>
</Tabs>

<Tip>
  **启用记忆功能**
  有关如何启用记忆功能的更多详细信息，请参阅 [记忆指南](/oss/python/langgraph/add-memory)。这是一个强大的功能，允许你在多次调用之间持久化智能体的状态。否则，状态仅限定于单次运行。
</Tip>

<a id="store" />

## 动态跨对话上下文

**动态跨对话上下文** 表示跨多个对话或会话持久存在且可变的动态数据，并通过 LangGraph 存储进行管理。这包括用户档案、偏好和历史交互。LangGraph 存储充当跨多次运行的 [长期记忆](/oss/python/concepts/memory#long-term-memory)。这可用于读取或更新持久化的事实（例如，用户档案、偏好、先前的交互）。

## 了解更多

* [记忆概念概述](/oss/python/concepts/memory)
* [LangChain 中的短期记忆](/oss/python/langchain/short-term-memory)
* [LangGraph 中的记忆](/oss/python/langgraph/add-memory)

***

<div className="source-links">
  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\oss\concepts\context.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
