# Live API 中的思考能力

Gemini Live API 可与 Gemini 型号进行实时双向语音对话。

标准语音模型非常适合即时来回对话。您与模型交谈，它会立即生成语音回复。但是，当请求需要规划、复杂分析或外部工具时，直接响应就会达到极限。模型必须要么不带推理地回答，要么在等待工具完成时静静地暂停。

Live API 中的思考（`gemini-3.8-live-extended-thinking`）为实时语音会话添加背景推理。该模型在后台计划和调用异步工具，同时说出自然的对话填充物以保持交互活跃。

该架构通过两个关键方式改变了对话生命周期：

- **对话填充物**：模型在后台执行工具时会说出中间更新（例如“立即检查航班选项”）。
- **交互状态追踪**：由于模型可以在单个请求期间多次说话，因此服务器会发出 `interaction_status: "IN_PROGRESS"` 在后台处理期间和 `interaction_status: "IDLE"`
  当整体任务完成时。

下图比较了标准实时语音会话和带有背景推理的 Thinking 之间的交互生命周期：

![](https://www.gstatic.com/cloud-cms/d358052eb48e0aed4b9d7b95d66c61c0.svg)

## 选择正确的型号  {% #choosing-a-model %}

当在两者之间做出决定时 `gemini-3.8-live` 和 `gemini-3.8-live-extended-thinking`，权衡三个主要考虑因素：响应延迟、任务复杂性和客户端状态处理。

### 何时使用 Gemini 3.8 Live  {% #when-to-use-live %}

使用 `gemini-3.8-live` 适用于低延迟对话语音智能体，其中立即轮流至关重要并且任务是直接的。

- **对话式语音助手**：客户服务分类、语言练习、语音搜索和互动讲故事。
- **快速工具执行**：外部工具在几毫秒内返回的工作流程（例如读取传感器值或控制智能设备）。
- **简单的客户端逻辑**：每个用户轮流接收单个模型响应的应用程序，以及 `turnComplete: true` 当会话空闲时可靠地发出信号。

### 何时使用 Gemini 3.8 Live Extended Thinking  {% #when-to-use-thinking %}

使用 `gemini-3.8-live-extended-thinking` 当您的智能体必须评估复杂数据、规划多个步骤或处理需要几秒钟运行的工具时。

- **多步骤诊断和支持**：技术支持智能体通过多个日志、错误代码和配置检查诊断系统问题。
- **协调数据检索**：旅行和预订智能体，可通过并行 API 呼叫搜索航班、查询酒店并比较价格。
- **STEM 和代码辅导**：教育智能体，用于在进行解释之前验证公式、调试代码或完成多步骤逻辑。
- **屏蔽工具延迟**：语音体验，否则长时间运行的函数会给听者带来尴尬的沉默。

### 主要差异总结  {% #key-differences %}

下表总结了两种型号之间的技术差异：

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
特点
{% /doc-cell %}

{% doc-cell %}
Gemini 3.8 Live
{% /doc-cell %}

{% doc-cell %}
Gemini 3.8 Live Extended Thinking
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**主要用例**
{% /doc-cell %}

{% doc-cell %}
低延迟语音智能体，直接命令，快速工具
{% /doc-cell %}

{% doc-cell %}
多步骤问题解决、复杂规划、多工具工作流程
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**模型端点**
{% /doc-cell %}

{% doc-cell %}
`gemini-3.8-live`
{% /doc-cell %}

{% doc-cell %}
`gemini-3.8-live-extended-thinking`
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**推理架构**
{% /doc-cell %}

{% doc-cell %}
具有固定延迟配置文件的交错推理（`thinking_level` 不支持）
{% /doc-cell %}

{% doc-cell %}
可配置的后台推理（`thinking_level`: `low`, `medium`, `high`; `MINIMAL` 不支持）
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**转弯边界**
{% /doc-cell %}

{% doc-cell %}
`turnComplete: true` 关闭转弯并返回空闲状态
{% /doc-cell %}

{% doc-cell %}
`turnComplete: true` 完成一个话语； `interaction_status` 控制会话生命周期
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**对话填充物**
{% /doc-cell %}

{% doc-cell %}
模型在说话之前等待工具执行
{% /doc-cell %}

{% doc-cell %}
模型在处理时流中间会话填充符
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
**工具执行**
{% /doc-cell %}

{% doc-cell %}
支持同步（`BLOCKING`) 和异步 (`NON_BLOCKING`) 工具
{% /doc-cell %}

