Live API

Live API की मदद से, Gemini के साथ कम इंतज़ार के साथ, दोनों तरफ़ से आवाज़ और वीडियो के ज़रिए इंटरैक्ट किया जा सकता है. इसकी मदद से, वीडियो इनपुट स्ट्रीम करने या अपनी स्क्रीन शेयर करने के साथ-साथ, Gemini से लाइव बातचीत की जा सकती है. Live API का इस्तेमाल करके, असली उपयोगकर्ताओं को नैचुरल और इंसानों जैसी आवाज़ में बातचीत करने का अनुभव दिया जा सकता है.

Google AI Studio में Live API को आज़माया जा सकता है. Google AI Studio में Live API का इस्तेमाल करने के लिए, स्ट्रीम करें को चुनें.

Live API के काम करने का तरीका

स्ट्रीमिंग

Live API, WebSocket कनेक्शन पर स्ट्रीमिंग मॉडल का इस्तेमाल करता है. एपीआई के साथ इंटरैक्ट करने पर, एक पर्सिस्टेंट कनेक्शन बन जाता है. आपका इनपुट (ऑडियो, वीडियो या टेक्स्ट), मॉडल पर लगातार स्ट्रीम किया जाता है. साथ ही, मॉडल का जवाब (टेक्स्ट या ऑडियो), उसी कनेक्शन पर रीयल-टाइम में स्ट्रीम किया जाता है.

इस सुविधा की मदद से, दोनों तरफ़ से स्ट्रीमिंग की जा सकती है. इससे, अनुरोधों को पूरा करने में लगने वाला समय कम होता है. साथ ही, इसमें आवाज़ की गतिविधि का पता लगाने, टूल इस्तेमाल करने, और बोली जनरेट करने जैसी सुविधाएं भी काम करती हैं.

Live API के बारे में खास जानकारी

WebSockets API के बारे में ज़्यादा जानकारी के लिए, WebSockets API का रेफ़रंस देखें.

लाइव एपीआई {:#building-with-live-api} का इस्तेमाल करके लैंडिंग पेज बनानाß

कनेक्शन सेट अप करना

यहां दिए गए उदाहरण में, एपीआई पासकोड से कनेक्शन बनाने का तरीका बताया गया है:

Python

import asyncio
from google import genai

client = genai.Client(api_key="GEMINI_API_KEY")

model = "gemini-2.0-flash-live-001"
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 } from '@google/genai';

const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
const model = 'gemini-2.0-flash-live-001';
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();

टेक्स्ट भेजना और पाना

मैसेज भेजने और पाने का तरीका यहां बताया गया है:

Python

import asyncio
from google import genai

client = genai.Client(api_key="GEMINI_API_KEY")
model = "gemini-2.0-flash-live-001"

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({ apiKey: "GOOGLE_API_KEY" });
const model = 'gemini-2.0-flash-live-001';
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 simple = 'Hello how are you?';
    session.sendClientContent({ turns: simple });

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

ऑडियो भेजना और पाना

ऑडियो को 16-बिट PCM, 16kHz, मोनो फ़ॉर्मैट में बदलकर भेजा जा सकता है. इस उदाहरण में, WAV फ़ाइल को पढ़कर उसे सही फ़ॉर्मैट में भेजा जाता है:

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(api_key="GEMINI_API_KEY")
model = "gemini-2.0-flash-live-001"

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({ apiKey: "GOOGLE_API_KEY" });
const model = 'gemini-2.0-flash-live-001';
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();

AUDIO को रिस्पॉन्स मोड के तौर पर सेट करके, ऑडियो रिकॉर्ड किया जा सकता है. इस उदाहरण में, मिले डेटा को WAV फ़ाइल के तौर पर सेव किया जाता है:

Python

import asyncio
import wave
from google import genai

