Gemini API का इस्तेमाल करके टेक्स्ट जनरेट करना

Gemini मॉडल से, सिर्फ़ टेक्स्ट वाले प्रॉम्प्ट या कई तरह के प्रॉम्प्ट से टेक्स्ट जनरेट करने के लिए कहा जा सकता है. Firebase AI Logic का इस्तेमाल करने पर, यह अनुरोध सीधे अपने ऐप्लिकेशन से किया जा सकता है.

मल्टीमोडल प्रॉम्प्ट में कई तरह के इनपुट शामिल हो सकते हैं. जैसे, इमेज के साथ टेक्स्ट, PDF, सादा टेक्स्ट फ़ाइलें, ऑडियो, और वीडियो.

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

सिर्फ़ टेक्स्ट इनपुट के लिए कोड सैंपल पर जाएं अलग-अलग तरह के इनपुट के लिए कोड सैंपल पर जाएं


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

इस पेज पर, सेवा देने वाली कंपनी से जुड़ा कॉन्टेंट और कोड देखने के लिए, Gemini API पर क्लिक करें.

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

हमारा सुझाव है कि अपने प्रॉम्प्ट की जांच करने और उन पर बार-बार काम करने के लिए, Google AI Studio का इस्तेमाल करें. इससे, जनरेट किया गया कोड स्निपेट भी मिल सकता है.

सिर्फ़ टेक्स्ट वाले इनपुट से टेक्स्ट जनरेट करना

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

Gemini मॉडल से टेक्स्ट जनरेट करने के लिए कहा जा सकता है. इसके लिए, सिर्फ़ टेक्स्ट वाले इनपुट का इस्तेमाल करें.

Swift KotlinJavaWebDart Unity

सिर्फ़ टेक्स्ट वाले इनपुट से टेक्स्ट जनरेट करने के लिए, generateContent() को कॉल किया जा सकता है.


import FirebaseAI

// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.generativeModel(modelName: "gemini-2.0-flash")


// Provide a prompt that contains text
let prompt = "Write a story about a magic backpack."

// To generate text output, call generateContent with the text input
let response = try await model.generateContent(prompt)
print(response.text ?? "No text in response.")

सिर्फ़ टेक्स्ट वाले इनपुट से टेक्स्ट जनरेट करने के लिए, generateContent() को कॉल किया जा सकता है.

Kotlin के लिए, इस SDK टूल में मौजूद मैथड, सस्पेंड फ़ंक्शन हैं. इन्हें कोरूटीन स्कोप से कॉल किया जाना चाहिए.

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
                        .generativeModel("gemini-2.0-flash")


// Provide a prompt that contains text
val prompt = "Write a story about a magic backpack."

// To generate text output, call generateContent with the text input
val response = generativeModel.generateContent(prompt)
print(response.text)

सिर्फ़ टेक्स्ट वाले इनपुट से टेक्स्ट जनरेट करने के लिए, generateContent() को कॉल किया जा सकता है.

Java के लिए, इस SDK टूल के तरीके ListenableFuture दिखाते हैं.

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
        .generativeModel("gemini-2.0-flash");

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);


// Provide a prompt that contains text
Content prompt = new Content.Builder()
    .addText("Write a story about a magic backpack.")
    .build();

// To generate text output, call generateContent with the text input
ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        System.out.println(resultText);
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

सिर्फ़ टेक्स्ट वाले इनपुट से टेक्स्ट जनरेट करने के लिए, generateContent() को कॉल किया जा सकता है.


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";

// TODO(developer) Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(ai, { model: "gemini-2.0-flash" });


// Wrap in an async function so you can use await
async function run() {
  // Provide a prompt that contains text
  const prompt = "Write a story about a magic backpack."

  // To generate text output, call generateContent with the text input
  const result = await model.generateContent(prompt);

  const response = result.response;
  const text = response.text();
  console.log(text);
}

run();

सिर्फ़ टेक्स्ट वाले इनपुट से टेक्स्ट जनरेट करने के लिए, generateContent() को कॉल किया जा सकता है.


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

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

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
final model =
      FirebaseAI.googleAI().generativeModel(model: 'gemini-2.0-flash');


// Provide a prompt that contains text
final prompt = [Content.text('Write a story about a magic backpack.')];

// To generate text output, call generateContent with the text input
final response = await model.generateContent(prompt);
print(response.text);