{% doc-cell %}
需要异步（`NON_BLOCKING`) 工具声明
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

## 迁移和集成路径  {% #migration-paths %}

请按照以下步骤升级现有语音应用程序或将 Thinking 集成到您的 Live API 会话中。

### 从 Gemini 3.1 Flash Live 升级  {% #upgrading-from-31 %}

对于现有的语音应用程序使用 `gemini-3.1-flash-live-preview`，升级到 `gemini-3.8-live` 需要更新模型字符串并省略 `thinking_level` （或 `thinking_config`) 从您的设置配置中，如 `thinking_level` 不支持 `gemini-3.8-live`:

```json
{
  "setup": {
    "model": "models/gemini-3.8-live"
  }
}
```

回合生命周期和 `turnComplete` 信号保持相同。

### 采用思维  {% #adopting-thinking %}

采纳 `gemini-3.8-live-extended-thinking`，更新三个集成点：

1. **轨道 `interaction_status` 而不是 `turnComplete`**：在思考会话中，模型可以在推理时发出中间会话填充物。检查 `interaction_status` 传入服务器消息上的字段来管理 UI 状态。仅在以下情况下返回空闲状态： `interaction_status`
   是 `IDLE`.

{% tabs %}
{% tab label="Python" %}
```python
status = getattr(message, "interaction_status", None)
if status == "IDLE":
    # Ready for user input
    set_ui_state("listening")
elif status == "IN_PROGRESS":
    # Reasoning or executing tools
    set_ui_state("thinking")
```
{% /tab %}

{% tab label="JavaScript" %}
```js
if (message.interactionStatus === 'IDLE') {
  // Ready for user input
  setUiState('listening');
} else if (message.interactionStatus === 'IN_PROGRESS') {
  // Reasoning or executing tools
  setUiState('thinking');
}
```
{% /tab %}
{% /tabs %}

1. **声明非阻塞函数**：设定 `"behavior": "NON_BLOCKING"` 在所有函数声明上。思维模型在后台异步运行工具，同时传输口头更新。同步阻塞工具返回错误。

{% tabs %}
{% tab label="Python" %}
```python
search_flights = types.FunctionDeclaration(
    name="search_flights",
    description="Searches for available flights.",
    behavior="NON_BLOCKING",
    parameters={
        "type": "OBJECT",
        "properties": {
            "destination": {"type": "STRING"},
        },
        "required": ["destination"],
    },
)
```
{% /tab %}

{% tab label="JavaScript" %}
```js
const searchFlights = {
  name: 'search_flights',
  description: 'Searches for available flights.',
  behavior: 'NON_BLOCKING',
  parameters: {
    type: 'OBJECT',
    properties: {
      destination: { type: 'STRING' },
    },
    required: ['destination'],
  },
};
```
{% /tab %}
{% /tabs %}

1. **配置推理深度**：设定 `thinking_config` 在您的会话配置中调整推理级别（`low`, `medium`, 或 `high`; `MINIMAL` 不支持）。

{% tabs %}
{% tab label="Python" %}
```python
config = types.LiveConnectConfig(
    response_modalities=["AUDIO"],
    thinking_config=types.ThinkingConfig(
        thinking_level="low",
    ),
    tools=[types.Tool(function_declarations=[search_flights])],
)
```
{% /tab %}

{% tab label="JavaScript" %}
```js
const config = {
  responseModalities: [Modality.AUDIO],
  thinkingConfig: {
    thinkingLevel: 'low',
  },
  tools: [{ functionDeclarations: [searchFlights] }],
};
```
{% /tab %}
{% /tabs %}

## 协议并排比较  {% #protocol-comparison %}

本节比较 Live API 会话的每个阶段期间交换的 WebSocket 消息。

### 步骤 1：会话设置  {% #step-1-setup %}

两种型号都连接到相同的 WebSocket 端点：

```text
wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContent?key=$API_KEY
```

- **相同**：WebSocket URL 和 API 密钥身份验证。
- **模型串**: `gemini-3.8-live` 与 `gemini-3.8-live-extended-thinking`.
- **思维配置**: 思考补充 `thinkingConfig` 调整推理深度。
- **工具行为**: 思考需要 `"behavior": "NON_BLOCKING"` 关于函数声明。

