搭配 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 來檢測 LangChain 具備 Genkit 觀測能力功能的連鎖店。現在當您在 Dev UI 或實際工作環境中執行流程時 即可完全掌握 LangChain 鏈結。

另請注意,LangChain 元件無法與 Genkit 基元 (模型、 文件、擷取程式等)。

評估工具 (預先發布版)

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

import { langchain } from 'genkitx-langchain';

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