LightRAG 自定义 LLM / Embedding 接入常见问题总结
LightRAG 自定义 LLM / Embedding 接入常见问题总结环境LightRAG 版本: 当前仓库HKUDS/LightRAGLLM: DeepSeek (deepseek-chat, API:https://api.deepseek.com/v1)Embedding: 硅基流动 (Qwen/Qwen3-VL-Embedding-8B, API:https://api.siliconflow.cn/v1)运行平台: Windows 11问题 1:ImportError—wrap_llm_func_with_attrs不存在错误信息ImportError: cannot import name wrap_llm_func_with_attrs from lightrag.utils根因lightrag.utils中根本没有wrap_llm_func_with_attrs这个函数。只有wrap_embedding_func_with_attrs。修复删除该导入LLM 函数不需要专用包装器只需手动补充属性fromlightrag.utilsimportwrap_embedding_func_with_attrs# 只保留这一个问题 2: LLM 函数不是 async错误信息运行异常LLM 函数被同步调用导致阻塞。根因LightRAG 是全异步框架llm_model_func的预期签名是async def。使用同步defrequests会破坏事件循环。修复# ❌ 错误defdeepseek_llm_func(prompt,...):responserequests.post(...)...# ✅ 正确asyncdefdeepseek_llm_func(prompt,...):asyncwithaiohttp.ClientSession()assession:asyncwithsession.post(...)asresp:...问题 3:function object has no attribute func错误信息AttributeError: function object has no attribute func根因LightRAG 内部代码会访问llm_model_func.func参见lightrag/utils.pyEmbeddingFunc.__post_init__中的 unwrap 逻辑自定义 LLM 函数没有这个属性。修复手动给函数附加func和model_name属性deepseek_llm_func.funcdeepseek_llm_func deepseek_llm_func.model_namedeepseek-chat问题 4:wrap_embedding_func_with_attrs用法错误错误信息不确定的行为 / 装饰器未生效。根因wrap_embedding_func_with_attrs是一个返回装饰器的函数必须用作装饰器不能当成普通函数调用。修复# ❌ 错误 — 当普通函数传参调用silicon_embedding_wrappedwrap_embedding_func_with_attrs(embedding_funcsilicon_qwen_embedding_func,model_nameEMBED_MODEL_NAME)# ✅ 正确 — 作为装饰器使用wrap_embedding_func_with_attrs(embedding_dim4096,max_token_size8192,model_nameEMBED_MODEL_NAME)asyncdefsilicon_qwen_embedding_func(texts):...问题 5:list object has no attribute size⭐ 核心问题错误信息ERROR: Pipeline halted on internal storage error (Cancelled by internal error: NanoVectorDBStorage[entities]: list object has no attribute size) WARNING: Failed to batch pre-compute embeddings: list object has no attribute size ERROR: Query failed: list object has no attribute size根因EmbeddingFunc.__call__lightrag/utils.py:614会在返回值上调用.size# lightrag/utils.py 第 614 行total_elementsresult.size# 要求 np.ndarrayPython list 没有此属性返回List[np.ndarray]Python list 包装的 numpy 数组是错误的——list 没有.size属性。修复返回二维np.ndarray形状为(N, embedding_dim)# ❌ 错误embedding_list[np.array(item[embedding],dtypenp.float32)foritemindata[data]]returnembedding_list# 返回的是 list# ✅ 正确returnnp.array([np.array(item[embedding],dtypenp.float32)foritemindata[data]])# 返回 shape(len(texts), 4096) 的二维 numpy 数组同时修正类型注解asyncdefsilicon_qwen_embedding_func(texts:List[str])-np.ndarray:问题 6: 缺少存储初始化错误信息AttributeError: __aenter__ # 或 KeyError: history_messages根因LightRAG构造函数只创建对象不会自动初始化底层存储后端。官方文档AGENTS.md明确将此列为最常见错误。修复ragLightRAG(...)awaitrag.initialize_storages()# 必须手动调用try:awaitrag.ainsert(...)awaitrag.aquery(...)finally:awaitrag.finalize_storages()问题 7: 旧数据污染错误信息修复代码后仍然报list object has no attribute size。根因之前错误运行时embedding 返回了 list 而非 ndarray向量数据库NanoVectorDB写入了损坏数据。修复代码后旧数据没有被清理继续触发错误。修复importshutilifos.path.exists(WORKING_DIR):shutil.rmtree(WORKING_DIR)print(已清理旧损坏数据库目录)完整正确代码模板importosimportasyncioimportaiohttpimportnumpyasnpfromtypingimportListfromlightrag.utilsimportwrap_embedding_func_with_attrs# ---------- 配置 ----------DEEPSEEK_API_KEYyour-keyDEEPSEEK_BASE_URLhttps://api.deepseek.com/v1DEEPSEEK_MODEL_NAMEdeepseek-chatSILICONFLOW_API_KEYyour-keySILICONFLOW_BASE_URLhttps://api.siliconflow.cn/v1EMBED_MODEL_NAMEQwen/Qwen3-VL-Embedding-8BEMBED_DIM4096MAX_TOKEN8192WORKING_DIR./lightrag_db# ---------- LLM 函数 (async) ----------asyncdefdeepseek_llm_func(prompt,system_promptNone,history_messagesNone,**kwargs):headers{Authorization:fBearer{DEEPSEEK_API_KEY},Content-Type:application/json}messages[]ifsystem_prompt:messages.append({role:system,content:system_prompt})ifhistory_messages:messages.extend(history_messages)messages.append({role:user,content:prompt})payload{model:DEEPSEEK_MODEL_NAME,messages:messages,temperature:0.1,max_tokens:2048}asyncwithaiohttp.ClientSession()assession:asyncwithsession.post(f{DEEPSEEK_BASE_URL}/chat/completions,headersheaders,jsonpayload,timeoutaiohttp.ClientTimeout(total90))asresp:resp.raise_for_status()dataawaitresp.json()returndata[choices][0][message][content]deepseek_llm_func.funcdeepseek_llm_func deepseek_llm_func.model_nameDEEPSEEK_MODEL_NAME# ---------- Embedding 函数 (async 装饰器 返回 np.ndarray) ----------wrap_embedding_func_with_attrs(embedding_dimEMBED_DIM,max_token_sizeMAX_TOKEN,model_nameEMBED_MODEL_NAME)asyncdefsilicon_qwen_embedding_func(texts:List[str])-np.ndarray:headers{Authorization:fBearer{SILICONFLOW_API_KEY},Content-Type:application/json}payload{model:EMBED_MODEL_NAME,input:texts}asyncwithaiohttp.ClientSession()assession:asyncwithsession.post(f{SILICONFLOW_BASE_URL}/embeddings,headersheaders,jsonpayload,timeoutaiohttp.ClientTimeout(total90))asresp:resp.raise_for_status()dataawaitresp.json()# 关键: 返回二维 np.ndarray 而不是 listreturnnp.array([np.array(item[embedding],dtypenp.float32)foritemindata[data]])# ---------- 主流程 ----------fromlightrag.lightragimportLightRAGasyncdefmain():importshutilifos.path.exists(WORKING_DIR):shutil.rmtree(WORKING_DIR)ragLightRAG(working_dirWORKING_DIR,llm_model_funcdeepseek_llm_func,embedding_funcsilicon_qwen_embedding_func,)awaitrag.initialize_storages()# 必须try:awaitrag.ainsert(你的文档内容...)resultawaitrag.aquery(你的问题?)print(result)finally:awaitrag.finalize_storages()if__name____main__:asyncio.run(main())关键要点速查类别要求LLM 函数async def, 手动加.func/.model_name属性Embedding 函数async def,wrap_embedding_func_with_attrs(...)装饰器Embedding 返回值二维np.ndarray形状(N, dim),不能返回 list存储初始化await rag.initialize_storages()必须手动调用数据清理切换 embedding 模型/修复代码后删除working_dir