教學課程:開始使用 Gemini API


本教學課程示範如何使用 Google AI JavaScript SDK,為 Node.js 應用程式存取 Gemini API。

在本教學課程中,您將瞭解如何執行下列操作:

此外,本教學課程包含進階用途相關章節 (例如嵌入計算符記),以及控制內容產生的選項。

先備知識

本教學課程假設您已熟悉如何使用 Node.js 建構應用程式。

如要完成本教學課程,請確認您的開發環境符合下列規定:

  • Node.js v18 以上版本
  • npm

設定專案

呼叫 Gemini API 之前,您需要先設定專案,包括設定 API 金鑰、安裝 SDK 套件,以及初始化模型。

設定 API 金鑰

如要使用 Gemini API,您必須具備 API 金鑰。如果您沒有金鑰 請在 Google AI Studio 中建立金鑰

取得 API 金鑰

確保 API 金鑰安全

強烈建議您「不要」在版本管控系統中登錄 API 金鑰。您應該改用密鑰儲存庫做為 API 金鑰。

本教學課程的所有程式碼片段都假設您是以環境變數的形式存取 API 金鑰。

安裝 SDK 套件

如要在自己的應用程式中使用 Gemini API,您必須安裝 Node.js 適用的 GoogleGenerativeAI 套件:

npm install @google/generative-ai

初始化生成式模型

您必須先匯入並初始化生成式模型,才能發出 API 呼叫。

const { GoogleGenerativeAI } = require("@google/generative-ai");

// Access your API key as an environment variable (see "Set up your API key" above)
const genAI = new GoogleGenerativeAI(process.env.API_KEY);

// ...

// The Gemini 1.5 models are versatile and work with most use cases
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash"});

// ...

指定模型時,請注意下列事項:

  • 使用您用途專屬的模型 (例如,gemini-1.5-flash 適用於多模態輸入)。在本指南中,各實作方法的操作說明會列出每種用途的建議模型。

實作常見用途

專案設定完成後,您就可以瞭解如何使用 Gemini API 實作不同的用途:

在進階用途部分中,您可以找到 Gemini API 和嵌入的相關資訊。

從純文字輸入來生成文字

如果提示輸入內容僅包含文字,請使用搭載 generateContent 的 Gemini 1.5 模型來產生文字:

const { GoogleGenerativeAI } = require("@google/generative-ai");

// Access your API key as an environment variable (see "Set up your API key" above)
const genAI = new GoogleGenerativeAI(process.env.API_KEY);

async function run() {
  // The Gemini 1.5 models are versatile and work with both text-only and multimodal prompts
  const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash"});

  const prompt = "Write a story about a magic backpack."

  const result = await model.generateContent(prompt);
  const response = await result.response;
  const text = response.text();
  console.log(text);
}

run();

根據文字和圖片輸入內容產生文字 (多模態)

Gemini 1.5 Flash 和 1.5 Pro 可以處理多模態輸入,讓您能夠輸入文字和圖片。請務必查看提示的圖片規定

如果提示輸入內容包含文字和圖片,請使用 Gemini 1.5 模型搭配 generateContent 方法產生文字輸出:

const { GoogleGenerativeAI } = require("@google/generative-ai");
const fs = require("fs");

// Access your API key as an environment variable (see "Set up your API key" above)
const genAI = new GoogleGenerativeAI(process.env.API_KEY);

// Converts local file information to a GoogleGenerativeAI.Part object.
function fileToGenerativePart(path, mimeType) {
  return {
    inlineData: {
      data: Buffer.from(fs.readFileSync(path)).toString("base64"),
      mimeType
    },
  };
}

async function run() {
  // The Gemini 1.5 models are versatile and work with both text-only and multimodal prompts
  const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

  const prompt = "What's different between these pictures?";

  const imageParts = [
    fileToGenerativePart("image1.png", "image/png"),
    fileToGenerativePart("image2.jpeg", "image/jpeg"),
  ];

  const result = await model.generateContent([prompt, ...imageParts]);
  const response = await result.response;
  const text = response.text();
  console.log(text);
}

run();

打造多輪對話 (聊天)

使用 Gemini 即可多回合,建立任意形式的對話。SDK 會透過管理對話狀態來簡化程序,因此與 generateContent 不同,您不需要自行儲存對話記錄。

如要建構多輪對話 (例如對話),請使用 Gemini 1.5 模型或 Gemini 1.0 Pro 模型,然後呼叫 startChat() 初始化對話。接著使用 sendMessage() 傳送新的使用者訊息,這個訊息也會將訊息和回應附加到即時通訊記錄中。

與對話中的內容相關的 role 有兩種可能的選項:

  • user:提供提示的角色。這個值是 sendMessage 呼叫的預設值。

  • model:提供回應的角色。透過現有的 history 呼叫 startChat() 時,您可以使用這個角色。

const { GoogleGenerativeAI } = require("@google/generative-ai");

// Access your API key as an environment variable (see "Set up your API key" above)
const genAI = new GoogleGenerativeAI(process.env.API_KEY);

