Get started with Live API

‫Live API מאפשר אינטראקציות בזמן אמת עם Gemini באמצעות קול ווידאו עם זמן טעינה נמוך. הוא מעבד זרמים רציפים של אודיו, וידאו או טקסט כדי לספק תשובות מיידיות בדיבור שנשמע טבעי, וכך ליצור חוויה טבעית של שיחה למשתמשים.

סקירה כללית על Live API

‫Live API מציע קבוצה מקיפה של תכונות, כמו זיהוי פעילות קולית, שימוש בכלים והפעלת פונקציות, ניהול סשנים (לניהול שיחות ארוכות) וטוקנים זמניים (לאימות מאובטח בצד הלקוח).

בדף הזה מוצגות דוגמאות ודוגמאות קוד בסיסיות שיעזרו לכם להתחיל לעבוד עם ה-API.

רוצים לנסות את ה-API בזמן אמת ב-Google AI Studio?

דוגמאות לאפליקציות

בדוגמאות הבאות לאפליקציות אפשר לראות איך משתמשים ב-Live API בתרחישי שימוש מקצה לקצה:

שילובים עם שותפים

אם אתם מעדיפים תהליך פיתוח פשוט יותר, אתם יכולים להשתמש ב-Daily, ב-LiveKit או ב-Voximplant. אלה פלטפורמות של שותפים מצד שלישי שכבר שילבו את Gemini Live API באמצעות פרוטוקול WebRTC כדי לייעל את הפיתוח של אפליקציות אודיו ווידאו בזמן אמת.

בחירת גישת הטמעה

כשמשלבים עם Live API, צריך לבחור באחת מגישות ההטמעה הבאות:

  • שרת לשרת: הקצה העורפי מתחבר ל-Live API באמצעות WebSockets. בדרך כלל, הלקוח שולח נתוני שידור (אודיו, וידאו, טקסט) לשרת שלכם, והשרת מעביר אותם ל-Live API.
  • לקוח לשרת: קוד הקצה הקדמי מתחבר ישירות ל-Live API באמצעות WebSockets כדי להזרים נתונים, בלי לעבור דרך הקצה העורפי.

שנתחיל?

בדוגמה הזו מתבצעת קריאה של קובץ WAV, הוא נשלח בפורמט הנכון והנתונים שהתקבלו נשמרים כקובץ WAV.

כדי לשלוח אודיו, צריך להמיר אותו לפורמט מונו 16kHz‏, PCM‏ 16 ביט. כדי לקבל אודיו, צריך להגדיר את 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()

# New native audio model:
model = "gemini-2.5-flash-native-audio-preview-09-2025"

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

// New native audio model:
const model = "gemini-2.5-flash-native-audio-preview-09-2025"

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();

המאמרים הבאים