安裝項目
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 基元 (模型、文件、擷取器等) 互通。
評估工具 (預先發布版)
您可以透過 Genkit 使用 LangChain 評估工具。透過 langchain
外掛程式設定需要的評估工具,然後按照標準評估程序操作:
import { langchain } from 'genkitx-langchain';
configureGenkit({
plugins: [
langchain({
evaluators: {
judge: geminiPro,
criteria: ['harmfulness', 'maliciousness'],
},
}),
],
});