如何通过LangChain表达式语言传递额外参数至检索验证链
解决LangChain中传递多参数到提示词模板的问题
我正在使用LangChain表达式语言构建检索器,目标是创建一个用于AI验证前期交互响应的函数,需要传入原始问题(question)和AI回答(answer)两个参数。目前仅能传递question参数,请问如何修改代码将answer也传入提示词模板?
修改步骤
要实现同时传递question和answer两个参数到提示词模板,需要调整两个核心部分:
- 更新
RunnableParallel结构,添加answer的传递逻辑 - 调整链的调用方式,传入包含两个参数的字典而非单个字符串
修改后的完整代码
from langchain_community.vectorstores import DocArrayInMemorySearch from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_core.runnables import RunnableParallel, RunnablePassthrough from langchain_openai import OpenAIEmbeddings, ChatOpenAI from langchain_community.vectorstores import FAISS import os region = "usa" vector_databases_path = "db" k = 10 model_name = "gpt-4" retriever_chain_type= "stuff" question = "Albuquerque" answer = ' MetroArea State\n0 Albuquerque NM' ####################### 获取检索器 ################## # 设置嵌入模型 embeddings = OpenAIEmbeddings() # 加载数据库嵌入 docsearch = FAISS.load_local(os.path.join(os.getcwd(), vector_databases_path, "MSA_State_faiss_index"), embeddings) # 配置检索器 retriever = docsearch.as_retriever(search_type="similarity", search_kwargs={"k": k}) prompt_template = """ Use the following pieces of context to check the AI's Answer. {context} Job: Your job is to check the MetroArea and State code based on what the AI has returned. Here is the original input: {question} Here is the AI's answer: {answer} Report your answer as a CSV. Where the column names are AI_Correct, AI_Correct: Return TRUE if the AI was correct or FALSE if it is incorrect. Each variable after the comma should be one row. If there is no comma between them then treat input as one row. If you do not know the answer, then return: IDK """ ####################### 初始化LLM ################## llm = ChatOpenAI( model_name=model_name, temperature=0.0 ) prompt = ChatPromptTemplate.from_template(prompt_template) output_parser = StrOutputParser() # 更新RunnableParallel,同时传递question和answer setup_and_retrieval = RunnableParallel( { "context": retriever, "question": lambda x: x["question"], "answer": lambda x: x["answer"] } ) chain = setup_and_retrieval | prompt | llm | output_parser # 传入包含question和answer的字典 final_answer = chain.invoke({"question": question, "answer": answer}) print(final_answer)
关键修改说明
- RunnableParallel调整:用lambda函数从输入字典中提取
question和answer,替代原有的RunnablePassthrough(),确保两个参数都能传递到提示词模板 - invoke调用方式:将单个字符串输入改为包含
question和answer的字典,让链能正确解析并传递参数 - 补充缺失依赖:原代码缺少
OpenAIEmbeddings、ChatOpenAI等类的导入,已补充完整保证代码可运行
内容的提问来源于stack exchange,提问作者Sharif Amlani
相关产品推荐
相关产品推荐

