Firebase Genkit

Firebase Genkit는 프로덕션에 즉시 사용 가능한 AI 기반 앱을 빌드, 배포, 모니터링하는 데 도움이 되는 오픈소스 프레임워크입니다.

Genkit 로고

Genkit는 앱 개발자를 위해 설계되었으므로 익숙한 패턴과 패러다임으로 강력한 AI 기능을 앱에 손쉽게 통합할 수 있습니다. Firebase를 지원하는 동일한 팀에서 빌드했으며, 전 세계 수백만 개발자가 사용하는 도구의 개발 경험을 바탕으로 합니다.

Genkit를 사용하면 커스텀 콘텐츠 생성, 시맨틱 검색 사용, 구조화되지 않은 입력 처리, 비즈니스 데이터로 질문에 대한 답변, 자율적인 의사 결정, 도구 호출 조정 등의 앱을 만들 수 있습니다.

Genkit는 현재 JavaScript/TypeScript(Node.js)로 서버 측 개발을 지원하며 진행 중인 개발에서는 Go가 지원됩니다.

GitHub 저장소에서 개발 과정을 진행하거나 직접 개발에 참여할 수 있습니다.

주요 기능

Genkit를 사용하면 프로토타입 제작의 시작부터 프로덕션의 모니터링에 이르기까지 AI 개발 여정의 모든 단계를 지원할 수 있습니다. 따라서 논의할 사항이 많습니다.

시작하는 데 도움이 될 만한 10가지 주요 Genkit 기능을 소개합니다.

1. 여러 모델, 하나의 인터페이스

Genkit는 인기 모델에 즉시 액세스할 수 있는 플러그인과 모든 모델 API를 쉽게 통합하고 커뮤니티에서 유지관리하는 모델을 사용할 수 있는 유연한 모델 추상화를 제공합니다. 새 모델을 사용해 보는 것은 단일 인수를 변경하는 것만큼 쉽지만 모델마다 커스텀 구성을 지정할 수 있습니다.

import { geminiPro } from '@genkit-ai/vertexai';
import { ollama } from 'genkitx-ollama';
import { generate } from '@genkit-ai/ai';

function flipACoin(a, b) {
  return Math.random() > 0.5 ? a : b;
}

const result = await generate({
  model: flipACoin(geminiPro, 'ollama/gemma'),
  config: { temperature: 0.3, maxOutputTokens: 200 },
  prompt: 'What makes you the best LLM out there?',
});

console.log(result.text());

2. 구조화된 출력

Zod 스키마를 사용하여 Genkit으로 강타입(strongly typed) 데이터를 생성합니다. 이를 통해 구조화되지 않은 텍스트를 분석하고, 창의적인 콘텐츠를 생성하고, 작업을 선택하고, 결과를 구조화된 유형에 안전한 객체로 다시 앱에 전송할 수 있습니다.

import { generate } from "@genkit-ai/ai";
import { geminiPro } from "@genkit-ai/vertexai";
import { z } from "zod";

const CreatureSchema = z.object({
  name: z.string().describe('the name of the creature'),
  hitPoints: z.number().describe('hit points, between 5 and 100'),
  attacks: z.array(z.object({
    name: z.string(),
    damage: z.number().describe('amount of damage, between 2 and 25'),
  })).describe('3 attacks the creature can use')
});

const createCreature = defineFlow({
    name: "createCreature",
    inputSchema: z.string(),
    outputSchema: CreatureSchema,
  },
  (habitat) => {
    const result = await generate({
      model: geminiPro,
      prompt: `You are a brilliant RPG designer. Generate a creature that lives in ${habitat}.`,
      output: {schema: CreatureSchema}
    });
    // strongly typed and ready to go
    return result.output();
  }
)

console.log(await createCreature("a developer conference"));

3. 멀티모달, 멀티미디어

Genkit는 텍스트, 데이터, 임의 미디어의 혼합을 지원하는 콘텐츠에 공통 형식을 제공합니다. 이를 통해 LLM뿐만 아니라 모든 생성 작업 (예: 이미지 생성)을 수행하는 모델에 Genkit를 사용할 수 있습니다.

import { imagen2, geminiProVision } from '@genkit-ai/vertexai';
import { generate } from '@genkit-ai/ai';

const imageResult = await generate({
  model: imagen2,
  prompt: 'Generate an image of a very specific historical time and place.',
});
const generatedImage = imageResult.media();

