您可以使用 Gemini API 建立任意形式的多輪對話。Firebase AI Logic SDK 會管理對話狀態,簡化程序,因此不像 generateContent() (或 generateContentStream()) 那樣,您不必自行儲存對話記錄。
跳至純文字對話的程式碼 跳至疊代圖像編輯的程式碼 跳至串流回應的程式碼
事前準備
|
按一下您的Gemini API供應商,即可在這個頁面查看供應商專屬內容和程式碼。 |
如果尚未完成入門指南,請先完成。該指南說明如何設定 Firebase 專案、將應用程式連結至 Firebase、新增 SDK、為所選 Gemini API 供應商初始化後端服務,以及建立 GenerativeModel 執行個體。
如要測試及反覆調整提示,建議使用 Google AI Studio。
查看實用資源
Swift
試用快速入門應用程式
您可以使用快速入門導覽課程應用程式,快速試用 SDK,並查看各種用途的完整實作。如果沒有自己的 Apple 平台應用程式,也可以使用快速入門應用程式。如要使用快速入門應用程式,請將其連結至 Firebase 專案。
觀看教學影片
這部影片示範如何建構實際的 AI 輔助餐點規劃應用程式,讓使用者與廚師討論想準備的食譜,藉此實作與 Firebase AI Logic 的對話功能。
您也可以下載並探索影片中應用程式的程式碼集。
Kotlin
試用快速入門導覽課程應用程式
使用快速入門應用程式快速試用 SDK,並查看各種應用情境的完整實作方式。如果您沒有自己的 Android 應用程式,也可以使用快速入門導覽課程應用程式。如要使用快速入門導覽課程應用程式,您必須將其連結至 Firebase 專案。
Java
試用快速入門導覽課程應用程式
您可以使用快速入門導覽課程應用程式,快速試用 SDK,並查看各種用途的完整實作。如果您沒有自己的 Android 應用程式,也可以使用快速入門導覽課程應用程式。如要使用快速入門導覽課程應用程式,您必須將其連結至 Firebase 專案。
Web
試用快速入門應用程式
使用快速入門應用程式快速試用 SDK,並查看各種應用情境的完整實作方式。如果沒有自己的網頁應用程式,也可以使用快速入門導覽課程應用程式。如要使用快速入門導覽課程應用程式,請將其連結至 Firebase 專案。
觀看教學影片
這部影片示範如何建構實際的 AI 輔助餐點規劃應用程式,讓使用者與廚師討論想準備的食譜,藉此實作與 Firebase AI Logic 的對話功能。
您也可以下載並探索影片中應用程式的程式碼庫。
Dart
試用快速入門導覽課程應用程式
您可以使用快速入門導覽課程應用程式,快速試用 SDK,並查看各種用途的完整實作。如果您沒有自己的 Flutter 應用程式,也可以使用快速入門導覽課程應用程式。如要使用快速入門導覽課程應用程式,您必須將其連結至 Firebase 專案。
Unity
試用快速入門導覽課程應用程式
使用快速入門應用程式快速試用 SDK,並查看各種應用情境的完整實作方式。如果您沒有自己的 Unity 遊戲,也可以使用快速入門應用程式。如要使用快速入門導覽課程應用程式,您必須將其連結至 Firebase 專案。
打造純文字對話體驗
|
嘗試這個範例前,請先完成本指南的「事前準備」一節,設定專案和應用程式。 在該節中,您也會點選所選Gemini API供應商的按鈕,以便在本頁面查看供應商專屬內容。 |
如要建立多輪對話 (例如聊天),請先呼叫 startChat() 初始化對話。接著使用 sendMessage() 傳送新的使用者訊息,這也會將訊息和回覆附加到對話記錄。
與對話內容相關聯的 role 有兩種可能選項:
user:提供提示的角色。這個值是呼叫sendMessage()的預設值,如果傳遞其他角色,函式會擲回例外狀況。model:提供回覆的角色。使用現有history撥打startChat()時,可以使用這個角色。請注意,
gemini-4-argon、gemini-3.x-flash模型 (gemini-3.5-flash除外) 和gemini-3.5-flash-lite不支援預填模型輪次。如果要求中最後一個非空白的輪替是model輪替,要求就會失敗並出現 400 錯誤。
Swift
你可以撥打電話
startChat()
和
sendMessage()
傳送新的使用者訊息:
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")
// 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 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")
// Initialize the chat
val chat = model.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 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);
// (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 { 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" });
async function run() {
const chat = model.startChat({
history: [
{
role: "user",
parts: [{ type: "text", text: "Hello, I have 2 dogs in my house." }],
},
{
role: "model",
parts: [{ type: "text", 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 text = result.response.text();
console.log(text);
}
run();
Dart
您可以呼叫 startChat() 和 sendMessage() 傳送新的使用者訊息:
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');
// Initialize the chat with history
final chat = model.startChat(
history: [
Content.text('Hello, I have 2 dogs in my house.'),
Content.model([const TextPart('Great to meet you. What would you like to know?')]),
],
);
// Send a message to the chat
final response = await chat.sendMessage(Content.text('How many paws are in my house?'));
print(response.text);
Unity
您可以呼叫 StartChat() 和 SendMessageAsync() 傳送新的使用者訊息:
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");
// Optionally specify existing chat history
var history = new [] {
ModelContent.Text("Hello, I have 2 dogs in my house."),
new ModelContent("model", new ModelContent.TextPart("Great to meet you. What would you like to know?")),
};
// Initialize the chat with optional chat history
var chat = model.StartChat(history);
// To generate text output, call SendMessageAsync and pass in the message
var response = await chat.SendMessageAsync("How many paws are in my house?");
UnityEngine.Debug.Log(response.Text ?? "No text in response.");
瞭解如何根據用途和應用程式,選擇模型 。
透過多輪對話調整及編輯圖片
|
嘗試這個範例前,請先完成本指南的「事前準備」一節,設定專案和應用程式。 在該節中,您也需要點選所選Gemini API供應商的按鈕,這樣這個頁面才會顯示供應商專屬內容。 |
透過多輪對話,您可以與 Gemini 圖像模型互動,反覆修改模型生成或您提供的圖像。
建立 GenerativeModel 例項、在模型設定中加入 IMAGE 的回應模式,並呼叫 startChat() 和 sendMessage() 傳送新的使用者訊息。
Swift
import FirebaseAILogic
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
let model = FirebaseAI.firebaseAI(backend: .googleAI()).generativeModel(
modelName: "gemini-3.1-flash-image",
// Configure the model to respond with images only.
generationConfig: GenerationConfig(responseModalities: [.image])
)
// Initialize the chat
let chat = model.startChat()
guard let image = UIImage(named: "scones") else { fatalError("Image file not found.") }
// Provide an initial text prompt instructing the model to edit the image
let prompt = "Edit this image to make it look like a cartoon"
// To generate an initial response, send a user message with the image and text prompt
let response = try await chat.sendMessage(image, prompt)
// Inspect the generated image
guard let inlineDataPart = response.inlineDataParts.first else {
fatalError("No image data in response.")
}
guard let uiImage = UIImage(data: inlineDataPart.data) else {
fatalError("Failed to convert data to UIImage.")
}
// Follow up requests do not need to specify the image again
let followUpResponse = try await chat.sendMessage("But make it old-school line drawing style")
// Inspect the edited image after the follow up request
guard let followUpInlineDataPart = followUpResponse.inlineDataParts.first else {
fatalError("No image data in response.")
}
guard let followUpUIImage = UIImage(data: followUpInlineDataPart.data) else {
fatalError("Failed to convert data to UIImage.")
}
Kotlin
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
modelName = "gemini-3.1-flash-image",
// Configure the model to respond with images only.
generationConfig = generationConfig {
responseModalities = listOf(ResponseModality.IMAGE) }
)
// Provide an image for the model to edit
val bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.scones)
// Create the initial prompt instructing the model to edit the image
val prompt = content {
image(bitmap)
text("Edit this image to make it look like a cartoon")
}
// Initialize the chat
val chat = model.startChat()
// To generate an initial response, send a user message with the image and text prompt
var response = chat.sendMessage(prompt)
// Inspect the returned image
var generatedImageAsBitmap = response
.candidates.first().content.parts.filterIsInstance<ImagePart>().firstOrNull()?.image
// Follow up requests do not need to specify the image again
response = chat.sendMessage("But make it old-school line drawing style")
generatedImageAsBitmap = response
.candidates.first().content.parts.filterIsInstance<ImagePart>().firstOrNull()?.image
Java
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI()).generativeModel(
"gemini-3.1-flash-image",
// Configure the model to respond with images only.
new GenerationConfig.Builder()
.setResponseModalities(Arrays.asList(ResponseModality.IMAGE))
.build()
);
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
// Provide an image for the model to edit
Bitmap bitmap = BitmapFactory.decodeResource(resources, R.drawable.scones);
// Initialize the chat
ChatFutures chat = model.startChat();
// Create the initial prompt instructing the model to edit the image
Content prompt = new Content.Builder()
.setRole("user")
.addImage(bitmap)
.addText("Edit this image to make it look like a cartoon")
.build();
// To generate an initial response, send a user message with the image and text prompt
ListenableFuture<GenerateContentResponse> response = chat.sendMessage(prompt);
// Extract the image from the initial response
ListenableFuture<@Nullable Bitmap> initialRequest = Futures.transform(response, result -> {
for (Part part : result.getCandidates().get(0).getContent().getParts()) {
if (part instanceof ImagePart) {
ImagePart imagePart = (ImagePart) part;
return imagePart.getImage();
}
}
return null;
}, executor);
// Follow up requests do not need to specify the image again
ListenableFuture<GenerateContentResponse> modelResponseFuture = Futures.transformAsync(
initialRequest,
generatedImage -> {
Content followUpPrompt = new Content.Builder()
.addText("But make it old-school line drawing style")
.build();
return chat.sendMessage(followUpPrompt);
},
executor);
// Add a final callback to check the reworked image
Futures.addCallback(modelResponseFuture, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
for (Part part : result.getCandidates().get(0).getContent().getParts()) {
if (part instanceof ImagePart) {
ImagePart imagePart = (ImagePart) part;
Bitmap generatedImageAsBitmap = imagePart.getImage();
break;
}
}
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
Web
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } 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.1-flash-image",
// Configure the model to respond with images only.
generationConfig: {
responseModalities: [ResponseModality.IMAGE],
},
});
// Prepare an image for the model to edit
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 },
};
}
const fileInputEl = document.querySelector("input[type=file]");
const imagePart = await fileToGenerativePart(fileInputEl.files[0]);
// Provide an initial text prompt instructing the model to edit the image
const prompt = "Edit this image to make it look like a cartoon";
// Initialize the chat
const chat = model.startChat();
// To generate an initial response, send a user message with the image and text prompt
const result = await chat.sendMessage([prompt, imagePart]);
// Request and inspect the generated image
try {
const inlineDataParts = result.response.inlineDataParts();
if (inlineDataParts?.[0]) {
// Inspect the generated image
const image = inlineDataParts[0].inlineData;
console.log(image.mimeType, image.data);
}
} catch (err) {
console.error('Prompt or candidate was blocked:', err);
}
// Follow up requests do not need to specify the image again
const followUpResult = await chat.sendMessage("But make it old-school line drawing style");
// Request and inspect the returned image
try {
const followUpInlineDataParts = followUpResult.response.inlineDataParts();
if (followUpInlineDataParts?.[0]) {
// Inspect the generated image
const followUpImage = followUpInlineDataParts[0].inlineData;
console.log(followUpImage.mimeType, followUpImage.data);
}
} catch (err) {
console.error('Prompt or candidate was blocked:', err);
}
Dart
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
final model = FirebaseAI.googleAI().generativeModel(
model: 'gemini-3.1-flash-image',
// Configure the model to respond with images only.
generationConfig: GenerationConfig(responseModalities: [ResponseModalities.image]),
);
// Prepare an image for the model to edit
final image = await File('scones.jpg').readAsBytes();
final imagePart = InlineDataPart('image/jpeg', image);
// Provide an initial text prompt instructing the model to edit the image
final prompt = TextPart("Edit this image to make it look like a cartoon");
// Initialize the chat
final chat = model.startChat();
// To generate an initial response, send a user message with the image and text prompt
final response = await chat.sendMessage([
Content.multi([prompt,imagePart])
]);
// Inspect the returned image
if (response.inlineDataParts.isNotEmpty) {
final imageBytes = response.inlineDataParts[0].bytes;
// Process the image
} else {
// Handle the case where no images were generated
print('Error: No images were generated.');
}
// Follow up requests do not need to specify the image again
final followUpResponse = await chat.sendMessage([
Content.text("But make it old-school line drawing style")
]);
// Inspect the returned image
if (followUpResponse.inlineDataParts.isNotEmpty) {
final followUpImageBytes = response.inlineDataParts[0].bytes;
// Process the image
} else {
// Handle the case where no images were generated
print('Error: No images were generated.');
}
Unity
using Firebase;
using Firebase.AI;
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
var model = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetGenerativeModel(
modelName: "gemini-3.1-flash-image",
// Configure the model to respond with images only.
generationConfig: new GenerationConfig(
responseModalities: new[] { ResponseModality.Image })
);
// Prepare an image for the model to edit
var imageFile = System.IO.File.ReadAllBytes(System.IO.Path.Combine(
UnityEngine.Application.streamingAssetsPath, "scones.jpg"));
var image = ModelContent.InlineData("image/jpeg", imageFile);
// Provide an initial text prompt instructing the model to edit the image
var prompt = ModelContent.Text("Edit this image to make it look like a cartoon.");
// Initialize the chat
var chat = model.StartChat();
// To generate an initial response, send a user message with the image and text prompt
var response = await chat.SendMessageAsync(new [] { prompt, image });
// Inspect the returned image
var imageParts = response.Candidates.First().Content.Parts
.OfType<ModelContent.InlineDataPart>()
.Where(part => part.MimeType == "image/png");
// Load the image into a Unity Texture2D object
UnityEngine.Texture2D texture2D = new(2, 2);
if (texture2D.LoadImage(imageParts.First().Data.ToArray())) {
// Do something with the image
}
// Follow up requests do not need to specify the image again
var followUpResponse = await chat.SendMessageAsync("But make it old-school line drawing style");
// Inspect the returned image
var followUpImageParts = followUpResponse.Candidates.First().Content.Parts
.OfType<ModelContent.InlineDataPart>()
.Where(part => part.MimeType == "image/png");
// Load the image into a Unity Texture2D object
UnityEngine.Texture2D followUpTexture2D = new(2, 2);
if (followUpTexture2D.LoadImage(followUpImageParts.First().Data.ToArray())) {
// Do something with the image
}
逐句顯示回覆
|
嘗試這個範例前,請先完成本指南的「事前準備」一節,設定專案和應用程式。 在該節中,您也需要點選所選Gemini API供應商的按鈕,這樣這個頁面才會顯示供應商專屬內容。 |
您不必等待模型生成完整結果,而是使用串流處理部分結果,加快互動速度。如要串流回覆,請呼叫 sendMessageStream()。
你還可以做些什麼?
- 瞭解如何先計算詞元,再將長提示傳送至模型。
- 設定 Cloud Storage for Firebase,即可在多模態要求中加入大型檔案,並以更妥善管理的方式在提示中提供檔案。檔案可包含圖片、PDF、影片和音訊。
-
開始準備正式版 (請參閱正式版檢查清單):
- 盡早強制執行 Firebase App Check,協助保護 Gemini API,避免未經授權的用戶端濫用。
- 使用 Firebase Remote Config 或伺服器提示詞範本,即可隨選變更 AI 功能的設定 (例如模型名稱),不必發布新版應用程式。
試用其他功能
- 根據僅限文字的提示生成文字。
- 透過各種檔案類型 (例如圖片、PDF、影片和音訊) 提示,生成文字。
- 根據文字和多模態提示生成結構化輸出內容 (例如 JSON)。
- 生成及編輯圖片:使用文字和多模態提示詞。
-
使用工具 (例如函式呼叫
和 Grounding with
Google Search 或Google Maps ) 將 Gemini 模型連結至應用程式的其他部分,以及外部系統和資訊。
瞭解如何控管內容生成
您也可以使用 Google AI Studio 測試提示和模型設定,甚至取得生成的程式碼片段。
進一步瞭解支援的模型
瞭解各種用途適用的模型,以及這些模型的配額和價格。提供「Firebase AI Logic」使用體驗的意見回饋