使用 Gemini API 建構多輪對話 (即時通訊)

使用 Gemini API,您可以展開任意形式的多輪對話。Firebase AI Logic SDK 會管理對話狀態,簡化程序,因此不像 generateContent() (或 generateContentStream()) 那樣,您不必自行儲存對話記錄。

跳至純文字對話的程式碼 跳至疊代圖像編輯的程式碼 跳至串流回應的程式碼

事前準備

按一下 Gemini API 供應商,即可在這個頁面查看供應商專屬內容和程式碼。

如果尚未完成,請參閱入門指南,瞭解如何設定 Firebase 專案、將應用程式連結至 Firebase、新增 SDK、為所選Gemini API供應商初始化後端服務,以及建立 GenerativeModel 執行個體。

如要測試及反覆調整提示,建議使用 Google AI Studio。

查看實用資源

Swift

試用快速入門應用程式

使用快速入門應用程式快速試用 SDK,並查看各種應用情境的完整實作方式。如果沒有自己的 Apple 平台應用程式,也可以使用快速入門應用程式。如要使用快速入門應用程式,請將其連結至 Firebase 專案。

前往快速入門應用程式

觀看教學影片

這部影片示範如何實作 Firebase AI Logic 的對話功能,建構 AI 輔助的實用餐點規劃應用程式,讓使用者與廚師討論想準備的食譜。

您也可以下載並探索影片中應用程式的程式碼庫。

查看影片中應用程式的程式碼集



Kotlin

試用快速入門應用程式

使用快速入門應用程式快速試用 SDK,並查看各種應用情境的完整實作方式。如果沒有自己的 Android 應用程式,也可以使用快速入門應用程式。如要使用快速入門應用程式,請將其連結至 Firebase 專案。

前往快速入門應用程式

Java

試用快速入門應用程式

使用快速入門應用程式快速試用 SDK,並查看各種應用情境的完整實作方式。如果沒有自己的 Android 應用程式,也可以使用快速入門應用程式。如要使用快速入門應用程式,請將其連結至 Firebase 專案。

前往快速入門應用程式

Web

試用快速入門應用程式

使用快速入門應用程式快速試用 SDK,並查看各種應用情境的完整實作方式。如果沒有自己的網頁應用程式,也可以使用快速入門應用程式。如要使用快速入門應用程式,請將其連結至 Firebase 專案。

前往快速入門應用程式

觀看教學影片

這部影片示範如何實作 Firebase AI Logic 的對話功能,建構 AI 輔助的實用餐點規劃應用程式,讓使用者與廚師討論想準備的食譜。

您也可以下載並探索影片中應用程式的程式碼庫。

查看影片中應用程式的程式碼集



Dart

試用快速入門應用程式

使用快速入門應用程式快速試用 SDK,並查看各種應用情境的完整實作方式。如果沒有自己的 Flutter 應用程式,也可以使用快速入門應用程式。如要使用快速入門應用程式,請將其連結至 Firebase 專案。

前往快速入門應用程式

Unity

試用快速入門應用程式

使用快速入門應用程式快速試用 SDK,並查看各種應用情境的完整實作方式。如果您沒有自己的 Unity 遊戲,也可以使用快速入門應用程式。如要使用快速入門應用程式,請將其連結至 Firebase 專案。

前往快速入門應用程式

打造純文字聊天體驗

嘗試這個範例前,請先完成本指南的「事前準備」一節,設定專案和應用程式。
在該節中,您也會點選所選Gemini API供應商的按鈕,以便在本頁面查看供應商專屬內容。

如要建立多輪對話 (例如即時通訊),請先呼叫 startChat() 初始化對話。然後使用 sendMessage() 傳送新的使用者訊息,系統也會將訊息和回覆附加至對話記錄。

與對話內容相關聯的 role 可能有兩種選項:

  • user:提供提示的角色。這個值是 sendMessage() 呼叫的預設值,如果傳遞不同的角色,函式會擲回例外狀況。

  • model:提供回覆的角色。使用現有 history 撥打 startChat() 時,可以使用這個角色。

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() 傳送新的使用者訊息:

如果是 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")


// 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() 傳送新的使用者訊息:

如果是 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);


// (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: [{ 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 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 generativeModel = 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 {
    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()。



你還可以做些什麼?

試試其他功能

瞭解如何控管內容生成功能

您也可以使用 Google AI Studio 測試提示和模型設定,甚至取得生成的程式碼片段。

進一步瞭解支援的機型

瞭解各種用途適用的模型,以及這些模型的配額和價格。


提供有關 Firebase AI Logic 的使用體驗意見回饋