Google 生成式 AI 插件

Google 生成式 AI 插件通过 Gemini API 提供 Google 的 Gemini 模型的接口。

安装

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' })],
});

如果您希望使用不同版本的 模型。

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

您可以通过 Genkit 使用上传到 Gemini Files API 的文件:

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}}
  ]
});