server.py 88 KB

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