Анализируйте документы (например, PDF-файлы) с помощью Gemini API.

You can ask a Gemini model to analyze document files (like PDFs and plain-text files) that you provide either inline (base64-encoded) or via URL. When you use Firebase AI Logic , you can make this request directly from your app.

With this capability, you can do things like:

  • Анализ диаграмм, графиков и таблиц внутри документов.
  • Извлечение информации в структурированные выходные форматы.
  • Ответьте на вопросы о визуальном и текстовом содержании документов.
  • Summarize documents
  • Преобразовать содержимое документа (например, в HTML), сохраняя макет и форматирование, для использования в последующих приложениях (например, в конвейерах RAG).

Перейти к примерам кода Перейти к коду для потоковых ответов


Дополнительные возможности работы с документами (например, PDF-файлами) можно найти в других руководствах.
Generate structured output Multi-turn chat

Прежде чем начать

Чтобы просмотреть контент и код, относящиеся к вашему поставщику API Gemini , нажмите на него.

Если вы еще этого не сделали, пройдите руководство по началу работы , в котором описывается, как настроить проект Firebase, подключить приложение к Firebase, добавить SDK, инициализировать бэкэнд-сервис для выбранного вами поставщика API Gemini и создать экземпляр GenerativeModel .

Для тестирования и доработки ваших подсказок мы рекомендуем использовать Google AI Studio .

Generate text from PDF files (base64-encoded)

Прежде чем опробовать этот пример, выполните раздел «Перед началом работы » этого руководства, чтобы настроить свой проект и приложение.
В этом разделе вам также нужно будет нажать кнопку для выбранного вами поставщика API Gemini , чтобы увидеть на этой странице контент, относящийся к данному поставщику .

You can ask a Gemini model to generate text by prompting with text and PDFs—providing each input file's mimeType and the file itself. Find requirements and recommendations for input files later on this page.

Быстрый

Вы можете вызвать 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-3.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-файлов.

В Kotlin методы в этом SDK являются функциями приостановки и должны вызываться из области видимости сопрограммы .

// 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-3.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

You can call generateContent() to generate text from multimodal input of text and PDFs.

В Java методы этого SDK возвращают объект 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-3.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

You can call generateContent() to generate text from multimodal input of text and PDFs.


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-3.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-3.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-3.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 .



Требования и рекомендации к входным документам

Обратите внимание, что файл, предоставленный в виде встроенных данных, кодируется в base64 во время передачи, что увеличивает размер запроса. В случае слишком большого размера запроса вы получите ошибку HTTP 413.

Подробную информацию о следующих параметрах можно найти на странице «Поддерживаемые входные файлы и требования»:

Поддерживаемые MIME-типы документов

Мультимодальные модели Gemini поддерживают следующие MIME-типы документов:

  • PDF - application/pdf
  • Text - text/plain

Limits per request

PDFs are treated as images, so a single page of a PDF is treated as one image. The number of pages allowed in a prompt is limited to the number of images the Gemini multimodal models can support.

  • Максимальное количество файлов на один запрос: 3000 файлов.
  • Максимальное количество страниц в файле: 1000 страниц в файле.
  • Максимальный размер файла: 50 МБ.



Что еще можно сделать?

Попробуйте другие возможности.

Узнайте, как управлять генерацией контента.

Вы также можете поэкспериментировать с подсказками и настройками модели, а также получить сгенерированный фрагмент кода с помощью Google AI Studio .

Узнайте больше о поддерживаемых моделях

Узнайте о моделях, доступных для различных вариантов использования , а также об их квотах и ​​ценах .


Оставьте отзыв о вашем опыте использования Firebase AI Logic.