میتوانید از یک مدل Gemini بخواهید فایلهای سند (مانند فایلهای PDF و فایلهای متن ساده) را که به صورت درون خطی (با کدگذاری پایه 64) یا از طریق URL ارائه میکنید، تجزیه و تحلیل کند. وقتی از Firebase AI Logic استفاده میکنید، میتوانید این درخواست را مستقیماً از برنامه خود ارسال کنید.
با این قابلیت می توانید کارهایی مانند:
- نمودارها، نمودارها و جداول داخل اسناد را تجزیه و تحلیل کنید
- استخراج اطلاعات به فرمت های خروجی ساخت یافته
- به سوالات مربوط به محتوای تصویری و متنی در اسناد پاسخ دهید
- اسناد را خلاصه کنید
- رونویسی محتوای سند (مثلاً به HTML)، حفظ طرحبندی و قالببندی، برای استفاده در برنامههای پایین دستی (مانند خطوط لوله RAG)
پرش به نمونه کد پرش به کد برای پاسخ های جریانی
سایر راهنماها را برای گزینه های اضافی برای کار با اسناد (مانند PDF) ببینید ایجاد خروجی ساختاریافته چت چند نوبتی |
قبل از شروع
برای مشاهده محتوا و کد ارائه دهنده خاص در این صفحه، روی ارائه دهنده API Gemini خود کلیک کنید. |
اگر قبلاً این کار را نکردهاید، راهنمای شروع را کامل کنید، که نحوه راهاندازی پروژه Firebase را توضیح میدهد، برنامه خود را به Firebase متصل کنید، SDK را اضافه کنید، سرویس Backend را برای ارائهدهنده API Gemini انتخابی خود مقداردهی کنید و یک نمونه GenerativeModel
ایجاد کنید.
میتوانید از این فایل در دسترس عموم با نوع MIME
application/pdf
استفاده کنید ( مشاهده یا دانلود فایل ).https://storage.googleapis.com/cloud-samples-data/generative-ai/pdf/2403.05530.pdf
تولید متن از فایلهای PDF (با پایه 64 کدگذاری شده)
قبل از امتحان این نمونه، بخش قبل از شروع این راهنما را تکمیل کنید تا پروژه و برنامه خود را راه اندازی کنید. در آن بخش، همچنین روی دکمه ای برای ارائه دهنده API Gemini انتخابی خود کلیک می کنید تا محتوای خاص ارائه دهنده را در این صفحه ببینید . |
میتوانید از یک مدل Gemini بخواهید که متنی را با درخواست متن و فایلهای PDF تولید کند—با ارائه mimeType
هر فایل ورودی و خود فایل. الزامات و توصیههای مربوط به فایلهای ورودی را بعداً در این صفحه پیدا کنید.
سویفت
برای تولید متن از ورودی چند وجهی متن و PDF، میتوانید generateContent()
فراخوانی کنید.
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.0-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
برای تولید متن از ورودی چند وجهی متن و PDF، میتوانید generateContent()
فراخوانی کنید.
// 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.0-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 = generativeModel.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
برای تولید متن از ورودی چند وجهی متن و PDF، میتوانید generateContent()
فراخوانی کنید.
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.0-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
برای تولید متن از ورودی چند وجهی متن و PDF، میتوانید generateContent()
فراخوانی کنید.
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.0-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
برای تولید متن از ورودی چند وجهی متن و PDF، میتوانید generateContent()
فراخوانی کنید.
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.0-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);
وحدت
برای تولید متن از ورودی چند وجهی متن و PDF، میتوانید GenerateContentAsync()
را فراخوانی کنید.
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.0-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
را فراخوانی کنید.
سویفت
برای پخش متن تولید شده از ورودی چند وجهی متن و PDF، میتوانید generateContentStream()
فراخوانی کنید.
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.0-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
برای پخش متن تولید شده از ورودی چند وجهی متن و PDF، میتوانید generateContentStream()
فراخوانی کنید.
// 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.0-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 = ""
generativeModel.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
برای پخش متن تولید شده از ورودی چند وجهی متن و PDF، میتوانید generateContentStream()
فراخوانی کنید.
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.0-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
برای پخش متن تولید شده از ورودی چند وجهی متن و PDF، میتوانید generateContentStream()
فراخوانی کنید.
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.0-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
برای پخش متن تولید شده از ورودی چند وجهی متن و PDF، میتوانید generateContentStream()
فراخوانی کنید.
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.0-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.0-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 دریافت می کنید.
برای کسب اطلاعات دقیق در مورد موارد زیر به "فایل های ورودی پشتیبانی شده و الزامات برای Vertex AI Gemini API " مراجعه کنید:
- گزینه های مختلف برای ارائه یک فایل در یک درخواست (به صورت درون خطی یا با استفاده از URL یا URI فایل)
- الزامات و بهترین شیوه ها برای فایل های سند
انواع MIME ویدیویی پشتیبانی شده
مدلهای چندوجهی Gemini از انواع سند MIME زیر پشتیبانی میکنند:
نوع MIME سند | فلش جمینی 2.0 | Gemini 2.0 Flash-Lite |
---|---|---|
PDF - application/pdf | ||
متن - text/plain |
محدودیت در هر درخواست
PDFها به عنوان تصویر در نظر گرفته می شوند، بنابراین یک صفحه از یک PDF به عنوان یک تصویر در نظر گرفته می شود. تعداد صفحات مجاز در یک درخواست محدود به تعداد تصاویری است که مدل می تواند پشتیبانی کند:
- Gemini 2.0 Flash و Gemini 2.0 Flash-Lite :
- حداکثر تعداد فایل در هر درخواست: 3000
- حداکثر صفحه در هر فایل: 1000
- حداکثر حجم هر فایل: 50 مگابایت
چه کار دیگری می توانید انجام دهید؟
- قبل از ارسال پیام های طولانی به مدل، نحوه شمارش نشانه ها را بیاموزید.
- Cloud Storage for Firebase راهاندازی کنید تا بتوانید فایلهای حجیم را در درخواستهای چندوجهی خود بگنجانید و راهحل مدیریتشدهتری برای ارائه فایلها در درخواستها داشته باشید. فایلها میتوانند شامل تصاویر، PDF، ویدیو و صدا باشند.
- در مورد آماده شدن برای تولید فکر کنید (به چک لیست تولید مراجعه کنید)، از جمله:
- راهاندازی Firebase App Check برای محافظت از Gemini API در برابر سوء استفاده توسط مشتریان غیرمجاز.
- یکپارچه سازی Firebase Remote Config برای به روز رسانی مقادیر در برنامه شما (مانند نام مدل) بدون انتشار نسخه جدید برنامه.
قابلیت های دیگر را امتحان کنید
- مکالمات چند نوبتی (چت) بسازید.
- متن را از اعلانهای فقط متنی ایجاد کنید.
- خروجی ساختاریافته (مانند JSON) را هم از دستورات متنی و هم از چند وجهی ایجاد کنید.
- تولید تصاویر از پیام های متنی
- از فراخوانی تابع برای اتصال مدل های مولد به سیستم ها و اطلاعات خارجی استفاده کنید.
یاد بگیرید چگونه تولید محتوا را کنترل کنید
- طراحی سریع، از جمله بهترین شیوهها، استراتژیها و درخواستهای نمونه را درک کنید .
- پارامترهای مدل مانند دما و نشانههای حداکثر خروجی (برای Gemini ) یا نسبت ابعاد و تولید شخص (برای Imagen ) را پیکربندی کنید.
- از تنظیمات ایمنی برای تنظیم احتمال دریافت پاسخ هایی که ممکن است مضر تلقی شوند استفاده کنید .
درباره مدل های پشتیبانی شده بیشتر بدانید
در مورد مدل های موجود برای موارد استفاده مختلف و سهمیه ها و قیمت آنها اطلاعات کسب کنید.درباره تجربه خود با Firebase AI Logic بازخورد بدهید