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

使用TruLens instrument装饰器后LangChain Chroma检索器失效

TruLens instrument装饰器导致Chroma检索器失效的问题排查与解决

问题描述

使用TruLens测试RAG应用时,只要导入from trulens.apps.custom import instrument并给函数加上该装饰器,Chroma检索器就会停止工作——调用retriever.invoke()时程序直接终止。移除instrument的导入和装饰器后,代码能正常检索并打印文档。

补充:相同代码在Mac环境下可正常运行,对比发现Mac环境安装了Linux相关库uvloop。

复现代码

from trulens.apps.custom import instrument
from langchain_community.vectorstores import Chroma
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_community.docstore.document import Document

@instrument
def test_chroma_instrumentation():
    docs = [Document("This is sample text")]

    vectorstore = Chroma.from_documents(documents=docs, embedding=HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L6-v2'))

    retriever = vectorstore.as_retriever()

    response = retriever.invoke("sample")

    print(response)


if __name__ == "__main__":
    test_chroma_instrumentation()

解决方法

1. 安装uvloop库

既然Mac环境因uvloop可正常运行,在当前环境尝试安装该库:

pip install uvloop

TruLens的instrument装饰器可能依赖异步事件循环,uvloop作为高效的异步实现,能修复装饰器引发的线程/事件循环冲突问题。

2. 调整instrument的使用范围

避免用装饰器包裹包含Chroma初始化和检索的整个函数,仅装饰RAG流程中的特定环节(比如LLM处理逻辑):

from trulens.apps.custom import instrument
from langchain_community.vectorstores import Chroma
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_community.docstore.document import Document

def test_chroma_instrumentation():
    docs = [Document("This is sample text")]

    vectorstore = Chroma.from_documents(documents=docs, embedding=HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L6-v2'))

    retriever = vectorstore.as_retriever()

    response = retriever.invoke("sample")
    process_response(response)

@instrument
def process_response(response):
    print(response)

if __name__ == "__main__":
    test_chroma_instrumentation()

3. 检查版本兼容性

确认TruLens与LangChain、Chroma的版本是否匹配,尝试升级TruLens到稳定版本:

pip install --upgrade trulens

内容的提问来源于stack exchange,提问作者Gautam Malhotra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 08:15:01