אתם יכולים לבקש ממודל Gemini ליצור טקסט מהנחיה שמכילה טקסט בלבד או מהנחיה מרובת-אופנים. כשמשתמשים ב-Firebase AI Logic, אפשר לשלוח את הבקשה הזו ישירות מהאפליקציה.
הנחיות מולטי-מודאליות יכולות לכלול כמה סוגים של קלט (כמו טקסט לצד תמונות, קובצי PDF, קובצי טקסט פשוט, אודיו ווידאו).
במדריך הזה מוסבר איך ליצור טקסט מהנחיה עם טקסט בלבד ומהנחיה בסיסית מולטימודאלית שכוללת קובץ.
מעבר לדוגמאות קוד להזנה של טקסט בלבד מעבר לדוגמאות קוד להזנה מולטימודאלית
מדריכים נוספים עם אפשרויות נוספות לעבודה עם טקסט יצירת פלט מובנה שיחה מרובת תפניות הזרמה דו-כיוונית יצירת טקסט במכשיר יצירת תמונות מטקסט |
לפני שמתחילים
לוחצים על הספק Gemini API כדי לראות בדף הזה תוכן וקוד שספציפיים לספק. |
אם עדיין לא עשיתם את זה, כדאי לעיין במדריך לתחילת העבודה. במדריך הזה מוסבר איך להגדיר את פרויקט Firebase, לקשר את האפליקציה ל-Firebase, להוסיף את ה-SDK, לאתחל את שירות ה-Backend עבור ספק Gemini API שבחרתם וליצור מופע GenerativeModel
.
כדי לבדוק את ההנחיות ולשפר אותן, ואפילו כדי לקבל קטע קוד שנוצר, מומלץ להשתמש ב-Google AI Studio.
יצירת טקסט מקלט טקסט בלבד
לפני שמנסים את הדוגמה הזו, צריך להשלים את השלבים שבקטע לפני שמתחילים במדריך הזה כדי להגדיר את הפרויקט והאפליקציה. בקטע הזה צריך גם ללחוץ על לחצן של ספק Gemini API שבחרתם כדי שיוצג בדף הזה תוכן שספציפי לספק. |
אתם יכולים לבקש ממודל Gemini ליצור טקסט באמצעות הנחיה עם קלט של טקסט בלבד.
אתם יכולים להתקשר אל
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.5-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()
כדי ליצור טקסט מקלט טקסט בלבד.
// 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.5-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()
כדי ליצור טקסט מקלט טקסט בלבד.
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.5-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.5-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.5-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.5-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.צריך קובץ וידאו לדוגמה?
אפשר להשתמש בקובץ הזה שזמין לציבור עם סוג MIME של
video/mp4
(צפייה בקובץ או הורדה שלו).https://storage.googleapis.com/cloud-samples-data/video/animals.mp4
אתם יכולים להתקשר אל
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.5-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()
כדי ליצור טקסט מקלט מרובה-אופנים של טקסט וקובצי וידאו.
// 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.5-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()
כדי ליצור טקסט מקלט מרובה-אופנים של טקסט וקובצי וידאו.
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.5-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.5-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.5-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.5-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
.
דוגמה: הזרמת טקסט שנוצר מקלט טקסט בלבד
אתם יכולים להתקשר אל
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.5-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()
כדי להזרים טקסט שנוצר מקלט טקסט בלבד.
// 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.5-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()
כדי להזרים טקסט שנוצר מקלט טקסט בלבד.
Publisher
מספריית Reactive Streams.
// 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.5-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.5-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.5-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.5-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);
}
}
איך בוחרים מודל שמתאימים לתרחיש השימוש ולאפליקציה שלכם.
דוגמה: הזרמת טקסט שנוצר מקלט מרובה מצבים
אתם יכולים להתקשר אל
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.5-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()
כדי להזרים טקסט שנוצר מקלט מולטימודאלי של טקסט וסרטון אחד.
// 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.5-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()
כדי להזרים טקסט שנוצר מקלט מולטימודאלי של טקסט וסרטון אחד.
Publisher
מספריית Reactive Streams.
// 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.5-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.5-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.5-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.5-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 בזמן ההעברה, מה שמגדיל את גודל הבקשה. אם הבקשה גדולה מדי, תתקבל שגיאת HTTP 413.
במאמר קבצי קלט נתמכים ודרישות ל-Vertex AI Gemini API מפורט מידע על הנושאים הבאים:
- אפשרויות שונות למסירת קובץ בבקשה (בתוך הבקשה או באמצעות כתובת ה-URL או ה-URI של הקובץ)
- סוגי קבצים נתמכים
- סוגי MIME נתמכים ואיך מציינים אותם
- דרישות ושיטות מומלצות לגבי קבצים ובקשות מולטימודאליות
מה עוד אפשר לעשות?
- כדאי ללמוד איך לספור טוקנים לפני ששולחים הנחיות ארוכות למודל.
- הגדרת Cloud Storage for Firebase כדי לכלול קבצים גדולים בבקשות מרובות-אופנים ולקבל פתרון מנוהל יותר לאספקת קבצים בהנחיות. הקבצים יכולים לכלול תמונות, קובצי PDF, סרטונים וקובצי אודיו.
-
מתחילים לחשוב על הכנה לייצור (ראו את רשימת המשימות לביצוע לפני העברה לייצור), כולל:
- הגדרת Firebase App Check כדי להגן על Gemini API מפני ניצול לרעה על ידי לקוחות לא מורשים.
- שילוב של Firebase Remote Config כדי לעדכן ערכים באפליקציה (כמו שם המודל) בלי לפרסם גרסה חדשה של האפליקציה.
כדאי לנסות יכולות אחרות
- פיתוח שיחות עם זיכרון (צ'אט).
- ליצור טקסט מהנחיות שמכילות טקסט בלבד.
- יצירה של פלט מובנה (כמו JSON) מהנחיות טקסט ומנחיות מולטימודאליות.
- יצירת תמונות מהנחיות טקסט (Gemini או Imagen).
- שימוש בכלים (כמו קריאה לפונקציות והתבססות על נתונים באמצעות חיפוש Google) כדי לקשר מודל Gemini לחלקים אחרים באפליקציה ולמערכות ולמידע חיצוניים.
איך שולטים ביצירת תוכן
- הסבר על תכנון הנחיות, כולל שיטות מומלצות, אסטרטגיות ודוגמאות להנחיות.
- הגדרת פרמטרים של המודל כמו טמפרטורה ומקסימום טוקנים של פלט (ל-Gemini) או יחס גובה-רוחב ויצירת דמות של אדם (ל-Imagen).
- שימוש בהגדרות בטיחות כדי לשנות את הסבירות לקבלת תשובות שעלולות להיחשב מזיקות.
מידע נוסף על המודלים הנתמכים
מידע על המודלים שזמינים לתרחישי שימוש שונים ועל המיכסות והתמחור שלהםרוצה לתת משוב על חוויית השימוש ב-Firebase AI Logic?