Используя API Gemini , вы можете создавать диалоги в свободной форме, состоящие из нескольких ходов. SDK Firebase AI Logic упрощает этот процесс, управляя состоянием диалога, поэтому, в отличие от generateContent() (или generateContentStream() ), вам не нужно самостоятельно хранить историю диалога.
Перейти к коду текстового чата Перейти к коду итеративного редактирования изображений Перейти к коду потоковых ответов
Прежде чем начать
Чтобы просмотреть контент и код, относящиеся к вашему поставщику API Gemini , нажмите на него. |
Если вы еще этого не сделали, пройдите руководство по началу работы , в котором описывается, как настроить проект Firebase, подключить приложение к Firebase, добавить SDK, инициализировать бэкэнд-сервис для выбранного вами поставщика API Gemini и создать экземпляр GenerativeModel .
Создайте чат, предназначенный исключительно для текста.
| Прежде чем опробовать этот пример, выполните раздел «Перед началом работы » этого руководства, чтобы настроить свой проект и приложение. В этом разделе вам также нужно будет нажать кнопку для выбранного вами поставщика API Gemini , чтобы увидеть на этой странице контент, относящийся к данному поставщику . |
Для создания многоэтапного диалога (например, чата) начните с инициализации чата путем вызова startChat() . Затем используйте sendMessage() для отправки нового сообщения пользователю, которое также будет добавлено в историю чата вместе с сообщением и ответом.
В контексте беседы возможны два варианта role , связанной с содержанием разговора:
user: роль, которая предоставляет подсказки. Это значение является значением по умолчанию для вызовов функцииsendMessage(), и функция генерирует исключение, если передана другая роль.model: роль, которая предоставляет ответы. Эта роль может использоваться при вызовеstartChat()с существующейhistory.
Быстрый
Для отправки нового сообщения пользователю можно вызвать startChat() и sendMessage() :
ni-2.5-flash")
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-2.5-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() :
ni-2.5-flash")
// 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.5-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 . elFutures.from(ai);
// 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.5-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?&q>uot;);
Content modelContent = userContentBuilder.build();
ListContent 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 mess>age = messageBuilder.build();
// Send the message
ListenableFutureGenerateContentRespo<nse response = chat.sen>dMessage(message);
Futures.addCallback(response, new FutureCallbackGenerateContentResponse() {
@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() :
{ model: "gemini-2.5-flash" });
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.5-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() :
del(model: 'gemini-2.5-flash');
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.5-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);
Единство
Для отправки нового сообщения пользователю можно вызвать StartChat() и SendMessageAsync() :
i-2.5-flash");
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.5-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.");
Узнайте, как выбрать модель.подходит для вашего сценария использования и приложения.
Редактируйте и повторяйте изображения с помощью многоходового чата.
| Прежде чем опробовать этот пример, выполните раздел «Перед началом работы » этого руководства, чтобы настроить свой проект и приложение. В этом разделе вам также нужно будет нажать кнопку для выбранного вами поставщика API Gemini , чтобы увидеть на этой странице контент, относящийся к данному поставщику . |
Используя многоходовый чат, вы можете взаимодействовать с моделью Gemini , обрабатывая изображения, которые она генерирует или которые предоставляете вы.
Обязательно создайте экземпляр GenerativeModel , включите его.responseModalities: ["TEXT", "IMAGE"] и вызовите методы startChat() и sendMessage() для отправки сообщений новым пользователям.
Быстрый
[.text, .image])
)
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-2.5-flash-image",
// Configure the model to respond with text and images (required)
generationConfig: GenerationConfig(responseModalities: [.text, .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
Modality.IMAGE) }
)
// 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-2.5-flash-image",
// Configure the model to respond with text and images (required)
generationConfig = generationConfig {
responseModalities = listOf(ResponseModality.TEXT, 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
.candidate<s.first()>.content.parts.filterIsInstanceImagePart().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
<.candidat>es.first().content.parts.filterIsInstanceImagePart().firstOrNull()?.image
Java
elFutures.from(ai);
// 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-2.5-flash-image",
// Configure the model to respond with text and images (required)
new GenerationConfig.Builder()
.setResponseModalities(Arrays.asList(ResponseModality.TEXT, 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 messa<ge with the image and t>ext prompt
ListenableFutureGenerateContentResponse response = chat.sendMessage(prompt);
// Extract th<e image from the> initial response
ListenableFuture@Nullable Bitmap ini>tialRequest = 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 no<t need to specify the i>mage again
ListenableFutureGenerateContentResponse 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(mo>delResponseFuture, new FutureCallbackGenerateContentResponse() {
@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
y.TEXT, ResponseModality.IMAGE],
},
});
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-2.5-flash-image",
// Configure the model to respond with text and images (required)
generationConfig: {
responseModalities: [ResponseModality.TEXT, 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
es.text, ResponseModalities.image]),
);
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-2.5-flash-image',
// Configure the model to respond with text and images (required)
generationConfig: GenerationConfig(responseModalities: [ResponseModalities.text, 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.');
}
Единство
odality.Image })
);
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-2.5-flash-image",
// Configure the model to respond with text and images (required)
generationConfig: new GenerationConfig(
responseModalities: new[] { ResponseModality.Text, 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
}
Трансляция ответа
| Прежде чем опробовать этот пример, выполните раздел «Перед началом работы » этого руководства, чтобы настроить свой проект и приложение. В этом разделе вам также нужно будет нажать кнопку для выбранного вами поставщика API Gemini , чтобы увидеть на этой странице контент, относящийся к данному поставщику . |
Для ускорения взаимодействия можно не ждать полного результата генерации модели, а использовать потоковую обработку для обработки частичных результатов. Для потоковой передачи ответа вызовите sendMessageStream() .
Быстрый
Для потоковой передачи ответов от модели можно вызвать startChat() и sendMessageStream() :
ni-2.5-flash")
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-2.5-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() :
ni-2.5-flash")
// 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.5-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?") }
)
)
chat.sendMessageStream("How many paws are in my house?").collect { chunk ->
print(chunk.text)
}
Java
Для потоковой передачи ответов от модели можно вызвать startChat() и sendMessageStream() :
Publisher из библиотеки Reactive Streams . elFutures.from(ai);
// 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.5-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?&q>uot;);
Content modelContent = userContentBuilder.build();
ListContent 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 m<y house?");
Conte>nt message = messageBuilder.build();
// Send the message
PublisherGenerateContentResponse streamingResponse =
chat.sendMessageStream(<message);
final String>[] fullResponse = {""};
streamingResponse.subscribe(new SubscriberGenerateContentResponse() {
@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() :
{ model: "gemini-2.5-flash" });
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.5-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() :
del(model: 'gemini-2.5-flash');
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.5-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);
}
Единство
Для потоковой передачи ответов от модели можно вызывать StartChat() и SendMessageStreamAsync() :
i-2.5-flash");
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.5-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 stream generated text output, call SendMessageStreamAsync and pass in the message
var responseStream = chat.SendMessageStreamAsync("How many paws are in my house?");
await foreach (var response in responseStream) {
if (!string.IsNullOrWhiteSpace(response.Text)) {
UnityEngine.Debug.Log(response.Text);
}
}
Узнайте, как выбрать модель.подходит для вашего сценария использования и приложения.
Что еще можно сделать?
- Научитесь подсчитывать токены, прежде чем отправлять модели длинные запросы.
- Настройте Cloud Storage for Firebase , чтобы включать большие файлы в ваши многомодальные запросы и иметь более управляемое решение для предоставления файлов в подсказках. Файлы могут включать изображения, PDF-файлы, видео и аудио.
- Начните думать о подготовке к производству (см. контрольный список для производства ), включая:
- Настройка Firebase App Check для защиты API Gemini от неправомерного использования неавторизованными клиентами.
- Интеграция Firebase Remote Config для обновления значений в вашем приложении (например, имени модели) без выпуска новой версии приложения.
Попробуйте другие возможности.
- Генерация текста на основе текстовых подсказок .
- Генерируйте текст, запрашивая различные типы файлов, такие как изображения , PDF-файлы , видео и аудио .
- Генерируйте структурированный вывод (например, в формате JSON) как из текстовых, так и из мультимодальных запросов.
- Создавайте изображения на основе текстовых подсказок ( Gemini или Imagen ).
- Используйте инструменты (например, вызов функций и привязку к Google Search ), чтобы связать модель Gemini с другими частями вашего приложения, а также с внешними системами и информацией.
Узнайте, как управлять генерацией контента.
- Разберитесь в разработке подсказок для заданий , включая лучшие практики, стратегии и примеры подсказок.
- Настройте параметры модели , такие как температура и максимальное количество выходных токенов (для Gemini ) или соотношение сторон и генерация людей (для Imagen ).
- Используйте настройки безопасности , чтобы скорректировать вероятность получения ответов, которые могут быть сочтены вредными.
Узнайте больше о поддерживаемых моделях
Узнайте о моделях, доступных для различных вариантов использования , а также об их квотах и ценах .Оставьте отзыв о вашем опыте использования Firebase AI Logic.