Вы можете запросить у модели Gemini анализ файлов документов (например, PDF-файлов и текстовых файлов), предоставленных вами как встроенным способом (в кодировке Base64), так и по URL. При использовании Firebase AI Logic вы можете сделать этот запрос непосредственно из своего приложения.
Используя эту возможность, вы можете делать следующее:
- Анализируйте диаграммы, графики и таблицы внутри документов
- Извлечение информации в структурированные выходные форматы
- Отвечайте на вопросы о визуальном и текстовом содержании документов
- Резюмировать документы
- Транскрибировать содержимое документа (например, в HTML) с сохранением макетов и форматирования для использования в последующих приложениях (например, в конвейерах RAG)
Перейти к примерам кода Перейти к коду для потоковых ответов
| Дополнительные возможности работы с документами (например, PDF-файлами) см. в других руководствах. Генерация структурированного вывода Многопоточный чат | 
Прежде чем начать
| Щелкните своего поставщика API Gemini , чтобы просмотреть специфичный для этого поставщика контент и код на этой странице. | 
 Если вы еще этого не сделали, ознакомьтесь с руководством по началу работы , в котором описывается, как настроить проект Firebase, подключить приложение к Firebase, добавить SDK, инициализировать внутреннюю службу для выбранного поставщика API Gemini и создать экземпляр GenerativeModel .
Вы можете использовать этот общедоступный файл с типом MIME
application/pdf( просмотреть или загрузить файл ).https://storage.googleapis.com/cloud-samples-data/generative-ai/pdf/2403.05530.pdf
Генерация текста из PDF-файлов (в кодировке base64)
| Прежде чем приступить к работе с этим примером, выполните указания раздела «Перед началом работы » данного руководства, чтобы настроить свой проект и приложение. В этом разделе вы также нажмете кнопку для выбранного вами поставщика API Gemini , чтобы увидеть на этой странице контент, специфичный для этого поставщика . | 
 Вы можете попросить модель Gemini сгенерировать текст, используя текстовые подсказки и PDF-файлы, указав mimeType каждого входного файла и сам файл. Требования и рекомендации к входным файлам см. далее на этой странице.
Быстрый
 Вы можете вызвать generateContent() для генерации текста из многомодального ввода текста и PDF-файлов.
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")
// Provide the PDF as `Data` with the appropriate MIME type
let pdf = try InlineDataPart(data: Data(contentsOf: pdfURL), mimeType: "application/pdf")
// Provide a text prompt to include with the PDF file
let prompt = "Summarize the important results in this report."
// To generate text output, call `generateContent` with the PDF file and text prompt
let response = try await model.generateContent(pdf, prompt)
// Print the generated text, handling the case where it might be nil
print(response.text ?? "No text in response.")
Kotlin
 Вы можете вызвать generateContent() для генерации текста из многомодального ввода текста и PDF-файлов.
