Gemini 4 Carbon 开发者指南

Gemini 4 Carbon 是 Google 的前沿模型,擅长在编码、金融、法律、网络安全和科学等领域处理复杂的实际任务,助力深度工作。它是 Gemini 4 系列中的一员。 Gemini 4 Carbon 是 Google 前沿模型,受服务专用条款第 34 条的约束(如需了解详情,请参阅滥用行为监控)。

本文档介绍了 4 Carbon 的主要功能、它强制执行的 API 惯例、如何迁移到该版本,以及快速入门。如需大致了解 Gemini 4 系列,请参阅 Gemini 4 使用入门。

Gemini 4 Carbon 的主要功能

Gemini 4 Carbon 包含以下功能:

  • 统一的输入和输出 token 限制:4 Carbon 具有统一的 1,048,576 token 限制,其中包括输入和输出 token(输出包括思考、函数调用和最终回答)。
  • 长解码(最多 1,048,576 个 token):4 Carbon 在 Interactions API 和 GenerateContent (v1beta1) 上,将生成范围从单个前台片段(流式传输时为 65,536 个 token,非流式传输时为 32,768 个 token)扩展到最多 1,048,576 个 token(减去输入 token)。Google Gen AI SDK 会自动处理跨片段的 continuation_token,您也可以运行异步服务器管理的后台解码 (background=true),或在自定义延续循环中管理 continuation_token。
  • 思考等级:4 Carbon 支持 LOW、MEDIUM(gemini-4-carbon 上的默认等级)和 HIGH(gemini-4-carbon-cyber-permissive 上的默认等级)。
  • 具有持久缓存的隐式缓存:隐式缓存会自动应用于 4,096 个或更多 token 的共享提示前缀,并且默认启用持久缓存。不支持显式上下文缓存。
  • Office 和 OpenDocument 文件输入:除了 PDF 和纯文本之外,4 Carbon 还接受内嵌或来自 Cloud Storage 的 Microsoft Office(.docx、.dotx、.doc、.pptx、.ppt、.xlsx、.xls)和 OpenDocument(.odt、.odp、.ods)文件,同时支持 GenerateContent 和 Interactions API。
  • 智能体视频理解:智能体视频理解功能已正式版,默认处于关闭状态。

快速入门

在开始之前,您必须使用应用默认凭证 (ADC) 或 API 密钥向 Gemini Enterprise Agent Platform 进行身份验证。如需了解详情,请参阅 Agent Platform 使用入门。

在以下代码块中,将 PROJECT_ID 替换为您的项目 ID。

在 Agent Studio 中试用

如需在 Agent Studio 界面中测试提示并配置 gemini-4-carbon,请执行以下操作:

  1. 在 Cloud de Confiance by S3NS 项目中打开 Agent Studio,然后在 Gemini 组下选择gemini-4-carbon。
  2. 在模型设置中,配置以下选项:
    • 思考等级:选择 Low、Medium(默认)或 High。
    • 区域:选择 Global、us 或 eu。
    • 输出 token 限制:设置为 32,768 到 1,048,576 之间的值(默认值为 1,048,576)。对于超出单次请求限制的回答,Agent Studio 会自动处理延续令牌。

安装

升级到最新的 Google Gen AI SDK。如需在 Interactions API 上使用自动继续功能,需要使用 google-genai >= 2.34.0(Python 版)、@google/genai >= 2.32.0(JavaScript/TypeScript 版)、>= 1.77.0(Go 版)或 >= 1.80.0(Java 版)(在 GenerateContent 上,自动继续功能需要使用 >= 2.30.1 [Python 版]、>= 2.29.1 [JavaScript/TypeScript 版]、>= 1.74.0 [Go 版]、>= 1.77.0 [Java 版]、>= 1.26.0 [.NET 版] 或 >= 1.6.0 [Kotlin 版]):

pip install --upgrade "google-genai>=2.34.0"

基本请求

使用 Google Gen AI SDK 或 REST 向 gemini-4-carbon 发送请求:

Python (GenerateContent)

from google import genai
from google.genai import types

client = genai.Client(enterprise=True, project="PROJECT_ID", location="global")

response = client.models.generate_content(
    model="gemini-4-carbon",
    contents="Design a lock-free ring buffer in Rust for multi-producer, single-consumer telemetry ingestion.",
    config=types.GenerateContentConfig(
        thinking_config=types.ThinkingConfig(
            thinking_level="MEDIUM",  # Default: "MEDIUM" (Valid: "LOW", "MEDIUM", "HIGH")
        ),
    ),
)
print(response.text)

Python (Interactions API)

from google import genai

client = genai.Client(enterprise=True, project="PROJECT_ID", location="global")

# Turn 1: Initial request (stored server-side by default)
turn1 = client.interactions.create(
    model="gemini-4-carbon",
    input="Design a lock-free ring buffer in Rust for multi-producer, single-consumer telemetry ingestion.",
    store=True,
)
print(turn1.output_text)

# Turn 2: Continue the conversation using previous_interaction_id
turn2 = client.interactions.create(
    model="gemini-4-carbon",
    input="Add a bounded backpressure policy and unit tests for concurrent writers.",
    previous_interaction_id=turn1.id,
)
print(turn2.output_text)

REST

curl -X POST \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
"https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/publishers/google/models/gemini-4-carbon:generateContent" \
-d '{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "text": "Provide an architectural review of this Go interface."
        }
      ]
    }
  ],
  "generationConfig": {
    "thinkingConfig": {
      "thinkingLevel": "MEDIUM"
    }
  }
}'

