pgvector.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. import ast
  2. import json
  3. import logging
  4. import uuid
  5. import pandas as pd
  6. from langchain_core.documents import Document
  7. from langchain_postgres.vectorstores import PGVector
  8. from sqlalchemy import create_engine, text
  9. from core.logging import get_vanna_logger
  10. from vanna.exceptions import ValidationError
  11. from vanna.base import VannaBase
  12. from vanna.types import TrainingPlan, TrainingPlanItem
  13. # 导入embedding缓存管理器
  14. from common.embedding_cache_manager import get_embedding_cache_manager
  15. class PG_VectorStore(VannaBase):
  16. def __init__(self, config=None):
  17. if not config or "connection_string" not in config:
  18. raise ValueError(
  19. "A valid 'config' dictionary with a 'connection_string' is required.")
  20. VannaBase.__init__(self, config=config)
  21. # 初始化日志
  22. self.logger = get_vanna_logger("PGVector")
  23. if config and "connection_string" in config:
  24. self.connection_string = config.get("connection_string")
  25. self.n_results = config.get("n_results", 10)
  26. if config and "embedding_function" in config:
  27. self.embedding_function = config.get("embedding_function")
  28. else:
  29. raise ValueError("No embedding_function was found.")
  30. # from langchain_huggingface import HuggingFaceEmbeddings
  31. # self.embedding_function = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
  32. self.sql_collection = PGVector(
  33. embeddings=self.embedding_function,
  34. collection_name="sql",
  35. connection=self.connection_string,
  36. )
  37. self.ddl_collection = PGVector(
  38. embeddings=self.embedding_function,
  39. collection_name="ddl",
  40. connection=self.connection_string,
  41. )
  42. self.documentation_collection = PGVector(
  43. embeddings=self.embedding_function,
  44. collection_name="documentation",
  45. connection=self.connection_string,
  46. )
  47. self.error_sql_collection = PGVector(
  48. embeddings=self.embedding_function,
  49. collection_name="error_sql",
  50. connection=self.connection_string,
  51. )
  52. def add_question_sql(self, question: str, sql: str, **kwargs) -> str:
  53. question_sql_json = json.dumps(
  54. {
  55. "question": question,
  56. "sql": sql,
  57. },
  58. ensure_ascii=False,
  59. )
  60. id = str(uuid.uuid4()) + "-sql"
  61. createdat = kwargs.get("createdat")
  62. doc = Document(
  63. page_content=question_sql_json,
  64. metadata={"id": id, "createdat": createdat},
  65. )
  66. self.sql_collection.add_documents([doc], ids=[doc.metadata["id"]])
  67. return id
  68. def add_ddl(self, ddl: str, **kwargs) -> str:
  69. _id = str(uuid.uuid4()) + "-ddl"
  70. doc = Document(
  71. page_content=ddl,
  72. metadata={"id": _id},
  73. )
  74. self.ddl_collection.add_documents([doc], ids=[doc.metadata["id"]])
  75. return _id
  76. def add_documentation(self, documentation: str, **kwargs) -> str:
  77. _id = str(uuid.uuid4()) + "-doc"
  78. doc = Document(
  79. page_content=documentation,
  80. metadata={"id": _id},
  81. )
  82. self.documentation_collection.add_documents([doc], ids=[doc.metadata["id"]])
  83. return _id
  84. def get_collection(self, collection_name):
  85. match collection_name:
  86. case "sql":
  87. return self.sql_collection
  88. case "ddl":
  89. return self.ddl_collection
  90. case "documentation":
  91. return self.documentation_collection
  92. case "error_sql":
  93. return self.error_sql_collection
  94. case _:
  95. raise ValueError("Specified collection does not exist.")
  96. # def get_similar_question_sql(self, question: str) -> list:
  97. # documents = self.sql_collection.similarity_search(query=question, k=self.n_results)
  98. # return [ast.literal_eval(document.page_content) for document in documents]
  99. # 在原来的基础之上,增加相似度的值。
  100. def get_similar_question_sql(self, question: str) -> list:
  101. # 尝试使用embedding缓存
  102. embedding_cache = get_embedding_cache_manager()
  103. cached_embedding = embedding_cache.get_cached_embedding(question)
  104. if cached_embedding is not None:
  105. # 使用缓存的embedding进行向量搜索
  106. docs_with_scores = self.sql_collection.similarity_search_with_score_by_vector(
  107. embedding=cached_embedding,
  108. k=self.n_results
  109. )
  110. else:
  111. # 执行常规的向量搜索(会自动生成embedding)
  112. docs_with_scores = self.sql_collection.similarity_search_with_score(
  113. query=question,
  114. k=self.n_results
  115. )
  116. # 获取刚生成的embedding并缓存
  117. try:
  118. # 通过embedding_function生成向量并缓存
  119. generated_embedding = self.embedding_function.generate_embedding(question)
  120. if generated_embedding:
  121. embedding_cache.cache_embedding(question, generated_embedding)
  122. except Exception as e:
  123. self.logger.warning(f"缓存embedding失败: {e}")
  124. results = []
  125. for doc, score in docs_with_scores:
  126. # 将文档内容转换为 dict
  127. base = ast.literal_eval(doc.page_content)
  128. # 计算相似度
  129. similarity = round(1 - score, 4)
  130. # 每条记录单独打印
  131. self.logger.debug(f"SQL Match: {base.get('question', '')} | similarity: {similarity}")
  132. # 添加 similarity 字段
  133. base["similarity"] = similarity
  134. results.append(base)
  135. # 检查原始查询结果是否为空
  136. if not results:
  137. self.logger.warning(f"向量查询未找到任何相似的SQL问答对,问题: {question}")
  138. # 应用阈值过滤
  139. filtered_results = self._apply_score_threshold_filter(
  140. results,
  141. "RESULT_VECTOR_SQL_SCORE_THRESHOLD",
  142. "SQL"
  143. )
  144. # 检查过滤后结果是否为空
  145. if results and not filtered_results:
  146. self.logger.warning(f"向量查询找到了 {len(results)} 条SQL问答对,但全部被阈值过滤掉,问题: {question}")
  147. return filtered_results
  148. def get_related_ddl(self, question: str, **kwargs) -> list:
  149. # 尝试使用embedding缓存
  150. embedding_cache = get_embedding_cache_manager()
  151. cached_embedding = embedding_cache.get_cached_embedding(question)
  152. if cached_embedding is not None:
  153. # 使用缓存的embedding进行向量搜索
  154. docs_with_scores = self.ddl_collection.similarity_search_with_score_by_vector(
  155. embedding=cached_embedding,
  156. k=self.n_results
  157. )
  158. else:
  159. # 执行常规的向量搜索(会自动生成embedding)
  160. docs_with_scores = self.ddl_collection.similarity_search_with_score(
  161. query=question,
  162. k=self.n_results
  163. )
  164. # 获取刚生成的embedding并缓存
  165. try:
  166. # 通过embedding_function生成向量并缓存
  167. generated_embedding = self.embedding_function.generate_embedding(question)
  168. if generated_embedding:
  169. embedding_cache.cache_embedding(question, generated_embedding)
  170. except Exception as e:
  171. self.logger.warning(f"缓存embedding失败: {e}")
  172. results = []
  173. for doc, score in docs_with_scores:
  174. # 计算相似度
  175. similarity = round(1 - score, 4)
  176. # 每条记录单独打印
  177. self.logger.debug(f"DDL Match: {doc.page_content[:50]}... | similarity: {similarity}")
  178. # 添加 similarity 字段
  179. result = {
  180. "content": doc.page_content,
  181. "similarity": similarity
  182. }
  183. results.append(result)
  184. # 检查原始查询结果是否为空
  185. if not results:
  186. self.logger.warning(f"向量查询未找到任何相关的DDL表结构,问题: {question}")
  187. # 应用阈值过滤
  188. filtered_results = self._apply_score_threshold_filter(
  189. results,
  190. "RESULT_VECTOR_DDL_SCORE_THRESHOLD",
  191. "DDL"
  192. )
  193. # 检查过滤后结果是否为空
  194. if results and not filtered_results:
  195. self.logger.warning(f"向量查询找到了 {len(results)} 条DDL表结构,但全部被阈值过滤掉,问题: {question}")
  196. return filtered_results
  197. def get_related_documentation(self, question: str, **kwargs) -> list:
  198. # 尝试使用embedding缓存
  199. embedding_cache = get_embedding_cache_manager()
  200. cached_embedding = embedding_cache.get_cached_embedding(question)
  201. if cached_embedding is not None:
  202. # 使用缓存的embedding进行向量搜索
  203. docs_with_scores = self.documentation_collection.similarity_search_with_score_by_vector(
  204. embedding=cached_embedding,
  205. k=self.n_results
  206. )
  207. else:
  208. # 执行常规的向量搜索(会自动生成embedding)
  209. docs_with_scores = self.documentation_collection.similarity_search_with_score(
  210. query=question,
  211. k=self.n_results
  212. )
  213. # 获取刚生成的embedding并缓存
  214. try:
  215. # 通过embedding_function生成向量并缓存
  216. generated_embedding = self.embedding_function.generate_embedding(question)
  217. if generated_embedding:
  218. embedding_cache.cache_embedding(question, generated_embedding)
  219. except Exception as e:
  220. self.logger.warning(f"缓存embedding失败: {e}")
  221. results = []
  222. for doc, score in docs_with_scores:
  223. # 计算相似度
  224. similarity = round(1 - score, 4)
  225. # 每条记录单独打印
  226. self.logger.debug(f"Doc Match: {doc.page_content[:50]}... | similarity: {similarity}")
  227. # 添加 similarity 字段
  228. result = {
  229. "content": doc.page_content,
  230. "similarity": similarity
  231. }
  232. results.append(result)
  233. # 检查原始查询结果是否为空
  234. if not results:
  235. self.logger.warning(f"向量查询未找到任何相关的文档,问题: {question}")
  236. # 应用阈值过滤
  237. filtered_results = self._apply_score_threshold_filter(
  238. results,
  239. "RESULT_VECTOR_DOC_SCORE_THRESHOLD",
  240. "DOC"
  241. )
  242. # 检查过滤后结果是否为空
  243. if results and not filtered_results:
  244. self.logger.warning(f"向量查询找到了 {len(results)} 条文档,但全部被阈值过滤掉,问题: {question}")
  245. return filtered_results
  246. def _apply_score_threshold_filter(self, results: list, threshold_config_key: str, result_type: str) -> list:
  247. """
  248. 应用相似度阈值过滤逻辑
  249. Args:
  250. results: 原始结果列表,每个元素包含 similarity 字段
  251. threshold_config_key: 配置中的阈值参数名
  252. result_type: 结果类型(用于日志)
  253. Returns:
  254. 过滤后的结果列表
  255. """
  256. if not results:
  257. return results
  258. # 导入配置
  259. try:
  260. import app_config
  261. enable_threshold = getattr(app_config, 'ENABLE_RESULT_VECTOR_SCORE_THRESHOLD', False)
  262. threshold = getattr(app_config, threshold_config_key, 0.65)
  263. except (ImportError, AttributeError) as e:
  264. self.logger.warning(f"无法加载阈值配置: {e},使用默认值")
  265. enable_threshold = False
  266. threshold = 0.65
  267. # 如果未启用阈值过滤,直接返回原结果
  268. if not enable_threshold:
  269. self.logger.debug(f"{result_type} 阈值过滤未启用,返回全部 {len(results)} 条结果")
  270. return results
  271. total_count = len(results)
  272. min_required = max((total_count + 1) // 2, 1)
  273. self.logger.debug(f"{result_type} 阈值过滤: 总数={total_count}, 阈值={threshold}, 最少保留={min_required}")
  274. # 按相似度降序排序(确保最相似的在前面)
  275. sorted_results = sorted(results, key=lambda x: x.get('similarity', 0), reverse=True)
  276. # 找出满足阈值的结果
  277. above_threshold = [r for r in sorted_results if r.get('similarity', 0) >= threshold]
  278. # 应用过滤逻辑
  279. if len(above_threshold) >= min_required:
  280. # 情况1: 满足阈值的结果数量 >= 最少保留数量,返回满足阈值的结果
  281. filtered_results = above_threshold
  282. filtered_count = len(above_threshold)
  283. self.logger.debug(f"{result_type} 过滤结果: 保留 {filtered_count} 条, 过滤掉 {total_count - filtered_count} 条 (全部满足阈值)")
  284. else:
  285. # 情况2: 满足阈值的结果数量 < 最少保留数量,强制保留前 min_required 条
  286. filtered_results = sorted_results[:min_required]
  287. above_count = len(above_threshold)
  288. below_count = min_required - above_count
  289. filtered_count = min_required
  290. self.logger.debug(f"{result_type} 过滤结果: 保留 {filtered_count} 条, 过滤掉 {total_count - filtered_count} 条 (满足阈值: {above_count}, 强制保留: {below_count})")
  291. # 打印过滤详情
  292. for i, result in enumerate(filtered_results):
  293. similarity = result.get('similarity', 0)
  294. status = "✓" if similarity >= threshold else "✗"
  295. self.logger.debug(f"{result_type} 保留 {i+1}: similarity={similarity} {status}")
  296. return filtered_results
  297. def _apply_error_sql_threshold_filter(self, results: list) -> list:
  298. """
  299. 应用错误SQL特有的相似度阈值过滤逻辑
  300. 与其他方法不同,错误SQL的过滤逻辑是:
  301. - 只返回相似度高于阈值的结果
  302. - 不设置最低返回数量
  303. - 如果都低于阈值,返回空列表
  304. Args:
  305. results: 原始结果列表,每个元素包含 similarity 字段
  306. Returns:
  307. 过滤后的结果列表
  308. """
  309. if not results:
  310. return results
  311. # 导入配置
  312. try:
  313. import app_config
  314. enable_threshold = getattr(app_config, 'ENABLE_RESULT_VECTOR_SCORE_THRESHOLD', False)
  315. threshold = getattr(app_config, 'RESULT_VECTOR_ERROR_SQL_SCORE_THRESHOLD', 0.5)
  316. except (ImportError, AttributeError) as e:
  317. self.logger.warning(f"无法加载错误SQL阈值配置: {e},使用默认值")
  318. enable_threshold = False
  319. threshold = 0.5
  320. # 如果未启用阈值过滤,直接返回原结果
  321. if not enable_threshold:
  322. self.logger.debug(f"Error SQL 阈值过滤未启用,返回全部 {len(results)} 条结果")
  323. return results
  324. total_count = len(results)
  325. self.logger.debug(f"Error SQL 阈值过滤: 总数={total_count}, 阈值={threshold}")
  326. # 按相似度降序排序(确保最相似的在前面)
  327. sorted_results = sorted(results, key=lambda x: x.get('similarity', 0), reverse=True)
  328. # 只保留满足阈值的结果,不设置最低返回数量
  329. filtered_results = [r for r in sorted_results if r.get('similarity', 0) >= threshold]
  330. filtered_count = len(filtered_results)
  331. filtered_out_count = total_count - filtered_count
  332. if filtered_count > 0:
  333. self.logger.debug(f"Error SQL 过滤结果: 保留 {filtered_count} 条, 过滤掉 {filtered_out_count} 条")
  334. # 打印保留的结果详情
  335. for i, result in enumerate(filtered_results):
  336. similarity = result.get('similarity', 0)
  337. self.logger.debug(f"Error SQL 保留 {i+1}: similarity={similarity} ✓")
  338. else:
  339. self.logger.debug(f"Error SQL 过滤结果: 所有 {total_count} 条结果都低于阈值 {threshold},返回空列表")
  340. return filtered_results
  341. def train(
  342. self,
  343. question: str | None = None,
  344. sql: str | None = None,
  345. ddl: str | None = None,
  346. documentation: str | None = None,
  347. plan: TrainingPlan | None = None,
  348. createdat: str | None = None,
  349. ):
  350. if question and not sql:
  351. raise ValidationError("Please provide a SQL query.")
  352. if documentation:
  353. logging.info(f"Adding documentation: {documentation}")
  354. return self.add_documentation(documentation)
  355. if sql and question:
  356. return self.add_question_sql(question=question, sql=sql, createdat=createdat)
  357. if ddl:
  358. logging.info(f"Adding ddl: {ddl}")
  359. return self.add_ddl(ddl)
  360. if plan:
  361. for item in plan._plan:
  362. if item.item_type == TrainingPlanItem.ITEM_TYPE_DDL:
  363. self.add_ddl(item.item_value)
  364. elif item.item_type == TrainingPlanItem.ITEM_TYPE_IS:
  365. self.add_documentation(item.item_value)
  366. elif item.item_type == TrainingPlanItem.ITEM_TYPE_SQL and item.item_name:
  367. self.add_question_sql(question=item.item_name, sql=item.item_value)
  368. def get_training_data(self, **kwargs) -> pd.DataFrame:
  369. # Establishing the connection
  370. engine = create_engine(self.connection_string)
  371. # Querying the 'langchain_pg_embedding' table
  372. query_embedding = "SELECT cmetadata, document FROM langchain_pg_embedding"
  373. df_embedding = pd.read_sql(query_embedding, engine)
  374. # List to accumulate the processed rows
  375. processed_rows = []
  376. # Process each row in the DataFrame
  377. for _, row in df_embedding.iterrows():
  378. custom_id = row["cmetadata"]["id"]
  379. document = row["document"]
  380. # 处理不同类型的ID后缀
  381. if custom_id.endswith("-doc"):
  382. training_data_type = "documentation"
  383. elif custom_id.endswith("-error_sql"):
  384. training_data_type = "error_sql"
  385. elif custom_id.endswith("-sql"):
  386. training_data_type = "sql"
  387. elif custom_id.endswith("-ddl"):
  388. training_data_type = "ddl"
  389. else:
  390. # If the suffix is not recognized, skip this row
  391. logging.info(f"Skipping row with custom_id {custom_id} due to unrecognized training data type.")
  392. continue
  393. if training_data_type in ["sql", "error_sql"]:
  394. # Convert the document string to a dictionary
  395. try:
  396. doc_dict = ast.literal_eval(document)
  397. question = doc_dict.get("question")
  398. content = doc_dict.get("sql")
  399. except (ValueError, SyntaxError):
  400. logging.info(f"Skipping row with custom_id {custom_id} due to parsing error.")
  401. continue
  402. elif training_data_type in ["documentation", "ddl"]:
  403. question = None # Default value for question
  404. content = document
  405. # Append the processed data to the list
  406. processed_rows.append(
  407. {"id": custom_id, "question": question, "content": content, "training_data_type": training_data_type}
  408. )
  409. # Create a DataFrame from the list of processed rows
  410. df_processed = pd.DataFrame(processed_rows)
  411. return df_processed
  412. def remove_training_data(self, id: str, **kwargs) -> bool:
  413. # Create the database engine
  414. engine = create_engine(self.connection_string)
  415. # SQL DELETE statement
  416. delete_statement = text(
  417. """
  418. DELETE FROM langchain_pg_embedding
  419. WHERE cmetadata ->> 'id' = :id
  420. """
  421. )
  422. # Connect to the database and execute the delete statement
  423. with engine.connect() as connection:
  424. # Start a transaction
  425. with connection.begin() as transaction:
  426. try:
  427. result = connection.execute(delete_statement, {"id": id})
  428. # Commit the transaction if the delete was successful
  429. transaction.commit()
  430. # Check if any row was deleted and return True or False accordingly
  431. return result.rowcount > 0
  432. except Exception as e:
  433. # Rollback the transaction in case of error
  434. logging.error(f"An error occurred: {e}")
  435. transaction.rollback()
  436. return False
  437. def remove_collection(self, collection_name: str) -> bool:
  438. engine = create_engine(self.connection_string)
  439. # Determine the suffix to look for based on the collection name
  440. suffix_map = {"ddl": "ddl", "sql": "sql", "documentation": "doc", "error_sql": "error_sql"}
  441. suffix = suffix_map.get(collection_name)
  442. if not suffix:
  443. logging.info("Invalid collection name. Choose from 'ddl', 'sql', 'documentation', or 'error_sql'.")
  444. return False
  445. # SQL query to delete rows based on the condition
  446. query = text(
  447. f"""
  448. DELETE FROM langchain_pg_embedding
  449. WHERE cmetadata->>'id' LIKE '%{suffix}'
  450. """
  451. )
  452. # Execute the deletion within a transaction block
  453. with engine.connect() as connection:
  454. with connection.begin() as transaction:
  455. try:
  456. result = connection.execute(query)
  457. transaction.commit() # Explicitly commit the transaction
  458. if result.rowcount > 0:
  459. logging.info(
  460. f"Deleted {result.rowcount} rows from "
  461. f"langchain_pg_embedding where collection is {collection_name}."
  462. )
  463. return True
  464. else:
  465. logging.info(f"No rows deleted for collection {collection_name}.")
  466. return False
  467. except Exception as e:
  468. logging.error(f"An error occurred: {e}")
  469. transaction.rollback() # Rollback in case of error
  470. return False
  471. def generate_embedding(self, *args, **kwargs):
  472. pass
  473. # 增加错误SQL的训练和查询功能
  474. # 1. 确保error_sql集合存在
  475. def _ensure_error_sql_collection(self):
  476. """确保error_sql集合存在"""
  477. # 集合已在 __init__ 中初始化,这里只是为了保持方法的一致性
  478. pass
  479. # 2. 将错误的question-sql对存储到error_sql集合中
  480. def train_error_sql(self, question: str, sql: str, **kwargs) -> str:
  481. """
  482. 将错误的question-sql对存储到error_sql集合中
  483. """
  484. # 确保集合存在
  485. self._ensure_error_sql_collection()
  486. # 创建文档内容,格式与现有SQL训练数据一致
  487. question_sql_json = json.dumps(
  488. {
  489. "question": question,
  490. "sql": sql,
  491. "type": "error_sql"
  492. },
  493. ensure_ascii=False,
  494. )
  495. # 生成ID,使用与现有方法一致的格式
  496. id = str(uuid.uuid4()) + "-error_sql"
  497. createdat = kwargs.get("createdat")
  498. # 创建Document对象
  499. doc = Document(
  500. page_content=question_sql_json,
  501. metadata={"id": id, "createdat": createdat},
  502. )
  503. # 添加到error_sql集合
  504. self.error_sql_collection.add_documents([doc], ids=[doc.metadata["id"]])
  505. return id
  506. # 3. 获取相关的错误SQL示例
  507. def get_related_error_sql(self, question: str, **kwargs) -> list:
  508. """
  509. 获取相关的错误SQL示例
  510. """
  511. # 确保集合存在
  512. self._ensure_error_sql_collection()
  513. try:
  514. # 尝试使用embedding缓存
  515. embedding_cache = get_embedding_cache_manager()
  516. cached_embedding = embedding_cache.get_cached_embedding(question)
  517. if cached_embedding is not None:
  518. # 使用缓存的embedding进行向量搜索
  519. docs_with_scores = self.error_sql_collection.similarity_search_with_score_by_vector(
  520. embedding=cached_embedding,
  521. k=self.n_results
  522. )
  523. else:
  524. # 执行常规的向量搜索(会自动生成embedding)
  525. docs_with_scores = self.error_sql_collection.similarity_search_with_score(
  526. query=question,
  527. k=self.n_results
  528. )
  529. # 获取刚生成的embedding并缓存
  530. try:
  531. # 通过embedding_function生成向量并缓存
  532. generated_embedding = self.embedding_function.generate_embedding(question)
  533. if generated_embedding:
  534. embedding_cache.cache_embedding(question, generated_embedding)
  535. except Exception as e:
  536. self.logger.warning(f"缓存embedding失败: {e}")
  537. results = []
  538. for doc, score in docs_with_scores:
  539. try:
  540. # 将文档内容转换为 dict,与现有方法保持一致
  541. base = ast.literal_eval(doc.page_content)
  542. # 计算相似度
  543. similarity = round(1 - score, 4)
  544. # 每条记录单独打印
  545. self.logger.debug(f"Error SQL Match: {base.get('question', '')} | similarity: {similarity}")
  546. # 添加 similarity 字段
  547. base["similarity"] = similarity
  548. results.append(base)
  549. except (ValueError, SyntaxError) as e:
  550. self.logger.error(f"Error parsing error SQL document: {e}")
  551. continue
  552. # 检查原始查询结果是否为空
  553. if not results:
  554. self.logger.warning(f"向量查询未找到任何相关的错误SQL示例,问题: {question}")
  555. # 应用错误SQL特有的阈值过滤逻辑
  556. filtered_results = self._apply_error_sql_threshold_filter(results)
  557. # 检查过滤后结果是否为空
  558. if results and not filtered_results:
  559. self.logger.warning(f"向量查询找到了 {len(results)} 条错误SQL示例,但全部被阈值过滤掉,问题: {question}")
  560. return filtered_results
  561. except Exception as e:
  562. self.logger.error(f"Error retrieving error SQL examples: {e}")
  563. return []