pg_capability_store.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. """
  2. PostgreSQL capability 存储封装
  3. 用于存储和检索原子能力数据,支持向量检索。
  4. 表名:capability(从 atomic_capability 迁移)
  5. """
  6. import os
  7. import json
  8. import psycopg2
  9. from psycopg2.extras import RealDictCursor
  10. from typing import List, Dict, Optional
  11. from dotenv import load_dotenv
  12. from knowhub.knowhub_db.cascade import cascade_delete
  13. load_dotenv()
  14. # 关联字段子查询
  15. _REL_SUBQUERIES = """
  16. (SELECT COALESCE(json_agg(rc.requirement_id), '[]'::json)
  17. FROM requirement_capability rc WHERE rc.capability_id = capability.id) AS requirement_ids,
  18. (SELECT COALESCE(json_agg(ct.tool_id), '[]'::json)
  19. FROM capability_tool ct WHERE ct.capability_id = capability.id) AS tool_ids,
  20. (SELECT COALESCE(
  21. json_object_agg(ct2.tool_id, ct2.description), '{}'::json)
  22. FROM capability_tool ct2 WHERE ct2.capability_id = capability.id AND ct2.description != '') AS implements,
  23. (SELECT COALESCE(json_agg(ck.knowledge_id), '[]'::json)
  24. FROM capability_knowledge ck WHERE ck.capability_id = capability.id) AS knowledge_ids,
  25. (SELECT COALESCE(json_agg(json_build_object(
  26. 'id', ck2.knowledge_id, 'relation_type', ck2.relation_type
  27. )), '[]'::json)
  28. FROM capability_knowledge ck2 WHERE ck2.capability_id = capability.id) AS knowledge_links,
  29. (SELECT COALESCE(json_agg(cr.resource_id), '[]'::json)
  30. FROM capability_resource cr WHERE cr.capability_id = capability.id) AS resource_ids
  31. """
  32. _BASE_FIELDS = "id, name, criterion, description, version"
  33. _SELECT_FIELDS = f"{_BASE_FIELDS}, {_REL_SUBQUERIES}"
  34. def _normalize_links(data: Dict, links_key: str, ids_key: str, default_type: str):
  35. """两种输入格式统一:{links_key: [{id, relation_type}]} 或 {ids_key: [id]}"""
  36. if links_key in data and data[links_key] is not None:
  37. out = []
  38. for item in data[links_key]:
  39. if isinstance(item, dict):
  40. out.append((item['id'], item.get('relation_type', default_type)))
  41. else:
  42. out.append((item, default_type))
  43. return out
  44. if ids_key in data and data[ids_key] is not None:
  45. return [(i, default_type) for i in data[ids_key]]
  46. return None
  47. class PostgreSQLCapabilityStore:
  48. def __init__(self):
  49. """初始化 PostgreSQL 连接"""
  50. self.conn = psycopg2.connect(
  51. host=os.getenv('KNOWHUB_DB'),
  52. port=int(os.getenv('KNOWHUB_PORT', 5432)),
  53. user=os.getenv('KNOWHUB_USER'),
  54. password=os.getenv('KNOWHUB_PASSWORD'),
  55. database=os.getenv('KNOWHUB_DB_NAME')
  56. )
  57. self.conn.autocommit = True
  58. print(f"[PostgreSQL Capability] 已连接到远程数据库: {os.getenv('KNOWHUB_DB')}")
  59. def _reconnect(self):
  60. self.conn = psycopg2.connect(
  61. host=os.getenv('KNOWHUB_DB'),
  62. port=int(os.getenv('KNOWHUB_PORT', 5432)),
  63. user=os.getenv('KNOWHUB_USER'),
  64. password=os.getenv('KNOWHUB_PASSWORD'),
  65. database=os.getenv('KNOWHUB_DB_NAME')
  66. )
  67. self.conn.autocommit = True
  68. def _ensure_connection(self):
  69. if self.conn.closed != 0:
  70. self._reconnect()
  71. else:
  72. try:
  73. c = self.conn.cursor()
  74. c.execute("SELECT 1")
  75. c.close()
  76. except (psycopg2.OperationalError, psycopg2.InterfaceError):
  77. self._reconnect()
  78. def _get_cursor(self):
  79. self._ensure_connection()
  80. return self.conn.cursor(cursor_factory=RealDictCursor)
  81. def _save_relations(self, cursor, cap_id: str, data: Dict):
  82. """保存 capability 的关联表数据"""
  83. if 'requirement_ids' in data:
  84. cursor.execute("DELETE FROM requirement_capability WHERE capability_id = %s", (cap_id,))
  85. for req_id in data['requirement_ids']:
  86. cursor.execute(
  87. "INSERT INTO requirement_capability (requirement_id, capability_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
  88. (req_id, cap_id))
  89. # tool_ids + implements 合并写入 capability_tool
  90. if 'tool_ids' in data or 'implements' in data:
  91. cursor.execute("DELETE FROM capability_tool WHERE capability_id = %s", (cap_id,))
  92. implements = data.get('implements', {})
  93. tool_ids = set(data.get('tool_ids', []))
  94. # 先写 tool_ids 列表中的(附带 implements 的 description)
  95. for tool_id in tool_ids:
  96. desc = implements.get(tool_id, '')
  97. cursor.execute(
  98. "INSERT INTO capability_tool (capability_id, tool_id, description) VALUES (%s, %s, %s) ON CONFLICT DO NOTHING",
  99. (cap_id, tool_id, desc))
  100. # 再写 implements 中有但 tool_ids 列表没有的
  101. for tool_id, desc in implements.items():
  102. if tool_id not in tool_ids:
  103. cursor.execute(
  104. "INSERT INTO capability_tool (capability_id, tool_id, description) VALUES (%s, %s, %s) ON CONFLICT DO NOTHING",
  105. (cap_id, tool_id, desc))
  106. k_links = _normalize_links(data, 'knowledge_links', 'knowledge_ids', 'related')
  107. if k_links is not None:
  108. cursor.execute("DELETE FROM capability_knowledge WHERE capability_id = %s", (cap_id,))
  109. for kid, rtype in k_links:
  110. cursor.execute(
  111. "INSERT INTO capability_knowledge (capability_id, knowledge_id, relation_type) "
  112. "VALUES (%s, %s, %s) ON CONFLICT DO NOTHING",
  113. (cap_id, kid, rtype))
  114. if 'resource_ids' in data and data['resource_ids'] is not None:
  115. cursor.execute("DELETE FROM capability_resource WHERE capability_id = %s", (cap_id,))
  116. for rid in data['resource_ids']:
  117. cursor.execute(
  118. "INSERT INTO capability_resource (capability_id, resource_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
  119. (cap_id, rid))
  120. def insert_or_update(self, cap: Dict):
  121. """插入或更新原子能力。AnalyticDB beam 表不支持 ON CONFLICT UPDATE 当含 ALTER 新增列,改用 DELETE+INSERT。"""
  122. cursor = self._get_cursor()
  123. try:
  124. cursor.execute("DELETE FROM capability WHERE id = %s", (cap['id'],))
  125. cursor.execute("""
  126. INSERT INTO capability (
  127. id, name, criterion, description, embedding, version
  128. ) VALUES (%s, %s, %s, %s, %s, %s)
  129. """, (
  130. cap['id'],
  131. cap.get('name', ''),
  132. cap.get('criterion', ''),
  133. cap.get('description', ''),
  134. cap.get('embedding'),
  135. cap.get('version', 'v0'),
  136. ))
  137. self._save_relations(cursor, cap['id'], cap)
  138. self.conn.commit()
  139. finally:
  140. cursor.close()
  141. def get_by_id(self, cap_id: str) -> Optional[Dict]:
  142. """根据 ID 获取原子能力"""
  143. cursor = self._get_cursor()
  144. try:
  145. cursor.execute(f"""
  146. SELECT {_SELECT_FIELDS}
  147. FROM capability WHERE id = %s
  148. """, (cap_id,))
  149. result = cursor.fetchone()
  150. return self._format_result(result) if result else None
  151. finally:
  152. cursor.close()
  153. def search(self, query_embedding: List[float], limit: int = 10) -> List[Dict]:
  154. """向量检索原子能力"""
  155. cursor = self._get_cursor()
  156. try:
  157. cursor.execute(f"""
  158. SELECT {_SELECT_FIELDS},
  159. 1 - (embedding <=> %s::real[]) as score
  160. FROM capability
  161. WHERE embedding IS NOT NULL
  162. ORDER BY embedding <=> %s::real[]
  163. LIMIT %s
  164. """, (query_embedding, query_embedding, limit))
  165. results = cursor.fetchall()
  166. return [self._format_result(r) for r in results]
  167. finally:
  168. cursor.close()
  169. def list_all(self, limit: int = 100, offset: int = 0) -> List[Dict]:
  170. """列出原子能力"""
  171. cursor = self._get_cursor()
  172. try:
  173. cursor.execute(f"""
  174. SELECT {_SELECT_FIELDS}
  175. FROM capability
  176. ORDER BY id
  177. LIMIT %s OFFSET %s
  178. """, (limit, offset))
  179. results = cursor.fetchall()
  180. return [self._format_result(r) for r in results]
  181. finally:
  182. cursor.close()
  183. def update(self, cap_id: str, updates: Dict):
  184. """更新原子能力字段"""
  185. cursor = self._get_cursor()
  186. try:
  187. # 分离关联字段
  188. rel_fields = {}
  189. for key in ('requirement_ids', 'implements', 'tool_ids',
  190. 'knowledge_ids', 'knowledge_links', 'resource_ids'):
  191. if key in updates:
  192. rel_fields[key] = updates.pop(key)
  193. if updates:
  194. set_parts = []
  195. params = []
  196. for key, value in updates.items():
  197. set_parts.append(f"{key} = %s")
  198. params.append(value)
  199. params.append(cap_id)
  200. cursor.execute(
  201. f"UPDATE capability SET {', '.join(set_parts)} WHERE id = %s",
  202. params
  203. )
  204. if rel_fields:
  205. self._save_relations(cursor, cap_id, rel_fields)
  206. self.conn.commit()
  207. finally:
  208. cursor.close()
  209. def delete(self, cap_id: str):
  210. """删除原子能力及其关联表记录"""
  211. cursor = self._get_cursor()
  212. try:
  213. cascade_delete(cursor, 'capability', cap_id)
  214. self.conn.commit()
  215. finally:
  216. cursor.close()
  217. def count(self) -> int:
  218. """统计原子能力总数"""
  219. cursor = self._get_cursor()
  220. try:
  221. cursor.execute("SELECT COUNT(*) as count FROM capability")
  222. return cursor.fetchone()['count']
  223. finally:
  224. cursor.close()
  225. def _format_result(self, row: Dict) -> Dict:
  226. """格式化查询结果"""
  227. if not row:
  228. return None
  229. result = dict(row)
  230. for field in ('requirement_ids', 'tool_ids', 'knowledge_ids',
  231. 'resource_ids', 'knowledge_links'):
  232. if field in result and isinstance(result[field], str):
  233. result[field] = json.loads(result[field])
  234. elif field in result and result[field] is None:
  235. result[field] = []
  236. if 'implements' in result:
  237. if isinstance(result['implements'], str):
  238. result['implements'] = json.loads(result['implements'])
  239. elif result['implements'] is None:
  240. result['implements'] = {}
  241. return result
  242. def add_knowledge(self, cap_id: str, knowledge_id: str, relation_type: str = 'related'):
  243. """增量挂接 capability-knowledge 边"""
  244. cursor = self._get_cursor()
  245. try:
  246. cursor.execute(
  247. "INSERT INTO capability_knowledge (capability_id, knowledge_id, relation_type) "
  248. "VALUES (%s, %s, %s) ON CONFLICT DO NOTHING",
  249. (cap_id, knowledge_id, relation_type))
  250. self.conn.commit()
  251. finally:
  252. cursor.close()
  253. def add_resource(self, cap_id: str, resource_id: str):
  254. """增量挂接 capability-resource 边"""
  255. cursor = self._get_cursor()
  256. try:
  257. cursor.execute(
  258. "INSERT INTO capability_resource (capability_id, resource_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
  259. (cap_id, resource_id))
  260. self.conn.commit()
  261. finally:
  262. cursor.close()
  263. def close(self):
  264. if self.conn:
  265. self.conn.close()