搭建面向瑞典建筑师的RAG项目时query_text参数缺失报错求助
问题排查:argparse必填参数报错解决
我是编程初学者,正在搭建面向瑞典建筑师的建筑规则RAG系统,运行代码时遇到报错,尝试过部分方法仍未解决,寻求排查帮助。
代码实现
import argparse from dataclasses import dataclass from langchain.vectorstores.chroma import Chroma from langchain_openai import OpenAIEmbeddings from langchain_community.chat_models import ChatOpenAI from langchain.prompts import ChatPromptTemplate CHROMA_PATH = "chroma" PROMPT_TEMPLATE = """ Answer the question based only on the following context: {context} --- Answer the question based on the above context: {question} """ def main(): # Create CLI. parser = argparse.ArgumentParser() parser.add_argument("query_text", type=str, help="is the word regler used in this text?") args = parser.parse_args() query_text = args.query_text # Prepare the DB. embedding_function = OpenAIEmbeddings() db = Chroma(persist_directory=CHROMA_PATH, embedding_function=embedding_function) # Search the DB. results = db.similarity_search_with_relevance_scores(query_text, k=3) if len(results) == 0 or results[0][1] < 0.7: print(f"Unable to find matching results.") return context_text = "\n\n---\n\n".join([doc.page_content for doc, _score in results]) prompt_template = ChatPromptTemplate.from_template(PROMPT_TEMPLATE) prompt = prompt_template.format(context=context_text, question=query_text) print(prompt) model = ChatOpenAI() response_text = model.predict(prompt) sources = [doc.metadata.get("source", None) for doc, _score in results] formatted_response = f"Response: {response_text}\nSources: {sources}" print(formatted_response) if __name__ == "__main__": main()
报错信息
usage: query_data.py [-h] query_text query_data.py: error: the following arguments are required: query_text
已尝试的操作
- 改用纯英文查询文本,问题未解决
- 尝试通过pip安装argparse库
- 注意到编辑器中代码着色与教程存在差异
解决方案
问题本质
代码中argparse将query_text定义为位置必填参数,运行时必须在命令行传入该参数值,否则会触发报错。
解决方法1:命令行传入参数
运行代码时,在命令行末尾直接添加查询文本,示例:
python query_data.py "is the word regler used in this text?"
解决方法2:修改代码支持可选/交互式输入
如果希望参数可选,或支持手动输入查询内容,可以修改argparse配置,示例:
# 替换原main函数中的argparse部分 def main(): # Create CLI with optional argument parser = argparse.ArgumentParser() parser.add_argument("--query_text", type=str, help="Your query text", default=None) args = parser.parse_args() # 如果未传入参数,交互式获取输入 query_text = args.query_text or input("Please enter your query: ") # 后续代码保持不变...
额外说明
- argparse是Python标准库,无需单独通过pip安装
- 编辑器代码着色差异属于界面显示问题,不影响代码实际运行,可通过调整编辑器主题或安装对应语法插件优化
内容的提问来源于stack exchange,提问作者Klaus Landenburg
相关产品推荐
相关产品推荐

