Genkit과 함께 LangChain 사용

설치

npm i --save genkitx-langchain

사용량

Genkit 흐름에서 대부분의 LangChain 체인 또는 유틸리티를 그대로 사용할 수 있습니다. 아래 예에서는 LangChain 검색기, 문서 로더 및 체인 구조를 사용하여 기본 RAG 샘플을 빌드합니다.

import { initializeGenkit } from '@genkit-ai/core';
import { defineFlow, run, startFlowsServer } from '@genkit-ai/flow';
import { GoogleVertexAIEmbeddings } from '@langchain/community/embeddings/googlevertexai';
import { GoogleVertexAI } from '@langchain/community/llms/googlevertexai';
import { StringOutputParser } from '@langchain/core/output_parsers';
import { PromptTemplate } from '@langchain/core/prompts';
import {
  RunnablePassthrough,
  RunnableSequence,
} from '@langchain/core/runnables';
import { GenkitTracer } from 'genkitx-langchain';
import { PDFLoader } from 'langchain/document_loaders/fs/pdf';
import { formatDocumentsAsString } from 'langchain/util/document';
import { MemoryVectorStore } from 'langchain/vectorstores/memory';
import * as z from 'zod';

import config from './genkit.config';

initializeGenkit(config);

const vectorStore = new MemoryVectorStore(new GoogleVertexAIEmbeddings());
const model = new GoogleVertexAI();

export const indexPdf = defineFlow(
  { name: 'indexPdf', inputSchema: z.string(), outputSchema: z.void() },
  async (filePath) => {
    const docs = await run('load-pdf', async () => {
      return await new PDFLoader(filePath).load();
    });
    await run('index', async () => {
      vectorStore.addDocuments(docs);
    });
  }
);

const prompt =
  PromptTemplate.fromTemplate(`Answer the question based only on the following context:
{context}

Question: {question}`);
const retriever = vectorStore.asRetriever();

export const pdfQA = defineFlow(
  { name: 'pdfQA', inputSchema: z.string(), outputSchema: z.string() },
  async (question) => {
    const chain = RunnableSequence.from([
      {
        context: retriever.pipe(formatDocumentsAsString),
        question: new RunnablePassthrough(),
      },
      prompt,
      model,
      new StringOutputParser(),
    ]);

    return await chain.invoke(question, { callbacks: [new GenkitTracer()] });
  }
);

startFlowsServer();

이 예에서는 genkitx-langchain 플러그인에서 제공하는 GenkitTracer를 사용하여 Genkit 관측 가능성 기능으로 LangChain 체인을 계측합니다. 이제 Dev UI 또는 프로덕션 단계에서 흐름을 실행하면 LangChain 체인을 완전히 확인할 수 있습니다.

또한 LangChain 구성요소는 Genkit 프리미티브 (모델, 문서, 검색기 등)와 상호 운용이 불가능합니다.

평가자 (미리보기)

Genkit와 함께 LangChain 평가자를 사용할 수 있습니다. langchain 플러그인에서 원하는 평가자를 구성한 후 표준 평가 프로세스를 따릅니다.

import { langchain } from 'genkitx-langchain';

configureGenkit({
  plugins: [
    langchain({
      evaluators: {
        judge: geminiPro,
        criteria: ['harmfulness', 'maliciousness'],
      },
    }),
  ],
});