搭配使用 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 鏈結。現在,當您在開發人員 UI 或實際工作環境中執行流程時,您將能全面掌握 LangChain 鏈結。

另請注意,LangChain 元件無法與 Genkit 原始版本 (模型、文件、擷取器等) 互通。

評估工具 (預先發布版)

您可以將 LangChain 評估工具與 Genkit 搭配使用。透過 langchain 外掛程式設定需要的評估工具,然後按照標準評估程序操作:

import { langchain } from 'genkitx-langchain';

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