> ## AI Agent Context
> - Full documentation index: https://aistudio.google.com/llms.txt
> - Gemini Docs MCP server (consistent live info): https://gemini-api-docs-mcp.dev
> - Coding agent skills & setup guide: https://aistudio.google.com/docs/coding-agents.md

# Thinking in the Live API

The Gemini Live API enables real-time, bidirectional voice conversations with
Gemini models.

Standard voice models work well for immediate back-and-forth dialogue. You speak
to the model, and it generates a spoken reply right away. But when a request
requires planning, complex analysis, or external tools, direct responses hit a
limit. The model must either answer without reasoning or pause silently while
waiting for tools to finish.

Thinking in the Live API adds background reasoning to real-time voice sessions
on [`gemini-4-live`](/docs/models/gemini-4-live) (and legacy
`gemini-3.8-live-extended-thinking`). On `gemini-4-live`, the `thinking_level`
parameter selects the mode on a single unified endpoint:

-   **Fast default mode** (omit `thinking_level` or set `MINIMAL`): Lowest
    latency for immediate back-and-forth dialogue.
-   **Background reasoning mode** (`thinking_level` set to `LOW`, `MEDIUM`, or
    `HIGH`): The model plans and calls asynchronous tools in the background
    while speaking natural conversational updates to keep the interaction
    active.

Background reasoning changes the conversational lifecycle in two key ways:

-   **Conversational fillers**: The model speaks intermediate updates (such as
    "Checking flight options now") while executing tools in the background.
-   **Interaction status tracking**: Because the model can speak multiple times
    during a single request, the server emits `interaction_status:
    "IN_PROGRESS"` during background processing and `interaction_status: "IDLE"`
    when the overall task completes.

The following diagram compares the interaction lifecycles between standard Live
voice sessions and Thinking with background reasoning:

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

## Choosing the right thinking level  {% id="choosing-a-model" %}

When configuring [`gemini-4-live`](/docs/models/gemini-4-live), weigh three main
considerations: response latency, task complexity, and client state handling.

### When to use fast default mode (`MINIMAL` or omitted)  {% id="when-to-use-live" %}

Omit `thinking_level` or set `thinking_level="MINIMAL"` on `gemini-4-live` for
low-latency conversational voice agents where immediate turn-taking is essential
and tasks are direct.

-   **Conversational voice assistants**: Customer service triage, language
    practice, voice search, and interactive storytelling.
-   **Fast tool execution**: Workflows where external tools return within
    milliseconds (such as reading sensor values or controlling smart devices).
-   **Simple client logic**: Applications where each user turn receives a single
    model response, and `turnComplete: true` reliably signals when the session
    is idle.

### When to use deeper thinking (`LOW`, `MEDIUM`, or `HIGH`)  {% id="when-to-use-thinking" %}

Set `thinking_level` to `LOW`, `MEDIUM`, or `HIGH` on `gemini-4-live` when your
agent must evaluate complex data, plan multiple steps, or handle tools that
take several seconds to run.

-   **Multi-step diagnostics and support**: Technical support agents diagnosing
    system issues across multiple logs, error codes, and configuration checks.
-   **Coordinated data retrieval**: Travel and booking agents that search
    flights, query hotels, and compare prices across parallel API calls.
-   **STEM and code tutoring**: Educational agents that verify formulas, debug
    code, or work through multi-step logic before speaking an explanation.
-   **Masking tool latency**: Voice experiences where long-running functions
    would otherwise create awkward silence for the listener.

### Key differences summary  {% id="key-differences" %}

The following table summarizes the technical differences between the two
`gemini-4-live` modes:

{% table %}
  * Feature
  * Fast default mode (`MINIMAL` or omitted)
  * Deeper thinking mode (`LOW`, `MEDIUM`, `HIGH`)

  ---

  * **Primary use cases**
  * Low-latency voice agents, direct commands, fast tools
  * Multi-step problem solving, complex planning, multi-tool workflows

  ---

  * **Model endpoint**
  * `gemini-4-live`
  * `gemini-4-live`

  ---

  * **Reasoning configuration**
  * Omit `thinking_level` or set `MINIMAL`
  * Set `thinking_level` to `LOW`, `MEDIUM`, or `HIGH` (supports `include_thoughts`; `thinking_budget` and `XHIGH` are not supported)

  ---

  * **Turn boundaries**
  * `turnComplete: true` closes the turn and returns to idle
  * `turnComplete: true` finishes an utterance; `server_content.interaction_status` controls session lifecycle

  ---

  * **Conversational fillers**
  * Model responds directly without background thinking delays
  * Model streams intermediate conversational updates while processing

  ---

  * **Tool execution**
  * Supports synchronous (`BLOCKING`) and asynchronous (`NON_BLOCKING`) tools, plus function response scheduling
  * Requires asynchronous (`NON_BLOCKING`) tool declarations; `BLOCKING` calls and function response scheduling are not supported
{% /table %}

## Migration and integration paths  {% id="migration-paths" %}

Follow these steps to upgrade existing voice applications or enable Thinking in
your `gemini-4-live` sessions.

### Upgrading from Gemini 3.8 Live or 3.1 Flash Live  {% id="upgrading-from-31" %}

For existing voice applications using `gemini-3.8-live` or
`gemini-3.1-flash-live-preview`, update the model string to `gemini-4-live` and
omit `thinking_level` (or set `MINIMAL`) to keep the same fast turn lifecycle:

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

