יצירת טקסט באמצעות Gemini API

אפשר לבקש ממודל Gemini ליצור טקסט מהנחיה של טקסט בלבד או מהנחיה מולטימודאלית. כשמשתמשים ב-Firebase AI Logic, אפשר לשלוח את הבקשה הזו ישירות מהאפליקציה.

הנחיות מולטי-מודאליות יכולות לכלול כמה סוגים של קלט (כמו טקסט עם תמונות, קובצי PDF, קובצי טקסט רגילים, אודיו ווידאו).

במדריך הזה מוסבר איך ליצור טקסט מהנחיה עם טקסט בלבד ומהנחיה בסיסית עם כמה מודלים שכוללת קובץ.

מעבר לדוגמאות קוד להזנה של טקסט בלבד מעבר לדוגמאות קוד להזנה של מידע במגוון דרכים


במדריכים נוספים מפורטות אפשרויות נוספות לעבודה עם טקסט
יצירת פלט מובנה צ'אט בכמה סבבים סטרימינג דו-כיווני יצירת טקסט במכשיר יצירת תמונות מטקסט

לפני שמתחילים

לוחצים על ספק Gemini API כדי להציג בדף הזה תוכן וקוד ספציפיים לספק.

אם עדיין לא עשיתם זאת, כדאי לעיין במדריך למתחילים, שבו מוסבר איך מגדירים את פרויקט Firebase, מחברים את האפליקציה ל-Firebase, מוסיפים את ה-SDK, מאתחלים את שירות הקצה העורפי של ספק Gemini API שבחרתם ויוצרים מכונה של GenerativeModel.

כדי לבדוק את ההנחיות ולבצע בהן שינויים, ואפילו לקבל קטע קוד שנוצר, מומלץ להשתמש ב-Google AI Studio.

יצירת טקסט מקלט טקסט בלבד

לפני שמנסים את הדוגמה הזו, צריך להשלים את הקטע לפני שמתחילים במדריך הזה כדי להגדיר את הפרויקט והאפליקציה.
בקטע הזה צריך גם ללחוץ על הלחצן של ספק ה-Gemini API שבחרתם כדי להציג תוכן ספציפי לספק בדף הזה.

כדי לבקש ממודל Gemini ליצור טקסט, צריך להזין לו קלט של טקסט בלבד.

Swift

אפשר להפעיל את הפונקציה 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.")

Kotlin

אפשר להפעיל את הפונקציה generateContent() כדי ליצור טקסט מקלט טקסט בלבד.

ב-Kotlin, השיטות ב-SDK הזה הן פונקציות השהיה (suspend) וצריך לקרוא להן מהיקף של פונקציית אירוע (coroutine).

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

Java

אפשר להפעיל את הפונקציה 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);

Web

אפשר להפעיל את הפונקציה 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();

Dart

אפשר להפעיל את הפונקציה 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);

Unity

אפשר להפעיל את הפונקציה 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).

הערה: בדוגמה הזו מוצגת הוספת הקובץ בקוד, אבל ערכות ה-SDK תומכות גם בהוספת כתובת URL של YouTube.

Swift

אפשר להפעיל את הפונקציה 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.")

Kotlin

אפשר להפעיל את הפונקציה generateContent() כדי ליצור טקסט מקלט רב-מודלי של קובצי טקסט וקובצי וידאו.

ב-Kotlin, השיטות ב-SDK הזה הן פונקציות השהיה (suspend) וצריך לקרוא להן מהיקף של פונקציית אירוע (coroutine).

// 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 ?: "")
  }
}

Java

אפשר להפעיל את הפונקציה 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();
}

Web

אפשר להפעיל את הפונקציה 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();

Dart

אפשר להפעיל את הפונקציה 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);

Unity

אפשר להפעיל את הפונקציה 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.



דרישות והמלצות לגבי קובצי תמונה להזנה

חשוב לזכור שקובץ שסופק כנתונים בתוך שורה מקודד ל-base64 במהלך ההעברה, וכתוצאה מכך גדל גודל הבקשה. אם בקשה גדולה מדי, תקבלו את השגיאה HTTP 413.

במאמר קבצי קלט נתמכים ודרישות ל-Vertex AI Gemini API מפורט מידע על הנושאים הבאים:

  • אפשרויות שונות לשליחת קובץ בבקשה (בתוך הקוד או באמצעות כתובת ה-URL או ה-URI של הקובץ)
  • סוגי קבצים נתמכים
  • סוגי ה-MIME הנתמכים ואופן הציון שלהם
  • דרישות ושיטות מומלצות לגבי קבצים ובקשות במגוון מודלים



מה עוד אפשר לעשות?

לנסות יכולות אחרות

איך שולטים ביצירת תוכן

אפשר גם להתנסות בהנחיות ובהגדרות של מודלים, ואפילו ליצור קטע קוד באמצעות Google AI Studio.

מידע נוסף על המודלים הנתמכים

כאן תוכלו לקרוא מידע נוסף על המודלים הזמינים לתרחישי שימוש שונים, על המכסות ועל התמחור שלהם.


שליחת משוב על חוויית השימוש ב-Firebase AI Logic