构建RAG时遇SquadExample类型错误,求创建方法及代码修正
问题分析与修复方案
错误原因
- Prompt类型不匹配:
create_stuff_documents_chain要求传入ChatPromptTemplate类型的prompt,但你传入了普通PromptTemplate(QA_CHAIN_PROMPT),导致类型校验失败,触发SquadExample相关错误。 - 参数冗余与格式错误:
create_retrieval_chain的invoke方法仅需接收{"input": 问题文本}即可,无需重复传入question字段;同时你的系统prompt重复引用{question}变量,存在逻辑冗余。
修正后的代码
from langchain.chains import create_retrieval_chain from langchain.chains.combine_documents import create_stuff_documents_chain from langchain_core.prompts import ChatPromptTemplate # 定义符合要求的ChatPromptTemplate system_prompt = """As a US Census information assistant, answer the question based on the provided context. Context: {context}""" prompt = ChatPromptTemplate.from_messages( [ ("system", system_prompt), ("human", "{question}"), ] ) # 创建问答链与检索链 question_answer_chain = create_stuff_documents_chain(llm, prompt) chain = create_retrieval_chain(vectorstore.as_retriever(), question_answer_chain) # 发起查询(仅需传入input字段) question = "What were the trends in median household income across different states in the United States between 2021 and 2022." result = chain.invoke({"input": question}) # 输出结果 print(result["answer"])
关键说明
- 需确保
llm和vectorstore已完成正确初始化(你的代码未展示该部分,需自行保证配置正常)。 create_stuff_documents_chain会自动将检索到的文档内容注入{context}变量,无需手动处理文档拼接逻辑。- 调用
chain.invoke()时,仅传递input参数即可,链内部会自动将其映射为question变量供prompt使用。
内容的提问来源于stack exchange,提问作者Kavya Sivakumar
相关产品推荐
相关产品推荐