结构化输出

如需生成符合架构的 JSON 输出,请配置 response_mime_type 和 response_schema:

from pydantic import BaseModel, Field
from google import genai
from google.genai import types

class ArchitectureReview(BaseModel):
    component: str = Field(description="Service or module name")
    bottlenecks: list[str] = Field(description="Throughput or latency bottlenecks")
    recommended_changes: list[str] = Field(description="Concrete refactoring steps")

client = genai.Client(enterprise=True, project="PROJECT_ID", location="global")

response = client.models.generate_content(
    model="gemini-4-carbon",
    contents="Review a synchronous order-processing pipeline backed by a single primary database at 15,000 writes/sec.",
    config=types.GenerateContentConfig(
        response_mime_type="application/json",
        response_schema=ArchitectureReview,
        thinking_config=types.ThinkingConfig(thinking_level="HIGH"),
    ),
)
print(response.text)

长解码示例

默认情况下,单个前台 API 段在流式传输时最多生成 65,536 个输出词元,在非流式传输时最多生成 32,768 个输出词元,其中输出包括思考、函数调用和最终回答。如需生成最多 1,048,576 个 token(减去输入 token)的补全内容,请在 Interactions API 或 GenerateContent 中使用长解码。如需了解延续选项、状态转换和验证规则,请参阅长解码。

通过 Interactions API 使用长解码

在 google-genai >= 2.34.0 (Python)、@google/genai >= 2.32.0 (JavaScript/TypeScript)、Go >= 1.77.0 和 Java >= 1.80.0 中,只要某个片段返回 status="requires_continuation",interactions.create() 就会自动跨片段跟踪 continuation_token。您还可以选择停用 (automatic_continuation=False) 以运行自定义存储 (store=True) 或无状态 (store=False) 循环:

Python(SDK 自动)

from google import genai

client = genai.Client(
    enterprise=True,
    project="PROJECT_ID",
    location="global",
)

# Automatic continuation is enabled by default in google-genai >= 2.34.0.
# Unary calls merge all segments into one Interaction with summed usage.
interaction = client.interactions.create(
    model="gemini-4-carbon",
    input="Write a complete formal proof of the prime number theorem.",
    generation_config={
        "max_output_tokens": 256000,
        "thinking_level": "high",
    },
)
print(interaction.output_text)
print(f"Merged segment IDs: {interaction.continuation_ids}")
print(f"Initial input tokens: {interaction.usage.initial_input_tokens}")

# Optional: Delete each stored server segment (last segment first) before its 7-day TTL expires.
for segment_id in reversed(interaction.continuation_ids or [interaction.id]):
    client.interactions.delete(id=segment_id)

# Streaming yields events across all segments in order. Intermediate segments
# emit interaction.completed with status="requires_continuation".
stream = client.interactions.create(
    model="gemini-4-carbon",
    input="Write a complete formal proof of the prime number theorem.",
    stream=True,
    generation_config={
        "max_output_tokens": 256000,
        "thinking_level": "high",
    },
)
for event in stream:
    if event.event_type == "step.delta" and getattr(event.delta, "text", None):
        print(event.delta.text, end="", flush=True)
    elif (
        event.event_type == "interaction.completed"
        and event.interaction.status != "requires_continuation"
    ):
        print(f"\nFinal status: {event.interaction.status}")

# Set automatic_continuation=False to return after a single segment.
single_segment = client.interactions.create(
    model="gemini-4-carbon",
    input="Write a complete formal proof of the prime number theorem.",
    generation_config={"max_output_tokens": 256000, "thinking_level": "high"},
    automatic_continuation=False,
)

Python(自定义循环)

from google import genai

client = genai.Client(
    enterprise=True,
    project="PROJECT_ID",
    location="global",
)

prompt = "Write a complete formal proof of the prime number theorem."

# Stored loop (store=True, default): chain previous_interaction_id + continuation_token
# without resending input.
segment = client.interactions.create(
    model="gemini-4-carbon",
    input=prompt,
    store=True,
    generation_config={"max_output_tokens": 131072, "thinking_level": "high"},
    automatic_continuation=False,
)
full_text = segment.output_text or ""

while segment.status == "requires_continuation" and segment.continuation_token:
    segment = client.interactions.create(
        model="gemini-4-carbon",
        previous_interaction_id=segment.id,
        continuation_token=segment.continuation_token,
        generation_config={"max_output_tokens": 131072, "thinking_level": "high"},
        automatic_continuation=False,
    )
    full_text += segment.output_text or ""

# If status == "incomplete", max_output_tokens was exhausted; raise max_output_tokens
# to continue (leaving default automatic_continuation=True lets the SDK finish remaining segments).
if segment.status == "incomplete" and segment.continuation_token:
    segment = client.interactions.create(
        model="gemini-4-carbon",
        previous_interaction_id=segment.id,
        continuation_token=segment.continuation_token,
        generation_config={"max_output_tokens": 256000, "thinking_level": "high"},
    )
    full_text += segment.output_text or ""

# Stateless loop (store=False): resend original input + continuation_token
# with no previous_interaction_id.
stateless_seg = client.interactions.create(
    model="gemini-4-carbon",
    input=prompt,
    store=False,
    generation_config={"max_output_tokens": 131072, "thinking_level": "high"},
    automatic_continuation=False,
)
stateless_text = stateless_seg.output_text or ""
while stateless_seg.status == "requires_continuation" and stateless_seg.continuation_token:
    stateless_seg = client.interactions.create(
        model="gemini-4-carbon",
        input=prompt,
        store=False,
        continuation_token=stateless_seg.continuation_token,
        generation_config={"max_output_tokens": 131072, "thinking_level": "high"},
        automatic_continuation=False,
    )
    stateless_text += stateless_seg.output_text or ""

