使用 Gemini API,您可以构建多轮自由对话。Vertex AI in Firebase SDK 通过管理对话状态来简化该流程,因此与 generateContent()
(或 generateContentStream()
)不同,您无需自行存储对话记录。
准备工作
如果您尚未完成入门指南,请先完成该指南。该指南介绍了如何设置 Firebase 项目、将应用连接到 Firebase、添加 SDK、初始化 Vertex AI 服务以及创建 GenerativeModel
实例。
发送聊天提示请求
如需构建多轮对话(例如聊天),请先通过调用 startChat()
初始化聊天。然后,使用 sendMessage()
发送新用户消息,这也会将消息和回复附加到聊天记录中。
与对话内容相关联的 role
有两种可能的选项:
user
:提供提示的角色。此值是调用sendMessage()
的默认值,如果传递其他角色,该函数会抛出异常。model
:提供响应的角色。使用现有history
调用startChat()
时,可以使用此角色。
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)。
- 根据文本提示生成图片。
- 使用函数调用将生成式模型连接到外部系统和信息。
了解如何控制内容生成
- 了解提示设计,包括最佳实践、策略和示例提示。
- 配置模型参数,例如温度和输出 token 数上限(适用于 Gemini)或宽高比和人物生成(适用于 Imagen)。
- 使用安全设置来调整收到可能被视为有害的回答的可能性。
详细了解支持的模型
了解适用于各种用例的模型及其配额和价格。就您使用 Vertex AI in Firebase 的体验提供反馈