פיתוח שיחות (צ'אטים) עם כמה תשובות באמצעות Gemini API

בעזרת 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() כדי לשלוח הודעה למשתמש חדש:

ב-Kotlin, השיטות ב-SDK הזה הן פונקציות השהיה (suspend) וצריך לקרוא להן מהיקף של פונקציית אירוע (coroutine).
// 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() כדי לשלוח הודעה למשתמש חדש:

ב-Java, השיטות ב-SDK הזה מחזירות 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().



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

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

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

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

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

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


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