{% tabs %}
{% tab label="Gemini 3.8 Live" %}
```json
{
  "setup": {
    "model": "models/gemini-3.8-live",
    "generationConfig": {
      "responseModalities": ["AUDIO"],
      "speechConfig": {
        "voiceConfig": {
          "prebuiltVoiceConfig": {
            "voiceName": "Puck"
          }
        }
      }
    }
  }
}
```
{% /tab %}

{% tab label="Gemini 3.8 Live Extended Thinking" %}
```json
{
  "setup": {
    "model": "models/gemini-3.8-live-extended-thinking",
    "generationConfig": {
      "responseModalities": ["AUDIO"],
      "speechConfig": {
        "voiceConfig": {
          "prebuiltVoiceConfig": {
            "voiceName": "Puck"
          }
        }
      },
      "thinkingConfig": {
        "thinkingLevel": "LOW"
      }
    },
    "tools": [{
      "functionDeclarations": [{
        "name": "searchFlights",
        "description": "Searches for flights between cities.",
        "behavior": "NON_BLOCKING",
        "parameters": {
          "type": "OBJECT",
          "properties": {
            "destination": { "type": "STRING" }
          },
          "required": ["destination"]
        }
      }]
    }]
  }
}
```
{% /tab %}
{% /tabs %}

两种模型在连接时都会收到相同的服务器确认：

```json
{
  "setupComplete": {}
}
```

### 步骤 2：用户音频输入  {% #step-2-user-input %}

两种型号的音频流是相同的。实时 16kHz 原始 PCM 音频块使用流式传输 `realtimeInput`:

```json
{
  "realtimeInput": {
    "audio": {
      "data": "UklGRiQAAABXQVZF...",
      "mimeType": "audio/pcm;rate=16000"
    }
  }
}
```

### 步骤 3：模型响应和状态生命周期  {% #step-3-model-response %}

两种型号均以流式传输 24kHz PCM 音频块 `serverContent.modelTurn`。然而，生命周期管理有所不同：

#### Gemini 3.8 Live响应流程

1. 服务器流式传输该回合的音频块。
1. 服务器发送 `turnComplete: true`，表示模型已完成讲话并且会话处于空闲状态。

```json
// 1. Audio stream chunks
{
  "serverContent": {
    "modelTurn": {
      "parts": [
        {
          "inlineData": {
            "mimeType": "audio/pcm;rate=24000",
            "data": "..."
          }
        }
      ]
    }
  }
}

// 2. Turn completion -> Signals client to switch UI to Idle/Listening
{
  "serverContent": {
    "turnComplete": true
  }
}
```

#### Gemini 3.8 Live Extended Thinking响应流程

1. **口语填充物**：模型发出中间语音（例如 *“正在检查飞往西雅图的航班……”*）与 `turnComplete: true` 和 `interactionStatus: "IN_PROGRESS"`.
1. **异步工具调用**：服务器发出工具调用，同时 `interactionStatus` 遗骸 `"IN_PROGRESS"`，表示服务器正在主动处理多步转弯，等待工具响应。
1. **工具响应**：客户端执行函数并返回输出。
1. **最终回应**：服务器提供完整的答案 `turnComplete: true` 和 `interactionStatus: "IDLE"`.

```json
// 1. Spoken verbal filler while background reasoning proceeds
{
  "serverContent": {
    "modelTurn": {
      "parts": [
        {
          "inlineData": {
            "mimeType": "audio/pcm;rate=24000",
            "data": "..."
          }
        }
      ]
    },
    "turnComplete": true,
    "interactionStatus": "IN_PROGRESS"
  }
}

// 2. Asynchronous tool call emitted with IN_PROGRESS status
{
  "toolCall": {
    "functionCalls": [
      {
        "id": "call_123",
        "name": "searchFlights",
        "args": {
          "destination": "Seattle"
        }
      }
    ]
  },
  "interactionStatus": "IN_PROGRESS"
}

// 3. Client executes function and returns result
{
  "toolResponse": {
    "functionResponses": [
      {
        "response": {
          "output": {
            "flight": "DL 145",
            "price": "$145"
          }
        },
        "id": "call_123"
      }
    ]
  }
}

// 4. Final spoken answer delivered -> session transitions to IDLE when done
{
  "serverContent": {
    "modelTurn": {
      "parts": [
        {
          "inlineData": {
            "mimeType": "audio/pcm;rate=24000",
            "data": "..."
          }
        }
      ]
    },
    "interactionStatus": "IDLE",
    "turnComplete": true
  }
}
```