client = genai.Client(api_key="GEMINI_API_KEY")
model = "gemini-2.0-flash-live-001"

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 idx,response in async_enumerate(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';

const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
const model = 'gemini-2.0-flash-live-001';
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 simple = 'Hello how are you?';
    session.sendClientContent({ turns: simple });

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

ऑडियो फ़ॉर्मैट

Live API में ऑडियो डेटा हमेशा रॉ, लिटल-एंडियन, और 16-बिट PCM होता है. ऑडियो आउटपुट हमेशा 24 किलोहर्ट्ज़ के सैंपल रेट का इस्तेमाल करता है. इनपुट ऑडियो का नेटिव सैंपल रेट 16 किलोहर्ट्ज़ होता है. हालांकि, ज़रूरत पड़ने पर Live API, ऑडियो को फिर से सैंपल करेगा, ताकि कोई भी सैंपल रेट भेजा जा सके. इनपुट ऑडियो का सैंपल रेट बताने के लिए, ऑडियो वाले हर Blob का MIME टाइप, audio/pcm;rate=16000 जैसी वैल्यू पर सेट करें.

ऑडियो ट्रांसक्रिप्शन पाना

सेटअप कॉन्फ़िगरेशन में output_audio_transcription भेजकर, मॉडल के ऑडियो आउटपुट को टेक्स्ट में बदलने की सुविधा चालू की जा सकती है. बोली को लेख में बदलने के लिए इस्तेमाल की जाने वाली भाषा का पता, मॉडल के जवाब से लगाया जाता है.

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

client = genai.Client(api_key="GEMINI_API_KEY")
model = "gemini-2.0-flash-live-001"

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

सेटअप कॉन्फ़िगरेशन में input_audio_transcription भेजकर, ऑडियो इनपुट का ट्रांसक्रिप्शन चालू किया जा सकता है.

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

client = genai.Client(api_key="GEMINI_API_KEY")
model = "gemini-2.0-flash-live-001"

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

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

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

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

ऑडियो और वीडियो स्ट्रीम करना

सिस्टम से जुड़े निर्देश

सिस्टम के निर्देशों की मदद से, अपनी ज़रूरतों और इस्तेमाल के उदाहरणों के आधार पर, मॉडल के व्यवहार को कंट्रोल किया जा सकता है. सेटअप कॉन्फ़िगरेशन में सिस्टम के निर्देश सेट किए जा सकते हैं. ये निर्देश पूरे सेशन के लिए लागू रहेंगे.

from google.genai import types

config = {
    "system_instruction": types.Content(
        parts=[
            types.Part(
                text="You are a helpful assistant and answer in a friendly tone."
            )
        ]
    ),
    "response_modalities": ["TEXT"],
}

कॉन्टेंट के इंक्रीमेंटल अपडेट

टेक्स्ट इनपुट भेजने, सेशन का कॉन्टेक्स्ट सेट करने या सेशन का कॉन्टेक्स्ट वापस लाने के लिए, इंक्रीमेंटल अपडेट का इस्तेमाल करें. कम शब्दों वाले कॉन्टेक्स्ट के लिए, इवेंट के सटीक क्रम को दिखाने के लिए, बारी-बारी से इंटरैक्शन भेजे जा सकते हैं:

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)

JSON

{
  "clientContent": {
    "turns": [
      {
        "parts":[
          {
            "text": ""
          }
        ],
        "role":"user"
      },
      {
        "parts":[
          {
            "text": ""
          }
        ],
        "role":"model"
      }
    ],
    "turnComplete": true
  }
}

लंबे कॉन्टेक्स्ट के लिए, हमारा सुझाव है कि आप एक मैसेज की खास जानकारी दें, ताकि बाद के इंटरैक्शन के लिए कॉन्टेक्स्ट विंडो खाली हो सके.

आवाज़ और भाषा बदलना

Live API में ये आवाज़ें उपलब्ध हैं: Puck, Charon, Kore, Fenrir, Aoede, Leda, Orus, और Zephyr.

किसी आवाज़ को सेट करने के लिए, सेशन कॉन्फ़िगरेशन के हिस्से के तौर पर, speechConfig ऑब्जेक्ट में आवाज़ का नाम सेट करें:

Python

from google.genai import types

config = types.LiveConnectConfig(
    response_modalities=["AUDIO"],
    speech_config=types.SpeechConfig(
        voice_config=types.VoiceConfig(
            prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name="Kore")
        )
    )
)