सिर्फ़ टेक्स्ट वाले इनपुट से टेक्स्ट जनरेट करने के लिए, GenerateContentAsync() को कॉल किया जा सकता है.


using Firebase;
using Firebase.AI;

// Initialize the Gemini Developer API backend service
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` instance with a model that supports your use case
var model = ai.GetGenerativeModel(modelName: "gemini-2.0-flash");


// Provide a prompt that contains text
var prompt = "Write a story about a magic backpack.";

// To generate text output, call GenerateContentAsync with the text input
var response = await model.GenerateContentAsync(prompt);
UnityEngine.Debug.Log(response.Text ?? "No text in response.");

टेक्स्ट और फ़ाइल (मल्टीमोडल) इनपुट से टेक्स्ट जनरेट करना

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

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

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

ध्यान दें कि इस उदाहरण में, फ़ाइल को इनलाइन में उपलब्ध कराने का तरीका बताया गया है. हालांकि, एसडीके में YouTube का यूआरएल उपलब्ध कराने की सुविधा भी उपलब्ध है.

सार्वजनिक तौर पर उपलब्ध इस फ़ाइल का इस्तेमाल, video/mp4 के एमआईएमई टाइप के साथ किया जा सकता है (फ़ाइल देखें या डाउनलोड करें). https://storage.googleapis.com/cloud-samples-data/video/animals.mp4

Swift KotlinJavaWebDart Unity

टेक्स्ट और वीडियो फ़ाइलों के मल्टीमोडल इनपुट से टेक्स्ट जनरेट करने के लिए, generateContent() को कॉल किया जा सकता है.


import FirebaseAI

// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.generativeModel(modelName: "gemini-2.0-flash")


// Provide the video as `Data` with the appropriate MIME type.
let video = InlineDataPart(data: try Data(contentsOf: videoURL), mimeType: "video/mp4")

// Provide a text prompt to include with the video
let prompt = "What is in the video?"

// To generate text output, call generateContent with the text and video
let response = try await model.generateContent(video, prompt)
print(response.text ?? "No text in response.")

टेक्स्ट और वीडियो फ़ाइलों के मल्टीमोडल इनपुट से टेक्स्ट जनरेट करने के लिए, generateContent() को कॉल किया जा सकता है.

Kotlin के लिए, इस SDK टूल में मौजूद मैथड, सस्पेंड फ़ंक्शन हैं. इन्हें कोरूटीन स्कोप से कॉल किया जाना चाहिए.

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
                        .generativeModel("gemini-2.0-flash")


val contentResolver = applicationContext.contentResolver
contentResolver.openInputStream(videoUri).use { stream ->
  stream?.let {
    val bytes = stream.readBytes()

    // Provide a prompt that includes the video specified above and text
    val prompt = content {
        inlineData(bytes, "video/mp4")
        text("What is in the video?")
    }

    // To generate text output, call generateContent with the prompt
    val response = generativeModel.generateContent(prompt)
    Log.d(TAG, response.text ?: "")
  }
}

टेक्स्ट और वीडियो फ़ाइलों के मल्टीमोडल इनपुट से टेक्स्ट जनरेट करने के लिए, generateContent() को कॉल किया जा सकता है.

Java के लिए, इस SDK टूल के तरीके ListenableFuture दिखाते हैं.

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
        .generativeModel("gemini-2.0-flash");

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);


ContentResolver resolver = getApplicationContext().getContentResolver();
try (InputStream stream = resolver.openInputStream(videoUri)) {
    File videoFile = new File(new URI(videoUri.toString()));
    int videoSize = (int) videoFile.length();
    byte[] videoBytes = new byte[videoSize];
    if (stream != null) {
        stream.read(videoBytes, 0, videoBytes.length);
        stream.close();

        // Provide a prompt that includes the video specified above and text
        Content prompt = new Content.Builder()
                .addInlineData(videoBytes, "video/mp4")
                .addText("What is in the video?")
                .build();

        // To generate text output, call generateContent with the prompt
        ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
        Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
            @Override
            public void onSuccess(GenerateContentResponse result) {
                String resultText = result.getText();
                System.out.println(resultText);
            }

            @Override
            public void onFailure(Throwable t) {
                t.printStackTrace();
            }
        }, executor);
    }
} catch (IOException e) {
    e.printStackTrace();
} catch (URISyntaxException e) {
    e.printStackTrace();
}

टेक्स्ट और वीडियो फ़ाइलों के मल्टीमोडल इनपुट से टेक्स्ट जनरेट करने के लिए, generateContent() को कॉल किया जा सकता है.


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";

// TODO(developer) Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(ai, { model: "gemini-2.0-flash" });


// Converts a File object to a Part object.
async function fileToGenerativePart(file) {
  const base64EncodedDataPromise = new Promise((resolve) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result.split(',')[1]);
    reader.readAsDataURL(file);
  });
  return {
    inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
  };
}

async function run() {
  // Provide a text prompt to include with the video
  const prompt = "What do you see?";

  const fileInputEl = document.querySelector("input[type=file]");
  const videoPart = await fileToGenerativePart(fileInputEl.files[0]);

  // To generate text output, call generateContent with the text and video
  const result = await model.generateContent([prompt, videoPart]);

  const response = result.response;
  const text = response.text();
  console.log(text);
}

run();

टेक्स्ट और वीडियो फ़ाइलों के मल्टीमोडल इनपुट से टेक्स्ट जनरेट करने के लिए, generateContent() को कॉल किया जा सकता है.


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

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

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
final model =
      FirebaseAI.googleAI().generativeModel(model: 'gemini-2.0-flash');


// Provide a text prompt to include with the video
final prompt = TextPart("What's in the video?");

// Prepare video for input
final video = await File('video0.mp4').readAsBytes();

// Provide the video as `Data` with the appropriate mimetype
final videoPart = InlineDataPart('video/mp4', video);

// To generate text output, call generateContent with the text and images
final response = await model.generateContent([
  Content.multi([prompt, ...videoPart])
]);
print(response.text);

टेक्स्ट और वीडियो फ़ाइलों के मल्टीमोडल इनपुट से टेक्स्ट जनरेट करने के लिए, GenerateContentAsync() को कॉल किया जा सकता है.


using Firebase;
using Firebase.AI;

// Initialize the Gemini Developer API backend service
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` instance with a model that supports your use case
var model = ai.GetGenerativeModel(modelName: "gemini-2.0-flash");