// 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")
val contentResolver = applicationContext.contentResolver
// Provide the URI for the PDF file you want to send to the model
val inputStream = contentResolver.openInputStream(pdfUri)
if (inputStream != null) {  // Check if the PDF file loaded successfully
    inputStream.use { stream ->
        // Provide a prompt that includes the PDF file specified above and text
        val prompt = content {
            inlineData(
                bytes = stream.readBytes(),
                mimeType = "application/pdf" // Specify the appropriate PDF file MIME type
            )
            text("Summarize the important results in this report.")
        }
        // To generate text output, call `generateContent` with the prompt
        val response = model.generateContent(prompt)
        // Log the generated text, handling the case where it might be null
        Log.d(TAG, response.text ?: "")
    }
} else {
    Log.e(TAG, "Error getting input stream for file.")
    // Handle the error appropriately
}
Java
 Вы можете вызвать generateContent() для генерации текста из многомодального ввода текста и PDF-файлов.
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.5-flash");
// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
ContentResolver resolver = getApplicationContext().getContentResolver();
// Provide the URI for the PDF file you want to send to the model
try (InputStream stream = resolver.openInputStream(pdfUri)) {
    if (stream != null) {
        byte[] audioBytes = stream.readAllBytes();
        stream.close();
        // Provide a prompt that includes the PDF file specified above and text
        Content prompt = new Content.Builder()
              .addInlineData(audioBytes, "application/pdf")  // Specify the appropriate PDF file MIME type
              .addText("Summarize the important results in this report.")
              .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 pdf file", e);
} catch (URISyntaxException e) {
    Log.e(TAG, "Invalid pdf file", e);
}
Web
 Вы можете вызвать generateContent() для генерации текста из многомодального ввода текста и PDF-файлов.
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" });
// Converts a File object to a Part object.
async function fileToGenerativePart(file) {
  const base64EncodedDataPromise = new Promise((resolve) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result.split(','));
    reader.readAsDataURL(file);
  });
  return {
    inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
  };
}
async function run() {
  // Provide a text prompt to include with the PDF file
  const prompt = "Summarize the important results in this report.";
  // Prepare PDF file for input
  const fileInputEl = document.querySelector("input[type=file]");
  const pdfPart = await fileToGenerativePart(fileInputEl.files);
  // To generate text output, call `generateContent` with the text and PDF file
  const result = await model.generateContent([prompt, pdfPart]);
  // Log the generated text, handling the case where it might be undefined
  console.log(result.response.text() ?? "No text in response.");
}
run();
Dart
 Вы можете вызвать generateContent() для генерации текста из многомодального ввода текста и PDF-файлов.
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');
// Provide a text prompt to include with the PDF file
final prompt = TextPart("Summarize the important results in this report.");
// Prepare the PDF file for input
final doc = await File('document0.pdf').readAsBytes();
// Provide the PDF file as `Data` with the appropriate PDF file MIME type
final docPart = InlineDataPart('application/pdf', doc);
// To generate text output, call `generateContent` with the text and PDF file
final response = await model.generateContent([
  Content.multi([prompt,docPart])
]);
// Print the generated text
print(response.text);
Единство
 Вы можете вызвать GenerateContentAsync() для генерации текста из многомодального ввода текста и PDF-файлов.
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");
// Provide a text prompt to include with the PDF file
var prompt = ModelContent.Text("Summarize the important results in this report.");
// Provide the PDF file as `data` with the appropriate PDF file MIME type
var doc = ModelContent.InlineData("application/pdf",
      System.IO.File.ReadAllBytes(System.IO.Path.Combine(
        UnityEngine.Application.streamingAssetsPath, "document0.pdf")));
// To generate text output, call `GenerateContentAsync` with the text and PDF file
var response = await model.GenerateContentAsync(new [] { prompt, doc });
// Print the generated text
UnityEngine.Debug.Log(response.Text ?? "No text in response.");
Узнайте, как выбрать модельподходящий для вашего варианта использования и приложения.
Транслировать ответ
| Прежде чем приступить к работе с этим примером, выполните указания раздела «Перед началом работы » данного руководства, чтобы настроить свой проект и приложение. В этом разделе вы также нажмете кнопку для выбранного вами поставщика API Gemini , чтобы увидеть на этой странице контент, специфичный для этого поставщика . | 
 Вы можете добиться более быстрого взаимодействия, не дожидаясь полного результата генерации модели, а вместо этого используя потоковую передачу для обработки частичных результатов. Для потоковой передачи ответа вызовите generateContentStream . 
Быстрый
 Вы можете вызвать generateContentStream() для потоковой передачи сгенерированного текста из многомодального ввода текста и PDF-файлов.
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")
// Provide the PDF as `Data` with the appropriate MIME type
let pdf = try InlineDataPart(data: Data(contentsOf: pdfURL), mimeType: "application/pdf")
// Provide a text prompt to include with the PDF file
let prompt = "Summarize the important results in this report."
// To stream generated text output, call `generateContentStream` with the PDF file and text prompt
let contentStream = try model.generateContentStream(pdf, prompt)
// Print the generated text, handling the case where it might be nil
for try await chunk in contentStream {
  if let text = chunk.text {
    print(text)
  }
}
Kotlin
 Вы можете вызвать generateContentStream() для потоковой передачи сгенерированного текста из многомодального ввода текста и PDF-файлов.
