安装
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 链进行插桩。现在,当您从开发界面或生产环境中运行流程时,可以全面了解 LangChain 链。
另请注意,LangChain 组件无法与 Genkit 基元(模型、文档、检索器等)互操作。
评估器(预览版)
您可以将 LangChain 评估器与 Genkit 结合使用。从 langchain
插件配置所需的评估器,然后遵循标准评估流程:
import { langchain } from 'genkitx-langchain';
configureGenkit({
plugins: [
langchain({
evaluators: {
judge: geminiPro,
criteria: ['harmfulness', 'maliciousness'],
},
}),
],
});