JSON

{
  "voiceConfig": {
    "prebuiltVoiceConfig": {
      "voiceName": "Kore"
    }
  }
}

Live API, कई भाषाओं में काम करता है.

भाषा बदलने के लिए, सेशन कॉन्फ़िगरेशन के हिस्से के तौर पर, speechConfig ऑब्जेक्ट में भाषा कोड सेट करें:

from google.genai import types

config = types.LiveConnectConfig(
    response_modalities=["AUDIO"],
    speech_config=types.SpeechConfig(
        language_code="de-DE",
    )
)

लाइव एपीआई के साथ टूल का इस्तेमाल करना

लाइव एपीआई की मदद से, फ़ंक्शन कॉल, कोड को लागू करना, और Google Search जैसे टूल तय किए जा सकते हैं.

फ़ंक्शन कॉल करना

सेशन कॉन्फ़िगरेशन के हिस्से के तौर पर, फ़ंक्शन के एलान तय किए जा सकते हैं. ज़्यादा जानने के लिए, फ़ंक्शन कॉल करने का ट्यूटोरियल देखें.

टूल कॉल मिलने के बाद, क्लाइंट को session.send_tool_response तरीके का इस्तेमाल करके, FunctionResponse ऑब्जेक्ट की सूची के साथ जवाब देना चाहिए.

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

client = genai.Client(api_key="GEMINI_API_KEY")
model = "gemini-2.0-flash-live-001"

# Simple function definitions
turn_on_the_lights = {"name": "turn_on_the_lights"}
turn_off_the_lights = {"name": "turn_off_the_lights"}

tools = [{"function_declarations": [turn_on_the_lights, turn_off_the_lights]}]
config = {"response_modalities": ["TEXT"], "tools": tools}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        prompt = "Turn on the lights please"
        await session.send_client_content(turns={"parts": [{"text": prompt}]})

        async for chunk in session.receive():
            if chunk.server_content:
                if chunk.text is not None:
                    print(chunk.text)
            elif chunk.tool_call:
                function_responses = []
                for fc in tool_call.function_calls:
                    function_response = types.FunctionResponse(
                        id=fc.id,
                        name=fc.name,
                        response={ "result": "ok" } # simple, hard-coded function response
                    )
                    function_responses.append(function_response)

                await session.send_tool_response(function_responses=function_responses)


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

एक प्रॉम्प्ट से, मॉडल कई फ़ंक्शन कॉल और उनके आउटपुट को चेन करने के लिए ज़रूरी कोड जनरेट कर सकता है. यह कोड सैंडबॉक्स एनवायरमेंट में चलता है और इसके बाद BidiGenerateContentToolCall मैसेज जनरेट करता है.

एसिंक्रोनस फ़ंक्शन कॉल

डिफ़ॉल्ट रूप से, एक्ज़ीक्यूशन तब तक रुका रहता है, जब तक हर फ़ंक्शन कॉल के नतीजे उपलब्ध नहीं हो जाते. इससे क्रम से प्रोसेस करने की सुविधा मिलती है. इसका मतलब है कि फ़ंक्शन चलने के दौरान, मॉडल के साथ इंटरैक्ट नहीं किया जा सकेगा.

अगर आपको बातचीत को ब्लॉक नहीं करना है, तो मॉडल को फ़ंक्शन को एक साथ चलाने के लिए कहा जा सकता है.

ऐसा करने के लिए, आपको फ़ंक्शन की परिभाषाओं में पहले behavior जोड़ना होगा:

  # Non-blocking function definitions
  turn_on_the_lights = {"name": "turn_on_the_lights", "behavior": "NON_BLOCKING"} # turn_on_the_lights will run asynchronously
  turn_off_the_lights = {"name": "turn_off_the_lights"} # turn_off_the_lights will still pause all interactions with the model

NON-BLOCKING से यह पक्का होगा कि फ़ंक्शन असिंक्रोनस तरीके से चलेगा, जबकि आपके पास मॉडल के साथ इंटरैक्ट करने का विकल्प रहेगा.

