如需查看完整的文档索引,请参阅 llms.txt。在文档页面的 URL 末尾加上 .md 即可查看该页面的 Markdown 版本。
主导航
主题

压缩

使用服务端压缩和独立压缩管理长时间持续的对话。

概述

在长时间交互中,您可以通过压缩缩小上下文,同时保留后续轮次所需的状态。

随着对话变长,压缩有助于平衡质量、成本和延迟。要了解如何在修改对话历史时保留推理信息,请参阅保持前缀不变。

服务端压缩

要启用服务端压缩,请在 Responses API 的响应创建请求(POST /responses 或 client.responses.create)中设置 context_management,并在其中指定 compact_threshold。

  • 当渲染后的 Token 数量超过设定的阈值时,服务端会执行压缩。
  • 在此模式下,无需单独调用 /responses/compact。
  • 响应流中包含加密的压缩项。
  • 在 Responses API 的响应创建请求中设置 store=false 后,服务端压缩可与零数据保留(ZDR)配合使用。

返回的压缩项使用更少的 Token,将此前的关键状态和推理信息传递给下一次运行。压缩项的内容不透明,不供人工解读。

如果您通过输入数组以无状态方式串联请求,请照常追加输出项。如果您使用 previous_response_id,每轮只需传入新的用户消息。无论采用哪种方式,压缩项都会保留下一个上下文窗口所需的信息。

如果对话中已有 configuration_update 项,API 会在 compaction 项之后立即输出一个新的 configuration_update 项。对于 reasoning.effort 和 text.format 这两个字段,新项会保留每个已更新字段最近一次显式设置的值。例如,如果某次更新只更改了输出格式,此前设置的推理强度仍然有效。如果对话中没有配置更新,API 就不会输出该项。

请按原顺序将返回的输出项传回 API。如果其中有新的配置更新项,也要一并传回。

将输出项追加到此前的输入项之后,您可以移除最近一个压缩项之前的所有项,以减小请求大小并降低长尾延迟。最近的压缩项包含继续对话所需的上下文。如果您使用 previous_response_id 串联请求,请勿手动裁剪上下文。

开发者添加的工具

开发者可以在对话过程中添加工具,具体做法是追加一个 additional_tools 输入项。自动压缩会将这些工具声明按原顺序保存在加密的 compaction 项中。例如,如果您添加了名为 lookup_ticket 的函数,模型一恢复生成就可以调用它。在后续轮次中,只要您传回该压缩项或使用 previous_response_id,模型仍可调用该函数。即使经过多次自动压缩,这些声明也会保留。

单独添加工具声明不会在 response.output 中产生额外的输出项。如果您还更改了推理强度或输出格式,请依次传回 compaction 项及其后的 configuration_update 项。如果之后需要更改某个工具的模式,请为该工具追加一个新的 additional_tools 项。对于仅在请求级 tools 数组中定义的工具,请在需要使用这些工具的轮次中重新提供其定义。

  • 工具选择。 您可以选择已恢复的函数、自定义工具以及命名空间中的工具。如果在 tool_choice 中指定不可用的函数,API 会返回 HTTP 400。
  • 客户端工具搜索。 恢复后的客户端工具搜索可以发现设置了 defer_loading: true 的函数。收到 tool_search_call 后,请返回一个 tool_search_output,并使用相同的 call_id。仅靠客户端工具搜索无法满足 tool_choice: "required" 的要求。
  • 托管的 MCP 服务器。 自动压缩会保存 server_label。请在下一次请求中使用该标签提供当前的端点和凭据。

使用步骤

  1. 照常调用 /responses,并在请求中加入 context_management,在其中指定 compact_threshold 以启用服务端压缩。
  2. 在流式返回响应期间,如果上下文大小超过阈值,服务端会执行一次压缩,在同一响应流中返回一个压缩输出项,然后裁剪上下文,再继续推理。
  3. 选择以下一种方式继续对话。通过输入数组以无状态方式串联请求时,将输出项(包括压缩项)追加到下一个输入数组。通过 previous_response_id 串联请求时,每轮只传入新的用户消息,并将响应 ID 传给下一轮。

