# 使用 Google GenAI SDK 快速入门 Gemini Live API

Gemini Live API 允许与 Gemini 模型进行实时双向交互，支持音频、视频和文本输入以及本机音频输出。本指南介绍了如何使用服务器上的 Google GenAI SDK 与 API 集成。

{% button
   href="https://aistudio.google.com/live"
   icon="mic"
   variant="primary" %}
尝试 Google AI Studio 中的 Live API
{% /button %}

{% button
   href="https://github.com/google-gemini/gemini-live-api-examples/tree/main/gemini-live-genai-python-sdk"
   icon="code"
   variant="primary" %}
从 GitHub 克隆示例应用程序
{% /button %}

{% button href="/docs/coding-agents" icon="terminal" variant="primary" %}
使用编码智能体技巧
{% /button %}

## 概览  {% #overview %}

Gemini Live API 使用 WebSocket 进行实时通信。的 `google-genai` SDK 提供了一个高级异步接口来管理这些连接。

关键概念：

* **会议**：与模型的持久连接。
* **配置**：设置模式（音频/文本）、语音和系统指令。
* **实时输入**：将音频和视频帧作为 blob 发送。

## 连接到 Live API  {% #connecting-to-the-live-api %}

与 API 密钥启动 Live API 会话：

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

client = genai.Client(api_key="YOUR_API_KEY", http_options={"api_version": "v1beta"})

model = "gemini-3.8-live"
config = {"response_modalities": ["AUDIO"]}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        print("Session started")
        # Send content...

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

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

const ai = new GoogleGenAI({ apiKey: "YOUR_API_KEY", httpOptions: { apiVersion: "v1beta" } });
const model = 'gemini-3.8-live';
const config = { responseModalities: [Modality.AUDIO] };

async function main() {

  const session = await ai.live.connect({
    model: model,
    callbacks: {
      onopen: function () {
        console.debug('Opened');
      },
      onmessage: function (message) {
        console.debug(message);
      },
      onerror: function (e) {
        console.debug('Error:', e.message);
      },
      onclose: function (e) {
        console.debug('Close:', e.reason);
      },
    },
    config: config,
  });

  console.debug("Session started");
  // Send content...

  session.close();
}

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

## 发送文本  {% #sending-text %}

可以使用发送文本 `send_realtime_input` （Python）或 `sendRealtimeInput`
（JavaScript）。

{% tabs %}
{% tab label="Python" %}
```python
await session.send_realtime_input(text="Hello, how are you?")
```
{% /tab %}

{% tab label="JavaScript" %}
```js
session.sendRealtimeInput({
  text: 'Hello, how are you?'
});
```
{% /tab %}
{% /tabs %}

## 发送音频  {% #sending-audio %}

音频需要作为原始 PCM 数据发送（原始 16 位 PCM 音频，16kHz，小端）。

{% tabs %}
{% tab label="Python" %}
```python
# Assuming 'chunk' is your raw PCM audio bytes
await session.send_realtime_input(
    audio=types.Blob(
        data=chunk,
        mime_type="audio/pcm;rate=16000"
    )
)
```
{% /tab %}

{% tab label="JavaScript" %}
```js
// Assuming 'chunk' is a Buffer of raw PCM audio
session.sendRealtimeInput({
  audio: {
    data: chunk.toString('base64'),
    mimeType: 'audio/pcm;rate=16000'
  }
});
```
{% /tab %}
{% /tabs %}

