pg_capability_store.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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"
  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. """插入或更新原子能力"""
  122. cursor = self._get_cursor()
  123. try:
  124. cursor.execute("""
  125. INSERT INTO capability (
  126. id, name, criterion, description, embedding
  127. ) VALUES (%s, %s, %s, %s, %s)
  128. ON CONFLICT (id) DO UPDATE SET
  129. name = EXCLUDED.name,
  130. criterion = EXCLUDED.criterion,
  131. description = EXCLUDED.description,
  132. embedding = EXCLUDED.embedding
  133. """, (
  134. cap['id'],
  135. cap.get('name', ''),
  136. cap.get('criterion', ''),
  137. cap.get('description', ''),
  138. cap.get('embedding'),
  139. ))
  140. self._save_relations(cursor, cap['id'], cap)
  141. self.conn.commit()
  142. finally:
  143. cursor.close()
  144. def get_by_id(self, cap_id: str) -> Optional[Dict]:
  145. """根据 ID 获取原子能力"""
  146. cursor = self._get_cursor()
  147. try:
  148. cursor.execute(f"""
  149. SELECT {_SELECT_FIELDS}
  150. FROM capability WHERE id = %s
  151. """, (cap_id,))
  152. result = cursor.fetchone()
  153. return self._format_result(result) if result else None
  154. finally:
  155. cursor.close()
  156. def search(self, query_embedding: List[float], limit: int = 10) -> List[Dict]:
  157. """向量检索原子能力"""
  158. cursor = self._get_cursor()
  159. try:
  160. cursor.execute(f"""
  161. SELECT {_SELECT_FIELDS},
  162. 1 - (embedding <=> %s::real[]) as score
  163. FROM capability
  164. WHERE embedding IS NOT NULL
  165. ORDER BY embedding <=> %s::real[]
  166. LIMIT %s
  167. """, (query_embedding, query_embedding, limit))
  168. results = cursor.fetchall()
  169. return [self._format_result(r) for r in results]
  170. finally:
  171. cursor.close()
  172. def list_all(self, limit: int = 100, offset: int = 0) -> List[Dict]:
  173. """列出原子能力"""
  174. cursor = self._get_cursor()
  175. try:
  176. cursor.execute(f"""
  177. SELECT {_SELECT_FIELDS}
  178. FROM capability
  179. ORDER BY id
  180. LIMIT %s OFFSET %s
  181. """, (limit, offset))
  182. results = cursor.fetchall()
  183. return [self._format_result(r) for r in results]
  184. finally:
  185. cursor.close()
  186. def update(self, cap_id: str, updates: Dict):
  187. """更新原子能力字段"""
  188. cursor = self._get_cursor()
  189. try:
  190. # 分离关联字段
  191. rel_fields = {}
  192. for key in ('requirement_ids', 'implements', 'tool_ids',
  193. 'knowledge_ids', 'knowledge_links', 'resource_ids'):
  194. if key in updates:
  195. rel_fields[key] = updates.pop(key)
  196. if updates:
  197. set_parts = []
  198. params = []
  199. for key, value in updates.items():
  200. set_parts.append(f"{key} = %s")
  201. params.append(value)
  202. params.append(cap_id)
  203. cursor.execute(
  204. f"UPDATE capability SET {', '.join(set_parts)} WHERE id = %s",
  205. params
  206. )
  207. if rel_fields:
  208. self._save_relations(cursor, cap_id, rel_fields)
  209. self.conn.commit()
  210. finally:
  211. cursor.close()
  212. def delete(self, cap_id: str):
  213. """删除原子能力及其关联表记录"""
  214. cursor = self._get_cursor()
  215. try:
  216. cascade_delete(cursor, 'capability', cap_id)
  217. self.conn.commit()
  218. finally:
  219. cursor.close()
  220. def count(self) -> int:
  221. """统计原子能力总数"""
  222. cursor = self._get_cursor()
  223. try:
  224. cursor.execute("SELECT COUNT(*) as count FROM capability")
  225. return cursor.fetchone()['count']
  226. finally:
  227. cursor.close()
  228. def _format_result(self, row: Dict) -> Dict:
  229. """格式化查询结果"""
  230. if not row:
  231. return None
  232. result = dict(row)
  233. for field in ('requirement_ids', 'tool_ids', 'knowledge_ids',
  234. 'resource_ids', 'knowledge_links'):
  235. if field in result and isinstance(result[field], str):
  236. result[field] = json.loads(result[field])
  237. elif field in result and result[field] is None:
  238. result[field] = []
  239. if 'implements' in result:
  240. if isinstance(result['implements'], str):
  241. result['implements'] = json.loads(result['implements'])
  242. elif result['implements'] is None:
  243. result['implements'] = {}
  244. return result
  245. def add_knowledge(self, cap_id: str, knowledge_id: str, relation_type: str = 'related'):
  246. """增量挂接 capability-knowledge 边"""
  247. cursor = self._get_cursor()
  248. try:
  249. cursor.execute(
  250. "INSERT INTO capability_knowledge (capability_id, knowledge_id, relation_type) "
  251. "VALUES (%s, %s, %s) ON CONFLICT DO NOTHING",
  252. (cap_id, knowledge_id, relation_type))
  253. self.conn.commit()
  254. finally:
  255. cursor.close()
  256. def add_resource(self, cap_id: str, resource_id: str):
  257. """增量挂接 capability-resource 边"""
  258. cursor = self._get_cursor()
  259. try:
  260. cursor.execute(
  261. "INSERT INTO capability_resource (capability_id, resource_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
  262. (cap_id, resource_id))
  263. self.conn.commit()
  264. finally:
  265. cursor.close()
  266. def close(self):
  267. if self.conn:
  268. self.conn.close()