میتوانید از یک مدل Gemini بخواهید فایلهای سند (مانند فایلهای PDF و فایلهای متن ساده) را که به صورت درون خطی (با کدگذاری پایه 64) یا از طریق URL ارائه میکنید، تجزیه و تحلیل کند. وقتی از Vertex AI در Firebase استفاده میکنید، میتوانید این درخواست را مستقیماً از برنامه خود ارسال کنید.
با این قابلیت می توانید کارهایی مانند:
- نمودارها، نمودارها و جداول داخل اسناد را تجزیه و تحلیل کنید
- استخراج اطلاعات به فرمت های خروجی ساخت یافته
- به سوالات مربوط به محتوای تصویری و متنی در اسناد پاسخ دهید
- اسناد را خلاصه کنید
- رونویسی محتوای سند (مثلاً به HTML)، حفظ طرحبندی و قالببندی، برای استفاده در برنامههای پایین دستی (مانند خطوط لوله RAG)
پرش به نمونه کد پرش به کد برای پاسخ های جریانی
سایر راهنماها را برای گزینه های اضافی برای کار با اسناد (مانند PDF) ببینید ایجاد خروجی ساختاریافته چت چند نوبتی |
قبل از شروع
اگر قبلاً این کار را نکردهاید، راهنمای شروع را کامل کنید، که نحوه راهاندازی پروژه Firebase را توضیح میدهد، برنامه خود را به Firebase متصل کنید، SDK را اضافه کنید، سرویس Vertex AI را راهاندازی کنید، و یک نمونه GenerativeModel
ایجاد کنید.
برای آزمایش و تکرار بر روی دستورات خود و حتی دریافت یک قطعه کد تولید شده، توصیه می کنیم از Vertex AI Studio استفاده کنید.
میتوانید از این فایل در دسترس عموم با نوع MIME
application/pdf
استفاده کنید ( مشاهده یا دانلود فایل ).https://storage.googleapis.com/cloud-samples-data/generative-ai/pdf/2403.05530.pdf
فایلهای PDF (با کدگذاری پایه 64) را ارسال کنید و متن را دریافت کنید
قبل از امتحان کردن این نمونه، مطمئن شوید که بخش قبل از شروع این راهنما را تکمیل کرده اید.
میتوانید از یک مدل Gemini بخواهید که متنی را با درخواست متن و فایلهای PDF تولید کند—با ارائه mimeType
هر فایل ورودی و خود فایل. الزامات و توصیههای مربوط به فایلهای ورودی را بعداً در این صفحه پیدا کنید.
سویفت
برای تولید متن از ورودی چند وجهی متن و PDF، میتوانید generateContent()
فراخوانی کنید.
import FirebaseVertexAI
// Initialize the Vertex AI service
let vertex = VertexAI.vertexAI()
// Create a `GenerativeModel` instance with a model that supports your use case
let model = vertex.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 Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
val generativeModel = Firebase.vertexAI.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 Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
GenerativeModel gm = FirebaseVertexAI.getInstance()
.generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(gm);
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 { getVertexAI, getGenerativeModel } from "firebase/vertexai";
// 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 Vertex AI service
const vertexAI = getVertexAI(firebaseApp);
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(vertexAI, { 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_vertexai/firebase_vertexai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
final model =
FirebaseVertexAI.instance.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);
نحوه انتخاب یک مدل و به صورت اختیاری مکان مناسب برای مورد استفاده و برنامه خود را بیاموزید.
جریان پاسخ
قبل از امتحان کردن این نمونه، مطمئن شوید که بخش قبل از شروع این راهنما را تکمیل کرده اید.
میتوانید با منتظر ماندن برای کل نتیجه تولید مدل، به تعاملات سریعتری برسید و در عوض از استریم برای مدیریت نتایج جزئی استفاده کنید. برای پخش جریانی پاسخ، generateContentStream
را فراخوانی کنید.
سویفت
برای پخش متن تولید شده از ورودی چند وجهی متن و PDF، میتوانید generateContentStream()
فراخوانی کنید.
import FirebaseVertexAI
// Initialize the Vertex AI service
let vertex = VertexAI.vertexAI()
// Create a `GenerativeModel` instance with a model that supports your use case
let model = vertex.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 Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
val generativeModel = Firebase.vertexAI.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 Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
GenerativeModel gm = FirebaseVertexAI.getInstance()
.generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(gm);
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 { getVertexAI, getGenerativeModel } from "firebase/vertexai";
// 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 Vertex AI service
const vertexAI = getVertexAI(firebaseApp);
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(vertexAI, { 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_vertexai/firebase_vertexai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
final model =
FirebaseVertexAI.instance.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);
}
الزامات و توصیه ها برای اسناد ورودی
برای کسب اطلاعات دقیق در مورد موارد زیر به "فایل های ورودی پشتیبانی شده و الزامات برای 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 در برابر سوء استفاده توسط مشتریان غیرمجاز باشید. همچنین، حتماً چک لیست تولید را مرور کنید.
قابلیت های دیگر را امتحان کنید
- مکالمات چند نوبتی (چت) بسازید.
- متن را از اعلانهای فقط متنی ایجاد کنید.
- خروجی ساختاریافته (مانند JSON) را هم از دستورات متنی و هم از چند وجهی ایجاد کنید.
- تولید تصاویر از پیام های متنی
- از فراخوانی تابع برای اتصال مدل های مولد به سیستم ها و اطلاعات خارجی استفاده کنید.
بیاموزید که چگونه تولید محتوا را کنترل کنید
- طراحی سریع، از جمله بهترین شیوهها، استراتژیها و درخواستهای نمونه را درک کنید .
- پارامترهای مدل مانند دما و نشانههای حداکثر خروجی (برای Gemini ) یا نسبت ابعاد و تولید شخص (برای Imagen ) را پیکربندی کنید.
- از تنظیمات ایمنی برای تنظیم احتمال دریافت پاسخ هایی که ممکن است مضر تلقی شوند استفاده کنید .
درباره مدل های پشتیبانی شده بیشتر بدانید
در مورد مدل های موجود برای موارد استفاده مختلف و سهمیه ها و قیمت آنها اطلاعات کسب کنید.درباره تجربه خود با Vertex AI در Firebase بازخورد بدهید