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 플러그인은 Genkit 레지스트리에 구성 (예: 사용자의 Google Cloud 프로젝트 ID)을 가져와 다양한 새 모델, 임베더 등을 등록합니다. 레지스트리는 모델, 프롬프트 등을 실행하고 검사하기 위한 Genkit의 로컬 UI를 지원하고 런타임 시 이름이 지정된 작업의 조회 서비스 역할도 합니다.

플러그인 만들기

플러그인을 만들려면 일반적으로 다음과 같이 새 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 인수를 사용해야 합니다. 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 모델 플러그인은 Genkit 레지스트리에 하��� 이상의 생성형 AI 모델을 추가합니다. 모델은 프롬프트를 입력으로 수신하고 텍스트, 미디어 또는 데이터를 출력으로 생성할 수 있는 모든 생성 모델을 나타냅니다. 일반적으로 모델 플러그인은 초기화 함수에서 하나 이상의 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 플러그인임을 나타내야 하며 플러그인과 관련된 다음 keywordspackage.json에 최대한 많이 포함해야 합니다.

  • 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.
}