इसके बाद, आपको मॉडल को यह बताना होगा कि scheduling पैरामीटर का इस्तेमाल करके, FunctionResponse मिलने पर उसे क्या करना चाहिए. यह इनमें से कोई एक काम कर सकता है:

  • वह जो भी कर रहा है उसे बीच में रोककर, आपको तुरंत जवाब दे सकता है (scheduling="INTERRUPT"),
  • जब तक यह प्रोसेस पूरी न हो जाए तब तक इंतज़ार करें (scheduling="WHEN_IDLE"),
  • इसके अलावा, कुछ न करें और उस जानकारी का इस्तेमाल बाद में चर्चा में करें (scheduling="SILENT")
# Non-blocking function definitions
  function_response = types.FunctionResponse(
      id=fc.id,
      name=fc.name,
      response={
          "result": "ok",
          "scheduling": "INTERRUPT" # Can also be WHEN_IDLE or SILENT
      }
  )

कोड चलाना

सेशन कॉन्फ़िगरेशन के हिस्से के तौर पर, कोड को लागू करने का तरीका तय किया जा सकता है. ज़्यादा जानने के लिए, कोड लागू करने का ट्यूटोरियल देखें.

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

client = genai.Client(api_key="GEMINI_API_KEY")
model = "gemini-2.0-flash-live-001"

tools = [{'code_execution': {}}]
config = {"response_modalities": ["TEXT"], "tools": tools}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        prompt = "Compute the largest prime palindrome under 100000."
        await session.send_client_content(turns={"parts": [{"text": prompt}]})

        async for chunk in session.receive():
            if chunk.server_content:
                if chunk.text is not None:
                    print(chunk.text)
            
                model_turn = chunk.server_content.model_turn
                if model_turn:
                    for part in model_turn.parts:
                      if part.executable_code is not None:
                        print(part.executable_code.code)

                      if part.code_execution_result is not None:
                        print(part.code_execution_result.output)

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

सेशन कॉन्फ़िगरेशन के हिस्से के तौर पर, Google Search के साथ ग्राउंडिंग की सुविधा चालू की जा सकती है. ज़्यादा जानने के लिए, ग्राउंडिंग ट्यूटोरियल देखें.

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

client = genai.Client(api_key="GEMINI_API_KEY")
model = "gemini-2.0-flash-live-001"

tools = [{'google_search': {}}]
config = {"response_modalities": ["TEXT"], "tools": tools}

async def main():
    async with client.aio.live.connect(model=model, config=config) as session:
        prompt = "When did the last Brazil vs. Argentina soccer match happen?"
        await session.send_client_content(turns={"parts": [{"text": prompt}]})

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

                # The model might generate and execute Python code to use Search
                model_turn = chunk.server_content.model_turn
                if model_turn:
                    for part in model_turn.parts:
                      if part.executable_code is not None:
                        print(part.executable_code.code)

                      if part.code_execution_result is not None:
                        print(part.code_execution_result.output)

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

एक से ज़्यादा टूल का इस्तेमाल करना

Live API में कई टूल को एक साथ इस्तेमाल किया जा सकता है:

prompt = """
Hey, I need you to do three things for me.

1. Compute the largest prime palindrome under 100000.
2. Then use Google Search to look up information about the largest earthquake in California the week of Dec 5 2024?
3. Turn on the lights

Thanks!
"""

tools = [
    {"google_search": {}},
    {"code_execution": {}},
    {"function_declarations": [turn_on_the_lights, turn_off_the_lights]},
]

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

रुकावटों को मैनेज करना

उपयोगकर्ता किसी भी समय मॉडल के आउटपुट में रुकावट डाल सकते हैं. जब आवाज़ की गतिविधि का पता लगाने (वीएडी) की सुविधा किसी रुकावट का पता लगाती है, तो जनरेट की जा रही फ़ोटो रद्द कर दी जाती है और उसे हटा दिया जाता है. सेशन के इतिहास में सिर्फ़ वह जानकारी सेव रहती है जो क्लाइंट को पहले से भेजी जा चुकी है. इसके बाद, रुकावट की शिकायत करने के लिए, सर्वर एक BidiGenerateContentServerContent मैसेज भेजता है.