// Provide the video as `data` with the appropriate MIME type.
var video = ModelContent.InlineData("video/mp4",
      System.IO.File.ReadAllBytes(System.IO.Path.Combine(
          UnityEngine.Application.streamingAssetsPath, "yourVideo.mp4")));

// Provide a text prompt to include with the video
var prompt = ModelContent.Text("What is in the video?");

// To generate text output, call GenerateContentAsync with the text and video
var response = await model.GenerateContentAsync(new [] { video, prompt });
UnityEngine.Debug.Log(response.Text ?? "No text in response.");

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

जवाब स्ट्रीम करना

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

मॉडल जनरेशन के पूरे नतीजे का इंतज़ार किए बिना, तेज़ी से इंटरैक्शन हासिल किए जा सकते हैं. इसके बजाय, कुछ नतीजों को मैनेज करने के लिए स्ट्रीमिंग का इस्तेमाल करें. जवाब को स्ट्रीम करने के लिए, generateContentStream को कॉल करें.

Swift KotlinJavaWebDart Unity

सिर्फ़ टेक्स्ट वाले इनपुट से जनरेट किए गए टेक्स्ट को स्ट्रीम करने के लिए, generateContentStream() को कॉल किया जा सकता है.


import FirebaseAI

// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.generativeModel(modelName: "gemini-2.0-flash")


// Provide a prompt that contains text
let prompt = "Write a story about a magic backpack."

// To stream generated text output, call generateContentStream with the text input
let contentStream = try model.generateContentStream(prompt)
for try await chunk in contentStream {
  if let text = chunk.text {
    print(text)
  }
}

सिर्फ़ टेक्स्ट वाले इनपुट से जनरेट किए गए टेक्स्ट को स्ट्रीम करने के लिए, generateContentStream() को कॉल किया जा सकता है.

Kotlin के लिए, इस SDK टूल में मौजूद मैथड, सस्पेंड फ़ंक्शन हैं. इन्हें कोरूटीन स्कोप से कॉल किया जाना चाहिए.

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
                        .generativeModel("gemini-2.0-flash")


// Provide a prompt that includes only text
val prompt = "Write a story about a magic backpack."

// To stream generated text output, call generateContentStream and pass in the prompt
var response = ""
generativeModel.generateContentStream(prompt).collect { chunk ->
    print(chunk.text)
    response += chunk.text
}

