server.py 57 KB

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