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