सिर्फ़ टेक्स्ट वाले इनपुट से जनरेट किए गए टेक्स्ट को स्ट्रीम करने के लिए, generateContentStream() को कॉल किया जा सकता है.

Java के लिए, इस SDK टूल में स्ट्रीमिंग के तरीके, Reactive Streams लाइब्रेरी से Publisher टाइप दिखाते हैं.

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
        .generativeModel("gemini-2.0-flash");

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);


// Provide a prompt that contains text
Content prompt = new Content.Builder()
        .addText("Write a story about a magic backpack.")
        .build();

// To stream generated text output, call generateContentStream with the text input
Publisher<GenerateContentResponse> streamingResponse =
    model.generateContentStream(prompt);

// Subscribe to partial results from the response
final String[] fullResponse = {""};
streamingResponse.subscribe(new Subscriber<GenerateContentResponse>() {
  @Override
  public void onNext(GenerateContentResponse generateContentResponse) {
    String chunk = generateContentResponse.getText();
    fullResponse[0] += chunk;
  }

  @Override
  public void onComplete() {
    System.out.println(fullResponse[0]);
  }

  @Override
  public void onError(Throwable t) {
    t.printStackTrace();
  }

  @Override
  public void onSubscribe(Subscription s) { }
});

सिर्फ़ टेक्स्ट वाले इनपुट से जनरेट किए गए टेक्स्ट को स्ट्रीम करने के लिए, generateContentStream() को कॉल किया जा सकता है.


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";

// TODO(developer) Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(ai, { model: "gemini-2.0-flash" });


// Wrap in an async function so you can use await
async function run() {
  // Provide a prompt that contains text
  const prompt = "Write a story about a magic backpack."

  // To stream generated text output, call generateContentStream with the text input
  const result = await model.generateContentStream(prompt);

  for await (const chunk of result.stream) {
    const chunkText = chunk.text();
    console.log(chunkText);
  }

  console.log('aggregated response: ', await result.response);
}

run();

सिर्फ़ टेक्स्ट वाले इनपुट से जनरेट किए गए टेक्स्ट को स्ट्रीम करने के लिए, generateContentStream() को कॉल किया जा सकता है.


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

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

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
final model =
      FirebaseAI.googleAI().generativeModel(model: 'gemini-2.0-flash');


// Provide a prompt that contains text
final prompt = [Content.text('Write a story about a magic backpack.')];

// To stream generated text output, call generateContentStream with the text input
final response = model.generateContentStream(prompt);
await for (final chunk in response) {
  print(chunk.text);
}

सिर्फ़ टेक्स्ट वाले इनपुट से जनरेट किए गए टेक्स्ट को स्ट्रीम करने के लिए, GenerateContentStreamAsync() को कॉल किया जा सकता है.


using Firebase;
using Firebase.AI;