इसके अलावा, Gemini सर्वर उन सभी फ़ंक्शन कॉल को खारिज कर देता है जो प्रोसेस नहीं हो पाए हैं. साथ ही, रद्द किए गए कॉल के आईडी के साथ एक BidiGenerateContentServerContent मैसेज भेजता है.

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

आवाज़ की गतिविधि का पता लगाने की सुविधा (वीएडी)

आपके पास वॉइस ऐक्टिविटी डिटेक्शन (वीएडी) को कॉन्फ़िगर करने या बंद करने का विकल्प है.

ऑटोमैटिक वीएडी का इस्तेमाल करना

डिफ़ॉल्ट रूप से, मॉडल लगातार चलने वाली ऑडियो इनपुट स्ट्रीम पर, अपने-आप वीएडी करता है. VAD को सेटअप कॉन्फ़िगरेशन के realtimeInputConfig.automaticActivityDetection फ़ील्ड की मदद से कॉन्फ़िगर किया जा सकता है.

जब ऑडियो स्ट्रीम को एक सेकंड से ज़्यादा समय के लिए रोका जाता है (उदाहरण के लिए, उपयोगकर्ता ने माइक्रोफ़ोन बंद कर दिया है), तो कैश मेमोरी में सेव किए गए किसी भी ऑडियो को फ़्लश करने के लिए, audioStreamEnd इवेंट भेजा जाना चाहिए. क्लाइंट, ऑडियो डेटा भेजना कभी भी फिर से शुरू कर सकता है.

# 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(api_key="GEMINI_API_KEY")
model = "gemini-2.0-flash-live-001"

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

send_realtime_input का इस्तेमाल करने पर, एपीआई वीएडी के आधार पर ऑडियो का जवाब अपने-आप देगा. send_client_content, मॉडल के कॉन्टेक्स्ट में मैसेज को क्रम से जोड़ता है, जबकि send_realtime_input को जवाब देने की सुविधा के लिए ऑप्टिमाइज़ किया जाता है. हालांकि, ऐसा करने पर मैसेज का क्रम तय नहीं होता.

अपने-आप आवाज़ का पता लगाने की सुविधा कॉन्फ़िगर करना

वीएडी गतिविधि को ज़्यादा कंट्रोल करने के लिए, यहां दिए गए पैरामीटर कॉन्फ़िगर किए जा सकते हैं. ज़्यादा जानकारी के लिए, एपीआई रेफ़रंस देखें.

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

अपने-आप बोली पहचानने की सुविधा बंद करना

इसके अलावा, सेटअप मैसेज में realtimeInputConfig.automaticActivityDetection.disabled को true पर सेट करके, अपने-आप आवाज़ पहचानने की सुविधा को बंद किया जा सकता है. इस कॉन्फ़िगरेशन में, उपयोगकर्ता की बातचीत का पता लगाने और सही समय पर activityStart और activityEnd मैसेज भेजने की ज़िम्मेदारी क्लाइंट की होती है. इस कॉन्फ़िगरेशन में audioStreamEnd नहीं भेजा जाता. इसके बजाय, स्ट्रीम में किसी भी तरह की रुकावट आने पर, activityEnd मैसेज के ज़रिए उसे मार्क किया जाता है.

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())
    # ...

टोकन की संख्या

इस्तेमाल किए गए टोकन की कुल संख्या, सर्वर से मिले मैसेज के usageMetadata फ़ील्ड में देखी जा सकती है.

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

सेशन की अवधि बढ़ाना

सेशन की ज़्यादा से ज़्यादा अवधि को दो तरीकों से अनलिमिटेड किया जा सकता है:

इसके अलावा, सेशन खत्म होने से पहले आपको GoAway मैसेज मिलेगा. इससे आपको आगे की कार्रवाइयां करने में मदद मिलेगी.

कॉन्टेक्स्ट विंडो का कम्प्रेशन

