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

LangChain中PromptTemplate与RetrievalQA交互及代码疑问

LangChain 基于文档的问答机器人疑问解答

示例代码

template = """Use the following pieces of context to answer the question at the end. 
If you don't know the answer, just say that you don't know, don't try to make up an answer. 
Use three sentences maximum and keep the answer as concise as possible. 
Always say "thanks for asking!" at the end of the answer. 
{context}
Question: {question}
Helpful Answer:"""

QA_CHAIN_PROMPT = PromptTemplate(input_variables=["context", "question"], template=template)

llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)
qa = RetrievalQA.from_chain_type(llm,
                                chain_type='stuff',
                                retriever=vectorstore.as_retriever(),
                                chain_type_kwargs={"prompt": QA_CHAIN_PROMPT})

query = "some query"
print(qa.run(query))

问题1:提示模板中包含{context}和{question}变量,但未直接传入参数,其作用是什么?

  • {context}:是RetrievalQA组件通过指定的retriever从向量数据库(vectorstore)中检索到的与用户查询相关的文档片段,在调用qa.run(query)时会自动填充到模板中,作为LLM回答问题的核心依据。
  • {question}:对应用户传入的查询内容(即代码中的query变量),同样会在run方法执行时自动替换到模板里,让LLM明确需要回应的具体问题。

问题2:chain_type_kwargs={"prompt": QA_CHAIN_PROMPT}的实际功能是什么?

  • chain_type='stuff'指定了RetrievalQA使用的链类型为"stuff"(直接将检索到的所有文档内容整合进提示词),chain_type_kwargs是用于给该特定链类型传递额外配置参数的字典。
  • 这里传入自定义的QA_CHAIN_PROMPT,目的是替换LangChain内置的默认提示模板,让LLM严格按照我们设定的规则(比如限制回答长度、未知问题如实说明、结尾固定话术)生成回答,而非使用默认逻辑。

问题3:若在提示模板中新增参数(如{name}),应如何传入对应的值?

  1. 先修改PromptTemplate的input_variables,新增name变量:
# 假设template已添加{name}占位符
QA_CHAIN_PROMPT = PromptTemplate(input_variables=["context", "question", "name"], template=template)
  1. 调用qa.run()时,以关键字参数的形式动态传入新增变量的值:
print(qa.run(query, name="张三"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 19:07:46