Для доступа к моделям Gemini Pro и Flash мы рекомендуем разработчикам Android использовать Gemini Developer API с использованием Firebase AI Logic. Это позволяет вам начать работу без необходимости использования кредитной карты и предоставляет щедрый бесплатный уровень. После проверки интеграции с небольшой базой пользователей вы можете масштабировать ее, перейдя на платный уровень.
Начиная
Прежде чем взаимодействовать с API Gemini напрямую из своего приложения, вам необходимо выполнить несколько действий, в том числе ознакомиться с подсказками, а также настроить Firebase и свое приложение для использования SDK.
Экспериментируйте с подсказками
Эксперименты с подсказками могут помочь вам найти наилучшую формулировку, содержание и формат для вашего приложения Android. Google AI Studio — это IDE, которую вы можете использовать для прототипирования и проектирования подсказок для вариантов использования вашего приложения.
Создание правильного приглашения для вашего варианта использования — это больше искусство, чем наука, что делает эксперименты критически важными. Вы можете узнать больше о приглашении в документации Firebase .
Когда вы будете удовлетворены своим запросом, нажмите кнопку «<>», чтобы получить фрагменты кода, которые вы можете добавить в свой код.
Настройте проект Firebase и подключите свое приложение к Firebase
Когда вы будете готовы вызвать API из своего приложения, следуйте инструкциям в «Шаге 1» руководства по началу работы с Firebase AI Logic, чтобы настроить Firebase и SDK в своем приложении.
Добавьте зависимость Gradle
Добавьте следующую зависимость Gradle в модуль вашего приложения:
Котлин
dependencies {
// ... other androidx dependencies
// Import the BoM for the Firebase platform
implementation(platform("com.google.firebase:firebase-bom:33.13.0"))
// Add the dependency for the Firebase AI Logic library When using the BoM,
// you don't specify versions in Firebase library dependencies
implementation("com.google.firebase:firebase-ai")
}
Ява
dependencies {
// Import the BoM for the Firebase platform
implementation(platform("com.google.firebase:firebase-bom:33.13.0"))
// Add the dependency for the Firebase AI Logic library When using the BoM,
// you don't specify versions in Firebase library dependencies
implementation("com.google.firebase:firebase-ai")
// Required for one-shot operations (to use `ListenableFuture` from Guava
// Android)
implementation("com.google.guava:guava:31.0.1-android")
// Required for streaming operations (to use `Publisher` from Reactive
// Streams)
implementation("org.reactivestreams:reactive-streams:1.0.4")
}
Инициализируйте генеративную модель
Начните с создания экземпляра GenerativeModel
и указания имени модели:
Котлин
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
.generativeModel("gemini-2.0-flash")
Ява
GenerativeModel firebaseAI = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(firebaseAI);
Узнайте больше о доступных моделях для использования с Gemini Developer API. Вы также можете узнать больше о настройке параметров модели .
Взаимодействуйте с API разработчика Gemini из вашего приложения
Теперь, когда вы настроили Firebase и свое приложение для использования SDK, вы готовы взаимодействовать с API разработчика Gemini из своего приложения.
Сгенерировать текст
Чтобы сгенерировать текстовый ответ, вызовите generateContent()
с вашим приглашением.
Котлин
scope.launch {
val response = model.generateContent("Write a story about a magic backpack.")
}
Ява
Content prompt = new Content.Builder()
.addText("Write a story about a magic backpack.")
.build();
ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
[...]
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
Генерация текста из изображений и других медиафайлов
Вы также можете генерировать текст из приглашения, которое включает текст плюс изображения или другие медиа. Когда вы вызываете generateContent()
, вы можете передать медиа как встроенные данные.
Например, чтобы использовать растровое изображение, используйте тип содержимого image
:
Котлин
scope.launch {
val response = model.generateContent(
content {
image(bitmap)
text("what is the object in the picture?")
}
)
}
Ява
Content content = new Content.Builder()
.addImage(bitmap)
.addText("what is the object in the picture?")
.build();
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
[...]
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
Для передачи аудиофайла используйте тип содержимого inlineData
:
Котлин
val contentResolver = applicationContext.contentResolver
val inputStream = contentResolver.openInputStream(audioUri).use { stream ->
stream?.let {
val bytes = stream.readBytes()
val prompt = content {
inlineData(bytes, "audio/mpeg") // Specify the appropriate audio MIME type
text("Transcribe this audio recording.")
}
val response = model.generateContent(prompt)
}
}
Ява
ContentResolver resolver = getApplicationContext().getContentResolver();
try (InputStream stream = resolver.openInputStream(audioUri)) {
File audioFile = new File(new URI(audioUri.toString()));
int audioSize = (int) audioFile.length();
byte audioBytes = new byte[audioSize];
if (stream != null) {
stream.read(audioBytes, 0, audioBytes.length);
stream.close();
// Provide a prompt that includes audio specified earlier and text
Content prompt = new Content.Builder()
.addInlineData(audioBytes, "audio/mpeg") // Specify the appropriate audio MIME type
.addText("Transcribe what's said in this audio recording.")
.build();
// To generate text output, call `generateContent` with the prompt
ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String text = result.getText();
Log.d(TAG, (text == null) ? "" : text);
}
@Override
public void onFailure(Throwable t) {
Log.e(TAG, "Failed to generate a response", t);
}
}, executor);
} else {
Log.e(TAG, "Error getting input stream for file.");
// Handle the error appropriately
}
} catch (IOException e) {
Log.e(TAG, "Failed to read the audio file", e);
} catch (URISyntaxException e) {
Log.e(TAG, "Invalid audio file", e);
}
А чтобы предоставить видеофайл, продолжайте использовать тип контента inlineData
:
Котлин
val contentResolver = applicationContext.contentResolver
contentResolver.openInputStream(videoUri).use { stream ->
stream?.let {
val bytes = stream.readBytes()
val prompt = content {
inlineData(bytes, "video/mp4") // Specify the appropriate video MIME type
text("Describe the content of this video")
}
val response = model.generateContent(prompt)
}
}
Ява
ContentResolver resolver = getApplicationContext().getContentResolver();
try (InputStream stream = resolver.openInputStream(videoUri)) {
File videoFile = new File(new URI(videoUri.toString()));
int videoSize = (int) videoFile.length();
byte[] videoBytes = new byte[videoSize];
if (stream != null) {
stream.read(videoBytes, 0, videoBytes.length);
stream.close();
// Provide a prompt that includes video specified earlier and text
Content prompt = new Content.Builder()
.addInlineData(videoBytes, "video/mp4")
.addText("Describe the content of this video")
.build();
// To generate text output, call generateContent with the prompt
ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
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);
}
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
Аналогичным образом вы также можете передавать PDF-документы ( application/pdf
) и простые текстовые документы ( text/plain
), передавая их соответствующий тип MIME в качестве параметра.
Многооборотный чат
Вы также можете поддерживать многопоточные разговоры. Инициализируйте чат с помощью функции startChat()
. Вы можете опционально предоставить модели историю сообщений. Затем вызовите функцию sendMessage()
для отправки сообщений чата.
Котлин
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?") }
)
)
scope.launch {
val response = chat.sendMessage("How many paws are in my house?")
}
Ява
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);
Более подробную информацию смотрите в документации Firebase .
Следующие шаги
- Ознакомьтесь с примером приложения Android Quickstart Firebase и каталогом примеров Android AI на GitHub.
- Подготовьте свое приложение к производству , включая настройку Firebase App Check для защиты API Gemini от злоупотреблений со стороны неавторизованных клиентов.
- Подробнее о Firebase AI Logic читайте в документации Firebase .