Gemini API를 사용하여 문서 (예: PDF) 분석

Gemini 모델에 인라인(base64 인코딩) 또는 URL을 통해 제공하는 문서 파일 (예: PDF 및 일반 텍스트 파일) 을 분석하도록 요청할 수 있습니다. Firebase AI Logic을 사용하면 앱에서 직접 이 요청을 할 수 있습니다.

이 기능을 사용하면 다음과 같은 작업을 할 수 있습니다.

  • 문서 내의 다이어그램, 차트, 표 분석
  • 구조화된 출력 형식으로 정보 추출
  • 문서의 시각적 콘텐츠 및 텍스트 콘텐츠에 관한 질문에 답변
  • 문서 요약 기능
  • 다운스트림 애플리케이션 (예: RAG 파이프라인)에서 사용할 수 있도록 레이아웃과 서식을 유지하면서 문서 콘텐츠를 트랜스크립션 (예: HTML로)합니다.

이 가이드는 PDF와 같은 문서 입력에서 텍스트 를 생성하는 방법을 설명 하지만 문서 입력에서 이미지 를 생성할 수도 있습니다.

코드 샘플로 이동 스트리밍된 응답 코드로 이동


문서 (예: PDF) 작업에 관한 추가 옵션은 다른 가이드를 참고하세요.
구조화된 출력 생성 멀티턴 채팅

시작하기 전에

Gemini API 제공업체를 클릭하여 이 페이지에서 제공업체별 콘텐츠 및 코드를 확인합니다.

아직 시작 가이드를 완료하지 않았다면 완료하세요. 이 가이드에서는 Firebase 프로젝트를 설정하고, 앱을 Firebase에 연결하고, SDK를 추가하고, 선택한 Gemini API 제공업체의 백엔드 서비스를 초기화하고, GenerativeModel 인스턴스를 만드는 방법을 설명합니다.

프롬프트를 테스트하고 반복하려면 사용하는 것이 좋습니다.Google AI Studio

이 기능을 지원하는 모델

이 가이드는 PDF와 같은 문서 입력에서 텍스트를 생성하는 방법을 설명하며 다음 Gemini 모델에 적용됩니다.

  • gemini-3.1-pro-preview
  • gemini-3.7-flash (이전의 gemini-3.6-flashgemini-3.5-flash)
  • gemini-3.5-flash-lite (이전의 gemini-3.1-flash-lite)

일반 용도 Gemini 2.5 모델은 이 기능을 지원하지만 모두 지원 중단되었습니다.

PDF 파일 (base64 인코딩)에서 텍스트 생성

이 샘플을 사용해 보기 전에 이 가이드의 시작하기 전에 섹션을 완료하여 프로젝트와 앱을 설정하세요.
이 섹션에서 선택한 Gemini API 제공업체의 버튼을 클릭하면 이 페이지에 제공업체별 콘텐츠가 표시됩니다.

각 입력 파일의 mimeType과 파일 자체를 제공하여 텍스트와 PDF로 프롬프트를 표시하여 Gemini 모델에 텍스트 생성을 요청할 수 있습니다. 이 페이지의 뒷부분에서 입력 파일의 요구사항 및 권장사항 을 확인하세요.

Swift

`generateContent()`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.7-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()`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.7-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()`generateContent()를 호출하여 텍스트 및 PDF의 멀티모달 입력에서 텍스트를 생성할 수 있습니다.

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.7-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()`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-3.7-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()`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.7-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);

Unity

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.7-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.");

사용 사례 및 앱에 적합한 모델 를 선택하는 방법을 알아보세요.

응답 스트리밍

이 샘플을 사용해 보기 전에 이 가이드의 시작하기 전에 섹션을 완료하여 프로젝트와 앱을 설정하세요.
이 섹션에서 선택한 Gemini API 제공업체의 버튼을 클릭하면 이 페이지에 제공업체별 콘텐츠가 표시됩니다.

모델 생성의 전체 결과를 기다리지 않고 스트리밍을 사용하여 부분 결과를 처리하면 상호작용 속도를 높일 수 있습니다. 응답을 스트리밍하려면 generateContentStream을 호출합니다.



입력 문서의 요구사항 및 권장사항

인라인 데이터로 제공되는 파일은 전송 중에 base64로 인코딩되어 요청 크기가 증가합니다. 요청이 너무 크면 HTTP 413 오류가 발생합니다.

'지원되는 입력 파일 및 요구사항' 페이지에서 다음 사항에 관한 자세한 정보를 알아보세요.

지원되는 문서 MIME 유형

Gemini 멀티모달 모델은 다음과 같은 문서 MIME 유형을 지원합니다.

  • PDF - application/pdf
  • 텍스트 - text/plain

요청당 한도

PDF는 이미지로 취급되므로 PDF의 한 페이지는 하나의 이미지로 취급됩니다. 프롬프트에서 허용되는 페이지 수는 이미지 수로 제한됩니다. Gemini 멀티모달 모델이 지원할 수 있습니다.

  • 요청당 최대 파일 수: 3,000개
  • 파일당 최대 페이지 수: 파일당 1,000페이지
  • 파일당 최대 크기: 파일당 50MB



또 뭘 할 수 있니?

다른 기능 사용해 보기

콘텐츠 생성 제어 방법 알아보기

  • 프롬프트 설계를 비롯한 권장사항, 전략, 예시 프롬프트를 이해합니다.
  • 모델 매개변수 구성 (예: 최대 출력 토큰, 반복된 출력 토큰의 확률 등)
  • 안전 설정을 사용하여 유해하다고 간주될 수 있는 응답을 받을 가능성을 조정합니다.
Google AI 스튜디오를 사용하여 프롬프트 및 모델 구성을 실험하고 생성된 코드 스니펫을 가져올 수도 있습니다. Google AI Studio.

지원되는 모델 자세히 알아보기

다양한 사용 사례에 사용할 수 있는 모델할당량가격을 알아봅니다.


의견 보내기 Firebase AI Logic 사용 경험에 관한