REST(存储)

# Segment 1: Start a stored interaction (store=true by default)
curl -s -X POST \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  "https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/global/interactions" \
  -d '{
    "model": "gemini-4-carbon",
    "store": true,
    "input": "Write a complete formal proof of the prime number theorem.",
    "generation_config": {
      "max_output_tokens": 131072,
      "thinking_level": "high"
    }
  }'

# Segment 2: When status is "requires_continuation", pass previous_interaction_id
# and continuation_token without resending input
curl -s -X POST \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  "https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/global/interactions" \
  -d '{
    "model": "gemini-4-carbon",
    "store": true,
    "previous_interaction_id": "SEGMENT_1_ID",
    "continuation_token": "CONTINUATION_TOKEN",
    "generation_config": {
      "max_output_tokens": 131072,
      "thinking_level": "high"
    }
  }'

REST(无状态)

# Segment 1: Stateless interaction (store=false)
curl -s -X POST \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  "https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/global/interactions" \
  -d '{
    "model": "gemini-4-carbon",
    "store": false,
    "input": "Write a complete formal proof of the prime number theorem.",
    "generation_config": {
      "max_output_tokens": 131072,
      "thinking_level": "high"
    }
  }'

# Segment 2: Resend the original input and continuation_token (no previous_interaction_id)
curl -s -X POST \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  "https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/global/interactions" \
  -d '{
    "model": "gemini-4-carbon",
    "store": false,
    "input": "Write a complete formal proof of the prime number theorem.",
    "continuation_token": "CONTINUATION_TOKEN",
    "generation_config": {
      "max_output_tokens": 131072,
      "thinking_level": "high"
    }
  }'

对于异步服务器管理执行(background=True 搭配 store=True)或从流式检查点恢复(interaction.status_update 事件在 32,768 个输出词元处发出,之后每 5,000 个词元发出一次),请使用以下模式:

Python(后台)

import time
from google import genai

client = genai.Client(
    enterprise=True,
    project="PROJECT_ID",
    location="global",
)

# Start a server-managed background long decode (requires store=True)
interaction = client.interactions.create(
    model="gemini-4-carbon",
    input="Write a complete formal proof of the prime number theorem.",
    background=True,
    store=True,
    generation_config={"max_output_tokens": 256000, "thinking_level": "high"},
)

while interaction.status in ("queued", "in_progress"):
    time.sleep(10)
    interaction = client.interactions.get(id=interaction.id)

print(f"Status: {interaction.status}")
print(interaction.output_text)

# Optional: Cancel an in-progress background interaction and resume later
# from its persisted checkpoint continuation_token (if >= 32,768 tokens decoded).
# cancelled = client.interactions.cancel(id=interaction.id)
# if cancelled.continuation_token:
#     resumed = client.interactions.create(
#         model="gemini-4-carbon",
#         previous_interaction_id=cancelled.id,
#         continuation_token=cancelled.continuation_token,
#         background=True,
#         generation_config={"max_output_tokens": 256000, "thinking_level": "high"},
#     )

REST(后台)

# Start a server-managed background long decode (requires store=true)
curl -s -X POST \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  "https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/global/interactions" \
  -d '{
    "model": "gemini-4-carbon",
    "background": true,
    "store": true,
    "input": "Write a complete formal proof of the prime number theorem.",
    "generation_config": {
      "max_output_tokens": 256000,
      "thinking_level": "high"
    }
  }'

# Poll the interaction until status reaches completed, incomplete, failed, or cancelled
curl -s -X GET \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  "https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/global/interactions/INTERACTION_ID"

# Optional: Cancel an in-progress background decode
curl -s -X POST \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  "https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/global/interactions/INTERACTION_ID/cancel"

# Optional: Resume a cancelled background decode from its checkpoint continuation_token
curl -s -X POST \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  "https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/global/interactions" \
  -d '{
    "model": "gemini-4-carbon",
    "background": true,
    "store": true,
    "previous_interaction_id": "INTERACTION_ID",
    "continuation_token": "CONTINUATION_TOKEN",
    "generation_config": {
      "max_output_tokens": 256000,
      "thinking_level": "high"
    }
  }'

Python(流式检查点)

from google import genai
from google.genai import errors

client = genai.Client(
    enterprise=True,
    project="PROJECT_ID",
    location="global",
)

# With default automatic_continuation=True, stream=True automatically
# reconnects from the latest interaction.status_update checkpoint (32,768
# output tokens, then every 5,000 tokens) if no output was yielded after the
# checkpoint. If a disconnect occurs after output was yielded since the last
# checkpoint, the SDK raises ContinuationInterruptedError so you can resume
# from err.continuation_token.
stream = client.interactions.create(
    model="gemini-4-carbon",
    input="Write a complete formal proof of the prime number theorem.",
    stream=True,
    store=True,
    generation_config={"max_output_tokens": 256000, "thinking_level": "high"},
)

try:
    for event in stream:
        if event.event_type == "step.delta" and getattr(event.delta, "text", None):
            print(event.delta.text, end="", flush=True)
