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 具備下列功能:

  • 統一輸入和輸出詞元限制:4 Carbon 的統一詞元限制為 1,048,576 個,包含輸入和輸出詞元 (輸出包含思考、函式呼叫和最終回覆)。
  • 解碼長度最多可達 1,048,576 個詞元:4 Carbon 可在 Interactions API 和 GenerateContent (v1beta1) 上,將生成內容延伸至單一前景區隔 (串流時為 65,536 個詞元,非串流時為 32,768 個詞元) 以外,最多可達 1,048,576 個詞元 (扣除輸入詞元)。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 個以上詞元的共用提示詞前置字串,且預設會啟用永久快取。不支援明確脈絡快取。
  • Office 和 OpenDocument 檔案輸入:除了 PDF 和純文字,4 Carbon 也接受 Microsoft Office (.docx、.dotx、.doc、.pptx、.ppt、.xlsx、.xls) 和 OpenDocument (.odt、.odp、.ods) 檔案,可透過 GenerateContent 和 Interactions API 內嵌或從 Cloud Storage 匯入。
  • 代理式影片解讀:代理式影片解讀功能已正式發布,預設為關閉。

快速入門導覽課程

開始之前,您必須使用應用程式預設憑證 (ADC) 或 API 金鑰,向 Gemini Enterprise Agent Platform 驗證身分。詳情請參閱「開始使用 Agent Platform」。

在下列程式碼區塊中,將 PROJECT_ID 替換為您的專案 ID。

在 Agent Studio 試用

如要在 Agent Studio UI 中測試提示並設定 gemini-4-carbon,請按照下列步驟操作:

  1. 在 Cloud de Confiance by S3NS 專案中開啟 Agent Studio,然後選取 Gemini 群組下方的「gemini-4-carbon」。
  2. 在「模型設定」中,設定下列選項:
    • 思考程度:選擇 Low、Medium (預設) 或 High。
    • 區域:選取 Global、us 或 eu。
    • 輸出詞元限制:設為 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 個詞元的補全內容 (扣除輸入詞元),請在 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 分類、摘要和中繼資料擷取。

詞元數量上限、快取和計費

4 Carbon 適用下列權杖、快取、媒體和計費規則:

  • 統一輸入和輸出詞元限制,以及預設輸出預算: 詞元預算和前景區隔限制的運作方式如下:
    • 模型的整體詞元限制為 1,048,576 個詞元,包括輸入和輸出詞元 (輸出內容包括思考、函式呼叫和最終回覆)。max_output_tokens 控制生成作業的輸出詞元上限 (最多為 1,048,576 減去輸入詞元);如果 max_output_tokens 大於 1,048,576,則會傳回 HTTP 400 錯誤。
    • 如果 GenerateContent 或 Interactions API 省略 max_output_tokens,預設總輸出預算 (思考、函式呼叫和回覆) 為 65,536 個詞元。由於單一前景區隔在串流時最多會產生 65,536 個詞元,非串流時則會產生 32,768 個詞元,因此 Google Gen AI SDK (v1beta1) 會在需要時,自動鏈結兩個 32,768 個詞元的區隔,而非串流 REST 要求則會在一個 32,768 個詞元的前景區隔後停止。在 Agent Studio 中,輸出詞元限制預設為 1,048,576,並會自動接續。
  • 長解碼:單一前景片段在串流時最多可產生 65,536 個輸出詞元,非串流時則可產生 32,768 個輸出詞元。如要將 Interactions API 或 GenerateContent (v1beta1) 的單輪輸出內容擴充至最多 1,048,576 個詞元 (扣除輸入詞元),請參閱「長解碼」。
  • 脈絡快取:不支援明確脈絡快取。隱含快取 (預設啟用永久快取) 會自動套用至 4,096 個以上詞元的共用提示前置字串,因此請將靜態內容放在提示開頭。
  • Office 和 OpenDocument 輸入內容:使用 GenerateContent 上的 inlineData 或 fileData,以及 Interactions API 上的 document 輸入內容 (包括工具結果),以內嵌方式或透過 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":設為啟用代理影片處理。
  • 詞元計數和計費:模型處理的每個詞元都會計入並計費,包括思考詞元、內部工具系統指令,以及使用基準化功能時的函式宣告。以 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 個輸出詞元,非串流區隔最多會生成 32,768 個輸出詞元,然後發出 finish_reason=CONTINUATION 和 continuation_token,直到 finish_reason=STOP 為止。在 Agent Studio 中,如果將輸出詞元限制設為 65,536 到 1,048,576 之間,系統會自動處理接續詞元。如需可執行的程式碼範例,請參閱長音訊解碼快速入門導覽課程範例。

