capability.py 9.1 KB

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