except errors.ContinuationInterruptedError as err:
    # Resuming from a mid-segment checkpoint regenerates any output yielded
    # after that checkpoint.
    if err.interaction_id and err.continuation_token:
        resumed_stream = client.interactions.create(
            model="gemini-4-carbon",
            previous_interaction_id=err.interaction_id,
            continuation_token=err.continuation_token,
            stream=True,
            store=True,
            generation_config={"max_output_tokens": 256000, "thinking_level": "high"},
        )
        for event in resumed_stream:
            if event.event_type == "step.delta" and getattr(event.delta, "text", None):
                print(event.delta.text, end="", flush=True)

REST(流式检查点)

# Start a streaming interaction; save interaction.id from interaction.created
# and the latest continuation_token from interaction.status_update SSE events
curl -N -X POST \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  "https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/global/interactions" \
  -d '{
    "model": "gemini-4-carbon",
    "stream": true,
    "store": true,
    "input": "Write a complete formal proof of the prime number theorem.",
    "generation_config": {
      "max_output_tokens": 256000,
      "thinking_level": "high"
    }
  }'

# Resume a dropped stream from the last saved checkpoint continuation_token
# (for store=false, resend the original input instead of previous_interaction_id)
curl -N -X POST \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  "https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/global/interactions" \
  -d '{
    "model": "gemini-4-carbon",
    "stream": true,
    "store": true,
    "previous_interaction_id": "SEGMENT_ID",
    "continuation_token": "CHECKPOINT_CONTINUATION_TOKEN",
    "generation_config": {
      "max_output_tokens": 256000,
      "thinking_level": "high"
    }
  }'

将长解码与 GenerateContent 搭配使用

在 GenerateContent (v1beta1) 上, 对于流式传输请求,将 max_output_tokens 设置为大于 65,536 的值;对于非流式传输请求,将 设置为大于 32,768 的值(最多 1,048,576)。当 finish_reason 为 CONTINUATION 时,Google Gen AI SDK 会自动跨片段跟踪 continuation_token(在 GenerateContentConfig 中设置 automatic_continuation=False 即可停用),您也可以在自定义循环中传递 continuation_token:

from google import genai
from google.genai import types

client = genai.Client(enterprise=True, project="PROJECT_ID", location="global")

# Automatic continuation is enabled by default in google-genai >= 2.30.1.
# Chunks across all continuation requests are yielded as a single stream.
for chunk in client.models.generate_content_stream(
    model="gemini-4-carbon",
    contents="Write a complete formal proof of the prime number theorem.",
    config=types.GenerateContentConfig(
        max_output_tokens=256000,
        thinking_config=types.ThinkingConfig(thinking_level="HIGH"),
    ),
):
    print(chunk.text, end="")

# Set automatic_continuation=False to disable automatic continuation.
for chunk in client.models.generate_content_stream(
    model="gemini-4-carbon",
    contents="Write a complete formal proof of the prime number theorem.",
    config=types.GenerateContentConfig(
        thinking_config=types.ThinkingConfig(thinking_level="HIGH"),
        automatic_continuation=False,
    ),
):
    print(chunk.text, end="")

REST(自定义接续循环)

# Request 1: Initial request with maxOutputTokens > 32,768
curl -s -X POST \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  "https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/global/publishers/google/models/gemini-4-carbon:generateContent" \
  -d '{
    "contents": [{
      "role": "user",
      "parts": [{"text": "Write a complete formal proof of the prime number theorem."}]
    }],
    "generationConfig": {
      "maxOutputTokens": 131072,
      "thinkingConfig": {"thinkingLevel": "HIGH"}
    }
  }'

# Request 2: Resend the original request with top-level continuationToken
# from Request 1 (candidates[0].continuationToken)
curl -s -X POST \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  "https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/global/publishers/google/models/gemini-4-carbon:generateContent" \
  -d '{
    "contents": [{
      "role": "user",
      "parts": [{"text": "Write a complete formal proof of the prime number theorem."}]
    }],
    "continuationToken": "CONTINUATION_TOKEN",
    "generationConfig": {
      "maxOutputTokens": 131072,
      "thinkingConfig": {"thinkingLevel": "HIGH"}
    }
  }'

强制性 API 规则和行为规范

4 Carbon 强制执行以下各部分中关于思考级别、词元限制、缓存、生成参数和多轮工具执行的规范。

思考等级

4 Carbon 支持三个 thinking_level 值(thinking_budget 和 MINIMAL 会返回 HTTP 400 验证错误)。在 GenerateContent 上传递大写值("LOW"、"MEDIUM"、"HIGH"),在 Interactions API 上传递小写值("low"、"medium"、"high")。下表列出了每个思考级别及其推荐的工作负载:

思考等级 推荐的工作负载
HIGH(gemini-4-carbon-cyber-permissive 上的默认设置) 多文件软件工程、形式化证明、架构设计和漏洞发现。
MEDIUM(gemini-4-carbon 上的默认设置) 通用编码、工具使用、文档问答和视频理解。
LOW 分类、摘要和元数据提取。

Token 数量上限、缓存和结算

