LangChain RAG管道报错:ChatPromptTemplate缺失变量的解决求助
问题解决:ChatPromptTemplate变量不匹配错误
错误原因
你遇到的错误核心是提示模板要求的变量和RAG管道传递的变量完全不匹配,同时误用了Agent专属的占位符:
- 提示模板里声明需要
input和agent_scratchpad两个变量 - 但你的RAG管道实际传递的是
context和question - 而且这个纯RAG场景根本不需要
agent_scratchpad(这是给智能体保存思考过程用的,普通检索生成用不到)
修正方案
- 调整提示模板:移除
agent_scratchpad占位符,在系统提示中加入{context}变量,用户提示用{question}(和管道传递的变量对齐) - 确保管道的输入映射和提示模板的变量完全对应
修正后的完整代码
from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables import RunnablePassthrough from langchain_core.prompts import ChatPromptTemplate from langchain_weaviate import Weaviate def create_weaviate_new_RAG(client, embeddings, llm, class_name_rich, class_properties_rich, class_text_key): vector_store = Weaviate(client=client, index_name=class_name_rich, text_key=class_text_key, embedding=embeddings, attributes=class_properties_rich, #by_text=False, ) retriever=vector_store.as_retriever( search_type= "mmr", search_kwargs={ "k": 4, "fetch_k": 20, } ) # 关键修改1:移除agent_scratchpad占位符,加入context变量用于检索结果注入 prompt = ChatPromptTemplate.from_messages( [ ("system", "你是一个从文档中检索信息的助手,仅根据提供的上下文回答问题:\n{context}"), ("user", "{question}"), ] ) # 关键修改2:管道变量与提示模板完全对齐 rag_pipe = ( {"context": retriever, "question": RunnablePassthrough()} | prompt | llm | StrOutputParser() ) return rag_pipe rag_pipe = create_weaviate_new_RAG(client, embeddings, llm_chat, class_name, ["chunk_id", "doc_name", "doc_path"], "chunk_text") text = "what is ai policy?" rag_pipe.invoke(text)
补充说明
- 如果坚持想用
input作为用户问题的变量名,只需要把管道里的"question"改成"input",同时提示模板里的{question}换成{input}即可 - 确保所有导入语句完整,原代码可能漏掉了部分必要的导入(符合langchain==0.1.0版本的规范)
内容的提问来源于stack exchange,提问作者Starry Night
相关产品推荐
相关产品推荐

