Firebase Genkit

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

Genkit 로고

앱 개발자용으로 설계된 Genkit는 익숙한 패턴과 패러다임으로 강력한 AI 기능을 앱에 쉽게 통합할 수 있도록 설계되었습니다. 전 세계 수백만 개발자가 사용하는 빌드 도구에서 Google의 경험을 활용하여 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로 강력한 유형의 데이터를 생성합니다. 이렇게 하면 구조화되지 않은 텍스트를 분석하고, 광고 소재 콘텐츠를 생성하고, 작업을 선택하고, 결과를 구조화된 유형 안전 객체로 앱에 다시 보낼 수 있습니다.

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에는 새로운 모델, Retriever 등과의 사전 빌드된 통합을 제공하는 개방형 플러그인 모델이 있습니다. 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 흐름을 실행하는 방법을 알아보세요.