लंबे सेशन चालू करने और अचानक कनेक्शन बंद होने से बचने के लिए, सेशन कॉन्फ़िगरेशन के हिस्से के तौर पर contextWindowCompression फ़ील्ड को सेट करके, कॉन्टेक्स्ट विंडो कंप्रेसन की सुविधा चालू की जा सकती है.

ContextWindowCompressionConfig में, स्लाइडिंग-विंडो मेकेनिज्म और टोकन की संख्या को कॉन्फ़िगर किया जा सकता है. इससे कंप्रेस करने की सुविधा चालू होती है.

from google.genai import types

config = types.LiveConnectConfig(
    response_modalities=["AUDIO"],
    context_window_compression=(
        # Configures compression with default parameters.
        types.ContextWindowCompressionConfig(
            sliding_window=types.SlidingWindow(),
        )
    ),
)

सेशन फिर से शुरू करना

जब सर्वर समय-समय पर WebSocket कनेक्शन को रीसेट करता है, तो सेशन खत्म होने से रोकने के लिए, सेटअप कॉन्फ़िगरेशन में sessionResumption फ़ील्ड को कॉन्फ़िगर करें.

इस कॉन्फ़िगरेशन को पास करने पर, सर्वर SessionResumptionUpdate मैसेज भेजता है. इन मैसेज का इस्तेमाल, सेशन को फिर से शुरू करने के लिए किया जा सकता है. इसके लिए, पिछले सेशन को फिर से शुरू करने वाले टोकन को अगले कनेक्शन के SessionResumptionConfig.handle के तौर पर पास करना होगा.

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

client = genai.Client(api_key="GEMINI_API_KEY")
model = "gemini-2.0-flash-live-001"

async def main():
    print(f"Connecting to the service with handle {previous_session_handle}...")
    async with client.aio.live.connect(
        model=model,
        config=types.LiveConnectConfig(
            response_modalities=["AUDIO"],
            session_resumption=types.SessionResumptionConfig(
                # The handle of the session to resume is passed here,
                # or else None to start a new session.
                handle=previous_session_handle
            ),
        ),
    ) as session:
        while True:
            await session.send_client_content(
                turns=types.Content(
                    role="user", parts=[types.Part(text="Hello world!")]
                )
            )
            async for message in session.receive():
                # Periodically, the server will send update messages that may
                # contain a handle for the current state of the session.
                if message.session_resumption_update:
                    update = message.session_resumption_update
                    if update.resumable and update.new_handle:
                        # The handle should be retained and linked to the session.
                        return update.new_handle

                # For the purposes of this example, placeholder input is continually fed
                # to the model. In non-sample code, the model inputs would come from
                # the user.
                if message.server_content and message.server_content.turn_complete:
                    break

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

सेशन डिसकनेक्ट होने से पहले मैसेज मिलना

सर्वर, GoAway मैसेज भेजता है. इससे पता चलता है कि मौजूदा कनेक्शन जल्द ही बंद हो जाएगा. इस मैसेज में timeLeft शामिल होता है, जो बाकी बचे समय के बारे में बताता है. साथ ही, 'रद्द किया गया' के तौर पर कनेक्शन खत्म होने से पहले, आपको आगे की कार्रवाई करने की सुविधा देता है.

async for response in session.receive():
    if response.go_away is not None:
        # The connection will soon be terminated
        print(response.go_away.time_left)

जनरेट होने के बाद मैसेज पाना

सर्वर, generationComplete मैसेज भेजता है. इससे पता चलता है कि मॉडल ने जवाब जनरेट कर लिया है.

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

मीडिया का रिज़ॉल्यूशन

सेशन कॉन्फ़िगरेशन के हिस्से के तौर पर mediaResolution फ़ील्ड को सेट करके, इनपुट मीडिया के लिए मीडिया रिज़ॉल्यूशन तय किया जा सकता है:

from google.genai import types

config = types.LiveConnectConfig(
    response_modalities=["AUDIO"],
    media_resolution=types.MediaResolution.MEDIA_RESOLUTION_LOW,
)

सीमाएं

