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 का रेफ़रंस देखें.

आउटपुट जनरेशन

Live API, रीयल-टाइम में टेक्स्ट या ऑडियो जनरेट करने के लिए, अलग-अलग तरह के इनपुट (टेक्स्ट, ऑडियो, वीडियो) को प्रोसेस करता है. इसमें ऑडियो जनरेट करने की सुविधा पहले से मौजूद होती है. आपके इस्तेमाल किए जा रहे मॉडल के वर्शन के हिसाब से, यह ऑडियो जनरेट करने के इनमें से किसी एक तरीके का इस्तेमाल करता है:

  • हाफ़ कैस्केड: इस मॉडल को नेटिव ऑडियो इनपुट मिलता है. साथ ही, इनपुट को प्रोसेस करने और ऑडियो आउटपुट जनरेट करने के लिए, अलग-अलग मॉडल के खास कैस्केड का इस्तेमाल किया जाता है.
  • नेटिव: Gemini 2.5 में नेटिव ऑडियो जनरेशन की सुविधा जोड़ी गई है. इससे, ऑडियो आउटपुट सीधे जनरेट होता है. इससे, ऑडियो ज़्यादा स्वाभाविक लगता है, भावनाओं को बेहतर तरीके से ज़ाहिर करने वाली आवाज़ें मिलती हैं, और ज़्यादा कॉन्टेक्स्ट की जानकारी मिलती है. जैसे, टोन और ज़्यादा सक्रिय जवाब.

Live API का इस्तेमाल करके लैंडिंग पेज बनाना

Live API का इस्तेमाल करके प्रोजेक्ट बनाने से पहले, अपनी ज़रूरतों के हिसाब से ऑडियो जनरेट करने का सबसे सही तरीका चुनें.

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

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

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

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

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

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

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

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

PythonJavaScript
# 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())
// 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 फ़ाइल के तौर पर सेव किया जाता है:

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

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

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

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

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

PythonJavaScript
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())
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],
  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();

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

PythonJavaScript
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"],
    "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())
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],
  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();

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

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

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

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

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

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

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

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

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

Live API में इन आवाज़ों का इस्तेमाल किया जा सकता है: Puck, Charon, Kore, Fenrir, Aoede, Leda, Orus, और Zephyr.

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

PythonJavaScript
config = {
    "response_modalities": ["AUDIO"],
    "speech_config": {
        "voice_config": {"prebuilt_voice_config": {"voice_name": "Kore"}}
    },
}
const config = {
  responseModalities: [Modality.AUDIO],
  speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: "Kore" } } }
};

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

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

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

नेटिव ऑडियो आउटपुट

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

नेटिव ऑडियो आउटपुट, इन नेटिव ऑडियो मॉडल के साथ काम करता है:

  • gemini-2.5-flash-preview-native-audio-dialog
  • gemini-2.5-flash-exp-native-audio-thinking-dialog

नेटिव ऑडियो आउटपुट का इस्तेमाल करने का तरीका

नेटिव ऑडियो आउटपुट का इस्तेमाल करने के लिए, नेटिव ऑडियो मॉडल में से किसी एक को कॉन्फ़िगर करें और response_modalities को AUDIO पर सेट करें.

पूरा उदाहरण देखने के लिए, ऑडियो भेजना और पाना लेख पढ़ें.

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

भावुक डायलॉग

इस सुविधा की मदद से, Gemini अपने जवाब की स्टाइल को इनपुट एक्सप्रेशन और टोन के हिसाब से अडजस्ट कर सकता है.

एफ़ेक्टिव डायलॉग का इस्तेमाल करने के लिए, एपीआई वर्शन को v1alpha पर सेट करें और सेटअप मैसेज में enable_affective_dialog को true पर सेट करें:

PythonJavaScript
client = genai.Client(api_key="GOOGLE_API_KEY", http_options={"api_version": "v1alpha"})

config = types.LiveConnectConfig(
    response_modalities=["AUDIO"],
    enable_affective_dialog=True
)
const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY", httpOptions: {"apiVersion": "v1alpha"} });

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

ध्यान दें कि फ़िलहाल, भावों के हिसाब से डायलॉग जनरेट करने की सुविधा, सिर्फ़ नेटिव ऑडियो आउटपुट मॉडल के साथ काम करती है.

ऑडियो के लिए प्रोएक्टिव सुविधा

इस सुविधा के चालू होने पर, Gemini यह तय कर सकता है कि अगर कोई कॉन्टेंट काम का नहीं है, तो उस पर जवाब न दिया जाए.

इसका इस्तेमाल करने के लिए, एपीआई वर्शन को v1alpha पर सेट करें. साथ ही, सेटअप मैसेज में proactivity फ़ील्ड को कॉन्फ़िगर करें और proactive_audio को true पर सेट करें:

PythonJavaScript
client = genai.Client(api_key="GOOGLE_API_KEY", http_options={"api_version": "v1alpha"})

config = types.LiveConnectConfig(
    response_modalities=["AUDIO"],
    proactivity={'proactive_audio': True}
)
const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY", httpOptions: {"apiVersion": "v1alpha"} });

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

ध्यान दें कि फ़िलहाल, ऑडियो के लिए पहले से तैयार मॉडल के साथ ही, ऑडियो के लिए पहले से तैयार ऑडियो आउटपुट मॉडल का इस्तेमाल किया जा सकता है.

सोचने की सुविधा के साथ नेटिव ऑडियो आउटपुट

नेटिव ऑडियो आउटपुट में सोचने की सुविधाएं काम करती हैं. ये सुविधाएं, gemini-2.5-flash-exp-native-audio-thinking-dialog नाम के अलग मॉडल के ज़रिए उपलब्ध हैं.

पूरा उदाहरण देखने के लिए, ऑडियो भेजना और पाना लेख पढ़ें.

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

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

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

इस्तेमाल किए जा सकने वाले टूल की खास जानकारी

यहां हर मॉडल के लिए उपलब्ध टूल के बारे में खास जानकारी दी गई है:

टूल कैस्केड किए गए मॉडल
gemini-2.0-flash-live-001
gemini-2.5-flash-preview-native-audio-dialog gemini-2.5-flash-exp-native-audio-thinking-dialog
खोजें हां हां हां
फ़ंक्शन कॉलिंग हां हां नहीं
कोड चलाना हां नहीं नहीं
यूआरएल का कॉन्टेक्स्ट हां नहीं नहीं

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

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

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

Python JavaScript
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 chunk.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())
import { GoogleGenAI, Modality } from '@google/genai';

const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
const model = 'gemini-2.0-flash-live-001';

// Simple function definitions
const turn_on_the_lights = { name: "turn_on_the_lights" } // , description: '...', parameters: { ... }
const turn_off_the_lights = { name: "turn_off_the_lights" }

const tools = [{ functionDeclarations: [turn_on_the_lights, turn_off_the_lights] }]

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

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;
      } else if (message.toolCall) {
        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 = 'Turn on the lights please';
  session.sendClientContent({ turns: inputTurns });

  let turns = await handleTurn();

  for (const turn of turns) {
    if (turn.serverContent && turn.serverContent.modelTurn && turn.serverContent.modelTurn.parts) {
      for (const part of turn.serverContent.modelTurn.parts) {
        if (part.text) {
          console.debug('Received text: %s\n', part.text);
        }
      }
    }
    else if (turn.toolCall) {
      const functionResponses = [];
      for (const fc of turn.toolCall.functionCalls) {
        functionResponses.push({
          id: fc.id,
          name: fc.name,
          response: { result: "ok" } // simple, hard-coded function response
        });
      }

      console.debug('Sending tool response...\n');
      session.sendToolResponse({ functionResponses: functionResponses });
    }
  }

  // Check again for new messages
  turns = await handleTurn();

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

  session.close();
}

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

main();

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

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

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

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

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

Python JavaScript
  # 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
import { GoogleGenAI, Modality, Behavior } from '@google/genai';

// Non-blocking function definitions
const turn_on_the_lights = {name: "turn_on_the_lights", behavior: Behavior.NON_BLOCKING}

// Blocking function definitions
const turn_off_the_lights = {name: "turn_off_the_lights"}

const tools = [{ functionDeclarations: [turn_on_the_lights, turn_off_the_lights] }]

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

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

  • वह जो भी कर रहा है उसे बीच में रोककर, आपको तुरंत जवाब दे सकता है (scheduling="INTERRUPT"),
  • जब तक यह प्रोसेस पूरी न हो जाए तब तक इंतज़ार करें (scheduling="WHEN_IDLE"),
  • इसके अलावा, कुछ न करें और उस जानकारी का इस्तेमाल बाद में चर्चा में करें (scheduling="SILENT")

Python JavaScript
# for a non-blocking function definition, apply scheduling in the function response:
  function_response = types.FunctionResponse(
      id=fc.id,
      name=fc.name,
      response={
          "result": "ok",
          "scheduling": "INTERRUPT" # Can also be WHEN_IDLE or SILENT
      }
  )
import { GoogleGenAI, Modality, Behavior, FunctionResponseScheduling } from '@google/genai';

// for a non-blocking function definition, apply scheduling in the function response:
const functionResponse = {
  id: fc.id,
  name: fc.name,
  response: {
    result: "ok",
    scheduling: FunctionResponseScheduling.INTERRUPT  // Can also be WHEN_IDLE or SILENT
  }
}

कोड चलाना

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

Python JavaScript
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())
import { GoogleGenAI, Modality } from '@google/genai';

const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
const model = 'gemini-2.0-flash-live-001';

const tools = [{codeExecution: {}}]
const config = {
  responseModalities: [Modality.TEXT],
  tools: tools
}

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;
      } else if (message.toolCall) {
        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 = 'Compute the largest prime palindrome under 100000.';
  session.sendClientContent({ turns: inputTurns });

  const turns = await handleTurn();

  for (const turn of turns) {
    if (turn.serverContent && turn.serverContent.modelTurn && turn.serverContent.modelTurn.parts) {
      for (const part of turn.serverContent.modelTurn.parts) {
        if (part.text) {
          console.debug('Received text: %s\n', part.text);
        }
        else if (part.executableCode) {
          console.debug('executableCode: %s\n', part.executableCode.code);
        }
        else if (part.codeExecutionResult) {
          console.debug('codeExecutionResult: %s\n', part.codeExecutionResult.output);
        }
      }
    }
  }

  session.close();
}

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

main();

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

Python JavaScript
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())
import { GoogleGenAI, Modality } from '@google/genai';

const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
const model = 'gemini-2.0-flash-live-001';

const tools = [{googleSearch: {}}]
const config = {
  responseModalities: [Modality.TEXT],
  tools: tools
}

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;
      } else if (message.toolCall) {
        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 = 'When did the last Brazil vs. Argentina soccer match happen?';
  session.sendClientContent({ turns: inputTurns });

  const turns = await handleTurn();

  for (const turn of turns) {
    if (turn.serverContent && turn.serverContent.modelTurn && turn.serverContent.modelTurn.parts) {
      for (const part of turn.serverContent.modelTurn.parts) {
        if (part.text) {
          console.debug('Received text: %s\n', part.text);
        }
        else if (part.executableCode) {
          console.debug('executableCode: %s\n', part.executableCode.code);
        }
        else if (part.codeExecutionResult) {
          console.debug('codeExecutionResult: %s\n', part.codeExecutionResult.output);
        }
      }
    }
  }

  session.close();
}

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

main();

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

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

Python JavaScript
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}
const 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!
`

const tools = [
  { googleSearch: {} },
  { codeExecution: {} },
  { functionDeclarations: [turn_on_the_lights, turn_off_the_lights] }
]

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

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

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

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

PythonJavaScript
async for response in session.receive():
    if response.server_content.interrupted is True:
        # The generation was interrupted
const turns = await handleTurn();

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

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

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

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

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

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

PythonJavaScript
# 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())
// 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({ 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.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();

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

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

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

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

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

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

PythonJavaScript
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())
    # ...
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: {} })

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

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

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

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

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

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

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

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

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

PythonJavaScript
from google.genai import types

config = {
    "response_modalities": ["AUDIO"],
    "context_window_compression": (
        # Configures compression with default parameters.
        types.ContextWindowCompressionConfig(
            sliding_window=types.SlidingWindow(),
        )
    ),
}
const config = {
  responseModalities: [Modality.AUDIO],
  contextWindowCompression: { slidingWindow: {} }
};

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

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

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

PythonJavaScript
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():
                if message.session_resumption_update:
                    update = message.session_resumption_update
                    if update.resumable and update.new_handle:
                        newHandle = update.new_handle
                        # TODO: store newHandle and start new session with this handle
                        # ...

if __name__ == "__main__":
    asyncio.run(main())
import { GoogleGenAI, Modality } from '@google/genai';

const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
const model = 'gemini-2.0-flash-live-001';

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

  console.debug('Connecting to the service with handle %s...', previousSessionHandle)
  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: {
      responseModalities: [Modality.TEXT],
      sessionResumption: { handle: previousSessionHandle }
      // The handle of the session to resume is passed here, or else null to start a new session.
    }
  });

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

  const turns = await handleTurn();
  for (const turn of turns) {
    if (turn.sessionResumptionUpdate) {
      if (turn.sessionResumptionUpdate.resumable && turn.sessionResumptionUpdate.newHandle) {
        let newHandle = turn.sessionResumptionUpdate.newHandle
        // TODO: store newHandle and start new session with this handle
        // ...
      }
    }
  }

  session.close();
}

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

main();

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

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

PythonJavaScript
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)
const turns = await handleTurn();

for (const turn of turns) {
  if (turn.goAway) {
    console.debug('Time left: %s\n', turn.goAway.timeLeft);
  }
}

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

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

PythonJavaScript
async for response in session.receive():
    if response.server_content.generation_complete is True:
        # The generation is complete
const turns = await handleTurn();

for (const turn of turns) {
  if (turn.serverContent && turn.serverContent.generationComplete) {
    // The generation is complete
  }
}

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

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

PythonJavaScript
from google.genai import types

config = {
    "response_modalities": ["AUDIO"],
    "media_resolution": types.MediaResolution.MEDIA_RESOLUTION_LOW,
}
import { GoogleGenAI, Modality, MediaResolution } from '@google/genai';

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

सीमाएं

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

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

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

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

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

सत्र की अवधि

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

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

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

किसी सेशन की कॉन्टेक्स्ट विंडो की सीमा:

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

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

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

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

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