您可以要求 Gemini 模型分析您透過內嵌 (base64 編碼) 或網址提供的文件檔案 (例如 PDF 和純文字檔案)。使用 Firebase AI Logic 時,您可以直接透過應用程式提出這項要求。
這項功能可讓您執行下列操作:
- 分析文件中的圖表、圖表和表格
- 將資訊擷取至結構化輸出格式
- 回答文件中圖像和文字內容的問題
- 生成文件摘要
- 將文件內容轉錄成 HTML 等格式,並保留版面配置和格式,以便在後續應用程式 (例如 RAG 管道) 中使用
如要瞭解其他文件 (例如 PDF) 的其他工作選項,請參閱其他指南 產生結構化輸出內容 多回合即時通訊 |
事前準備
按一下您的 Gemini API 供應商,即可在本頁查看供應商專屬內容和程式碼。 |
如果您尚未完成,請參閱入門指南,瞭解如何設定 Firebase 專案、將應用程式連結至 Firebase、新增 SDK、為所選 Gemini API 供應器初始化後端服務,以及建立 GenerativeModel
例項。
如要測試並重複提示,甚至取得產生的程式碼片段,建議您使用 Google AI Studio。
從 PDF 檔案產生文字 (以 base64 編碼)
在嘗試這個範例前,請先完成本指南的「開始前」一節,設定專案和應用程式。 在該部分,您也需要點選所選Gemini API供應商的按鈕,才能在本頁面上看到供應商專屬內容。 |
您可以要求 Gemini 模型透過文字和 PDF 提示來產生文字,方法是提供每個輸入檔案的 mimeType
和檔案本身。請參閱本頁後續的輸入檔案相關規定和建議。
Swift
您可以呼叫 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.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
您可以呼叫 generateContent()
,從文字和 PDF 的多模態輸入內容產生文字。
// 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
您可以呼叫 generateContent()
,從文字和 PDF 的多模態輸入內容產生文字。
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
您可以呼叫 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.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
您可以呼叫 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.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);
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-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.");
瞭解如何選擇適合用途和應用程式的模型。
逐句顯示回應
在嘗試這個範例前,請先完成本指南的「開始前」一節,設定專案和應用程式。 在該部分,您也需要點選所選Gemini API供應商的按鈕,才能在本頁面上看到供應商專屬內容。 |
您可以不等待模型產生的完整結果,改用串流處理部分結果,以便加快互動速度。如要串流回應,請呼叫 generateContentStream
。
輸入文件的規定和建議
請注意,以內嵌資料形式提供的檔案會在傳輸過程中編碼為 base64,因此會增加要求的大小。如果要求過大,您會收到 HTTP 413 錯誤。
請參閱「支援的 Vertex AI Gemini API 輸入檔案和相關規定」一文,瞭解下列項目的詳細資訊:
- 在要求中提供檔案的不同選項 (內嵌或使用檔案的網址或 URI)
- 文件檔案的相關規定和最佳做法
支援的影片 MIME 類型
Gemini 多模態模型支援下列文件 MIME 類型:
文件 MIME 類型 | Gemini 2.0 Flash | Gemini 2.0 Flash‑Lite |
---|---|---|
PDF - application/pdf |
||
文字 - text/plain |
每項要求的限制
PDF 會視為圖片,因此 PDF 的單一頁面會視為一張圖片。提示中允許的頁面數量,以模型可支援的圖片數量為限:
- Gemini 2.0 Flash 和 Gemini 2.0 Flash‑Lite:
- 每項要求的檔案數量上限:3,000 個
- 每個檔案的頁數上限:1,000 個
- 每個檔案的大小上限:50 MB
你還可以做些什麼?
- 瞭解如何計算符號,再將長提示傳送至模型。
- 設定 Cloud Storage for Firebase,這樣您就能在多模態要求中加入大型檔案,並透過更妥善的解決方案在提示中提供檔案。檔案可包含圖片、PDF、影片和音訊。
-
開始著手準備正式版 (請參閱正式版檢查清單),包括:
- 設定 Firebase App Check,以免 Gemini API 遭到未經授權的用戶端濫用。
- 整合 Firebase Remote Config,無須發布新版應用程式,即可更新應用程式中的值 (例如型號名稱)。
試用其他功能
- 建構多輪對話 (聊天)。
- 使用文字提示來生成文字。
- 從文字和多模態提示產生結構化輸出內容 (例如 JSON)。
- 使用文字提示生成圖片。
- 使用函式呼叫,將生成模型連結至外部系統和資訊。
瞭解如何控管內容產生作業
- 瞭解提示設計,包括最佳做法、策略和提示範例。
- 設定模型參數,例如溫度參數和輸出符記數量上限 (適用於 Gemini),或顯示比例和人物生成 (適用於 Imagen)。
- 使用安全性設定,調整可能會收到有害回應的機率。
進一步瞭解支援的型號
瞭解可用於各種用途的模型,以及相關配額和價格。針對使用 Firebase AI Logic 的體驗提供意見回饋