अपना प्रोजेक्ट प्लान करते समय, Live API की इन सीमाओं को ध्यान में रखें.

जवाब देने के तरीके

सेशन कॉन्फ़िगरेशन में, हर सेशन के लिए सिर्फ़ एक जवाब मोड (TEXT या AUDIO) सेट किया जा सकता है. कॉन्फ़िगरेशन से जुड़ी गड़बड़ी के मैसेज में दोनों नतीजे सेट करना. इसका मतलब है कि मॉडल को टेक्स्ट या ऑडियो में से किसी एक के साथ जवाब देने के लिए कॉन्फ़िगर किया जा सकता है. हालांकि, एक ही सेशन में दोनों का इस्तेमाल नहीं किया जा सकता.

क्लाइंट प्रमाणीकरण

लाइव एपीआई सिर्फ़ सर्वर से सर्वर की पुष्टि करता है और इसका सुझाव सीधे क्लाइंट के इस्तेमाल के लिए नहीं दिया जाता. Live API की मदद से सुरक्षित तरीके से पुष्टि करने के लिए, क्लाइंट इनपुट को किसी इंटरमीडियरी ऐप्लिकेशन सर्वर के ज़रिए रूट किया जाना चाहिए.

सत्र की अवधि

सेशन कंप्रेस करने की सुविधा चालू करके, सेशन की अवधि को अनलिमिटेड किया जा सकता है. बिना कंप्रेस किए, सिर्फ़ ऑडियो वाले सेशन 15 मिनट तक के हो सकते हैं. साथ ही, ऑडियो और वीडियो वाले सेशन दो मिनट तक के हो सकते हैं. कंप्रेस किए बिना इन सीमाओं को पार करने पर, कनेक्शन बंद हो जाएगा.

इसके अलावा, सेशन फिर से शुरू करने की सुविधा को कॉन्फ़िगर करके, क्लाइंट को उस सेशन को फिर से शुरू करने की अनुमति दी जा सकती है जिसे बंद कर दिया गया था.

कॉन्टेक्स्ट विंडो

किसी सेशन की कॉन्टेक्स्ट विंडो की सीमा 32 हज़ार टोकन होती है.

इस्तेमाल की जा सकने वाली भाषाएं

Live API इन भाषाओं में काम करता है.

भाषा BCP-47 कोड
जर्मन (जर्मनी) de-DE
अंग्रेज़ी (ऑस्ट्रेलिया) en-AU
अंग्रेज़ी (यूनाइटेड किंगडम) en-GB
अंग्रेज़ी (भारत) en-IN
अंग्रेज़ी (यूएस) en-US
स्पैनिश (संयुक्त राज्य अमेरिका) es-US
फ़्रेंच (फ़्रांस) fr-FR
हिन्दी (भारत) hi-IN
पॉर्चुगीज़ (ब्राज़ील) pt-BR
ऐरेबिक (सामान्य) ar-XA
स्पैनिश (स्पेन) es-ES
फ़्रेंच (कनाडा) fr-CA
इंडोनेशियन (इंडोनेशिया) id-ID
इतालवी (इटली) it-IT
जापानी (जापान) ja-JP
तुर्किये (तुर्किये) tr-TR
वियतनामी (वियतनाम) vi-VN
बांग्ला (भारत) bn-IN
गुजराती (भारत) gu-IN
कन्नड़ (भारत) kn-IN
मलयालम (भारत) ml-IN
मराठी (भारत) mr-IN
तमिल (भारत) ta-IN
तेलुगू (भारत) te-IN
डच (नीदरलैंड्स) nl-NL
कोरियाई (दक्षिण कोरिया) ko-KR
मैंडरिन चाइनीज़ (चीन) cmn-CN
पोलिश (पोलैंड) pl-PL
रूसी (रूस) ru-RU
थाई (थाईलैंड) th-TH

तीसरे पक्ष के इंटिग्रेशन

वेब और मोबाइल ऐप्लिकेशन को डिप्लॉय करने के लिए, इन विकल्पों को एक्सप्लोर किया जा सकता है:

आगे क्या करना है