// Initialize the Gemini Developer API backend service
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` instance with a model that supports your use case
var model = ai.GetGenerativeModel(modelName: "gemini-2.0-flash");


// Provide a prompt that contains text
var prompt = "Write a story about a magic backpack.";

// To stream generated text output, call GenerateContentStreamAsync with the text input
var responseStream = model.GenerateContentStreamAsync(prompt);
await foreach (var response in responseStream) {
  if (!string.IsNullOrWhiteSpace(response.Text)) {
    UnityEngine.Debug.Log(response.Text);
  }
}

Swift KotlinJavaWebDart Unity

टेक्स्ट और एक वीडियो के मल्टीमोडल इनपुट से जनरेट किए गए टेक्स्ट को स्ट्रीम करने के लिए, generateContentStream() को कॉल किया जा सकता है.


import FirebaseAI

// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.generativeModel(modelName: "gemini-2.0-flash")


// Provide the video as `Data` with the appropriate MIME type
let video = InlineDataPart(data: try Data(contentsOf: videoURL), mimeType: "video/mp4")

// Provide a text prompt to include with the video
let prompt = "What is in the video?"

// To stream generated text output, call generateContentStream with the text and video
let contentStream = try model.generateContentStream(video, prompt)
for try await chunk in contentStream {
  if let text = chunk.text {
    print(text)
  }
}

टेक्स्ट और एक वीडियो के मल्टीमोडल इनपुट से जनरेट किए गए टेक्स्ट को स्ट्रीम करने के लिए, generateContentStream() को कॉल किया जा सकता है.

Kotlin के लिए, इस SDK टूल में मौजूद मैथड, सस्पेंड फ़ंक्शन हैं. इन्हें कोरूटीन स्कोप से कॉल किया जाना चाहिए.

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
                        .generativeModel("gemini-2.0-flash")


val contentResolver = applicationContext.contentResolver
contentResolver.openInputStream(videoUri).use { stream ->
  stream?.let {
    val bytes = stream.readBytes()

    // Provide a prompt that includes the video specified above and text
    val prompt = content {
        inlineData(bytes, "video/mp4")
        text("What is in the video?")
    }

    // To stream generated text output, call generateContentStream with the prompt
    var fullResponse = ""
    generativeModel.generateContentStream(prompt).collect { chunk ->
        Log.d(TAG, chunk.text ?: "")
        fullResponse += chunk.text
    }
  }
}

टेक्स्ट और एक वीडियो के मल्टीमोडल इनपुट से जनरेट किए गए टेक्स्ट को स्ट्रीम करने के लिए, generateContentStream() को कॉल किया जा सकता है.

Java के लिए, इस SDK टूल में स्ट्रीमिंग के तरीके, Reactive Streams लाइब्रेरी से Publisher टाइप दिखाते हैं.

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
        .generativeModel("gemini-2.0-flash");

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);


ContentResolver resolver = getApplicationContext().getContentResolver();
try (InputStream stream = resolver.openInputStream(videoUri)) {
    File videoFile = new File(new URI(videoUri.toString()));
    int videoSize = (int) videoFile.length();
    byte[] videoBytes = new byte[videoSize];
    if (stream != null) {
        stream.read(videoBytes, 0, videoBytes.length);
        stream.close();

        // Provide a prompt that includes the video specified above and text
        Content prompt = new Content.Builder()
                .addInlineData(videoBytes, "video/mp4")
                .addText("What is in the video?")
                .build();

        // To stream generated text output, call generateContentStream with the prompt
        Publisher<GenerateContentResponse> streamingResponse =
                model.generateContentStream(prompt);

        final String[] fullResponse = {""};

        streamingResponse.subscribe(new Subscriber<GenerateContentResponse>() {
            @Override
            public void onNext(GenerateContentResponse generateContentResponse) {
                String chunk = generateContentResponse.getText();
                fullResponse[0] += chunk;
            }

            @Override
            public void onComplete() {
                System.out.println(fullResponse[0]);
            }

            @Override
            public void onError(Throwable t) {
                t.printStackTrace();
            }

            @Override
            public void onSubscribe(Subscription s) {
            }
         });
    }
} catch (IOException e) {
    e.printStackTrace();
} catch (URISyntaxException e) {
    e.printStackTrace();
}

टेक्स्ट और एक वीडियो के मल्टीमोडल इनपुट से जनरेट किए गए टेक्स्ट को स्ट्रीम करने के लिए, generateContentStream() को कॉल किया जा सकता है.


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";

// TODO(developer) Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(ai, { model: "gemini-2.0-flash" });


// Converts a File object to a Part object.
async function fileToGenerativePart(file) {
  const base64EncodedDataPromise = new Promise((resolve) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result.split(',')[1]);
    reader.readAsDataURL(file);
  });
  return {
    inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
  };
}

async function run() {
  // Provide a text prompt to include with the video
  const prompt = "What do you see?";

  const fileInputEl = document.querySelector("input[type=file]");
  const videoPart = await fileToGenerativePart(fileInputEl.files[0]);

  // To stream generated text output, call generateContentStream with the text and video
  const result = await model.generateContentStream([prompt, videoPart]);

  for await (const chunk of result.stream) {
    const chunkText = chunk.text();
    console.log(chunkText);
  }
}

run();

टेक्स्ट और एक वीडियो के मल्टीमोडल इनपुट से जनरेट किए गए टेक्स्ट को स्ट्रीम करने के लिए, generateContentStream() को कॉल किया जा सकता है.


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

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

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
final model =
      FirebaseAI.googleAI().generativeModel(model: 'gemini-2.0-flash');


// Provide a text prompt to include with the video
final prompt = TextPart("What's in the video?");

// Prepare video for input
final video = await File('video0.mp4').readAsBytes();

// Provide the video as `Data` with the appropriate mimetype
final videoPart = InlineDataPart('video/mp4', video);

// To stream generated text output, call generateContentStream with the text and image
final response = await model.generateContentStream([
  Content.multi([prompt,videoPart])
]);
await for (final chunk in response) {
  print(chunk.text);
}

टेक्स्ट और एक वीडियो के मल्टीमोडल इनपुट से जनरेट किए गए टेक्स्ट को स्ट्रीम करने के लिए, GenerateContentStreamAsync() को कॉल किया जा सकता है.


using Firebase;
using Firebase.AI;

// Initialize the Gemini Developer API backend service
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` instance with a model that supports your use case
var model = ai.GetGenerativeModel(modelName: "gemini-2.0-flash");


