你可以要求 Gemini 模型根據純文字提示或多模態提示生成文字。使用 Firebase AI Logic 時,您可以直接從應用程式提出這項要求。
多模態提示可包含多種輸入類型 (例如文字和圖片、PDF、純文字檔案、音訊和影片)。
本指南說明如何從純文字提示詞和包含檔案的基本多模態提示詞生成文字。
跳至僅限文字輸入的程式碼 跳至多模態輸入的程式碼 跳至串流回應的程式碼
|
如需其他文字處理選項,請參閱其他指南 生成結構化輸出內容 多輪對話 在裝置上生成文字 文字轉語音 (TTS) 根據文字生成圖片 |
事前準備
|
按一下 Gemini API 供應商,即可在這個頁面查看供應商專屬內容和程式碼。 |
如果尚未完成,請參閱入門指南,瞭解如何設定 Firebase 專案、將應用程式連結至 Firebase、新增 SDK、為所選Gemini API供應商初始化後端服務,以及建立 GenerativeModel 執行個體。
如要測試及反覆調整提示,建議使用 Google AI Studio。
使用純文字輸入生成文字
|
嘗試這個範例前,請先完成本指南的「事前準備」一節,設定專案和應用程式。 在該節中,您也會點選所選Gemini API供應商的按鈕,以便在本頁面查看供應商專屬內容。 |
你可以只輸入文字,要求 Gemini 模型生成文字。
Swift
您可以呼叫
generateContent()
,從純文字輸入內容生成文字。
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.8-flash")
// Provide a prompt that contains text
let prompt = "Write a story about a magic backpack."
// To generate text output, call generateContent with the text input
let response = try await model.generateContent(prompt)
print(response.text ?? "No text in response.")
Kotlin
您可以呼叫
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-3.8-flash")
// Provide a prompt that contains text
val prompt = "Write a story about a magic backpack."
// To generate text output, call generateContent with the text input
val response = model.generateContent(prompt)
print(response.text)
Java
您可以呼叫
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-3.8-flash");
// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
// Provide a prompt that contains text
Content prompt = new Content.Builder()
.addText("Write a story about a magic backpack.")
.build();
// To generate text output, call generateContent with the text input
ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
System.out.println(resultText);
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
Web
您可以呼叫
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-3.8-flash" });
// Wrap in an async function so you can use await
async function run() {
// Provide a prompt that contains text
const prompt = "Write a story about a magic backpack."
// To generate text output, call generateContent with the text input
const result = await model.generateContent(prompt);
const response = result.response;
const text = response.text();
console.log(text);
}
run();
Dart
您可以呼叫 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-3.8-flash');
// Provide a prompt that contains text
final prompt = [Content.text('Write a story about a magic backpack.')];
// To generate text output, call generateContent with the text input
final response = await model.generateContent(prompt);
print(response.text);
Unity
您可以呼叫
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-3.8-flash");
// Provide a prompt that contains text
var prompt = "Write a story about a magic backpack.";
// To generate text output, call GenerateContentAsync with the text input
var response = await model.GenerateContentAsync(prompt);
UnityEngine.Debug.Log(response.Text ?? "No text in response.");
瞭解如何選擇適合應用程式和用途的模型, 。
使用文字和檔案 (多模態) 輸入內容生成文字
|
嘗試這個範例前,請先完成本指南的「事前準備」一節,設定專案和應用程式。 在該節中,您也會點選所選Gemini API供應商的按鈕,以便在本頁面查看供應商專屬內容。 |
您可以透過文字和檔案提示 Gemini 模型生成文字,方法是提供每個輸入檔案的 mimeType 和檔案本身。請參閱本頁面稍後的輸入檔案規定和建議。
以下範例說明如何從檔案輸入內容生成文字,方法是分析以內嵌資料 (Base64 編碼檔案) 形式提供的單一影片檔案。
請注意,這個範例顯示的是內嵌提供檔案,但 SDK 也支援提供 YouTube 網址。
Swift
您可以呼叫
generateContent()
從文字和影片檔案的多模態輸入內容生成文字。
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.8-flash")
// Provide the video as `Data` with the appropriate MIME type.
let video = InlineDataPart(data: try Data(contentsOf: videoURL), mimeType: "video/mp4")
// Provide a text prompt to include with the video
let prompt = "What is in the video?"
// To generate text output, call generateContent with the text and video
let response = try await model.generateContent(video, prompt)
print(response.text ?? "No text in response.")
Kotlin
您可以呼叫
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-3.8-flash")
val contentResolver = applicationContext.contentResolver
contentResolver.openInputStream(videoUri).use { stream ->
stream?.let {
val bytes = stream.readBytes()
// Provide a prompt that includes the video specified above and text
val prompt = content {
inlineData(bytes, "video/mp4")
text("What is in the video?")
}
// To generate text output, call generateContent with the prompt
val response = model.generateContent(prompt)
Log.d(TAG, response.text ?: "")
}
}
Java
您可以呼叫
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-3.8-flash");
// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
ContentResolver resolver = getApplicationContext().getContentResolver();
try (InputStream stream = resolver.openInputStream(videoUri)) {
File videoFile = new File(new URI(videoUri.toString()));
int videoSize = (int) videoFile.length();
byte[] videoBytes = new byte[videoSize];
if (stream != null) {
stream.read(videoBytes, 0, videoBytes.length);
stream.close();
// Provide a prompt that includes the video specified above and text
Content prompt = new Content.Builder()
.addInlineData(videoBytes, "video/mp4")
.addText("What is in the video?")
.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 resultText = result.getText();
System.out.println(resultText);
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
}
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
Web
您可以呼叫
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-3.8-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(',')[1]);
reader.readAsDataURL(file);
});
return {
inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
};
}
async function run() {
// Provide a text prompt to include with the video
const prompt = "What do you see?";
const fileInputEl = document.querySelector("input[type=file]");
const videoPart = await fileToGenerativePart(fileInputEl.files[0]);
// To generate text output, call generateContent with the text and video
const result = await model.generateContent([prompt, videoPart]);
const response = result.response;
const text = response.text();
console.log(text);
}
run();
Dart
您可以呼叫 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-3.8-flash');
// Provide a text prompt to include with the video
final prompt = TextPart("What's in the video?");
// Prepare video for input
final video = await File('video0.mp4').readAsBytes();
// Provide the video as `Data` with the appropriate mimetype
final videoPart = InlineDataPart('video/mp4', video);
// To generate text output, call generateContent with the text and images
final response = await model.generateContent([
Content.multi([prompt, ...videoPart])
]);
print(response.text);
Unity
您可以呼叫
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-3.8-flash");
// Provide the video as `data` with the appropriate MIME type.
var video = ModelContent.InlineData("video/mp4",
System.IO.File.ReadAllBytes(System.IO.Path.Combine(
UnityEngine.Application.streamingAssetsPath, "yourVideo.mp4")));
// Provide a text prompt to include with the video
var prompt = ModelContent.Text("What is in the video?");
// To generate text output, call GenerateContentAsync with the text and video
var response = await model.GenerateContentAsync(new [] { video, prompt });
UnityEngine.Debug.Log(response.Text ?? "No text in response.");
瞭解如何選擇適合應用程式和用途的模型, 。
逐句顯示回覆
|
嘗試這個範例前,請先完成本指南的「事前準備」一節,設定專案和應用程式。 在該節中,您也會點選所選Gemini API供應商的按鈕,以便在本頁面查看供應商專屬內容。 |
您不必等待模型生成完整結果,而是使用串流處理部分結果,即可加快互動速度。如要串流回覆,請呼叫 generateContentStream。
輸入圖片檔案的規定和建議
請注意,以內嵌資料形式提供的檔案在傳輸過程中會編碼為 base64,這會增加要求的大小。如果要求過大,就會收到 HTTP 413 錯誤。
請參閱「Agent Platform Gemini API (formerly Vertex AI)支援的輸入檔案和規定」,詳細瞭解下列事項:
- 在要求中提供檔案的不同選項 (內嵌或使用檔案的網址/URI)
- 支援的檔案類型
- 支援的 MIME 類型和指定方式
- 檔案和多模態要求的相關規定和最佳做法
你還可以做些什麼?
- 瞭解如何計算符記數量, 再將長提示傳送給模型。
- 設定 Cloud Storage for Firebase,以便在多模態要求中加入大型檔案,並取得更完善的解決方案,在提示中提供檔案。檔案可包含圖片、PDF、影片和音訊。
-
開始準備正式版 (請參閱正式版檢查清單):
- 盡早Firebase App Check強制執行 ,有助於保護 Gemini API,避免未經授權的用戶濫用。
- 使用Firebase Remote Config或伺服器提示詞範本,即可隨選變更 AI 功能的設定 (例如模型名稱),不必發布新版應用程式。
試試其他功能
- 建立多輪對話 (即時通訊)。
- 使用純文字提示生成文字。
- 從文字和多模態提示生成結構化輸出內容 (例如 JSON)。
- 生成及編輯圖片:使用文字和多模態提示詞。
- 使用 Gemini 文字轉語音 (TTS) 模型生成語音 (單人或多人)。
- 使用 Gemini Live API 串流輸入和輸出內容 (包括音訊)。
-
使用工具 (例如函式呼叫
和 Grounding with
Google Search 或Google Maps ) 將 Gemini 模型連結至應用程式的其他部分,以及外部系統和資訊。
瞭解如何控管內容生成功能
您也可以使用 Google AI Studio 測試提示和模型設定,甚至取得生成的程式碼片段。
進一步瞭解支援的機型
瞭解各種用途適用的模型,以及這些模型的配額和價格。提供有關 Firebase AI Logic 的使用體驗意見回饋