> ## 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 的最大令牌数。

  运行时上下文是你在线程中传递数据的方式。你可以将值（如数据库连接、用户会话或配置）附加到上下文，并在工具和中间件内部访问它们，而不是将内容存储在全局状态中。这使事物保持无状态、可测试和可重用。例如，你可以使用运行时上下文中的用户元数据来获取用户偏好，并将其输入到上下文窗口中。
</Tip>

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

| 上下文类型                                                         | 描述             | 可变性 | 生命周期 |
| ------------------------------------------------------------- | -------------- | --- | ---- |
| [**配置**](#config-static-context)                              | 运行开始时传递的数据     | 静态  | 单次运行 |
| [**动态运行时上下文（状态）**](#dynamic-runtime-context-state)            | 在单次运行期间演变的可变数据 | 动态  | 单次运行 |
| [**动态跨对话上下文（存储）**](#dynamic-cross-conversation-context-store) | 跨对话共享的持久化数据    | 动态  | 跨对话  |

<a id="static-context" />

## 配置

配置用于不可变数据，如用户元数据或 API 密钥。当你有在运行中途不会改变的值时使用此方式。

使用名为 **"configurable"** 的键来指定配置，该键为此目的保留。

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
await graph.invoke(
  { messages: [{ role: "user", content: "hi!" }] },
  { configurable: { user_id: "user_123" } } // [!code highlight]
);
```

<a id="state" />

## 动态运行时上下文

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

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

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

    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import { createAgent, createMiddleware } from "langchain";
    import type { AgentState } from "langchain";
    import * as z from "zod";

    const CustomState = z.object({ // [!code highlight]
      userName: z.string(),
    });

    const personalizedPrompt = createMiddleware({ // [!code highlight]
      name: "PersonalizedPrompt",
      stateSchema: CustomState,
      wrapModelCall: (request, handler) => {
        const userName = request.state.userName || "User";
        const systemPrompt = `You are a helpful assistant. User's name is ${userName}`;
        return handler({ ...request, systemPrompt });
      },
    });

    const agent = createAgent({  // [!code highlight]
      model: "claude-sonnet-4-6",
      tools: [/* your tools here */],
      middleware: [personalizedPrompt] as const, // [!code highlight]
    });

    await agent.invoke({
      messages: [{ role: "user", content: "hi!" }],
      userName: "John Smith",
    });
    ```
  </Tab>

  <Tab title="在工作流中">
    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import { z } from "zod/v4";
    import { StateGraph, StateSchema, MessagesValue, START } from "@langchain/langgraph";

    const CustomState = new StateSchema({  // [!code highlight]
      messages: MessagesValue,
      extraField: z.number(),
    });

    const builder = new StateGraph(CustomState)
      .addNode("node", async (state) => {  // [!code highlight]
        const messages = state.messages;
        // ...
        return {  // [!code highlight]
          extraField: state.extraField + 1,
        };
      })
      .addEdge(START, "node");

    const graph = builder.compile();
    ```
  </Tab>
</Tabs>

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

<a id="store" />

## 动态跨对话上下文

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

## 了解更多

* [记忆概念概述](/oss/javascript/concepts/memory)
* [LangChain 中的短期记忆](/oss/javascript/langchain/short-term-memory)
* [LangGraph 中的记忆](/oss/javascript/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>
