pgvector.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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 vanna.exceptions import ValidationError
  10. from vanna.base import VannaBase
  11. from vanna.types import TrainingPlan, TrainingPlanItem
  12. class PG_VectorStore(VannaBase):
  13. def __init__(self, config=None):
  14. if not config or "connection_string" not in config:
  15. raise ValueError(
  16. "A valid 'config' dictionary with a 'connection_string' is required.")
  17. VannaBase.__init__(self, config=config)
  18. if config and "connection_string" in config:
  19. self.connection_string = config.get("connection_string")
  20. self.n_results = config.get("n_results", 10)
  21. if config and "embedding_function" in config:
  22. self.embedding_function = config.get("embedding_function")
  23. else:
  24. raise ValueError("No embedding_function was found.")
  25. # from langchain_huggingface import HuggingFaceEmbeddings
  26. # self.embedding_function = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
  27. self.sql_collection = PGVector(
  28. embeddings=self.embedding_function,
  29. collection_name="sql",
  30. connection=self.connection_string,
  31. )
  32. self.ddl_collection = PGVector(
  33. embeddings=self.embedding_function,
  34. collection_name="ddl",
  35. connection=self.connection_string,
  36. )
  37. self.documentation_collection = PGVector(
  38. embeddings=self.embedding_function,
  39. collection_name="documentation",
  40. connection=self.connection_string,
  41. )
  42. self.error_sql_collection = PGVector(
  43. embeddings=self.embedding_function,
  44. collection_name="error_sql",
  45. connection=self.connection_string,
  46. )
  47. def add_question_sql(self, question: str, sql: str, **kwargs) -> str:
  48. question_sql_json = json.dumps(
  49. {
  50. "question": question,
  51. "sql": sql,
  52. },
  53. ensure_ascii=False,
  54. )
  55. id = str(uuid.uuid4()) + "-sql"
  56. createdat = kwargs.get("createdat")
  57. doc = Document(
  58. page_content=question_sql_json,
  59. metadata={"id": id, "createdat": createdat},
  60. )
  61. self.sql_collection.add_documents([doc], ids=[doc.metadata["id"]])
  62. return id
  63. def add_ddl(self, ddl: str, **kwargs) -> str:
  64. _id = str(uuid.uuid4()) + "-ddl"
  65. doc = Document(
  66. page_content=ddl,
  67. metadata={"id": _id},
  68. )
  69. self.ddl_collection.add_documents([doc], ids=[doc.metadata["id"]])
  70. return _id
  71. def add_documentation(self, documentation: str, **kwargs) -> str:
  72. _id = str(uuid.uuid4()) + "-doc"
  73. doc = Document(
  74. page_content=documentation,
  75. metadata={"id": _id},
  76. )
  77. self.documentation_collection.add_documents([doc], ids=[doc.metadata["id"]])
  78. return _id
  79. def get_collection(self, collection_name):
  80. match collection_name:
  81. case "sql":
  82. return self.sql_collection
  83. case "ddl":
  84. return self.ddl_collection
  85. case "documentation":
  86. return self.documentation_collection
  87. case "error_sql":
  88. return self.error_sql_collection
  89. case _:
  90. raise ValueError("Specified collection does not exist.")
  91. # def get_similar_question_sql(self, question: str) -> list:
  92. # documents = self.sql_collection.similarity_search(query=question, k=self.n_results)
  93. # return [ast.literal_eval(document.page_content) for document in documents]
  94. # 在原来的基础之上,增加相似度的值。
  95. def get_similar_question_sql(self, question: str) -> list:
  96. docs_with_scores = self.sql_collection.similarity_search_with_score(
  97. query=question,
  98. k=self.n_results
  99. )
  100. results = []
  101. for doc, score in docs_with_scores:
  102. # 将文档内容转换为 dict
  103. base = ast.literal_eval(doc.page_content)
  104. # 计算相似度
  105. similarity = round(1 - score, 4)
  106. # 每条记录单独打印
  107. print(f"[DEBUG] SQL Match: {base.get('question', '')} | similarity: {similarity}")
  108. # 添加 similarity 字段
  109. base["similarity"] = similarity
  110. results.append(base)
  111. # 应用阈值过滤
  112. filtered_results = self._apply_score_threshold_filter(
  113. results,
  114. "RESULT_VECTOR_SQL_SCORE_THRESHOLD",
  115. "SQL"
  116. )
  117. return filtered_results
  118. def get_related_ddl(self, question: str, **kwargs) -> list:
  119. docs_with_scores = self.ddl_collection.similarity_search_with_score(
  120. query=question,
  121. k=self.n_results
  122. )
  123. results = []
  124. for doc, score in docs_with_scores:
  125. # 计算相似度
  126. similarity = round(1 - score, 4)
  127. # 每条记录单独打印
  128. print(f"[DEBUG] DDL Match: {doc.page_content[:50]}... | similarity: {similarity}")
  129. # 添加 similarity 字段
  130. result = {
  131. "content": doc.page_content,
  132. "similarity": similarity
  133. }
  134. results.append(result)
  135. # 应用阈值过滤
  136. filtered_results = self._apply_score_threshold_filter(
  137. results,
  138. "RESULT_VECTOR_DDL_SCORE_THRESHOLD",
  139. "DDL"
  140. )
  141. return filtered_results
  142. def get_related_documentation(self, question: str, **kwargs) -> list:
  143. docs_with_scores = self.documentation_collection.similarity_search_with_score(
  144. query=question,
  145. k=self.n_results
  146. )
  147. results = []
  148. for doc, score in docs_with_scores:
  149. # 计算相似度
  150. similarity = round(1 - score, 4)
  151. # 每条记录单独打印
  152. print(f"[DEBUG] Doc Match: {doc.page_content[:50]}... | similarity: {similarity}")
  153. # 添加 similarity 字段
  154. result = {
  155. "content": doc.page_content,
  156. "similarity": similarity
  157. }
  158. results.append(result)
  159. # 应用阈值过滤
  160. filtered_results = self._apply_score_threshold_filter(
  161. results,
  162. "RESULT_VECTOR_DOC_SCORE_THRESHOLD",
  163. "DOC"
  164. )
  165. return filtered_results
  166. def _apply_score_threshold_filter(self, results: list, threshold_config_key: str, result_type: str) -> list:
  167. """
  168. 应用相似度阈值过滤逻辑
  169. Args:
  170. results: 原始结果列表,每个元素包含 similarity 字段
  171. threshold_config_key: 配置中的阈值参数名
  172. result_type: 结果类型(用于日志)
  173. Returns:
  174. 过滤后的结果列表
  175. """
  176. if not results:
  177. return results
  178. # 导入配置
  179. try:
  180. import app_config
  181. enable_threshold = getattr(app_config, 'ENABLE_RESULT_VECTOR_SCORE_THRESHOLD', False)
  182. threshold = getattr(app_config, threshold_config_key, 0.65)
  183. except (ImportError, AttributeError) as e:
  184. print(f"[WARNING] 无法加载阈值配置: {e},使用默认值")
  185. enable_threshold = False
  186. threshold = 0.65
  187. # 如果未启用阈值过滤,直接返回原结果
  188. if not enable_threshold:
  189. print(f"[DEBUG] {result_type} 阈值过滤未启用,返回全部 {len(results)} 条结果")
  190. return results
  191. total_count = len(results)
  192. min_required = max((total_count + 1) // 2, 1)
  193. print(f"[DEBUG] {result_type} 阈值过滤: 总数={total_count}, 阈值={threshold}, 最少保留={min_required}")
  194. # 按相似度降序排序(确保最相似的在前面)
  195. sorted_results = sorted(results, key=lambda x: x.get('similarity', 0), reverse=True)
  196. # 找出满足阈值的结果
  197. above_threshold = [r for r in sorted_results if r.get('similarity', 0) >= threshold]
  198. # 应用过滤逻辑
  199. if len(above_threshold) >= min_required:
  200. # 情况1: 满足阈值的结果数量 >= 最少保留数量,返回满足阈值的结果
  201. filtered_results = above_threshold
  202. filtered_count = len(above_threshold)
  203. print(f"[DEBUG] {result_type} 过滤结果: 保留 {filtered_count} 条, 过滤掉 {total_count - filtered_count} 条 (全部满足阈值)")
  204. else:
  205. # 情况2: 满足阈值的结果数量 < 最少保留数量,强制保留前 min_required 条
  206. filtered_results = sorted_results[:min_required]
  207. above_count = len(above_threshold)
  208. below_count = min_required - above_count
  209. filtered_count = min_required
  210. print(f"[DEBUG] {result_type} 过滤结果: 保留 {filtered_count} 条, 过滤掉 {total_count - filtered_count} 条 (满足阈值: {above_count}, 强制保留: {below_count})")
  211. # 打印过滤详情
  212. for i, result in enumerate(filtered_results):
  213. similarity = result.get('similarity', 0)
  214. status = "✓" if similarity >= threshold else "✗"
  215. print(f"[DEBUG] {result_type} 保留 {i+1}: similarity={similarity} {status}")
  216. return filtered_results
  217. def train(
  218. self,
  219. question: str | None = None,
  220. sql: str | None = None,
  221. ddl: str | None = None,
  222. documentation: str | None = None,
  223. plan: TrainingPlan | None = None,
  224. createdat: str | None = None,
  225. ):
  226. if question and not sql:
  227. raise ValidationError("Please provide a SQL query.")
  228. if documentation:
  229. logging.info(f"Adding documentation: {documentation}")
  230. return self.add_documentation(documentation)
  231. if sql and question:
  232. return self.add_question_sql(question=question, sql=sql, createdat=createdat)
  233. if ddl:
  234. logging.info(f"Adding ddl: {ddl}")
  235. return self.add_ddl(ddl)
  236. if plan:
  237. for item in plan._plan:
  238. if item.item_type == TrainingPlanItem.ITEM_TYPE_DDL:
  239. self.add_ddl(item.item_value)
  240. elif item.item_type == TrainingPlanItem.ITEM_TYPE_IS:
  241. self.add_documentation(item.item_value)
  242. elif item.item_type == TrainingPlanItem.ITEM_TYPE_SQL and item.item_name:
  243. self.add_question_sql(question=item.item_name, sql=item.item_value)
  244. def get_training_data(self, **kwargs) -> pd.DataFrame:
  245. # Establishing the connection
  246. engine = create_engine(self.connection_string)
  247. # Querying the 'langchain_pg_embedding' table
  248. query_embedding = "SELECT cmetadata, document FROM langchain_pg_embedding"
  249. df_embedding = pd.read_sql(query_embedding, engine)
  250. # List to accumulate the processed rows
  251. processed_rows = []
  252. # Process each row in the DataFrame
  253. for _, row in df_embedding.iterrows():
  254. custom_id = row["cmetadata"]["id"]
  255. document = row["document"]
  256. # 处理不同类型的ID后缀
  257. if custom_id.endswith("-doc"):
  258. training_data_type = "documentation"
  259. elif custom_id.endswith("-error_sql"):
  260. training_data_type = "error_sql"
  261. elif custom_id.endswith("-sql"):
  262. training_data_type = "sql"
  263. elif custom_id.endswith("-ddl"):
  264. training_data_type = "ddl"
  265. else:
  266. # If the suffix is not recognized, skip this row
  267. logging.info(f"Skipping row with custom_id {custom_id} due to unrecognized training data type.")
  268. continue
  269. if training_data_type in ["sql", "error_sql"]:
  270. # Convert the document string to a dictionary
  271. try:
  272. doc_dict = ast.literal_eval(document)
  273. question = doc_dict.get("question")
  274. content = doc_dict.get("sql")
  275. except (ValueError, SyntaxError):
  276. logging.info(f"Skipping row with custom_id {custom_id} due to parsing error.")
  277. continue
  278. elif training_data_type in ["documentation", "ddl"]:
  279. question = None # Default value for question
  280. content = document
  281. # Append the processed data to the list
  282. processed_rows.append(
  283. {"id": custom_id, "question": question, "content": content, "training_data_type": training_data_type}
  284. )
  285. # Create a DataFrame from the list of processed rows
  286. df_processed = pd.DataFrame(processed_rows)
  287. return df_processed
  288. def remove_training_data(self, id: str, **kwargs) -> bool:
  289. # Create the database engine
  290. engine = create_engine(self.connection_string)
  291. # SQL DELETE statement
  292. delete_statement = text(
  293. """
  294. DELETE FROM langchain_pg_embedding
  295. WHERE cmetadata ->> 'id' = :id
  296. """
  297. )
  298. # Connect to the database and execute the delete statement
  299. with engine.connect() as connection:
  300. # Start a transaction
  301. with connection.begin() as transaction:
  302. try:
  303. result = connection.execute(delete_statement, {"id": id})
  304. # Commit the transaction if the delete was successful
  305. transaction.commit()
  306. # Check if any row was deleted and return True or False accordingly
  307. return result.rowcount > 0
  308. except Exception as e:
  309. # Rollback the transaction in case of error
  310. logging.error(f"An error occurred: {e}")
  311. transaction.rollback()
  312. return False
  313. def remove_collection(self, collection_name: str) -> bool:
  314. engine = create_engine(self.connection_string)
  315. # Determine the suffix to look for based on the collection name
  316. suffix_map = {"ddl": "ddl", "sql": "sql", "documentation": "doc", "error_sql": "error_sql"}
  317. suffix = suffix_map.get(collection_name)
  318. if not suffix:
  319. logging.info("Invalid collection name. Choose from 'ddl', 'sql', 'documentation', or 'error_sql'.")
  320. return False
  321. # SQL query to delete rows based on the condition
  322. query = text(
  323. f"""
  324. DELETE FROM langchain_pg_embedding
  325. WHERE cmetadata->>'id' LIKE '%{suffix}'
  326. """
  327. )
  328. # Execute the deletion within a transaction block
  329. with engine.connect() as connection:
  330. with connection.begin() as transaction:
  331. try:
  332. result = connection.execute(query)
  333. transaction.commit() # Explicitly commit the transaction
  334. if result.rowcount > 0:
  335. logging.info(
  336. f"Deleted {result.rowcount} rows from "
  337. f"langchain_pg_embedding where collection is {collection_name}."
  338. )
  339. return True
  340. else:
  341. logging.info(f"No rows deleted for collection {collection_name}.")
  342. return False
  343. except Exception as e:
  344. logging.error(f"An error occurred: {e}")
  345. transaction.rollback() # Rollback in case of error
  346. return False
  347. def generate_embedding(self, *args, **kwargs):
  348. pass
  349. # 增加错误SQL的训练和查询功能
  350. # 1. 确保error_sql集合存在
  351. def _ensure_error_sql_collection(self):
  352. """确保error_sql集合存在"""
  353. # 集合已在 __init__ 中初始化,这里只是为了保持方法的一致性
  354. pass
  355. # 2. 将错误的question-sql对存储到error_sql集合中
  356. def train_error_sql(self, question: str, sql: str, **kwargs) -> str:
  357. """
  358. 将错误的question-sql对存储到error_sql集合中
  359. """
  360. # 确保集合存在
  361. self._ensure_error_sql_collection()
  362. # 创建文档内容,格式与现有SQL训练数据一致
  363. question_sql_json = json.dumps(
  364. {
  365. "question": question,
  366. "sql": sql,
  367. "type": "error_sql"
  368. },
  369. ensure_ascii=False,
  370. )
  371. # 生成ID,使用与现有方法一致的格式
  372. id = str(uuid.uuid4()) + "-error_sql"
  373. createdat = kwargs.get("createdat")
  374. # 创建Document对象
  375. doc = Document(
  376. page_content=question_sql_json,
  377. metadata={"id": id, "createdat": createdat},
  378. )
  379. # 添加到error_sql集合
  380. self.error_sql_collection.add_documents([doc], ids=[doc.metadata["id"]])
  381. return id
  382. # 3. 获取相似的错误SQL示例
  383. def get_error_sql_examples(self, question: str, limit: int = 5) -> list:
  384. """
  385. 获取相似的错误SQL示例
  386. """
  387. # 确保集合存在
  388. self._ensure_error_sql_collection()
  389. try:
  390. docs_with_scores = self.error_sql_collection.similarity_search_with_score(
  391. query=question,
  392. k=limit
  393. )
  394. results = []
  395. for doc, score in docs_with_scores:
  396. try:
  397. # 将文档内容转换为 dict,与现有方法保持一致
  398. base = ast.literal_eval(doc.page_content)
  399. # 计算相似度
  400. similarity = round(1 - score, 4)
  401. # 每条记录单独打印
  402. print(f"[DEBUG] Error SQL Match: {base.get('question', '')} | similarity: {similarity}")
  403. # 添加 similarity 字段
  404. base["similarity"] = similarity
  405. results.append(base)
  406. except (ValueError, SyntaxError) as e:
  407. print(f"Error parsing error SQL document: {e}")
  408. continue
  409. return results
  410. except Exception as e:
  411. print(f"Error retrieving error SQL examples: {e}")
  412. return []