使用 Gemini API 构建多轮对话(聊天)

使用 Gemini API,您可以构建多轮自由对话。Firebase AI Logic SDK 通过管理对话状态来简化该流程,因此与 generateContent()(或 generateContentStream())不同,您无需自行存储对话记录。

准备工作

点击您的 Gemini API 提供商,在本页面上查看特定于提供商的内容和代码。

如果您尚未完成入门指南,请先完成该指南。其中介绍了如何设置 Firebase 项目、将应用连接到 Firebase、添加 SDK、为所选的 Gemini API 提供程序初始化后端服务,以及创建 GenerativeModel 实例。

如需测试和迭代提示,甚至获取生成的代码段,我们建议使用 Google AI Studio

发送聊天提示请求

在试用此示例之前,请完成本指南的准备工作部分,以设置您的项目和应用。
在此部分中,您还需要点击所选 Gemini API 提供方的按钮,以便在本页上看到特定于该提供方的相关内容

如需构建多轮对话(例如聊天),请先通过调用 startChat() 初始化聊天。然后,使用 sendMessage() 发送新用户消息,这也会将消息和回复附加到聊天记录中。

与对话内容相关联的 role 有两个可能的选项:

  • user:提供提示的角色。此值是调用 sendMessage() 的默认值,如果传递其他角色,该函数会抛出异常。

  • model:提供响应的角色。使用现有 history 调用 startChat() 时,可以使用此角色。

Swift

您可以调用 startChat()sendMessage() 来发送新用户消息:


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.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 中的方法是挂起函数,需要从协程作用域调用。

// 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.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 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.0-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-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_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.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);

Unity

您可以调用 startChat()sendMessage() 来发送新用户消息:


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.0-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 提供方的按钮,以便在本页上看到特定于该提供方的相关内容

您可以通过不等待模型生成的完整结果,而是使用流式处理部分结果,从而实现更快的互动。如需流式传输响应,请调用 sendMessageStream()



您还可以执行以下操作

试用其他功能

了解如何控制内容生成

  • 了解提示设计,包括最佳实践、策略和示例提示。
  • 配置模型参数,例如温度和输出 token 数上限(适用于 Gemini)或宽高比和人物生成(适用于 Imagen)。
  • 使用安全设置来调整收到可能被视为有害的回答的可能性。
您还可以对提示和模型配置进行实验,甚至可以使用 Google AI Studio 获取生成的代码段。

详细了解支持的模型

了解适用于各种使用情形的模型及其配额价格


就您使用 Firebase AI Logic 的体验提供反馈