使用長解碼的時機

大多數要求會在 65,536 個詞元的預設輸出預算內完成 (或透過 REST 傳送的單一 32,768 個詞元非串流前景區隔)。只有在單次回覆需要更多輸出內容時,才使用長解碼。長解碼可讓模型有更多空間進行推論,但不會讓答案變長 (使用 thinking_level 可控制推論深度)。

工作負載 要使用長解碼嗎? 原因
困難的數學、科學、研究和正式證明 是 模型最多可使用 65,536 個詞元,探索及檢查推論過程。
最困難的程式設計和代理式工作 是 部分工作需要超過 65,536 個詞元的思考和程式碼,才能在單一回覆中完成。大多數程式設計和代理工作都能在 65,536 個詞元內完成。
評估工具在輸出內容達到上限時停止 是 如果模型將整個 65,536 或 32,768 詞元要求用於思考,長解碼功能可避免答案遭到截斷。
對話、問答、摘要、分類和擷取 否 這些工作在 32,768 個詞元內就能完成。
要求固定長度,例如「寫一本 70 萬字的小說」 否 模型未遵循長度目標。
代理會多次呼叫工具,但每次呼叫的時間都很短 否 每回合都很短。每輪輸出內容過多,很快就會達到 1,048,576 個詞元的輸入和輸出總量上限。
提示詞接近 1,048,576 個詞元的輸入限制 否 輸出內容最多只能使用 1,048,576 個詞元減去輸入內容。
對延遲時間敏感的要求 否 Long Decode 則可執行數分鐘。

選擇接續選項

請根據 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 個詞元檢查一次) 或 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 個詞元檢查一次) 或 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 個詞元檢查一次) 或 32,768 個 (generateContent) 每段 20 分鐘 不儲存在伺服器 (零資料保留工作流程) 直接 REST GenerateContent 呼叫端和評估工具

API 版本和 SDK 規定

長解碼需要下列 API 版本和最低 SDK 版本:

  • v1beta1 API 需求 (已知問題):Interactions API 和 GenerateContent (generateContent 和 streamGenerateContent) 的長解碼 (continuation_token) 僅支援 Agent Platform 的 v1beta1 API (不支援 v1)。除非在 http_options (或 interactions.create 上的 api_version="v1") 中指定 api_version='v1',否則 Google Gen AI SDK 預設會使用 v1beta1;如果是直接 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 的長時間解碼。

狀態值和輸出詞元預算