## SDK实现示例  {% #sdk-examples %}

以下示例展示了如何配置Thinking和处理 `interaction_status` 使用 Google GenAI SDK。

{% tabs %}
{% tab label="Python" %}
```python
import asyncio
from google import genai
from google.genai import types

client = genai.Client(http_options={"api_version": "v1beta"})
model = "gemini-3.8-live-extended-thinking"

# Define non-blocking function declaration
search_flights = types.FunctionDeclaration(
    name="search_flights",
    description="Searches for available flights to a destination.",
    behavior="NON_BLOCKING",
    parameters={
        "type": "OBJECT",
        "properties": {
            "destination": {"type": "STRING"}
        },
        "required": ["destination"]
    }
)

config = types.LiveConnectConfig(
    response_modalities=["AUDIO"],
    thinking_config=types.ThinkingConfig(
        thinking_level="low"
    ),
    tools=[types.Tool(function_declarations=[search_flights])]
)

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        print("Session connected with Thinking")

        async for message in session.receive():
            # Inspect interaction status for server lifecycle tracking
            status = getattr(message, "interaction_status", None)
            if status:
                print(f"Interaction status: {status}")

            # Handle audio output parts
            if message.server_content and message.server_content.model_turn:
                for part in message.server_content.model_turn.parts:
                    if part.inline_data:
                        # Process 24kHz audio chunk
                        pass

            # Handle asynchronous tool call
            if message.tool_call:
                for call in message.tool_call.function_calls:
                    print(f"Executing tool: {call.name}")
                    # Simulate function execution
                    response = types.FunctionResponse(
                        id=call.id,
                        name=call.name,
                        response={"result": "Flight DL 145 ($145)"}
                    )
                    await session.send_tool_response(
                        function_responses=[response]
                    )

            # Status is IDLE when reasoning and all turns are complete
            if status == "IDLE":
                print("Session is idle and ready for user input.")

if __name__ == "__main__":
    asyncio.run(main())
```
{% /tab %}

{% tab label="JavaScript" %}
```js
import { GoogleGenAI, Modality } from '@google/genai';

const ai = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });
const model = 'gemini-3.8-live-extended-thinking';

const searchFlights = {
  name: 'search_flights',
  description: 'Searches for available flights to a destination.',
  behavior: 'NON_BLOCKING',
  parameters: {
    type: 'OBJECT',
    properties: {
      destination: { type: 'STRING' }
    },
    required: ['destination']
  }
};

const config = {
  responseModalities: [Modality.AUDIO],
  thinkingConfig: {
    thinkingLevel: 'low'
  },
  tools: [{ functionDeclarations: [searchFlights] }]
};

async function main() {
  const session = await ai.live.connect({
    model: model,
    config: config,
    callbacks: {
      onopen: () => console.log('Session connected'),
      onmessage: async (event) => {
        const message = JSON.parse(event.data);

        if (message.interactionStatus) {
          console.log(`Interaction status: ${message.interactionStatus}`);
        }

        if (message.toolCall) {
          for (const call of message.toolCall.functionCalls) {
            console.log(`Executing tool: ${call.name}`);
            session.sendToolResponse({
              functionResponses: [{
                id: call.id,
                name: call.name,
                response: { result: 'Flight DL 145 ($145)' }
              }]
            });
          }
        }

        if (message.interactionStatus === 'IDLE') {
          console.log('Session is idle and waiting for input.');
        }
      }
    }
  });
}

main();
```
{% /tab %}
{% /tabs %}

## 后续步骤  {% #whats-next %}

- 阅读 [Gemini 3.8 Live](/docs/models/gemini-3.8-live) 和 [Gemini 3.8 Live Extended Thinking](/docs/models/gemini-3.8-live-extended-thinking) 模型页面。
- 检查 [型号对比](/docs/live-api/capabilities#model-comparison) 表中列出了所有 Live API 型号的详细功能比较。
- 了解有关函数调用的更多信息 [Live API 工具使用](/docs/live-api/tools)
  指导。
- 评论 [会话管理](/docs/live-api/session-management) 处理会话恢复和上下文生命周期。
