执行查询,失败时自动纠错并重试(Reflection 循环) 流程:SQL生成 → 执行 → [失败] → 错误反馈给LLM → 重新生成 → 最多重试 max_retries 次 Args: question: 用户问题 max_retries: 最大重试次数(默认3次) Returns: { "sql": 最终执行的SQL, "data": 查询结
(self, question: str, max_retries: int = 3)
| 178 | return asyncio.run(coro) |
| 179 | |
| 180 | def query(self, question: str, max_retries: int = 3) -> Dict[str, Any]: |
| 181 | """执行查询,失败时自动纠错并重试(Reflection 循环) |
| 182 | |
| 183 | 流程:SQL生成 → 执行 → [失败] → 错误反馈给LLM → 重新生成 → 最多重试 max_retries 次 |
| 184 | |
| 185 | Args: |
| 186 | question: 用户问题 |
| 187 | max_retries: 最大重试次数(默认3次) |
| 188 | |
| 189 | Returns: |
| 190 | { |
| 191 | "sql": 最终执行的SQL, |
| 192 | "data": 查询结果JSON字符串(成功时), |
| 193 | "error": 错误信息(成功时为None), |
| 194 | "retry_count": 实际重试次数(0表示首次成功) |
| 195 | } |
| 196 | """ |
| 197 | result = { |
| 198 | "sql": None, |
| 199 | "data": None, |
| 200 | "error": None, |
| 201 | "retry_count": 0 |
| 202 | } |
| 203 | |
| 204 | try: |
| 205 | sql = self._generate_sql(question) |
| 206 | result["sql"] = sql |
| 207 | |
| 208 | if not sql: |
| 209 | result["error"] = "未能生成有效的SQL" |
| 210 | return result |
| 211 | |
| 212 | for attempt in range(max_retries): |
| 213 | query_result = self._run_async(self._execute_sql_via_mcp(sql)) |
| 214 | result_data = json.loads(query_result) |
| 215 | |
| 216 | if isinstance(result_data, dict) and "error" in result_data: |
| 217 | error_msg = result_data["error"] |
| 218 | |
| 219 | if attempt < max_retries - 1: |
| 220 | print(f"[SQL纠错] 第{attempt + 1}次执行失败: {error_msg},正在让LLM自动修复...") |
| 221 | sql = self._correct_sql(question, sql, error_msg, attempt + 1) |
| 222 | result["sql"] = sql |
| 223 | result["retry_count"] = attempt + 1 |
| 224 | else: |
| 225 | result["error"] = f"SQL执行失败(已自动重试{attempt}次): {error_msg}" |
| 226 | else: |
| 227 | result["data"] = query_result |
| 228 | if attempt > 0: |
| 229 | print(f"[SQL纠错] 第{attempt}次修复后执行成功") |
| 230 | break |
| 231 | |
| 232 | except Exception as e: |
| 233 | result["error"] = f"查询失败: {str(e)}" |
| 234 | |
| 235 | return result |
| 236 |
nothing calls this directly
no test coverage detected