Get started with Live API

API-ja Live mundëson ndërveprime zanore dhe video me vonesë të ulët, në kohë reale me Gemini. Ai përpunon rrjedha të vazhdueshme audio, video ose teksti për të ofruar përgjigje të menjëhershme, të ngjashme me ato të njerëzve, duke krijuar një përvojë të natyrshme bisedore për përdoruesit tuaj.

Përmbledhje e API-t të drejtpërdrejtë

Live API ofron një sërë gjithëpërfshirëse veçorish të tilla si Zbulimi i Aktivitetit Zëror , përdorimi i mjeteve dhe thirrja e funksioneve , menaxhimi i sesioneve (për menaxhimin e bisedave të gjata) dhe tokenët epemeralë (për autentifikim të sigurt nga klienti).

Kjo faqe ju ndihmon të filloni punën me shembuj dhe mostra bazë të kodit.

Provo API-n Live në e Google AI Studio

Aplikacione shembullore

Shikoni shembujt e mëposhtëm të aplikacioneve që ilustrojnë se si të përdorni Live API për raste përdorimi nga fillimi në fund:

  • Aplikacioni fillestar i audios live në AI Studio, duke përdorur bibliotekat JavaScript për t'u lidhur me Live API dhe për të transmetuar audio dypalëshe përmes mikrofonit dhe altoparlantëve tuaj.
  • Libër gatimi Python në Live API duke përdorur Pyaudio që lidhet me Live API.

Integrimet e partnerëve

Nëse preferoni një proces më të thjeshtë zhvillimi, mund të përdorni Daily , LiveKit ose Voximplant . Këto janë platforma partnere të palëve të treta që kanë integruar tashmë Gemini Live API mbi protokollin WebRTC për të përmirësuar zhvillimin e aplikacioneve audio dhe video në kohë reale.

Zgjidhni një qasje zbatimi

Kur integroheni me Live API, do t'ju duhet të zgjidhni një nga qasjet e mëposhtme të implementimit:

  • Server-me-server : Backend-i juaj lidhet me Live API duke përdorur WebSockets . Zakonisht, klienti juaj dërgon të dhëna transmetimi (audio, video, tekst) në serverin tuaj, i cili më pas ia përcjell ato Live API.
  • Klient-me-server : Kodi juaj i frontend-it lidhet direkt me Live API-n duke përdorur WebSockets për të transmetuar të dhëna, duke anashkaluar backend-in tuaj.

Filloni

Ky shembull lexon një skedar WAV , e dërgon atë në formatin e saktë dhe i ruan të dhënat e marra si skedar WAV.

Mund të dërgoni audio duke e konvertuar atë në formatin PCM 16-bit, 16kHz, mono, dhe mund të merrni audio duke vendosur AUDIO si modalitet përgjigjeje. Dalja përdor një shpejtësi mostrimi prej 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();

Çfarë vjen më pas