// Provide the video as `data` with the appropriate MIME type.
var video = ModelContent.InlineData("video/mp4",
      System.IO.File.ReadAllBytes(System.IO.Path.Combine(
          UnityEngine.Application.streamingAssetsPath, "yourVideo.mp4")));

// Provide a text prompt to include with the video
var prompt = ModelContent.Text("What is in the video?");

// To stream generated text output, call GenerateContentStreamAsync with the text and video
var responseStream = model.GenerateContentStreamAsync(new [] { video, prompt });
await foreach (var response in responseStream) {
  if (!string.IsNullOrWhiteSpace(response.Text)) {
    UnityEngine.Debug.Log(response.Text);
  }
}



इनपुट इमेज फ़ाइलों के लिए ज़रूरी शर्तें और सुझाव

ध्यान दें कि इनलाइन डेटा के तौर पर दी गई फ़ाइल को ट्रांज़िट में Base64 में एन्कोड किया जाता है. इससे अनुरोध का साइज़ बढ़ जाता है. अगर अनुरोध बहुत बड़ा है, तो आपको एचटीटीपी 413 गड़बड़ी का मैसेज मिलता है.

इनके बारे में ज़्यादा जानकारी पाने के लिए, Vertex AI Gemini API के लिए काम करने वाली इनपुट फ़ाइलें और ज़रूरी शर्तें देखें:

  • अनुरोध में फ़ाइल देने के अलग-अलग विकल्प (इनलाइन या फ़ाइल के यूआरएल या यूआरआई का इस्तेमाल करके)
  • समर्थित फ़ाइल प्रकार
  • इस्तेमाल किए जा सकने वाले MIME टाइप और उन्हें बताने का तरीका
  • फ़ाइलों और अलग-अलग तरीकों से किए जाने वाले अनुरोधों के लिए ज़रूरी शर्तें और सबसे सही तरीके



तुम और क्या कर सकती हो?

  • मॉडल को लंबे प्रॉम्प्ट भेजने से पहले, टोकन की गिनती करने का तरीका जानें.
  • Cloud Storage for Firebase को सेट अप करें, ताकि आप अपने कई मोड वाले अनुरोधों में बड़ी फ़ाइलें शामिल कर सकें. साथ ही, प्रॉम्प्ट में फ़ाइलें उपलब्ध कराने के लिए, बेहतर तरीके से मैनेज किया जा सके. फ़ाइलों में इमेज, PDF, वीडियो, और ऑडियो शामिल हो सकते हैं.
  • प्रोडक्शन की तैयारी शुरू करें (प्रोडक्शन की चेकलिस्ट देखें). इसमें ये चीज़ें शामिल हैं:
    • Gemini API को बिना अनुमति वाले क्लाइंट के गलत इस्तेमाल से बचाने के लिए, Firebase App Check सेट अप करना
    • Firebase Remote Config को इंटिग्रेट करना, ताकि ऐप्लिकेशन का नया वर्शन रिलीज़ किए बिना, ऐप्लिकेशन में वैल्यू (जैसे, मॉडल का नाम) अपडेट की जा सकें.

अन्य सुविधाएं आज़माएं

कॉन्टेंट जनरेशन को कंट्रोल करने का तरीका जानें

प्रॉम्प्ट और मॉडल कॉन्फ़िगरेशन के साथ भी एक्सपेरिमेंट किया जा सकता है. साथ ही, Google AI Studio का इस्तेमाल करके, जनरेट किया गया कोड स्निपेट भी पाया जा सकता है.

इस्तेमाल किए जा सकने वाले मॉडल के बारे में ज़्यादा जानें

अलग-अलग कामों के लिए उपलब्ध मॉडल, उनके कोटे, और कीमत के बारे में जानें.


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