LangChain中Chroma.fromDocuments调用报TypeError问题求助
Chroma.fromDocuments 报错 TypeError: Cannot read properties of undefined (reading 'data') 解决方法
问题场景
本地Node.js服务器运行LangChain流程,调用Chroma.fromDocuments创建向量存储时触发错误,已执行npm install -S langchain和npm install -S chromadb安装依赖。
报错代码
// Create docs with a loader const loader = new TextLoader("Documentation/hello.txt"); const docs = await loader.load(); // Create vector store and index the docs const vectorStore = await Chroma.fromDocuments(docs, new OpenAIEmbeddings(), { collectionName: "z-test-collection", }); // Search for the most similar document const response = await vectorStore.similaritySearch("hello", 1); console.log(response);
错误栈信息
/home/alexandre/projects/langChain/ProcessGPT/node_modules/chromadb/dist/main/index.js:291 return response.data; ^ TypeError: Cannot read properties of undefined (reading 'data') at /home/alexandre/projects/langChain/ProcessGPT/node_modules/chromadb/dist/main/index.js:291:29 at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async ChromaClient.getOrCreateCollection (/home/alexandre/projects/langChain/ProcessGPT/node_modules/chromadb/dist/main/index.js:286:31) at async Chroma.ensureCollection (/home/alexandre/projects/langChain/ProcessGPT/node_modules/langchain/dist/vectorstores/chroma.cjs:60:31) at async Chroma.addVectors (/home/alexandre/projects/langChain/ProcessGPT/node_modules/langchain/dist/vectorstores/chroma.cjs:77:28) at async Chroma.addDocuments (/home/alexandre/projects/langChain/ProcessGPT/node_modules/langchain/dist/vectorstores/chroma.cjs:52:9) at async Chroma.fromDocuments (/home/alexandre/projects/langChain/ProcessGPT/node_modules/langchain/dist/vectorstores/chroma.cjs:121:9) at async testChroma (/home/alexandre/projects/langChain/ProcessGPT/controllers/backendController.js:31:25)
原因分析
该错误核心原因是Chroma数据库服务未启动:npm安装的chromadb是客户端库,而非服务端程序,LangChain必须连接运行中的Chroma服务才能创建向量存储。
解决步骤
1. 启动本地Chroma服务
Chroma服务端基于Python实现,需完成以下操作:
- 确保本地已安装Python 3.8+
- 安装Chroma服务端:
pip install chromadb - 启动Chroma服务:
chroma run --host localhost --port 8000
2. 在代码中指定Chroma服务地址
修改Chroma.fromDocuments的配置参数,添加服务连接地址:
const vectorStore = await Chroma.fromDocuments(docs, new OpenAIEmbeddings(), { collectionName: "z-test-collection", url: "http://localhost:8000" // 指定Chroma服务地址 });
3. 配置OpenAI API密钥
使用OpenAIEmbeddings需要提供有效API密钥,可通过两种方式配置:
- 系统环境变量设置:
export OPENAI_API_KEY="你的API密钥"(Linux/macOS)或set OPENAI_API_KEY="你的API密钥"(Windows) - 代码中临时设置(仅测试用):
process.env.OPENAI_API_KEY = "你的API密钥";
4. 验证依赖版本兼容性
确保langchain和chromadb版本匹配,执行以下命令更新到最新稳定版:
npm update langchain chromadb
验证
启动Chroma服务后重新运行代码,即可正常创建向量存储并执行相似度搜索。
内容的提问来源于stack exchange,提问作者qYUUU
相关产品推荐
相关产品推荐

