使用LangChain+GPT-3.5生成MongoDB聚合查询时遇ValueError求助
解决LangChain生成MongoDB聚合查询时的ValueError问题
问题概述
使用LangChain结合GPT-3.5-turbo-0125生成MongoDB聚合查询时,触发ValueError: Missing some input keys: {'\n "_id"'}错误。核心流程是通过PromptTemplate构建提示词,调用LLM生成查询后解析为JSON格式,最终用于MongoDB查询。
报错原因分析
该错误本质是LLM返回的内容不符合标准JSON格式,导致json.loads()解析失败:
- LLM可能返回了多余的文本(如注释、混乱的换行缩进),或生成的聚合查询JSON存在语法缺陷(比如键名前带多余换行空格、缺少闭合符号)。
- 当前结果清洗逻辑仅移除了
db.collectionName.aggregate(前缀,未处理其他格式问题,导致解析时识别到不规范的键名(如带换行空格的"\n "_id"")。
解决方案
1. 优化Prompt,强制返回纯JSON格式
修改提示词,明确要求LLM仅返回聚合管道的JSON数组,不需要包含db.collection.aggregate()包裹,也不能添加任何额外说明文本。
2. 增强结果清洗与校验逻辑
对LLM返回的文本做更严格的清洗,移除所有非JSON字符,处理多余的换行和空格,确保输入json.loads()的是标准JSON字符串。
3. 添加异常处理
捕获JSON解析异常,便于调试返回内容的格式问题。
修正后的代码示例
llm_openai = ChatOpenAI(openai_api_key=OPEN_AI_KEY, model='gpt-3.5-turbo-0125') table_schema = ConfigData.TABLE_SCHEMA schema_description = ConfigData.SCHEMA_DESCRIPTION json_ex_1 = ConfigData.FEW_SHOT_EXAMPLE_1 json_ex_string = json.dumps(json_ex_1) # 优化后的Prompt,明确要求返回纯JSON数组 prompt_template_for_creating_query = """ You are an expert in crafting MongoDB aggregation pipelines with 10 years of experience. I will provide you with the table schema and schema description. Your task is to generate a valid MongoDB aggregation pipeline (as a JSON array) based on the user's question. Table schema:{table_schema} Schema Description: {schema_description} Example: Input: Find movies by Quentin Tarantino and include a count of how many actors are in each movie Output: {json_ex_string_1} Important Rules: - ONLY return the JSON array of the aggregation pipeline, no other text. - Do NOT include `db.collection.aggregate()` or any extra explanations. - Ensure the JSON is valid, with proper syntax and no extra whitespace/line breaks inside keys/values. Input: {user_question} """ query_creation_prompt = PromptTemplate( template=prompt_template_for_creating_query, input_variables=["user_question", "json_ex_string_1", "table_schema", "schema_description"], ) llmchain = LLMChain(llm=llm_openai, prompt=query_creation_prompt, verbose=True) def get_query(user_question): response = llmchain.invoke({ "user_question": user_question, "json_ex_string_1": json_ex_string, "table_schema": table_schema, "schema_description": schema_description }) response_text = response['text'].strip() # 移除可能存在的代码块标记 response_text = response_text.replace("```json", "").replace("```", "").strip() try: # 尝试解析JSON return json.loads(response_text) except json.JSONDecodeError as e: print(f"JSON解析错误: {e}") print(f"返回内容: {response_text}") # 可根据情况返回默认值或抛出异常 raise client = pymongo.MongoClient(ConfigData.MONGO_DB_URI) db = client[ConfigData.DB_NAME] collection_name = db[ConfigData.COLLECTION_NAME] query_1 = get_query(user_question="when InnovateTech Solutions founded?")
关键修改点说明
- Prompt优化:明确要求只返回聚合管道的JSON数组,禁止多余内容,同时将table_schema和schema_description作为变量传入(原代码直接拼接字符串可能导致格式混乱)。
- 结果清洗:移除代码块标记,去除首尾空格,确保输入JSON解析的文本干净。
- 异常处理:捕获JSON解析错误,打印错误信息和返回内容,方便定位问题。
内容的提问来源于stack exchange,提问作者Zakariya Mansuri
相关产品推荐
相关产品推荐