const descriptionResult = await generate({
  model: geminiProVision,
  prompt: [
    {
      text: 'What is the historical time and place represented in this picture?',
    },
    { media: generatedImage },
  ],
});
console.log(descriptionResult.text());

4. LLM에 도구 제공

Genkit를 사용하면 도구를 통해 LLM으로 함수 호출을 간편하게 수행할 수 있습니다. 도구를 사용하면 AI가 데이터를 가져오거나 UI를 표시하거나 데이터베이스에 쓰는 등 코딩 가능한 기타 모든 작업을 수행할 수 있습니다.

import { generate, defineTool } from '@genkit-ai/ai';
import { geminiPro } from '@genkit-ai/vertexai';
import { z } from 'zod';

const createReminder = defineTool(
  {
    name: 'createReminder',
    description: 'Use this to create reminders for things in the future',
    inputSchema: z.object({
      time: z
        .string()
        .describe('ISO timestamp string, e.g. 2024-04-03T12:23:00Z'),
      reminder: z.string().describe('the content of the reminder'),
    }),
    outputSchema: z.number().describe('the ID of the created reminder'),
  },
  (reminder) => db.reminders.create(reminder)
);

const searchNotes = defineTool(
  {
    name: 'searchNotes',
    description: "Use this to search the user's notes for people or phrases",
    inputSchema: z.string().describe('the search query'),
    outputSchema: z.object({ notes: z.array(NoteSchema) }),
  },
  (query) => db.notes.search(query)
);

const result = await generate({
  model: geminiPro,
  tools: [createReminder, searchNotes],
  prompt: `
  You are a note-taking assistant. Using the tools available, try to answer the provided query.
  If you create a reminder, describe in text the reminder you created as a response.

  Query: I took a note about a meeting with Anna - can you set a reminder for the time?
  `,
});
console.log(result.text());

5. Dotprompt를 사용한 프롬프트 관리

프롬프트 엔지니어링은 단순한 텍스트 수정 이상의 의미가 있습니다. 사용하는 모델, 개발자가 제공하는 매개변수, 요청한 형식이 모두 출력 품질에 영향을 미칩니다. Genkit의 프롬프트 파일 형식인 Dotprompt를 사용하면 하나의 파일로 간편하게 테스트하고 정리할 수 있습니다.

---
model: vertexai/gemini-1.0-pro
config:
  temperature: 0.9
input:
  schema:
    properties:
      location: {type: string}
      style: {type: string}
      name: {type: string}
    required: [location]
  default:
    location: a restaurant
---

You are the world's most welcoming AI assistant and are currently working at {{location}}.

Greet a guest{{#if name}} named {{name}}{{/if}}{{#if style}} in the style of {{style}}{{/if}}.

6. 로컬에서 흐름 실행

생성형 AI는 결과에 엄청난 변화가 있기 때문에 실험이 매우 중요합니다 로컬 Genkit 개발자 UI를 사용하면 모델 및 검색기와 같은 필수 AI 구성요소와 상호작용할 수 있을 뿐만 아니라 직접 작성한 모든 커스텀 코드를 포함하여 엔드 투 엔드 흐름을 수동으로 테스트할 수 있습니다.

7. 트레이스 검사

AI를 사용하여 복잡한 다단계 워크플로를 디버깅하는 것은 무작위성과 숨겨진 프로세스로 인해 어려울 수 있습니다. Genkit는 개발자 UI에 트레이스 검사기를 제공하므로 흐름에서 각 모델 호출 및 단계의 트레이스를 검사할 수 있습니다. 프로덕션의 트레이스를 보고 이미지를 렌더링할 수도 있습니다.

8. 개방성 및 확장성

AI 생태계는 어느 한 팀이 따라잡을 수 없을 정도로 빠르게 성장하고 있습니다. Genkit에는 새 모델, 검색기 등과의 사전 빌드된 통합을 제공하는 개방형 플러그인 모델이 있습니다. Genkit팀은 소규모 공식 플러그인 세트를 유지하지만 누구나 자유롭게 자체 Genkit 플러그인을 NPM에 게시할 수 있습니다.

원하는 통합에 맞는 플러그인을 찾을 수 없으신가요? 괜찮습니다. Genkit의 추상화는 유연하며 이 커스텀 Firestore 검색기와 같이 프레임워크에 통합되는 커스텀 구성요소를 쉽게 빌드할 수 있습니다.

import { embed } from '@genkit-ai/ai/embedder';
import { Document, defineRetriever } from '@genkit-ai/ai/retriever';
import { textEmbeddingGecko } from '@genkit-ai/vertexai';
import {
  FieldValue,
  VectorQuery,
  VectorQuerySnapshot,
} from '@google-cloud/firestore';
import { Firestore } from 'firebase-admin/firestore';
import * as z from 'zod';
import { augmentedPrompt } from './prompt';

const QueryOptions = z.object({
  k: z.number().optional(),
});

const firestoreArtifactsRetriever = defineRetriever(
  {
    name: 'firestore/artifacts',
    configSchema: QueryOptions,
  },
  async (input, options) => {
    const embedding = await embed({
      embedder: textEmbeddingGecko,
      content: input,
    });

    const db = new Firestore();
    const coll = db.collection('vectors' /* your collection name */);

    const vectorQuery: VectorQuery = coll.findNearest(
      'embedding' /* the name of the field that contains the vector */,
      FieldValue.vector(embedding),
      {
        limit: options.k ?? 3,
        distanceMeasure: 'COSINE',
      }
    );

    const vectorQuerySnapshot: VectorQuerySnapshot = await vectorQuery.get();
    return {
      documents: vectorQuerySnapshot.docs.map((doc) =>
        // doc.data() represents the Firestore document. You may process
        // it as needed to generate a Genkit document object, depending on your
        // storage format.
        Document.fromText(doc.data().content.text)
      ),
    };
  }
);

9. 프로덕션을 위한 빌드

Express.js 앱을 제공할 수 있는 모든 플랫폼에 흐름을 손쉽게 배포할 수 있습니다. Genkit은 엔터프라이즈급 프로덕션 모니터링을 위해 OpenTelemetry 및 커스텀 메타데이터로 완벽하게 계측됩니다.

Google Cloud의 운영 제품군으로 데이터를 내보내고 Firebase용 Cloud Functions, Firebase 인증, 앱 체크, Firestore와 같은 Firebase 서비스와 통합하는 데 도움이 되는 Google Cloud 및 Firebase용 공식 플러그인도 있습니다.

Cloud Trace 스크린샷

10. 승인 및 보안 처리

공개용 애플리케이션을 빌드할 때는 시스템에 저장된 데이터를 보호하는 것이 중요합니다. LLM의 경우 모델이 필요한 데이터에만 액세스하고, 도구 호출 범위가 LLM을 호출하는 사용자로 적절하게 지정되며, 확인된 클라이언트 애플리케이션에 의해서만 흐름이 호출되는지 확인하기 위해 더욱 주의를 기울여야 합니다.

Genkit는 승인 정책 및 컨텍스트를 관리하기 위한 메커니즘을 제공합니다.

import { defineFlow, runFlow } from '@genkit-ai/flow';

export const selfSummaryFlow = defineFlow(
  {
    name: 'selfSummaryFlow',
    inputSchema: z.object({uid: z.string()}),
    outputSchema: z.string(),
    authPolicy: (auth, input) => {
      if (!auth) {
        throw new Error('Authorization required.');
      }
      if (input.uid !== auth.uid) {
        throw new Error('You may only summarize your own profile data.');
      }
    }
  },
  async (input) => { ... });

통합

Genkit는 플러그인 시스템을 통해 AI 모델, 벡터 데이터베이스, 원격 분석 플랫폼 등과의 통합을 제공합니다. 다음 플러그인은 Genkit팀에서 유지관리합니다.

공식 플러그인
googleai 생성 모델: Gemini Pro, Gemini 1.5 Pro, Gemini Pro Vision
임베딩 모델: Gecko 텍스트 임베딩
vertexai 생성 모델: Gemini Pro, Gemini Pro Vision, Gemini 1.5 Flash, Gemini 1.5 Pro, Imagen2, Anthropic Claude 3
임베딩 모델: Gecko 텍스트 임베딩
평가자: Vertex AI 평가
ollama 생성 모델: Gemma, Llama 3, Mistral 등 여러 로컬 모델
chroma 벡터 데이터베이스: ChromaDB
pinecone 벡터 데이터베이스: Pinecone
google-cloud 모니터링 도구: Google Cloud Trace, Google Cloud Logging
firebase Cloud 배포: Cloud Functions, Firebase 인증, 앱 체크
벡터 데이터베이스: Cloud Firestore 벡터 저장소
langchain Genkit 흐름에서 LangChain 체인 및 유틸리티 사용

시작하기

Genkit를 설치하고 첫 번째 AI 흐름을 실행하는 방법은 시작 가이드를 참조하세요.