server.py 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721
  1. """
  2. KnowHub Server
  3. Agent 工具使用经验的共享平台。
  4. FastAPI + SQLite,单文件部署。
  5. """
  6. import os
  7. import re
  8. import json
  9. import sqlite3
  10. import asyncio
  11. import base64
  12. from contextlib import asynccontextmanager
  13. from datetime import datetime, timezone
  14. from typing import Optional
  15. from pathlib import Path
  16. from cryptography.hazmat.primitives.ciphers.aead import AESGCM
  17. from fastapi import FastAPI, HTTPException, Query, Header
  18. from fastapi.responses import HTMLResponse
  19. from pydantic import BaseModel, Field
  20. # 导入 LLM 调用(需要 agent 模块在 Python path 中)
  21. import sys
  22. sys.path.insert(0, str(Path(__file__).parent.parent))
  23. # 加载环境变量
  24. from dotenv import load_dotenv
  25. load_dotenv(Path(__file__).parent.parent / ".env")
  26. from agent.llm.openrouter import openrouter_llm_call
  27. BRAND_NAME = os.getenv("BRAND_NAME", "KnowHub")
  28. BRAND_API_ENV = os.getenv("BRAND_API_ENV", "KNOWHUB_API")
  29. BRAND_DB = os.getenv("BRAND_DB", "knowhub.db")
  30. # 组织密钥配置(格式:org1:key1_base64,org2:key2_base64)
  31. ORG_KEYS_RAW = os.getenv("ORG_KEYS", "")
  32. ORG_KEYS = {}
  33. if ORG_KEYS_RAW:
  34. for pair in ORG_KEYS_RAW.split(","):
  35. if ":" in pair:
  36. org, key_b64 = pair.split(":", 1)
  37. ORG_KEYS[org.strip()] = key_b64.strip()
  38. DB_PATH = Path(__file__).parent / BRAND_DB
  39. # --- 数据库 ---
  40. def get_db() -> sqlite3.Connection:
  41. conn = sqlite3.connect(str(DB_PATH))
  42. conn.row_factory = sqlite3.Row
  43. conn.execute("PRAGMA journal_mode=WAL")
  44. return conn
  45. # --- 加密/解密 ---
  46. def get_org_key(resource_id: str) -> Optional[bytes]:
  47. """从content_id提取组织前缀,返回对应密钥"""
  48. if "/" in resource_id:
  49. org = resource_id.split("/")[0]
  50. if org in ORG_KEYS:
  51. return base64.b64decode(ORG_KEYS[org])
  52. return None
  53. def encrypt_content(resource_id: str, plaintext: str) -> str:
  54. """加密内容,返回格式:encrypted:AES256-GCM:{base64_data}"""
  55. if not plaintext:
  56. return ""
  57. key = get_org_key(resource_id)
  58. if not key:
  59. # 没有配置密钥,明文存储(不推荐)
  60. return plaintext
  61. aesgcm = AESGCM(key)
  62. nonce = os.urandom(12) # 96-bit nonce
  63. ciphertext = aesgcm.encrypt(nonce, plaintext.encode("utf-8"), None)
  64. # 组合 nonce + ciphertext
  65. encrypted_data = nonce + ciphertext
  66. encoded = base64.b64encode(encrypted_data).decode("ascii")
  67. return f"encrypted:AES256-GCM:{encoded}"
  68. def decrypt_content(resource_id: str, encrypted_text: str, provided_key: Optional[str] = None) -> str:
  69. """解密内容,如果没有提供密钥或密钥错误,返回[ENCRYPTED]"""
  70. if not encrypted_text:
  71. return ""
  72. if not encrypted_text.startswith("encrypted:AES256-GCM:"):
  73. # 未加密的内容,直接返回
  74. return encrypted_text
  75. # 提取加密数据
  76. encoded = encrypted_text.split(":", 2)[2]
  77. encrypted_data = base64.b64decode(encoded)
  78. nonce = encrypted_data[:12]
  79. ciphertext = encrypted_data[12:]
  80. # 获取密钥
  81. key = None
  82. if provided_key:
  83. # 使用提供的密钥
  84. try:
  85. key = base64.b64decode(provided_key)
  86. except Exception:
  87. return "[ENCRYPTED]"
  88. else:
  89. # 从配置中获取
  90. key = get_org_key(resource_id)
  91. if not key:
  92. return "[ENCRYPTED]"
  93. try:
  94. aesgcm = AESGCM(key)
  95. plaintext = aesgcm.decrypt(nonce, ciphertext, None)
  96. return plaintext.decode("utf-8")
  97. except Exception:
  98. return "[ENCRYPTED]"
  99. def init_db():
  100. conn = get_db()
  101. conn.execute("""
  102. CREATE TABLE IF NOT EXISTS experiences (
  103. id INTEGER PRIMARY KEY AUTOINCREMENT,
  104. name TEXT NOT NULL,
  105. url TEXT DEFAULT '',
  106. category TEXT DEFAULT '',
  107. task TEXT NOT NULL,
  108. score INTEGER CHECK(score BETWEEN 1 AND 5),
  109. outcome TEXT DEFAULT '',
  110. tips TEXT DEFAULT '',
  111. content_id TEXT DEFAULT '',
  112. submitted_by TEXT DEFAULT '',
  113. created_at TEXT NOT NULL
  114. )
  115. """)
  116. conn.execute("CREATE INDEX IF NOT EXISTS idx_name ON experiences(name)")
  117. conn.execute("""
  118. CREATE TABLE IF NOT EXISTS resources (
  119. id TEXT PRIMARY KEY,
  120. title TEXT DEFAULT '',
  121. body TEXT NOT NULL,
  122. secure_body TEXT DEFAULT '',
  123. content_type TEXT DEFAULT 'text',
  124. metadata TEXT DEFAULT '{}',
  125. sort_order INTEGER DEFAULT 0,
  126. submitted_by TEXT DEFAULT '',
  127. created_at TEXT NOT NULL,
  128. updated_at TEXT DEFAULT ''
  129. )
  130. """)
  131. conn.execute("""
  132. CREATE TABLE IF NOT EXISTS knowledge (
  133. id TEXT PRIMARY KEY,
  134. message_id TEXT DEFAULT '',
  135. types TEXT NOT NULL, -- JSON array: ["strategy", "tool"]
  136. task TEXT NOT NULL,
  137. tags TEXT DEFAULT '{}', -- JSON object: {"category": "...", "domain": "..."}
  138. scopes TEXT DEFAULT '["org:cybertogether"]', -- JSON array
  139. owner TEXT DEFAULT '',
  140. content TEXT NOT NULL,
  141. resource_ids TEXT DEFAULT '[]', -- JSON array: ["code/selenium/login", "credentials/website"]
  142. source TEXT DEFAULT '{}', -- JSON object: {name, category, urls, agent_id, submitted_by, timestamp}
  143. eval TEXT DEFAULT '{}', -- JSON object: {score, helpful, harmful, confidence, histories}
  144. created_at TEXT NOT NULL,
  145. updated_at TEXT DEFAULT ''
  146. )
  147. """)
  148. conn.execute("CREATE INDEX IF NOT EXISTS idx_knowledge_types ON knowledge(types)")
  149. conn.execute("CREATE INDEX IF NOT EXISTS idx_knowledge_task ON knowledge(task)")
  150. conn.execute("CREATE INDEX IF NOT EXISTS idx_knowledge_owner ON knowledge(owner)")
  151. conn.execute("CREATE INDEX IF NOT EXISTS idx_knowledge_scopes ON knowledge(scopes)")
  152. conn.commit()
  153. conn.close()
  154. # --- Models ---
  155. class ResourceIn(BaseModel):
  156. id: str
  157. title: str = ""
  158. body: str
  159. secure_body: str = ""
  160. content_type: str = "text" # text|code|credential|cookie
  161. metadata: dict = {}
  162. sort_order: int = 0
  163. submitted_by: str = ""
  164. class ResourcePatchIn(BaseModel):
  165. """PATCH /api/resource/{id} 请求体"""
  166. title: Optional[str] = None
  167. body: Optional[str] = None
  168. secure_body: Optional[str] = None
  169. content_type: Optional[str] = None
  170. metadata: Optional[dict] = None
  171. # Knowledge Models
  172. class KnowledgeIn(BaseModel):
  173. task: str
  174. content: str
  175. types: list[str] = ["strategy"]
  176. tags: dict = {}
  177. scopes: list[str] = ["org:cybertogether"]
  178. owner: str = ""
  179. message_id: str = ""
  180. resource_ids: list[str] = []
  181. source: dict = {} # {name, category, urls, agent_id, submitted_by, timestamp}
  182. eval: dict = {} # {score, helpful, harmful, confidence}
  183. class KnowledgeOut(BaseModel):
  184. id: str
  185. message_id: str
  186. types: list[str]
  187. task: str
  188. tags: dict
  189. scopes: list[str]
  190. owner: str
  191. content: str
  192. resource_ids: list[str]
  193. source: dict
  194. eval: dict
  195. created_at: str
  196. updated_at: str
  197. class KnowledgeUpdateIn(BaseModel):
  198. add_helpful_case: Optional[dict] = None
  199. add_harmful_case: Optional[dict] = None
  200. update_score: Optional[int] = Field(default=None, ge=1, le=5)
  201. evolve_feedback: Optional[str] = None
  202. class KnowledgePatchIn(BaseModel):
  203. """PATCH /api/knowledge/{id} 请求体(直接字段编辑)"""
  204. task: Optional[str] = None
  205. content: Optional[str] = None
  206. types: Optional[list[str]] = None
  207. tags: Optional[dict] = None
  208. scopes: Optional[list[str]] = None
  209. owner: Optional[str] = None
  210. class MessageExtractIn(BaseModel):
  211. """POST /api/extract 请求体(消息历史提取)"""
  212. messages: list[dict] # [{role: str, content: str}, ...]
  213. agent_id: str = "unknown"
  214. submitted_by: str # 必填,作为 owner
  215. session_key: str = ""
  216. class KnowledgeBatchUpdateIn(BaseModel):
  217. feedback_list: list[dict]
  218. class KnowledgeSearchResponse(BaseModel):
  219. results: list[dict]
  220. count: int
  221. class ResourceNode(BaseModel):
  222. id: str
  223. title: str
  224. class ResourceOut(BaseModel):
  225. id: str
  226. title: str
  227. body: str
  228. secure_body: str = ""
  229. content_type: str = "text"
  230. metadata: dict = {}
  231. toc: Optional[ResourceNode] = None
  232. children: list[ResourceNode]
  233. prev: Optional[ResourceNode] = None
  234. next: Optional[ResourceNode] = None
  235. # --- App ---
  236. @asynccontextmanager
  237. async def lifespan(app: FastAPI):
  238. init_db()
  239. yield
  240. app = FastAPI(title=BRAND_NAME, lifespan=lifespan)
  241. # --- Knowledge API ---
  242. @app.post("/api/resource", status_code=201)
  243. def submit_resource(resource: ResourceIn):
  244. conn = get_db()
  245. try:
  246. now = datetime.now(timezone.utc).isoformat()
  247. # 加密敏感内容
  248. encrypted_secure_body = encrypt_content(resource.id, resource.secure_body)
  249. conn.execute(
  250. "INSERT OR REPLACE INTO resources"
  251. "(id, title, body, secure_body, content_type, metadata, sort_order, submitted_by, created_at, updated_at)"
  252. " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
  253. (
  254. resource.id,
  255. resource.title,
  256. resource.body,
  257. encrypted_secure_body,
  258. resource.content_type,
  259. json.dumps(resource.metadata),
  260. resource.sort_order,
  261. resource.submitted_by,
  262. now,
  263. now,
  264. ),
  265. )
  266. conn.commit()
  267. return {"status": "ok", "id": resource.id}
  268. finally:
  269. conn.close()
  270. @app.get("/api/resource/{resource_id:path}", response_model=ResourceOut)
  271. def get_resource(resource_id: str, x_org_key: Optional[str] = Header(None)):
  272. conn = get_db()
  273. try:
  274. row = conn.execute(
  275. "SELECT id, title, body, secure_body, content_type, metadata, sort_order FROM resources WHERE id = ?",
  276. (resource_id,),
  277. ).fetchone()
  278. if not row:
  279. raise HTTPException(status_code=404, detail=f"Resource not found: {resource_id}")
  280. # 解密敏感内容
  281. secure_body = decrypt_content(resource_id, row["secure_body"] or "", x_org_key)
  282. # 解析metadata
  283. metadata = json.loads(row["metadata"] or "{}")
  284. # 计算导航上下文
  285. root_id = resource_id.split("/")[0] if "/" in resource_id else resource_id
  286. # TOC (根节点)
  287. toc = None
  288. if "/" in resource_id:
  289. toc_row = conn.execute(
  290. "SELECT id, title FROM resources WHERE id = ?",
  291. (root_id,),
  292. ).fetchone()
  293. if toc_row:
  294. toc = ResourceNode(id=toc_row["id"], title=toc_row["title"])
  295. # Children (子节点)
  296. children = []
  297. children_rows = conn.execute(
  298. "SELECT id, title FROM resources WHERE id LIKE ? AND id != ? ORDER BY sort_order",
  299. (f"{resource_id}/%", resource_id),
  300. ).fetchall()
  301. children = [ResourceNode(id=r["id"], title=r["title"]) for r in children_rows]
  302. # Prev/Next (同级节点)
  303. prev_node = None
  304. next_node = None
  305. if "/" in resource_id:
  306. siblings = conn.execute(
  307. "SELECT id, title, sort_order FROM resources WHERE id LIKE ? AND id NOT LIKE ? ORDER BY sort_order",
  308. (f"{root_id}/%", f"{root_id}/%/%"),
  309. ).fetchall()
  310. for i, sib in enumerate(siblings):
  311. if sib["id"] == resource_id:
  312. if i > 0:
  313. prev_node = ResourceNode(id=siblings[i-1]["id"], title=siblings[i-1]["title"])
  314. if i < len(siblings) - 1:
  315. next_node = ResourceNode(id=siblings[i+1]["id"], title=siblings[i+1]["title"])
  316. break
  317. return ResourceOut(
  318. id=row["id"],
  319. title=row["title"],
  320. body=row["body"],
  321. secure_body=secure_body,
  322. content_type=row["content_type"],
  323. metadata=metadata,
  324. toc=toc,
  325. children=children,
  326. prev=prev_node,
  327. next=next_node,
  328. )
  329. finally:
  330. conn.close()
  331. @app.patch("/api/resource/{resource_id:path}")
  332. def patch_resource(resource_id: str, patch: ResourcePatchIn):
  333. """更新resource字段"""
  334. conn = get_db()
  335. try:
  336. # 检查是否存在
  337. row = conn.execute("SELECT id FROM resources WHERE id = ?", (resource_id,)).fetchone()
  338. if not row:
  339. raise HTTPException(status_code=404, detail=f"Resource not found: {resource_id}")
  340. # 构建更新语句
  341. updates = []
  342. params = []
  343. if patch.title is not None:
  344. updates.append("title = ?")
  345. params.append(patch.title)
  346. if patch.body is not None:
  347. updates.append("body = ?")
  348. params.append(patch.body)
  349. if patch.secure_body is not None:
  350. encrypted = encrypt_content(resource_id, patch.secure_body)
  351. updates.append("secure_body = ?")
  352. params.append(encrypted)
  353. if patch.content_type is not None:
  354. updates.append("content_type = ?")
  355. params.append(patch.content_type)
  356. if patch.metadata is not None:
  357. updates.append("metadata = ?")
  358. params.append(json.dumps(patch.metadata))
  359. if not updates:
  360. return {"status": "ok", "message": "No fields to update"}
  361. # 添加updated_at
  362. updates.append("updated_at = ?")
  363. params.append(datetime.now(timezone.utc).isoformat())
  364. # 执行更新
  365. params.append(resource_id)
  366. sql = f"UPDATE resources SET {', '.join(updates)} WHERE id = ?"
  367. conn.execute(sql, params)
  368. conn.commit()
  369. return {"status": "ok", "id": resource_id}
  370. finally:
  371. conn.close()
  372. @app.get("/api/resource")
  373. def list_resources(
  374. content_type: Optional[str] = Query(None),
  375. limit: int = Query(100, ge=1, le=1000)
  376. ):
  377. """列出所有resource"""
  378. conn = get_db()
  379. try:
  380. sql = "SELECT id, title, content_type, metadata, created_at FROM resources"
  381. params = []
  382. if content_type:
  383. sql += " WHERE content_type = ?"
  384. params.append(content_type)
  385. sql += " ORDER BY id LIMIT ?"
  386. params.append(limit)
  387. rows = conn.execute(sql, params).fetchall()
  388. results = []
  389. for row in rows:
  390. results.append({
  391. "id": row["id"],
  392. "title": row["title"],
  393. "content_type": row["content_type"],
  394. "metadata": json.loads(row["metadata"] or "{}"),
  395. "created_at": row["created_at"],
  396. })
  397. return {"results": results, "count": len(results)}
  398. finally:
  399. conn.close()
  400. # --- Knowledge API ---
  401. # ===== Knowledge API =====
  402. # 两阶段检索逻辑
  403. async def _route_knowledge_by_llm(query_text: str, metadata_list: list[dict], k: int = 5) -> list[str]:
  404. """
  405. 第一阶段:语义路由。
  406. 让 LLM 挑选出 2*k 个语义相关的 ID。
  407. """
  408. if not metadata_list:
  409. return []
  410. routing_k = k * 2
  411. routing_data = [
  412. {
  413. "id": m["id"],
  414. "types": m["types"],
  415. "task": m["task"][:100]
  416. } for m in metadata_list
  417. ]
  418. prompt = f"""
  419. 你是一个知识检索专家。根据用户的当前任务需求,从下列原子知识元数据中挑选出最相关的最多 {routing_k} 个知识 ID。
  420. 任务需求:"{query_text}"
  421. 可选知识列表:
  422. {json.dumps(routing_data, ensure_ascii=False, indent=1)}
  423. 请直接输出 ID 列表,用逗号分隔(例如: knowledge-20260302-001, research-20260302-002)。若无相关项请输出 "None"。
  424. """
  425. try:
  426. print(f"\n[Step 1: 知识语义路由] 任务: '{query_text}' | 候选总数: {len(metadata_list)} | 目标提取数: {routing_k}")
  427. response = await openrouter_llm_call(
  428. messages=[{"role": "user", "content": prompt}],
  429. model="google/gemini-2.5-flash-lite"
  430. )
  431. content = response.get("content", "").strip()
  432. selected_ids = [idx.strip() for idx in re.split(r'[,\s]+', content) if idx.strip().startswith(("knowledge-", "research-"))]
  433. print(f"[Step 1: 知识语义路由] LLM 初选 ID ({len(selected_ids)}个): {selected_ids}")
  434. return selected_ids
  435. except Exception as e:
  436. print(f"LLM 知识路由失败: {e}")
  437. return []
  438. async def _search_knowledge_two_stage(
  439. query_text: str,
  440. top_k: int = 5,
  441. min_score: int = 3,
  442. types_filter: Optional[list[str]] = None,
  443. owner_filter: Optional[str] = None,
  444. conn: sqlite3.Connection = None
  445. ) -> list[dict]:
  446. """
  447. 两阶段检索:语义路由 + 质量精排
  448. """
  449. if conn is None:
  450. conn = get_db()
  451. should_close = True
  452. else:
  453. should_close = False
  454. try:
  455. # 阶段 1: 解析所有知识
  456. query = "SELECT * FROM knowledge"
  457. rows = conn.execute(query).fetchall()
  458. if not rows:
  459. return []
  460. content_map = {}
  461. metadata_list = []
  462. for row in rows:
  463. kid = row["id"]
  464. types = json.loads(row["types"])
  465. # 标签过滤
  466. if types_filter:
  467. if not any(t in types for t in types_filter):
  468. continue
  469. # owner 过滤
  470. if owner_filter and row["owner"] != owner_filter:
  471. continue
  472. task = row["task"]
  473. content_text = row["content"]
  474. eval_data = json.loads(row["eval"])
  475. source = json.loads(row["source"])
  476. meta_item = {
  477. "id": kid,
  478. "types": types,
  479. "task": task,
  480. "score": eval_data.get("score", 3),
  481. "helpful": eval_data.get("helpful", 0),
  482. "harmful": eval_data.get("harmful", 0),
  483. }
  484. metadata_list.append(meta_item)
  485. content_map[kid] = {
  486. "task": task,
  487. "content": content_text,
  488. "types": types,
  489. "tags": json.loads(row["tags"]),
  490. "scopes": json.loads(row["scopes"]),
  491. "owner": row["owner"],
  492. "score": meta_item["score"],
  493. "helpful": meta_item["helpful"],
  494. "harmful": meta_item["harmful"],
  495. "message_id": row["message_id"],
  496. "source": source,
  497. "eval": eval_data,
  498. "created_at": row["created_at"],
  499. "updated_at": row["updated_at"]
  500. }
  501. if not metadata_list:
  502. return []
  503. # 阶段 2: 语义路由 (取 2*k)
  504. candidate_ids = await _route_knowledge_by_llm(query_text, metadata_list, k=top_k)
  505. # 阶段 3: 质量精排
  506. print(f"[Step 2: 知识质量精排] 正在根据评分和反馈进行打分...")
  507. scored_items = []
  508. for kid in candidate_ids:
  509. if kid in content_map:
  510. item = content_map[kid]
  511. score = item["score"]
  512. helpful = item["helpful"]
  513. harmful = item["harmful"]
  514. # 计算综合分:基础分 + helpful - harmful*2
  515. quality_score = score + helpful - (harmful * 2.0)
  516. # 过滤门槛
  517. if score < min_score or quality_score < 0:
  518. print(f" - 剔除低质量知识: {kid} (Score: {score}, Helpful: {helpful}, Harmful: {harmful})")
  519. continue
  520. scored_items.append({
  521. "id": kid,
  522. "message_id": item["message_id"],
  523. "types": item["types"],
  524. "task": item["task"],
  525. "tags": item["tags"],
  526. "scopes": item["scopes"],
  527. "owner": item["owner"],
  528. "content": item["content"],
  529. "source": item["source"],
  530. "eval": item["eval"],
  531. "quality_score": quality_score,
  532. "created_at": item["created_at"],
  533. "updated_at": item["updated_at"]
  534. })
  535. # 按照质量分排序
  536. final_sorted = sorted(scored_items, key=lambda x: x["quality_score"], reverse=True)
  537. # 截取最终的 top_k
  538. result = final_sorted[:top_k]
  539. print(f"[Step 2: 知识质量精排] 最终选定知识: {[it['id'] for it in result]}")
  540. print(f"[Knowledge System] 检索结束。\n")
  541. return result
  542. finally:
  543. if should_close:
  544. conn.close()
  545. @app.get("/api/knowledge/search")
  546. async def search_knowledge_api(
  547. q: str = Query(..., description="查询文本"),
  548. top_k: int = Query(default=5, ge=1, le=20),
  549. min_score: int = Query(default=3, ge=1, le=5),
  550. types: Optional[str] = None,
  551. owner: Optional[str] = None
  552. ):
  553. """检索知识(两阶段:语义路由 + 质量精排)"""
  554. conn = get_db()
  555. try:
  556. types_filter = types.split(",") if types else None
  557. results = await _search_knowledge_two_stage(
  558. query_text=q,
  559. top_k=top_k,
  560. min_score=min_score,
  561. types_filter=types_filter,
  562. owner_filter=owner,
  563. conn=conn
  564. )
  565. return {"results": results, "count": len(results)}
  566. finally:
  567. conn.close()
  568. @app.post("/api/knowledge", status_code=201)
  569. def save_knowledge(knowledge: KnowledgeIn):
  570. """保存新知识"""
  571. import uuid
  572. conn = get_db()
  573. try:
  574. # 生成 ID
  575. timestamp = datetime.now().strftime('%Y%m%d-%H%M%S')
  576. random_suffix = uuid.uuid4().hex[:4]
  577. knowledge_id = f"knowledge-{timestamp}-{random_suffix}"
  578. now = datetime.now(timezone.utc).isoformat()
  579. # 设置默认值
  580. owner = knowledge.owner or f"agent:{knowledge.source.get('agent_id', 'unknown')}"
  581. # 准备 source
  582. source = {
  583. "name": knowledge.source.get("name", ""),
  584. "category": knowledge.source.get("category", ""),
  585. "urls": knowledge.source.get("urls", []),
  586. "agent_id": knowledge.source.get("agent_id", "unknown"),
  587. "submitted_by": knowledge.source.get("submitted_by", ""),
  588. "timestamp": now,
  589. "message_id": knowledge.message_id
  590. }
  591. # 准备 eval
  592. eval_data = {
  593. "score": knowledge.eval.get("score", 3),
  594. "helpful": knowledge.eval.get("helpful", 1),
  595. "harmful": knowledge.eval.get("harmful", 0),
  596. "confidence": knowledge.eval.get("confidence", 0.5),
  597. "helpful_history": [],
  598. "harmful_history": []
  599. }
  600. conn.execute(
  601. """INSERT INTO knowledge
  602. (id, message_id, types, task, tags, scopes, owner, content,
  603. resource_ids, source, eval, created_at, updated_at)
  604. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
  605. (
  606. knowledge_id,
  607. knowledge.message_id,
  608. json.dumps(knowledge.types),
  609. knowledge.task,
  610. json.dumps(knowledge.tags),
  611. json.dumps(knowledge.scopes),
  612. owner,
  613. knowledge.content,
  614. json.dumps(knowledge.resource_ids),
  615. json.dumps(source),
  616. json.dumps(eval_data),
  617. now,
  618. now,
  619. ),
  620. )
  621. conn.commit()
  622. return {"status": "ok", "knowledge_id": knowledge_id}
  623. finally:
  624. conn.close()
  625. @app.get("/api/knowledge")
  626. def list_knowledge(
  627. limit: int = Query(default=100, ge=1, le=1000),
  628. types: Optional[str] = None,
  629. scopes: Optional[str] = None,
  630. owner: Optional[str] = None,
  631. tags: Optional[str] = None
  632. ):
  633. """列出知识(支持后端筛选)"""
  634. conn = get_db()
  635. try:
  636. query = "SELECT * FROM knowledge"
  637. params = []
  638. conditions = []
  639. # types 支持多个,用 AND 连接(交集:必须同时包含所有选中的type)
  640. if types:
  641. type_list = [t.strip() for t in types.split(',') if t.strip()]
  642. if type_list:
  643. for t in type_list:
  644. conditions.append("types LIKE ?")
  645. params.append(f"%{t}%")
  646. if scopes:
  647. conditions.append("scopes LIKE ?")
  648. params.append(f"%{scopes}%")
  649. if owner:
  650. conditions.append("owner LIKE ?")
  651. params.append(f"%{owner}%")
  652. # tags 支持多个,用 AND 连接(交集:必须同时包含所有选中的tag)
  653. if tags:
  654. tag_list = [t.strip() for t in tags.split(',') if t.strip()]
  655. if tag_list:
  656. for t in tag_list:
  657. conditions.append("tags LIKE ?")
  658. params.append(f"%{t}%")
  659. if conditions:
  660. query += " WHERE " + " AND ".join(conditions)
  661. query += " ORDER BY created_at DESC LIMIT ?"
  662. params.append(limit)
  663. rows = conn.execute(query, params).fetchall()
  664. results = []
  665. for row in rows:
  666. results.append({
  667. "id": row["id"],
  668. "message_id": row["message_id"],
  669. "types": json.loads(row["types"]),
  670. "task": row["task"],
  671. "tags": json.loads(row["tags"]),
  672. "scopes": json.loads(row["scopes"]),
  673. "owner": row["owner"],
  674. "content": row["content"],
  675. "source": json.loads(row["source"]),
  676. "eval": json.loads(row["eval"]),
  677. "created_at": row["created_at"],
  678. "updated_at": row["updated_at"]
  679. })
  680. return {"results": results, "count": len(results)}
  681. finally:
  682. conn.close()
  683. @app.get("/api/knowledge/meta/tags")
  684. def get_all_tags():
  685. """获取所有已有的 tags"""
  686. conn = get_db()
  687. try:
  688. rows = conn.execute("SELECT tags FROM knowledge").fetchall()
  689. all_tags = set()
  690. for row in rows:
  691. tags_dict = json.loads(row["tags"])
  692. for key in tags_dict.keys():
  693. all_tags.add(key)
  694. return {"tags": sorted(list(all_tags))}
  695. finally:
  696. conn.close()
  697. @app.get("/api/knowledge/{knowledge_id}")
  698. def get_knowledge(knowledge_id: str):
  699. """获取单条知识"""
  700. conn = get_db()
  701. try:
  702. row = conn.execute(
  703. "SELECT * FROM knowledge WHERE id = ?",
  704. (knowledge_id,)
  705. ).fetchone()
  706. if not row:
  707. raise HTTPException(status_code=404, detail=f"Knowledge not found: {knowledge_id}")
  708. return {
  709. "id": row["id"],
  710. "message_id": row["message_id"],
  711. "types": json.loads(row["types"]),
  712. "task": row["task"],
  713. "tags": json.loads(row["tags"]),
  714. "scopes": json.loads(row["scopes"]),
  715. "owner": row["owner"],
  716. "content": row["content"],
  717. "resource_ids": json.loads(row["resource_ids"]),
  718. "source": json.loads(row["source"]),
  719. "eval": json.loads(row["eval"]),
  720. "created_at": row["created_at"],
  721. "updated_at": row["updated_at"]
  722. }
  723. finally:
  724. conn.close()
  725. async def _evolve_knowledge_with_llm(old_content: str, feedback: str) -> str:
  726. """使用 LLM 进行知识进化重写"""
  727. prompt = f"""你是一个 AI Agent 知识库管理员。请根据反馈建议,对现有的知识内容进行重写进化。
  728. 【原知识内容】:
  729. {old_content}
  730. 【实战反馈建议】:
  731. {feedback}
  732. 【重写要求】:
  733. 1. 融合知识:将反馈中的避坑指南、新参数或修正后的选择逻辑融入原知识,使其更具通用性和准确性。
  734. 2. 保持结构:如果原内容有特定格式(如 Markdown、代码示例等),请保持该格式。
  735. 3. 语言:简洁直接,使用中文。
  736. 4. 禁止:严禁输出任何开场白、解释语或额外的 Markdown 标题,直接返回重写后的正文。
  737. """
  738. try:
  739. response = await openrouter_llm_call(
  740. messages=[{"role": "user", "content": prompt}],
  741. model="google/gemini-2.5-flash-lite"
  742. )
  743. evolved = response.get("content", "").strip()
  744. if len(evolved) < 5:
  745. raise ValueError("LLM output too short")
  746. return evolved
  747. except Exception as e:
  748. print(f"知识进化失败,采用追加模式回退: {e}")
  749. return f"{old_content}\n\n---\n[Update {datetime.now().strftime('%Y-%m-%d')}]: {feedback}"
  750. @app.put("/api/knowledge/{knowledge_id}")
  751. async def update_knowledge(knowledge_id: str, update: KnowledgeUpdateIn):
  752. """更新知识评估,支持知识进化"""
  753. conn = get_db()
  754. try:
  755. row = conn.execute("SELECT * FROM knowledge WHERE id = ?", (knowledge_id,)).fetchone()
  756. if not row:
  757. raise HTTPException(status_code=404, detail=f"Knowledge not found: {knowledge_id}")
  758. now = datetime.now(timezone.utc).isoformat()
  759. eval_data = json.loads(row["eval"])
  760. # 更新评分
  761. if update.update_score is not None:
  762. eval_data["score"] = update.update_score
  763. # 添加有效案例
  764. if update.add_helpful_case:
  765. eval_data["helpful"] = eval_data.get("helpful", 0) + 1
  766. if "helpful_history" not in eval_data:
  767. eval_data["helpful_history"] = []
  768. eval_data["helpful_history"].append(update.add_helpful_case)
  769. # 添加有害案例
  770. if update.add_harmful_case:
  771. eval_data["harmful"] = eval_data.get("harmful", 0) + 1
  772. if "harmful_history" not in eval_data:
  773. eval_data["harmful_history"] = []
  774. eval_data["harmful_history"].append(update.add_harmful_case)
  775. # 知识进化
  776. content = row["content"]
  777. if update.evolve_feedback:
  778. content = await _evolve_knowledge_with_llm(content, update.evolve_feedback)
  779. eval_data["helpful"] = eval_data.get("helpful", 0) + 1
  780. # 更新数据库
  781. conn.execute(
  782. "UPDATE knowledge SET content = ?, eval = ?, updated_at = ? WHERE id = ?",
  783. (content, json.dumps(eval_data, ensure_ascii=False), now, knowledge_id)
  784. )
  785. conn.commit()
  786. return {"status": "ok", "knowledge_id": knowledge_id}
  787. finally:
  788. conn.close()
  789. @app.patch("/api/knowledge/{knowledge_id}")
  790. def patch_knowledge(knowledge_id: str, patch: KnowledgePatchIn):
  791. """直接编辑知识字段"""
  792. conn = get_db()
  793. try:
  794. row = conn.execute("SELECT * FROM knowledge WHERE id = ?", (knowledge_id,)).fetchone()
  795. if not row:
  796. raise HTTPException(status_code=404, detail=f"Knowledge not found: {knowledge_id}")
  797. updates = []
  798. params = []
  799. if patch.task is not None:
  800. updates.append("task = ?")
  801. params.append(patch.task)
  802. if patch.content is not None:
  803. updates.append("content = ?")
  804. params.append(patch.content)
  805. if patch.types is not None:
  806. updates.append("types = ?")
  807. params.append(json.dumps(patch.types, ensure_ascii=False))
  808. if patch.tags is not None:
  809. updates.append("tags = ?")
  810. params.append(json.dumps(patch.tags, ensure_ascii=False))
  811. if patch.scopes is not None:
  812. updates.append("scopes = ?")
  813. params.append(json.dumps(patch.scopes, ensure_ascii=False))
  814. if patch.owner is not None:
  815. updates.append("owner = ?")
  816. params.append(patch.owner)
  817. if not updates:
  818. return {"status": "ok", "knowledge_id": knowledge_id}
  819. now = datetime.now(timezone.utc).isoformat()
  820. updates.append("updated_at = ?")
  821. params.append(now)
  822. params.append(knowledge_id)
  823. query = f"UPDATE knowledge SET {', '.join(updates)} WHERE id = ?"
  824. conn.execute(query, params)
  825. conn.commit()
  826. return {"status": "ok", "knowledge_id": knowledge_id}
  827. finally:
  828. conn.close()
  829. @app.post("/api/knowledge/batch_update")
  830. async def batch_update_knowledge(batch: KnowledgeBatchUpdateIn):
  831. """批量反馈知识有效性"""
  832. if not batch.feedback_list:
  833. return {"status": "ok", "updated": 0}
  834. conn = get_db()
  835. try:
  836. # 先处理无需进化的,收集需要进化的
  837. evolution_tasks = [] # [(knowledge_id, old_content, feedback, eval_data)]
  838. simple_updates = [] # [(knowledge_id, is_effective, eval_data)]
  839. for item in batch.feedback_list:
  840. knowledge_id = item.get("knowledge_id")
  841. is_effective = item.get("is_effective")
  842. feedback = item.get("feedback", "")
  843. if not knowledge_id:
  844. continue
  845. row = conn.execute("SELECT * FROM knowledge WHERE id = ?", (knowledge_id,)).fetchone()
  846. if not row:
  847. continue
  848. eval_data = json.loads(row["eval"])
  849. if is_effective and feedback:
  850. evolution_tasks.append((knowledge_id, row["content"], feedback, eval_data))
  851. else:
  852. simple_updates.append((knowledge_id, is_effective, eval_data))
  853. # 执行简单更新
  854. now = datetime.now(timezone.utc).isoformat()
  855. for knowledge_id, is_effective, eval_data in simple_updates:
  856. if is_effective:
  857. eval_data["helpful"] = eval_data.get("helpful", 0) + 1
  858. else:
  859. eval_data["harmful"] = eval_data.get("harmful", 0) + 1
  860. conn.execute(
  861. "UPDATE knowledge SET eval = ?, updated_at = ? WHERE id = ?",
  862. (json.dumps(eval_data, ensure_ascii=False), now, knowledge_id)
  863. )
  864. # 并发执行知识进化
  865. if evolution_tasks:
  866. print(f"🧬 并发处理 {len(evolution_tasks)} 条知识进化...")
  867. evolved_results = await asyncio.gather(
  868. *[_evolve_knowledge_with_llm(old, fb) for _, old, fb, _ in evolution_tasks]
  869. )
  870. for (knowledge_id, _, _, eval_data), evolved_content in zip(evolution_tasks, evolved_results):
  871. eval_data["helpful"] = eval_data.get("helpful", 0) + 1
  872. conn.execute(
  873. "UPDATE knowledge SET content = ?, eval = ?, updated_at = ? WHERE id = ?",
  874. (evolved_content, json.dumps(eval_data, ensure_ascii=False), now, knowledge_id)
  875. )
  876. conn.commit()
  877. return {"status": "ok", "updated": len(simple_updates) + len(evolution_tasks)}
  878. finally:
  879. conn.close()
  880. @app.post("/api/knowledge/slim")
  881. async def slim_knowledge(model: str = "google/gemini-2.5-flash-lite"):
  882. """知识库瘦身:合并语义相似知识"""
  883. conn = get_db()
  884. try:
  885. rows = conn.execute("SELECT * FROM knowledge").fetchall()
  886. if len(rows) < 2:
  887. return {"status": "ok", "message": f"知识库仅有 {len(rows)} 条,无需瘦身"}
  888. # 构造发给大模型的内容
  889. entries_text = ""
  890. for row in rows:
  891. eval_data = json.loads(row["eval"])
  892. types = json.loads(row["types"])
  893. entries_text += f"[ID: {row['id']}] [Types: {','.join(types)}] "
  894. entries_text += f"[Helpful: {eval_data.get('helpful', 0)}, Harmful: {eval_data.get('harmful', 0)}] [Score: {eval_data.get('score', 3)}]\n"
  895. entries_text += f"Task: {row['task']}\n"
  896. entries_text += f"Content: {row['content'][:200]}...\n\n"
  897. prompt = f"""你是一个 AI Agent 知识库管理员。以下是当前知识库的全部条目,请执行瘦身操作:
  898. 【任务】:
  899. 1. 识别语义高度相似或重复的知识,将它们合并为一条更精炼、更通用的知识。
  900. 2. 合并时保留 helpful 最高的那条的 ID(helpful 取各条之和)。
  901. 3. 对于独立的、无重复的知识,保持原样不动。
  902. 【当前知识库】:
  903. {entries_text}
  904. 【输出格式要求】:
  905. 严格按以下格式输出每条知识,条目之间用 === 分隔:
  906. ID: <保留的id>
  907. TYPES: <逗号分隔的type列表>
  908. HELPFUL: <合并后的helpful计数>
  909. HARMFUL: <合并后的harmful计数>
  910. SCORE: <评分>
  911. TASK: <任务描述>
  912. CONTENT: <合并后的知识内容>
  913. ===
  914. 最后输出合并报告:
  915. REPORT: 原有 X 条,合并后 Y 条,精简了 Z 条。
  916. 禁止输出任何开场白或解释。"""
  917. print(f"\n[知识瘦身] 正在调用 {model} 分析 {len(rows)} 条知识...")
  918. response = await openrouter_llm_call(
  919. messages=[{"role": "user", "content": prompt}],
  920. model=model
  921. )
  922. content = response.get("content", "").strip()
  923. if not content:
  924. raise HTTPException(status_code=500, detail="LLM 返回为空")
  925. # 解析大模型输出
  926. report_line = ""
  927. new_entries = []
  928. blocks = [b.strip() for b in content.split("===") if b.strip()]
  929. for block in blocks:
  930. if block.startswith("REPORT:"):
  931. report_line = block
  932. continue
  933. lines = block.split("\n")
  934. kid, types, helpful, harmful, score, task, content_lines = None, [], 0, 0, 3, "", []
  935. current_field = None
  936. for line in lines:
  937. if line.startswith("ID:"):
  938. kid = line[3:].strip()
  939. current_field = None
  940. elif line.startswith("TYPES:"):
  941. types_str = line[6:].strip()
  942. types = [t.strip() for t in types_str.split(",") if t.strip()]
  943. current_field = None
  944. elif line.startswith("HELPFUL:"):
  945. try:
  946. helpful = int(line[8:].strip())
  947. except Exception:
  948. helpful = 0
  949. current_field = None
  950. elif line.startswith("HARMFUL:"):
  951. try:
  952. harmful = int(line[8:].strip())
  953. except Exception:
  954. harmful = 0
  955. current_field = None
  956. elif line.startswith("SCORE:"):
  957. try:
  958. score = int(line[6:].strip())
  959. except Exception:
  960. score = 3
  961. current_field = None
  962. elif line.startswith("TASK:"):
  963. task = line[5:].strip()
  964. current_field = "task"
  965. elif line.startswith("CONTENT:"):
  966. content_lines.append(line[8:].strip())
  967. current_field = "content"
  968. elif current_field == "task":
  969. task += "\n" + line
  970. elif current_field == "content":
  971. content_lines.append(line)
  972. if kid and content_lines:
  973. new_entries.append({
  974. "id": kid,
  975. "types": types if types else ["strategy"],
  976. "helpful": helpful,
  977. "harmful": harmful,
  978. "score": score,
  979. "task": task.strip(),
  980. "content": "\n".join(content_lines).strip()
  981. })
  982. if not new_entries:
  983. raise HTTPException(status_code=500, detail="解析大模型输出失败")
  984. # 原子化写回
  985. now = datetime.now(timezone.utc).isoformat()
  986. conn.execute("DELETE FROM knowledge")
  987. for e in new_entries:
  988. eval_data = {
  989. "score": e["score"],
  990. "helpful": e["helpful"],
  991. "harmful": e["harmful"],
  992. "confidence": 0.9,
  993. "helpful_history": [],
  994. "harmful_history": []
  995. }
  996. source = {
  997. "name": "slim",
  998. "category": "exp",
  999. "urls": [],
  1000. "agent_id": "slim",
  1001. "submitted_by": "system",
  1002. "timestamp": now
  1003. }
  1004. conn.execute(
  1005. """INSERT INTO knowledge
  1006. (id, message_id, types, task, tags, scopes, owner, content, source, eval, created_at, updated_at)
  1007. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
  1008. (
  1009. e["id"],
  1010. "",
  1011. json.dumps(e["types"]),
  1012. e["task"],
  1013. json.dumps({}),
  1014. json.dumps(["org:cybertogether"]),
  1015. "agent:slim",
  1016. e["content"],
  1017. json.dumps(source, ensure_ascii=False),
  1018. json.dumps(eval_data, ensure_ascii=False),
  1019. now,
  1020. now
  1021. )
  1022. )
  1023. conn.commit()
  1024. result_msg = f"瘦身完成:{len(rows)} → {len(new_entries)} 条知识"
  1025. if report_line:
  1026. result_msg += f"\n{report_line}"
  1027. print(f"[知识瘦身] {result_msg}")
  1028. return {"status": "ok", "before": len(rows), "after": len(new_entries), "report": report_line}
  1029. finally:
  1030. conn.close()
  1031. @app.post("/api/extract")
  1032. async def extract_knowledge_from_messages(extract_req: MessageExtractIn):
  1033. """从消息历史中提取知识(LLM 分析)"""
  1034. if not extract_req.submitted_by:
  1035. raise HTTPException(status_code=400, detail="submitted_by is required")
  1036. messages = extract_req.messages
  1037. if not messages or len(messages) == 0:
  1038. return {"status": "ok", "extracted_count": 0, "knowledge_ids": []}
  1039. # 构造消息历史文本
  1040. messages_text = ""
  1041. for msg in messages:
  1042. role = msg.get("role", "unknown")
  1043. content = msg.get("content", "")
  1044. messages_text += f"[{role}]: {content}\n\n"
  1045. # LLM 提取知识
  1046. prompt = f"""你是一个知识提取专家。请从以下 Agent 对话历史中提取有价值的知识。
  1047. 【对话历史】:
  1048. {messages_text}
  1049. 【提取要求】:
  1050. 1. 识别对话中的关键知识点(工具使用经验、问题解决方案、最佳实践、踩坑经验等)
  1051. 2. 每条知识必须包含:
  1052. - task: 任务场景描述(在什么情况下,要完成什么目标)
  1053. - content: 核心知识内容(具体可操作的方法、注意事项)
  1054. - types: 知识类型(从 strategy/tool/user_profile/usecase/definition/plan 中选择)
  1055. - score: 评分 1-5(根据知识的价值和可操作性)
  1056. 3. 只提取有实际价值的知识,不要提取泛泛而谈的内容,一次就成功或比较简单的经验就不要记录了。
  1057. 4. 如果没有值得提取的知识,返回空列表
  1058. 【输出格式】:
  1059. 严格按以下 JSON 格式输出,每条知识之间用逗号分隔:
  1060. [
  1061. {{
  1062. "task": "任务场景描述",
  1063. "content": "核心知识内容",
  1064. "types": ["strategy"],
  1065. "score": 4
  1066. }},
  1067. {{
  1068. "task": "另一个任务场景",
  1069. "content": "另一个知识内容",
  1070. "types": ["tool"],
  1071. "score": 5
  1072. }}
  1073. ]
  1074. 如果没有知识,输出: []
  1075. **注意**:只记录经过多次尝试、或经过用户指导才成功的知识,一次就成功或比较简单的经验就不要记录了。
  1076. 禁止输出任何解释或额外文本,只输出 JSON 数组。"""
  1077. try:
  1078. print(f"\n[Extract] 正在从 {len(messages)} 条消息中提取知识...")
  1079. response = await openrouter_llm_call(
  1080. messages=[{"role": "user", "content": prompt}],
  1081. model="google/gemini-2.5-flash-lite"
  1082. )
  1083. content = response.get("content", "").strip()
  1084. # 尝试解析 JSON
  1085. # 移除可能的 markdown 代码块标记
  1086. if content.startswith("```json"):
  1087. content = content[7:]
  1088. if content.startswith("```"):
  1089. content = content[3:]
  1090. if content.endswith("```"):
  1091. content = content[:-3]
  1092. content = content.strip()
  1093. extracted_knowledge = json.loads(content)
  1094. if not isinstance(extracted_knowledge, list):
  1095. raise ValueError("LLM output is not a list")
  1096. # 保存提取的知识
  1097. conn = get_db()
  1098. knowledge_ids = []
  1099. now = datetime.now(timezone.utc).isoformat()
  1100. try:
  1101. for item in extracted_knowledge:
  1102. task = item.get("task", "")
  1103. knowledge_content = item.get("content", "")
  1104. types = item.get("types", ["strategy"])
  1105. score = item.get("score", 3)
  1106. if not task or not knowledge_content:
  1107. continue
  1108. # 生成 ID
  1109. import uuid
  1110. timestamp = datetime.now().strftime('%Y%m%d-%H%M%S')
  1111. random_suffix = uuid.uuid4().hex[:4]
  1112. knowledge_id = f"knowledge-{timestamp}-{random_suffix}"
  1113. # 准备数据
  1114. source = {
  1115. "name": "message_extraction",
  1116. "category": "exp",
  1117. "urls": [],
  1118. "agent_id": extract_req.agent_id,
  1119. "submitted_by": extract_req.submitted_by,
  1120. "timestamp": now,
  1121. "session_key": extract_req.session_key
  1122. }
  1123. eval_data = {
  1124. "score": score,
  1125. "helpful": 1,
  1126. "harmful": 0,
  1127. "confidence": 0.7,
  1128. "helpful_history": [],
  1129. "harmful_history": []
  1130. }
  1131. # 插入数据库
  1132. conn.execute(
  1133. """INSERT INTO knowledge
  1134. (id, message_id, types, task, tags, scopes, owner, content,
  1135. source, eval, created_at, updated_at)
  1136. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
  1137. (
  1138. knowledge_id,
  1139. "",
  1140. json.dumps(types),
  1141. task,
  1142. json.dumps({}),
  1143. json.dumps(["org:cybertogether"]),
  1144. extract_req.submitted_by,
  1145. knowledge_content,
  1146. json.dumps(source, ensure_ascii=False),
  1147. json.dumps(eval_data, ensure_ascii=False),
  1148. now,
  1149. now,
  1150. ),
  1151. )
  1152. knowledge_ids.append(knowledge_id)
  1153. conn.commit()
  1154. print(f"[Extract] 成功提取并保存 {len(knowledge_ids)} 条知识")
  1155. return {
  1156. "status": "ok",
  1157. "extracted_count": len(knowledge_ids),
  1158. "knowledge_ids": knowledge_ids
  1159. }
  1160. finally:
  1161. conn.close()
  1162. except json.JSONDecodeError as e:
  1163. print(f"[Extract] JSON 解析失败: {e}")
  1164. print(f"[Extract] LLM 输出: {content[:500]}")
  1165. return {"status": "error", "error": "Failed to parse LLM output", "extracted_count": 0}
  1166. except Exception as e:
  1167. print(f"[Extract] 提取失败: {e}")
  1168. return {"status": "error", "error": str(e), "extracted_count": 0}
  1169. @app.get("/", response_class=HTMLResponse)
  1170. def frontend():
  1171. """KnowHub 管理前端"""
  1172. return """<!DOCTYPE html>
  1173. <html lang="zh-CN">
  1174. <head>
  1175. <meta charset="UTF-8">
  1176. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  1177. <title>KnowHub 管理</title>
  1178. <script src="https://cdn.tailwindcss.com"></script>
  1179. </head>
  1180. <body class="bg-gray-50">
  1181. <div class="container mx-auto px-4 py-8 max-w-7xl">
  1182. <div class="flex justify-between items-center mb-8">
  1183. <h1 class="text-3xl font-bold text-gray-800">KnowHub 全局知识库</h1>
  1184. <button onclick="openAddModal()" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg">
  1185. + 新增知识
  1186. </button>
  1187. </div>
  1188. <!-- 筛选栏 -->
  1189. <div class="bg-white rounded-lg shadow p-6 mb-6">
  1190. <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
  1191. <div>
  1192. <label class="block text-sm font-medium text-gray-700 mb-2">类型 (Types)</label>
  1193. <div class="space-y-2">
  1194. <label class="flex items-center"><input type="checkbox" value="strategy" class="mr-2 type-filter"> Strategy</label>
  1195. <label class="flex items-center"><input type="checkbox" value="tool" class="mr-2 type-filter"> Tool</label>
  1196. <label class="flex items-center"><input type="checkbox" value="user_profile" class="mr-2 type-filter"> User Profile</label>
  1197. <label class="flex items-center"><input type="checkbox" value="usecase" class="mr-2 type-filter"> Usecase</label>
  1198. <label class="flex items-center"><input type="checkbox" value="definition" class="mr-2 type-filter"> Definition</label>
  1199. <label class="flex items-center"><input type="checkbox" value="plan" class="mr-2 type-filter"> Plan</label>
  1200. </div>
  1201. </div>
  1202. <div>
  1203. <label class="block text-sm font-medium text-gray-700 mb-2">Tags</label>
  1204. <div id="tagsFilterContainer" class="space-y-2 max-h-40 overflow-y-auto">
  1205. <p class="text-sm text-gray-500">加载中...</p>
  1206. </div>
  1207. </div>
  1208. <div>
  1209. <label class="block text-sm font-medium text-gray-700 mb-2">Owner</label>
  1210. <input type="text" id="ownerFilter" placeholder="输入 owner" class="w-full border rounded px-3 py-2">
  1211. </div>
  1212. <div>
  1213. <label class="block text-sm font-medium text-gray-700 mb-2">Scopes</label>
  1214. <input type="text" id="scopesFilter" placeholder="输入 scope" class="w-full border rounded px-3 py-2">
  1215. </div>
  1216. </div>
  1217. <button onclick="applyFilters()" class="mt-4 bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded">
  1218. 应用筛选
  1219. </button>
  1220. </div>
  1221. <!-- 知识列表 -->
  1222. <div id="knowledgeList" class="space-y-4"></div>
  1223. </div>
  1224. <!-- 新增/编辑 Modal -->
  1225. <div id="modal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4">
  1226. <div class="bg-white rounded-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto p-6">
  1227. <h2 id="modalTitle" class="text-2xl font-bold mb-4">新增知识</h2>
  1228. <form id="knowledgeForm" class="space-y-4">
  1229. <input type="hidden" id="editId">
  1230. <div>
  1231. <label class="block text-sm font-medium mb-1">Task *</label>
  1232. <input type="text" id="taskInput" required class="w-full border rounded px-3 py-2">
  1233. </div>
  1234. <div>
  1235. <label class="block text-sm font-medium mb-1">Content *</label>
  1236. <textarea id="contentInput" required rows="6" class="w-full border rounded px-3 py-2"></textarea>
  1237. </div>
  1238. <div>
  1239. <label class="block text-sm font-medium mb-1">Types (多选)</label>
  1240. <div class="space-y-1">
  1241. <label class="flex items-center"><input type="checkbox" value="strategy" class="mr-2 type-checkbox"> Strategy</label>
  1242. <label class="flex items-center"><input type="checkbox" value="tool" class="mr-2 type-checkbox"> Tool</label>
  1243. <label class="flex items-center"><input type="checkbox" value="user_profile" class="mr-2 type-checkbox"> User Profile</label>
  1244. <label class="flex items-center"><input type="checkbox" value="usecase" class="mr-2 type-checkbox"> Usecase</label>
  1245. <label class="flex items-center"><input type="checkbox" value="definition" class="mr-2 type-checkbox"> Definition</label>
  1246. <label class="flex items-center"><input type="checkbox" value="plan" class="mr-2 type-checkbox"> Plan</label>
  1247. </div>
  1248. </div>
  1249. <div>
  1250. <label class="block text-sm font-medium mb-1">Tags (JSON)</label>
  1251. <textarea id="tagsInput" rows="2" placeholder='{"key": "value"}' class="w-full border rounded px-3 py-2"></textarea>
  1252. </div>
  1253. <div>
  1254. <label class="block text-sm font-medium mb-1">Scopes (逗号分隔)</label>
  1255. <input type="text" id="scopesInput" placeholder="org:cybertogether" class="w-full border rounded px-3 py-2">
  1256. </div>
  1257. <div>
  1258. <label class="block text-sm font-medium mb-1">Owner</label>
  1259. <input type="text" id="ownerInput" class="w-full border rounded px-3 py-2">
  1260. </div>
  1261. <div class="flex gap-2 pt-4">
  1262. <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded">保存</button>
  1263. <button type="button" onclick="closeModal()" class="bg-gray-300 hover:bg-gray-400 px-6 py-2 rounded">取消</button>
  1264. </div>
  1265. </form>
  1266. </div>
  1267. </div>
  1268. <script>
  1269. let allKnowledge = [];
  1270. let availableTags = [];
  1271. async function loadTags() {
  1272. const res = await fetch('/api/knowledge/meta/tags');
  1273. const data = await res.json();
  1274. availableTags = data.tags;
  1275. renderTagsFilter();
  1276. }
  1277. function renderTagsFilter() {
  1278. const container = document.getElementById('tagsFilterContainer');
  1279. if (availableTags.length === 0) {
  1280. container.innerHTML = '<p class="text-sm text-gray-500">暂无 tags</p>';
  1281. return;
  1282. }
  1283. container.innerHTML = availableTags.map(tag =>
  1284. `<label class="flex items-center"><input type="checkbox" value="${escapeHtml(tag)}" class="mr-2 tag-filter"> ${escapeHtml(tag)}</label>`
  1285. ).join('');
  1286. }
  1287. async function loadKnowledge() {
  1288. const params = new URLSearchParams();
  1289. params.append('limit', '1000');
  1290. const selectedTypes = Array.from(document.querySelectorAll('.type-filter:checked')).map(el => el.value);
  1291. if (selectedTypes.length > 0) {
  1292. params.append('types', selectedTypes.join(','));
  1293. }
  1294. const selectedTags = Array.from(document.querySelectorAll('.tag-filter:checked')).map(el => el.value);
  1295. if (selectedTags.length > 0) {
  1296. params.append('tags', selectedTags.join(','));
  1297. }
  1298. const ownerFilter = document.getElementById('ownerFilter').value.trim();
  1299. if (ownerFilter) {
  1300. params.append('owner', ownerFilter);
  1301. }
  1302. const scopesFilter = document.getElementById('scopesFilter').value.trim();
  1303. if (scopesFilter) {
  1304. params.append('scopes', scopesFilter);
  1305. }
  1306. try {
  1307. const res = await fetch(`/api/knowledge?${params.toString()}`);
  1308. if (!res.ok) {
  1309. console.error('加载失败:', res.status, res.statusText);
  1310. document.getElementById('knowledgeList').innerHTML = '<p class="text-red-500 text-center py-8">加载失败,请刷新页面重试</p>';
  1311. return;
  1312. }
  1313. const data = await res.json();
  1314. allKnowledge = data.results || [];
  1315. renderKnowledge(allKnowledge);
  1316. } catch (error) {
  1317. console.error('加载错误:', error);
  1318. document.getElementById('knowledgeList').innerHTML = '<p class="text-red-500 text-center py-8">加载错误: ' + error.message + '</p>';
  1319. }
  1320. }
  1321. function applyFilters() {
  1322. loadKnowledge();
  1323. }
  1324. function renderKnowledge(list) {
  1325. const container = document.getElementById('knowledgeList');
  1326. if (list.length === 0) {
  1327. container.innerHTML = '<p class="text-gray-500 text-center py-8">暂无知识</p>';
  1328. return;
  1329. }
  1330. container.innerHTML = list.map(k => {
  1331. // 确保types是数组
  1332. let types = [];
  1333. if (Array.isArray(k.types)) {
  1334. types = k.types;
  1335. } else if (typeof k.types === 'string') {
  1336. // 如果是JSON字符串(以[开头),尝试解析
  1337. if (k.types.startsWith('[')) {
  1338. try {
  1339. types = JSON.parse(k.types);
  1340. } catch (e) {
  1341. console.error('解析types失败:', k.types, e);
  1342. types = [k.types];
  1343. }
  1344. } else {
  1345. // 如果是普通字符串,包装成数组
  1346. types = [k.types];
  1347. }
  1348. }
  1349. const eval_data = k.eval || {};
  1350. return `
  1351. <div class="bg-white rounded-lg shadow p-6 hover:shadow-lg transition cursor-pointer" onclick="openEditModal('${k.id}')">
  1352. <div class="flex justify-between items-start mb-2">
  1353. <div class="flex gap-2 flex-wrap">
  1354. ${types.map(t => `<span class="bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded">${t}</span>`).join('')}
  1355. </div>
  1356. <span class="text-sm text-gray-500">${eval_data.score || 3}/5</span>
  1357. </div>
  1358. <h3 class="text-lg font-semibold text-gray-800 mb-2">${escapeHtml(k.task)}</h3>
  1359. <p class="text-sm text-gray-600 mb-2">${escapeHtml(k.content.substring(0, 150))}${k.content.length > 150 ? '...' : ''}</p>
  1360. <div class="flex justify-between text-xs text-gray-500">
  1361. <span>Owner: ${k.owner || 'N/A'}</span>
  1362. <span>${new Date(k.created_at).toLocaleDateString()}</span>
  1363. </div>
  1364. </div>
  1365. `;
  1366. }).join('');
  1367. }
  1368. function openAddModal() {
  1369. document.getElementById('modalTitle').textContent = '新增知识';
  1370. document.getElementById('knowledgeForm').reset();
  1371. document.getElementById('editId').value = '';
  1372. document.querySelectorAll('.type-checkbox').forEach(el => el.checked = false);
  1373. document.getElementById('modal').classList.remove('hidden');
  1374. }
  1375. async function openEditModal(id) {
  1376. const k = allKnowledge.find(item => item.id === id);
  1377. if (!k) return;
  1378. document.getElementById('modalTitle').textContent = '编辑知识';
  1379. document.getElementById('editId').value = k.id;
  1380. document.getElementById('taskInput').value = k.task;
  1381. document.getElementById('contentInput').value = k.content;
  1382. document.getElementById('tagsInput').value = JSON.stringify(k.tags);
  1383. document.getElementById('scopesInput').value = k.scopes.join(', ');
  1384. document.getElementById('ownerInput').value = k.owner;
  1385. document.querySelectorAll('.type-checkbox').forEach(el => {
  1386. el.checked = k.types.includes(el.value);
  1387. });
  1388. document.getElementById('modal').classList.remove('hidden');
  1389. }
  1390. function closeModal() {
  1391. document.getElementById('modal').classList.add('hidden');
  1392. }
  1393. document.getElementById('knowledgeForm').addEventListener('submit', async (e) => {
  1394. e.preventDefault();
  1395. const editId = document.getElementById('editId').value;
  1396. const task = document.getElementById('taskInput').value;
  1397. const content = document.getElementById('contentInput').value;
  1398. const types = Array.from(document.querySelectorAll('.type-checkbox:checked')).map(el => el.value);
  1399. const tagsText = document.getElementById('tagsInput').value.trim();
  1400. const scopesText = document.getElementById('scopesInput').value.trim();
  1401. const owner = document.getElementById('ownerInput').value.trim();
  1402. let tags = {};
  1403. if (tagsText) {
  1404. try {
  1405. tags = JSON.parse(tagsText);
  1406. } catch (e) {
  1407. alert('Tags JSON 格式错误');
  1408. return;
  1409. }
  1410. }
  1411. const scopes = scopesText ? scopesText.split(',').map(s => s.trim()).filter(s => s) : ['org:cybertogether'];
  1412. if (editId) {
  1413. // 编辑
  1414. const res = await fetch(`/api/knowledge/${editId}`, {
  1415. method: 'PATCH',
  1416. headers: {'Content-Type': 'application/json'},
  1417. body: JSON.stringify({task, content, types, tags, scopes, owner})
  1418. });
  1419. if (!res.ok) {
  1420. alert('更新失败');
  1421. return;
  1422. }
  1423. } else {
  1424. // 新增
  1425. const res = await fetch('/api/knowledge', {
  1426. method: 'POST',
  1427. headers: {'Content-Type': 'application/json'},
  1428. body: JSON.stringify({task, content, types, tags, scopes, owner})
  1429. });
  1430. if (!res.ok) {
  1431. alert('新增失败');
  1432. return;
  1433. }
  1434. }
  1435. closeModal();
  1436. await loadKnowledge();
  1437. });
  1438. function escapeHtml(text) {
  1439. const div = document.createElement('div');
  1440. div.textContent = text;
  1441. return div.innerHTML;
  1442. }
  1443. loadTags();
  1444. loadKnowledge();
  1445. </script>
  1446. </body>
  1447. </html>"""
  1448. if __name__ == "__main__":
  1449. import uvicorn
  1450. uvicorn.run(app, host="0.0.0.0", port=9999)