4 Carbon 适用以下令牌、缓存、媒体和结算规则:

  • 统一的输入和输出 token 限制以及默认输出预算: token 预算和前台片段限制的工作原理如下:
    • 模型的总体 token 限制为 1,048,576 个 token,包括输入和输出 token(其中输出包括思考、函数调用和最终回答)。max_output_tokens 控制生成的输出 token 上限(最多为 1,048,576 减去输入 token);如果将 max_output_tokens 设置为大于 1,048,576,则会返回 HTTP 400 错误。
    • 如果在 GenerateContent 或 Interactions API 中省略 max_output_tokens,则默认总输出预算(思考、函数调用和回答)为 65,536 个 token。由于单个前台片段在流式传输时最多会生成 65,536 个 token,在非流式传输时最多会生成 32,768 个 token,因此 Google Gen AI SDK (v1beta1) 会在需要时自动在非流式传输调用中串联两个 32,768 token 的片段,而单个非流式传输 REST 请求会在一个 32,768 token 的前台片段后停止。在 Agent Studio 中,输出 token 上限默认为 1,048,576,并会自动继续。
  • 长解码:单个前台片段在流式传输时最多可生成 65,536 个输出 token,在非流式传输时最多可生成 32,768 个输出 token。如需在 Interactions API 或 GenerateContent (v1beta1) 上将单轮输出扩展到最多 1,048,576 个 token(减去输入 token),请参阅长解码。
  • 上下文缓存:不支持显式上下文缓存。隐式缓存(默认启用持久缓存)会自动应用于 4,096 个或更多 token 的共享提示前缀,因此请将静态内容放在提示的开头。
  • Office 和 OpenDocument 输入:通过 GenerateContent 和 document 输入(包括工具结果),在 Interactions API 上使用 inlineData 或 fileData,以内嵌方式或通过 Cloud Storage URI (gs://) 传递 Word(application/vnd.openxmlformats-officedocument.wordprocessingml.document、application/vnd.openxmlformats-officedocument.wordprocessingml.template、application/msword、application/vnd.oasis.opendocument.text)、PowerPoint(application/vnd.openxmlformats-officedocument.presentationml.presentation、application/vnd.ms-powerpoint、application/vnd.oasis.opendocument.presentation)以及 Excel 或 OpenDocument 电子表格(application/vnd.openxmlformats-officedocument.spreadsheetml.sheet、application/vnd.ms-excel、application/vnd.oasis.opendocument.spreadsheet)文件。
  • 智能体视频:上传的视频默认使用 media_processing="static"。设置 media_processing="agentic" 以启用智能体视频处理。
  • Token 统计和结算:模型处理的每个 Token 都会被统计并计费,包括思考 Token、内部工具系统指令以及使用接地功能时的函数声明。“依托 Google 搜索进行接地”功能仍按查询次数计费。

参数、函数调用和对话验证

4 Carbon 针对生成参数、工具调用和对话记录强制执行以下规则:

  • 忽略的采样参数(temperature、top_k、top_p):后端会忽略自定义值。使用 thinking_level 控制推理深度,使用 response_schema 控制输出格式。
  • 不支持的参数(frequency_penalty、presence_penalty 和 candidate_count 大于 1):传递 frequency_penalty、presence_penalty 或 candidate_count 大于 1(candidateCount 固定为 1)会返回 HTTP 400 错误。请从您的请求中移除这些参数。
  • 函数调用:工具声明和执行轮次遵循以下规则:

    • 回合对称性:每个 FunctionResponse 必须与前一个 FunctionCall 的 id、name 和顺序相匹配。
    • 依序执行:在多步工具循环中,优先选择依序执行工具。
    • 工具前格式设置:使用 \n\n 分隔内嵌指令,并避免在工具调用之前使用非结构化文本。如需在工具调用之前记录中间状态,请使用专用函数声明:

      {
        "name": "update",
        "description": "Update working notes before tool execution",
        "parameters": {
          "type": "OBJECT",
          "properties": {
            "previous_step": {"type": "STRING"},
            "plan": {"type": "STRING"},
            "next_step": {"type": "STRING"}
          },
          "required": ["previous_step", "plan", "next_step"]
        }
      }
      
  • 对话序列验证:多轮对话载荷强制执行以下限制:

    • 历史记录载荷不能以 model 角色轮次结尾。
    • 不支持预填模型轮次。

长解码

长解码功能可将生成内容(最多 1,048,576 个词元,不含输入词元)拆分为多个片段,并在 Interactions API 或 GenerateContent (v1beta1) 上运行。在 Interactions API 上,每个前台片段在流式传输 (stream=true) 时最多生成 65,536 个输出词元,在非流式传输 (stream=false) 时最多生成 32,768 个输出词元,并返回 status="requires_continuation" 以及加密的 continuation_token;或者,您可以设置 background=true (store=true),让服务器异步运行延续循环,并将合并后的输出存储在一个 Interaction 中。在 GenerateContent 上,流式片段最多生成 65,536 个输出 token,非流式片段最多生成 32,768 个输出 token,然后发出带有 continuation_token 的 finish_reason=CONTINUATION,并持续到 finish_reason=STOP。在 Agent Studio 中,将输出 token 限制设置为大于 65,536 且不超过 1,048,576 时,系统会自动处理延续 token。如需查看可运行的代码示例,请参阅长解码快速入门示例。

何时使用长解码

大多数请求都会在 65,536 个 token 的默认输出预算(或通过 REST 发送的单个 32,768 个 token 的非流式前台片段)内完成。仅当一个回答需要更多输出时,才使用长解码。长解码为模型提供了更多推理空间,但不会使回答变长(使用 thinking_level 控制推理深度)。

工作负载 要使用长解码吗? 原因
高难度数学、科学、研究和形式化证明 是 模型可以花费超过 65,536 个 token 来探索和检查其推理过程。
最棘手的编程和智能体任务 是 有些任务需要单次回答中包含超过 65,536 个 token 的思考和代码。大多数编码和智能体任务在 65,536 个 token 内即可完成。
在达到输出上限时停止的评估框架 是 长解码功能可防止模型在思考时用尽整个 65,536 或 32,768 token 请求,从而避免回答被截断。
Chat、问答、总结、分类和提取 否 这些任务在 32,768 个 token 内即可完成。
要求固定长度,例如“写一本 70 万字的书” 否 模型不遵循长度目标。
通过多次简短对话调用工具的智能体 否 每轮对话都很简短。每轮对话的大量输出会很快达到 1,048,576 个 token 的统一输入和输出限制。
提示接近 1,048,576 个 token 的输入限制 否 输出只能使用 1,048,576 个词元减去输入词元数。
对延迟时间敏感的请求 否 长解码可能需要运行几分钟。

选择继续选项

根据您的 API 接口、存储状况和运行时环境选择延续模式。下表中的所有选项在 gemini-4-carbon 和 gemini-4-carbon-cyber-permissive 上都达到了相同的 1,048,576 个词元限制(减去输入词元)。

接续选项 API 接口 每个片段的启动者 每个片段的词元数 每个请求的时间限制 服务器存储空间 适用场景
Google Gen AI SDK 自动继续(推荐) Interactions API (v1beta1) Google Gen AI SDK:Python (google-genai >= 2.34.0)、JavaScript/TypeScript (@google/genai >= 2.32.0)、Go (>= 1.77.0) 和 Java (>= 1.80.0) 最多 65,536 (stream=true) 或 32,768 (stream=false) 每个片段 20 分钟 默认情况下,服务器存储空间为 7 天 (store=true),或无 (store=false) 大多数有状态或无状态 Interactions API 应用
后台服务器管理的循环 (background=true) Interactions API (v1beta1) Agent Platform 服务器循环;您的代码会轮询 get 在服务器端管理,最多可管理 max_output_tokens 异步(无需打开客户端流) 7 天服务器存储空间(需要 store=true) 异步作业、通过 REST 使用其他语言的调用方,以及单记录持久性
自定义前台存储循环 (store=true) Interactions API (v1beta1) 您的代码(previous_interaction_id + continuation_token,无 input) 最多 65,536 个(stream=true,在 32,768 个之后,每 5,000 个 token 设置一个检查点)或 32,768 个(stream=false) 每个片段 20 分钟 7 天服务器存储空间 (store=true) REST 调用方和自定义检查点恢复
自定义前台无状态循环 (store=false) Interactions API (v1beta1) 您的代码(原始 input + continuation_token,无 previous_interaction_id) 最多 65,536 个(stream=true,在 32,768 个之后,每 5,000 个 token 设置一个检查点)或 32,768 个(stream=false) 每个片段 20 分钟 无服务器存储(零数据保留工作流) 需要无状态执行的自定义 REST 自动化测试框架
Google Gen AI SDK 自动继续(推荐) GenerateContent (v1beta1) Google Gen AI SDK:Python (>= 2.30.1)、JavaScript/TypeScript (>= 2.29.1)、Go (>= 1.74.0)、Java (>= 1.77.0)、.NET (>= 1.26.0) 和 Kotlin (>= 1.6.0) 最多 65,536 (generate_content_stream) 或 32,768 (generate_content) 每个片段 20 分钟 无服务器存储(零数据保留工作流) 现有 GenerateContent 应用
自定义延续循环 GenerateContent (v1beta1) 您的代码(原始 contents + continuation_token) 最多 65,536 个(streamGenerateContent,在 32,768 个之后,每 5,000 个 token 设置一个检查点)或 32,768 个(generateContent) 每个片段 20 分钟 无服务器存储(零数据保留工作流) 直接 REST GenerateContent 调用方和评估工具

API 版本和 SDK 要求

长解码需要以下 API 版本和最低 SDK 版本:

  • v1beta1 API 要求(已知问题):Interactions API 和 GenerateContent(generateContent 和 streamGenerateContent)上的长解码 (continuation_token) 仅在 Agent Platform 上的 v1beta1 API(而非 v1)中受支持。 Google Gen AI SDK 默认使用 v1beta1,除非在 http_options(或 interactions.create 上的 api_version="v1")中指定了 api_version='v1';对于直接 REST 调用,请使用 /v1beta1/ 端点路径。
  • SDK 版本和 OpenAI 兼容性:如需在 Interactions API 上自动继续,请升级到 Python google-genai >= 2.34.0、JavaScript/TypeScript @google/genai >= 2.32.0、Go >= 1.77.0 或 Java >= 1.80.0(对于 Interactions API 上的其他语言,请直接使用 background=true 或自定义继续循环调用 REST API)。如需在 GenerateContent 上自动继续使用,请升级到 Python >= 2.30.1、JavaScript/TypeScript >= 2.29.1、Go >= 1.74.0、Java >= 1.77.0、.NET >= 1.26.0 或 Kotlin >= 1.6.0。旧版 SDK 和 OpenAI 兼容性层无法使用延续令牌检索长补全。

Interactions API 延续规则

以下状态转换、链式规则和存储行为适用于 Interactions API 上的长解码。

状态值和输出 token 预算

如果在 Interactions API 请求中省略 generation_config.max_output_tokens,则总输出预算默认为 65,536 个 token(因此,非流式调用会在 32,768 个 token 处停止,并显示 status="requires_continuation",而第二个片段可以生成剩余的 32,768 个 token)。将 generation_config.max_output_tokens 设置为最多 1,048,576(减去输入词元),以便在前台和 background=true 模式下进行更长的解码。服务器会返回以下状态值:

  • requires_continuation:在 max_output_tokens 之前已达到每个片段的输出限制(32,768 个非流式或 65,536 个流式);在下一个请求中传递返回的 continuation_token 以继续解码。
  • incomplete:总 max_output_tokens 预算已用尽;在不提高 max_output_tokens 的情况下继续使用 continuation_token 会返回 HTTP 400 错误 (max_output_tokens has already been exhausted)。在下一个请求中增加 max_output_tokens 以恢复解码。
  • completed:生成自然完成,continuation_token 已清除。

链式执行、模式切换和片段存储

Interactions API 上的延续请求会强制执行以下规则:

  • 存储的延续(store=true,默认):将 previous_interaction_id 传递给发出 continuation_token 的片段 id,同时传递 continuation_token,并省略 input(存储的片段已包含轮次输入)。始终将每个 continuation_token 与发出该令牌的片段的 previous_interaction_id 配对;在已 completed 的互动中传递 continuation_token 会返回 HTTP 400 错误。
  • 无状态延续 (store=false):省略 previous_interaction_id,并在每个片段中重新发送原始 input 以及 continuation_token。
  • 在不同片段之间切换 store 模式:您可以在解码过程中从存储模式 (store=true) 切换到无状态模式 (store=false),方法是省略 previous_interaction_id 并使用 continuation_token 重新发送原始 input。不支持从无状态 (store=false) 切换到存储 (store=true),因为 previous_interaction_id 不存在存储的父级互动。
  • 前台和 background=true 模式切换和分支:存储的延续 (store=true) 可以在前台 (background=false) 和后台 (background=true) 执行之间切换,包括从其检查点 continuation_token(在 32,768 个输出 token 后持久化)在前台或后台模式下恢复已取消的 background=true 交互。重复使用相同的 previous_interaction_id 和 continuation_token 会创建独立的分支延续。
  • 轮次边界强制执行:如果从状态为 requires_continuation 或 incomplete 的片段开始新的用户轮次(previous_interaction_id 具有新的 input 且没有 continuation_token),则会返回 HTTP 400 错误。完成对 completed 的继续解码,或从最近的 completed 互动中分支您的下一轮对话。当最后一个片段达到 completed 时,将该片段的 id 作为 previous_interaction_id 传递,即可重构所有先前片段的完整对话历史记录。
  • 各片段之间的参数一致性:在延续片段上更改 model、system_instruction 或函数声明 (tools) 会返回 HTTP 400 错误。在各个细分受众群中,thinking_level 和内置工具也保持不变(请参阅已知问题)。
  • 单段 get、list 和 delete 行为:在前台模式 (background=false) 下,每个段都存储为单独的 Interaction 资源(interactions.get(id) 仅返回该段,interactions.list() 分别列出每个段,interactions.delete(id) 仅删除该段;删除段链时,请按从最后一个段向前的相反顺序删除)。在采用 automatic_continuation=True (stream=False) 的 Google Gen AI SDK 中,interactions.create() 会在返回时合并所有片段,并使用有序片段 ID(以 interaction.id 结尾)填充 interaction.continuation_ids。如果后续片段失败、超出每次调用的数字 timeout,或在超过可恢复检查点后中途断开,SDK 会引发 ContinuationInterruptedError,其中包含 partial_interaction、continuation_token、interaction_id 和 continuation_ids,以便您从 continuation_token 恢复。

GenerateContent 自定义循环规则

在自定义 GenerateContent 延续循环中,请遵循以下规则:

  • 将 max_output_tokens 设置为大于 65,536(流式传输)或 32,768(非流式传输),最高可达 1,048,576,并在每个后续请求中重新发送原始 contents、system_instruction 和 tools,以及最新的 continuation_token(REST 中 GenerateContentRequest 的顶级字段,或 Google Gen AI SDK 中 GenerateContentConfig 的顶级字段)。
  • 请勿将部分模型输出附加到 contents 中,也不要发送后续提示要求模型继续。
  • 只要 finish_reason 为 CONTINUATION 且存在 continuation_token,就继续循环,即使某个片段在思考 (parts: [{"text": ""}]) 上用完了所有 32,768 或 65,536 个 token 也是如此。如果存在 continuation_token 时 finish_reason 为 MAX_TOKENS,请在下一个请求中提高 max_output_tokens。
  • 仅在 STOP 之后,将累积的部分合并为多轮对话历史记录中的单个 model 轮次。

词元计数、压缩和隐式缓存

跨延续片段的 token 统计和缓存工作原理如下:

  • 在 Interactions API 上,使用 automatic_continuation=True 的非流式 interactions.create() 调用和服务器管理的 background=true 互动会汇总 usage(total_input_tokens、total_cached_tokens、total_output_tokens、total_thought_tokens、total_tokens)中所有片段的 token 数量,并在 usage.initial_input_tokens 中保留第一个片段的提示数量。在自定义前台循环和流式 interaction.completed 事件中,每个片段的 usage 仅报告该片段的增量,因此需要将各个片段的 usage 字段相加,才能得出计费 token 总数。
  • 在 GenerateContent 上,Python Google Gen AI SDK(generate_content 和 generate_content_stream)会在最终的 usage_metadata 中累加各片段的总计费 token 数,并保留 initial_prompt_token_count。在自定义 REST 循环中,对各细分受众群的最终 prompt_token_count、cached_content_token_count、candidates_token_count 和 thoughts_token_count 求和。
  • 由于每个前台延续片段都会重新预填充对话和之前生成的词元作为输入,因此 usage.total_input_tokens(在 Interactions API 上)和 prompt_token_count(在 GenerateContent 上)会跨片段增加。请勿使用累积输入计数来触发智能体 Harness 中的上下文压缩;而是应检查 usage.initial_input_tokens(或 GenerateContent 上的 initial_prompt_token_count),并且仅在轮次结束后(status="completed" 或没有 continuation_token)进行压缩。
  • 每个后续片段都会重新预填充提示以及之前解码的 token,并且在片段连续运行时自动符合隐式上下文缓存(至少 4,096 个 token,默认启用持久缓存)的条件。已完成的片段会在每个片段结束时计费,即使后续片段失败或被取消也是如此。

从 3.1 Pro 迁移到 4 Carbon

以下行为与 gemini-3.1-pro-preview 不同:

  • 4 Carbon 的输入和输出(其中输出包括思考、函数调用和最终回答)共用一个 1,048,576 个词元的统一限制,而不是分别设置输入和输出限制。单个前台片段在流式传输时上限为 65,536 个 token(非流式传输时为 32,768 个 token),并且可以使用 Interactions API 或 GenerateContent 上的长解码将输出扩展到最多 1,048,576 个 token(在 Google Gen AI SDK 中自动处理,在 Interactions API 上使用 background=true,或在自定义循环中使用 continuation_token)。
  • thinking_budget 会返回 HTTP 400 错误,而不是映射到思考级别。MINIMAL 也会返回错误。
  • 不支持显式上下文缓存。
  • 模型处理的每个 token 都会计费,包括使用接地时的内部工具系统指令和函数声明。

如需进行对照比较,请参阅从 Gemini 3.1 Pro 迁移。

 client = genai.Client(
     enterprise=True,
     project="PROJECT_ID",
     location="global", # Supports "global", "us", and "eu" ("global" and "us" for cyber)
 )

 response = client.models.generate_content(
-    model="gemini-3.1-pro-preview",
+    model="gemini-4-carbon",
     contents=prompt,
     config=types.GenerateContentConfig(
-        temperature=0.0,
-        cached_content="projects/.../cachedContents/...", # Explicit caching unsupported
         thinking_config=types.ThinkingConfig(
-            thinking_budget=16384, # Returns HTTP 400 instead of mapping silently
-            thinking_level="MINIMAL", # MINIMAL unsupported on Gemini 4 Carbon
+            thinking_level="MEDIUM", # Valid: "LOW", "MEDIUM" (default), "HIGH"
         ),
     ),
 )

如需从 gemini-3.1-pro-preview 迁移,请执行以下操作:

  1. 将模型 ID 更新为 gemini-4-carbon(或 gemini-4-carbon-cyber-permissive,适用于通过 Fairwind 计划批准的网络安全工作负载)。
  2. 升级到最新的 Google Gen AI SDK,并考虑统一的输入和输出 token 限制:升级到 google-genai >= 2.34.0 (Python)、@google/genai >= 2.32.0 (JavaScript/TypeScript)、Go >= 1.77.0 或 Java >= 1.80.0,以实现 Interactions API 自动延续(或 GenerateContent 上的 >= 2.30.1 Python / >= 2.29.1 JavaScript)。输入和输出 token(包括思考和函数调用)共享 1,048,576 个 token 的统一限制。对于 Interactions API 或 GenerateContent 上超过 65,536 个 token(最多 1,048,576 个 token)的输出,请将 max_output_tokens 设置为大于 65,536,以便 Google Gen AI SDK 自动跨片段继续(或使用 background=true 或自定义 continuation_token 循环)。
  3. 替换推理预算参数:将 thinking_budget 和 MINIMAL 替换为 thinking_level,并将其设置为 LOW、MEDIUM(gemini-4-carbon 上的默认值)或 HIGH(gemini-4-carbon-cyber-permissive 上的默认值)(在 Interactions API 上使用小写 "low"、"medium" 或 "high")。
  4. 移除显式缓存,并预先加载静态提示内容(4,096 个或更多 token),以便进行自动隐式缓存。
  5. 移除无效或不受支持的参数:移除被忽略和被拒绝的生成字段,如下所示:
    • 移除 temperature、top_p 和 top_k,这些参数会被忽略。
    • 移除 frequency_penalty、presence_penalty 以及任何大于 1 的 candidate_count 值。
    • 从对话记录中移除所有预填模型轮次。

面向开发者的核对清单摘要

请使用以下核对清单来验证您的 4 Carbon 集成:

已知问题

以下已知问题适用于 4 Carbon 长解码:

  • 长解码需要 v1beta1:Interactions API 和 GenerateContent API(generateContent 和 streamGenerateContent)上的长解码 (continuation_token) 仅在 Agent Platform 上的 v1beta1 API(而非 v1)中受支持。Google Gen AI SDK 默认使用 v1beta1,除非在 http_options(或 interactions.create 上的 api_version="v1")中设置了 api_version='v1';对于直接 REST 调用,请使用 /v1beta1/ 端点路径。
  • Interactions API 延续片段之间的参数更改:在延续片段之间更改 model、system_instruction 或函数声明会返回 HTTP 400 错误,而在解码过程中对 generation_config.thinking_level 或内置工具(google_search、code_execution、url_context)进行的更改不会被服务器验证拒绝。在延续循环的所有片段中,保持 thinking_level 和内置工具不变。

其他资源

如需详细了解 4 Carbon,请参阅以下资源: