Live API capabilities guide

Ky është një udhëzues gjithëpërfshirës që mbulon aftësitë dhe konfigurimet e disponueshme me Live API. Shikoni faqen Filloni me API të drejtpërdrejtë për një përmbledhje dhe kodin e mostrës për rastet e përdorimit të zakonshëm.

Para se të filloni

  • Njihuni me konceptet thelbësore: Nëse nuk e keni bërë tashmë këtë, lexoni fillimisht faqen Filloni me Live API . Kjo do t'ju prezantojë me parimet themelore të API-së Live, mënyrën se si funksionon dhe dallimin midis modeleve të ndryshme dhe metodave të tyre përkatëse të gjenerimit të audios ( audio origjinale ose gjysmë-kaskadë).
  • Provoni Live API-në në AI Studio: Mund ta gjeni të dobishme të provoni API-në e drejtpërdrejtë në Google AI Studio përpara se të filloni të ndërtoni. Për të përdorur API-në e drejtpërdrejtë në Google AI Studio, zgjidhni Transmeto .

Krijimi i një lidhjeje

Shembulli i mëposhtëm tregon se si të krijoni një lidhje me një çelës API:

Python

import asyncio
from google import genai

client = genai.Client()

model = "gemini-live-2.5-flash-preview"
config = {"response_modalities": ["TEXT"]}

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

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

JavaScript

import { GoogleGenAI, Modality } from '@google/genai';

const ai = new GoogleGenAI({});
const model = 'gemini-live-2.5-flash-preview';
const config = { responseModalities: [Modality.TEXT] };

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,
  });

  // Send content...

  session.close();
}

main();

Modalitetet e ndërveprimit

Seksionet e mëposhtme ofrojnë shembuj dhe kontekst mbështetës për modalitetet e ndryshme hyrëse dhe dalëse të disponueshme në Live API.

Dërgimi dhe marrja e tekstit

Ja se si mund të dërgoni dhe merrni tekst:

Python

import asyncio
from google import genai

client = genai.Client()
model = "gemini-live-2.5-flash-preview"

config = {"response_modalities": ["TEXT"]}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        message = "Hello, how are you?"
        await session.send_client_content(
            turns={"role": "user", "parts": [{"text": message}]}, turn_complete=True
        )

        async for response in session.receive():
            if response.text is not None:
                print(response.text, end="")

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

JavaScript

import { GoogleGenAI, Modality } from '@google/genai';

const ai = new GoogleGenAI({});
const model = 'gemini-live-2.5-flash-preview';
const config = { responseModalities: [Modality.TEXT] };

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,
  });

  const inputTurns = 'Hello how are you?';
  session.sendClientContent({ turns: inputTurns });

  const turns = await handleTurn();
  for (const turn of turns) {
    if (turn.text) {
      console.debug('Received text: %s\n', turn.text);
    }
    else if (turn.data) {
      console.debug('Received inline data: %s\n', turn.data);
    }
  }

  session.close();
}

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

main();

Përditësimet në rritje të përmbajtjes

Përdorni përditësime shtesë për të dërguar të dhëna teksti, për të krijuar kontekstin e sesionit ose për të rivendosur kontekstin e sesionit. Për kontekste të shkurtra, mund të dërgoni ndërveprime kthesë pas kthese për të përfaqësuar sekuencën e saktë të ngjarjeve:

Python

turns = [
    {"role": "user", "parts": [{"text": "What is the capital of France?"}]},
    {"role": "model", "parts": [{"text": "Paris"}]},
]

await session.send_client_content(turns=turns, turn_complete=False)

turns = [{"role": "user", "parts": [{"text": "What is the capital of Germany?"}]}]

await session.send_client_content(turns=turns, turn_complete=True)

JavaScript

let inputTurns = [
  { "role": "user", "parts": [{ "text": "What is the capital of France?" }] },
  { "role": "model", "parts": [{ "text": "Paris" }] },
]

session.sendClientContent({ turns: inputTurns, turnComplete: false })

inputTurns = [{ "role": "user", "parts": [{ "text": "What is the capital of Germany?" }] }]

session.sendClientContent({ turns: inputTurns, turnComplete: true })

Për kontekste më të gjata, rekomandohet të sigurohet një përmbledhje e vetme e mesazhit për të liruar dritaren e kontekstit për ndërveprimet e mëvonshme. Shihni Rifillimin e sesionit për një metodë tjetër për ngarkimin e kontekstit të sesionit.

