Ben*_*nji 2 npm typescript reactjs next.js langchain
我正在 Langchain 和 OpenAI 的帮助下创建一个应用程序。我正在加载数据并JSONLoader希望将其存储在矢量存储中,以便我可以根据用户请求进行检索以回答特定于我的数据的问题。Langchain 文档将 HNSWLib 描述为仅 Node.js 应用程序的可能存储。根据我的理解,NEXT 是建立在 Node.js 之上的,因此它可以运行 SS javascript,所以我应该能够使用它。我还应该提到JSONLoader也只能在 NodeJS 上运行,它运行得很好,所以我认为它应该已经全部设置完毕。
我按照新路由处理程序的文档在 app/api/llm/route.ts 中创建了一个 API 路由,并安装了该hnswlib-node包。
import { NextRequest } from 'next/server';
import { OpenAI } from 'langchain/llms/openai';
import { RetrievalQAChain } from 'langchain/chains';
import { JSONLoader } from 'langchain/document_loaders/fs/json';
import { HNSWLib } from 'langchain/vectorstores/hnswlib';
import { OpenAIEmbeddings } from 'langchain/embeddings/openai';
import path from 'path';
// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
export const GET = async (req: NextRequest) => {
const apiKey = process.env.NEXT_PUBLIC_OPENAI_API_KEY;
const model = new OpenAI({ openAIApiKey: apiKey, temperature: 0.9, modelName: 'gpt-3.5-turbo' });
// Initialize the LLM to use to answer the question.
const loader = new JSONLoader(path.join(process.cwd(), '/assets/surfspots.json'));
const docs = await loader.load();
// Create a vector store from the documents.
const vectorStore = await HNSWLib.fromDocuments(docs, new OpenAIEmbeddings({ openAIApiKey: apiKey }));
// Create a chain that uses the OpenAI LLM and HNSWLib vector store.
const chain = RetrievalQAChain.fromLLM(model, vectorStore.asRetriever());
const res = await chain.call({
query: 'List me all of the waves I can find in Fuerteventura',
});
console.log({ res });
};
Run Code Online (Sandbox Code Playgroud)
我在客户端反应组件的前端调用它。
当我尝试运行此代码时,出现以下错误:
Error: Please install hnswlib-node as a dependency with, e.g. `npm install -S hnswlib-node`
at HNSWLib.imports (webpack-internal:///(sc_server)/./node_modules/langchain/dist/vectorstores/hnswlib.js:184:19)
Run Code Online (Sandbox Code Playgroud)
我尝试重新安装软件包,删除node_modules并重新安装所有内容,在网上搜索答案等。
有人使用过这些库或者有任何方向我可以考虑调试这个吗?先感谢您!
Ben*_*nji 11
尝试重新安装后,更改导入并删除独立包并尝试从 langchain 库中使用。我在 github 上遇到了一个问题。在 langchain/js 的 github 上,有一个线程描述了不同环境下的类似问题,事实证明,该next.config.js文件需要一些额外的设置才能使其工作。强烈感谢@manduks。
https://github.com/hwchase17/langchainjs/issues/943#issuecomment-1544928533
添加第 6 行解决了问题。
/** @type {import("next").NextConfig} */
module.exports = {
experimental: { appDir: true },
webpack(config) {
config.experiments = { ...config.experiments, topLevelAwait: true };
config.externals = [...config.externals, 'hnswlib-node']; // by adding this line, solved the import
return config;
},
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1257 次 |
| 最近记录: |