運用混合式推論,使用 Firebase AI Logic 建構 AI 輔助網頁應用程式和功能。混合式推論功能可讓您在裝置端模型可用時,使用該模型執行推論,否則會順暢地改用雲端代管模型 (反之亦然)。
本頁說明如何開始使用用戶端 SDK。完成這項標準設定後,請查看其他設定選項和功能 (例如結構化輸出)。
請注意,在電腦版 Chrome 上執行的網頁應用程式支援裝置端推論。
建議用途和支援的功能
建議用途:
使用裝置端模型進行推論:
- 強化隱私權
- 查看當地特色
- 免付費推論
- 離線功能
使用混合功能方案:
- 無論裝置端模型是否可用或是否連上網際網路,都能觸及 100% 的目標對象
裝置端推論支援的功能:
裝置端推論僅支援單輪文字生成 (不支援對話),支援的文字生成功能如下:
根據文字和圖片輸入內容生成文字,具體來說,輸入的圖片類型為 JPEG 和 PNG
您也可以產生結構化輸出內容,包括 JSON 和列舉。
事前準備
請注意下列事項:
使用裝置端模型進行推論時,會使用 Chrome 的提示 API;使用雲端託管模型進行推論時,則會使用您選擇的Gemini API供應商 (Gemini Developer API 或 Vertex AI Gemini API)。
本頁說明如何開始使用 localhost 進行開發 (如要進一步瞭解如何在 localhost 上使用 API,請參閱 Chrome 說明文件)。
完成這項標準設定後,請查看其他設定選項和功能 (例如結構化輸出)。
實作功能後,您可以讓使用者在實際應用程式中試用功能。
在 localhost 上開始使用
這些入門步驟說明傳送任何支援的提示要求時,所需的一般設定。
步驟 1:設定 Chrome 和 Prompt API,以便在裝置端進行推論
確認你使用的是新版 Chrome。前往 chrome://settings/help 更新。
Chrome 139 以上版本支援裝置端推論。將下列標記設為「Enabled」,即可啟用裝置端多模態模型:
chrome://flags/#prompt-api-for-gemini-nano-multimodal-input
重新啟動 Chrome。
(選用) 在發出第一個要求前,先下載裝置端模型。
Prompt API 已內建於 Chrome,但預設不會提供裝置端模型。如果您尚未下載模型,就首次要求進行裝置端推論,系統會自動在背景啟動模型下載作業。
步驟 2:設定 Firebase 專案,並將應用程式連結至 Firebase
登入 Firebase 控制台,然後選取 Firebase 專案。
在 Firebase 控制台中,依序前往「AI Services」(AI 服務) >「AI Logic」(AI 邏輯)。
按一下「開始使用」,啟動導覽工作流程,協助您為專案設定必要 API 和資源。
設定專案以使用「Gemini API」供應商。
建議您先使用 Gemini Developer API。 您隨時可以設定 Vertex AI Gemini API (以及帳單的相關規定)。
對於 Gemini Developer API,控制台會啟用必要的 API,並在專案中建立 Gemini API 金鑰。
請勿將這個 Gemini API 金鑰加入應用程式的程式碼庫。瞭解詳情。如果控制台工作流程中出現提示,請按照畫面上的指示註冊應用程式並連結至 Firebase。
請繼續按照本指南的下一個步驟,將 SDK 新增至應用程式。
步驟 3:新增 SDK
Firebase 程式庫提供 API,可與生成模型互動。這個程式庫是 Firebase JavaScript SDK for Web 的一部分。
使用 npm 安裝適用於網頁的 Firebase JS SDK:
npm install firebase在應用程式中初始化 Firebase:
import { initializeApp } from "firebase/app"; // 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);
步驟 4:初始化服務並建立模型例項
|
按一下 Gemini API 供應商,即可在這個頁面查看供應商專屬內容和程式碼。 |
將提示要求傳送至模型前,請先設定下列項目:
為所選 API 供應商初始化服務。
建立
GenerativeModel執行個體。請務必將mode設為下列其中一個值:PREFER_ON_DEVICE:如果裝置端模型可用,請使用該模型;否則改用雲端代管模型。ONLY_ON_DEVICE:如果裝置端提供模型,請使用該模型;否則擲回例外狀況。PREFER_IN_CLOUD:如可使用雲端代管模型,請使用該模型;否則改用裝置端模型。ONLY_IN_CLOUD:如果雲端主機代管模型可用,請使用該模型;否則擲回例外狀況。
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, InferenceMode } 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
// Set the mode (for example, use the on-device model if it's available)
const model = getGenerativeModel(ai, { mode: InferenceMode.PREFER_ON_DEVICE });
步驟 5:初始化裝置端模型
您必須在使用者與網頁互動 (例如點按按鈕) 後或當下,以及之前,呼叫 initializeDeviceModel(),才能將提示要求傳送至模型。如要進一步瞭解使用者啟用規定,請參閱 Chrome 說明文件。
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, InferenceMode } 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
// Set the mode (for example, use the on-device model if it's available)
const model = getGenerativeModel(ai, { mode: InferenceMode.PREFER_ON_DEVICE });
// `initializeDeviceModel` must be called:
// (1) after or on an end-user page interaction such as a button click
// and
// (2) before any queries to the model (such as `generateContent()`)
// You may want to `await` this promise if using `ONLY_ON_DEVICE` (see note below).
model.initializeDeviceModel((val) =>
// Example: "Download progress: 72.62%""
console.log(`Download progress: ${Math.round(val*10000) / 100}%`)
);
步驟 6:將提示要求傳送至模型
本節將說明如何傳送各種輸入內容,生成不同類型的輸出內容,包括:
如要生成結構化輸出內容 (例如 JSON 或列舉),請使用下列其中一個「生成文字」範例,並將模型設定為根據提供的結構定義回覆。
使用純文字輸入生成文字
| 嘗試這個範例前,請務必先完成本指南的「開始使用」一節。 |
您可以使用 generateContent() 從含有文字的提示生成文字:
// Imports + initialization of FirebaseApp and backend service + creation of model instance
// 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();
請注意,Firebase AI Logic 也支援使用
generateContentStream
(而非 generateContent) 串流傳輸文字回應。
根據文字和圖片 (多模態) 輸入內容生成文字
| 嘗試這個範例前,請務必先完成本指南的「開始使用」一節。 |
您可以使用
generateContent()
從含有文字和圖片檔案的提示生成文字,並提供每個輸入檔案的 mimeType 和檔案本身。
裝置端推論支援的輸入圖片類型為 PNG 和 JPEG。
// Imports + initialization of FirebaseApp and backend service + creation of model instance
// 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 image
const prompt = "Write a poem about this picture:";
const fileInputEl = document.querySelector("input[type=file]");
const imagePart = await fileToGenerativePart(fileInputEl.files[0]);
// To generate text output, call `generateContent` with the text and image
const result = await model.generateContent([prompt, imagePart]);
const response = result.response;
const text = response.text();
console.log(text);
}
run();
請注意,Firebase AI Logic 也支援使用
generateContentStream
(而非 generateContent) 串流傳輸文字回應。
讓使用者試用您的功能
如要讓使用者在應用程式中試用您的功能,您必須註冊 Chrome 原始碼試用計畫。請注意,這些試用方案有時間和用量限制。
註冊參加 Prompt API Chrome 來源試用。系統會提供權杖。
在要啟用試用功能的每個網頁上提供權杖。請使用下列其中一種方式:
在
<head>標記中以中繼標記的形式提供權杖:<meta http-equiv="origin-trial" content="TOKEN">以 HTTP 標頭形式提供權杖:
Origin-Trial: TOKEN以程式輔助方式提供權杖。
你還能做些什麼?
您可以為混合式體驗使用各種額外的設定選項和功能:
目前尚未支援裝置端推論的功能
由於這是搶先體驗版,因此並非所有 Web SDK 功能都適用於裝置端推論。下列功能尚未支援裝置端推論 (但通常適用於雲端推論)。
從 JPEG 和 PNG 以外的圖片檔案輸入類型生成文字
- 可改用雲端託管模型,但
ONLY_ON_DEVICE模式會擲回錯誤。
- 可改用雲端託管模型,但
從音訊、影片和文件 (例如 PDF) 輸入內容生成文字
- 可改用雲端託管模型,但
ONLY_ON_DEVICE模式會擲回錯誤。
- 可改用雲端託管模型,但
使用 Gemini 或 Imagen 模型生成圖片
- 可以改用雲端託管模型,但
ONLY_ON_DEVICE模式會擲回錯誤。
- 可以改用雲端託管模型,但
在多模態要求中,使用網址提供檔案。您必須以內嵌資料的形式,將檔案提供給裝置端模型。
多輪對話
- 可以改用雲端託管模型,但
ONLY_ON_DEVICE模式會擲回錯誤。
- 可以改用雲端託管模型,但
透過 Gemini Live API 進行雙向串流
提供工具給模型,協助生成回覆 (例如函式呼叫、程式碼執行、網址內容、
Google Search 基礎和Google Maps 基礎)計算詞元數
- 一律會擲回錯誤。雲端代管和裝置端模型之間的計數方式不同,因此沒有直覺式的備援機制。
Firebase 控制台中的 AI 監控功能,適用於裝置端推論。
- 請注意,使用雲端主機代管模型進行的任何推論,都可以像使用 Firebase AI Logic 用戶端 Web SDK 進行的其他推論一樣受到監控。
提供有關 Firebase AI Logic 的使用體驗意見回饋