Dërgimi dhe marrja e audios

Shembulli më i zakonshëm audio, audio-në-audio , mbulohet në udhëzuesin Fillimi .

Këtu është një shembull audio-në tekst që lexon një skedar WAV, e dërgon atë në formatin e duhur dhe merr daljen e tekstit:

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
from google import genai
from google.genai import types
import soundfile as sf
import librosa

client = genai.Client()
model = "gemini-live-2.5-flash-preview"

config = {"response_modalities": ["TEXT"]}

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")
        )

        async for response in session.receive():
            if response.text is not None:
                print(response.text)

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

JavaScript

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

const ai = new GoogleGenAI({});
const model = 'gemini-live-2.5-flash-preview';
const config = { responseModalities: [Modality.TEXT] };

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();
  for (const turn of turns) {
    if (turn.text) {
      console.debug('Received text: %s\n', turn.text);
    }
    else if (turn.data) {
      console.debug('Received inline data: %s\n', turn.data);
    }
  }

  session.close();
}

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

main();

Dhe këtu është një shembull tekst-në-audio . Ju mund të merrni audio duke vendosur AUDIO si modalitet përgjigjeje. Ky shembull ruan të dhënat e marra si skedar WAV:

Python

import asyncio
import wave
from google import genai

client = genai.Client()
model = "gemini-live-2.5-flash-preview"

config = {"response_modalities": ["AUDIO"]}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        wf = wave.open("audio.wav", "wb")
        wf.setnchannels(1)
        wf.setsampwidth(2)
        wf.setframerate(24000)

        message = "Hello how are you?"
        await session.send_client_content(
            turns={"role": "user", "parts": [{"text": message}]}, turn_complete=True
        )

        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

import { GoogleGenAI, Modality } from '@google/genai';
import * as fs from "node:fs";
import pkg from 'wavefile';
const { WaveFile } = pkg;

const ai = new GoogleGenAI({});
const model = 'gemini-live-2.5-flash-preview';
const config = { responseModalities: [Modality.AUDIO] };

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,
  });

  const inputTurns = 'Hello how are you?';
  session.sendClientContent({ turns: inputTurns });

  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);
  fs.writeFileSync('output.wav', wf.toBuffer());

  session.close();
}

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

main();

Formatet audio

Të dhënat audio në API-në e drejtpërdrejtë janë gjithmonë të papërpunuara, PCM 16-bitëshe të pakta. Dalja e audios përdor gjithmonë një shpejtësi të mostrës prej 24 kHz. Audioja e hyrjes është origjinale 16 kHz, por API Live do të rimodelojë nëse është e nevojshme, në mënyrë që të mund të dërgohet çdo shpejtësi e mostrës. Për të përcjellë shpejtësinë e mostrës së audios hyrëse, vendosni llojin MIME të çdo Blob që përmban audio në një vlerë si audio/pcm;rate=16000 .

Transkriptimet audio

Mund të aktivizoni transkriptimin e daljes audio të modelit duke dërguar output_audio_transcription në konfigurimin e konfigurimit. Gjuha e transkriptimit nxirret nga përgjigja e modelit.

Python

import asyncio
from google import genai
from google.genai import types

client = genai.Client()
model = "gemini-live-2.5-flash-preview"

config = {"response_modalities": ["AUDIO"],
        "output_audio_transcription": {}
}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        message = "Hello? Gemini are you there?"

        await session.send_client_content(
            turns={"role": "user", "parts": [{"text": message}]}, turn_complete=True
        )

        async for response in session.receive():
            if response.server_content.model_turn:
                print("Model turn:", response.server_content.model_turn)
            if response.server_content.output_transcription:
                print("Transcript:", response.server_content.output_transcription.text)

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

JavaScript

import { GoogleGenAI, Modality } from '@google/genai';

const ai = new GoogleGenAI({});
const model = 'gemini-live-2.5-flash-preview';

const config = {
  responseModalities: [Modality.AUDIO],
  outputAudioTranscription: {}
};

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,
  });

  const inputTurns = 'Hello how are you?';
  session.sendClientContent({ turns: inputTurns });

  const turns = await handleTurn();

  for (const turn of turns) {
    if (turn.serverContent && turn.serverContent.outputTranscription) {
      console.debug('Received output transcription: %s\n', turn.serverContent.outputTranscription.text);
    }
  }

  session.close();
}

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