使用流程示例

import OpenAI from "openai";
import { toResponseInputItems } from "openai/lib/responses/ResponseInputItems";
import { createInterface } from "node:readline";

const client = new OpenAI();

const conversation: OpenAI.Responses.ResponseInput = [
  {
    type: "message",
    role: "user",
    content: "Let's begin a long coding task.",
  },
];

// Subscribe before generation so piped follow-up turns are not lost.
const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
const turns = lines[Symbol.asyncIterator]();

async function respond() {
  const response = await client.responses.create({
    model: "gpt-6.2-astra",
    input: conversation,
    store: false,
    context_management: [{ type: "compaction", compact_threshold: 200_000 }],
  });

  conversation.push(...toResponseInputItems(response.output));
  console.log(response.output_text);
}

try {
  await respond();
  for await (const line of turns) {
    if (!line.trim()) continue;
    conversation.push({ type: "message", role: "user", content: line });
    await respond();
  }
} finally {
  lines.close();
}

显式触发压缩

要立即执行压缩,请将 {"type": "compaction_trigger"} 追加为 POST /v1/responses 请求的最后一个输入项。请将此前的 configuration_update 项保留在原位,以便模型在生成摘要时使用这些设置。API 会返回一个 compaction 项,不会附带新的 configuration_update 项。

要沿用这些设置,请在摘要之后、下一条用户消息之前追加一个新的 configuration_update 项,其中应包含您更改过的每个字段的最新值。如果使用 previous_response_id,摘要已包含在存储的历史记录中,因此只需依次发送新的配置更新项和用户消息。

显式触发压缩所生成的压缩项不包含此前的 additional_tools 声明。如果您从该项继续对话,请在请求的 tools 数组中提供所需的工具,或在用户消息之前追加一个由开发者声明的新 additional_tools 项。

使用流程示例

import OpenAI from "openai";
import { toResponseInputItems } from "openai/lib/responses/ResponseInputItems";

const client = new OpenAI();
const model = "gpt-6.2-astra";
const lookupTicket: OpenAI.Responses.FunctionTool = {
  type: "function",
  name: "lookup_ticket",
  description: "Look up a ticket by ID.",
  parameters: {
    type: "object",
    properties: { id: { type: "string" } },
    required: ["id"],
    additionalProperties: false,
  },
  strict: true,
};
const reasoning = { effort: "high" } as const;
const text = {
  format: {
    type: "json_schema",
    name: "trip_destination",
    strict: true,
    schema: {
      type: "object",
      properties: { city: { type: "string" } },
      required: ["city"],
      additionalProperties: false,
    },
  },
} as const;

const compacted = await client.responses.create({
  model,
  reasoning: { effort: "low" },
  input: [
    { role: "user", content: "Plan a trip to Kyoto." },
    { type: "additional_tools", role: "developer", tools: [lookupTicket] },
    { type: "configuration_update", reasoning },
    { type: "configuration_update", text },
    { type: "compaction_trigger" },
  ],
  store: false,
});

const response = await client.responses.create({
  model,
  reasoning: { effort: "low" },
  tools: [lookupTicket],
  input: [
    ...toResponseInputItems(compacted.output),
    { type: "configuration_update", reasoning, text },
    { role: "user", content: "Which city is my trip to?" },
  ],
  store: false,
});
console.log(response.output_text);

独立压缩端点

如果您希望自行控制压缩时机,可以在长时间运行的工作流中调用独立压缩端点来执行无状态压缩。

此端点完全无状态,可与 ZDR 配合使用。

您发送一个完整的上下文窗口(包含消息、工具和其他项),端点会返回一个压缩后的新上下文窗口,供您在下次调用 /responses 时传入。

