server.py 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624
  1. """
  2. KnowHub Server
  3. Agent 工具使用经验的共享平台。
  4. FastAPI + Milvus Lite(知识)+ SQLite(资源),单文件部署。
  5. """
  6. import os
  7. import re
  8. import json
  9. import asyncio
  10. import base64
  11. import time
  12. import uuid
  13. from contextlib import asynccontextmanager
  14. from datetime import datetime, timezone
  15. from typing import Optional, List, Dict
  16. from pathlib import Path
  17. import httpx
  18. from cryptography.hazmat.primitives.ciphers.aead import AESGCM
  19. from fastapi import FastAPI, HTTPException, Query, Header, Body, BackgroundTasks, Request
  20. from fastapi.responses import HTMLResponse, FileResponse
  21. from fastapi.staticfiles import StaticFiles
  22. from pydantic import BaseModel, Field
  23. # 导入 LLM 调用(需要 agent 模块在 Python path 中)
  24. import sys
  25. sys.path.insert(0, str(Path(__file__).parent.parent))
  26. # 加载环境变量
  27. from dotenv import load_dotenv
  28. load_dotenv(Path(__file__).parent.parent / ".env")
  29. from agent.llm import create_openrouter_llm_call, create_qwen_llm_call
  30. from knowhub.kb_manage_prompts import (
  31. DEDUP_RELATION_PROMPT,
  32. TOOL_ANALYSIS_PROMPT,
  33. RERANK_PROMPT_TEMPLATE,
  34. KNOWLEDGE_EVOLVE_PROMPT_TEMPLATE,
  35. KNOWLEDGE_SLIM_PROMPT_TEMPLATE,
  36. MESSAGE_EXTRACT_PROMPT_TEMPLATE,
  37. )
  38. _dedup_llm = create_openrouter_llm_call(model="google/gemini-2.5-flash-lite")
  39. _tool_analysis_llm = create_qwen_llm_call(model="qwen3.5-plus")
  40. # 导入向量存储和 embedding
  41. from knowhub.knowhub_db.pg_store import PostgreSQLStore
  42. from knowhub.knowhub_db.pg_resource_store import PostgreSQLResourceStore
  43. from knowhub.knowhub_db.pg_tool_store import PostgreSQLToolStore
  44. from knowhub.knowhub_db.pg_capability_store import PostgreSQLCapabilityStore
  45. from knowhub.knowhub_db.pg_requirement_store import PostgreSQLRequirementStore
  46. from knowhub.knowhub_db.pg_strategy_store import PostgreSQLStrategyStore
  47. from knowhub.embeddings import get_embedding, get_embeddings_batch
  48. BRAND_NAME = os.getenv("BRAND_NAME", "KnowHub")
  49. BRAND_API_ENV = os.getenv("BRAND_API_ENV", "KNOWHUB_API")
  50. BRAND_DB = os.getenv("BRAND_DB", "knowhub.db")
  51. # 组织密钥配置(格式:org1:key1_base64,org2:key2_base64)
  52. ORG_KEYS_RAW = os.getenv("ORG_KEYS", "")
  53. ORG_KEYS = {}
  54. if ORG_KEYS_RAW:
  55. for pair in ORG_KEYS_RAW.split(","):
  56. if ":" in pair:
  57. org, key_b64 = pair.split(":", 1)
  58. ORG_KEYS[org.strip()] = key_b64.strip()
  59. DB_PATH = Path(__file__).parent / BRAND_DB
  60. # 全局 PostgreSQL 存储实例
  61. pg_store: Optional[PostgreSQLStore] = None
  62. pg_resource_store: Optional[PostgreSQLResourceStore] = None
  63. pg_tool_store: Optional[PostgreSQLToolStore] = None
  64. pg_capability_store: Optional[PostgreSQLCapabilityStore] = None
  65. pg_requirement_store: Optional[PostgreSQLRequirementStore] = None
  66. pg_strategy_store: Optional[PostgreSQLStrategyStore] = None
  67. # --- 加密/解密 ---
  68. def get_org_key(resource_id: str) -> Optional[bytes]:
  69. """从content_id提取组织前缀,返回对应密钥"""
  70. if "/" in resource_id:
  71. org = resource_id.split("/")[0]
  72. if org in ORG_KEYS:
  73. return base64.b64decode(ORG_KEYS[org])
  74. return None
  75. def encrypt_content(resource_id: str, plaintext: str) -> str:
  76. """加密内容,返回格式:encrypted:AES256-GCM:{base64_data}"""
  77. if not plaintext:
  78. return ""
  79. key = get_org_key(resource_id)
  80. if not key:
  81. # 没有配置密钥,明文存储(不推荐)
  82. return plaintext
  83. aesgcm = AESGCM(key)
  84. nonce = os.urandom(12) # 96-bit nonce
  85. ciphertext = aesgcm.encrypt(nonce, plaintext.encode("utf-8"), None)
  86. # 组合 nonce + ciphertext
  87. encrypted_data = nonce + ciphertext
  88. encoded = base64.b64encode(encrypted_data).decode("ascii")
  89. return f"encrypted:AES256-GCM:{encoded}"
  90. def decrypt_content(resource_id: str, encrypted_text: str, provided_key: Optional[str] = None) -> str:
  91. """解密内容,如果没有提供密钥或密钥错误,返回[ENCRYPTED]"""
  92. if not encrypted_text:
  93. return ""
  94. if not encrypted_text.startswith("encrypted:AES256-GCM:"):
  95. # 未加密的内容,直接返回
  96. return encrypted_text
  97. # 提取加密数据
  98. encoded = encrypted_text.split(":", 2)[2]
  99. encrypted_data = base64.b64decode(encoded)
  100. nonce = encrypted_data[:12]
  101. ciphertext = encrypted_data[12:]
  102. # 获取密钥
  103. key = None
  104. if provided_key:
  105. # 使用提供的密钥
  106. try:
  107. key = base64.b64decode(provided_key)
  108. except Exception:
  109. return "[ENCRYPTED]"
  110. else:
  111. # 从配置中获取
  112. key = get_org_key(resource_id)
  113. if not key:
  114. return "[ENCRYPTED]"
  115. try:
  116. aesgcm = AESGCM(key)
  117. plaintext = aesgcm.decrypt(nonce, ciphertext, None)
  118. return plaintext.decode("utf-8")
  119. except Exception:
  120. return "[ENCRYPTED]"
  121. def to_serializable(data):
  122. """通用序列化工具:把任意 Python 对象转换为 JSON 可序列化的原生类型"""
  123. # 基本类型直接返回
  124. if data is None or isinstance(data, (str, int, float, bool)):
  125. return data
  126. # 字典类型递归处理
  127. if isinstance(data, dict):
  128. return {k: to_serializable(v) for k, v in data.items()}
  129. # 列表/元组类型递归处理
  130. if isinstance(data, (list, tuple)):
  131. return [to_serializable(item) for item in data]
  132. # 尝试转换为字典(对于有 to_dict 方法的对象)
  133. if hasattr(data, 'to_dict') and callable(getattr(data, 'to_dict')):
  134. try:
  135. return to_serializable(data.to_dict())
  136. except:
  137. pass
  138. # 尝试转换为列表(对于可迭代对象,如 RepeatedScalarContainer)
  139. if hasattr(data, '__iter__') and not isinstance(data, (str, bytes, dict)):
  140. try:
  141. # 强制转换为列表并递归处理
  142. result = []
  143. for item in data:
  144. result.append(to_serializable(item))
  145. return result
  146. except:
  147. pass
  148. # 尝试获取对象的属性字典
  149. if hasattr(data, '__dict__'):
  150. try:
  151. return to_serializable(vars(data))
  152. except:
  153. pass
  154. # 最后的 fallback:对于无法处理的类型,返回 None 而不是字符串表示
  155. # 这样可以避免产生无法序列化的字符串
  156. return None
  157. # --- Models ---
  158. class ResourceIn(BaseModel):
  159. id: str
  160. title: str = ""
  161. body: str
  162. secure_body: str = ""
  163. content_type: str = "text" # text|code|credential|cookie
  164. metadata: dict = {}
  165. sort_order: int = 0
  166. submitted_by: str = ""
  167. class ResourcePatchIn(BaseModel):
  168. """PATCH /api/resource/{id} 请求体"""
  169. title: Optional[str] = None
  170. body: Optional[str] = None
  171. secure_body: Optional[str] = None
  172. content_type: Optional[str] = None
  173. metadata: Optional[dict] = None
  174. class PostBatchRequest(BaseModel):
  175. post_ids: List[str] = Field(default_factory=list)
  176. # Knowledge Models
  177. class KnowledgeIn(BaseModel):
  178. task: str
  179. content: str
  180. types: list[str] = ["strategy"]
  181. tags: dict = {}
  182. scopes: list[str] = ["org:cybertogether"]
  183. owner: str = ""
  184. message_id: str = ""
  185. resource_ids: list[str] = []
  186. source: dict = {} # {name, category, urls, agent_id, submitted_by, timestamp}
  187. eval: dict = {} # {score, helpful, harmful, confidence}
  188. capability_ids: list[str] = []
  189. tool_ids: list[str] = []
  190. class KnowledgeOut(BaseModel):
  191. id: str
  192. message_id: str
  193. types: list[str]
  194. task: str
  195. tags: dict
  196. scopes: list[str]
  197. owner: str
  198. content: str
  199. source: dict
  200. eval: dict
  201. created_at: str
  202. updated_at: str
  203. class KnowledgeUpdateIn(BaseModel):
  204. add_helpful_case: Optional[dict] = None
  205. add_harmful_case: Optional[dict] = None
  206. update_score: Optional[int] = Field(default=None, ge=1, le=5)
  207. evolve_feedback: Optional[str] = None
  208. class KnowledgePatchIn(BaseModel):
  209. """PATCH /api/knowledge/{id} 请求体(直接字段编辑)"""
  210. task: Optional[str] = None
  211. content: Optional[str] = None
  212. types: Optional[list[str]] = None
  213. tags: Optional[dict] = None
  214. scopes: Optional[list[str]] = None
  215. owner: Optional[str] = None
  216. capability_ids: Optional[list[str]] = None
  217. tool_ids: Optional[list[str]] = None
  218. class MessageExtractIn(BaseModel):
  219. """POST /api/extract 请求体(消息历史提取)"""
  220. messages: list[dict] # [{role: str, content: str}, ...]
  221. agent_id: str = "unknown"
  222. submitted_by: str # 必填,作为 owner
  223. session_key: str = ""
  224. class KnowledgeBatchUpdateIn(BaseModel):
  225. feedback_list: list[dict]
  226. class KnowledgeVerifyIn(BaseModel):
  227. action: str # "approve" | "reject"
  228. verified_by: str = "user"
  229. class KnowledgeBatchVerifyIn(BaseModel):
  230. knowledge_ids: List[str]
  231. action: str # "approve"
  232. verified_by: str
  233. class KnowledgeSearchResponse(BaseModel):
  234. results: list[dict]
  235. count: int
  236. # --- Tool Models ---
  237. class ToolIn(BaseModel):
  238. id: str
  239. name: str = ""
  240. version: Optional[str] = None
  241. introduction: str = ""
  242. tutorial: str = ""
  243. input: dict | str = ""
  244. output: dict | str = ""
  245. status: str = "未接入"
  246. capability_ids: list[str] = []
  247. knowledge_ids: list[str] = []
  248. provider_ids: list[str] = []
  249. class ToolPatchIn(BaseModel):
  250. name: Optional[str] = None
  251. version: Optional[str] = None
  252. introduction: Optional[str] = None
  253. tutorial: Optional[str] = None
  254. input: Optional[dict | str] = None
  255. output: Optional[dict | str] = None
  256. status: Optional[str] = None
  257. capability_ids: Optional[list[str]] = None
  258. knowledge_ids: Optional[list[str]] = None
  259. provider_ids: Optional[list[str]] = None
  260. # --- Capability Models ---
  261. class CapabilityIn(BaseModel):
  262. id: str
  263. name: str = ""
  264. criterion: str = ""
  265. description: str = ""
  266. requirement_ids: list[str] = []
  267. implements: dict = {}
  268. tool_ids: list[str] = []
  269. knowledge_ids: list[str] = []
  270. class CapabilityPatchIn(BaseModel):
  271. name: Optional[str] = None
  272. criterion: Optional[str] = None
  273. description: Optional[str] = None
  274. requirement_ids: Optional[list[str]] = None
  275. implements: Optional[dict] = None
  276. tool_ids: Optional[list[str]] = None
  277. knowledge_ids: Optional[list[str]] = None
  278. # --- Requirement Models ---
  279. class RequirementIn(BaseModel):
  280. id: str
  281. description: str = ""
  282. capability_ids: list[str] = []
  283. knowledge_ids: list[str] = []
  284. source_nodes: list[dict] = []
  285. status: str = "未满足"
  286. match_result: str = ""
  287. class RequirementPatchIn(BaseModel):
  288. description: Optional[str] = None
  289. capability_ids: Optional[list[str]] = None
  290. knowledge_ids: Optional[list[str]] = None
  291. source_nodes: Optional[list[dict]] = None
  292. status: Optional[str] = None
  293. match_result: Optional[str] = None
  294. # --- Strategy Models ---
  295. class StrategyIn(BaseModel):
  296. id: str
  297. name: str = ""
  298. description: str = ""
  299. body: str = ""
  300. status: str = "draft"
  301. version: str = "v0"
  302. capability_ids: list[str] = []
  303. knowledge_ids: list[str] = []
  304. resource_ids: list[str] = []
  305. requirement_ids: list[str] = []
  306. class StrategyPatchIn(BaseModel):
  307. name: Optional[str] = None
  308. description: Optional[str] = None
  309. body: Optional[str] = None
  310. status: Optional[str] = None
  311. version: Optional[str] = None
  312. capability_ids: Optional[list[str]] = None
  313. knowledge_ids: Optional[list[str]] = None
  314. resource_ids: Optional[list[str]] = None
  315. requirement_ids: Optional[list[str]] = None
  316. class ResourceNode(BaseModel):
  317. id: str
  318. title: str
  319. class ResourceOut(BaseModel):
  320. id: str
  321. title: str
  322. body: str
  323. secure_body: str = ""
  324. content_type: str = "text"
  325. metadata: dict = {}
  326. images: list[str] = []
  327. toc: Optional[ResourceNode] = None
  328. children: list[ResourceNode]
  329. prev: Optional[ResourceNode] = None
  330. next: Optional[ResourceNode] = None
  331. # --- Dedup: Globals & Prompt ---
  332. knowledge_processor: Optional["KnowledgeProcessor"] = None
  333. # --- Dedup: RelationCache ---
  334. class RelationCache:
  335. """关系缓存,存储在内存中"""
  336. def __init__(self):
  337. self._cache: Dict[str, List[str]] = {}
  338. def load(self) -> dict:
  339. return self._cache
  340. def save(self, cache: dict):
  341. self._cache = cache
  342. def add_relation(self, relation_type: str, knowledge_id: str):
  343. if relation_type not in self._cache:
  344. self._cache[relation_type] = []
  345. if knowledge_id not in self._cache[relation_type]:
  346. self._cache[relation_type].append(knowledge_id)
  347. # --- Dedup: KnowledgeProcessor ---
  348. class KnowledgeProcessor:
  349. def __init__(self):
  350. self._lock = asyncio.Lock()
  351. self._relation_cache = RelationCache()
  352. async def process_pending(self):
  353. """持续处理 pending 和 dedup_passed 知识直到队列为空,有锁防并发"""
  354. if self._lock.locked():
  355. return
  356. async with self._lock:
  357. # 第一阶段:处理 pending(去重)
  358. while True:
  359. try:
  360. pending = pg_store.query('status == "pending"', limit=50)
  361. except Exception as e:
  362. print(f"[KnowledgeProcessor] 查询 pending 失败: {e}")
  363. break
  364. if not pending:
  365. break
  366. for knowledge in pending:
  367. await self._process_one(knowledge)
  368. # 第二阶段:处理 dedup_passed(工具关联)
  369. while True:
  370. try:
  371. dedup_passed = pg_store.query('status == "dedup_passed"', limit=50)
  372. except Exception as e:
  373. print(f"[KnowledgeProcessor] 查询 dedup_passed 失败: {e}")
  374. break
  375. if not dedup_passed:
  376. break
  377. for knowledge in dedup_passed:
  378. await self._analyze_tool_relation(knowledge)
  379. async def _process_one(self, knowledge: dict):
  380. kid = knowledge["id"]
  381. now = int(time.time())
  382. # 乐观锁:pending → processing(时间戳存秒级)
  383. try:
  384. pg_store.update(kid, {"status": "processing", "updated_at": now})
  385. except Exception as e:
  386. print(f"[KnowledgeProcessor] 锁定 {kid} 失败: {e}")
  387. return
  388. try:
  389. # 向量召回 top-10(只召回 approved/checked)
  390. embedding = knowledge.get("task_embedding") or knowledge.get("embedding")
  391. if not embedding:
  392. embedding = await get_embedding(knowledge["task"])
  393. candidates = pg_store.search(
  394. query_embedding=embedding,
  395. filters='(status == "approved" or status == "checked")',
  396. limit=10
  397. )
  398. candidates = [c for c in candidates if c["id"] != kid]
  399. # 只保留相似度 >= 0.75 的候选,低于阈值的 task 语义差异太大,直接视为 none
  400. candidates = [c for c in candidates if c.get("score", 0) >= 0.75]
  401. if not candidates:
  402. pg_store.update(kid, {"status": "dedup_passed", "updated_at": now})
  403. return
  404. llm_result = await self._llm_judge_relations(knowledge, candidates)
  405. await self._apply_decision(knowledge, llm_result)
  406. except Exception as e:
  407. print(f"[KnowledgeProcessor] 处理 {kid} 失败: {e},回退到 pending")
  408. try:
  409. pg_store.update(kid, {"status": "pending", "updated_at": int(time.time())})
  410. except Exception:
  411. pass
  412. async def _llm_judge_relations(self, new_knowledge: dict, candidates: list) -> dict:
  413. existing_list = "\n".join([
  414. f"[{i+1}] ID: {c['id']} | Task: {c['task']} | Content: {c['content'][:300]}"
  415. for i, c in enumerate(candidates)
  416. ])
  417. prompt = DEDUP_RELATION_PROMPT.format(
  418. new_task=new_knowledge["task"],
  419. new_content=new_knowledge["content"],
  420. existing_list=existing_list
  421. )
  422. for attempt in range(3):
  423. try:
  424. response = await _dedup_llm(
  425. messages=[{"role": "user", "content": prompt}],
  426. )
  427. content = response.get("content", "").strip()
  428. # 清理 markdown 代码块
  429. if "```" in content:
  430. parts = content.split("```")
  431. for part in parts:
  432. part = part.strip()
  433. if part.startswith("json"):
  434. part = part[4:].strip()
  435. try:
  436. result = json.loads(part)
  437. if "final_decision" in result:
  438. content = part
  439. break
  440. except Exception:
  441. continue
  442. result = json.loads(content)
  443. assert result.get("final_decision") in ("approved", "rejected")
  444. return result
  445. except Exception as e:
  446. print(f"[LLM Judge] 第{attempt+1}次失败: {e}")
  447. if attempt < 2:
  448. await asyncio.sleep(1)
  449. return {"final_decision": "approved", "relations": []}
  450. async def _apply_decision(self, new_knowledge: dict, llm_result: dict):
  451. kid = new_knowledge["id"]
  452. final_decision = llm_result.get("final_decision", "approved")
  453. relations = llm_result.get("relations", [])
  454. now = int(time.time())
  455. # 强制规则:如果存在 duplicate 或 subset 关系,必须 rejected
  456. if any(rel.get("type") in ("duplicate", "subset") for rel in relations):
  457. final_decision = "rejected"
  458. if final_decision == "rejected":
  459. # 记录 rejected 知识的关系到 knowledge_relation 表
  460. for rel in relations:
  461. old_id = rel.get("old_id")
  462. rel_type = rel.get("type", "none")
  463. if old_id and rel_type != "none":
  464. pg_store.add_relation(kid, old_id, rel_type)
  465. if rel_type in ("duplicate", "subset") and old_id:
  466. try:
  467. old = pg_store.get_by_id(old_id)
  468. if not old:
  469. continue
  470. eval_data = old.get("eval") or {}
  471. eval_data["helpful"] = eval_data.get("helpful", 0) + 1
  472. helpful_history = eval_data.get("helpful_history") or []
  473. helpful_history.append({
  474. "source": "dedup",
  475. "related_id": kid,
  476. "relation_type": rel_type,
  477. "timestamp": now
  478. })
  479. eval_data["helpful_history"] = helpful_history
  480. pg_store.update(old_id, {"eval": eval_data, "updated_at": now})
  481. except Exception as e:
  482. print(f"[Apply Decision] 更新旧知识 {old_id} helpful 失败: {e}")
  483. pg_store.update(kid, {"status": "rejected", "updated_at": now})
  484. else:
  485. for rel in relations:
  486. rel_type = rel.get("type", "none")
  487. reverse_type = rel.get("reverse_type", "none")
  488. old_id = rel.get("old_id")
  489. if not old_id or rel_type == "none":
  490. continue
  491. pg_store.add_relation(kid, old_id, rel_type)
  492. self._relation_cache.add_relation(rel_type, kid)
  493. self._relation_cache.add_relation(rel_type, old_id)
  494. if reverse_type and reverse_type != "none":
  495. try:
  496. pg_store.add_relation(old_id, kid, reverse_type)
  497. self._relation_cache.add_relation(reverse_type, old_id)
  498. self._relation_cache.add_relation(reverse_type, kid)
  499. except Exception as e:
  500. print(f"[Apply Decision] 写入反向关系 {old_id} 失败: {e}")
  501. pg_store.update(kid, {
  502. "status": "dedup_passed",
  503. "updated_at": now
  504. })
  505. async def _llm_analyze_tools(self, knowledge: dict) -> dict:
  506. """使用 LLM 分析知识中涉及的工具(复用迁移脚本逻辑)"""
  507. task = (knowledge.get("task") or "")[:600]
  508. content = (knowledge.get("content") or "")[:1200]
  509. prompt = TOOL_ANALYSIS_PROMPT.format(task=task, content=content)
  510. try:
  511. response = await _tool_analysis_llm(
  512. messages=[{"role": "user", "content": prompt}],
  513. max_tokens=2048,
  514. temperature=0.1,
  515. )
  516. raw = (response.get("content") or "").strip()
  517. if raw.startswith("```"):
  518. lines = raw.split("\n")
  519. inner = []
  520. in_block = False
  521. for line in lines:
  522. if line.startswith("```"):
  523. in_block = not in_block
  524. continue
  525. if in_block:
  526. inner.append(line)
  527. raw = "\n".join(inner).strip()
  528. return json.loads(raw)
  529. except Exception as e:
  530. print(f"[Tool Analysis LLM] 调用失败: {e}")
  531. raise
  532. async def _create_or_get_tool_resource(self, tool_info: dict) -> Optional[str]:
  533. """创建或获取工具资源(存入 PostgreSQL tool 表)"""
  534. category = tool_info.get("category", "other")
  535. slug = tool_info.get("slug", "")
  536. if not slug:
  537. return None
  538. tool_id = f"tools/{category}/{slug}"
  539. now_ts = int(time.time())
  540. cursor = pg_store._get_cursor()
  541. try:
  542. cursor.execute("SELECT id FROM tool WHERE id = %s", (tool_id,))
  543. if cursor.fetchone():
  544. return tool_id
  545. cursor.execute("""
  546. INSERT INTO tool (id, name, version, introduction, tutorial, input, output,
  547. updated_time, status)
  548. VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
  549. """, (
  550. tool_id,
  551. tool_info.get("name", slug),
  552. tool_info.get("version") or None,
  553. tool_info.get("description", ""),
  554. tool_info.get("usage", ""),
  555. json.dumps(tool_info.get("input", "")),
  556. json.dumps(tool_info.get("output", "")),
  557. now_ts,
  558. tool_info.get("status", "未接入"),
  559. ))
  560. pg_store.conn.commit()
  561. print(f"[Tool Resource] 创建新工具: {tool_id}")
  562. return tool_id
  563. finally:
  564. cursor.close()
  565. async def _update_tool_knowledge_index(self, tool_id: str, knowledge_id: str):
  566. """向工具添加知识关联(写入 tool_knowledge 关联表)"""
  567. pg_tool_store.add_knowledge(tool_id, knowledge_id)
  568. async def _analyze_tool_relation(self, knowledge: dict):
  569. """分析知识与工具的关联关系"""
  570. kid = knowledge["id"]
  571. now = int(time.time())
  572. # 乐观锁:dedup_passed → analyzing
  573. try:
  574. pg_store.update(kid, {"status": "analyzing", "updated_at": now})
  575. except Exception as e:
  576. print(f"[Tool Analysis] 锁定 {kid} 失败: {e}")
  577. return
  578. try:
  579. tool_analysis = await self._llm_analyze_tools(knowledge)
  580. has_tools = bool(tool_analysis and tool_analysis.get("has_tools"))
  581. existing_tags = knowledge.get("tags") or {}
  582. has_tool_tag = existing_tags.get("tool") is True
  583. # 情况1:LLM 判定无工具,但有 tool tag → 重新分析一次
  584. if not has_tools and has_tool_tag:
  585. print(f"[Tool Analysis] {kid} LLM 判定无工具但有 tool tag,重新分析")
  586. tool_analysis = await self._llm_analyze_tools(knowledge)
  587. has_tools = bool(tool_analysis and tool_analysis.get("has_tools"))
  588. # 重新分析后仍然不一致 → 知识模糊,rejected
  589. if not has_tools:
  590. pg_store.update(kid, {"status": "rejected", "updated_at": now})
  591. print(f"[Tool Analysis] {kid} 两次判定不一致,知识模糊,rejected")
  592. return
  593. # 情况2:无工具且无 tool tag → 直接 approved
  594. if not has_tools:
  595. pg_store.update(kid, {"status": "approved", "updated_at": now})
  596. return
  597. # 情况3/4:有工具 → 创建工具并关联
  598. tool_ids = []
  599. for tool_info in (tool_analysis.get("tools") or []):
  600. tool_id = await self._create_or_get_tool_resource(tool_info)
  601. if tool_id:
  602. tool_ids.append(tool_id)
  603. updates: dict = {
  604. "status": "approved",
  605. "updated_at": now
  606. }
  607. # 有工具但无 tool tag → 添加 tag
  608. if not has_tool_tag:
  609. updated_tags = dict(existing_tags)
  610. updated_tags["tool"] = True
  611. updates["tags"] = updated_tags
  612. print(f"[Tool Analysis] {kid} 添加 tool tag")
  613. pg_store.update(kid, updates)
  614. # 写入 tool_knowledge 关联
  615. for tool_id in tool_ids:
  616. await self._update_tool_knowledge_index(tool_id, kid)
  617. print(f"[Tool Analysis] {kid} 关联了 {len(tool_ids)} 个工具")
  618. except Exception as e:
  619. print(f"[Tool Analysis] {kid} 分析失败: {e},回退到 dedup_passed")
  620. try:
  621. pg_store.update(kid, {"status": "dedup_passed", "updated_at": int(time.time())})
  622. except Exception:
  623. pass
  624. async def _periodic_processor():
  625. """每60秒检测超时条目并回滚:processing(>5min)→pending,analyzing(>10min)→dedup_passed"""
  626. while True:
  627. await asyncio.sleep(60)
  628. try:
  629. now = int(time.time())
  630. # 回滚超时的 processing(5分钟 → pending)
  631. timeout_5min = now - 300
  632. processing = pg_store.query('status == "processing"', limit=200)
  633. for item in processing:
  634. updated_at = item.get("updated_at", 0) or 0
  635. updated_at_sec = updated_at // 1000 if updated_at > 1_000_000_000_000 else updated_at
  636. if updated_at_sec < timeout_5min:
  637. print(f"[Periodic] 回滚超时 processing → pending: {item['id']}")
  638. pg_store.update(item["id"], {"status": "pending", "updated_at": int(time.time())})
  639. # 回滚超时的 analyzing(10分钟 → dedup_passed)
  640. timeout_10min = now - 600
  641. analyzing = pg_store.query('status == "analyzing"', limit=200)
  642. for item in analyzing:
  643. updated_at = item.get("updated_at", 0) or 0
  644. updated_at_sec = updated_at // 1000 if updated_at > 1_000_000_000_000 else updated_at
  645. if updated_at_sec < timeout_10min:
  646. print(f"[Periodic] 回滚超时 analyzing → dedup_passed: {item['id']}")
  647. pg_store.update(item["id"], {"status": "dedup_passed", "updated_at": int(time.time())})
  648. except Exception as e:
  649. print(f"[Periodic] 定时任务错误: {e}")
  650. # --- App ---
  651. @asynccontextmanager
  652. async def lifespan(app: FastAPI):
  653. global pg_store, pg_resource_store, pg_tool_store, pg_capability_store, pg_requirement_store, pg_strategy_store, knowledge_processor
  654. # 初始化 PostgreSQL(knowledge + resources + tools + capabilities + requirements + strategy)
  655. pg_store = PostgreSQLStore()
  656. pg_resource_store = PostgreSQLResourceStore()
  657. pg_tool_store = PostgreSQLToolStore()
  658. pg_capability_store = PostgreSQLCapabilityStore()
  659. pg_requirement_store = PostgreSQLRequirementStore()
  660. pg_strategy_store = PostgreSQLStrategyStore()
  661. # 初始化去重处理器 + 启动定时兜底任务
  662. knowledge_processor = KnowledgeProcessor()
  663. periodic_task = asyncio.create_task(_periodic_processor())
  664. yield
  665. # 清理
  666. periodic_task.cancel()
  667. try:
  668. await periodic_task
  669. except asyncio.CancelledError:
  670. pass
  671. pg_store.close()
  672. pg_resource_store.close()
  673. pg_tool_store.close()
  674. pg_capability_store.close()
  675. pg_requirement_store.close()
  676. pg_strategy_store.close()
  677. app = FastAPI(title=BRAND_NAME, lifespan=lifespan)
  678. # 挂载静态文件
  679. STATIC_DIR = Path(__file__).parent / "frontend" / "dist"
  680. if STATIC_DIR.exists():
  681. app.mount("/assets", StaticFiles(directory=str(STATIC_DIR / "assets")), name="assets")
  682. # --- Knowledge API ---
  683. @app.post("/api/resource", status_code=201)
  684. def submit_resource(resource: ResourceIn):
  685. """提交资源(存入 PostgreSQL resources 表)"""
  686. try:
  687. # 加密敏感内容
  688. encrypted_secure_body = encrypt_content(resource.id, resource.secure_body)
  689. pg_resource_store.insert_or_update({
  690. 'id': resource.id,
  691. 'title': resource.title,
  692. 'body': resource.body,
  693. 'secure_body': encrypted_secure_body,
  694. 'content_type': resource.content_type,
  695. 'metadata': resource.metadata,
  696. 'sort_order': resource.sort_order,
  697. 'submitted_by': resource.submitted_by
  698. })
  699. return {"status": "ok", "id": resource.id}
  700. except Exception as e:
  701. raise HTTPException(status_code=500, detail=str(e))
  702. @app.get("/api/resource/{resource_id:path}", response_model=ResourceOut)
  703. def get_resource(resource_id: str, x_org_key: Optional[str] = Header(None)):
  704. """获取资源详情(从 PostgreSQL)"""
  705. try:
  706. row = pg_resource_store.get_by_id(resource_id)
  707. if not row:
  708. raise HTTPException(status_code=404, detail=f"Resource not found: {resource_id}")
  709. # 解密敏感内容
  710. secure_body = decrypt_content(resource_id, row.get("secure_body", ""), x_org_key)
  711. # 计算导航上下文
  712. root_id = resource_id.split("/")[0] if "/" in resource_id else resource_id
  713. # TOC (根节点)
  714. toc = None
  715. if "/" in resource_id:
  716. toc_row = pg_resource_store.get_by_id(root_id)
  717. if toc_row:
  718. toc = ResourceNode(id=toc_row["id"], title=toc_row["title"])
  719. # Children (子节点)
  720. children_rows = pg_resource_store.list_resources(prefix=f"{resource_id}/", limit=1000)
  721. children = [ResourceNode(id=r["id"], title=r["title"]) for r in children_rows
  722. if r["id"].count("/") == resource_id.count("/") + 1]
  723. # Prev/Next (同级节点)
  724. prev_node, next_node = pg_resource_store.get_siblings(resource_id)
  725. prev = ResourceNode(id=prev_node["id"], title=prev_node["title"]) if prev_node else None
  726. next = ResourceNode(id=next_node["id"], title=next_node["title"]) if next_node else None
  727. return ResourceOut(
  728. id=row["id"],
  729. title=row["title"],
  730. body=row["body"],
  731. secure_body=secure_body,
  732. content_type=row["content_type"],
  733. metadata=row.get("metadata", {}),
  734. images=row.get("images", []),
  735. toc=toc,
  736. children=children,
  737. prev=prev,
  738. next=next,
  739. )
  740. except HTTPException:
  741. raise
  742. except Exception as e:
  743. raise HTTPException(status_code=500, detail=str(e))
  744. @app.patch("/api/resource/{resource_id:path}")
  745. def patch_resource(resource_id: str, patch: ResourcePatchIn):
  746. """更新resource字段(PostgreSQL)"""
  747. try:
  748. # 检查是否存在
  749. if not pg_resource_store.get_by_id(resource_id):
  750. raise HTTPException(status_code=404, detail=f"Resource not found: {resource_id}")
  751. # 构建更新字典
  752. updates = {}
  753. if patch.title is not None:
  754. updates['title'] = patch.title
  755. if patch.body is not None:
  756. updates['body'] = patch.body
  757. if patch.secure_body is not None:
  758. updates['secure_body'] = encrypt_content(resource_id, patch.secure_body)
  759. if patch.content_type is not None:
  760. updates['content_type'] = patch.content_type
  761. if patch.metadata is not None:
  762. updates['metadata'] = patch.metadata
  763. if not updates:
  764. return {"status": "ok", "message": "No fields to update"}
  765. pg_resource_store.update(resource_id, updates)
  766. return {"status": "ok", "id": resource_id}
  767. except HTTPException:
  768. raise
  769. except Exception as e:
  770. raise HTTPException(status_code=500, detail=str(e))
  771. @app.get("/api/resource")
  772. def list_resources(
  773. content_type: Optional[str] = Query(None),
  774. limit: int = Query(100, ge=1, le=1000)
  775. ):
  776. """列出所有resource(PostgreSQL)"""
  777. try:
  778. results = pg_resource_store.list_resources(
  779. content_type=content_type,
  780. limit=limit
  781. )
  782. return {"results": results, "count": len(results)}
  783. except Exception as e:
  784. raise HTTPException(status_code=500, detail=str(e))
  785. @app.delete("/api/resource/{resource_id:path}")
  786. def delete_resource(resource_id: str):
  787. """删除单个resource(PostgreSQL)"""
  788. try:
  789. if not pg_resource_store.get_by_id(resource_id):
  790. raise HTTPException(status_code=404, detail=f"Resource not found: {resource_id}")
  791. pg_resource_store.delete(resource_id)
  792. return {"status": "ok", "id": resource_id}
  793. except HTTPException:
  794. raise
  795. except Exception as e:
  796. raise HTTPException(status_code=500, detail=str(e))
  797. # --- Knowledge API ---
  798. # ===== Knowledge API =====
  799. async def _llm_rerank(query: str, candidates: list[dict], top_k: int) -> list[str]:
  800. """
  801. 使用 LLM 对候选知识进行精排
  802. Args:
  803. query: 查询文本
  804. candidates: 候选知识列表
  805. top_k: 返回数量
  806. Returns:
  807. 排序后的知识 ID 列表
  808. """
  809. if not candidates:
  810. return []
  811. # 构造 prompt
  812. candidates_text = "\n".join([
  813. f"[{i+1}] ID: {c['id']}\nTask: {c['task']}\nContent: {c['content'][:200]}..."
  814. for i, c in enumerate(candidates)
  815. ])
  816. prompt = RERANK_PROMPT_TEMPLATE.format(
  817. top_k=top_k,
  818. query=query,
  819. candidates_text=candidates_text
  820. )
  821. try:
  822. response = await _dedup_llm(
  823. messages=[{"role": "user", "content": prompt}],
  824. )
  825. content = response.get("content", "").strip()
  826. # 解析 ID 列表
  827. selected_ids = [
  828. idx.strip()
  829. for idx in re.split(r'[,\s]+', content)
  830. if idx.strip().startswith(("knowledge-", "research-"))
  831. ]
  832. return selected_ids[:top_k]
  833. except Exception as e:
  834. print(f"[LLM Rerank] 失败: {e}")
  835. return []
  836. # --- Knowledge Ask / Upload API (Librarian Agent HTTP 接口) ---
  837. class AgentRequest(BaseModel):
  838. """POST /api/agent 请求体(统一远端 Agent 入口)"""
  839. agent_type: str # 必填,必须是 remote_ 前缀
  840. task: str # 必填,单任务描述
  841. messages: Optional[list[dict]] = None # 预置 OpenAI 格式消息
  842. continue_from: Optional[str] = None # 已有 sub_trace_id,传入则续跑
  843. skills: Optional[list[str]] = None # 调用方指定 skill,服务器按 agent_type 的白名单过滤
  844. class AgentResponse(BaseModel):
  845. """POST /api/agent 响应体(标准 Agent 结果)"""
  846. sub_trace_id: Optional[str] = None
  847. status: str
  848. summary: str = ""
  849. stats: dict = {}
  850. error: Optional[str] = None
  851. # agent_type → handler 的映射。handler 签名: (query, continue_from, skills) -> dict
  852. # 新增远端 Agent 在这里登记。
  853. _REMOTE_AGENT_DISPATCH = {}
  854. def _get_remote_agent_dispatch():
  855. """延迟导入 agent 实现,避免循环导入和启动时加载重型依赖"""
  856. global _REMOTE_AGENT_DISPATCH
  857. if not _REMOTE_AGENT_DISPATCH:
  858. from agents.librarian import run_librarian
  859. from agents.research import research as _research
  860. _REMOTE_AGENT_DISPATCH = {
  861. "remote_librarian": run_librarian,
  862. "remote_research": _research,
  863. }
  864. return _REMOTE_AGENT_DISPATCH
  865. @app.post("/api/agent", response_model=AgentResponse)
  866. async def agent_api(req: AgentRequest):
  867. """
  868. 统一远端 Agent 入口。按 agent_type 分发到对应实现。
  869. 全部同步:Agent 运行完成后返回标准 {status, sub_trace_id, summary, stats}。
  870. 续跑由 caller 传入 continue_from 显式指定(服务器不维护 caller→trace 映射)。
  871. Skills 由 caller 指定,每个 handler 用自己的白名单过滤。
  872. """
  873. if not req.agent_type.startswith("remote_"):
  874. raise HTTPException(
  875. status_code=400,
  876. detail=f"agent_type 必须以 'remote_' 开头,收到: {req.agent_type}",
  877. )
  878. dispatch = _get_remote_agent_dispatch()
  879. handler = dispatch.get(req.agent_type)
  880. if handler is None:
  881. raise HTTPException(
  882. status_code=404,
  883. detail=f"未注册的 agent_type: {req.agent_type},可用: {list(dispatch.keys())}",
  884. )
  885. try:
  886. result = await handler(
  887. query=req.task,
  888. continue_from=req.continue_from,
  889. skills=req.skills,
  890. )
  891. return AgentResponse(**result)
  892. except Exception as e:
  893. import traceback
  894. traceback.print_exc()
  895. print(f"[/api/agent] {req.agent_type} 错误: {e}")
  896. raise HTTPException(status_code=500, detail=str(e))
  897. @app.get("/api/knowledge/upload/pending")
  898. async def list_pending_uploads_api():
  899. """列出所有未处理或失败的 upload 任务(用于排查和重跑)"""
  900. from agents.librarian import list_pending_uploads
  901. pending = list_pending_uploads()
  902. return {"pending": pending, "count": len(pending)}
  903. @app.post("/api/knowledge/upload/retry")
  904. async def retry_pending_uploads_api():
  905. """重跑所有失败的 upload 任务(同步执行,按顺序处理)"""
  906. from agents.librarian import list_pending_uploads, run_librarian
  907. pending = list_pending_uploads()
  908. failed = [p for p in pending if p["status"] == "failed"]
  909. results = []
  910. for item in failed:
  911. buffer_file = item["file"]
  912. data = json.loads(Path(buffer_file).read_text(encoding="utf-8"))
  913. payload = data.get("data", {})
  914. result = await run_librarian(
  915. query=json.dumps(payload),
  916. continue_from=None,
  917. skills=["upload_strategy"],
  918. )
  919. results.append({"file": buffer_file, "status": result.get("status"), "error": result.get("error")})
  920. return {"retried": len(failed), "results": results}
  921. @app.get("/api/knowledge/search")
  922. async def search_knowledge_api(
  923. q: str = Query(..., description="查询文本"),
  924. top_k: int = Query(default=5, ge=1, le=20),
  925. min_score: int = Query(default=3, ge=1, le=5),
  926. types: Optional[str] = None,
  927. owner: Optional[str] = None,
  928. requirement_id: Optional[str] = None,
  929. capability_id: Optional[str] = None,
  930. tool_id: Optional[str] = None
  931. ):
  932. """检索知识(向量召回 + LLM 精排)"""
  933. try:
  934. # 1. 生成查询向量
  935. query_embedding = await get_embedding(q)
  936. # 2. 构建过滤表达式
  937. filters = []
  938. if types:
  939. type_list = [t.strip() for t in types.split(',') if t.strip()]
  940. if len(type_list) == 1:
  941. filters.append(f'array_contains(types, "{type_list[0]}")')
  942. elif len(type_list) > 1:
  943. type_filters = [f'array_contains(types, "{t}")' for t in type_list]
  944. filters.append(f'({" or ".join(type_filters)})')
  945. if owner:
  946. owner_list = [o.strip() for o in owner.split(',') if o.strip()]
  947. if len(owner_list) == 1:
  948. filters.append(f'owner == "{owner_list[0]}"')
  949. else:
  950. # 多个owner用OR连接
  951. owner_filters = [f'owner == "{o}"' for o in owner_list]
  952. filters.append(f'({" or ".join(owner_filters)})')
  953. # 添加 min_score 过滤
  954. filters.append(f'eval["score"] >= {min_score}')
  955. # 只搜索 approved 和 checked 的知识
  956. filters.append('(status == "approved" or status == "checked")')
  957. filter_expr = ' and '.join(filters) if filters else None
  958. relation_filters = {}
  959. if requirement_id: relation_filters['requirement_id'] = requirement_id
  960. if capability_id: relation_filters['capability_id'] = capability_id
  961. if tool_id: relation_filters['tool_id'] = tool_id
  962. # 3. 向量召回(3*k 个候选)
  963. recall_limit = top_k * 3
  964. candidates = pg_store.search(
  965. query_embedding=query_embedding,
  966. filters=filter_expr,
  967. limit=recall_limit,
  968. relation_filters=relation_filters
  969. )
  970. if not candidates:
  971. return {"results": [], "count": 0, "reranked": False}
  972. # 转换为可序列化的格式
  973. serialized_candidates = [to_serializable(c) for c in candidates]
  974. # 为了保证搜索的极致速度,直接返回向量召回的 top-k(跳过缓慢的 LLM 精排)
  975. return {"results": serialized_candidates[:top_k], "count": len(serialized_candidates[:top_k]), "reranked": False}
  976. except Exception as e:
  977. print(f"[Knowledge Search] 错误: {e}")
  978. raise HTTPException(status_code=500, detail=str(e))
  979. @app.post("/api/knowledge", status_code=201)
  980. async def save_knowledge(knowledge: KnowledgeIn, background_tasks: BackgroundTasks):
  981. """保存新知识"""
  982. try:
  983. # 生成 ID
  984. timestamp = datetime.now().strftime('%Y%m%d-%H%M%S')
  985. random_suffix = uuid.uuid4().hex[:4]
  986. knowledge_id = f"knowledge-{timestamp}-{random_suffix}"
  987. now = int(time.time())
  988. # 设置默认值
  989. owner = knowledge.owner or f"agent:{knowledge.source.get('agent_id', 'unknown')}"
  990. # 准备 source
  991. source = {
  992. "name": knowledge.source.get("name", ""),
  993. "category": knowledge.source.get("category", ""),
  994. "urls": knowledge.source.get("urls", []),
  995. "agent_id": knowledge.source.get("agent_id", "unknown"),
  996. "submitted_by": knowledge.source.get("submitted_by", ""),
  997. "timestamp": datetime.now(timezone.utc).isoformat(),
  998. "message_id": knowledge.message_id
  999. }
  1000. # 准备 eval
  1001. eval_data = {
  1002. "score": knowledge.eval.get("score", 3),
  1003. "helpful": knowledge.eval.get("helpful", 1),
  1004. "harmful": knowledge.eval.get("harmful", 0),
  1005. "confidence": knowledge.eval.get("confidence", 0.5),
  1006. "helpful_history": [],
  1007. "harmful_history": []
  1008. }
  1009. # 生成向量(task_embedding + content_embedding 双向量)
  1010. task_embedding = await get_embedding(knowledge.task)
  1011. content_embedding = await get_embedding(knowledge.content)
  1012. # 提取 tag keys(用于高效筛选)
  1013. tag_keys = list(knowledge.tags.keys()) if isinstance(knowledge.tags, dict) else []
  1014. # 准备插入数据
  1015. insert_data = {
  1016. "id": knowledge_id,
  1017. "task_embedding": task_embedding,
  1018. "content_embedding": content_embedding,
  1019. "message_id": knowledge.message_id,
  1020. "task": knowledge.task,
  1021. "content": knowledge.content,
  1022. "types": knowledge.types,
  1023. "tags": knowledge.tags,
  1024. "tag_keys": tag_keys,
  1025. "scopes": knowledge.scopes,
  1026. "owner": owner,
  1027. "source": source,
  1028. "eval": eval_data,
  1029. "created_at": now,
  1030. "updated_at": now,
  1031. "status": "pending",
  1032. "capability_ids": knowledge.capability_ids,
  1033. "tool_ids": knowledge.tool_ids,
  1034. "resource_ids": knowledge.resource_ids,
  1035. }
  1036. print(f"[Save Knowledge] 插入数据: {json.dumps({k: v for k, v in insert_data.items() if k != 'embedding'}, ensure_ascii=False)}")
  1037. # 插入 Milvus
  1038. pg_store.insert(insert_data)
  1039. # 触发后台去重处理
  1040. background_tasks.add_task(knowledge_processor.process_pending)
  1041. return {"status": "pending", "knowledge_id": knowledge_id, "message": "知识已入队,正在处理去重..."}
  1042. except Exception as e:
  1043. print(f"[Save Knowledge] 错误: {e}")
  1044. raise HTTPException(status_code=500, detail=str(e))
  1045. @app.get("/api/knowledge")
  1046. def list_knowledge(
  1047. page: int = Query(default=1, ge=1),
  1048. page_size: int = Query(default=20, ge=1, le=1000),
  1049. types: Optional[str] = None,
  1050. scopes: Optional[str] = None,
  1051. owner: Optional[str] = None,
  1052. tags: Optional[str] = None,
  1053. status: Optional[str] = None,
  1054. requirement_id: Optional[str] = None,
  1055. capability_id: Optional[str] = None,
  1056. tool_id: Optional[str] = None
  1057. ):
  1058. """列出知识(支持后端筛选和分页)"""
  1059. try:
  1060. # 构建过滤表达式
  1061. filters = []
  1062. # types 支持多个,改为用 OR 连接(并集:包含任意选中 type 即可)
  1063. if types:
  1064. type_list = [t.strip() for t in types.split(',') if t.strip()]
  1065. if len(type_list) == 1:
  1066. filters.append(f'array_contains(types, "{type_list[0]}")')
  1067. elif len(type_list) > 1:
  1068. type_filters = [f'array_contains(types, "{t}")' for t in type_list]
  1069. filters.append(f'({" or ".join(type_filters)})')
  1070. if scopes:
  1071. filters.append(f'array_contains(scopes, "{scopes}")')
  1072. if owner:
  1073. owner_list = [o.strip() for o in owner.split(',') if o.strip()]
  1074. if len(owner_list) == 1:
  1075. filters.append(f'owner == "{owner_list[0]}"')
  1076. else:
  1077. # 多个owner用OR连接
  1078. owner_filters = [f'owner == "{o}"' for o in owner_list]
  1079. filters.append(f'({" or ".join(owner_filters)})')
  1080. # tags 支持多个,用 AND 连接(使用 tag_keys 数组进行高效筛选)
  1081. if tags:
  1082. tag_list = [t.strip() for t in tags.split(',') if t.strip()]
  1083. for t in tag_list:
  1084. filters.append(f'array_contains(tag_keys, "{t}")')
  1085. # 只返回指定 status 的知识(默认 approved 和 checked)
  1086. status_list = [s.strip() for s in (status or "approved,checked").split(',') if s.strip()]
  1087. status_conditions = ' or '.join([f'status == "{s}"' for s in status_list])
  1088. filters.append(f'({status_conditions})')
  1089. # 如果没有过滤条件,查询所有
  1090. filter_expr = ' and '.join(filters) if filters else 'id != ""'
  1091. relation_filters = {}
  1092. if requirement_id: relation_filters['requirement_id'] = requirement_id
  1093. if capability_id: relation_filters['capability_id'] = capability_id
  1094. if tool_id: relation_filters['tool_id'] = tool_id
  1095. # 查询 Milvus/PG(先获取所有符合条件的数据)
  1096. # limit 是总数限制,我们需要获取足够多的数据来支持分页
  1097. max_limit = 10000 # 设置一个合理的上限
  1098. results = pg_store.query(filter_expr, limit=max_limit, relation_filters=relation_filters)
  1099. # 转换为可序列化的格式
  1100. serialized_results = [to_serializable(r) for r in results]
  1101. # 按 created_at 降序排序(最新的在前)
  1102. serialized_results.sort(key=lambda x: x.get('created_at', 0), reverse=True)
  1103. # 计算分页
  1104. total = len(serialized_results)
  1105. total_pages = (total + page_size - 1) // page_size # 向上取整
  1106. start_idx = (page - 1) * page_size
  1107. end_idx = start_idx + page_size
  1108. page_results = serialized_results[start_idx:end_idx]
  1109. return {
  1110. "results": page_results,
  1111. "pagination": {
  1112. "page": page,
  1113. "page_size": page_size,
  1114. "total": total,
  1115. "total_pages": total_pages
  1116. }
  1117. }
  1118. except Exception as e:
  1119. print(f"[List Knowledge] 错误: {e}")
  1120. raise HTTPException(status_code=500, detail=str(e))
  1121. @app.get("/api/knowledge/meta/tags")
  1122. def get_all_tags():
  1123. """获取所有已有的 tags"""
  1124. try:
  1125. # 查询所有知识
  1126. results = pg_store.query('id != ""', limit=10000)
  1127. all_tags = set()
  1128. for item in results:
  1129. # 转换为标准字典
  1130. serialized_item = to_serializable(item)
  1131. tags_dict = serialized_item.get("tags", {})
  1132. if isinstance(tags_dict, dict):
  1133. for key in tags_dict.keys():
  1134. all_tags.add(key)
  1135. return {"tags": sorted(list(all_tags))}
  1136. except Exception as e:
  1137. print(f"[Get Tags] 错误: {e}")
  1138. raise HTTPException(status_code=500, detail=str(e))
  1139. @app.get("/api/knowledge/pending")
  1140. def get_pending_knowledge(limit: int = Query(default=50, ge=1, le=200)):
  1141. """查询待处理队列(pending + processing + dedup_passed + analyzing)"""
  1142. try:
  1143. pending = pg_store.query(
  1144. 'status == "pending" or status == "processing" or status == "dedup_passed" or status == "analyzing"',
  1145. limit=limit
  1146. )
  1147. serialized = [to_serializable(r) for r in pending]
  1148. return {"results": serialized, "count": len(serialized)}
  1149. except Exception as e:
  1150. print(f"[Pending] 错误: {e}")
  1151. raise HTTPException(status_code=500, detail=str(e))
  1152. @app.post("/api/knowledge/process")
  1153. async def trigger_process(force: bool = Query(default=False)):
  1154. """手动触发去重处理。force=true 时先回滚所有 processing → pending,analyzing → dedup_passed"""
  1155. try:
  1156. if force:
  1157. processing = pg_store.query('status == "processing"', limit=200)
  1158. for item in processing:
  1159. pg_store.update(item["id"], {"status": "pending", "updated_at": int(time.time())})
  1160. print(f"[Manual Process] 回滚 {len(processing)} 条 processing → pending")
  1161. analyzing = pg_store.query('status == "analyzing"', limit=200)
  1162. for item in analyzing:
  1163. pg_store.update(item["id"], {"status": "dedup_passed", "updated_at": int(time.time())})
  1164. print(f"[Manual Process] 回滚 {len(analyzing)} 条 analyzing → dedup_passed")
  1165. asyncio.create_task(knowledge_processor.process_pending())
  1166. return {"status": "ok", "message": "处理任务已触发"}
  1167. except Exception as e:
  1168. print(f"[Manual Process] 错误: {e}")
  1169. raise HTTPException(status_code=500, detail=str(e))
  1170. @app.post("/api/knowledge/migrate")
  1171. async def migrate_knowledge_schema():
  1172. """手动触发 schema 迁移(PostgreSQL不需要此功能)"""
  1173. return {"status": "ok", "message": "PostgreSQL不需要schema迁移"}
  1174. @app.get("/api/knowledge/status/{knowledge_id}")
  1175. def get_knowledge_status(knowledge_id: str):
  1176. """查询单条知识的处理状态和关系"""
  1177. try:
  1178. result = pg_store.get_by_id(knowledge_id)
  1179. if not result:
  1180. raise HTTPException(status_code=404, detail=f"Knowledge not found: {knowledge_id}")
  1181. serialized = to_serializable(result)
  1182. return {
  1183. "id": knowledge_id,
  1184. "status": serialized.get("status", "approved"),
  1185. "relations": serialized.get("relations", []),
  1186. "created_at": serialized.get("created_at"),
  1187. "updated_at": serialized.get("updated_at"),
  1188. }
  1189. except HTTPException:
  1190. raise
  1191. except Exception as e:
  1192. print(f"[Knowledge Status] 错误: {e}")
  1193. raise HTTPException(status_code=500, detail=str(e))
  1194. @app.get("/api/knowledge/{knowledge_id}")
  1195. def get_knowledge(knowledge_id: str):
  1196. """获取单条知识"""
  1197. try:
  1198. result = pg_store.get_by_id(knowledge_id)
  1199. if not result:
  1200. raise HTTPException(status_code=404, detail=f"Knowledge not found: {knowledge_id}")
  1201. return to_serializable(result)
  1202. except HTTPException:
  1203. raise
  1204. except Exception as e:
  1205. print(f"[Get Knowledge] 错误: {e}")
  1206. raise HTTPException(status_code=500, detail=str(e))
  1207. async def _evolve_knowledge_with_llm(old_content: str, feedback: str) -> str:
  1208. """使用 LLM 进行知识进化重写"""
  1209. prompt = KNOWLEDGE_EVOLVE_PROMPT_TEMPLATE.format(
  1210. old_content=old_content,
  1211. feedback=feedback
  1212. )
  1213. try:
  1214. response = await _dedup_llm(
  1215. messages=[{"role": "user", "content": prompt}],
  1216. )
  1217. evolved = response.get("content", "").strip()
  1218. if len(evolved) < 5:
  1219. raise ValueError("LLM output too short")
  1220. return evolved
  1221. except Exception as e:
  1222. print(f"知识进化失败,采用追加模式回退: {e}")
  1223. return f"{old_content}\n\n---\n[Update {datetime.now().strftime('%Y-%m-%d')}]: {feedback}"
  1224. @app.put("/api/knowledge/{knowledge_id}")
  1225. async def update_knowledge(knowledge_id: str, update: KnowledgeUpdateIn):
  1226. """更新知识评估,支持知识进化"""
  1227. try:
  1228. # 获取现有知识
  1229. existing = pg_store.get_by_id(knowledge_id)
  1230. if not existing:
  1231. raise HTTPException(status_code=404, detail=f"Knowledge not found: {knowledge_id}")
  1232. eval_data = existing.get("eval", {})
  1233. # 更新评分
  1234. if update.update_score is not None:
  1235. eval_data["score"] = update.update_score
  1236. # 添加有效案例
  1237. if update.add_helpful_case:
  1238. eval_data["helpful"] = eval_data.get("helpful", 0) + 1
  1239. if "helpful_history" not in eval_data:
  1240. eval_data["helpful_history"] = []
  1241. eval_data["helpful_history"].append(update.add_helpful_case)
  1242. # 添加有害案例
  1243. if update.add_harmful_case:
  1244. eval_data["harmful"] = eval_data.get("harmful", 0) + 1
  1245. if "harmful_history" not in eval_data:
  1246. eval_data["harmful_history"] = []
  1247. eval_data["harmful_history"].append(update.add_harmful_case)
  1248. # 知识进化
  1249. content = existing["content"]
  1250. need_reembed = False
  1251. if update.evolve_feedback:
  1252. content = await _evolve_knowledge_with_llm(content, update.evolve_feedback)
  1253. eval_data["helpful"] = eval_data.get("helpful", 0) + 1
  1254. need_reembed = True
  1255. # 准备更新数据
  1256. updates = {
  1257. "content": content,
  1258. "eval": eval_data,
  1259. }
  1260. # 如果内容变化,重新生成向量
  1261. if need_reembed:
  1262. embedding = await get_embedding(existing['task'])
  1263. updates["task_embedding"] = embedding
  1264. # 更新 Milvus
  1265. pg_store.update(knowledge_id, updates)
  1266. return {"status": "ok", "knowledge_id": knowledge_id}
  1267. except HTTPException:
  1268. raise
  1269. except Exception as e:
  1270. print(f"[Update Knowledge] 错误: {e}")
  1271. raise HTTPException(status_code=500, detail=str(e))
  1272. @app.patch("/api/knowledge/{knowledge_id}")
  1273. async def patch_knowledge(knowledge_id: str, patch: KnowledgePatchIn):
  1274. """直接编辑知识字段"""
  1275. try:
  1276. # 获取现有知识
  1277. existing = pg_store.get_by_id(knowledge_id)
  1278. if not existing:
  1279. raise HTTPException(status_code=404, detail=f"Knowledge not found: {knowledge_id}")
  1280. updates = {}
  1281. need_reembed = False
  1282. need_content_reembed = False
  1283. if patch.task is not None:
  1284. updates["task"] = patch.task
  1285. need_reembed = True
  1286. if patch.content is not None:
  1287. updates["content"] = patch.content
  1288. need_content_reembed = True
  1289. if patch.types is not None:
  1290. updates["types"] = patch.types
  1291. if patch.tags is not None:
  1292. updates["tags"] = patch.tags
  1293. # 同时更新 tag_keys
  1294. updates["tag_keys"] = list(patch.tags.keys()) if isinstance(patch.tags, dict) else []
  1295. if patch.scopes is not None:
  1296. updates["scopes"] = patch.scopes
  1297. if patch.owner is not None:
  1298. updates["owner"] = patch.owner
  1299. if patch.capability_ids is not None:
  1300. updates["capability_ids"] = patch.capability_ids
  1301. if patch.tool_ids is not None:
  1302. updates["tool_ids"] = patch.tool_ids
  1303. if not updates:
  1304. return {"status": "ok", "knowledge_id": knowledge_id}
  1305. # 如果 task 变化,重新生成 task_embedding
  1306. if need_reembed:
  1307. task = updates.get("task", existing["task"])
  1308. embedding = await get_embedding(task)
  1309. updates["task_embedding"] = embedding
  1310. # 如果 content 变化,重新生成 content_embedding
  1311. if need_content_reembed:
  1312. content = updates.get("content", existing["content"])
  1313. content_embedding = await get_embedding(content)
  1314. updates["content_embedding"] = content_embedding
  1315. # 更新 Milvus
  1316. pg_store.update(knowledge_id, updates)
  1317. return {"status": "ok", "knowledge_id": knowledge_id}
  1318. except HTTPException:
  1319. raise
  1320. except Exception as e:
  1321. print(f"[Patch Knowledge] 错误: {e}")
  1322. raise HTTPException(status_code=500, detail=str(e))
  1323. @app.delete("/api/knowledge/{knowledge_id}")
  1324. def delete_knowledge(knowledge_id: str):
  1325. """删除单条知识"""
  1326. try:
  1327. # 检查知识是否存在
  1328. existing = pg_store.get_by_id(knowledge_id)
  1329. if not existing:
  1330. raise HTTPException(status_code=404, detail=f"Knowledge not found: {knowledge_id}")
  1331. # 从 PostgreSQL 删除
  1332. pg_store.delete(knowledge_id)
  1333. print(f"[Delete Knowledge] 已删除知识: {knowledge_id}")
  1334. return {"status": "ok", "knowledge_id": knowledge_id}
  1335. except HTTPException:
  1336. raise
  1337. except Exception as e:
  1338. print(f"[Delete Knowledge] 错误: {e}")
  1339. raise HTTPException(status_code=500, detail=str(e))
  1340. @app.post("/api/knowledge/batch_delete")
  1341. def batch_delete_knowledge(knowledge_ids: List[str] = Body(...)):
  1342. """批量删除知识"""
  1343. try:
  1344. if not knowledge_ids:
  1345. raise HTTPException(status_code=400, detail="knowledge_ids cannot be empty")
  1346. deleted_count = 0
  1347. for kid in knowledge_ids:
  1348. pg_store.delete(kid)
  1349. deleted_count += 1
  1350. print(f"[Batch Delete] 已删除 {deleted_count} 条知识")
  1351. return {"status": "ok", "deleted_count": deleted_count}
  1352. except HTTPException:
  1353. raise
  1354. except Exception as e:
  1355. print(f"[Batch Delete] 错误: {e}")
  1356. raise HTTPException(status_code=500, detail=str(e))
  1357. @app.post("/api/knowledge/batch_verify")
  1358. async def batch_verify_knowledge(batch: KnowledgeBatchVerifyIn):
  1359. """批量验证通过(approved → checked)"""
  1360. if not batch.knowledge_ids:
  1361. return {"status": "ok", "updated": 0}
  1362. try:
  1363. now_iso = datetime.now(timezone.utc).isoformat()
  1364. updated_count = 0
  1365. for kid in batch.knowledge_ids:
  1366. existing = pg_store.get_by_id(kid)
  1367. if not existing:
  1368. continue
  1369. eval_data = existing.get("eval") or {}
  1370. eval_data["verification"] = {
  1371. "status": "checked",
  1372. "verified_by": batch.verified_by,
  1373. "verified_at": now_iso,
  1374. "note": None,
  1375. "issue_type": None,
  1376. "issue_action": None,
  1377. }
  1378. pg_store.update(kid, {"eval": eval_data, "status": "checked", "updated_at": int(time.time())})
  1379. updated_count += 1
  1380. return {"status": "ok", "updated": updated_count}
  1381. except Exception as e:
  1382. print(f"[Batch Verify] 错误: {e}")
  1383. raise HTTPException(status_code=500, detail=str(e))
  1384. @app.post("/api/knowledge/{knowledge_id}/verify")
  1385. async def verify_knowledge(knowledge_id: str, verify: KnowledgeVerifyIn):
  1386. """知识验证:approve 切换 approved↔checked,reject 设为 rejected"""
  1387. try:
  1388. existing = pg_store.get_by_id(knowledge_id)
  1389. if not existing:
  1390. raise HTTPException(status_code=404, detail=f"Knowledge not found: {knowledge_id}")
  1391. current_status = existing.get("status", "approved")
  1392. if verify.action == "approve":
  1393. # checked → approved(取消验证),其他 → checked
  1394. new_status = "approved" if current_status == "checked" else "checked"
  1395. pg_store.update(knowledge_id, {
  1396. "status": new_status,
  1397. "updated_at": int(time.time())
  1398. })
  1399. return {"status": "ok", "new_status": new_status,
  1400. "message": "已取消验证" if new_status == "approved" else "验证通过"}
  1401. elif verify.action == "reject":
  1402. pg_store.update(knowledge_id, {
  1403. "status": "rejected",
  1404. "updated_at": int(time.time())
  1405. })
  1406. return {"status": "ok", "new_status": "rejected", "message": "已拒绝"}
  1407. else:
  1408. raise HTTPException(status_code=400, detail=f"Unknown action: {verify.action}")
  1409. except HTTPException:
  1410. raise
  1411. except Exception as e:
  1412. print(f"[Verify Knowledge] 错误: {e}")
  1413. raise HTTPException(status_code=500, detail=str(e))
  1414. @app.post("/api/knowledge/batch_update")
  1415. async def batch_update_knowledge(batch: KnowledgeBatchUpdateIn):
  1416. """批量反馈知识有效性"""
  1417. if not batch.feedback_list:
  1418. return {"status": "ok", "updated": 0}
  1419. try:
  1420. # 先处理无需进化的,收集需要进化的
  1421. evolution_tasks = [] # [(knowledge_id, old_content, feedback, eval_data)]
  1422. simple_updates = [] # [(knowledge_id, is_effective, eval_data)]
  1423. for item in batch.feedback_list:
  1424. knowledge_id = item.get("knowledge_id")
  1425. is_effective = item.get("is_effective")
  1426. feedback = item.get("feedback", "")
  1427. if not knowledge_id:
  1428. continue
  1429. existing = pg_store.get_by_id(knowledge_id)
  1430. if not existing:
  1431. continue
  1432. eval_data = existing.get("eval", {})
  1433. if is_effective and feedback:
  1434. evolution_tasks.append((knowledge_id, existing["content"], feedback, eval_data, existing["task"]))
  1435. else:
  1436. simple_updates.append((knowledge_id, is_effective, eval_data))
  1437. # 执行简单更新
  1438. for knowledge_id, is_effective, eval_data in simple_updates:
  1439. if is_effective:
  1440. eval_data["helpful"] = eval_data.get("helpful", 0) + 1
  1441. else:
  1442. eval_data["harmful"] = eval_data.get("harmful", 0) + 1
  1443. pg_store.update(knowledge_id, {"eval": eval_data})
  1444. # 并发执行知识进化
  1445. if evolution_tasks:
  1446. print(f"🧬 并发处理 {len(evolution_tasks)} 条知识进化...")
  1447. evolved_results = await asyncio.gather(
  1448. *[_evolve_knowledge_with_llm(old, fb) for _, old, fb, _, _ in evolution_tasks]
  1449. )
  1450. for (knowledge_id, _, _, eval_data, task), evolved_content in zip(evolution_tasks, evolved_results):
  1451. eval_data["helpful"] = eval_data.get("helpful", 0) + 1
  1452. # 重新生成向量(只基于 task)
  1453. embedding = await get_embedding(task)
  1454. pg_store.update(knowledge_id, {
  1455. "content": evolved_content,
  1456. "eval": eval_data,
  1457. "task_embedding": embedding
  1458. })
  1459. return {"status": "ok", "updated": len(simple_updates) + len(evolution_tasks)}
  1460. except Exception as e:
  1461. print(f"[Batch Update] 错误: {e}")
  1462. raise HTTPException(status_code=500, detail=str(e))
  1463. @app.post("/api/knowledge/slim")
  1464. async def slim_knowledge(model: str = "google/gemini-2.5-flash-lite"):
  1465. """知识库瘦身:合并语义相似知识"""
  1466. try:
  1467. # 获取所有知识
  1468. all_knowledge = pg_store.query('id != ""', limit=10000)
  1469. # 转换为可序列化的格式
  1470. all_knowledge = [to_serializable(item) for item in all_knowledge]
  1471. if len(all_knowledge) < 2:
  1472. return {"status": "ok", "message": f"知识库仅有 {len(all_knowledge)} 条,无需瘦身"}
  1473. # 构造发给大模型的内容
  1474. entries_text = ""
  1475. for item in all_knowledge:
  1476. eval_data = item.get("eval", {})
  1477. types = item.get("types", [])
  1478. entries_text += f"[ID: {item['id']}] [Types: {','.join(types)}] "
  1479. entries_text += f"[Helpful: {eval_data.get('helpful', 0)}, Harmful: {eval_data.get('harmful', 0)}] [Score: {eval_data.get('score', 3)}]\n"
  1480. entries_text += f"Task: {item['task']}\n"
  1481. entries_text += f"Content: {item['content'][:200]}...\n\n"
  1482. prompt = KNOWLEDGE_SLIM_PROMPT_TEMPLATE.format(entries_text=entries_text)
  1483. print(f"\n[知识瘦身] 正在调用 {model} 分析 {len(all_knowledge)} 条知识...")
  1484. slim_llm = create_openrouter_llm_call(model=model)
  1485. response = await slim_llm(
  1486. messages=[{"role": "user", "content": prompt}],
  1487. )
  1488. content = response.get("content", "").strip()
  1489. if not content:
  1490. raise HTTPException(status_code=500, detail="LLM 返回为空")
  1491. # 解析大模型输出
  1492. report_line = ""
  1493. new_entries = []
  1494. blocks = [b.strip() for b in content.split("===") if b.strip()]
  1495. for block in blocks:
  1496. if block.startswith("REPORT:"):
  1497. report_line = block
  1498. continue
  1499. lines = block.split("\n")
  1500. kid, types, helpful, harmful, score, task, content_lines = None, [], 0, 0, 3, "", []
  1501. current_field = None
  1502. for line in lines:
  1503. if line.startswith("ID:"):
  1504. kid = line[3:].strip()
  1505. current_field = None
  1506. elif line.startswith("TYPES:"):
  1507. types_str = line[6:].strip()
  1508. types = [t.strip() for t in types_str.split(",") if t.strip()]
  1509. current_field = None
  1510. elif line.startswith("HELPFUL:"):
  1511. try:
  1512. helpful = int(line[8:].strip())
  1513. except Exception:
  1514. helpful = 0
  1515. current_field = None
  1516. elif line.startswith("HARMFUL:"):
  1517. try:
  1518. harmful = int(line[8:].strip())
  1519. except Exception:
  1520. harmful = 0
  1521. current_field = None
  1522. elif line.startswith("SCORE:"):
  1523. try:
  1524. score = int(line[6:].strip())
  1525. except Exception:
  1526. score = 3
  1527. current_field = None
  1528. elif line.startswith("TASK:"):
  1529. task = line[5:].strip()
  1530. current_field = "task"
  1531. elif line.startswith("CONTENT:"):
  1532. content_lines.append(line[8:].strip())
  1533. current_field = "content"
  1534. elif current_field == "task":
  1535. task += "\n" + line
  1536. elif current_field == "content":
  1537. content_lines.append(line)
  1538. if kid and content_lines:
  1539. new_entries.append({
  1540. "id": kid,
  1541. "types": types if types else ["strategy"],
  1542. "helpful": helpful,
  1543. "harmful": harmful,
  1544. "score": score,
  1545. "task": task.strip(),
  1546. "content": "\n".join(content_lines).strip()
  1547. })
  1548. if not new_entries:
  1549. raise HTTPException(status_code=500, detail="解析大模型输出失败")
  1550. # 生成向量并重建知识库
  1551. print(f"[知识瘦身] 正在为 {len(new_entries)} 条知识生成向量...")
  1552. # 批量生成向量(只基于 task)
  1553. texts = [e['task'] for e in new_entries]
  1554. embeddings = await get_embeddings_batch(texts)
  1555. # 清空并重建(PostgreSQL使用TRUNCATE)
  1556. cursor = pg_store._get_cursor()
  1557. try:
  1558. # 先清关联表再清主表
  1559. for jt in ('requirement_knowledge', 'capability_knowledge', 'tool_knowledge',
  1560. 'knowledge_resource', 'knowledge_relation'):
  1561. cursor.execute(f"TRUNCATE TABLE {jt}")
  1562. cursor.execute("TRUNCATE TABLE knowledge")
  1563. pg_store.conn.commit()
  1564. finally:
  1565. cursor.close()
  1566. knowledge_list = []
  1567. for e, embedding in zip(new_entries, embeddings):
  1568. eval_data = {
  1569. "score": e["score"],
  1570. "helpful": e["helpful"],
  1571. "harmful": e["harmful"],
  1572. "confidence": 0.9,
  1573. "helpful_history": [],
  1574. "harmful_history": []
  1575. }
  1576. source = {
  1577. "name": "slim",
  1578. "category": "exp",
  1579. "urls": [],
  1580. "agent_id": "slim",
  1581. "submitted_by": "system",
  1582. "timestamp": datetime.now(timezone.utc).isoformat()
  1583. }
  1584. knowledge_list.append({
  1585. "id": e["id"],
  1586. "task_embedding": embedding,
  1587. "message_id": "",
  1588. "task": e["task"],
  1589. "content": e["content"],
  1590. "types": e["types"],
  1591. "tags": {},
  1592. "tag_keys": [],
  1593. "scopes": ["org:cybertogether"],
  1594. "owner": "agent:slim",
  1595. "source": source,
  1596. "eval": eval_data,
  1597. "created_at": now,
  1598. "updated_at": now,
  1599. "status": "approved",
  1600. })
  1601. pg_store.insert_batch(knowledge_list)
  1602. result_msg = f"瘦身完成:{len(all_knowledge)} → {len(new_entries)} 条知识"
  1603. if report_line:
  1604. result_msg += f"\n{report_line}"
  1605. print(f"[知识瘦身] {result_msg}")
  1606. return {"status": "ok", "before": len(all_knowledge), "after": len(new_entries), "report": report_line}
  1607. except HTTPException:
  1608. raise
  1609. except Exception as e:
  1610. print(f"[Slim Knowledge] 错误: {e}")
  1611. raise HTTPException(status_code=500, detail=str(e))
  1612. @app.post("/api/extract")
  1613. async def extract_knowledge_from_messages(extract_req: MessageExtractIn, background_tasks: BackgroundTasks):
  1614. """从消息历史中提取知识(LLM 分析)"""
  1615. if not extract_req.submitted_by:
  1616. raise HTTPException(status_code=400, detail="submitted_by is required")
  1617. messages = extract_req.messages
  1618. if not messages or len(messages) == 0:
  1619. return {"status": "ok", "extracted_count": 0, "knowledge_ids": []}
  1620. # 构造消息历史文本
  1621. messages_text = ""
  1622. for msg in messages:
  1623. role = msg.get("role", "unknown")
  1624. content = msg.get("content", "")
  1625. messages_text += f"[{role}]: {content}\n\n"
  1626. # LLM 提取知识
  1627. prompt = MESSAGE_EXTRACT_PROMPT_TEMPLATE.format(messages_text=messages_text)
  1628. try:
  1629. print(f"\n[Extract] 正在从 {len(messages)} 条消息中提取知识...")
  1630. response = await _dedup_llm(
  1631. messages=[{"role": "user", "content": prompt}],
  1632. )
  1633. content = response.get("content", "").strip()
  1634. # 尝试解析 JSON
  1635. # 移除可能的 markdown 代码块标记
  1636. if content.startswith("```json"):
  1637. content = content[7:]
  1638. if content.startswith("```"):
  1639. content = content[3:]
  1640. if content.endswith("```"):
  1641. content = content[:-3]
  1642. content = content.strip()
  1643. extracted_knowledge = json.loads(content)
  1644. if not isinstance(extracted_knowledge, list):
  1645. raise ValueError("LLM output is not a list")
  1646. if not extracted_knowledge:
  1647. return {"status": "ok", "extracted_count": 0, "knowledge_ids": []}
  1648. # 批量生成向量(只基于 task)
  1649. texts = [item.get('task', '') for item in extracted_knowledge]
  1650. embeddings = await get_embeddings_batch(texts)
  1651. # 保存提取的知识
  1652. knowledge_ids = []
  1653. now = int(time.time())
  1654. knowledge_list = []
  1655. for item, embedding in zip(extracted_knowledge, embeddings):
  1656. task = item.get("task", "")
  1657. knowledge_content = item.get("content", "")
  1658. types = item.get("types", ["strategy"])
  1659. score = item.get("score", 3)
  1660. if not task or not knowledge_content:
  1661. continue
  1662. # 生成 ID
  1663. timestamp = datetime.now().strftime('%Y%m%d-%H%M%S')
  1664. random_suffix = uuid.uuid4().hex[:4]
  1665. knowledge_id = f"knowledge-{timestamp}-{random_suffix}"
  1666. # 准备数据
  1667. source = {
  1668. "name": "message_extraction",
  1669. "category": "exp",
  1670. "urls": [],
  1671. "agent_id": extract_req.agent_id,
  1672. "submitted_by": extract_req.submitted_by,
  1673. "timestamp": datetime.now(timezone.utc).isoformat(),
  1674. "session_key": extract_req.session_key
  1675. }
  1676. eval_data = {
  1677. "score": score,
  1678. "helpful": 1,
  1679. "harmful": 0,
  1680. "confidence": 0.7,
  1681. "helpful_history": [],
  1682. "harmful_history": []
  1683. }
  1684. knowledge_list.append({
  1685. "id": knowledge_id,
  1686. "task_embedding": embedding,
  1687. "message_id": "",
  1688. "task": task,
  1689. "content": knowledge_content,
  1690. "types": types,
  1691. "tags": {},
  1692. "tag_keys": [],
  1693. "scopes": ["org:cybertogether"],
  1694. "owner": extract_req.submitted_by,
  1695. "source": source,
  1696. "eval": eval_data,
  1697. "created_at": now,
  1698. "updated_at": now,
  1699. "status": "pending",
  1700. })
  1701. knowledge_ids.append(knowledge_id)
  1702. # 批量插入
  1703. if knowledge_list:
  1704. pg_store.insert_batch(knowledge_list)
  1705. background_tasks.add_task(knowledge_processor.process_pending)
  1706. print(f"[Extract] 成功提取并保存 {len(knowledge_ids)} 条知识")
  1707. return {
  1708. "status": "ok",
  1709. "extracted_count": len(knowledge_ids),
  1710. "knowledge_ids": knowledge_ids
  1711. }
  1712. except json.JSONDecodeError as e:
  1713. print(f"[Extract] JSON 解析失败: {e}")
  1714. print(f"[Extract] LLM 输出: {content[:500]}")
  1715. return {"status": "error", "error": "Failed to parse LLM output", "extracted_count": 0}
  1716. except Exception as e:
  1717. print(f"[Extract] 提取失败: {e}")
  1718. return {"status": "error", "error": str(e), "extracted_count": 0}
  1719. # ===== Tool API =====
  1720. @app.post("/api/tool", status_code=201)
  1721. async def create_tool(tool: ToolIn):
  1722. """创建或更新工具"""
  1723. try:
  1724. now = int(time.time())
  1725. embedding = await get_embedding(f"{tool.name} {tool.introduction}")
  1726. pg_tool_store.insert_or_update({
  1727. 'id': tool.id,
  1728. 'name': tool.name,
  1729. 'version': tool.version,
  1730. 'introduction': tool.introduction,
  1731. 'tutorial': tool.tutorial,
  1732. 'input': tool.input,
  1733. 'output': tool.output,
  1734. 'updated_time': now,
  1735. 'status': tool.status,
  1736. 'capability_ids': tool.capability_ids,
  1737. 'knowledge_ids': tool.knowledge_ids,
  1738. 'provider_ids': tool.provider_ids,
  1739. 'embedding': embedding,
  1740. })
  1741. return {"status": "ok", "id": tool.id}
  1742. except Exception as e:
  1743. raise HTTPException(status_code=500, detail=str(e))
  1744. @app.get("/api/tool")
  1745. def list_tools(
  1746. status: Optional[str] = Query(None),
  1747. limit: int = Query(100, ge=1, le=1000),
  1748. offset: int = Query(0, ge=0),
  1749. ):
  1750. """列出工具"""
  1751. try:
  1752. results = pg_tool_store.list_all(limit=limit, offset=offset, status=status)
  1753. total = pg_tool_store.count(status=status)
  1754. return {"results": results, "total": total}
  1755. except Exception as e:
  1756. raise HTTPException(status_code=500, detail=str(e))
  1757. @app.get("/api/tool/search")
  1758. async def search_tools(
  1759. q: str = Query(..., description="查询文本"),
  1760. top_k: int = Query(5, ge=1, le=100),
  1761. status: Optional[str] = None,
  1762. ):
  1763. """向量检索工具"""
  1764. try:
  1765. query_embedding = await get_embedding(q)
  1766. results = pg_tool_store.search(query_embedding, limit=top_k, status=status)
  1767. return {"results": results, "count": len(results)}
  1768. except Exception as e:
  1769. raise HTTPException(status_code=500, detail=str(e))
  1770. @app.get("/api/tool/{tool_id:path}")
  1771. def get_tool(tool_id: str):
  1772. """获取单个工具详情"""
  1773. try:
  1774. result = pg_tool_store.get_by_id(tool_id)
  1775. if not result:
  1776. raise HTTPException(status_code=404, detail=f"Tool not found: {tool_id}")
  1777. return result
  1778. except HTTPException:
  1779. raise
  1780. except Exception as e:
  1781. raise HTTPException(status_code=500, detail=str(e))
  1782. @app.patch("/api/tool/{tool_id:path}")
  1783. async def patch_tool(tool_id: str, patch: ToolPatchIn):
  1784. """更新工具字段"""
  1785. try:
  1786. if not pg_tool_store.get_by_id(tool_id):
  1787. raise HTTPException(status_code=404, detail=f"Tool not found: {tool_id}")
  1788. updates = {}
  1789. need_reembed = False
  1790. for field in ('name', 'version', 'introduction', 'tutorial', 'input', 'output',
  1791. 'status', 'capability_ids', 'knowledge_ids', 'provider_ids'):
  1792. value = getattr(patch, field)
  1793. if value is not None:
  1794. updates[field] = value
  1795. if field in ('name', 'introduction'):
  1796. need_reembed = True
  1797. if not updates:
  1798. return {"status": "ok", "id": tool_id}
  1799. updates['updated_time'] = int(time.time())
  1800. if need_reembed:
  1801. existing = pg_tool_store.get_by_id(tool_id)
  1802. name = updates.get('name', existing['name'])
  1803. intro = updates.get('introduction', existing['introduction'])
  1804. updates['embedding'] = await get_embedding(f"{name} {intro}")
  1805. pg_tool_store.update(tool_id, updates)
  1806. return {"status": "ok", "id": tool_id}
  1807. except HTTPException:
  1808. raise
  1809. except Exception as e:
  1810. raise HTTPException(status_code=500, detail=str(e))
  1811. @app.delete("/api/tool/{tool_id:path}")
  1812. def delete_tool(tool_id: str):
  1813. """删除工具"""
  1814. try:
  1815. if not pg_tool_store.get_by_id(tool_id):
  1816. raise HTTPException(status_code=404, detail=f"Tool not found: {tool_id}")
  1817. pg_tool_store.delete(tool_id)
  1818. return {"status": "ok", "id": tool_id}
  1819. except HTTPException:
  1820. raise
  1821. except Exception as e:
  1822. raise HTTPException(status_code=500, detail=str(e))
  1823. # ===== Capability API =====
  1824. @app.post("/api/capability", status_code=201)
  1825. async def create_capability(cap: CapabilityIn):
  1826. """创建或更新原子能力"""
  1827. try:
  1828. embedding = await get_embedding(f"{cap.name} {cap.description}")
  1829. pg_capability_store.insert_or_update({
  1830. 'id': cap.id,
  1831. 'name': cap.name,
  1832. 'criterion': cap.criterion,
  1833. 'description': cap.description,
  1834. 'requirement_ids': cap.requirement_ids,
  1835. 'implements': cap.implements,
  1836. 'tool_ids': cap.tool_ids,
  1837. 'knowledge_ids': cap.knowledge_ids,
  1838. 'embedding': embedding,
  1839. })
  1840. return {"status": "ok", "id": cap.id}
  1841. except Exception as e:
  1842. raise HTTPException(status_code=500, detail=str(e))
  1843. @app.get("/api/capability")
  1844. def list_capabilities(
  1845. limit: int = Query(100, ge=1, le=1000),
  1846. offset: int = Query(0, ge=0),
  1847. ):
  1848. """列出原子能力"""
  1849. try:
  1850. results = pg_capability_store.list_all(limit=limit, offset=offset)
  1851. total = pg_capability_store.count()
  1852. return {"results": results, "total": total}
  1853. except Exception as e:
  1854. raise HTTPException(status_code=500, detail=str(e))
  1855. @app.get("/api/capability/search")
  1856. async def search_capabilities(
  1857. q: str = Query(..., description="查询文本"),
  1858. top_k: int = Query(5, ge=1, le=100),
  1859. ):
  1860. """向量检索原子能力"""
  1861. try:
  1862. query_embedding = await get_embedding(q)
  1863. results = pg_capability_store.search(query_embedding, limit=top_k)
  1864. return {"results": results, "count": len(results)}
  1865. except Exception as e:
  1866. raise HTTPException(status_code=500, detail=str(e))
  1867. @app.get("/api/capability/{cap_id}")
  1868. def get_capability(cap_id: str):
  1869. """获取单个原子能力"""
  1870. try:
  1871. result = pg_capability_store.get_by_id(cap_id)
  1872. if not result:
  1873. raise HTTPException(status_code=404, detail=f"Capability not found: {cap_id}")
  1874. return result
  1875. except HTTPException:
  1876. raise
  1877. except Exception as e:
  1878. raise HTTPException(status_code=500, detail=str(e))
  1879. @app.patch("/api/capability/{cap_id}")
  1880. async def patch_capability(cap_id: str, patch: CapabilityPatchIn):
  1881. """更新原子能力字段"""
  1882. try:
  1883. existing = pg_capability_store.get_by_id(cap_id)
  1884. if not existing:
  1885. raise HTTPException(status_code=404, detail=f"Capability not found: {cap_id}")
  1886. updates = {}
  1887. need_reembed = False
  1888. for field in ('name', 'criterion', 'description', 'requirement_ids',
  1889. 'implements', 'tool_ids', 'knowledge_ids'):
  1890. value = getattr(patch, field)
  1891. if value is not None:
  1892. updates[field] = value
  1893. if field in ('name', 'description'):
  1894. need_reembed = True
  1895. if not updates:
  1896. return {"status": "ok", "id": cap_id}
  1897. if need_reembed:
  1898. name = updates.get('name', existing['name'])
  1899. desc = updates.get('description', existing['description'])
  1900. updates['embedding'] = await get_embedding(f"{name} {desc}")
  1901. pg_capability_store.update(cap_id, updates)
  1902. return {"status": "ok", "id": cap_id}
  1903. except HTTPException:
  1904. raise
  1905. except Exception as e:
  1906. raise HTTPException(status_code=500, detail=str(e))
  1907. @app.delete("/api/capability/{cap_id}")
  1908. def delete_capability(cap_id: str):
  1909. """删除原子能力"""
  1910. try:
  1911. if not pg_capability_store.get_by_id(cap_id):
  1912. raise HTTPException(status_code=404, detail=f"Capability not found: {cap_id}")
  1913. pg_capability_store.delete(cap_id)
  1914. return {"status": "ok", "id": cap_id}
  1915. except HTTPException:
  1916. raise
  1917. except Exception as e:
  1918. raise HTTPException(status_code=500, detail=str(e))
  1919. # ===== Requirement API =====
  1920. @app.post("/api/requirement", status_code=201)
  1921. async def create_requirement(req: RequirementIn):
  1922. """创建或更新需求"""
  1923. try:
  1924. embedding = await get_embedding(req.description)
  1925. pg_requirement_store.insert_or_update({
  1926. 'id': req.id,
  1927. 'description': req.description,
  1928. 'capability_ids': req.capability_ids,
  1929. 'knowledge_ids': req.knowledge_ids,
  1930. 'source_nodes': req.source_nodes,
  1931. 'status': req.status,
  1932. 'match_result': req.match_result,
  1933. 'embedding': embedding,
  1934. })
  1935. return {"status": "ok", "id": req.id}
  1936. except Exception as e:
  1937. raise HTTPException(status_code=500, detail=str(e))
  1938. @app.get("/api/requirement")
  1939. def list_requirements(
  1940. status: Optional[str] = Query(None),
  1941. limit: int = Query(100, ge=1, le=1000),
  1942. offset: int = Query(0, ge=0),
  1943. ):
  1944. """列出需求"""
  1945. try:
  1946. results = pg_requirement_store.list_all(limit=limit, offset=offset, status=status)
  1947. total = pg_requirement_store.count(status=status)
  1948. return {"results": results, "total": total}
  1949. except Exception as e:
  1950. raise HTTPException(status_code=500, detail=str(e))
  1951. @app.get("/api/requirement/search")
  1952. async def search_requirements(
  1953. q: str = Query(..., description="查询文本"),
  1954. top_k: int = Query(5, ge=1, le=100),
  1955. ):
  1956. """向量检索需求"""
  1957. try:
  1958. query_embedding = await get_embedding(q)
  1959. results = pg_requirement_store.search(query_embedding, limit=top_k)
  1960. return {"results": results, "count": len(results)}
  1961. except Exception as e:
  1962. raise HTTPException(status_code=500, detail=str(e))
  1963. @app.get("/api/requirement/{req_id}")
  1964. def get_requirement(req_id: str):
  1965. """获取单个需求"""
  1966. try:
  1967. result = pg_requirement_store.get_by_id(req_id)
  1968. if not result:
  1969. raise HTTPException(status_code=404, detail=f"Requirement not found: {req_id}")
  1970. return result
  1971. except HTTPException:
  1972. raise
  1973. except Exception as e:
  1974. raise HTTPException(status_code=500, detail=str(e))
  1975. @app.patch("/api/requirement/{req_id}")
  1976. async def patch_requirement(req_id: str, patch: RequirementPatchIn):
  1977. """更新需求字段"""
  1978. try:
  1979. existing = pg_requirement_store.get_by_id(req_id)
  1980. if not existing:
  1981. raise HTTPException(status_code=404, detail=f"Requirement not found: {req_id}")
  1982. updates = {}
  1983. need_reembed = False
  1984. for field in ('description', 'capability_ids', 'knowledge_ids', 'source_nodes', 'status', 'match_result'):
  1985. value = getattr(patch, field)
  1986. if value is not None:
  1987. updates[field] = value
  1988. if field == 'description':
  1989. need_reembed = True
  1990. if not updates:
  1991. return {"status": "ok", "id": req_id}
  1992. if need_reembed:
  1993. updates['embedding'] = await get_embedding(updates['description'])
  1994. pg_requirement_store.update(req_id, updates)
  1995. return {"status": "ok", "id": req_id}
  1996. except HTTPException:
  1997. raise
  1998. except Exception as e:
  1999. raise HTTPException(status_code=500, detail=str(e))
  2000. @app.delete("/api/requirement/{req_id}")
  2001. def delete_requirement(req_id: str):
  2002. """删除需求"""
  2003. try:
  2004. if not pg_requirement_store.get_by_id(req_id):
  2005. raise HTTPException(status_code=404, detail=f"Requirement not found: {req_id}")
  2006. pg_requirement_store.delete(req_id)
  2007. return {"status": "ok", "id": req_id}
  2008. except HTTPException:
  2009. raise
  2010. except Exception as e:
  2011. raise HTTPException(status_code=500, detail=str(e))
  2012. @app.post("/api/pattern/posts/batch")
  2013. async def proxy_pattern_posts_batch(payload: PostBatchRequest):
  2014. """代理帖子批量查询,避免前端直接请求外部域名失败后静默回退为纯 ID。"""
  2015. post_ids = [pid for pid in payload.post_ids if pid]
  2016. if not post_ids:
  2017. return {"success": True, "posts": []}
  2018. try:
  2019. async with httpx.AsyncClient(timeout=30.0) as client:
  2020. resp = await client.post(
  2021. "https://pattern.aiddit.com/api/pattern/posts/batch",
  2022. json={"post_ids": post_ids},
  2023. )
  2024. resp.raise_for_status()
  2025. return resp.json()
  2026. except httpx.HTTPStatusError as e:
  2027. raise HTTPException(status_code=e.response.status_code, detail="Pattern posts API returned an error")
  2028. except Exception as e:
  2029. raise HTTPException(status_code=502, detail=f"Failed to fetch pattern posts: {e}")
  2030. @app.get("/")
  2031. def frontend():
  2032. """KnowHub 管理前端"""
  2033. index_file = STATIC_DIR / "index.html"
  2034. if not index_file.exists():
  2035. return HTMLResponse("<h1>KnowHub Frontend Not Found</h1><p>Please ensure knowhub/frontend/dist/index.html exists. Run 'yarn build' in frontend directory.</p>", status_code=404)
  2036. return FileResponse(str(index_file))
  2037. # ===== Strategy API =====
  2038. @app.post("/api/strategy", status_code=201)
  2039. async def submit_strategy(strategy: StrategyIn):
  2040. """创建或更新策略(自动填时间戳 + name/description 向量)"""
  2041. try:
  2042. now = int(time.time())
  2043. data = strategy.model_dump()
  2044. data['created_at'] = data.get('created_at') or now
  2045. data['updated_at'] = now
  2046. data['embedding'] = await get_embedding(f"{strategy.name} {strategy.description}")
  2047. pg_strategy_store.insert_or_update(data)
  2048. return {"success": True, "id": strategy.id}
  2049. except Exception as e:
  2050. raise HTTPException(status_code=500, detail=str(e))
  2051. @app.get("/api/strategy")
  2052. def get_strategies(limit: int = 100, offset: int = 0, status: Optional[str] = None):
  2053. try:
  2054. results = pg_strategy_store.list_all(limit=limit, offset=offset, status=status)
  2055. total = pg_strategy_store.count(status=status)
  2056. return {"strategies": results, "total": total}
  2057. except Exception as e:
  2058. raise HTTPException(status_code=500, detail=str(e))
  2059. @app.get("/api/strategy/search")
  2060. async def search_strategies(q: str = Query(...), top_k: int = 20, status: Optional[str] = None):
  2061. try:
  2062. query_embedding = await get_embedding(q)
  2063. results = pg_strategy_store.search(query_embedding, limit=top_k, status=status)
  2064. return {"results": results, "count": len(results)}
  2065. except Exception as e:
  2066. raise HTTPException(status_code=500, detail=str(e))
  2067. @app.get("/api/strategy/{strategy_id:path}")
  2068. def get_strategy(strategy_id: str):
  2069. try:
  2070. result = pg_strategy_store.get_by_id(strategy_id)
  2071. if not result:
  2072. raise HTTPException(status_code=404, detail="Strategy not found")
  2073. return result
  2074. except HTTPException:
  2075. raise
  2076. except Exception as e:
  2077. raise HTTPException(status_code=500, detail=str(e))
  2078. @app.patch("/api/strategy/{strategy_id:path}")
  2079. async def patch_strategy(strategy_id: str, updates: StrategyPatchIn):
  2080. """更新策略字段。若改了 name/description,会重算向量。"""
  2081. try:
  2082. existing = pg_strategy_store.get_by_id(strategy_id)
  2083. if not existing:
  2084. raise HTTPException(status_code=404, detail="Strategy not found")
  2085. update_dict = updates.model_dump(exclude_unset=True)
  2086. if not update_dict:
  2087. return {"success": True}
  2088. if 'name' in update_dict or 'description' in update_dict:
  2089. name = update_dict.get('name', existing.get('name', ''))
  2090. desc = update_dict.get('description', existing.get('description', ''))
  2091. update_dict['embedding'] = await get_embedding(f"{name} {desc}")
  2092. update_dict['updated_at'] = int(time.time())
  2093. pg_strategy_store.update(strategy_id, update_dict)
  2094. return {"success": True}
  2095. except HTTPException:
  2096. raise
  2097. except Exception as e:
  2098. raise HTTPException(status_code=500, detail=str(e))
  2099. @app.delete("/api/strategy/{strategy_id:path}")
  2100. def delete_strategy(strategy_id: str):
  2101. try:
  2102. if not pg_strategy_store.get_by_id(strategy_id):
  2103. raise HTTPException(status_code=404, detail="Strategy not found")
  2104. pg_strategy_store.delete(strategy_id)
  2105. return {"success": True}
  2106. except HTTPException:
  2107. raise
  2108. except Exception as e:
  2109. raise HTTPException(status_code=500, detail=str(e))
  2110. # ===== Relation API =====
  2111. @app.get("/api/relation/{table_name}")
  2112. async def get_relations(table_name: str, request: Request):
  2113. """通用关系表查询接口"""
  2114. allowed_tables = {
  2115. "capability_knowledge",
  2116. "capability_tool",
  2117. "knowledge_relation",
  2118. "knowledge_resource",
  2119. "requirement_capability",
  2120. "requirement_knowledge",
  2121. "tool_knowledge",
  2122. "tool_provider"
  2123. }
  2124. table_name = table_name.lower()
  2125. if table_name not in allowed_tables:
  2126. raise HTTPException(status_code=400, detail="Invalid table name")
  2127. try:
  2128. params = dict(request.query_params)
  2129. where_clauses = []
  2130. values = []
  2131. for k, v in params.items():
  2132. if k in ["limit", "offset"]: continue
  2133. where_clauses.append(f"{k} = %s")
  2134. values.append(v)
  2135. query = f"SELECT * FROM {table_name}"
  2136. if where_clauses:
  2137. query += " WHERE " + " AND ".join(where_clauses)
  2138. limit = int(params.get("limit", 100))
  2139. query += " LIMIT %s"
  2140. values.append(limit)
  2141. cursor = pg_store._get_cursor()
  2142. try:
  2143. cursor.execute(query, tuple(values))
  2144. rows = cursor.fetchall()
  2145. if not rows:
  2146. return {"results": [], "count": 0}
  2147. colnames = [desc[0] for desc in cursor.description]
  2148. results = [dict(zip(colnames, row)) for row in rows]
  2149. return {"results": results, "count": len(results)}
  2150. finally:
  2151. cursor.close()
  2152. except Exception as e:
  2153. raise HTTPException(status_code=500, detail=str(e))
  2154. @app.get("/category_tree.json")
  2155. def serve_category_tree():
  2156. """类别树JSON数据"""
  2157. tree_file = STATIC_DIR / "category_tree.json"
  2158. if not tree_file.exists():
  2159. return {"error": "Not Found"}
  2160. return FileResponse(str(tree_file))
  2161. @app.get("/{frontend_path:path}")
  2162. def frontend_spa_fallback(frontend_path: str):
  2163. """SPA 路由兜底:将非 API 的前端子路径回退到 index.html,由 React Router 处理。"""
  2164. if frontend_path.startswith("api/") or frontend_path.startswith("assets/"):
  2165. raise HTTPException(status_code=404, detail="Not Found")
  2166. # 带扩展名的路径按静态文件处理,不走 SPA fallback。
  2167. if "." in Path(frontend_path).name:
  2168. raise HTTPException(status_code=404, detail="Not Found")
  2169. index_file = STATIC_DIR / "index.html"
  2170. if not index_file.exists():
  2171. return HTMLResponse("<h1>KnowHub Frontend Not Found</h1><p>Please ensure knowhub/frontend/dist/index.html exists. Run 'yarn build' in frontend directory.</p>", status_code=404)
  2172. return FileResponse(str(index_file))
  2173. if __name__ == "__main__":
  2174. import uvicorn
  2175. uvicorn.run(app, host="0.0.0.0", port=9999)