// 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")
val contentResolver = applicationContext.contentResolver
// Provide the URI for the PDF you want to send to the model
val inputStream = contentResolver.openInputStream(pdfUri)
if (inputStream != null) {  // Check if the PDF file loaded successfully
    inputStream.use { stream ->
        // Provide a prompt that includes the PDF file specified above and text
        val prompt = content {
            inlineData(
                bytes = stream.readBytes(),
                mimeType = "application/pdf" // Specify the appropriate PDF file MIME type
            )
            text("Summarize the important results in this report.")
        }
        // To stream generated text output, call `generateContentStream` with the prompt
        var fullResponse = ""
        model.generateContentStream(prompt).collect { chunk ->
            // Log the generated text, handling the case where it might be null
            val chunkText = chunk.text ?: ""
            Log.d(TAG, chunkText)
            fullResponse += chunkText
        }
    }
} else {
    Log.e(TAG, "Error getting input stream for file.")
    // Handle the error appropriately
}
Java
 Вы можете вызвать generateContentStream() для потоковой передачи сгенерированного текста из многомодального ввода текста и PDF-файлов.
Publisher из библиотеки Reactive Streams . 
// 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);
ContentResolver resolver = getApplicationContext().getContentResolver();
// Provide the URI for the PDF file you want to send to the model
try (InputStream stream = resolver.openInputStream(pdfUri)) {
    if (stream != null) {
        byte[] audioBytes = stream.readAllBytes();
        stream.close();
        // Provide a prompt that includes the PDF file specified above and text
        Content prompt = new Content.Builder()
              .addInlineData(audioBytes, "application/pdf")  // Specify the appropriate PDF file MIME type
              .addText("Summarize the important results in this report.")
              .build();
        // To stream generated text output, call `generateContentStream` with the prompt
        Publisher<GenerateContentResponse> streamingResponse =
                model.generateContentStream(prompt);
        StringBuilder fullResponse = new StringBuilder();
        streamingResponse.subscribe(new Subscriber<GenerateContentResponse>() {
            @Override
            public void onNext(GenerateContentResponse generateContentResponse) {
                String chunk = generateContentResponse.getText();
                String text = (chunk == null) ? "" : chunk;
                Log.d(TAG, text);
                fullResponse.append(text);
            }
            @Override
            public void onComplete() {
                Log.d(TAG, fullResponse.toString());
            }
            @Override
            public void onError(Throwable t) {
                Log.e(TAG, "Failed to generate a response", t);
            }
            @Override
            public void onSubscribe(Subscription s) {
            }
         });
    } else {
        Log.e(TAG, "Error getting input stream for file.");
        // Handle the error appropriately
    }
} catch (IOException e) {
    Log.e(TAG, "Failed to read the pdf file", e);
} catch (URISyntaxException e) {
    Log.e(TAG, "Invalid pdf file", e);
}
Web
 Вы можете вызвать generateContentStream() для потоковой передачи сгенерированного текста из многомодального ввода текста и PDF-файлов. 
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" });
// Converts a File object to a Part object.
async function fileToGenerativePart(file) {
  const base64EncodedDataPromise = new Promise((resolve) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result.split(','));
    reader.readAsDataURL(file);
  });
  return {
    inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
  };
}
async function run() {
  // Provide a text prompt to include with the PDF file
  const prompt = "Summarize the important results in this report.";
  // Prepare PDF file for input
  const fileInputEl = document.querySelector("input[type=file]");
  const pdfPart = await fileToGenerativePart(fileInputEl.files);
  // To stream generated text output, call `generateContentStream` with the text and PDF file
  const result = await model.generateContentStream([prompt, pdfPart]);
  // Log the generated text
  for await (const chunk of result.stream) {
    const chunkText = chunk.text();
    console.log(chunkText);
  }
}
run();
Dart
 Вы можете вызвать generateContentStream() для потоковой передачи сгенерированного текста из многомодального ввода текста и PDF-файлов. 
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');
// Provide a text prompt to include with the PDF file
final prompt = TextPart("Summarize the important results in this report.");
// Prepare the PDF file for input
final doc = await File('document0.pdf').readAsBytes();
// Provide the PDF file as `Data` with the appropriate PDF file MIME type
final docPart = InlineDataPart('application/pdf', doc);
// To generate text output, call `generateContentStream` with the text and PDF file
final response = await model.generateContentStream([
  Content.multi([prompt,docPart])
]);
// Print the generated text
await for (final chunk in response) {
  print(chunk.text);
}
Единство
 Вы можете вызвать GenerateContentStreamAsync() для потоковой передачи сгенерированного текста из многомодального ввода текста и PDF-файлов. 
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");
// Provide a text prompt to include with the PDF file
var prompt = ModelContent.Text("Summarize the important results in this report.");
// Provide the PDF file as `data` with the appropriate PDF file MIME type
var doc = ModelContent.InlineData("application/pdf",
      System.IO.File.ReadAllBytes(System.IO.Path.Combine(
        UnityEngine.Application.streamingAssetsPath, "document0.pdf")));