main();

Mund të aktivizoni transkriptimin e hyrjes audio duke dërguar input_audio_transcription në konfigurimin e konfigurimit.

Python

import asyncio
from pathlib import Path
from google import genai
from google.genai import types

client = genai.Client()
model = "gemini-live-2.5-flash-preview"

config = {
    "response_modalities": ["TEXT"],
    "input_audio_transcription": {},
}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        audio_data = Path("16000.pcm").read_bytes()

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

        async for msg in session.receive():
            if msg.server_content.input_transcription:
                print('Transcript:', msg.server_content.input_transcription.text)

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

JavaScript

import { GoogleGenAI, Modality } from '@google/genai';
import * as fs from "node:fs";
import pkg from 'wavefile';
const { WaveFile } = pkg;

const ai = new GoogleGenAI({});
const model = 'gemini-live-2.5-flash-preview';

const config = {
  responseModalities: [Modality.TEXT],
  inputAudioTranscription: {}
};

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("16000.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();

  for (const turn of turns) {
    if (turn.serverContent && turn.serverContent.outputTranscription) {
      console.log("Transcription")
      console.log(turn.serverContent.outputTranscription.text);
    }
  }
  for (const turn of turns) {
    if (turn.text) {
      console.debug('Received text: %s\n', turn.text);
    }
    else if (turn.data) {
      console.debug('Received inline data: %s\n', turn.data);
    }
    else if (turn.serverContent && turn.serverContent.inputTranscription) {
      console.debug('Received input transcription: %s\n', turn.serverContent.inputTranscription.text);
    }
  }

  session.close();
}

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

main();

Transmetoni audio dhe video

Ndryshoni zërin dhe gjuhën

Modelet Live API mbështesin secili një grup të ndryshëm zërash. Gjysmë-kaskada mbështet Puck, Charon, Kore, Fenrir, Aoede, Leda, Orus dhe Zephyr. Audioja origjinale mbështet një listë shumë më të gjatë (identike me listën e modeleve TTS ). Ju mund të dëgjoni të gjithë zërat në AI Studio .

Për të specifikuar një zë, vendosni emrin e zërit brenda objektit speechConfig si pjesë e konfigurimit të sesionit:

Python

config = {
    "response_modalities": ["AUDIO"],
    "speech_config": {
        "voice_config": {"prebuilt_voice_config": {"voice_name": "Kore"}}
    },
}

JavaScript

const config = {
  responseModalities: [Modality.AUDIO],
  speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: "Kore" } } }
};

API Live mbështet shumë gjuhë .

Për të ndryshuar gjuhën, vendosni kodin e gjuhës brenda objektit speechConfig si pjesë e konfigurimit të sesionit:

Python

config = {
    "response_modalities": ["AUDIO"],
    "speech_config": {
        "language_code": "de-DE"
    }
}

JavaScript

const config = {
  responseModalities: [Modality.AUDIO],
  speechConfig: { languageCode: "de-DE" }
};

Aftësitë e audios vendase

Aftësitë e mëposhtme janë të disponueshme vetëm me audio origjinale. Mund të mësoni më shumë rreth audios vendase në Zgjidhni një model dhe gjenerim audio .

Si të përdorni daljen e audios amtare

Për të përdorur daljen origjinale të audios, konfiguroni një nga modelet origjinale të audios dhe caktoni response_modalitiesAUDIO .

Shihni Dërgoni dhe merrni audio për një shembull të plotë.

Python

model = "gemini-2.5-flash-preview-native-audio-dialog"
config = types.LiveConnectConfig(response_modalities=["AUDIO"])

async with client.aio.live.connect(model=model, config=config) as session:
    # Send audio input and receive audio

JavaScript

const model = 'gemini-2.5-flash-preview-native-audio-dialog';
const config = { responseModalities: [Modality.AUDIO] };

async function main() {

  const session = await ai.live.connect({
    model: model,
    config: config,
    callbacks: ...,
  });

  // Send audio input and receive audio

  session.close();
}

main();

Dialog afektiv

Kjo veçori i lejon Binjakëve të përshtasë stilin e përgjigjes me shprehjen dhe tonin e hyrjes.