The turn lifecycle and `turnComplete` signals remain identical.

### Adopting Thinking  {% id="adopting-thinking" %}

To enable background reasoning on `gemini-4-live` (or migrate from
`gemini-3.8-live-extended-thinking`), update three integration points:

1.  **Track `server_content.interaction_status` instead of `turnComplete`**: In
    Thinking sessions, the model emits intermediate spoken updates while
    reasoning. Inspect `interaction_status` on `server_content` (sent alongside
    `turn_complete`) to manage UI state. Only return to idle when
    `interaction_status` is `IDLE`.

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

  {% /tab %}

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

  {% /tab %}

{% /tabs %}

1. **Declare non-blocking functions**: Set `"behavior": "NON_BLOCKING"` on all
   function declarations. Deeper thinking levels run tools asynchronously while
   streaming spoken updates. Synchronous `BLOCKING` tools and function response
   scheduling (`SILENT`, `WHEN_IDLE`, `INTERRUPT`) return an error.

{% 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" %}
  ```javascript
  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. **Configure reasoning depth**: Set `thinking_config` in your session
   configuration to adjust reasoning levels (`LOW`, `MEDIUM`, or `HIGH`). Omit
   `thinking_level` or set `MINIMAL` to stay in fast default mode.

{% 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" %}
  ```javascript
  const config = {
    responseModalities: [Modality.AUDIO],
    thinkingConfig: {
      thinkingLevel: 'low',
    },
    tools: [{ functionDeclarations: [searchFlights] }],
  };
  ```

  {% /tab %}

{% /tabs %}

## Protocol side-by-side comparison  {% id="protocol-comparison" %}

This section compares the WebSocket messages exchanged during each phase of a
Live API session.

### Step 1: Session setup  {% id="step-1-setup" %}

Both models connect to the same WebSocket endpoint:

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

-   **Identical**: WebSocket URL, API key authentication, and model string
    (`models/gemini-4-live`).
-   **Thinking configuration**: Adding `thinkingConfig` with `thinkingLevel` set
    to `LOW`, `MEDIUM`, or `HIGH` enables background reasoning.
-   **Tool behavior**: Deeper thinking levels require `"behavior":
    "NON_BLOCKING"` on function declarations.

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

  {% /tab %}

  {% tab label="Deeper thinking mode" %}
  ```json
  {
    "setup": {
      "model": "models/gemini-4-live",
      "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 %}

Both models receive the same server acknowledgment upon connection:

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

### Step 2: User audio input  {% id="step-2-user-input" %}

Audio streaming is identical across both models. Real-time 16kHz raw PCM audio
chunks are streamed using `realtimeInput`:

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

### Step 3: Model response and state lifecycle  {% id="step-3-model-response" %}

Both models stream 24kHz PCM audio chunks in `serverContent.modelTurn`. However,
lifecycle management differs:

#### Fast default mode response flow

1.  The server streams audio chunks for the turn.
2.  The server sends `turnComplete: true`, indicating the model is finished
    speaking and the session is idle.

```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
  }
}
```

#### Deeper thinking mode response flow

1.  **Spoken filler**: The model emits intermediate speech (such as *"Checking
    flights to Seattle..."*) with `turnComplete: true` and `interactionStatus:
    "IN_PROGRESS"`.
2.  **Asynchronous tool call**: The server emits the tool call while
    `interactionStatus` remains `"IN_PROGRESS"`, indicating that the server is
    actively processing the multi-step turn and waiting for the tool response.
3.  **Tool response**: The client executes the function and returns the output.
4.  **Final response**: The server delivers the complete answer with
    `turnComplete: true` and `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 while the interaction remains in progress
{
  "toolCall": {
    "functionCalls": [
      {
        "id": "call_123",
        "name": "searchFlights",
        "args": {
          "destination": "Seattle"
        }
      }
    ]
  }
}

// 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 implementation examples  {% id="sdk-examples" %}

The following examples show how to configure Thinking and handle
`interaction_status` using the 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-4-live"
  
  # 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 server_content.interaction_status for lifecycle tracking
              status = (
                  message.server_content.interaction_status
                  if message.server_content
                  else 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 == types.InteractionStatus.IDLE:
                  print("Session is idle and ready for user input.")
  
  if __name__ == "__main__":
      asyncio.run(main())
  ```

  {% /tab %}

  {% tab label="JavaScript" %}
  ```javascript
  import { GoogleGenAI, Modality } from '@google/genai';
  
  const ai = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });
  const model = 'gemini-4-live';
  
  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: (message) => {
          const status = message.serverContent?.interactionStatus;
          if (status) {
            console.log(`Interaction status: ${status}`);
          }
  
          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 (status === 'IDLE') {
            console.log('Session is idle and waiting for input.');
          }
        }
      }
    });
  }
  
  main();
  ```

  {% /tab %}

{% /tabs %}

## What's next  {% id="whats-next" %}

-   Read the [Gemini 4 Live](/docs/models/gemini-4-live) model page.
-   Check the [Model comparison](/docs/live-api/capabilities#model-comparison) table for detailed feature
    comparisons across all Live API models.
-   Learn more about function calling in the [Live API Tool use](/docs/live-api/tools)
    guide.
-   Review [Session management](/docs/live-api/session-management) to handle session resumption
    and context lifecycle.

