Get started with Live API

Live API 可讓您與 Gemini 進行低延遲的即時語音/視訊互動。這項服務會處理持續的音訊、影像或文字串流,提供即時且擬人的語音回應,為使用者打造自然的對話體驗。

Live API 總覽

Live API 提供一套完整的功能,例如 Voice Activity Detection工具使用和函式呼叫工作階段管理 (用於管理長時間執行的對話) 和暫時性權杖 (用於安全的用戶端驗證)。

本頁提供範例和基本程式碼範例,協助您快速上手。

應用程式範例

請參閱以下應用程式示例,瞭解如何將 Live API 用於端對端用途:

  • AI Studio 上的即時音訊啟動應用程式,使用 JavaScript 程式庫連線至 Live API,並透過麥克風和喇叭串流雙向音訊。
  • Live API Python 食譜,使用可連線至 Live API 的 Pyaudio。

與合作夥伴整合

如果您偏好簡單的開發程序,可以使用 DailyLiveKit。這些第三方合作夥伴平台已透過 WebRTC 通訊協定整合 Gemini Live API,以便簡化即時音訊和影像應用程式的開發作業。

開始建構前

開始使用 Live API 建構應用程式前,您必須做出兩項重要決策:選擇模型和實作方法。

選擇音訊產生架構

如果您要建構以音訊為主的用途,所選模型會決定用於建立音訊回應的音訊生成架構:

  • 原生音訊這個選項可提供最自然流暢的語音,並提供更佳的多語言效能。這項功能還可啟用進階功能,例如情感 (情緒感知) 對話主動音訊 (模型可決定是否忽略或回應特定輸入內容),以及「思考」。下列原生音訊模型支援原生音訊:
    • gemini-2.5-flash-preview-native-audio-dialog
    • gemini-2.5-flash-exp-native-audio-thinking-dialog
  • 半階層音訊:這個選項會使用階層模型架構 (原生音訊輸入和文字轉語音輸出)。在實際工作環境中,這項功能可提供更佳的效能和可靠性,尤其是在使用工具時。下列型號支援半階層音訊:
    • gemini-live-2.5-flash-preview
    • gemini-2.0-flash-live-001

選擇導入方法

整合 Live API 時,您必須選擇下列其中一種實作方式:

  • 伺服器對伺服器:後端會使用 WebSockets 連線至 Live API。通常,用戶端會將串流資料 (音訊、影像、文字) 傳送至伺服器,然後由伺服器轉送至 Live API。
  • 用戶端到伺服器:前端程式碼會使用 WebSockets 直接連線至 Live API,以便略過後端並串流資料。

開始使用

這個範例會讀取 WAV 檔案,以正確格式傳送,並將收到的資料儲存為 WAV 檔案。

您可以將音訊轉換為 16 位元 PCM、16 kHz 的單聲道格式,然後將 AUDIO 設為回應模式,即可傳送音訊。輸出內容使用 24kHz 的取樣率。

Python

# Test file: https://storage.googleapis.com/generativeai-downloads/data/16000.wav
# Install helpers for converting files: pip install librosa soundfile
import asyncio
import io
from pathlib import Path
import wave
from google import genai
from google.genai import types
import soundfile as sf
import librosa

client = genai.Client()

# Half cascade model:
# model = "gemini-live-2.5-flash-preview"

# Native audio output model:
model = "gemini-2.5-flash-preview-native-audio-dialog"

config = {
  "response_modalities": ["AUDIO"],
  "system_instruction": "You are a helpful assistant and answer in a friendly tone.",
}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:

        buffer = io.BytesIO()
        y, sr = librosa.load("sample.wav", sr=16000)
        sf.write(buffer, y, sr, format='RAW', subtype='PCM_16')
        buffer.seek(0)
        audio_bytes = buffer.read()

        # If already in correct format, you can use this:
        # audio_bytes = Path("sample.pcm").read_bytes()

        await session.send_realtime_input(
            audio=types.Blob(data=audio_bytes, mime_type="audio/pcm;rate=16000")
        )

        wf = wave.open("audio.wav", "wb")
        wf.setnchannels(1)
        wf.setsampwidth(2)
        wf.setframerate(24000)  # Output is 24kHz

        async for response in session.receive():
            if response.data is not None:
                wf.writeframes(response.data)

            # Un-comment this code to print audio data info
            # if response.server_content.model_turn is not None:
            #      print(response.server_content.model_turn.parts[0].inline_data.mime_type)

        wf.close()

if __name__ == "__main__":
    asyncio.run(main())

JavaScript

// Test file: https://storage.googleapis.com/generativeai-downloads/data/16000.wav
import { GoogleGenAI, Modality } from '@google/genai';
import * as fs from "node:fs";
import pkg from 'wavefile';  // npm install wavefile
const { WaveFile } = pkg;

const ai = new GoogleGenAI({});
// WARNING: Do not use API keys in client-side (browser based) applications
// Consider using Ephemeral Tokens instead
// More information at: https://ai.google.dev/gemini-api/docs/ephemeral-tokens

// Half cascade model:
// const model = "gemini-live-2.5-flash-preview"

// Native audio output model:
const model = "gemini-2.5-flash-preview-native-audio-dialog"

const config = {
  responseModalities: [Modality.AUDIO], 
  systemInstruction: "You are a helpful assistant and answer in a friendly tone."
};

async function live() {
    const responseQueue = [];

    async function waitMessage() {
        let done = false;
        let message = undefined;
        while (!done) {
            message = responseQueue.shift();
            if (message) {
                done = true;
            } else {
                await new Promise((resolve) => setTimeout(resolve, 100));
            }
        }
        return message;
    }

    async function handleTurn() {
        const turns = [];
        let done = false;
        while (!done) {
            const message = await waitMessage();
            turns.push(message);
            if (message.serverContent && message.serverContent.turnComplete) {
                done = true;
            }
        }
        return turns;
    }

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

    // Send Audio Chunk
    const fileBuffer = fs.readFileSync("sample.wav");

    // Ensure audio conforms to API requirements (16-bit PCM, 16kHz, mono)
    const wav = new WaveFile();
    wav.fromBuffer(fileBuffer);
    wav.toSampleRate(16000);
    wav.toBitDepth("16");
    const base64Audio = wav.toBase64();

    // If already in correct format, you can use this:
    // const fileBuffer = fs.readFileSync("sample.pcm");
    // const base64Audio = Buffer.from(fileBuffer).toString('base64');

    session.sendRealtimeInput(
        {
            audio: {
                data: base64Audio,
                mimeType: "audio/pcm;rate=16000"
            }
        }

    );

    const turns = await handleTurn();

    // Combine audio data strings and save as wave file
    const combinedAudio = turns.reduce((acc, turn) => {
        if (turn.data) {
            const buffer = Buffer.from(turn.data, 'base64');
            const intArray = new Int16Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / Int16Array.BYTES_PER_ELEMENT);
            return acc.concat(Array.from(intArray));
        }
        return acc;
    }, []);

    const audioBuffer = new Int16Array(combinedAudio);

    const wf = new WaveFile();
    wf.fromScratch(1, 24000, '16', audioBuffer);  // output is 24kHz
    fs.writeFileSync('audio.wav', wf.toBuffer());

    session.close();
}

async function main() {
    await live().catch((e) => console.error('got error', e));
}

main();

後續步驟