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

使用Langchain RetrievalQA时出现Missing some input keys: {'query'}错误求助

解决LangChain RetrievalQA输入键不匹配的错误

你遇到的ValueError: Missing some input keys: {'query'}是因为RetrievalQA链默认使用question作为输入参数的键名,但你的代码里prompt模板用了{query},调用时也传了{'query': question},两者不匹配导致的。下面提供两种解决方法:

方案一:统一使用默认的question键

修改prompt模板中的变量名,同时调整调用时的输入键,保持和链的默认要求一致:

from langchain.chains import RetrievalQA
from langchain.prompts import PromptTemplate

# 修改prompt模板,将{query}改为{question}
template = """Given the following context answer the question.
    Context:
    {context}
    ------------------
    Question: {question}
    Answer:"""

QA_CHAIN_PROMPT = PromptTemplate.from_template(template)
qa_chain = RetrievalQA.from_chain_type(
    llm,
    retriever=vectordb.as_retriever(),
    return_source_documents=True,
    chain_type_kwargs={"prompt": QA_CHAIN_PROMPT}
)

question = "What methodology was used in this research paper?"

# 调用时使用question作为输入键
result = qa_chain({'question': question})

# 后续结果查看代码不变
result["result"]
result["source_documents"][0]

方案二:指定RetrievalQA使用query作为输入键

在初始化RetrievalQA时添加input_key参数,明确告诉链接受query作为输入键,这样无需修改prompt和调用代码:

from langchain.chains import RetrievalQA
from langchain.prompts import PromptTemplate

# 保持原prompt模板不变
template = """Given the following context answer the question.
    Context:
    {context}
    ------------------
    Question: {query}
    Answer:"""

QA_CHAIN_PROMPT = PromptTemplate.from_template(template)
qa_chain = RetrievalQA.from_chain_type(
    llm,
    retriever=vectordb.as_retriever(),
    return_source_documents=True,
    chain_type_kwargs={"prompt": QA_CHAIN_PROMPT},
    input_key="query"  # 添加该行指定输入键
)

question = "What methodology was used in this research paper?"

# 调用方式保持不变
result = qa_chain({'query': question})

# 后续结果查看代码不变
result["result"]
result["source_documents"][0]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 15:12:15