有关如何从客户端设备（例如浏览器）获取音频的示例，请参阅上的端到端示例 [GitHub](https://github.com/google-gemini/gemini-live-api-examples/blob/main/gemini-live-genai-python-sdk/frontend/media-handler.js#L31-L70).

## 发送视频  {% #sending-video %}

视频帧以特定帧速率（每秒最大 1 帧）作为单独图像（例如 JPEG 或 PNG）发送。

{% tabs %}
{% tab label="Python" %}
```python
# Assuming 'frame' is your JPEG-encoded image bytes
await session.send_realtime_input(
    video=types.Blob(
        data=frame,
        mime_type="image/jpeg"
    )
)
```
{% /tab %}

{% tab label="JavaScript" %}
```js
// Assuming 'frame' is a Buffer of JPEG-encoded image data
session.sendRealtimeInput({
  video: {
    data: frame.toString('base64'),
    mimeType: 'image/jpeg'
  }
});
```
{% /tab %}
{% /tabs %}

有关如何从客户端设备（例如浏览器）获取视频的示例，请参阅上的端到端示例 [GitHub](https://github.com/google-gemini/gemini-live-api-examples/blob/main/gemini-live-genai-python-sdk/frontend/media-handler.js#L84-L120).

## 接收音频  {% #receiving-audio %}

模型的音频响应作为数据块被接收。

{% tabs %}
{% tab label="Python" %}
```python
async for response in session.receive():
    if response.server_content and response.server_content.model_turn:
        for part in response.server_content.model_turn.parts:
            if part.inline_data:
                audio_data = part.inline_data.data
                # Process or play the audio data
```
{% /tab %}

{% tab label="JavaScript" %}
```js
// Inside the onmessage callback
const content = response.serverContent;
if (content?.modelTurn?.parts) {
  for (const part of content.modelTurn.parts) {
    if (part.inlineData) {
      const audioData = part.inlineData.data;
      // Process or play audioData (base64 encoded string)
    }
  }
}
```
{% /tab %}
{% /tabs %}

请参阅 GitHub 上的示例应用程序以了解如何 [在您的服务器上接收音频](https://github.com/google-gemini/gemini-live-api-examples/blob/main/gemini-live-genai-python-sdk/gemini_live.py#L86-L98) 和 [在浏览器中播放](https://github.com/google-gemini/gemini-live-api-examples/blob/main/gemini-live-genai-python-sdk/frontend/media-handler.js#L145-L174).

## 接收短信  {% #receiving-text %}

服务器内容中提供了用户输入和模型输出的转录。

{% tabs %}
{% tab label="Python" %}
```python
async for response in session.receive():
    content = response.server_content
    if content:
        if content.input_transcription:
            print(f"User: {content.input_transcription.text}")
        if content.output_transcription:
            print(f"Gemini: {content.output_transcription.text}")
```
{% /tab %}

{% tab label="JavaScript" %}
```js
// Inside the onmessage callback
const content = response.serverContent;
if (content?.inputTranscription) {
  console.log('User:', content.inputTranscription.text);
}
if (content?.outputTranscription) {
  console.log('Gemini:', content.outputTranscription.text);
}
```
{% /tab %}
{% /tabs %}

## 处理工具调用  {% #handling-tool-calls %}

API支持工具调用（函数调用）。当模型请求工具调用时，您必须执行该函数并发回响应。

{% tabs %}
{% tab label="Python" %}
```python
async for response in session.receive():
    if response.tool_call:
        function_responses = []
        for fc in response.tool_call.function_calls:
            # 1. Execute the function locally
            result = my_tool_function(**fc.args)

            # 2. Prepare the response
            function_responses.append(types.FunctionResponse(
                name=fc.name,
                id=fc.id,
                response={"result": result}
            ))

        # 3. Send the tool response back to the session
        await session.send_tool_response(function_responses=function_responses)
```
{% /tab %}

{% tab label="JavaScript" %}
```js
// Inside the onmessage callback
if (response.toolCall) {
  const functionResponses = [];
  for (const fc of response.toolCall.functionCalls) {
    const result = myToolFunction(fc.args);
    functionResponses.push({
      name: fc.name,
      id: fc.id,
      response: { result }
    });
  }
  session.sendToolResponse({ functionResponses });
}
```
{% /tab %}
{% /tabs %}

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

* 阅读完整的 Live API [功能](/docs/live-api/capabilities) 关键功能和配置指南；包括语音活动检测和本机音频功能。
* 阅读 [工具使用](/docs/live-api/tools) 指南了解如何将 Live API 与工具和函数调用集成。
* 阅读 [会话管理](/docs/live-api/session-management) 管理长时间运行的对话的指南。
* 阅读 [临时 token](/docs/live-api/ephemeral-tokens) 安全认证指南 [客户端到服务器](/docs/live-api#implementation-approach) 应用程序。
* 有关底层 WebSocket API 的更多信息，请参阅 [WebSocket API 参考](/api-reference/live).
