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

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

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

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

דילוג לקוד של קלט טקסט בלבד דילוג לקוד של קלט מולטימודלי דילוג לקוד של תשובות בסטרימינג


מדריכים נוספים עם אפשרויות נוספות לעבודה עם טקסט
יצירת פלט מובנה שיחה עם זיכרון יצירת טקסט דינמי מבוסס-AI במכשיר המרת טקסט לדיבור (TTS) יצירת תמונות מטקסט

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

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

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

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

יצירת טקסט דינמי מבוסס-AI מקלט טקסט בלבד

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

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

Swift

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


import FirebaseAILogic

// 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-3.8-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 הזה הן פונקציות השהיה וצריך לקרוא להן מהיקף 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-3.8-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 = model.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-3.8-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-3.8-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() כדי ליצור טקסט דינמי מבוסס-AI מקלט טקסט בלבד.


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-3.8-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-3.8-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() כדי ליצור טקסט דינמי מבוסס-AI מקלט מולטי-מודאלי של קובצי טקסט ווידאו.


import FirebaseAILogic

// 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-3.8-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() כדי ליצור טקסט דינמי מבוסס-AI מקלט מולטי-מודאלי של קובצי טקסט ווידאו.

ב-Kotlin, השיטות ב-SDK הזה הן פונקציות השהיה וצריך לקרוא להן מהיקף 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-3.8-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 = model.generateContent(prompt)
    Log.d(TAG, response.text ?: "")
  }
}

Java

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

ב-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-3.8-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() כדי ליצור טקסט דינמי מבוסס-AI מקלט מולטי-מודאלי של קובצי טקסט ווידאו.


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-3.8-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 {
    type: "inlineData",
    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-3.8-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() כדי ליצור טקסט דינמי מבוסס-AI מקלט מולטי-מודאלי של קובצי טקסט ווידאו.


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-3.8-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.

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

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



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

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

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

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

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

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


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