使用Langchain ConversationalRetrievalChain返回源文档时触发输出键数量错误
问题原因
当你设置 return_source_documents=True 后,ConversationalRetrievalChain 的输出会包含两个键:answer 和 source_documents。但 run() 方法的设计逻辑是仅处理单一输出键的链,因此会触发 ValueError。
解决方案
不要使用 run() 方法,改用 invoke()(LangChain v0.1+ 推荐)或 call() 方法,这两个方法会返回完整的输出字典,包含你需要的所有结果。
修改后的代码示例
假设你的原代码类似这样:
from langchain.chains import ConversationalRetrievalChain from langchain.llms import OpenAI from langchain.vectorstores import Chroma # 初始化组件 llm = OpenAI(temperature=0) vectorstore = Chroma(persist_directory="./chroma_db") chain = ConversationalRetrievalChain.from_llm( llm=llm, retriever=vectorstore.as_retriever(), return_source_documents=True ) # 原错误调用方式 # response = chain.run({"question": "你的问题", "chat_history": []})
修改为:
# 使用invoke方法获取完整结果 result = chain.invoke({ "question": "你的问题", "chat_history": [] }) # 提取需要的内容 answer = result["answer"] source_docs = result["source_documents"] # 打印结果 print("回答:", answer) print("源文档:", source_docs)
补充说明
如果你的LangChain版本较低(v0.1之前),可以用 call() 替代 invoke(),用法基本一致:
result = chain.call({ "question": "你的问题", "chat_history": [] })
额外提示
如果出于某些场景必须使用 run() 方法,你需要修改链的输出结构,仅保留 answer 键,但这样会丢失 source_documents,因此不推荐这种做法。
内容的提问来源于stack exchange,提问作者philip hess
相关产品推荐
相关产品推荐

