编写 Genkit 插件

Firebase Genkit 的功能可通过插件进行扩展。Genkit 插件是可配置的模块,可提供模型、检索器、索引器、跟踪记录存储区等。您已经通过 Genkit 了解了插件的实际应用:

import { configureGenkit } from '@genkit-ai/core';
import { vertexAI } from '@genkit-ai/vertexai';

configureGenkit({
  plugins: [vertexAI({ projectId: 'my-project' })],
});

Vertex AI 插件接受配置(例如用户的 Google Cloud 项目 ID),并通过 Genkit 注册表注册各种新模型、嵌入器等。该注册表可为 Genkit 的本地界面提供支持,用于运行和检查模型、提示等,并在运行时充当已命名操作的查找服务。

创建插件

若要创建插件,通常需要创建新的 NPM 软件包:

mkdir genkitx-my-plugin
cd genkitx-my-plugin
npm init -y
npm i --save @genkit-ai/core
npm i --save-dev typescript
npx tsc --init

然后,从主入口点定义并导出您的插件:

import { genkitPlugin } from '@genkit-ai/core';

interface MyPluginOptions {
  // add any plugin configuration here
}

export const myPlugin = genkitPlugin(
  'my-plugin',
  async (options: MyPluginOptions) => {
    // initialize your plugin here...
  }
);

插件选项指南

一般来说,您的插件应接受一个 options 参数,其中包含正常运行所需的任何插件范围的配置。对于任何需要 Secret 值的插件选项(例如 API 密钥),您应同时提供选项和默认环境变量来对其进行配置:

import { genkitPlugin, GenkitError } from '@genkit-ai/core';

interface MyPluginOptions {
  apiKey?: string;
}

export const myPlugin = genkitPlugin(
  'my-plugin',
  async (options: MyPluginOptions) => {
    const apiKey = options.apiKey || process.env.MY_PLUGIN_API_KEY;
    if (!apiKey)
      throw new GenkitError({
        source: 'my-plugin',
        status: 'INVALID_ARGUMENT',
        message:
          'Must supply either `options.apiKey` or set `MY_PLUGIN_API_KEY` environment variable.',
      });
    // ... continue initialization
  }
);

构建插件

单个插件可以激活 Genkit 中的许多新功能。例如,Vertex AI 插件会激活几个新模型以及一个嵌入器。

模型插件

Genkit 模型插件会将一个或多个生成式 AI 模型添加到 Genkit 注册表。模型表示能够接收提示作为输入并生成文本、媒体或数据作为输出的任何生成模型。通常,模型插件会在其初始化函数中进行一个或多个 defineModel 调用。

自定义模型通常由三部分组成:

  1. 定义模型功能的元数据。
  2. 包含模型支持的任何特定参数的配置架构。
  3. 一个函数,用于实现接受 GenerateRequest 并返回 GenerateResponse 的模型。

如需构建模型插件,您需要使用 @genkit-ai/ai 软件包:

npm i --save @genkit-ai/ai

大体上讲,模型插件可能如下所示:

import { genkitPlugin, GenkitError } from '@genkit-ai/core';
import { defineModel, GenerationCommonConfigSchema } from '@genkit-ai/ai/model';
import { simulateSystemPrompt } from '@genkit-ai/ai/model/middleware';
import { z } from 'zod';

export const myPlugin = genkitPlugin('my-plugin', async (options: {apiKey?: string}) => {
  defineModel({
    // be sure to include your plugin as a provider prefix
    name: 'my-plugin/my-model',
    // label for your model as shown in Genkit Developer UI
    label: 'My Awesome Model',
    // optional list of supported versions of your model
    versions: ['my-model-001', 'my-model-001'],
    // model support attributes
    supports: {
      multiturn: true, // true if your model supports conversations
      media: true, // true if your model supports multimodal input
      tools: true, // true if your model supports tool/function calling
      systemRole: true, // true if your model supports the system role
      output: ['text', 'media', 'json'], // types of output your model supports
    },
    // Zod schema for your model's custom configuration
    configSchema: GenerationCommonConfigSchema.extend({
      safetySettings: z.object({...}),
    }),
    // list of middleware for your model to use
    use: [simulateSystemPrompt()]
  }, async request => {
    const myModelRequest = toMyModelRequest(request);
    const myModelResponse = await myModelApi(myModelRequest);
    return toGenerateResponse(myModelResponse);
  });
});

转换请求和响应

Genkit 模型插件的主要工作是将 GenerateRequest 从 Genkit 的通用格式转换为模型 API 可识别和支持的格式,然后将模型的响应转换为 Genkit 使用的 GenerateResponseData 格式。

有时,这可能需要处理或处理数据以解决模型限制。例如,如果您的模型本身不支持 system 消息,您可能需要将提示的系统消息转换为用户/模型消息对。

模型参考

使用 defineModel 注册模型后,模型在通过名称请求时将始终可用。不过,为了改进输入和 IDE 自动补全功能,您可以从软件包中导出模型引用,其中仅包含模型的元数据,而不包含其实现:

import { modelRef } from "@genkit-ai/ai/model";

export myModelRef = modelRef({
  name: "my-plugin/my-model",
  configSchema: MyConfigSchema,
  info: {
    // ... model-specific info
  },
})

调用 generate() 时,模型引用和字符串模型名称可以互换使用:

import { myModelRef } from 'genkitx-my-plugin';
import { generate } from '@genkit-ai/ai';

generate({ model: myModelRef });
// is equivalent to
generate({ model: 'my-plugin/my-model' });

遥测插件

请参阅编写 Genkit 遥测插件

发布插件

Genkit 插件可以作为常规 NPM 软件包发布。为了提高可检测性并最大限度地提高一致性,您的软件包应命名为 genkitx-{name},以表明它是 Genkit 插件,并且您应该尽可能多地在 package.json 中添加与您的插件相关的以下 keywords

  • genkit-plugin:请务必在软件包中包含此关键字,以指明它是 Genkit 插件。
  • genkit-model:如果您的软件包定义了任何模型,请添加此关键字。
  • genkit-retriever:如果您的软件包定义了任何检索器,请添加此关键字。
  • genkit-indexer:如果您的软件包定义了任何索引器,请添加此关键字。
  • genkit-embedder:如果您的软件包定义了任何索引器,请添加此关键字。
  • genkit-tracestore:如果您的软件包定义了任何轨迹存储区,请添加此关键字。
  • genkit-statestore:如果您的软件包定义了任何状态存储,请添加此关键字。
  • genkit-telemetry:如果您的软件包定义了遥测提供程序,请添加此关键字。
  • genkit-deploy:如果您的软件包包含用于将 Genkit 应用部署到云服务提供商的帮助程序,请添加此关键字。
  • genkit-flow:如果您的软件包可以增强 Genkit 流程,请添加此关键字。

提供检索器、嵌入器和模型的插件可能具有如下所示的 package.json

{
  "name": "genkitx-my-plugin",
  "keywords": ["genkit-plugin", "genkit-retriever", "genkit-embedder", "genkit-model"],
  // ... dependencies etc.
}