server.py 52 KB

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