การใช้ LangChain กับ Genkit

การติดตั้ง

npm i --save genkitx-langchain

การใช้งาน

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

โปรดทราบว่าตัวอย่างนี้ใช้ 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'],
      },
    }),
  ],
});