Për të përdorur dialogun afektiv, vendosni versionin api në v1alpha dhe vendosni enable_affective_dialogtrue në mesazhin e konfigurimit:

Python

client = genai.Client(http_options={"api_version": "v1alpha"})

config = types.LiveConnectConfig(
    response_modalities=["AUDIO"],
    enable_affective_dialog=True
)

JavaScript

const ai = new GoogleGenAI({ httpOptions: {"apiVersion": "v1alpha"} });

const config = {
  responseModalities: [Modality.AUDIO],
  enableAffectiveDialog: true
};

Vini re se dialogu afektiv aktualisht mbështetet vetëm nga modelet e daljes audio vendase.

Audio proaktive

Kur kjo veçori është e aktivizuar, Binjakët mund të vendosin në mënyrë proaktive të mos përgjigjen nëse përmbajtja nuk është e rëndësishme.

Për ta përdorur atë, vendosni versionin api në v1alpha dhe konfiguroni fushën e proactivity në mesazhin e konfigurimit dhe vendosni proactive_audiotrue :

Python

client = genai.Client(http_options={"api_version": "v1alpha"})

config = types.LiveConnectConfig(
    response_modalities=["AUDIO"],
    proactivity={'proactive_audio': True}
)

JavaScript

const ai = new GoogleGenAI({ httpOptions: {"apiVersion": "v1alpha"} });

const config = {
  responseModalities: [Modality.AUDIO],
  proactivity: { proactiveAudio: true }
}

Vini re se audio proaktive aktualisht mbështetet vetëm nga modelet e daljes audio vendase.

Dalje audio vendase me të menduarit

Dalja origjinale e audios mbështet aftësitë e të menduarit , të disponueshme nëpërmjet një modeli të veçantë gemini-2.5-flash-exp-native-audio-thinking-dialog .

Shihni Dërgoni dhe merrni audio për një shembull të plotë.

Python

model = "gemini-2.5-flash-exp-native-audio-thinking-dialog"
config = types.LiveConnectConfig(response_modalities=["AUDIO"])

async with client.aio.live.connect(model=model, config=config) as session:
    # Send audio input and receive audio

JavaScript

const model = 'gemini-2.5-flash-exp-native-audio-thinking-dialog';
const config = { responseModalities: [Modality.AUDIO] };

async function main() {

  const session = await ai.live.connect({
    model: model,
    config: config,
    callbacks: ...,
  });

  // Send audio input and receive audio

  session.close();
}

main();

Zbulimi i aktivitetit zanor (VAD)

Zbulimi i aktivitetit zanor (VAD) lejon modelin të njohë kur një person është duke folur. Kjo është thelbësore për krijimin e bisedave të natyrshme, pasi lejon një përdorues të ndërpresë modelin në çdo kohë.

Kur VAD zbulon një ndërprerje, gjenerimi në vazhdim anulohet dhe hidhet poshtë. Vetëm informacioni i dërguar tashmë klientit ruhet në historikun e sesionit. Serveri më pas dërgon një mesazh BidiGenerateContentServerContent për të raportuar ndërprerjen.

Serveri Gemini më pas hedh poshtë çdo thirrje funksioni në pritje dhe dërgon një mesazh BidiGenerateContentServerContent me ID-të e thirrjeve të anuluara.

Python

async for response in session.receive():
    if response.server_content.interrupted is True:
        # The generation was interrupted

        # If realtime playback is implemented in your application,
        # you should stop playing audio and clear queued playback here.

JavaScript

const turns = await handleTurn();

for (const turn of turns) {
  if (turn.serverContent && turn.serverContent.interrupted) {
    // The generation was interrupted

    // If realtime playback is implemented in your application,
    // you should stop playing audio and clear queued playback here.
  }
}

VAD automatike

Si parazgjedhje, modeli kryen automatikisht VAD në një transmetim të vazhdueshëm të hyrjes audio. VAD mund të konfigurohet me fushën realtimeInputConfig.automaticActivityDetectionkonfigurimit të konfigurimit .

Kur transmetimi i audios ndalet për më shumë se një sekondë (për shembull, për shkak se përdoruesi ka fikur mikrofonin), duhet të dërgohet një ngjarje audioStreamEnd për të pastruar çdo audio të ruajtur në memorie. Klienti mund të rifillojë dërgimin e të dhënave audio në çdo kohë.

Python

