You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用TypeScript+LangChain调用ChromaDB遇请求错误及挂起问题

问题解决:LangChain + ChromaDB 在TypeScript中的报错与挂起问题

问题现象

  • Docker容器运行时,执行代码抛出Error: [object Response],报错栈指向ChromaClient.getOrCreateCollection
  • Docker关闭时,程序陷入无响应挂起状态

错误原因分析

  1. 未指定ChromaDB连接地址:LangChain的Chroma客户端默认未正确指向Docker运行的Chroma服务地址,导致请求响应处理异常
  2. 文本处理逻辑错误:将字符串数组JSON.stringify后再拆分,生成的Document内容是JSON格式字符串,而非预期的分段文本,同时增加了不必要的处理步骤
  3. Docker关闭时无超时处理:客户端持续等待无响应的Chroma服务,导致程序挂起

修复步骤

  • 配置ChromaDB连接地址:在Chroma.fromDocuments的配置项中显式指定Docker映射的Chroma服务地址(默认是http://localhost:8000)
  • 修正文本拆分逻辑:直接使用原始字符串数组创建Documents,无需JSON序列化
  • 确保Docker端口映射正确:启动Chroma容器时确认端口映射命令为docker run -p 8000:8000 chromadb/chroma
  • 优化错误处理:添加更详细的错误信息打印,便于排查响应问题

优化后的代码

export async function processTextArray(): Promise<void> {
    const testTexts = [
        `Tortoise: Labyrinth? Labyrinth? Could it Are we in the notorious Little
Harmonic Labyrinth of the dreaded Majotaur?`,
        'Achilles: Yiikes! What is that?',
        `Tortoise: They say-although I person never believed it myself-that an I
Majotaur has created a tiny labyrinth sits in a pit in the middle of
it, waiting innocent victims to get lost in its fears complexity.
Then, when they wander and dazed into the center, he laughs and
laughs at them-so hard, that he laughs them to death!`,
        'Achilles: Oh, no!',
        "Tortoise: But it's only a myth. Courage, Achilles.",
    ];

    try {
        // 直接用文本数组创建Documents,无需JSON序列化
        const textSplitter = new RecursiveCharacterTextSplitter({
            chunkSize: 1000,
        });
        // 对每个文本单独拆分,而非序列化整个数组
        const docs = await textSplitter.createDocuments(testTexts);
        console.log('Generated documents:', docs);

        // 显式指定ChromaDB的连接地址
        const chromaResponse = await Chroma.fromDocuments(
            docs,
            new OpenAIEmbeddings({ openAIApiKey: process.env.OPENAI_API_KEY }),
            {
                collectionName: 'test',
                url: 'http://localhost:8000' // 关键:指定Docker运行的Chroma服务地址
            }
        );

        console.log('Chroma response:', chromaResponse);
        console.log('Text data processed and saved to ChromaDB');
    } catch (error) {
        // 优化错误打印,显示完整错误信息
        console.error('Error details:', error);
        // 尝试解析Response类型的错误
        if (error instanceof Response) {
            console.error('Response status:', error.status);
            console.error('Response body:', await error.text());
        }
    }
}

额外注意事项

  • 确认Docker容器正常运行:执行docker ps查看chromadb/chroma容器状态,确保8000端口已映射
  • 检查OpenAI API密钥是否正确配置:确保环境变量OPENAI_API_KEY已正确设置且有效

内容的提问来源于stack exchange,提问作者Casey Mackrell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 21:15:42