Используя Gemini API , вы можете создавать диалоги в произвольной форме, состоящие из нескольких ходов. Vertex AI в Firebase SDK упрощает процесс, управляя состоянием диалога, поэтому, в отличие от generateContent()
( generateContentStream()
), вам не нужно самостоятельно хранить историю разговора.
При желании поэкспериментируйте с альтернативной версией API Gemini « Google AI ».
Получите бесплатный доступ (в пределах ограничений и там, где это возможно) с помощью Google AI Studio и клиентских SDK Google AI . Эти SDK следует использовать для прототипирования только в мобильных и веб-приложениях.После того, как вы ознакомитесь с тем, как работает API Gemini , перейдите на наши Vertex AI в Firebase SDK (эта документация), которые имеют множество дополнительных функций, важных для мобильных и веб-приложений, таких как защита API от злоупотреблений с помощью Firebase App Check и поддержка больших медиафайлов в запросах .
При необходимости вызовите серверный API Vertex AI Gemini (например, с помощью Python, Node.js или Go).
Используйте серверные Vertex AI SDK , Genkit или Firebase Extensions для Gemini API .
Прежде чем начать
Если вы еще этого не сделали, прочтите руководство по началу работы , в котором описывается, как настроить проект Firebase, подключить приложение к Firebase, добавить SDK, инициализировать службу Vertex AI и создать экземпляр GenerativeModel
.
Отправить запрос на подсказку в чате
Чтобы построить многоходовой разговор (например, чат), начните с инициализации чата, вызвав startChat()
. Затем используйте sendMessage()
для отправки нового сообщения пользователя, которое также добавит сообщение и ответ в историю чата.
Существует два возможных варианта role
, связанной с содержимым беседы:
user
: роль, которая предоставляет подсказки. Это значение является значением по умолчанию для вызововsendMessage()
, и функция выдает исключение, если передается другая роль.model
: роль, которая предоставляет ответы. Эту роль можно использовать при вызовеstartChat()
с существующейhistory
.
Быстрый
Вы можете вызвать 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()
.
Быстрый
Вы можете вызвать startChat()
и sendMessageStream()
для потоковой передачи ответов модели:
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 stream generated text output, call sendMessageStream and pass in the message
let contentStream = try chat.sendMessageStream("How many paws are in my house?")
for try await chunk in contentStream {
if let text = chunk.text {
print(text)
}
}
Kotlin
Вы можете вызвать startChat()
и sendMessageStream()
для потоковой передачи ответов модели:
// 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?") }
)
)
chat.sendMessageStream("How many paws are in my house?").collect { chunk ->
print(chunk.text)
}
Java
Вы можете вызвать startChat()
и sendMessageStream()
для потоковой передачи ответов модели:
Publisher
из библиотеки Reactive Streams . // 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
Publisher<GenerateContentResponse> streamingResponse =
chat.sendMessageStream(message);
final String[] fullResponse = {""};
streamingResponse.subscribe(new Subscriber<GenerateContentResponse>() {
@Override
public void onNext(GenerateContentResponse generateContentResponse) {
String chunk = generateContentResponse.getText();
fullResponse[0] += chunk;
}
@Override
public void onComplete() {
System.out.println(fullResponse[0]);
}
// ... other methods omitted for brevity
});
Web
Вы можете вызвать startChat()
и sendMessageStream()
для потоковой передачи ответов модели:
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.sendMessageStream(msg);
let text = '';
for await (const chunk of result.stream) {
const chunkText = chunk.text();
console.log(chunkText);
text += chunkText;
}
}
run();
Dart
Вы можете вызвать startChat()
и sendMessageStream()
для потоковой передачи ответов модели:
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.sendMessageStream(prompt);
await for (final chunk in response) {
print(chunk.text);
}
Что еще вы можете сделать?
- Узнайте, как считать токены, прежде чем отправлять модели длинные запросы.
- Настройте Cloud Storage for Firebase чтобы вы могли включать большие файлы в свои мультимодальные запросы и иметь более управляемое решение для предоставления файлов в приглашениях. Файлы могут включать изображения, PDF-файлы, видео и аудио.
- Начните думать о подготовке к работе, включая настройку Firebase App Check для защиты API Gemini от злоупотреблений со стороны неавторизованных клиентов. Также обязательно ознакомьтесь с производственным контрольным списком .
Попробуйте другие возможности
- Генерация текста из текстовых подсказок .
- Создавайте текст, предлагая различные типы файлов, например изображения , PDF-файлы , видео и аудио .
- Генерируйте структурированный вывод (например, JSON) как из текстовых, так и из мультимодальных подсказок.
- Генерируйте изображения из текстовых подсказок.
- Используйте вызов функций для подключения генеративных моделей к внешним системам и информации.
Узнайте, как контролировать создание контента
- Понимание структуры подсказок , включая лучшие практики, стратегии и примеры подсказок.
- Настройте параметры модели , такие как температура и токены максимальной выходной мощности (для Gemini ) или соотношение сторон и поколение людей (для Imagen ).
- Используйте настройки безопасности , чтобы настроить вероятность получения ответов, которые могут быть расценены как вредные.
Узнайте больше о поддерживаемых моделях
Узнайте о моделях, доступных для различных вариантов использования , а также об их квотах и ценах .Оставьте отзыв о своем опыте использования Vertex AI в Firebase.