# example audio file to try:
# URL = "https://storage.googleapis.com/generativeai-downloads/data/hello_are_you_there.pcm"
# !wget -q $URL -O sample.pcm
import asyncio
from pathlib import Path
from google import genai
from google.genai import types

client = genai.Client()
model = "gemini-live-2.5-flash-preview"

config = {"response_modalities": ["TEXT"]}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        audio_bytes = Path("sample.pcm").read_bytes()

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

        # if stream gets paused, send:
        # await session.send_realtime_input(audio_stream_end=True)

        async for response in session.receive():
            if response.text is not None:
                print(response.text)

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

JavaScript

// example audio file to try:
// URL = "https://storage.googleapis.com/generativeai-downloads/data/hello_are_you_there.pcm"
// !wget -q $URL -O sample.pcm
import { GoogleGenAI, Modality } from '@google/genai';
import * as fs from "node:fs";

const ai = new GoogleGenAI({});
const model = 'gemini-live-2.5-flash-preview';
const config = { responseModalities: [Modality.TEXT] };

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.pcm");
  const base64Audio = Buffer.from(fileBuffer).toString('base64');

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

  );

  // if stream gets paused, send:
  // session.sendRealtimeInput({ audioStreamEnd: true })

  const turns = await handleTurn();
  for (const turn of turns) {
    if (turn.text) {
      console.debug('Received text: %s\n', turn.text);
    }
    else if (turn.data) {
      console.debug('Received inline data: %s\n', turn.data);
    }
  }

  session.close();
}

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

main();

Me send_realtime_input , API do t'i përgjigjet audios automatikisht bazuar në VAD. Ndërsa send_client_content shton mesazhe në kontekstin e modelit sipas radhës, send_realtime_input optimizohet për reagim në kurriz të renditjes përcaktuese.

Konfigurimi automatik VAD

Për më shumë kontroll mbi aktivitetin VAD, mund të konfiguroni parametrat e mëposhtëm. Shih referencën API për më shumë informacion.

Python

from google.genai import types

config = {
    "response_modalities": ["TEXT"],
    "realtime_input_config": {
        "automatic_activity_detection": {
            "disabled": False, # default
            "start_of_speech_sensitivity": types.StartSensitivity.START_SENSITIVITY_LOW,
            "end_of_speech_sensitivity": types.EndSensitivity.END_SENSITIVITY_LOW,
            "prefix_padding_ms": 20,
            "silence_duration_ms": 100,
        }
    }
}

JavaScript

import { GoogleGenAI, Modality, StartSensitivity, EndSensitivity } from '@google/genai';

const config = {
  responseModalities: [Modality.TEXT],
  realtimeInputConfig: {
    automaticActivityDetection: {
      disabled: false, // default
      startOfSpeechSensitivity: StartSensitivity.START_SENSITIVITY_LOW,
      endOfSpeechSensitivity: EndSensitivity.END_SENSITIVITY_LOW,
      prefixPaddingMs: 20,
      silenceDurationMs: 100,
    }
  }
};

Çaktivizo VAD-në automatike

Përndryshe, VAD-i automatik mund të çaktivizohet duke vendosur realtimeInputConfig.automaticActivityDetection.disabledtrue në mesazhin e konfigurimit. Në këtë konfigurim klienti është përgjegjës për zbulimin e të folurit të përdoruesit dhe dërgimin e mesazheve activityStart dhe activityEnd në kohën e duhur. Një audioStreamEnd nuk dërgohet në këtë konfigurim. Në vend të kësaj, çdo ndërprerje e transmetimit shënohet nga një mesazh activityEnd .

Python

config = {
    "response_modalities": ["TEXT"],
    "realtime_input_config": {"automatic_activity_detection": {"disabled": True}},
}

async with client.aio.live.connect(model=model, config=config) as session:
    # ...
    await session.send_realtime_input(activity_start=types.ActivityStart())
    await session.send_realtime_input(
        audio=types.Blob(data=audio_bytes, mime_type="audio/pcm;rate=16000")
    )
    await session.send_realtime_input(activity_end=types.ActivityEnd())
    # ...

JavaScript

const config = {
  responseModalities: [Modality.TEXT],
  realtimeInputConfig: {
    automaticActivityDetection: {
      disabled: true,
    }
  }
};

session.sendRealtimeInput({ activityStart: {} })

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

);

