اسناد (مانند PDF) را با استفاده از Gemini API تجزیه و تحلیل کنید

شما می‌توانید از یک مدل Gemini بخواهید فایل‌های سند (مانند PDFها و فایل‌های متنی ساده) را که شما به صورت درون‌خطی (با کدگذاری base64) یا از طریق URL ارائه می‌دهید، تجزیه و تحلیل کند. وقتی از Firebase AI Logic استفاده می‌کنید، می‌توانید این درخواست را مستقیماً از برنامه خود انجام دهید.

با این قابلیت، می‌توانید کارهایی مانند موارد زیر را انجام دهید:

  • نمودارها، جداول و جداول داخل اسناد را تجزیه و تحلیل کنید
  • استخراج اطلاعات به فرمت‌های خروجی ساختاریافته
  • پاسخ به سوالات مربوط به محتوای بصری و متنی در اسناد
  • خلاصه کردن اسناد
  • رونویسی محتوای سند (برای مثال، به HTML)، با حفظ طرح‌بندی‌ها و قالب‌بندی، برای استفاده در برنامه‌های پایین‌دستی (مانند خطوط لوله RAG)

پرش به نمونه‌های کد پرش به کد برای پاسخ‌های استریم‌شده


برای گزینه‌های بیشتر برای کار با اسناد (مانند PDF) به راهنماهای دیگر مراجعه کنید.
تولید خروجی ساختاریافته چت چند نوبتی

قبل از اینکه شروع کنی

برای مشاهده محتوا و کد مخصوص ارائه‌دهنده در این صفحه، روی ارائه‌دهنده API Gemini خود کلیک کنید.

اگر هنوز این کار را نکرده‌اید، راهنمای شروع به کار را تکمیل کنید، که نحوه راه‌اندازی پروژه Firebase، اتصال برنامه به Firebase، افزودن SDK، راه‌اندازی سرویس backend برای ارائه‌دهنده API انتخابی Gemini و ایجاد یک نمونه GenerativeModel را شرح می‌دهد.

برای آزمایش و تکرار روی درخواست‌هایتان، توصیه می‌کنیم از Google AI Studio استفاده کنید.

تولید متن از فایل‌های PDF (با کدگذاری base64)

قبل از امتحان کردن این نمونه، بخش «قبل از شروع» این راهنما را برای راه‌اندازی پروژه و برنامه خود تکمیل کنید.
در آن بخش، شما همچنین می‌توانید روی دکمه‌ای برای ارائه‌دهنده‌ی API Gemini انتخابی خود کلیک کنید تا محتوای خاص ارائه‌دهنده را در این صفحه مشاهده کنید .

شما می‌توانید از یک مدل Gemini بخواهید با درخواست متن و فایل‌های PDF - با ارائه mimeType هر فایل ورودی و خود فایل - متن تولید کند. الزامات و توصیه‌هایی برای فایل‌های ورودی را بعداً در این صفحه بیابید.

سویفت

شما می‌توانید generateContent() برای تولید متن از ورودی چندوجهی متن و فایل‌های PDF فراخوانی کنید.


import FirebaseAI

// 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 فراخوانی کنید.

برای کاتلین، متدهای موجود در این SDK توابع suspend هستند و باید از یک scope کوروتین فراخوانی شوند.

// 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 فراخوانی کنید.

برای جاوا، متدهای موجود در این 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-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 فراخوانی کنید.



الزامات و توصیه‌ها برای اسناد ورودی

توجه داشته باشید که فایلی که به عنوان داده درون‌خطی ارائه می‌شود، در حین انتقال به base64 کدگذاری می‌شود که باعث افزایش اندازه درخواست می‌شود. اگر درخواست خیلی بزرگ باشد، خطای HTTP 413 دریافت خواهید کرد.

برای کسب اطلاعات دقیق در مورد موارد زیر، به صفحه «فایل‌های ورودی پشتیبانی‌شده و الزامات» مراجعه کنید:

انواع MIME سند پشتیبانی شده

مدل‌های چندوجهی Gemini از انواع MIME سند زیر پشتیبانی می‌کنند:

  • پی‌دی‌اف - application/pdf
  • متن - text/plain

محدودیت‌ها به ازای هر درخواست

فایل‌های PDF به عنوان تصویر در نظر گرفته می‌شوند، بنابراین یک صفحه از PDF به عنوان یک تصویر در نظر گرفته می‌شود. تعداد صفحات مجاز در یک prompt به تعداد تصاویری که مدل‌های چندوجهی Gemini می‌توانند پشتیبانی کنند، محدود شده است.

  • حداکثر تعداد فایل در هر درخواست: ۳۰۰۰ فایل
  • حداکثر تعداد صفحات در هر فایل: ۱۰۰۰ صفحه در هر فایل
  • حداکثر حجم هر فایل: ۵۰ مگابایت برای هر فایل



چه کار دیگری می‌توانید انجام دهید؟

  • یاد بگیرید که چگونه قبل از ارسال دستورات طولانی به مدل، توکن‌ها را بشمارید .
  • Cloud Storage for Firebase تنظیم کنید تا بتوانید فایل‌های بزرگ را در درخواست‌های چندوجهی خود بگنجانید و یک راه‌حل مدیریت‌شده‌تر برای ارائه فایل‌ها در اعلان‌ها داشته باشید. فایل‌ها می‌توانند شامل تصاویر، فایل‌های PDF، ویدیو و صدا باشند.
  • شروع به فکر کردن در مورد آماده‌سازی برای تولید کنید (به چک لیست تولید مراجعه کنید)، از جمله:

قابلیت‌های دیگر را امتحان کنید

آموزش کنترل تولید محتوا

شما همچنین می‌توانید با استفاده از دستورات و پیکربندی‌های مدل، آزمایش کنید و حتی یک قطعه کد تولید شده با استفاده از Google AI Studio دریافت کنید.

درباره مدل‌های پشتیبانی‌شده بیشتر بدانید

درباره مدل‌های موجود برای موارد استفاده مختلف و سهمیه‌ها و قیمت‌گذاری آنها اطلاعات کسب کنید.


درباره تجربه خود با Firebase AI Logic بازخورد دهید