长输出
默认情况下,Gemini 4 型号(gemini-4-carbon, gemini-4-argon, 和 gemini-4-hydrogen)每个响应生成最多 64K token (65,536) 的思考和输出。长解码可以让你提高 max_output_tokens 过去用于硬推理、数学和编码任务的 64K,一直到统一的 1M-token 上下文窗口(1,048,576 token 在输入、思维和输出之间共享)。在 Interactions API 上,您可以使用以下命令运行长解码 后台执行 因此我们的服务器会为您运行每一跳,或者在前台运行 客户端延续.
解码需要多长时间 #
生成数十万个 token 可能需要比单个 HTTP 请求保持打开状态更长的时间,因此长时间解码会将生成拆分为从前一跳停止位置继续的连续跃点:在后台调用、流式调用和非流式传输中,每跳最多 64K token (65,536) gemini-4-hydrogen 呼叫,或每个非流跳最多 32K token (32,768) gemini-4-carbon 和 gemini-4-argon.
当你设置 background: true 和 max_output_tokens 大于 Interactions API 上的 65,536:
- 该请求异步运行并返回与
status="in_progress". - 如果响应到达 64K token 但未完成,服务器将使用迄今为止生成的 token 启动连续跳跃。
- 重复此过程,直到模型完成或达到
max_output_tokens. - 当您轮询交互时,您将获得单个交互中所有跃点的综合思考和输出。
要从客户端运行连续跳跃,请参阅 选择如何运行长解码.
import time
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-4-carbon",
input="Write a complete, rigorous proof of the prime number theorem.",
background=True,
generation_config={
"max_output_tokens": 262144,
"thinking_level": "high",
},
)
while interaction.status in ("in_progress", "queued"):
time.sleep(5)
interaction = client.interactions.get(id=interaction.id)
# Each hop adds a model_output step, so join the text of all of them.
text = "".join(
content.text
for step in interaction.steps
if step.type == "model_output"
for content in step.content
if content.type == "text"
)
print(text)
print("Status:", interaction.status)
print("Usage:", interaction.usage)
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
let interaction = await client.interactions.create({
model: "gemini-4-carbon",
input: "Write a complete, rigorous proof of the prime number theorem.",
background: true,
generation_config: {
max_output_tokens: 262144,
thinking_level: "high",
},
});
while (interaction.status === "in_progress" || interaction.status === "queued") {
await new Promise((resolve) => setTimeout(resolve, 5000));
interaction = await client.interactions.get(interaction.id);
}
// Each hop adds a model_output step, so join the text of all of them.
const text = interaction.steps
.filter((step) => step.type === "model_output")
.flatMap((step) => step.content ?? [])
.filter((content) => content.type === "text")
.map((content) => content.text)
.join("");
console.log(text);
console.log("Status:", interaction.status);
console.log("Usage:", interaction.usage);
# 1. Create the background interaction. It returns an ID right away.
ID=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-4-carbon",
"input": "Write a complete, rigorous proof of the prime number theorem.",
"background": true,
"generation_config": {"max_output_tokens": 262144, "thinking_level": "high"}
}' | jq -r '.id')
# 2. Poll until the status is no longer in_progress or queued.
# The REST response has no output_text field, so join the text of every model_output step.
while true; do
RESP=$(curl -s "https://generativelanguage.googleapis.com/v1beta/interactions/$ID" \
-H "x-goog-api-key: $GEMINI_API_KEY")
STATUS=$(echo "$RESP" | jq -r '.status')
if [[ "$STATUS" != "in_progress" && "$STATUS" != "queued" ]]; then
echo "$RESP" | jq -r '[.steps[]? | select(.type == "model_output") | .content[]? | select(.type == "text") | .text] | join("")'
echo "$RESP" | jq '{status, usage}'
break
fi
sleep 5
done
输出限制 #
流式和非流式交互默认为 64K 输出 token 限制,因此高达 64K token 的响应无需更改代码。要生成过去的 64K token,请引发 max_output_tokens 并使用后台执行或客户端延续。
| 如何创建交互 | 输出限制 |
|---|---|
background: false, max_output_tokens 未设置 | 65,536 token |
background: false, max_output_tokens 大于 65,536, automatic_continuation: true (默认SDK) | 你的 max_output_tokens,最多 1,048,576 减去您的输入 |
background: false, max_output_tokens 大于 65,536, automatic_continuation: false 或休息 | 65,536 token 每个流跳跃(或非流跳跃) gemini-4-hydrogen),或每个非流式传输跳跃上的 32,768 gemini-4-carbon 和 gemini-4-argon。循环与 continuation_token 生成最多您的 max_output_tokens. |
background: true, max_output_tokens 未设置 | 65,536 token |
background: true, max_output_tokens 大于 65,536 | 你的 max_output_tokens,最多 1,048,576 减去您的输入 |
何时使用长解码 #
大多数请求在 64K token 内完成。仅当一个响应需要更多思考和输出时才使用长解码。
| 工作量 | 使用长解码? | 为什么 |
|---|---|---|
| 硬数学、科学、研究和形式证明 | 是的 | 该模型可以花费超过 64K token 来探索和检查其推理。 |
| 最困难的编码和智能体任务 | 是的 | 有些任务需要比 64K token 多的思考和代码一次响应。大多数编码和智能体任务在 64K 下完成。 |
| 止于输出极限的评估工具 | 是的 | 当模型花费整个 64K 响应进行思考时,长解码可以防止答案被切断。 |
| 聊天、问答、总结、分类、提取 | 否 | 这些任务在 32K token 下很好地完成。 |
| 固定长度的请求,例如“写一本700,000字的书” | 否 | 该模型不遵循长度目标。 |
| 智能体在多次短回合中调用工具 | 否 | 每个回合都很短。每转的大输出快速填充共享的上下文窗口。 |
| 提示接近输入限制 | 否 | 输出只能使用 1,048,576 token 减去您的输入。 |
| 延迟敏感的请求 | 否 | 长解码可能会运行几分钟。 |
设定高 max_output_tokens 给了模型在难题上思考更长时间的空间,但模型仍然决定写多少。要控制模型使用多少推理工作,请设置 thinking_level.
选择如何运行长解码 #
后台执行是在 Interactions API 上运行长解码的最简单方法。我们的服务器运行每一跳,因此客户端连接断开不会中断生成。客户端延续(Google GenAI SDK 或您自己的代码启动每一跳)也可在 Interactions API 上用于前台调用、无状态请求或管理您自己的重试弹性。
| 后台执行(Interactions API) | 客户端延续 (Interactions API) | |
|---|---|---|
| 每个跳跃由谁开始 | 我们的服务器 | Google GenAI SDK(默认),或您自己的代码 |
| 每个请求的token | 你的 max_output_tokens,在一次交互中(每个内部跃点最多 64K) | 每个流 64K(以及非流式传输) gemini-4-hydrogen); 32K 每个非流请求 gemini-4-carbon 和 gemini-4-argon |
| 运行时间 | 长达 24 小时 | 每个流式传输跃点 20 分钟,每个非流式传输跃点 10 分钟 |
| 存储 | 需要 store: true | 默认存储(store: true),或无状态 store: false |
| 最适合 | 运行长解码的最简单方法 | 前台调用、无状态应用程序或更细粒度的重试控制,以便您可以构建自己的退避、错误处理和弹性 |
如果您改用GenerateContent API,请参阅 使用GenerateContent API进行长解码.
客户端延续 #
以下各节适用于以下情况: background: false (默认)。您的客户端而不是我们的服务器驱动每个连续跃点,可以使用 Google GenAI SDK 自动驱动,也可以使用您自己的循环驱动。
使用 SDK 自动继续 #
当 max_output_tokens 超过单跳限制,Google GenAI SDK 运行连续跳并返回一个组合交互。对于 REST 或自定义循环控制,请参阅 客户端继续使用您自己的循环.
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-4-carbon",
input="Write a complete, rigorous proof of the prime number theorem.",
generation_config={
"max_output_tokens": 262144,
"thinking_level": "high",
},
)
print(interaction.output_text)
print("Status:", interaction.status)
print("Usage:", interaction.usage)
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: "gemini-4-carbon",
input: "Write a complete, rigorous proof of the prime number theorem.",
generation_config: {
max_output_tokens: 262144,
thinking_level: "high",
},
});
console.log(interaction.output_text);
console.log("Status:", interaction.status);
console.log("Usage:", interaction.usage);
请记住这些 SDK 行为:
- 保存合并的响应:
interactions.create使用最终跃点合并所有跃点的文本、步骤和用法id。因为每一跳都是单独存储的,interactions.get仅返回最后一跳的输出,因此保存响应create。通过那个id作为previous_interaction_id在下一个回合保留完整的历史记录。 - 超时: 客户
http_options设置每个跃点的 HTTP 超时。路过timeout到interactions.create限制所有跃点的总时间。 - 中断运行: 如果在较早的进度之后跳跃失败,则 SDK 会引发
ContinuationInterruptedError。对于非流式通话,partial_interaction保存已完成跳跃的合并输出。要恢复,请传递错误的交互 ID 并continuation_token到interactions.create(或重新发送input当store是false).
客户端继续使用您自己的循环 #
要直接调用 REST 或自行管理跃点之间的重试、退避和日志记录,请在代码中运行连续循环(在 SDK 中,禁用 automatic_continuation)。在每个跃点上保留相同的模型、工具、系统指令和生成配置,如果禁用存储,则重新发送提示而不是之前的交互 ID。
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-4-carbon",
input="Write a complete, rigorous proof of the prime number theorem.",
automatic_continuation=False,
generation_config={
"max_output_tokens": 262144,
"thinking_level": "high",
},
)
full_text = interaction.output_text or ""
while interaction.status == "requires_continuation":
interaction = client.interactions.create(
model="gemini-4-carbon",
previous_interaction_id=interaction.id,
continuation_token=interaction.continuation_token,
automatic_continuation=False,
generation_config={
"max_output_tokens": 262144,
"thinking_level": "high",
},
)
full_text += interaction.output_text or ""
print(full_text)
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
let interaction = await client.interactions.create({
model: "gemini-4-carbon",
input: "Write a complete, rigorous proof of the prime number theorem.",
automatic_continuation: false,
generation_config: {
max_output_tokens: 262144,
thinking_level: "high",
},
});
let fullText = interaction.output_text ?? "";
while (interaction.status === "requires_continuation") {
interaction = await client.interactions.create({
model: "gemini-4-carbon",
previous_interaction_id: interaction.id,
continuation_token: interaction.continuation_token,
automatic_continuation: false,
generation_config: {
max_output_tokens: 262144,
thinking_level: "high",
},
});
fullText += interaction.output_text ?? "";
}
console.log(fullText);
RESP=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-4-carbon",
"input": "Write a complete, rigorous proof of the prime number theorem.",
"generation_config": {"max_output_tokens": 262144, "thinking_level": "high"}
}')
while [[ "$(echo "$RESP" | jq -r '.status')" == "requires_continuation" ]]; do
echo "$RESP" | jq -rj '[.steps[]? | select(.type == "model_output") | .content[]? | select(.type == "text") | .text] | join("")'
PREV_ID=$(echo "$RESP" | jq -r '.id')
TOKEN=$(echo "$RESP" | jq -r '.continuation_token')
RESP=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d "{
\"model\": \"gemini-4-carbon\",
\"previous_interaction_id\": \"$PREV_ID\",
\"continuation_token\": \"$TOKEN\",
\"generation_config\": {\"max_output_tokens\": 262144, \"thinking_level\": \"high\"}
}")
done
echo "$RESP" | jq -r '[.steps[]? | select(.type == "model_output") | .content[]? | select(.type == "text") | .text] | join("")'
流长解码 #
要在输出和思想摘要到达时对其进行流式传输,请添加 stream: true 和 thinking_summaries: "auto"。长流可能会丢失,因此您的客户端必须重新连接。按照中的重新连接模式进行操作 后台执行引导。长解码添加了这些规则:
- 保存交互ID: 阅读它来自
interaction.created事件。 - 保存每个
event_id: 安event_id可以到达interaction.status_update事件,不仅仅是文本增量。 - 重新连接与
last_event_id: 致电interactions.get使用stream: true和最后一个event_id。该事件之后,直播将继续进行。 - 读到最后: 重新连接后,请先读完流,然后再检查状态。即使交互完成后,服务器也会重播错过的事件。
- 设置长超时: 将每个流的 HTTP 读取超时设置为 15 到 20 分钟。
- 预期 5K-token 块中的输出: 第一个 32K token 上后
gemini-4-carbon和gemini-4-argon(或在 64K token 之后gemini-4-hydrogen,从第二跳开始),流在每个检查点以大约 5,000 token 的块发送输出。块之间的停顿是正常的。交互不会卡住,因此请保持连接打开。
对于使用 Google GenAI SDK 的前台流,SDK 将连续跳跃链接到单个流中:
- 继续跨跃阅读: 每个跃点都是它自己的交互并发出
interaction.created和interaction.completed事件。不要重置流解析器interaction.created,并且不要停止interaction.completed而状态是requires_continuation。如果您继续对话,请保存最后一跳的 ID。 - 处理中跳断开连接: 如果连接在新增量到达之前在检查点断开,SDK 会为您重新连接。如果流在最新检查点之后已经产生增量,则 SDK 引发
ContinuationInterruptedError以避免重复输出。
互动状态 #
后台交互最多可以运行 24 小时。一旦状态不再 in_progress 或 queued,使用此表处理交互状态:
| 状态 | 含义 | 该怎么办 |
|---|---|---|
completed | 模型完成了。 | 加入 model_output 介入 steps 并阅读 usage。要继续对话,请传递此交互的 id 作为 previous_interaction_id. |
requires_continuation | 前台跃点达到其单请求上限(64K 用于流式传输和 gemini-4-hydrogen 非流式传输,或 32K gemini-4-carbon 和 gemini-4-argon 非流媒体),剩余 token 预算。 | 默认情况下,Google GenAI SDK 会继续为您执行此操作。在 REST 中,发送下一跳 previous_interaction_id 和 continuation_token. |
requires_action | 该模型要求进行工具调用。 | 运行该工具。然后将结果与此交互一起发送 id. |
incomplete | 该模型使用了所有 max_output_tokens。如果模型仍在思考,文本可以为空。 | 继续使用 previous_interaction_id, continuation_token,以及更高的 max_output_tokens,或者使用更高的值再次发送请求 max_output_tokens. |
failed | 服务器无法完成,或者交互运行时间超过 24 小时。 | 重试请求。如果再次失败,分享互动 id 与支持。 |
cancelled | 您取消了互动。 | 阅读 usage 查看计费的 token。 |
要停止正在运行的交互,请调用 client.interactions.cancel(id=interaction.id) 在Python中, client.interactions.cancel(interaction.id) 在 JavaScript 中,或者 POST /v1beta/interactions/{id}/cancel 休息中。
套装 max_output_tokens #
max_output_tokens 设置交互过程中思考和输出的综合限制。降低它并不会让模型思考得更简洁,反而会更快地切断响应。
| 你的工作量 | 推荐 max_output_tokens |
|---|---|
| 限制低于 32K 的现有应用程序 | 提升到 32,768. 不需要后台执行。 |
| 长编码和智能体任务 | 从 65,536(默认值)开始。不需要后台执行。 |
| 复杂推理、硬数学、科学和证明 | 套装 background: true (或使用客户端延续)并从 262,144, 开始直到 1,048,576 减去您的输入 token。 |
要使用更少的 token,请降低 thinking_level。使用 high 用于最困难的推理任务。使用 medium (默认)适用于大多数编码和智能体工作。
计数 token #
interaction.usage 报告所有跃点的总数。阅读这些字段: total_input_tokens, total_cached_tokens, total_output_tokens, total_thought_tokens, 和 total_tokens.
total_input_tokens 将每一跳的输入token相加。每个跃点都会将您的提示以及迄今为止生成的所有内容发送回模型作为输入,因此在以后的每个跃点中都会再次计算相同的 token。例如,产生 200,000 token 思考和输出的 1,000-token 提示需要四个 64K 跃点(或七个 32K 非流跃点) gemini-4-carbon 和 gemini-4-argon):
| 啤酒花 | 发送到模型的输入 | 输入 token |
|---|---|---|
| 1 | 提示 | 1,000 |
| 2 | 提示+跳跃1 | 66,536 |
| 3 | 提示 + 跳跃 1 和 2 | 132,072 |
| 4 | 提示 + 跳转 1 到 3 | 197,608 |
| 总计 | 397,216 |
total_input_tokens 报告有关 397,000 token(重复的跳跃输入通过隐式缓存自动折扣 95%),即使实际上下文大小仅约为 201,000 token:1,000-token 提示加上 200,000 token的思考和输出。
在直播过程中, interaction.status_update 和 interaction.completed 事件包括 usage (该跃点的累积值,或后台模式下完整交互的累积值)。在后台流或单个前台跃点内,读取最新的 usage 值而不是将它们加在一起。在前台流中,每一跳都是一个单独的交互,因此将最终的结果相加 usage 每跳的。
了解计费 #
您为每一跳中的每个 token 付费,包括仅包含思考的跳数。
- 缓存折扣: 隐式缓存将每一跳中的重复输入折扣 95%。在推出期间,缓存输入的成本为每 1M token(而不是 $2.00)$0.10。
- 取消和失败的交互: 您需要为交互结束前完成的所有工作付费。
问题排查 #
| 症状 | 原因和修复 |
|---|---|
| 输出停止于 64K | 套装 max_output_tokens 大于65,536,并使用后台执行或升级Google GenAI SDK。 |
输出停止并显示状态 requires_continuation | 该跃点达到了单一请求上限,且预算还剩。升级SDK,启用 automatic_continuation,或添加一个连续循环。 |
| 400:“后台交互需要 store=true” | 后台执行需求 store: true. |
状态 incomplete 带有空文本 | 该模型在思维上全部采用了token。提高 max_output_tokens 或更低 thinking_level. |
| 上下文压缩开始得太早 | 您的智能体框架或评估工具读取 total_input_tokens。参见 计数 token. |
限制 #
- 早期的 SDK: Python 2.34.0, JavaScript 2.32.0, Go 1.77.0, Java 1.80.0, 和 .NET 1.28.0 之前的版本不会继续前台交互。
- 无长度目标: 该模型不遵循 token 长度或字数目标。