בעזרת Gemini API אפשר ליצור שיחות בפורמט חופשי במספר סבבים. ה-SDK של Vertex AI in Firebase מפשט את התהליך על ידי ניהול המצב של השיחה, כך שלא כמו ב-generateContent()
(או ב-generateContentStream()
), אתם לא צריכים לאחסן את היסטוריית השיחות בעצמכם.
לפני שמתחילים
אם עדיין לא עשיתם זאת, כדאי לעיין במדריך למתחילים, שבו מוסבר איך מגדירים את פרויקט Firebase, מחברים את האפליקציה ל-Firebase, מוסיפים את ה-SDK, מאתחלים את השירות Vertex AI ויוצרים מכונה של GenerativeModel
.
שליחת בקשה להנחיה בצ'אט
כדי ליצור שיחה עם כמה תורנים (כמו צ'אט), מתחילים בהפעלת השיחה באמצעות קריאה ל-startChat()
. לאחר מכן, משתמשים ב-sendMessage()
כדי לשלוח הודעה חדשה מהמשתמש, וההודעה והתגובה יתווספו להיסטוריית הצ'אט.
יש שתי אפשרויות אפשריות ל-role
שמשויך לתוכן בשיחה:
user
: התפקיד שמספק את ההנחיות. זהו ערך ברירת המחדל לקריאות ל-sendMessage()
, והפונקציה תיצור חריגה אם יועבר תפקיד אחר.model
: התפקיד שמספק את התשובות. אפשר להשתמש בתפקיד הזה כשקוראים ל-startChat()
עםhistory
קיים.
Swift
אפשר להתקשר למספרים startChat()
ו-sendMessage()
כדי לשלוח הודעה למשתמש חדש:
import FirebaseVertexAI
// Initialize the Vertex AI service
let vertex = VertexAI.vertexAI()
// Create a `GenerativeModel` instance with a model that supports your use case
let model = vertex.generativeModel(modelName: "gemini-2.0-flash")
// Optionally specify existing chat history
let history = [
ModelContent(role: "user", parts: "Hello, I have 2 dogs in my house."),
ModelContent(role: "model", parts: "Great to meet you. What would you like to know?"),
]
// Initialize the chat with optional chat history
let chat = model.startChat(history: history)
// To generate text output, call sendMessage and pass in the message
let response = try await chat.sendMessage("How many paws are in my house?")
print(response.text ?? "No text in response.")
Kotlin
אפשר להתקשר למספר startChat()
ולמספר sendMessage()
כדי לשלוח הודעה למשתמש חדש:
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
val generativeModel = Firebase.vertexAI.generativeModel("gemini-2.0-flash")
// Initialize the chat
val chat = generativeModel.startChat(
history = listOf(
content(role = "user") { text("Hello, I have 2 dogs in my house.") },
content(role = "model") { text("Great to meet you. What would you like to know?") }
)
)
val response = chat.sendMessage("How many paws are in my house?")
print(response.text)
Java
אפשר להתקשר למספרים startChat()
ו-sendMessage()
כדי לשלוח הודעה למשתמש חדש:
ListenableFuture
.
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
GenerativeModel gm = FirebaseVertexAI.getInstance()
.generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(gm);
// (optional) Create previous chat history for context
Content.Builder userContentBuilder = new Content.Builder();
userContentBuilder.setRole("user");
userContentBuilder.addText("Hello, I have 2 dogs in my house.");
Content userContent = userContentBuilder.build();
Content.Builder modelContentBuilder = new Content.Builder();
modelContentBuilder.setRole("model");
modelContentBuilder.addText("Great to meet you. What would you like to know?");
Content modelContent = userContentBuilder.build();
List<Content> history = Arrays.asList(userContent, modelContent);
// Initialize the chat
ChatFutures chat = model.startChat(history);
// Create a new user message
Content.Builder messageBuilder = new Content.Builder();
messageBuilder.setRole("user");
messageBuilder.addText("How many paws are in my house?");
Content message = messageBuilder.build();
// Send the message
ListenableFuture<GenerateContentResponse> response = chat.sendMessage(message);
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
אפשר להתקשר למספרים startChat()
ו-sendMessage()
כדי לשלוח הודעה למשתמש חדש:
import { initializeApp } from "firebase/app";
import { getVertexAI, getGenerativeModel } from "firebase/vertexai";
// 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 Vertex AI service
const vertexAI = getVertexAI(firebaseApp);
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(vertexAI, { model: "gemini-2.0-flash" });
async function run() {
const chat = model.startChat({
history: [
{
role: "user",
parts: [{ text: "Hello, I have 2 dogs in my house." }],
},
{
role: "model",
parts: [{ text: "Great to meet you. What would you like to know?" }],
},
],
generationConfig: {
maxOutputTokens: 100,
},
});
const msg = "How many paws are in my house?";
const result = await chat.sendMessage(msg);
const response = await result.response;
const text = response.text();
console.log(text);
}
run();
Dart
אפשר להתקשר למספרים startChat()
ו-sendMessage()
כדי לשלוח הודעה למשתמש חדש:
import 'package:firebase_vertexai/firebase_vertexai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
final model =
FirebaseVertexAI.instance.generativeModel(model: 'gemini-2.0-flash');
final chat = model.startChat();
// Provide a prompt that contains text
final prompt = [Content.text('Write a story about a magic backpack.')];
final response = await chat.sendMessage(prompt);
print(response.text);
כאן מוסבר איך בוחרים מודל, ואם רוצים גם מיקום, שמתאימים לתרחיש לדוגמה ולאפליקציה.
שידור התשובה
חשוב לוודא שביצעתם את ההוראות בקטע לפני שמתחילים במדריך הזה לפני שאתם מנסים את הדוגמה הזו.
כדי לקבל אינטראקציות מהירות יותר, אפשר לא להמתין לתוצאה המלאה של יצירת המודל, אלא להשתמש בסטרימינג כדי לטפל בתוצאות חלקיות.
כדי להעביר את התשובה בסטרימינג, קוראים לפונקציה sendMessageStream()
.
מה עוד אפשר לעשות?
- כך סופרים אסימונים לפני ששולחים הנחיות ארוכות למודל.
- מגדירים את Cloud Storage for Firebase כדי שתוכלו לכלול קבצים גדולים בבקשות עם מודלים מרובים של קלט, ולקבל פתרון מנוהל יותר לשליחת קבצים בהנחיות. הקבצים יכולים לכלול תמונות, קובצי PDF, סרטונים וקטעי אודיו.
- כדאי להתחיל לחשוב על ההכנות לקראת ההשקה בסביבת הייצור, כולל הגדרת Firebase App Check כדי להגן על ה-Gemini API מפני ניצול לרעה על ידי לקוחות לא מורשים. בנוסף, חשוב לעיין ברשימת המשימות להעברה לייצור.
לנסות יכולות אחרות
- ליצור טקסט מהנחיות בטקסט בלבד.
- יצירת טקסט באמצעות הצגת הנחיות לגבי סוגי קבצים שונים, כמו תמונות, קבצי PDF, סרטונים ואודיו.
- יצירת פלט מובנה (כמו JSON) גם מהנחיות טקסט וגם מהנחיות מולטימודליות.
- יצירת תמונות מהנחיות טקסט.
- משתמשים בקריאה לפונקציה כדי לחבר מודלים גנרטיביים למערכות ולמידע חיצוניים.
איך שולטים ביצירת תוכן
- הסבר על תכנון הנחיות, כולל שיטות מומלצות, אסטרטגיות והנחיות לדוגמה.
- להגדיר את הפרמטרים של המודל, כמו טמפרטורה ואסימונים מקסימליים של פלט (עבור Gemini) או יחס גובה-רוחב ויצירת אנשים (עבור Imagen).
- שימוש בהגדרות הבטיחות כדי לשנות את הסבירות לקבלת תשובות שעשויות להיחשב כמזיקות.
מידע נוסף על המודלים הנתמכים
כאן תוכלו לקרוא מידע נוסף על המודלים הזמינים לתרחישי שימוש שונים, על המכסות ועל התמחור שלהם.שליחת משוב על חוויית השימוש ב-Vertex AI in Firebase