session.sendRealtimeInput({ activityEnd: {} })

Numri i shenjave

Ju mund të gjeni numrin total të argumenteve të konsumuara në fushën usageMetadata të mesazhit të serverit të kthyer.

Python

async for message in session.receive():
    # The server will periodically send messages that include UsageMetadata.
    if message.usage_metadata:
        usage = message.usage_metadata
        print(
            f"Used {usage.total_token_count} tokens in total. Response token breakdown:"
        )
        for detail in usage.response_tokens_details:
            match detail:
                case types.ModalityTokenCount(modality=modality, token_count=count):
                    print(f"{modality}: {count}")

JavaScript

const turns = await handleTurn();

for (const turn of turns) {
  if (turn.usageMetadata) {
    console.debug('Used %s tokens in total. Response token breakdown:\n', turn.usageMetadata.totalTokenCount);

    for (const detail of turn.usageMetadata.responseTokensDetails) {
      console.debug('%s\n', detail);
    }
  }
}

Rezolucioni i medias

Mund të specifikoni rezolucionin e medias për median hyrëse duke vendosur fushën mediaResolution si pjesë e konfigurimit të sesionit:

Python

from google.genai import types

config = {
    "response_modalities": ["AUDIO"],
    "media_resolution": types.MediaResolution.MEDIA_RESOLUTION_LOW,
}

JavaScript

import { GoogleGenAI, Modality, MediaResolution } from '@google/genai';

const config = {
    responseModalities: [Modality.TEXT],
    mediaResolution: MediaResolution.MEDIA_RESOLUTION_LOW,
};

Kufizimet

Merrni parasysh kufizimet e mëposhtme të Live API kur planifikoni projektin tuaj.

Modalitetet e reagimit

Mund të vendosni vetëm një modalitet përgjigjeje ( TEXT ose AUDIO ) për sesion në konfigurimin e sesionit. Vendosja e të dyjave rezulton në një mesazh gabimi të konfigurimit. Kjo do të thotë që ju mund ta konfiguroni modelin që të përgjigjet me tekst ose audio, por jo të dyja në të njëjtin seancë.

Autentifikimi i klientit

API Live siguron vetëm vërtetimin nga serveri në server si parazgjedhje. Nëse po zbatoni aplikacionin tuaj Live API duke përdorur një qasje klient-në-server , duhet të përdorni shenja kalimtare për të zbutur rreziqet e sigurisë.

Kohëzgjatja e seancës

Seancat vetëm me audio janë të kufizuara në 15 minuta dhe seancat audio plus video janë të kufizuara në 2 minuta. Sidoqoftë, mund të konfiguroni teknika të ndryshme të menaxhimit të sesioneve për zgjatje të pakufizuara në kohëzgjatjen e sesionit.

Dritarja e kontekstit

Një seancë ka një kufi të dritares së kontekstit prej:

Gjuhët e mbështetura

Live API mbështet gjuhët e mëposhtme.

Gjuha Kodi i PKK-47 Gjuha Kodi i PKK-47
gjermanisht (Gjermani) de-DE anglisht (Australi)* en-AU
anglisht (MB)* en-GB anglisht (Indi) en-IN
Anglisht (SHBA) en-US Spanjisht (SHBA) es-US
Frëngjisht (Francë) fr-FR Hindi (Indi) hi-IN
Portugeze (Brazil) pt-BR Arabisht (Gjenerike) ar-XA
spanjisht (Spanjë)* es-ES frëngjisht (Kanada)* fr-CA
Indonezisht (Indonezi) id-ID italisht (Itali) it-IT
japoneze (Japoni) ja-JP turqisht (Turqi) tr-TR
Vietnamisht (Vietnam) vi-VN Bengalisht (Indi) bn-IN
Guxharati (Indi)* gu-IN Kanada (Indi)* kn-IN
Marathi (Indi) mr-IN malajalam (Indi)* ml-IN
Tamile (Indi) ta-IN telugu (Indi) te-IN
Hollandisht (Holandë) nl-NL Koreane (Koreja e Jugut) ko-KR
Mandarin kineze (Kinë)* cmn-CN polake (Poloni) pl-PL
Rusisht (Rusi) ru-RU Thai (Tajlandë) th-TH

Gjuhët e shënuara me një yll (*) nuk janë të disponueshme për audion origjinale .

Çfarë është më pas