Google 生成式 AI 外掛程式

Google 生成式 AI 外掛程式為 Google 的 Gemini 模型提供介面 透過 Gemini API

安裝

npm i --save @genkit-ai/googleai

設定

如要使用這個外掛程式,請在呼叫 configureGenkit() 時指定:

import { googleAI } from '@genkit-ai/googleai';

export default configureGenkit({
  plugins: [googleAI()],
  // ...
});

外掛程式需要 Gemini API 的 API 金鑰,您可以從中取得 Google AI Studio

採取下列任一做法,設定外掛程式以使用 API 金鑰:

  • GOOGLE_GENAI_API_KEY 環境變數設為 API 金鑰。

  • 請在初始化外掛程式時指定 API 金鑰:

    googleAI({ apiKey: yourKey });
    

    不過,請勿直接在程式碼中嵌入 API 金鑰!僅使用這項功能 搭配 Cloud Secret Manager 或類似服務

Gemini 1.5 Pro 等部分模型目前為預先發布版,只能透過 v1beta API。您可以指定 apiVersion 來取得這些模型的存取權:

configureGenkit({
  plugins: [googleAI({ apiVersion: 'v1beta' })],
});

如果您要使用不同版本的 VM 同時處理不同模型

configureGenkit({
  plugins: [googleAI({ apiVersion: ['v1', 'v1beta'] })],
});

用量

這個外掛程式會以靜態方式將參照匯出至支援的模型:

import {
  gemini15Flash,
  gemini15Pro,
  textEmbeddingGecko001,
} from '@genkit-ai/googleai';

您可以透過這些參照來指定 generate() 使用的模型:

const llmResponse = await generate({
  model: gemini15Flash,
  prompt: 'Tell me a joke.',
});

或使用嵌入器 (例如textEmbeddingGecko001) 取代為 embed 或擷取器:

const embedding = await embed({
  embedder: textEmbeddingGecko001,
  content: input,
});

Gemini 檔案 API

你可以將上傳至 Gemini Files API 的檔案與 Genkit 搭配使用:

import { GoogleAIFileManager } from '@google/generative-ai/server';

const fileManager = new GoogleAIFileManager(process.env.GOOGLE_GENAI_API_KEY);
const uploadResult = await fileManager.uploadFile(
  'path/to/file.jpg',
  {
    mimeType: 'image/jpeg',
    displayName: 'Your Image',
  }
);

const response = await generate({
  model: gemini15Flash,
  prompt: [
    {text: 'Describe this image:'},
    {media: {contentType: uploadResult.file.mimeType, url: uploadResult.file.uri}}
  ]
});