Genkit での LangChain の使用

インストール

npm i --save genkitx-langchain

使用量

Genkit フローでは、ほとんどの LangChain チェーンまたはユーティリティをそのまま使用できます。以下の例では、LangChain Retriever、ドキュメント ローダー、チェーン構造を使用して、単純な 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'],
      },
    }),
  ],
});