การใช้ LangChain กับ Genkit

การติดตั้ง

npm i --save genkitx-langchain

การใช้งาน

คุณสามารถใช้เชนหรือยูทิลิตีของ LangChain ส่วนใหญ่ในโฟลว์ Genkit ตามที่เป็นอยู่ ตัวอย่างด้านล่างใช้ LangChain Retrievers, ตัวโหลดเอกสาร และโครงสร้างเชนเพื่อสร้างตัวอย่าง 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();

โปรดทราบว่าตัวอย่างนี้ใช้ GenkitTracer ที่ได้จากปลั๊กอิน genkitx-langchain เพื่อควบคุมเชน LangChain กับฟีเจอร์ความสามารถในการสังเกตของ Genkit ในตอนนี้ เมื่อคุณเรียกใช้โฟลว์จาก Dev UI หรือเวอร์ชันที่ใช้งานจริง คุณจะได้เห็นเชน LangChain อย่างเต็มรูปแบบ

โปรดทราบว่าคอมโพเนนต์ LangChain จะทำงานร่วมกับเวอร์ชันพื้นฐาน Genkit ไม่ได้ (โมเดล เอกสาร รีทรีฟเวอร์ ฯลฯ)

ผู้ประเมิน (ตัวอย่าง)

คุณจะใช้ผู้ประเมิน LangChain กับ Genkit ได้ กำหนดค่าผู้ประเมินที่คุณต้องการจากปลั๊กอิน langchain จากนั้นทำตามกระบวนการประเมินมาตรฐาน ดังนี้

import { langchain } from 'genkitx-langchain';

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