async function run() {
  // The Gemini 1.5 models are versatile and work with multi-turn conversations (like chat)
  const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash"});

  const chat = model.startChat({
    history: [
      {
        role: "user",
        parts: [{ text: "Hello, I have 2 dogs in my house." }],
      },
      {
        role: "model",
        parts: [{ text: "Great to meet you. What would you like to know?" }],
      },
    ],
    generationConfig: {
      maxOutputTokens: 100,
    },
  });

  const msg = "How many paws are in my house?";

  const result = await chat.sendMessage(msg);
  const response = await result.response;
  const text = response.text();
  console.log(text);
}

run();

使用串流加快互動速度

根據預設,模型會在完成整個產生程序後傳回回應。您不必等待整個結果,就能實現更快速的互動,並改用串流處理部分結果。

以下範例說明如何使用 generateContentStream 方法實作串流,根據文字和圖片輸入提示產生文字。

//...

const result = await model.generateContentStream([prompt, ...imageParts]);

let text = '';
for await (const chunk of result.stream) {
  const chunkText = chunk.text();
  console.log(chunkText);
  text += chunkText;
}

//...

在純文字輸入和聊天使用情境中,您也可以採取類似的做法。

// Use streaming with text-only input
const result = await model.generateContentStream(prompt);

請參閱上方的即時通訊範例,瞭解如何將 chat 執行個體化。

// Use streaming with multi-turn conversations (like chat)
const result = await chat.sendMessageStream(msg);

實作進階用途

本教學課程前一節所述的常見用途,可協助您熟悉 Gemini API 的使用方式。本節說明一些較進階的用途。

使用嵌入

嵌入是一種技術,用於將資訊顯示為陣列中的浮點數清單。您可以透過 Gemini 以向量形式表示文字 (字詞、句子和文字區塊),比較嵌入和對比。舉例來說,具有相同主題或情緒的兩段文字應有類似的嵌入,並且可透過數學相似度等數學比較技巧來識別。

搭配 embedContent 方法 (或 batchEmbedContent 方法) 使用 embedding-001 模型產生嵌入。以下範例會產生單一字串的嵌入:

const { GoogleGenerativeAI } = require("@google/generative-ai");

// Access your API key as an environment variable (see "Set up your API key" above)
const genAI = new GoogleGenerativeAI(process.env.API_KEY);

async function run() {
  // For embeddings, use the embedding-001 model
  const model = genAI.getGenerativeModel({ model: "embedding-001"});

  const text = "The quick brown fox jumps over the lazy dog."

  const result = await model.embedContent(text);
  const embedding = result.embedding;
  console.log(embedding.values);
}

run();

函式呼叫

函式呼叫可讓您輕鬆從生成式模型取得結構化資料輸出內容。接著,您可以使用這些輸出內容呼叫其他 API,並將相關的回應資料傳回模型。換句話說,函式呼叫可協助您將生成式模型連結至外部系統,讓產生的內容包含最新且準確的資訊。詳情請參閱函式呼叫教學課程

計算符記數量

使用長提示時,建議先計算符記再傳送任何內容至模型。下列範例說明如何將 countTokens() 用於各種用途:

// For text-only input
const { totalTokens } = await model.countTokens(prompt);
// For text-and-image input (multimodal)
const { totalTokens } = await model.countTokens([prompt, ...imageParts]);
// For multi-turn conversations (like chat)
const history = await chat.getHistory();
const msgContent = { role: "user", parts: [{ text: msg }] };
const contents = [...history, msgContent];
const { totalTokens } = await model.countTokens({ contents });

控管內容生成功能的選項

您可以設定模型參數及使用安全設定,控管內容產生作業。

請注意,將 generationConfigsafetySettings 傳遞至模型要求方法 (例如 generateContent) 會完全覆寫 getGenerativeModel 中傳遞的相同名稱設定物件。

設定模型參數

您傳送至模型的每個提示都含有參數值,用來控制模型生成回覆的方式。模型可能會針對不同的參數值產生不同的結果。進一步瞭解模型參數

const generationConfig = {
  stopSequences: ["red"],
  maxOutputTokens: 200,
  temperature: 0.9,
  topP: 0.1,
  topK: 16,
};

// The Gemini 1.5 models are versatile and work with most use cases
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash",  generationConfig });

使用安全性設定

您可以使用安全性設定,調整收到可能視為有害回應的機率。根據預設,安全性設定會封鎖中等和/或很有可能為不安全的內容。進一步瞭解安全性設定

以下說明如何進行各項安全性設定:

import { HarmBlockThreshold, HarmCategory } from "@google/generative-ai";

// ...

const safetySettings = [
  {
    category: HarmCategory.HARM_CATEGORY_HARASSMENT,
    threshold: HarmBlockThreshold.BLOCK_ONLY_HIGH,
  },
];

// The Gemini 1.5 models are versatile and work with most use cases
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash", safetySettings });

你也可以設置多項安全性設定:

const safetySettings = [
  {
    category: HarmCategory.HARM_CATEGORY_HARASSMENT,
    threshold: HarmBlockThreshold.BLOCK_ONLY_HIGH,
  },
  {
    category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,
    threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
  },
];

後續步驟

  • 「提示設計」是指建立提示的程序,會從語言模型中取得所需回應。想確保語言模型提供準確且高品質的回覆,就必須撰寫條理分明的提示。瞭解撰寫提示的最佳做法

  • Gemini 提供多種不同模型版本,可滿足不同用途的需求,例如輸入類型和複雜度、對話或其他對話方塊語言工作的實作方式,以及大小限制。瞭解可用的 Gemini 模型