// To stream generated text output, call `GenerateContentStreamAsync` with the text and PDF file
var responseStream = model.GenerateContentStreamAsync(new [] { prompt, doc });
// Print the generated text
await foreach (var response in responseStream) {
  if (!string.IsNullOrWhiteSpace(response.Text)) {
    UnityEngine.Debug.Log(response.Text);
  }
}
Узнайте, как выбрать модельподходящий для вашего варианта использования и приложения.
Требования и рекомендации к входным документам
Обратите внимание, что файл, предоставляемый как встроенные данные, при передаче кодируется в base64, что увеличивает размер запроса. Если запрос слишком большой, вы получите ошибку HTTP 413.
Подробную информацию о следующем см. на странице «Поддерживаемые входные файлы и требования»:
- Различные варианты предоставления файла в запросе (как встроенным, так и с использованием URL или URI файла)
- Требования и передовые практики для файлов документов
Поддерживаемые типы MIME документов
Мультимодальные модели Gemini поддерживают следующие типы MIME документов:
-  PDF - application/pdf
-  Текст - text/plain
Лимиты на запрос
PDF-файлы обрабатываются как изображения, поэтому одна страница PDF-файла рассматривается как одно изображение. Количество страниц, разрешенных в одном запросе, ограничено количеством изображений, поддерживаемых мультимодальными моделями Gemini .
- Максимальное количество файлов на запрос: 3000 файлов
- Максимальное количество страниц в файле: 1000 страниц в файле.
- Максимальный размер файла: 50 МБ на файл.
Что еще вы можете сделать?
- Научитесь подсчитывать токены, прежде чем отправлять модели длинные подсказки.
- Настройте Cloud Storage for Firebase чтобы включать большие файлы в мультимодальные запросы и использовать более управляемое решение для предоставления файлов в запросах. Файлы могут включать изображения, PDF-файлы, видео и аудио.
-  Начните думать о подготовке к производству (см. контрольный список производства ), включая:- Настройка Firebase App Check для защиты API Gemini от злоупотреблений со стороны неавторизованных клиентов.
- Интеграция Firebase Remote Config для обновления значений в вашем приложении (например, названия модели) без выпуска новой версии приложения.
 
Попробуйте другие возможности
- Создавайте многовариантные беседы (чаты) .
- Генерация текста из текстовых подсказок .
- Генерируйте структурированный вывод (например, JSON) из текстовых и многомодальных запросов.
- Генерация изображений из текстовых подсказок ( Gemini или Imagen ).
- Используйте инструменты (например, вызов функций и привязку к Google Search ) для подключения модели Gemini к другим частям вашего приложения, внешним системам и информации.
Узнайте, как контролировать генерацию контента
- Понимать дизайн подсказок , включая передовые практики, стратегии и примеры подсказок.
- Настройте параметры модели , такие как температура и максимальные выходные токены (для Gemini ) или соотношение сторон и генерация человека (для Imagen ).
- Используйте настройки безопасности , чтобы отрегулировать вероятность получения ответов, которые могут считаться опасными.
Узнайте больше о поддерживаемых моделях
Узнайте о моделях, доступных для различных вариантов использования , их квотах и ценах .Оставьте отзыв о своем опыте работы с Firebase AI Logic