如果在 Interactions API 要求中省略 generation_config.max_output_tokens,總輸出預算預設為 65,536 個詞元 (因此非串流呼叫會在 32,768 個詞元時停止,並顯示 status="requires_continuation",第二個區段則可生成剩餘的 32,768 個詞元)。在前景和 background=true 模式中,將 generation_config.max_output_tokens 設為 1,048,576 (減去輸入權杖) 以下的值,即可延長解碼時間。伺服器會傳回下列狀態值:

  • 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 的接續要求會強制執行下列規則:

  • Stored continuation (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 模式:您可以在解碼過程中,省略 previous_interaction_id 並重新傳送原始 input 和 continuation_token,從儲存模式 (store=true) 切換至無狀態模式 (store=false)。不支援從無狀態 (store=false) 切換至已儲存 (store=true),因為 previous_interaction_id 沒有已儲存的上層互動。
  • 前景和 background=true 模式切換與分支:儲存的接續 (store=true) 可以在前景 (background=false) 和背景 (background=true) 執行之間切換,包括從檢查點 continuation_token (在 32,768 個輸出權杖後保留) 恢復已取消的 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) 只會刪除該區隔;刪除區隔鏈時,請從最後一個區隔開始反向刪除)。在 Google Gen AI SDK 中,automatic_continuation=True (stream=False) 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 存在,即使某個區隔已用完所有 32,768 或 65,536 個思考詞元 (parts: [{"text": ""}]),仍會繼續迴圈。如果 continuation_token 存在時 finish_reason 為 MAX_TOKENS,請在下一個要求中提高 max_output_tokens。
  • 只有在 STOP 之後,才會將累積的部分合併為單一 model 輪,用於多輪對話記錄。

計算詞元數、壓縮和隱性快取

接續回覆區隔的詞元計算和快取方式如下:

  • 在 Interactions API 上,使用 automatic_continuation=True 的非串流 interactions.create() 呼叫和伺服器管理的 background=true 互動,會加總 usage 中所有區隔 (total_input_tokens、total_cached_tokens、total_output_tokens、total_thought_tokens、total_tokens) 的詞元數量,並保留 usage.initial_input_tokens 中第一個區隔的提示詞元數量。在自訂前景迴圈和串流 interaction.completed 事件中,每個區隔的 usage 只會回報該區隔的差異,因此請加總各區隔的 usage 欄位,取得計費權杖總數。
  • 在 GenerateContent,Python Google Gen AI SDK (generate_content 和 generate_content_stream) 會在最終 usage_metadata 累積各區隔的計費詞元總數,並保留 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) 會在各區隔中增加。請勿使用累積輸入計數觸發代理駕馭系統中的內容壓縮,而是應檢查 usage.initial_input_tokens (或 GenerateContent 上的 initial_prompt_token_count),並僅在回合結束後 (status="completed" 或沒有 continuation_token) 進行壓縮。
  • 每個接續片段都會重新預先填入提示和先前解碼的權杖,並在片段連續執行時,自動符合隱含脈絡快取的資格 (至少 4,096 個權杖,預設啟用永久快取)。即使後續區隔失敗或取消,系統仍會在每個區隔結束時,針對已完成的區隔收費。

從 3.1 Pro 遷移至 4 Carbon

以下行為與 gemini-3.1-pro-preview 不同:

  • 4 Carbon 的輸入和輸出內容 (包括思考、函式呼叫和最終回覆) 統一限制為 1,048,576 個詞元,而非分別限制。串流時,單一前景片段的詞元上限為 65,536 個 (非串流時為 32,768 個),而使用 Interactions API 或 GenerateContent 的長解碼功能,輸出內容最多可擴充至 1,048,576 個詞元 (在 Google Gen AI SDK 中自動處理,在 Interactions API 中使用 background=true,或在自訂迴圈中使用 continuation_token)。
  • thinking_budget 會傳回 HTTP 400 錯誤,而非對應至思考等級。MINIMAL 也會傳回錯誤。
  • 不支援明確脈絡快取。
  • 模型處理的每個詞元都會計費,包括使用基準化功能時,內部工具系統指令和函式宣告。

如要並排比較,請參閱「從 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 (如果網路安全工作負載已通過Fairwind 計畫核准,則為 gemini-4-carbon-cyber-permissive)。
  2. 升級至最新版 Google Gen AI SDK,並考量統一的輸入和輸出詞元限制:升級至 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)。輸入和輸出詞元 (包括思考和函式呼叫) 共用 1,048,576 個詞元的統一限制。如果 Interactions API 或 GenerateContent 的輸出內容超過 65,536 個詞元 (最多 1,048,576 個詞元),請將 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 個以上詞元),以便自動進行隱含快取。
  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,請參閱下列資源: