Gemini Live API का इस्तेमाल करके, दोनों तरफ़ से स्ट्रीमिंग करना


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

Vertex AI Studio में, प्रॉम्प्ट और Live API की मदद से प्रोटोटाइप बनाया जा सकता है.

Live API एक स्टेटफ़ुल एपीआई है, जो क्लाइंट और Gemini सर्वर के बीच सेशन सेट अप करने के लिए, वेबसोकेट कनेक्शन बनाता है. ज़्यादा जानकारी के लिए, Live API रेफ़रंस दस्तावेज़ देखें.

शुरू करने से पहले

यह सिर्फ़ तब उपलब्ध होता है, जब एपीआई प्रोवाइडर के तौर पर Vertex AI Gemini API का इस्तेमाल किया जा रहा हो.

अगर आपने अब तक ऐसा नहीं किया है, तो शुरू करने से जुड़ी गाइड पढ़ें. इसमें, Firebase प्रोजेक्ट सेट अप करने, अपने ऐप्लिकेशन को Firebase से कनेक्ट करने, SDK टूल जोड़ने, Vertex AI Gemini API के लिए बैकएंड सेवा को शुरू करने, और LiveModel इंस्टेंस बनाने का तरीका बताया गया है.

इस सुविधा के साथ काम करने वाले मॉडल

Live API का इस्तेमाल सिर्फ़ gemini-2.0-flash-live-preview-04-09 के साथ किया जा सकता है, gemini-2.0-flash के साथ नहीं.

Live API की स्टैंडर्ड सुविधाओं का इस्तेमाल करना

इस सेक्शन में, Live API की स्टैंडर्ड सुविधाओं का इस्तेमाल करने का तरीका बताया गया है. खास तौर पर, अलग-अलग तरह के इनपुट और आउटपुट को स्ट्रीम करने के लिए:

स्ट्रीम किए गए टेक्स्ट इनपुट से स्ट्रीम किया गया टेक्स्ट जनरेट करना

इस सैंपल को आज़माने से पहले, अपने प्रोजेक्ट और ऐप्लिकेशन को सेट अप करने के लिए, इस गाइड का शुरू करने से पहले सेक्शन पूरा करें.
इस सेक्शन में, आपको अपनी पसंद के Gemini API सेवा देने वाली कंपनी के लिए बटन पर भी क्लिक करना होगा, ताकि आपको इस पेज पर सेवा देने वाली कंपनी से जुड़ा कॉन्टेंट दिखे.

स्ट्रीम किया गया टेक्स्ट इनपुट भेजा जा सकता है और स्ट्रीम किया गया टेक्स्ट आउटपुट भी पाया जा सकता है. liveModel इंस्टेंस बनाएं और रिस्पॉन्स मोड को Text पर सेट करें.

Swift

फ़िलहाल, Live API Apple के प्लैटफ़ॉर्म पर काम नहीं करता. हालांकि, जल्द ही यह सुविधा उपलब्ध होगी!

Kotlin

// Initialize the Vertex AI Gemini API backend service
// Create a `LiveModel` instance with the model that supports the Live API
val model = Firebase.vertexAI.liveModel(
    modelName = "gemini-2.0-flash-live-preview-04-09",
    // Configure the model to respond with text
    generationConfig = liveGenerationConfig {
        responseModality = ResponseModality.TEXT 
   }
)

val session = model.connect()

// Provide a text prompt
val text = "tell a short story"

session.send(text)

var outputText = ""
session.receive().collect {
    if(it.status == Status.TURN_COMPLETE) {
        // Optional: if you don't require to send more requests.
        session.stopReceiving();
    }
    outputText = outputText + it.text
}

// Output received from the server.
println(outputText)

Java

ExecutorService executor = Executors.newFixedThreadPool(1);
// Initialize the Vertex AI Gemini API backend service
// Create a `LiveModel` instance with the model that supports the Live API
LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.vertexAI()).liveModel(
        "gemini-2.0-flash-live-preview-04-09",
        // Configure the model to respond with text
        new LiveGenerationConfig.Builder()
                .setResponseModalities(ResponseModality.TEXT)
                .build()
);
LiveModelFutures model = LiveModelFutures.from(lm);
ListenableFuture<LiveSession> sessionFuture =  model.connect();
class LiveContentResponseSubscriber implements Subscriber<LiveContentResponse> {
    @Override
    public void onSubscribe(Subscription s) {
        s.request(Long.MAX_VALUE); // Request an unlimited number of items
    }
    @Override
    public void onNext(LiveContentResponse liveContentResponse) {
       // Handle the response from the server.
	System.out.println(liveContentResponse.getText());
    }
    @Override
    public void onError(Throwable t) {
        System.err.println("Error: " + t.getMessage());
    }
    @Override
    public void onComplete() {
        System.out.println("Done receiving messages!");
    }
}
Futures.addCallback(sessionFuture, new FutureCallback<LiveSession>() {
    @Override
    public void onSuccess(LiveSession ses) {
	  LiveSessionFutures session = LiveSessionFutures.from(ses);
        // Provide a text prompt
        String text = "tell me a short story?";
        session.send(text);
        Publisher<LiveContentResponse> publisher = session.receive();
        publisher.subscribe(new LiveContentResponseSubscriber());
    }
    @Override
    public void onFailure(Throwable t) {
        // Handle exceptions
    }
}, executor);

Web

फ़िलहाल, Live API वेब ऐप्लिकेशन के लिए उपलब्ध नहीं है. हालांकि, जल्द ही इसे उपलब्ध कराया जाएगा!

Dart

import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

late LiveModelSession _session;

await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

// Initialize the Vertex AI Gemini API backend service
// Create a `LiveModel` instance with the model that supports the Live API
final model = FirebaseAI.vertexAI().liveModel(
  model: 'gemini-2.0-flash-live-preview-04-09',
  // Configure the model to respond with text
  config: LiveGenerationConfig(responseModalities: [ResponseModality.text]),
);

_session = await model.connect();

// Provide a text prompt
final prompt = Content.text('tell a short story');
await _session.send(input: prompt, turnComplete: true);

// In a separate thread, receive the response
await for (final message in _session.receive()) {
   // Process the received message 
}

Unity

using Firebase;
using Firebase.AI;

async Task SendTextReceiveText() {
  // Initialize the Vertex AI Gemini API backend service
  // Create a `LiveModel` instance with the model that supports the Live API
  var model = FirebaseAI.GetInstance(FirebaseAI.Backend.VertexAI()).GetLiveModel(
    modelName: "gemini-2.0-flash-live-preview-04-09",
    // Configure the model to respond with text
    liveGenerationConfig: new LiveGenerationConfig(
        responseModalities: new[] { ResponseModality.Text })
  );

  LiveSession session = await model.ConnectAsync();

  // Provide a text prompt
  var prompt = ModelContent.Text("tell a short story");
  await session.SendAsync(content: prompt, turnComplete: true);

  // Receive the response
  await foreach (var message in session.ReceiveAsync()) {
    // Process the received message
    if (!string.IsNullOrEmpty(message.Text)) {
      UnityEngine.Debug.Log("Received message: " + message.Text);
    }
  }
}

अपने इस्तेमाल के उदाहरण और ऐप्लिकेशन के हिसाब से सही मॉडल चुनने का तरीका जानें.

स्ट्रीम किए गए ऑडियो इनपुट से स्ट्रीम किया गया ऑडियो जनरेट करना

इस सैंपल को आज़माने से पहले, अपने प्रोजेक्ट और ऐप्लिकेशन को सेट अप करने के लिए, इस गाइड का शुरू करने से पहले सेक्शन पूरा करें.
इस सेक्शन में, आपको अपनी पसंद के Gemini API सेवा देने वाली कंपनी के लिए बटन पर भी क्लिक करना होगा, ताकि आपको इस पेज पर सेवा देने वाली कंपनी से जुड़ा कॉन्टेंट दिखे.

स्ट्रीम किया गया ऑडियो इनपुट भेजा जा सकता है और स्ट्रीम किया गया ऑडियो आउटपुट रिसीव किया जा सकता है. LiveModel इंस्टेंस बनाएं और रिस्पॉन्स मोड को Audio पर सेट करें.

इस पेज पर आगे, जवाब देने वाली आवाज़ को कॉन्फ़िगर और पसंद के मुताबिक बनाने का तरीका जानें.

Swift

फ़िलहाल, Live API Apple के प्लैटफ़ॉर्म पर काम नहीं करता. हालांकि, जल्द ही यह सुविधा उपलब्ध होगी!

Kotlin

// Initialize the Vertex AI Gemini API backend service
// Create a `LiveModel` instance with the model that supports the Live API
val model = Firebase.vertexAI.liveModel(
    modelName = "gemini-2.0-flash-live-preview-04-09",
    // Configure the model to respond with text
    generationConfig = liveGenerationConfig {
        responseModality = ResponseModality.AUDIO 
   }
)

val session = model.connect()

// This is the recommended way.
// However, you can create your own recorder and handle the stream.
session.startAudioConversation()

Java

ExecutorService executor = Executors.newFixedThreadPool(1);
// Initialize the Vertex AI Gemini API backend service
// Create a `LiveModel` instance with the model that supports the Live API
LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.vertexAI()).liveModel(
        "gemini-2.0-flash-live-preview-04-09",
        // Configure the model to respond with text
        new LiveGenerationConfig.Builder()
                .setResponseModalities(ResponseModality.TEXT)
                .build()
);
LiveModelFutures model = LiveModelFutures.from(lm);
ListenableFuture<LiveSession> sessionFuture =  model.connect();

Futures.addCallback(sessionFuture, new FutureCallback<LiveSession>() {
    @Override
    public void onSuccess(LiveSession ses) {
	 LiveSessionFutures session = LiveSessionFutures.from(ses);
        session.startAudioConversation();
    }
    @Override
    public void onFailure(Throwable t) {
        // Handle exceptions
    }
}, executor);

Web

फ़िलहाल, Live API वेब ऐप्लिकेशन के लिए उपलब्ध नहीं है. हालांकि, जल्द ही इसे उपलब्ध कराया जाएगा!

Dart

import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
import 'package:your_audio_recorder_package/your_audio_recorder_package.dart';

late LiveModelSession _session;
final _audioRecorder = YourAudioRecorder();

await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

// Initialize the Vertex AI Gemini API backend service
// Create a `LiveModel` instance with the model that supports the Live API
final model = FirebaseAI.vertexAI().liveModel(
  model: 'gemini-2.0-flash-live-preview-04-09',
   // Configure the model to respond with audio
   config: LiveGenerationConfig(responseModalities: [ResponseModality.audio]),
);

_session = await model.connect();

final audioRecordStream = _audioRecorder.startRecordingStream();
// Map the Uint8List stream to InlineDataPart stream
final mediaChunkStream = audioRecordStream.map((data) {
  return InlineDataPart('audio/pcm', data);
});
await _session.startMediaStream(mediaChunkStream);

// In a separate thread, receive the audio response from the model
await for (final message in _session.receive()) {
   // Process the received message 
}

Unity

using Firebase;
using Firebase.AI;

async Task SendTextReceiveAudio() {
  // Initialize the Vertex AI Gemini API backend service
  // Create a `LiveModel` instance with the model that supports the Live API
  var model = FirebaseAI.GetInstance(FirebaseAI.Backend.VertexAI()).GetLiveModel(
    modelName: "gemini-2.0-flash-live-preview-04-09",
    // Configure the model to respond with audio
    liveGenerationConfig: new LiveGenerationConfig(
        responseModalities: new[] { ResponseModality.Audio })
  );

  LiveSession session = await model.ConnectAsync();

  // Start a coroutine to send audio from the Microphone
  var recordingCoroutine = StartCoroutine(SendAudio(session));

  // Start receiving the response
  await ReceiveAudio(session);
}

IEnumerator SendAudio(LiveSession liveSession) {
  string microphoneDeviceName = null;
  int recordingFrequency = 16000;
  int recordingBufferSeconds = 2;

  var recordingClip = Microphone.Start(microphoneDeviceName, true,
                                       recordingBufferSeconds, recordingFrequency);

  int lastSamplePosition = 0;
  while (true) {
    if (!Microphone.IsRecording(microphoneDeviceName)) {
      yield break;
    }

    int currentSamplePosition = Microphone.GetPosition(microphoneDeviceName);

    if (currentSamplePosition != lastSamplePosition) {
      // The Microphone uses a circular buffer, so we need to check if the
      // current position wrapped around to the beginning, and handle it
      // accordingly.
      int sampleCount;
      if (currentSamplePosition > lastSamplePosition) {
        sampleCount = currentSamplePosition - lastSamplePosition;
      } else {
        sampleCount = recordingClip.samples - lastSamplePosition + currentSamplePosition;
      }

      if (sampleCount > 0) {
        // Get the audio chunk
        float[] samples = new float[sampleCount];
        recordingClip.GetData(samples, lastSamplePosition);

        // Send the data, discarding the resulting Task to avoid the warning
        _ = liveSession.SendAudioAsync(samples);

        lastSamplePosition = currentSamplePosition;
      }
    }

    // Wait for a short delay before reading the next sample from the Microphone
    const float MicrophoneReadDelay = 0.5f;
    yield return new WaitForSeconds(MicrophoneReadDelay);
  }
}

Queue audioBuffer = new();

async Task ReceiveAudio(LiveSession liveSession) {
  int sampleRate = 24000;
  int channelCount = 1;

  // Create a looping AudioClip to fill with the received audio data
  int bufferSamples = (int)(sampleRate * channelCount);
  AudioClip clip = AudioClip.Create("StreamingPCM", bufferSamples, channelCount,
                                    sampleRate, true, OnAudioRead);

  // Attach the clip to an AudioSource and start playing it
  AudioSource audioSource = GetComponent();
  audioSource.clip = clip;
  audioSource.loop = true;
  audioSource.Play();

  // Start receiving the response
  await foreach (var message in liveSession.ReceiveAsync()) {
    // Process the received message
    foreach (float[] pcmData in message.AudioAsFloat) {
      lock (audioBuffer) {
        foreach (float sample in pcmData) {
          audioBuffer.Enqueue(sample);
        }
      }
    }
  }
}

// This method is called by the AudioClip to load audio data.
private void OnAudioRead(float[] data) {
  int samplesToProvide = data.Length;
  int samplesProvided = 0;

  lock(audioBuffer) {
    while (samplesProvided < samplesToProvide && audioBuffer.Count > 0) {
      data[samplesProvided] = audioBuffer.Dequeue();
      samplesProvided++;
    }
  }

  while (samplesProvided < samplesToProvide) {
    data[samplesProvided] = 0.0f;
    samplesProvided++;
  }
}

अपने इस्तेमाल के उदाहरण और ऐप्लिकेशन के हिसाब से सही मॉडल चुनने का तरीका जानें.



दर्शकों को ज़्यादा दिलचस्प और इंटरैक्टिव अनुभव देना

इस सेक्शन में, Live API की ज़्यादा दिलचस्प या इंटरैक्टिव सुविधाएं बनाने और उन्हें मैनेज करने का तरीका बताया गया है.

जवाब देने वाली आवाज़ बदलना

Live API, सिंथेटिक वॉइस की मदद से जवाब देने के लिए, Chirp 3 का इस्तेमाल करता है. Firebase AI Logic का इस्तेमाल करके, एचडी क्वालिटी वाली पांच आवाज़ों और 31 भाषाओं में ऑडियो भेजा जा सकता है.

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

Aoede (महिला)
Charon (पुरुष)
Fenrir (पुरुष)
Kore (महिला)
Puck (पुरुष)

इन आवाज़ों की क्वालिटी जानने और उपलब्ध भाषाओं की पूरी सूची देखने के लिए, Chirp 3: एचडी आवाज़ें देखें.

किसी आवाज़ को चुनने के लिए, speechConfig ऑब्जेक्ट में आवाज़ का नाम सेट करें. यह नाम, मॉडल कॉन्फ़िगरेशन का हिस्सा होता है:

Swift

फ़िलहाल, Live API Apple के प्लैटफ़ॉर्म पर काम नहीं करता. हालांकि, जल्द ही यह सुविधा उपलब्ध होगी!

Kotlin

// ...

val model = Firebase.vertexAI.liveModel(
    modelName = "gemini-2.0-flash-live-preview-04-09",
    // Configure the model to use a specific voice for its audio response
    generationConfig = liveGenerationConfig {
        responseModality = ResponseModality.AUDIO
        speechConfig = SpeechConfig(voice = Voices.FENRIR)
    }
)

// ...

Java

// ...

LiveModel model = Firebase.getVertexAI().liveModel(
    "gemini-2.0-flash-live-preview-04-09",
    // Configure the model to use a specific voice for its audio response
    new LiveGenerationConfig.Builder()
        .setResponseModalities(ResponseModality.AUDIO)
        .setSpeechConfig(new SpeechConfig(Voices.FENRIR))
        .build()
);

// ...

Web

फ़िलहाल, Live API वेब ऐप्लिकेशन के लिए उपलब्ध नहीं है. हालांकि, जल्द ही इसे उपलब्ध कराया जाएगा!

Dart

// ...

final model = FirebaseVertexAI.instance.liveModel(
  model: 'gemini-2.0-flash-live-preview-04-09',
  // Configure the model to use a specific voice for its audio response
  config: LiveGenerationConfig(
    responseModality: ResponseModality.audio,
    speechConfig: SpeechConfig(voice: Voice.fenrir),
  ),
);

// ...

Unity

Snippets coming soon!

मॉडल को अंग्रेज़ी के अलावा किसी दूसरी भाषा में जवाब देने के लिए कहने और उससे जवाब पाने के लिए, सिस्टम के निर्देशों में ये चीज़ें शामिल करें, ताकि आपको सबसे अच्छे नतीजे मिलें:

RESPOND IN LANGUAGE. YOU MUST RESPOND UNMISTAKABLY IN LANGUAGE.

सभी सेशन और अनुरोधों में कॉन्टेक्स्ट बनाए रखना

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

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

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

Firebase AI Logic में, रुकावटों को मैनेज करने की सुविधा अभी उपलब्ध नहीं है. जल्‍द ही वापस जाँचें!

फ़ंक्शन कॉलिंग (टूल) का इस्तेमाल करना

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

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

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

क्लाइंट को BidiGenerateContentToolResponse के साथ जवाब देना चाहिए.



सीमाएं और ज़रूरी शर्तें

Live API की इन सीमाओं और ज़रूरी शर्तों का ध्यान रखें.

लिप्यंतरण

फ़िलहाल, Firebase AI Logic पर बोली को लेख में बदलने की सुविधा उपलब्ध नहीं है. जल्‍द ही वापस जाँचें!

भाषाएं

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

Live API इन ऑडियो फ़ॉर्मैट के साथ काम करता है:

  • इनपुट ऑडियो फ़ॉर्मैट: 16 किलोहर्ट्ज़ के लिटल-इंडियन फ़ॉर्मैट में रॉ 16 बिट PCM ऑडियो
  • आउटपुट ऑडियो फ़ॉर्मैट: 24kHz के little-endian में रॉ 16 बिट PCM ऑडियो

दर की सीमाएं

दर से जुड़ी ये सीमाएं लागू होती हैं:

  • हर Firebase प्रोजेक्ट के लिए, एक साथ 10 सेशन
  • हर मिनट 40 लाख टोकन

सेशन की अवधि

सेशन की डिफ़ॉल्ट अवधि 30 मिनट होती है. सेशन की अवधि तय सीमा से ज़्यादा होने पर, कनेक्शन बंद हो जाता है.

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

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

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

टोकन की गिनती

CountTokens एपीआई का इस्तेमाल Live API के साथ नहीं किया जा सकता.


Firebase AI Logic के साथ अपने अनुभव के बारे में सुझाव/राय दें या शिकायत करें