返回的窗口包含一个加密的压缩项,该项使用更少的 Token 保留此前的关键状态和推理信息。压缩项的内容不透明,不供人工解读。

压缩后的窗口通常还包含从上一个窗口保留下来的其他项。

请勿裁剪 /responses/compact 的输出。返回的窗口就是下一次调用应使用的上下文窗口,请在下次调用 /responses 时将其原样传入。

独立压缩的使用步骤

  1. 照常调用 /responses,发送包含用户消息、助手输出和工具交互的输入项。
  2. 当上下文窗口变得较大时,调用 /responses/compact 生成一个压缩后的新上下文窗口。您发送给 /responses/compact 的窗口大小仍须在模型的上下文窗口限制之内。
  3. 在后续调用 /responses 时,将返回的压缩窗口(包含压缩项)作为输入,以替代完整的对话记录。

使用流程示例

import OpenAI from "openai";
import { toResponseInputItems } from "openai/lib/responses/ResponseInputItems";

const client = new OpenAI();

const conversation: OpenAI.Responses.ResponseInput = [
  { role: "user", content: "Plan a trip to Kyoto." },
];

const compacted = await client.responses.compact({
  model: "gpt-6.2-astra",
  input: conversation,
});

const nextInput: OpenAI.Responses.ResponseInput = [
  ...toResponseInputItems(compacted.output),
  { role: "user", content: "Add two more days to the itinerary." },
];

const response = await client.responses.create({
  model: "gpt-6.2-astra",
  input: nextInput,
  store: false,
});

console.log(response.output_text);

在后续对话中沿用配置更新和工具

POST /v1/responses/compact 会拒绝包含 configuration_update 项的历史记录,即使这些更新是通过 previous_response_id 继承的。如果历史记录中包含配置更新,请按以下步骤操作。

  1. 从包含所有输入项和输出项的完整历史记录开始。分别保存 reasoning.effort 和 text.format 最近一次显式设置的值。仅排除配置更新项,将其余各项按原顺序发送到压缩端点。
  2. 完整保留返回的窗口。追加一个新的 configuration_update 项,在其中填入刚才保存的字段值,然后追加下一条用户消息。下次调用 /v1/responses 时,沿用原有的请求级设置。
  3. 如果您此前通过 additional_tools 添加过工具,请在 tools 中提供下一轮所需的工具定义,或在用户消息之前追加一条新的开发者工具声明。独立压缩生成的摘要不会恢复这些工具。

在此示例中,对话最初使用低推理强度和纯文本输出。一次更新将推理强度调至高,之后的一次更新提供了 JSON 模式。compactAndContinue 通过一个配置更新项恢复这两项设置。请通过 nextTools 传入下一轮所需的工具。

import OpenAI from "openai";
import { toResponseInputItems } from "openai/lib/responses/ResponseInputItems";

const client = new OpenAI();

async function compactAndContinue(
  model: string,
  history: OpenAI.Responses.ResponseInput,
  nextMessage: string,
  nextTools: OpenAI.Responses.Tool[]
) {
  const input: OpenAI.Responses.ResponseInput = [];
  const latest: OpenAI.Responses.ResponseConfigurationUpdateItemParam = {
    type: "configuration_update",
  };
  for (const item of history) {
    if (item.type === "configuration_update") {
      if (item.reasoning?.effort != null) latest.reasoning = item.reasoning;
      if (item.text?.format) latest.text = item.text;
    } else {
      input.push(item);
    }
  }

  const compacted = await client.responses.compact({ model, input });
  const nextInput = toResponseInputItems(compacted.output);
  if (latest.reasoning || latest.text) nextInput.push(latest);
  nextInput.push({ role: "user", content: nextMessage });

  return client.responses.create({
    model,
    reasoning: { effort: "low" },
    tools: nextTools,
    input: nextInput,
    store: false,
  });
}