> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/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提供了三种管理上下文的方式，结合了可变性和生命周期维度：

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

    * 详情请参阅[图API](/oss/python/langgraph/use-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:
        """Retrieve user information based on user ID."""
        # simulate fetching user info from a database
        email = get_user_email_from_db(runtime.context.user_name)  # [!code highlight]
        return email
    ```

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

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

## 动态运行时上下文

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

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

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

    ```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>

## 动态跨对话上下文

**动态跨对话上下文**表示跨多个对话或会话的持久化、可变数据，通过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="terminal-2">
    [将这些文档](/use-these-docs)通过MCP连接到Claude、VSCode等，以获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在GitHub上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/concepts/context.mdx)或[提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
