feat(agent-v1.1): 智能体系统第一阶段 —— 数据层 + 7 个工具 + 选择界面
按《智能体系统需求文档 v1.1》实现。这一阶段打通了"内核数据 → 接口 → 界面"整条链路。 ## 内核 - 新增 agentdb.py:智能体系统的 SQLite 层(记忆 / 情绪 / Token 统计 / Skill 绑定)。 **为什么这次用 SQLite 而别处还是 JSON**(store.py 顶上写着 JSON 的理由): 记忆是"条目无上限 + 每轮全量注入 + 要 LIKE 检索 + 要行级改删", 那三条都指向 SQLite;而设置/会话/智能体的量级仍然是"几个到几十个"、 且要人肉可读,继续留在 JSON。分界线写在 agentdb.py 的文件头。 - 新增 agent_context.py:按需求附录 C 拼 system prompt (人设 → skills → worldview → emotion → memory → peer_emotions,**空段整段删掉**,每轮重拼)。 - 新增 agent_tools.py:7 个内置工具(memory_add/update/forget/search、 memory_suggest_summary、emotion_set、get_token_usage)。 走进程内实现是因为它们要读写 agent.db,而电脑端的文件工具是子进程。 共享记忆的写入限权(只能改自己写的)+ pinned 保护都在这里。 - 新增 agent_api.py:20+ 个 HTTP 接口(记忆 CRUD/导出导入/整理、情绪、 Token 用量、世界观/模型列表/Skill 的 CRUD 与包导入导出)。 app.py 的老 /api/agents 三个路由删掉,统一由它处理(顺便补上"内置不能删")。 - store.py:Agent 字段按类型分开的 _apply_agent_patch(create/update 共用)、 三种资源的通用 CRUD、create_agent 改用 **UUID**(需求附录 A)、 delete_agent 清理绑定关系但**不删记忆**。 - Token:usage 从"只留最后一轮"改成**累加**(多轮工具调用的消耗是大头, 以前全丢);落库时按轮记在消息上(会话级 = 加起来,重新生成不会虚高) + 计入智能体累计(按模型分桶、输入输出分开);超限时**发起前**拦住, 附一条带语气的告别消息并给界面明确的 token_limit 错误(需求 3.1)。 - 会议节点的 system prompt 也改用 agent_context(以前是自己拼的, 同一个智能体在会议里没有记忆/情绪/世界观)。 - doubao_entry:web_search.py 补进 BUNDLED_TOOL_FILES(对拍脚本抓出的清单不一致)。 ## 安卓 - AgentSelectScreen:智能体选择界面(需求第二章)—— 左列表 + 右侧四层叠加(背景/主体边框/角色图/介绍边框), 1.5s 四阶段切换动画(0.3 出 / 0.5 间隔 / 0.4 边框 / 0.3 入,方向按列表顺序, 连点立即打断并从当前视觉状态续走),圆形「更多」按钮,默认资源回退。 - AssetImage:本地图片显示。**不引 Coil/Glide**(项目零第三方依赖)—— PNG/JPG 走 BitmapFactory,GIF 走 ImageDecoder(API28+ 能播动图,以下退化成首帧), SVG 走 WebView(原生解不了)。 - TokenUsageScreen / MemoryScreen:用量详情(输入输出分列、按模型分行、 限额进度、配了单价才估费用)+ 记忆管理(情绪编辑、整理、导入导出、 pinned 开关、共享记忆提示)。 - Models.kt / KernelClient.kt / AppViewModel.kt:全部新字段与新接口。 - 入口:抽屉「智能体」→ 选择界面;聊天页顶栏点名字 → 选择界面 (以前点开的是「模型」面板 —— 那是"换脑子"不是"换人")。 - 需求文档给的两张默认资源图进 res/drawable(2.3MB)。 ## 验证 - 新增 scripts/probe-agent-system.py:11 节 60+ 项断言,**不装机**跑完整链路 (临时数据目录 + 假 Handler)。覆盖:UUID 主键、记忆增删改查检索、 pinned 保护、共享记忆与写入限权、system prompt 五段注入与顺序、 20 多个接口、包的导出导入边界(模型引用/世界观/限额**不进包**)、 记忆导入的合并去重、资源 CRUD。全绿。 - 装机验证:选择界面四层叠加、默认资源回退、切换动画与高亮。 ## 还没做(下一阶段) 世界观/Skill/模型列表的管理界面、对话页会话级用量显示、智能体编辑界面扩展 (介绍/外观/模型引用/世界观/限额/技能绑定)、包的导入导出界面、 幻觉调用检测、不支持 function calling 的兼容降级、Node 端跟上。
This commit is contained in:
871
android/kernel/agent_api.py
Normal file
871
android/kernel/agent_api.py
Normal file
@@ -0,0 +1,871 @@
|
||||
"""智能体系统的 HTTP 接口(需求 v1.1)。
|
||||
|
||||
## 为什么单独一个模块
|
||||
|
||||
`app.py` 已经 1800 行,而这一批有二十多个接口。抽出来之后:
|
||||
|
||||
· 路由写得下、看得清(一段一段对应需求的章节)
|
||||
· `app.py` 只要在它的路由链里加一句 `agent_api.handle(...)` 就行
|
||||
· 这一批接口的**数据源**(`store` 的 JSON + `agentdb` 的 SQLite)也集中在一处,
|
||||
以后换存储只改这里
|
||||
|
||||
## 路由总表
|
||||
|
||||
GET/POST /api/agents 列表 / 新建
|
||||
PATCH/DELETE /api/agents/<id> 改 / 删
|
||||
GET /api/agents/<id>/memories 记忆列表
|
||||
POST /api/agents/<id>/memories 手动加一条
|
||||
POST /api/agents/<id>/memories/summarize AI 整理(一次独立 LLM 调用)
|
||||
GET/POST /api/agents/<id>/memories/export|import 记忆 JSON 导出/导入
|
||||
GET /api/agents/<id>/suggestion AI 提的"该整理记忆了"
|
||||
GET/PUT /api/agents/<id>/emotion 情绪
|
||||
POST /api/agents/<id>/skills 绑定 Skill(整体替换)
|
||||
GET /api/agents/<id>/usage Token 用量
|
||||
POST /api/agents/<id>/usage/reset 清零
|
||||
GET /api/agents/<id>/package 导出智能体包(base64 zip)
|
||||
POST /api/agents/import 导入智能体包
|
||||
PATCH/DELETE /api/memories/<mid> 改 / 删一条
|
||||
POST /api/memories/<mid>/pin 标记「必须保留」
|
||||
GET/POST /api/worldviews (+ /<id>) 世界观 CRUD
|
||||
GET/POST /api/model-entries (+ /<id>) 全局模型列表 CRUD
|
||||
GET/POST /api/skills (+ /<id>) Skill CRUD
|
||||
GET/POST /api/skills/export|import Skill JSON
|
||||
GET/POST /api/worldviews/<id>/package|import
|
||||
|
||||
★ `/api/model-entries` 而不是 `/api/models`:后者早就被"**拉上游**的可用模型列表"
|
||||
占了(`app.py` 的 `/api/models` 会去请求提供商的 `/v1/models`)。
|
||||
两个东西完全不是一回事,不能共用一个路径。
|
||||
"""
|
||||
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
import agentdb
|
||||
import paths
|
||||
import store
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 小工具
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
_SAFE_NAME = re.compile(r'[^\w.\-\u4e00-\u9fff]+')
|
||||
|
||||
|
||||
def _safe_segment(name: str) -> str:
|
||||
"""
|
||||
包里的文件名/目录名清洗。
|
||||
|
||||
★ 防路径穿越:zip 里完全可以有一条叫 `../../settings.json` 的条目,
|
||||
照原样拼路径就会**写出数据目录之外**。所以只保留字母数字下划线
|
||||
连字符点号和中文,其余一律换成下划线。
|
||||
"""
|
||||
base = os.path.basename(str(name or '').replace('\\', '/'))
|
||||
cleaned = _SAFE_NAME.sub('_', base).strip('._')
|
||||
return cleaned[:80] or 'file'
|
||||
|
||||
|
||||
def _asset_dir(owner_id: str) -> str:
|
||||
d = os.path.join(paths.get().agent_assets_dir, _safe_segment(owner_id))
|
||||
os.makedirs(d, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def _read_zip(data: bytes) -> dict:
|
||||
"""
|
||||
解一个 zip,返回 `{相对路径: 字节}`。
|
||||
|
||||
★ 只收**文件**、忽略目录;条目数/总大小有上限(防 zip 炸弹:
|
||||
一个 10KB 的 zip 能解出几十 GB)。
|
||||
"""
|
||||
out = {}
|
||||
total = 0
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as z:
|
||||
for info in z.infolist():
|
||||
if info.is_dir():
|
||||
continue
|
||||
if len(out) >= 200:
|
||||
raise ValueError('包里文件太多了(上限 200 个)')
|
||||
total += info.file_size
|
||||
if total > 60 * 1024 * 1024:
|
||||
raise ValueError('包解出来太大了(上限 60MB)')
|
||||
out[info.filename] = z.read(info)
|
||||
return out
|
||||
|
||||
|
||||
def _zip_of(files: dict) -> bytes:
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, 'w', zipfile.ZIP_DEFLATED) as z:
|
||||
for name, data in files.items():
|
||||
z.writestr(name, data)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _pick_asset(files: dict, wanted: str):
|
||||
"""
|
||||
按 `smartInfo.json` 里写的文件名找那个资源。
|
||||
|
||||
★ 找不到时**退一步**按扩展名猜一个:用户手写的包经常是
|
||||
`"front": "角色图.png"` 但实际文件叫 `character.png` ——
|
||||
严格匹配的话整张图就白丢了,而"图没显示"用户只会觉得功能坏了。
|
||||
"""
|
||||
if not wanted:
|
||||
return None
|
||||
want = os.path.basename(str(wanted).replace('\\', '/')).lower()
|
||||
for name, data in files.items():
|
||||
if os.path.basename(name).lower() == want:
|
||||
return name, data
|
||||
stem, ext = os.path.splitext(want)
|
||||
if not ext:
|
||||
return None
|
||||
for name, data in files.items():
|
||||
if os.path.splitext(name)[1].lower() == ext:
|
||||
return name, data
|
||||
return None
|
||||
|
||||
|
||||
def _save_assets(owner_id: str, files: dict, image_spec: dict) -> dict:
|
||||
"""
|
||||
把包里的四件套落到磁盘,返回新的 image 字段(**存绝对路径**)。
|
||||
|
||||
★ 为什么存路径而不是存"包内文件名":包解完就没了(用户不会留着那个 zip),
|
||||
而界面每次都要显示它 —— 存文件名的话每次都得再去找一遍包。
|
||||
"""
|
||||
out = {}
|
||||
target_dir = _asset_dir(owner_id)
|
||||
for key in ('front', 'back', 'border-main', 'border-info'):
|
||||
hit = _pick_asset(files, (image_spec or {}).get(key))
|
||||
if not hit:
|
||||
continue
|
||||
name, data = hit
|
||||
dest = os.path.join(target_dir, f'{key}-{_safe_segment(name)}')
|
||||
with open(dest, 'wb') as fh:
|
||||
fh.write(data)
|
||||
out[key] = dest
|
||||
return out
|
||||
|
||||
|
||||
def _llm_once(settings: dict, agent: dict, system: str, user: str):
|
||||
"""
|
||||
跑一次**独立**的 LLM 调用,返回 `(文本, usage)`。
|
||||
|
||||
给"AI 整理记忆"用(需求 3.2:一次独立 LLM 调用)。
|
||||
★ 不用工具、不开思考 —— 整理是个纯文本活,开思考只是白花时间和 token。
|
||||
"""
|
||||
import providers
|
||||
|
||||
provider = store.provider_info(settings, agent)
|
||||
chunks = []
|
||||
usage = None
|
||||
for ev in providers.stream_chat(
|
||||
provider=provider.get('provider') or settings.get('provider'),
|
||||
base_url=provider.get('baseUrl'),
|
||||
api_key=settings.get('apiKey') or '',
|
||||
model=provider.get('model'),
|
||||
messages=[
|
||||
{'role': 'system', 'content': system},
|
||||
{'role': 'user', 'content': user},
|
||||
],
|
||||
temperature=0.2,
|
||||
thinking_level='off',
|
||||
):
|
||||
kind = ev.get('type')
|
||||
if kind == 'text':
|
||||
chunks.append(ev['text'])
|
||||
elif kind == 'usage':
|
||||
import agent_loop
|
||||
|
||||
usage = agent_loop.add_usage(usage, ev.get('usage'))
|
||||
return ''.join(chunks), usage
|
||||
|
||||
|
||||
def _extract_json(text: str):
|
||||
"""
|
||||
从模型回复里抠出 JSON。
|
||||
|
||||
★ 必须容错:模型几乎总会把 JSON 包在 ```json 代码块里,
|
||||
直接 `json.loads` 十次有八次失败。而且失败的表现是"整理功能报错",
|
||||
用户根本不知道是模型多打了三个反引号。
|
||||
"""
|
||||
raw = (text or '').strip()
|
||||
fence = re.search(r'```(?:json)?\s*([\s\S]*?)```', raw)
|
||||
if fence:
|
||||
raw = fence.group(1).strip()
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
# 再退一步:从第一个 [ 或 { 到最后一个 ] 或 }
|
||||
for left, right in (('[', ']'), ('{', '}')):
|
||||
i, j = raw.find(left), raw.rfind(right)
|
||||
if i >= 0 and j > i:
|
||||
try:
|
||||
return json.loads(raw[i:j + 1])
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
raise ValueError('模型没有返回能解析的 JSON')
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 记忆
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def _memory_space(agent: dict) -> str:
|
||||
return agentdb.scope_of(agent.get('id') or '', agent.get('worldviewId') or '')
|
||||
|
||||
|
||||
def _memory_payload(agent: dict) -> dict:
|
||||
"""一个记忆空间的完整视图(列表 + 情绪 + 用量),界面进页面时一次拿够"""
|
||||
scope = _memory_space(agent)
|
||||
items = agentdb.memory_list(scope)
|
||||
return {
|
||||
'ok': True,
|
||||
'shared': bool(agent.get('worldviewId')), # 是不是共享空间(界面要提示)
|
||||
'worldviewId': agent.get('worldviewId') or '',
|
||||
'memories': items,
|
||||
'emotion': agentdb.emotion_get(agent.get('id') or ''),
|
||||
'suggestion': store.peek_summary_suggestion(agent.get('id') or ''),
|
||||
}
|
||||
|
||||
|
||||
MEMORY_SUMMARY_SYSTEM = '\n'.join([
|
||||
'你是一个记忆整理器。用户会给你一份记忆清单(JSON 数组),',
|
||||
'你要把**零散、重复、可以合并**的条目压缩成更少、更完整的几条。',
|
||||
'',
|
||||
'规则:',
|
||||
'1. 只输出一个 JSON 数组,每项 {"title": "...", "content": "..."},不要任何别的文字。',
|
||||
'2. **不许编造**:只能合并和改写已有的信息,不能新增原始记忆里没有的事实。',
|
||||
'3. 合并同类项:说同一件事的几条合成一条;时间上连续的经过可以并成一条。',
|
||||
'4. 具体的数字、名字、日期**必须保留**("他每月话费 36"不能变成"他有话费支出")。',
|
||||
'5. 条数控制在原来的 1/2 到 2/3;如果本来就不多(少于 8 条),原样返回即可。',
|
||||
'6. 用中文,标题短(10 字以内),正文说清楚。',
|
||||
])
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 路由
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def handle(handler, pathname: str, method: str) -> bool:
|
||||
"""
|
||||
处理一个请求。返回 True = 已经响应过了。
|
||||
|
||||
[handler] 是 `app.py` 的那个 Handler 实例(借用它的 send_json / read_json_body)。
|
||||
"""
|
||||
seg = [s for s in (pathname or '').split('/') if s]
|
||||
# 全都是 /api/... 开头的
|
||||
if len(seg) < 2 or seg[0] != 'api':
|
||||
return False
|
||||
|
||||
def body():
|
||||
"""
|
||||
解析请求体。
|
||||
|
||||
★ 做成**函数**而不是进来就解析:GET 请求没有 body,提前解析会抛异常。
|
||||
★ 但注意:往下传的时候必须**调用它**(`body()`)——
|
||||
直接把函数对象当 dict 传,报的是 `'function' object has no attribute 'get'`,
|
||||
而那个错看起来像"字段名写错了"。这里踩过一次。
|
||||
"""
|
||||
try:
|
||||
return handler.read_json_body()
|
||||
except Exception: # noqa: BLE001
|
||||
return {}
|
||||
|
||||
def err(code: int, msg: str):
|
||||
handler.send_json(code, {'ok': False, 'error': msg})
|
||||
|
||||
try:
|
||||
# ---------------- 智能体 ----------------
|
||||
if seg[1] == 'agents' and len(seg) == 2:
|
||||
if method == 'GET':
|
||||
handler.send_json(200, {'ok': True, 'agents': store.list_agents()})
|
||||
return True
|
||||
if method == 'POST':
|
||||
handler.send_json(200, {'ok': True, 'agent': store.create_agent(body())})
|
||||
return True
|
||||
|
||||
if seg[1] == 'agents' and len(seg) == 3 and seg[2] == 'import' and method == 'POST':
|
||||
return _import_agent(handler, body(), err)
|
||||
|
||||
if seg[1] == 'agents' and len(seg) == 3:
|
||||
aid = seg[2]
|
||||
if method == 'PATCH':
|
||||
updated = store.update_agent(aid, body())
|
||||
if updated is None:
|
||||
err(404, '没有这个智能体')
|
||||
else:
|
||||
handler.send_json(200, {'ok': True, 'agent': updated})
|
||||
return True
|
||||
if method == 'DELETE':
|
||||
# ★ 内置智能体不给删:删了内核下次读 agents.json 会**重建**它,
|
||||
# 用户看到"删了又回来"(界面也拦,但接口不能只靠界面拦)
|
||||
target = store.get_agent(aid)
|
||||
if target and target.get('builtin'):
|
||||
err(400, '内置智能体不能删除(删了会被自动重建)')
|
||||
return True
|
||||
handler.send_json(200, {'ok': True, 'deleted': store.delete_agent(aid)})
|
||||
return True
|
||||
|
||||
# ---------------- 记忆(挂在智能体下) ----------------
|
||||
if seg[1] == 'agents' and len(seg) >= 4 and seg[3] == 'memories':
|
||||
return _memories(handler, method, seg, body, err)
|
||||
|
||||
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'suggestion':
|
||||
agent = store.get_agent(seg[2])
|
||||
if not agent:
|
||||
err(404, '没有这个智能体')
|
||||
return True
|
||||
handler.send_json(200, {
|
||||
'ok': True,
|
||||
'suggestion': store.peek_summary_suggestion(agent.get('id') or ''),
|
||||
})
|
||||
return True
|
||||
|
||||
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'emotion':
|
||||
agent = store.get_agent(seg[2])
|
||||
if not agent:
|
||||
err(404, '没有这个智能体')
|
||||
return True
|
||||
if method == 'GET':
|
||||
handler.send_json(200, {'ok': True, 'emotion': agentdb.emotion_get(agent['id'])})
|
||||
return True
|
||||
if method in ('PUT', 'POST'):
|
||||
emo = str(body().get('emotion') or '')
|
||||
agentdb.emotion_set(agent['id'], emo[:200])
|
||||
handler.send_json(200, {'ok': True, 'emotion': emo[:200]})
|
||||
return True
|
||||
|
||||
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'skills':
|
||||
agent = store.get_agent(seg[2])
|
||||
if not agent:
|
||||
err(404, '没有这个智能体')
|
||||
return True
|
||||
if method == 'GET':
|
||||
handler.send_json(200, {'ok': True, 'skillIds': agentdb.skills_of(agent['id'])})
|
||||
return True
|
||||
if method in ('PUT', 'POST'):
|
||||
ids = body().get('skillIds') or []
|
||||
agentdb.bind_skills(agent['id'], ids if isinstance(ids, list) else [])
|
||||
handler.send_json(200, {'ok': True, 'skillIds': agentdb.skills_of(agent['id'])})
|
||||
return True
|
||||
|
||||
# ---------------- Token 用量 ----------------
|
||||
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'usage':
|
||||
agent = store.get_agent(seg[2])
|
||||
if not agent:
|
||||
err(404, '没有这个智能体')
|
||||
return True
|
||||
if method == 'GET':
|
||||
handler.send_json(200, {'ok': True, **_usage_payload(agent)})
|
||||
return True
|
||||
if method == 'POST':
|
||||
agentdb.token_reset(agent['id'])
|
||||
handler.send_json(200, {'ok': True, **_usage_payload(agent)})
|
||||
return True
|
||||
|
||||
# ---------------- 智能体包 ----------------
|
||||
if seg[1] == 'agents' and len(seg) == 4 and seg[3] == 'package' and method == 'GET':
|
||||
return _export_agent(handler, seg[2], err)
|
||||
|
||||
# ---------------- 单条记忆 ----------------
|
||||
if seg[1] == 'memories' and len(seg) == 3:
|
||||
mid = seg[2]
|
||||
item = agentdb.memory_get(mid)
|
||||
if not item:
|
||||
err(404, '没有这条记忆')
|
||||
return True
|
||||
if method == 'PATCH':
|
||||
b = body()
|
||||
# ★ 界面上改是**用户**在改,不受"只能改自己写的"限制
|
||||
# (那条限制是给 AI 的工具定的,见 agent_tools.py)
|
||||
updated = agentdb.memory_update(
|
||||
mid,
|
||||
title=b.get('title') if 'title' in b else None,
|
||||
content=b.get('content') if 'content' in b else None,
|
||||
)
|
||||
handler.send_json(200, {'ok': True, 'memory': updated})
|
||||
return True
|
||||
if method == 'DELETE':
|
||||
agentdb.memory_forget(mid)
|
||||
handler.send_json(200, {'ok': True, 'deleted': True})
|
||||
return True
|
||||
|
||||
if seg[1] == 'memories' and len(seg) == 4 and seg[3] == 'pin' and method == 'POST':
|
||||
ok = agentdb.memory_set_pinned(seg[2], bool(body().get('pinned', True)))
|
||||
handler.send_json(200, {'ok': ok})
|
||||
return True
|
||||
|
||||
# ---------------- 世界观 / 模型列表 / Skill ----------------
|
||||
res = _resource_route(handler, seg, method, body, err)
|
||||
if res is not None:
|
||||
return res
|
||||
|
||||
except Exception as exc: # noqa: BLE001 - 接口层不能把内核带崩
|
||||
print(f'[agent_api] {pathname} 出错:{exc}', file=sys.stderr)
|
||||
err(500, f'{type(exc).__name__}: {exc}')
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 记忆的具体路由
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def _memories(handler, method: str, seg: list, body, err) -> bool:
|
||||
agent = store.get_agent(seg[2])
|
||||
if not agent:
|
||||
err(404, '没有这个智能体')
|
||||
return True
|
||||
tail = seg[4:]
|
||||
|
||||
# /memories
|
||||
if not tail:
|
||||
if method == 'GET':
|
||||
handler.send_json(200, _memory_payload(agent))
|
||||
return True
|
||||
if method == 'POST':
|
||||
b = body()
|
||||
item = agentdb.memory_add(
|
||||
scope=_memory_space(agent),
|
||||
title=str(b.get('title') or ''),
|
||||
content=str(b.get('content') or ''),
|
||||
# 用户手动加的:author 记成自己(空 = 不是任何智能体写的)
|
||||
author_agent=str(b.get('author_agent') or ''),
|
||||
)
|
||||
handler.send_json(200, {'ok': True, 'memory': item})
|
||||
return True
|
||||
|
||||
# /memories/summarize —— AI 整理(需求 3.2)
|
||||
if tail == ['summarize'] and method == 'POST':
|
||||
return _summarize(handler, agent, err)
|
||||
|
||||
# /memories/export
|
||||
if tail == ['export'] and method == 'GET':
|
||||
payload = _memory_export(agent)
|
||||
handler.send_json(200, {'ok': True, **payload})
|
||||
return True
|
||||
|
||||
# /memories/import
|
||||
if tail == ['import'] and method == 'POST':
|
||||
return _memory_import(handler, agent, body(), err)
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def _memory_export(agent: dict) -> dict:
|
||||
"""
|
||||
导出成需求 3.4 那个格式。
|
||||
|
||||
★ **不含 `author_agent`**:需求原话"导出不含 author_agent(导入后全部归属当前智能体)"。
|
||||
带上它的话,把记忆导给另一个智能体之后,它会在共享空间里
|
||||
顶着"别人写的"身份出现、连自己都改不了。
|
||||
"""
|
||||
scope = _memory_space(agent)
|
||||
items = [
|
||||
{'title': m.get('title') or '', 'content': m.get('content') or '',
|
||||
'pinned': bool(m.get('pinned'))}
|
||||
for m in agentdb.memory_list(scope)
|
||||
]
|
||||
return {
|
||||
'type': 'world-memory' if agent.get('worldviewId') else 'agent-memory',
|
||||
'version': 1,
|
||||
'name': agent.get('name') or '',
|
||||
'smartMemory': items,
|
||||
'Emotion': agentdb.emotion_get(agent.get('id') or ''),
|
||||
}
|
||||
|
||||
|
||||
def _memory_import(handler, agent: dict, body: dict, err) -> bool:
|
||||
"""
|
||||
导入记忆(需求 3.4)。默认**合并**,可选**覆盖**。
|
||||
|
||||
合并按**标题去重**:标题相同的跳过(保留现有的)。
|
||||
"""
|
||||
payload = body.get('data') if isinstance(body.get('data'), dict) else body
|
||||
if not isinstance(payload, dict) or 'smartMemory' not in payload:
|
||||
err(400, '这不是一个记忆文件(缺少 smartMemory 字段)')
|
||||
return True
|
||||
if payload.get('type') and payload['type'] not in ('agent-memory', 'world-memory'):
|
||||
err(400, f'不认识的文件类型:{payload.get("type")}')
|
||||
return True
|
||||
|
||||
incoming = payload.get('smartMemory')
|
||||
if not isinstance(incoming, list):
|
||||
err(400, 'smartMemory 必须是数组')
|
||||
return True
|
||||
|
||||
scope = _memory_space(agent)
|
||||
mode = str(body.get('mode') or 'merge').lower()
|
||||
before = len(agentdb.memory_list(scope))
|
||||
|
||||
if mode == 'replace':
|
||||
agentdb.memory_replace_all(scope, incoming, keep_pinned=False)
|
||||
added = len(agentdb.memory_list(scope)) - 0
|
||||
skipped = 0
|
||||
else:
|
||||
existing = {(m.get('title') or '').strip() for m in agentdb.memory_list(scope)}
|
||||
added = skipped = 0
|
||||
for it in incoming:
|
||||
if not isinstance(it, dict):
|
||||
continue
|
||||
title = str(it.get('title') or '').strip()
|
||||
if title and title in existing:
|
||||
skipped += 1
|
||||
continue
|
||||
agentdb.memory_add(
|
||||
scope=scope,
|
||||
title=title,
|
||||
content=str(it.get('content') or ''),
|
||||
author_agent=agent.get('id') or '',
|
||||
)
|
||||
existing.add(title)
|
||||
added += 1
|
||||
|
||||
emotion_kept = True
|
||||
if mode == 'replace' and payload.get('Emotion') is not None:
|
||||
# 覆盖模式连情绪一起换(需求 3.4);合并模式保留当前值
|
||||
agentdb.emotion_set(agent.get('id') or '', str(payload.get('Emotion') or ''))
|
||||
emotion_kept = False
|
||||
|
||||
return _send_json_ok(handler, {
|
||||
'mode': mode,
|
||||
'added': added,
|
||||
'skipped': skipped,
|
||||
'before': before,
|
||||
'after': len(agentdb.memory_list(scope)),
|
||||
'emotionReplaced': not emotion_kept,
|
||||
})
|
||||
|
||||
|
||||
def _summarize(handler, agent: dict, err) -> bool:
|
||||
"""
|
||||
AI 整理记忆(需求 3.2)。
|
||||
|
||||
流程:全部记忆 + pinned 清单一并给模型 → 拿回压缩后的列表 →
|
||||
整体写回(**pinned 的原样保留**)。
|
||||
|
||||
★ Token 消耗计入该智能体统计(需求明确要求)。
|
||||
★ **不受限额约束**(需求 3.1 的豁免条款)—— 额度用完了还得能整理记忆,
|
||||
否则用户的记忆就永远是一团乱麻、还解不开。
|
||||
"""
|
||||
scope = _memory_space(agent)
|
||||
items = agentdb.memory_list(scope)
|
||||
if not items:
|
||||
return _send_json_ok(handler, {'summarized': False, 'reason': '还没有记忆可以整理'})
|
||||
|
||||
settings = store.read_settings()
|
||||
plain = [
|
||||
{'title': m.get('title') or '', 'content': m.get('content') or '',
|
||||
'pinned': bool(m.get('pinned'))}
|
||||
for m in items
|
||||
]
|
||||
try:
|
||||
text, usage = _llm_once(
|
||||
settings, agent, MEMORY_SUMMARY_SYSTEM,
|
||||
json.dumps(plain, ensure_ascii=False, indent=1),
|
||||
)
|
||||
merged = _extract_json(text)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
err(500, f'整理失败:{exc}')
|
||||
return True
|
||||
|
||||
if isinstance(merged, dict):
|
||||
merged = merged.get('smartMemory') or merged.get('items') or []
|
||||
if not isinstance(merged, list):
|
||||
err(500, '模型返回的不是列表')
|
||||
return True
|
||||
|
||||
# ★ pinned 的那几条**不能进这次替换**(需求 3.2:原样保留、不参与合并)
|
||||
kept = [m for m in items if m.get('pinned')]
|
||||
kept_titles = {(m.get('title') or '').strip() for m in kept}
|
||||
clean = [
|
||||
{'title': str(x.get('title') or ''), 'content': str(x.get('content') or '')}
|
||||
for x in merged
|
||||
if isinstance(x, dict) and (x.get('title') or x.get('content'))
|
||||
and (str(x.get('title') or '').strip() not in kept_titles)
|
||||
]
|
||||
if not clean:
|
||||
err(500, '模型返回的列表是空的,为了不丢数据这次不写回')
|
||||
return True
|
||||
|
||||
agentdb.memory_replace_all(scope, clean, keep_pinned=True)
|
||||
|
||||
# 计入用量(记失败不影响结果)
|
||||
try:
|
||||
import agent_loop
|
||||
|
||||
i, o = agent_loop.usage_pair(usage)
|
||||
if i or o:
|
||||
model = (store.provider_info(settings, agent) or {}).get('model') or ''
|
||||
agentdb.token_add(agent.get('id') or '', model, i, o)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f'[agent_api] 整理记忆的用量没记上:{exc}', file=sys.stderr)
|
||||
|
||||
store.take_summary_suggestion(agent.get('id') or '')
|
||||
return _send_json_ok(handler, {
|
||||
'summarized': True,
|
||||
'before': len(items),
|
||||
'after': len(agentdb.memory_list(scope)),
|
||||
'keptPinned': len(kept),
|
||||
})
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 三种资源的通用路由
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
_RES_PATH = {
|
||||
'worldviews': 'worldviews',
|
||||
'model-entries': 'models',
|
||||
'skills': 'skills',
|
||||
}
|
||||
|
||||
|
||||
def _resource_route(handler, seg: list, method: str, body, err):
|
||||
if seg[1] not in _RES_PATH:
|
||||
return None
|
||||
name = _RES_PATH[seg[1]]
|
||||
|
||||
# 包 / JSON 的导入导出(世界观包、Skill 文件)
|
||||
if len(seg) == 3 and seg[2] == 'import' and method == 'POST':
|
||||
return _resource_import(handler, name, body(), err)
|
||||
if len(seg) == 4 and seg[3] == 'package' and method == 'GET':
|
||||
return _resource_export(handler, name, seg[2], err)
|
||||
if len(seg) == 4 and seg[3] == 'export' and method == 'GET':
|
||||
return _resource_export(handler, name, seg[2], err)
|
||||
|
||||
if len(seg) == 2:
|
||||
if method == 'GET':
|
||||
handler.send_json(200, {'ok': True, 'items': store.list_resource(name)})
|
||||
return True
|
||||
if method == 'POST':
|
||||
handler.send_json(200, {'ok': True, 'item': store.create_resource(name, body())})
|
||||
return True
|
||||
|
||||
if len(seg) == 3:
|
||||
rid = seg[2]
|
||||
if method == 'PATCH':
|
||||
updated = store.update_resource(name, rid, body())
|
||||
if updated is None:
|
||||
err(404, '没有这一项')
|
||||
else:
|
||||
handler.send_json(200, {'ok': True, 'item': updated})
|
||||
return True
|
||||
if method == 'DELETE':
|
||||
handler.send_json(200, {'ok': True, 'deleted': store.delete_resource(name, rid)})
|
||||
return True
|
||||
return None
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 导入导出
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def _usage_payload(agent: dict) -> dict:
|
||||
usage = agentdb.token_usage(agent.get('id') or '')
|
||||
try:
|
||||
limit = int(float(agent.get('tokenLimit') or 0))
|
||||
except (TypeError, ValueError):
|
||||
limit = 0
|
||||
used = usage['total']['input'] + usage['total']['output']
|
||||
# 单价(元/千 Token):在**全局模型列表**里配,填了才估费用
|
||||
price = 0.0
|
||||
mid = agent.get('modelId') or ''
|
||||
if mid:
|
||||
entry = store.get_resource('models', mid) or {}
|
||||
try:
|
||||
price = float(entry.get('pricePerK') or 0)
|
||||
except (TypeError, ValueError):
|
||||
price = 0.0
|
||||
return {
|
||||
'agentId': agent.get('id') or '',
|
||||
'name': agent.get('name') or '',
|
||||
'input': usage['total']['input'],
|
||||
'output': usage['total']['output'],
|
||||
'total': used,
|
||||
'byModel': usage['byModel'],
|
||||
'limit': limit,
|
||||
'remaining': None if limit <= 0 else max(0, limit - used),
|
||||
'pricePerK': price,
|
||||
'cost': round(used / 1000.0 * price, 4) if price > 0 else None,
|
||||
}
|
||||
|
||||
|
||||
def _export_agent(handler, agent_id: str, err) -> bool:
|
||||
"""导出智能体包(需求 2.5:zip,只含 smartInfo.json + 图片)"""
|
||||
agent = store.get_agent(agent_id)
|
||||
if not agent:
|
||||
err(404, '没有这个智能体')
|
||||
return True
|
||||
files = {}
|
||||
image = agent.get('image') or {}
|
||||
for key, path in image.items():
|
||||
if not path or not os.path.isfile(path):
|
||||
continue
|
||||
try:
|
||||
with open(path, 'rb') as fh:
|
||||
files[f'{key}{os.path.splitext(path)[1]}'] = fh.read()
|
||||
except OSError:
|
||||
continue
|
||||
# ★ 包里**不存内部 ID、不存模型引用、不存限额**(需求 2.5 的"包的边界约定")
|
||||
info = {
|
||||
'name': agent.get('name') or '',
|
||||
'description': agent.get('description') or '',
|
||||
'prompt': agent.get('systemPrompt') or '',
|
||||
'image': {k: f'{k}{os.path.splitext(v)[1]}' for k, v in image.items() if v},
|
||||
}
|
||||
files['smartInfo.json'] = json.dumps(info, ensure_ascii=False, indent=2).encode('utf-8')
|
||||
blob = _zip_of(files)
|
||||
return _send_json_ok(handler, {
|
||||
'fileName': f'{(agent.get("name") or "agent")}.zip',
|
||||
'data': base64.b64encode(blob).decode('ascii'),
|
||||
'bytes': len(blob),
|
||||
})
|
||||
|
||||
|
||||
def _import_agent(handler, body, err) -> bool:
|
||||
"""
|
||||
导入智能体包(需求 2.5)。
|
||||
|
||||
★ **同一个包导入两次 = 两个互相独立的智能体**(需求原话)——
|
||||
所以这里每次都 `create_agent` 生成新 UUID,不做"按名字去重"。
|
||||
★ 模型引用 / 世界观绑定 / 限额这些**不进包**,导入后用默认值。
|
||||
"""
|
||||
raw = body.get('data') or body.get('base64') or ''
|
||||
if not raw:
|
||||
err(400, '缺少包内容')
|
||||
return True
|
||||
try:
|
||||
blob = base64.b64decode(raw)
|
||||
files = _read_zip(blob)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
err(400, f'包读不出来:{exc}')
|
||||
return True
|
||||
|
||||
info = None
|
||||
for name in files:
|
||||
if os.path.basename(name).lower() == 'smartinfo.json':
|
||||
try:
|
||||
info = json.loads(files[name].decode('utf-8'))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
err(400, f'smartInfo.json 解析失败:{exc}')
|
||||
return True
|
||||
break
|
||||
if info is None:
|
||||
err(400, '包里没有 smartInfo.json —— 这不是一个智能体包')
|
||||
return True
|
||||
|
||||
agent = store.create_agent({
|
||||
'name': str(info.get('name') or '未命名').strip()[:24],
|
||||
'description': str(info.get('description') or ''),
|
||||
'systemPrompt': str(info.get('prompt') or ''),
|
||||
'avatar': 'custom',
|
||||
})
|
||||
image = _save_assets(agent['id'], files, info.get('image') or {})
|
||||
if image:
|
||||
agent = store.update_agent(agent['id'], {'image': image}) or agent
|
||||
return _send_json_ok(handler, {'agent': agent, 'assets': len(image)})
|
||||
|
||||
|
||||
def _resource_export(handler, name: str, rid: str, err) -> bool:
|
||||
item = store.get_resource(name, rid)
|
||||
if not item:
|
||||
err(404, '没有这一项')
|
||||
return True
|
||||
if name == 'skills':
|
||||
# Skill 是**单个 JSON**(需求 3.7),不是 zip
|
||||
payload = {
|
||||
'type': 'agent-skill',
|
||||
'version': 1,
|
||||
'name': item.get('name') or '',
|
||||
'content': item.get('content') or '',
|
||||
}
|
||||
return _send_json_ok(handler, {
|
||||
'fileName': f'{(item.get("name") or "skill")}.json',
|
||||
'json': json.dumps(payload, ensure_ascii=False, indent=2),
|
||||
})
|
||||
# 世界观:zip,含 worldInfo.json + 图片
|
||||
files = {}
|
||||
image = item.get('image') or {}
|
||||
for key, path in image.items():
|
||||
if not path or not os.path.isfile(path):
|
||||
continue
|
||||
try:
|
||||
with open(path, 'rb') as fh:
|
||||
files[f'{key}{os.path.splitext(path)[1]}'] = fh.read()
|
||||
except OSError:
|
||||
continue
|
||||
info = {
|
||||
'name': item.get('name') or '',
|
||||
'setting': item.get('setting') or '',
|
||||
'image': {k: f'{k}{os.path.splitext(v)[1]}' for k, v in image.items() if v},
|
||||
}
|
||||
files['worldInfo.json'] = json.dumps(info, ensure_ascii=False, indent=2).encode('utf-8')
|
||||
blob = _zip_of(files)
|
||||
return _send_json_ok(handler, {
|
||||
'fileName': f'{(item.get("name") or "world")}.zip',
|
||||
'data': base64.b64encode(blob).decode('ascii'),
|
||||
'bytes': len(blob),
|
||||
})
|
||||
|
||||
|
||||
def _resource_import(handler, name: str, body, err) -> bool:
|
||||
if name == 'skills':
|
||||
payload = body.get('data') if isinstance(body.get('data'), dict) else body
|
||||
if isinstance(payload, str):
|
||||
try:
|
||||
payload = json.loads(payload)
|
||||
except Exception: # noqa: BLE001
|
||||
err(400, '不是合法的 JSON')
|
||||
return True
|
||||
if not isinstance(payload, dict) or not (payload.get('content') or payload.get('name')):
|
||||
err(400, '这不是一个 Skill 文件(缺 name / content)')
|
||||
return True
|
||||
if payload.get('type') and payload['type'] != 'agent-skill':
|
||||
err(400, f'不认识的文件类型:{payload.get("type")}')
|
||||
return True
|
||||
item = store.create_resource('skills', {
|
||||
'name': payload.get('name') or '未命名 Skill',
|
||||
'content': payload.get('content') or '',
|
||||
})
|
||||
return _send_json_ok(handler, {'item': item})
|
||||
|
||||
# 世界观包
|
||||
raw = body.get('data') or body.get('base64') or ''
|
||||
if not raw:
|
||||
err(400, '缺少包内容')
|
||||
return True
|
||||
try:
|
||||
files = _read_zip(base64.b64decode(raw))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
err(400, f'包读不出来:{exc}')
|
||||
return True
|
||||
info = None
|
||||
for fname in files:
|
||||
if os.path.basename(fname).lower() == 'worldinfo.json':
|
||||
try:
|
||||
info = json.loads(files[fname].decode('utf-8'))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
err(400, f'worldInfo.json 解析失败:{exc}')
|
||||
return True
|
||||
break
|
||||
if info is None:
|
||||
err(400, '包里没有 worldInfo.json —— 这不是一个世界观包')
|
||||
return True
|
||||
item = store.create_resource('worldviews', {
|
||||
'name': str(info.get('name') or '未命名').strip()[:40],
|
||||
'setting': str(info.get('setting') or ''),
|
||||
})
|
||||
image = _save_assets(item['id'], files, info.get('image') or {})
|
||||
if image:
|
||||
item = store.update_resource('worldviews', item['id'], {'image': image}) or item
|
||||
return _send_json_ok(handler, {'item': item, 'assets': len(image)})
|
||||
|
||||
|
||||
def _send_json_ok(handler, payload: dict) -> bool:
|
||||
handler.send_json(200, {'ok': True, **payload})
|
||||
return True
|
||||
205
android/kernel/agent_context.py
Normal file
205
android/kernel/agent_context.py
Normal file
@@ -0,0 +1,205 @@
|
||||
"""每轮对话前拼 system prompt(需求 3.2 / 3.5 / 3.6 / 3.7 + 附录 C)。
|
||||
|
||||
## 这个模块只做一件事
|
||||
|
||||
把「人设 + Skill 手册 + 世界观 + 情绪 + 记忆 + 同伴情绪」按**固定顺序**
|
||||
拼成一段 system prompt。
|
||||
|
||||
## 为什么单独一个模块,而不是写在 agent_loop 里
|
||||
|
||||
因为这里有**六种来源**,每一种都要判空、要查库/查 JSON、出错了还不能把
|
||||
整轮对话带崩。塞在 agent_loop 里会让那个函数变成两百行,而且没法单独测。
|
||||
|
||||
## 几条硬约定
|
||||
|
||||
**① 空段整段删掉。**
|
||||
绑没绑世界观、有没有情绪、记没记过东西 —— 都是常态。
|
||||
不删的话每次对话都带着一堆空的 `<worldview></worldview>`,
|
||||
模型会以为"这里本来该有内容但我没看到",反而更容易瞎编。
|
||||
|
||||
**② 顺序固定:人设 → skills → worldview → emotion → memory → peer_emotions。**
|
||||
见附录 C。顺序不是审美问题:记忆在情绪之后,模型读到"我现在有点烦"
|
||||
再看记忆,语气才连贯;反过来它会先看到一堆事实、再看到情绪,像事后补的。
|
||||
|
||||
**③ 每轮重新拼。**
|
||||
记忆和情绪随时会变(AI 自己就能改),拼一次缓存住的话,
|
||||
用户会看到"我明明让它记住了,下一句它又忘了"。
|
||||
|
||||
**④ 查库失败一律当成"这段没有"。**
|
||||
数据库被锁、文件损坏都不该让用户发不出消息。
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
import agentdb
|
||||
import store
|
||||
from defaults import (
|
||||
BUILTIN_SKILL,
|
||||
DEFAULT_MEMORY_LINE,
|
||||
DEFAULT_PROMPT_TEMPLATE,
|
||||
)
|
||||
|
||||
# 模板里的段名(顺序就是渲染顺序)。加一段要同时改 defaults.DEFAULT_PROMPT_TEMPLATE。
|
||||
SECTIONS = ('skills', 'worldview', 'emotion', 'memory', 'peer_emotions')
|
||||
|
||||
|
||||
def _safe(fn, fallback):
|
||||
"""
|
||||
跑一个小查询,出错就当"没有"。
|
||||
|
||||
★ 单独抽出来是因为这个模式在这里出现六次:**任何一处查库失败都不该
|
||||
让整轮对话发不出去**(数据库锁了、agent.db 被删了、JSON 坏了)。
|
||||
"""
|
||||
try:
|
||||
return fn()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f'[agent_context] 取上下文失败,按"没有"处理:{exc}', file=__import__('sys').stderr)
|
||||
return fallback
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 各段
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def build_skills(agent: dict) -> str:
|
||||
"""
|
||||
`<skills>` 段:内置手册 + 这个智能体绑定的自定义 Skill(**按绑定顺序**)。
|
||||
|
||||
内置的那份永远在最前面 —— 它讲的是记忆/情绪这些**基础工具**怎么用,
|
||||
自定义 Skill 是额外的,放后面读起来才是"先会基本操作,再学扩展"。
|
||||
"""
|
||||
parts = [BUILTIN_SKILL.strip()] if BUILTIN_SKILL.strip() else []
|
||||
agent_id = (agent or {}).get('id') or ''
|
||||
if agent_id:
|
||||
for sid in _safe(lambda: agentdb.skills_of(agent_id), []):
|
||||
sk = _safe(lambda: store.get_resource('skills', sid), None)
|
||||
if sk and (sk.get('content') or '').strip():
|
||||
parts.append(f'【{(sk.get("name") or "Skill").strip()}】\n{sk["content"].strip()}')
|
||||
return '\n\n'.join(parts)
|
||||
|
||||
|
||||
def build_worldview(agent: dict) -> str:
|
||||
"""`<worldview>` 段:绑定的世界观设定文本(没绑就是空)"""
|
||||
wid = (agent or {}).get('worldviewId') or ''
|
||||
if not wid:
|
||||
return ''
|
||||
wv = _safe(lambda: store.get_resource('worldviews', wid), None)
|
||||
return (wv or {}).get('setting', '').strip()
|
||||
|
||||
|
||||
def memory_scope(agent: dict) -> str:
|
||||
"""这个智能体当前该读写哪个记忆空间(绑了世界观就是共享空间)"""
|
||||
agent = agent or {}
|
||||
return agentdb.scope_of(agent.get('id') or '', agent.get('worldviewId') or '')
|
||||
|
||||
|
||||
def build_emotion(agent: dict) -> str:
|
||||
"""`<emotion>` 段:自己的情绪(**始终私有**,绑了世界观也不共享 —— 需求 3.5)"""
|
||||
agent_id = (agent or {}).get('id') or ''
|
||||
if not agent_id:
|
||||
return ''
|
||||
return (_safe(lambda: agentdb.emotion_get(agent_id), '') or '').strip()
|
||||
|
||||
|
||||
def build_memory(agent: dict) -> str:
|
||||
"""
|
||||
`<memory>` 段:那个记忆空间的**全部条目**(标题 + 正文,需求 3.2 的"全量注入")。
|
||||
"""
|
||||
scope = memory_scope(agent)
|
||||
items = _safe(lambda: agentdb.memory_list(scope), [])
|
||||
if not items:
|
||||
return ''
|
||||
tmpl = _safe(
|
||||
lambda: (store.read_settings().get('memoryLine') or DEFAULT_MEMORY_LINE),
|
||||
DEFAULT_MEMORY_LINE,
|
||||
)
|
||||
lines = []
|
||||
for it in items:
|
||||
title = (it.get('title') or '').strip()
|
||||
content = (it.get('content') or '').strip()
|
||||
try:
|
||||
lines.append(tmpl.format(title=title, content=content))
|
||||
except (KeyError, IndexError): # 用户把模板改坏了:退回默认再试
|
||||
lines.append(DEFAULT_MEMORY_LINE.format(title=title, content=content))
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
def build_peer_emotions(agent: dict) -> str:
|
||||
"""
|
||||
`<peer_emotions>` 段:**同世界观其他智能体**的名字 + 情绪(需求 3.5)。
|
||||
|
||||
★ 三个条件全满足才有内容:绑了世界观、开了情绪感知开关、世界观下还有别人。
|
||||
开关默认关(需求原话"默认关闭")—— 别人的情绪属于"角色内的隐私",
|
||||
默认让 AI 看到会让它们的表现互相串味。
|
||||
"""
|
||||
agent = agent or {}
|
||||
if not agent.get('worldviewId') or not agent.get('emotionEnabled'):
|
||||
return ''
|
||||
my_id = agent.get('id') or ''
|
||||
wid = agent.get('worldviewId') or ''
|
||||
others = [
|
||||
a for a in _safe(store.list_agents, [])
|
||||
if a.get('worldviewId') == wid and a.get('id') != my_id
|
||||
]
|
||||
rows = _safe(
|
||||
lambda: agentdb.peer_emotions(wid, my_id, [a.get('id') for a in others]),
|
||||
[],
|
||||
)
|
||||
by_id = {a.get('id'): a for a in others}
|
||||
parts = []
|
||||
for aid, emo in rows:
|
||||
name = (by_id.get(aid) or {}).get('name') or '某人'
|
||||
if (emo or '').strip():
|
||||
parts.append(f'{name}-{emo.strip()}')
|
||||
return ';'.join(parts)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 拼装
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
_RE_BLOCK = {name: re.compile(rf'<{name}>.*?</{name}>', re.S) for name in SECTIONS}
|
||||
|
||||
|
||||
def render(template: str, values: dict) -> str:
|
||||
"""
|
||||
按模板渲染,**空的段整段删掉**。
|
||||
|
||||
★ 先渲染 `{prompt}` 再处理段:人设里如果碰巧有 `<memory>` 这样的字
|
||||
(用户自己写的提示词里完全可能),会被当成段处理掉 —— 所以段的匹配
|
||||
只在**模板**上做,不在渲染结果上做。
|
||||
"""
|
||||
out = (template or DEFAULT_PROMPT_TEMPLATE).replace('{prompt}', (values.get('prompt') or '').strip())
|
||||
for name in SECTIONS:
|
||||
block = _RE_BLOCK[name].search(out)
|
||||
if not block:
|
||||
continue
|
||||
value = (values.get(name) or '').strip()
|
||||
if value:
|
||||
out = out[:block.start()] + f'<{name}>\n{value}\n</{name}>' + out[block.end():]
|
||||
else:
|
||||
out = out[:block.start()] + out[block.end():]
|
||||
# 段被删掉后会留下连续空行,压一压;别让提示词里出现四五行的空白
|
||||
out = re.sub(r'\n{3,}', '\n\n', out)
|
||||
return out.strip()
|
||||
|
||||
|
||||
def build_system_prompt(settings: dict, agent: dict) -> str:
|
||||
"""
|
||||
这一轮要用的 system prompt。
|
||||
|
||||
[settings] 里可以覆盖:`promptTemplate`(整份模板)、`memoryLine`(记忆条目排版)。
|
||||
"""
|
||||
agent = agent or {}
|
||||
settings = settings or {}
|
||||
prompt = (agent.get('systemPrompt') or '').strip() or (settings.get('systemPrompt') or '')
|
||||
values = {
|
||||
'prompt': prompt,
|
||||
'skills': build_skills(agent),
|
||||
'worldview': build_worldview(agent),
|
||||
'emotion': build_emotion(agent),
|
||||
'memory': build_memory(agent),
|
||||
'peer_emotions': build_peer_emotions(agent),
|
||||
}
|
||||
template = (settings.get('promptTemplate') or '').strip() or DEFAULT_PROMPT_TEMPLATE
|
||||
return render(template, values)
|
||||
@@ -12,6 +12,7 @@ Agent 主循环:系统提示词 + 多轮工具调用 + 流式输出。
|
||||
import json
|
||||
from typing import Callable, Optional
|
||||
|
||||
import agent_context
|
||||
import store
|
||||
import tools_runtime
|
||||
from providers import stream_chat
|
||||
@@ -19,6 +20,39 @@ from providers import stream_chat
|
||||
MAX_TOOL_RESULT_CHARS = 6000
|
||||
|
||||
|
||||
def add_usage(total, one) -> dict:
|
||||
"""
|
||||
把一次调用的 usage 累加进总数。
|
||||
|
||||
★ 各家的字段名不一样(OpenAI 系是 prompt_tokens / completion_tokens,
|
||||
兼容网关有时给 input_tokens / output_tokens),**两种都认** ——
|
||||
只认一种的话换个提供商统计就静默变成 0,而"统计是 0"极难被发现。
|
||||
"""
|
||||
if not isinstance(one, dict):
|
||||
return total or {}
|
||||
out = dict(total or {})
|
||||
pairs = (
|
||||
('prompt_tokens', 'prompt_tokens'),
|
||||
('completion_tokens', 'completion_tokens'),
|
||||
('total_tokens', 'total_tokens'),
|
||||
('input_tokens', 'prompt_tokens'), # 兼容写法
|
||||
('output_tokens', 'completion_tokens'), # 兼容写法
|
||||
)
|
||||
for src, dst in pairs:
|
||||
v = one.get(src)
|
||||
if isinstance(v, (int, float)):
|
||||
out[dst] = int(out.get(dst) or 0) + int(v)
|
||||
if 'total_tokens' not in out:
|
||||
out['total_tokens'] = int(out.get('prompt_tokens') or 0) + int(out.get('completion_tokens') or 0)
|
||||
return out
|
||||
|
||||
|
||||
def usage_pair(usage) -> tuple:
|
||||
"""从 usage 里取出 (输入, 输出)。给落库用 —— 字段名差异在这一处抹平"""
|
||||
u = usage if isinstance(usage, dict) else {}
|
||||
return int(u.get('prompt_tokens') or 0), int(u.get('completion_tokens') or 0)
|
||||
|
||||
|
||||
def truncate(text, max_len: int = MAX_TOOL_RESULT_CHARS) -> str:
|
||||
"""工具结果截断:和 Node 版的 truncate 一样,超长就截断并标注。"""
|
||||
if isinstance(text, str):
|
||||
@@ -99,7 +133,15 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
tool_defs = tools_runtime.build_tool_defs(settings)
|
||||
max_rounds = _max_rounds(settings)
|
||||
mode = (settings.get('security') or {}).get('mode') or 'open'
|
||||
system_prompt = ((agent or {}).get('systemPrompt') or '').strip() or settings.get('systemPrompt') or ''
|
||||
# ★★ system prompt **每轮重新拼**(需求 3.2):人设 → skills → 世界观 →
|
||||
# 情绪 → 记忆 → 同伴情绪,顺序固定(附录 C)。
|
||||
#
|
||||
# 为什么不拼一次缓存住:记忆和情绪**随时会变**,而且 AI 自己就能改它们
|
||||
# (memory_add / emotion_set)。缓存住的表现是"我明明让它记住了,
|
||||
# 下一句它又忘了"——这种 bug 用户会当成"记忆功能坏了"。
|
||||
#
|
||||
# 拼法、判空、查库失败的兜底全在 agent_context.py 里。
|
||||
system_prompt = agent_context.build_system_prompt(settings, agent or {})
|
||||
# ★★ 界面能力的用法**只在开关打开时才追加**。
|
||||
#
|
||||
# 为什么不写进 defaults.DEFAULT_SYSTEM_PROMPT:那个是**默认设置的一部分**,
|
||||
@@ -192,7 +234,13 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic
|
||||
elif kind == 'tool_calls':
|
||||
tool_calls = event.get('toolCalls') or []
|
||||
elif kind == 'usage':
|
||||
usage = event.get('usage')
|
||||
# ★★ **累加**而不是覆盖。
|
||||
#
|
||||
# 多轮工具调用时每一轮上游都会来一个 usage,以前是直接赋值 ——
|
||||
# 只留最后一轮。而消耗的大头恰恰在前面几轮(工具结果很长,
|
||||
# 一轮就是几千 input token),丢掉之后统计出来的数字
|
||||
# 会少得离谱,用户会以为"怎么才用了这么点"。
|
||||
usage = add_usage(usage, event.get('usage'))
|
||||
|
||||
if not tool_calls:
|
||||
emit({
|
||||
|
||||
345
android/kernel/agent_tools.py
Normal file
345
android/kernel/agent_tools.py
Normal file
@@ -0,0 +1,345 @@
|
||||
"""智能体系统的内置工具:记忆 / 情绪 / 用量(需求附录 B)。
|
||||
|
||||
## 为什么是"内置工具"而不是 `tools/*.py`
|
||||
|
||||
`tools/` 下的工具是**用户可改的 .py 文件**(内核启动时播种到手机上的可写目录)。
|
||||
这七个不一样:
|
||||
|
||||
· 它们要读写 `agent.db`(记忆、情绪、Token 统计)—— 那是内核进程内的模块,
|
||||
电脑端的工具是**子进程**,根本 import 不到
|
||||
· 它们是系统的核心能力,不该被用户在 tools/ 里改坏(改坏了 AI 会"失忆",
|
||||
而且表现是"有时记得有时不记得",极难查)
|
||||
|
||||
所以走 `builtin_tools.BUILTIN_TOOLS` 那条路(进程内、不进 tools/、不参与播种)。
|
||||
|
||||
## 限权规则(需求 3.6,**共享记忆里最重要的一条**)
|
||||
|
||||
绑定了世界观的智能体共用一个记忆空间,于是"谁都能删"就成了问题:
|
||||
|
||||
· `memory_add` —— 任何智能体都能往共享空间写(追加优先)
|
||||
· `memory_forget` / `memory_update` —— **只能动自己写的**(按 author_agent 判定)
|
||||
· `pinned` —— 用户标记"必须保留"的条目,AI 连自己的都改不动
|
||||
|
||||
改别人的条目只能由**用户在界面上手动做**。这条不做的话,
|
||||
两个智能体互相删对方的记忆,用户会看到"记忆莫名其妙少了"。
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
import agentdb
|
||||
import store
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 拿"我现在是谁"
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def _ctx() -> dict:
|
||||
"""
|
||||
当前这次工具调用的上下文(哪次对话、哪个智能体)。
|
||||
|
||||
★ 局部 import:`tools_runtime` → `builtin_tools` → 这里,顶部 import 就成环了。
|
||||
"""
|
||||
import tools_runtime
|
||||
|
||||
return tools_runtime.current_context() or {}
|
||||
|
||||
|
||||
def _me() -> dict:
|
||||
"""当前智能体(拿不到就返回空 dict —— 工具会据此报错,而不是瞎写)"""
|
||||
ctx = _ctx()
|
||||
agent = store.get_agent(ctx.get('agentId') or '') or {}
|
||||
return agent
|
||||
|
||||
|
||||
def _my_scope(agent: dict) -> str:
|
||||
return agentdb.scope_of(agent.get('id') or '', agent.get('worldviewId') or '')
|
||||
|
||||
|
||||
def _shared(agent: dict) -> bool:
|
||||
"""是不是在共享空间里(绑了世界观就是)"""
|
||||
return bool(agent.get('worldviewId'))
|
||||
|
||||
|
||||
def _check_editable(item: dict, agent: dict) -> None:
|
||||
"""
|
||||
能不能改/删这一条 —— 不能就抛错(**抛错而不是静默跳过**:
|
||||
静默的话模型以为改成功了,下一轮还按老样子说话)。
|
||||
"""
|
||||
if item.get('pinned'):
|
||||
raise ValueError(
|
||||
'这条记忆被用户标记为「必须保留」,你改不了也删不掉。'
|
||||
'如果它确实过时了,跟用户说一声让他自己处理。'
|
||||
)
|
||||
if _shared(agent) and (item.get('author_agent') or '') != (agent.get('id') or ''):
|
||||
raise ValueError(
|
||||
'这条是**其他智能体**写进共享记忆的,你只能改/删自己写的。'
|
||||
'需要修改它的话,跟用户说让他手动改。'
|
||||
)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 记忆
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
MEMORY_ADD = {
|
||||
'name': 'memory_add',
|
||||
'description': (
|
||||
'记住一件事,**跨对话保留**。用户告诉你的重要事实、偏好、约定、他的项目,'
|
||||
'都该记下来。记之前先看系统提示词里的记忆清单,已经记过的别再记一遍。'
|
||||
'返回新条目的 id(以后要改/删它需要这个 id)。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'title': {'type': 'string', 'description': '一句话标题(检索和整理时的锚点)'},
|
||||
'content': {'type': 'string', 'description': '要记住的正文'},
|
||||
},
|
||||
'required': ['title', 'content'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def memory_add(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体,无法写记忆')
|
||||
title = str(args.get('title') or '').strip()
|
||||
content = str(args.get('content') or '').strip()
|
||||
if not title and not content:
|
||||
raise ValueError('title 和 content 至少要有一个')
|
||||
item = agentdb.memory_add(
|
||||
scope=_my_scope(agent),
|
||||
title=title,
|
||||
content=content,
|
||||
author_agent=agent.get('id') or '',
|
||||
)
|
||||
return {
|
||||
'id': item['id'],
|
||||
'title': item['title'],
|
||||
'scope': '共享记忆(世界观)' if _shared(agent) else '你自己的记忆',
|
||||
'note': '已写入。不要只在正文里说"记住了"—— 你现在已经真的记住了,正常继续就行。',
|
||||
}
|
||||
|
||||
|
||||
MEMORY_UPDATE = {
|
||||
'name': 'memory_update',
|
||||
'description': (
|
||||
'修改一条已有的记忆(只改传进来的字段)。'
|
||||
'只能改**你自己写的**、且没被用户标记为「必须保留」的条目。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'id': {'type': 'string', 'description': '记忆的 id(memory_add 返回过,或记忆清单里带的)'},
|
||||
'title': {'type': 'string', 'description': '新标题,不改就不传'},
|
||||
'content': {'type': 'string', 'description': '新正文,不改就不传'},
|
||||
},
|
||||
'required': ['id'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def memory_update(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
mid = str(args.get('id') or '').strip()
|
||||
if not mid:
|
||||
raise ValueError('id 不能为空')
|
||||
item = agentdb.memory_get(mid)
|
||||
# ★ 只允许改**自己这个记忆空间**里的条目:不然知道 id 就能改到别人的私有记忆
|
||||
if not item or item.get('scope') != _my_scope(agent):
|
||||
raise ValueError('没找到这条记忆(id 不对,或者它不在你当前的记忆空间里)')
|
||||
_check_editable(item, agent)
|
||||
updated = agentdb.memory_update(
|
||||
mid,
|
||||
title=args.get('title') if 'title' in args else None,
|
||||
content=args.get('content') if 'content' in args else None,
|
||||
)
|
||||
return {'id': mid, 'title': (updated or {}).get('title', ''), 'note': '已更新。'}
|
||||
|
||||
|
||||
MEMORY_FORGET = {
|
||||
'name': 'memory_forget',
|
||||
'description': (
|
||||
'删掉一条记忆。只能删**你自己写的**、且没被用户标记为「必须保留」的条目。'
|
||||
'拿不准该不该删时,先问用户。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'id': {'type': 'string', 'description': '要删的记忆 id'},
|
||||
},
|
||||
'required': ['id'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def memory_forget(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
mid = str(args.get('id') or '').strip()
|
||||
if not mid:
|
||||
raise ValueError('id 不能为空')
|
||||
item = agentdb.memory_get(mid)
|
||||
if not item or item.get('scope') != _my_scope(agent):
|
||||
raise ValueError('没找到这条记忆(id 不对,或者它不在你当前的记忆空间里)')
|
||||
_check_editable(item, agent)
|
||||
agentdb.memory_forget(mid)
|
||||
return {'id': mid, 'forgotten': True, 'note': '已删除。'}
|
||||
|
||||
|
||||
MEMORY_SEARCH = {
|
||||
'name': 'memory_search',
|
||||
'description': (
|
||||
'在自己的记忆库里检索。系统提示词里的记忆清单是**全量**的,'
|
||||
'但条数多的时候你可能只想找相关的几条 —— 用这个按关键词查。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'keyword': {'type': 'string', 'description': '关键词(标题和正文都会匹配)'},
|
||||
'limit': {'type': 'number', 'description': '最多返回几条,默认 10'},
|
||||
},
|
||||
'required': ['keyword'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def memory_search(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
kw = str(args.get('keyword') or '').strip()
|
||||
if not kw:
|
||||
raise ValueError('keyword 不能为空')
|
||||
try:
|
||||
limit = int(float(args.get('limit') or 10))
|
||||
except (TypeError, ValueError):
|
||||
limit = 10
|
||||
rows = agentdb.memory_search(_my_scope(agent), kw, limit)
|
||||
return {
|
||||
'keyword': kw,
|
||||
'count': len(rows),
|
||||
'items': [
|
||||
{'id': r['id'], 'title': r['title'], 'content': r['content']} for r in rows
|
||||
],
|
||||
'note': '' if rows else '没有匹配的记忆。别据此说"我完全不记得"—— 换个关键词再试一次。',
|
||||
}
|
||||
|
||||
|
||||
MEMORY_SUGGEST_SUMMARY = {
|
||||
'name': 'memory_suggest_summary',
|
||||
'description': (
|
||||
'**建议**用户整理一次记忆(把零散的合并成几条)。'
|
||||
'你只负责建议,不执行 —— 用户点确认之后系统才会真的整理。'
|
||||
'什么时候用:记忆条数明显变多、或者有好几条在说同一件事。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'reason': {'type': 'string', 'description': '为什么建议整理(会显示给用户)'},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def memory_suggest_summary(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
why = str(args.get('reason') or '').strip() or '记忆有点多了,想合并一下'
|
||||
# ★ 只挂一个"建议"标记,**不执行总结**(需求 3.2:仅提示不执行)。
|
||||
# 界面看到这个标记会给用户一个「整理记忆」按钮。
|
||||
store.add_pending_summary_suggestion(agent.get('id') or '', why)
|
||||
return {
|
||||
'suggested': True,
|
||||
'reason': why,
|
||||
'note': '已经建议了。**别再说"我整理好了"** —— 你只是提了个建议,'
|
||||
'用户点确认之后才会真的整理。正文里正常说这件事就行。',
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 情绪
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
EMOTION_SET = {
|
||||
'name': 'emotion_set',
|
||||
'description': (
|
||||
'更新**你自己**当前的情绪状态(一小段话,比如"刚被夸了,有点得意")。'
|
||||
'它会跟着你到下一次对话,也会显示在系统提示词里。'
|
||||
'情绪要跟着对话内容自然变化,不用每轮都改。'
|
||||
),
|
||||
'parameters': {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'emotion': {'type': 'string', 'description': '你现在的情绪'},
|
||||
},
|
||||
'required': ['emotion'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def emotion_set(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
emo = str(args.get('emotion') or '').strip()
|
||||
if not emo:
|
||||
raise ValueError('emotion 不能为空(不想保留情绪的话直接别调用这个工具)')
|
||||
agentdb.emotion_set(agent.get('id') or '', emo[:200])
|
||||
return {'emotion': emo[:200], 'note': '已更新你自己的情绪。'}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 用量
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
GET_TOKEN_USAGE = {
|
||||
'name': 'get_token_usage',
|
||||
'description': (
|
||||
'查**你自己**累计用了多少 Token、还剩多少额度。'
|
||||
'用户问"你还能说多少""用了多少"时用这个查真实数字,别猜。'
|
||||
),
|
||||
'parameters': {'type': 'object', 'properties': {}},
|
||||
}
|
||||
|
||||
|
||||
def get_token_usage(args: dict) -> dict:
|
||||
agent = _me()
|
||||
if not agent:
|
||||
raise ValueError('拿不到当前智能体')
|
||||
usage = agentdb.token_usage(agent.get('id') or '')
|
||||
limit = int(float(agent.get('tokenLimit') or 0))
|
||||
used = usage['total']['input'] + usage['total']['output']
|
||||
return {
|
||||
'used': used,
|
||||
'input': usage['total']['input'],
|
||||
'output': usage['total']['output'],
|
||||
'byModel': usage['byModel'],
|
||||
'limit': limit,
|
||||
'remaining': (None if limit <= 0 else max(0, limit - used)),
|
||||
'note': '额度无限制。' if limit <= 0 else f'还剩 {max(0, limit - used)} Token。',
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 注册
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
#: 名字 → {'spec': TOOL, 'run': fn}(形状和 builtin_tools.BUILTIN_TOOLS 一样)
|
||||
AGENT_TOOLS = {
|
||||
'memory_add': {'spec': MEMORY_ADD, 'run': memory_add},
|
||||
'memory_update': {'spec': MEMORY_UPDATE, 'run': memory_update},
|
||||
'memory_forget': {'spec': MEMORY_FORGET, 'run': memory_forget},
|
||||
'memory_search': {'spec': MEMORY_SEARCH, 'run': memory_search},
|
||||
'memory_suggest_summary': {'spec': MEMORY_SUGGEST_SUMMARY, 'run': memory_suggest_summary},
|
||||
'emotion_set': {'spec': EMOTION_SET, 'run': emotion_set},
|
||||
'get_token_usage': {'spec': GET_TOKEN_USAGE, 'run': get_token_usage},
|
||||
}
|
||||
|
||||
|
||||
def _unused(): # pragma: no cover - 只是让 sys 的 import 不被 lint 当成没用
|
||||
return sys
|
||||
440
android/kernel/agentdb.py
Normal file
440
android/kernel/agentdb.py
Normal file
@@ -0,0 +1,440 @@
|
||||
"""智能体系统的数据层:**记忆 / 情绪 / Token 统计 / 绑定关系**。
|
||||
|
||||
## 为什么这次用 SQLite,而别处(设置/会话/智能体)还是 JSON
|
||||
|
||||
`store.py` 顶上写着"为什么用 JSON 而不是 SQLite",理由很实在:
|
||||
**数据量极小**(几条会话、几个智能体),而且用户/开发者要能直接看到、改那些文件。
|
||||
|
||||
那个理由对**智能体本身**依然成立(就几个),所以它们还在 `agents.json` 里。
|
||||
但记忆不一样,三条都指向 SQLite:
|
||||
|
||||
· 需求明确"记忆条目**无上限**",而**每轮对话都要全量注入** smartMemory ——
|
||||
几千条记忆塞进一个 JSON、每轮读盘再反序列化一遍,代价是实打实的
|
||||
· 要按关键词检索(`memory_search` 是 LIKE 查询)
|
||||
· 要"只改一条""只删自己写的"这种**行级**操作 —— 在 JSON 里就是
|
||||
读全量 → 改 → 写全量,多线程下一次并发写就可能把别人的改动盖掉
|
||||
|
||||
所以分界线是:**会持续增长、要按行操作或检索的数据 → SQLite;
|
||||
少量、要人肉可读的配置 → JSON。**
|
||||
|
||||
(另:这几张表**只属于智能体系统**,不和会话/设置混在一起 ——
|
||||
`agent.db` 单独一个文件,删了就是"重置智能体系统",不会碰到聊天记录。)
|
||||
|
||||
## 关联一律用 UUID
|
||||
|
||||
见需求附录 A。`memories.author_agent`、`agent_skills.agent_id`、
|
||||
`token_usage.agent_id` 存的都是 UUID,`name` 只是显示名(可重复、可随便改)。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sqlite3
|
||||
import threading
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import paths
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 连接
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★ 每线程一个连接:sqlite3 的连接默认不能跨线程用,而内核是多线程的
|
||||
# (HTTP 每请求一线程 + 工具跑在又一个线程里)。
|
||||
# 用 threading.local() 而不是"一个全局连接 + 一把大锁":记忆检索可能在
|
||||
# 对话生成的过程中被调用,一把大锁会把整条链路串起来。
|
||||
_local = threading.local()
|
||||
_init_done = False
|
||||
_init_lock = threading.Lock()
|
||||
|
||||
|
||||
def db_path() -> str:
|
||||
"""数据库文件的位置(跟着数据目录走,和 settings.json 同一层)"""
|
||||
return os.path.join(os.path.dirname(paths.get().settings_file), 'agent.db')
|
||||
|
||||
|
||||
def _connect() -> sqlite3.Connection:
|
||||
conn = getattr(_local, 'conn', None)
|
||||
if conn is not None:
|
||||
return conn
|
||||
os.makedirs(os.path.dirname(db_path()), exist_ok=True)
|
||||
# check_same_thread=False 是安全的:这个连接只会被**创建它的那个线程**用到
|
||||
conn = sqlite3.connect(db_path(), check_same_thread=False, timeout=10)
|
||||
conn.row_factory = sqlite3.Row
|
||||
# WAL:读不挡写。安卓上内核同时有"对话在写记忆"和"界面在读列表"。
|
||||
try:
|
||||
conn.execute('PRAGMA journal_mode=WAL')
|
||||
conn.execute('PRAGMA synchronous=NORMAL')
|
||||
except sqlite3.Error:
|
||||
pass # 只读文件系统之类:不致命,退化成默认模式
|
||||
_local.conn = conn
|
||||
return conn
|
||||
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS memories (
|
||||
id TEXT PRIMARY KEY,
|
||||
scope TEXT NOT NULL,
|
||||
title TEXT NOT NULL DEFAULT '',
|
||||
content TEXT NOT NULL DEFAULT '',
|
||||
pinned INTEGER NOT NULL DEFAULT 0,
|
||||
author_agent TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_memories_scope ON memories(scope, created_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS emotions (
|
||||
agent_id TEXT PRIMARY KEY,
|
||||
emotion TEXT NOT NULL DEFAULT '',
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS token_usage (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
agent_id TEXT NOT NULL,
|
||||
model TEXT NOT NULL DEFAULT '',
|
||||
input INTEGER NOT NULL DEFAULT 0,
|
||||
output INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_token_agent ON token_usage(agent_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS agent_skills (
|
||||
agent_id TEXT NOT NULL,
|
||||
skill_id TEXT NOT NULL,
|
||||
ord INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (agent_id, skill_id)
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
def init() -> None:
|
||||
"""建表(幂等)。内核启动时调一次,各处也会惰性调。"""
|
||||
global _init_done
|
||||
if _init_done:
|
||||
return
|
||||
with _init_lock:
|
||||
if _init_done:
|
||||
return
|
||||
conn = _connect()
|
||||
conn.executescript(SCHEMA)
|
||||
conn.commit()
|
||||
_init_done = True
|
||||
|
||||
|
||||
def reset_init() -> None:
|
||||
"""测试用:换过数据目录之后强制重新建表"""
|
||||
global _init_done
|
||||
_init_done = False
|
||||
_local.__dict__.pop('conn', None)
|
||||
|
||||
|
||||
def new_id() -> str:
|
||||
"""新实体的主键。**一律 UUID**(需求附录 A)"""
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
def now_iso() -> str:
|
||||
"""和 store.now_iso() 一样的格式(前端直接拿来排序/展示)"""
|
||||
return datetime.now(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z')
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# scope:记忆是"智能体私有"还是"世界观共享"
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★ 用带前缀的字符串而不是两列(agent_id / worldview_id):
|
||||
# 读的时候永远只关心"这一条属于哪个记忆空间",不需要分情况查两列;
|
||||
# 而且以后加第三种空间(比如"全局公共记忆")不用改表结构。
|
||||
|
||||
def agent_scope(agent_id: str) -> str:
|
||||
return f'agent:{agent_id or ""}'
|
||||
|
||||
|
||||
def world_scope(worldview_id: str) -> str:
|
||||
return f'world:{worldview_id or ""}'
|
||||
|
||||
|
||||
def scope_of(agent_id: str, worldview_id: str = '') -> str:
|
||||
"""
|
||||
这个智能体当前该读写哪个记忆空间。
|
||||
|
||||
绑定世界观 → 共享空间;没绑定 → 自己的私有空间(需求 3.6)。
|
||||
"""
|
||||
if worldview_id:
|
||||
return world_scope(worldview_id)
|
||||
return agent_scope(agent_id)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 记忆
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def memory_add(scope: str, title: str, content: str, author_agent: str = '') -> dict:
|
||||
"""新增一条。返回整条(带新生成的 UUID)"""
|
||||
init()
|
||||
item = {
|
||||
'id': new_id(),
|
||||
'scope': scope,
|
||||
'title': (title or '').strip(),
|
||||
'content': (content or '').strip(),
|
||||
'pinned': 0,
|
||||
'author_agent': author_agent or '',
|
||||
'created_at': now_iso(),
|
||||
}
|
||||
conn = _connect()
|
||||
conn.execute(
|
||||
'INSERT INTO memories (id, scope, title, content, pinned, author_agent, created_at) '
|
||||
'VALUES (:id, :scope, :title, :content, :pinned, :author_agent, :created_at)',
|
||||
item,
|
||||
)
|
||||
conn.commit()
|
||||
return item
|
||||
|
||||
|
||||
def memory_get(memory_id: str) -> dict | None:
|
||||
init()
|
||||
row = _connect().execute('SELECT * FROM memories WHERE id = ?', (memory_id,)).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def memory_list(scope: str) -> list:
|
||||
"""一个记忆空间的全部条目(**注入 system prompt 用的就是它**)"""
|
||||
init()
|
||||
rows = _connect().execute(
|
||||
'SELECT * FROM memories WHERE scope = ? ORDER BY created_at ASC', (scope,),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
def memory_search(scope: str, keyword: str, limit: int = 20) -> list:
|
||||
"""
|
||||
关键词检索(`memory_search` 工具)。
|
||||
|
||||
★ 用 LIKE 而不是 FTS5:FTS5 对中文要额外的分词器,而这里的关键词
|
||||
就是用户/模型给的整词,LIKE '%关键词%' 反而更符合直觉
|
||||
(搜"咖啡"能命中"喜欢喝咖啡")。条目量级(几千)下 LIKE 也够快。
|
||||
"""
|
||||
init()
|
||||
kw = (keyword or '').strip()
|
||||
if not kw:
|
||||
return []
|
||||
like = f'%{kw}%'
|
||||
rows = _connect().execute(
|
||||
'SELECT * FROM memories WHERE scope = ? AND (title LIKE ? OR content LIKE ?) '
|
||||
'ORDER BY pinned DESC, created_at DESC LIMIT ?',
|
||||
(scope, like, like, max(1, min(200, int(limit)))),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
def memory_update(memory_id: str, title: str = None, content: str = None) -> dict | None:
|
||||
"""改标题/正文(只改传进来的字段)"""
|
||||
init()
|
||||
cur = memory_get(memory_id)
|
||||
if not cur:
|
||||
return None
|
||||
new_title = cur['title'] if title is None else (title or '').strip()
|
||||
new_content = cur['content'] if content is None else (content or '').strip()
|
||||
conn = _connect()
|
||||
conn.execute(
|
||||
'UPDATE memories SET title = ?, content = ? WHERE id = ?',
|
||||
(new_title, new_content, memory_id),
|
||||
)
|
||||
conn.commit()
|
||||
return memory_get(memory_id)
|
||||
|
||||
|
||||
def memory_forget(memory_id: str) -> bool:
|
||||
init()
|
||||
conn = _connect()
|
||||
cur = conn.execute('DELETE FROM memories WHERE id = ?', (memory_id,))
|
||||
conn.commit()
|
||||
return cur.rowcount > 0
|
||||
|
||||
|
||||
def memory_set_pinned(memory_id: str, pinned: bool) -> bool:
|
||||
"""用户手动标记「必须保留」(AI 改不了这个,见需求 3.2)"""
|
||||
init()
|
||||
conn = _connect()
|
||||
cur = conn.execute('UPDATE memories SET pinned = ? WHERE id = ?', (1 if pinned else 0, memory_id))
|
||||
conn.commit()
|
||||
return cur.rowcount > 0
|
||||
|
||||
|
||||
def memory_replace_all(scope: str, items: list, keep_pinned: bool = True) -> int:
|
||||
"""
|
||||
**AI 总结**的写回:整个空间换成压缩后的那份。
|
||||
|
||||
★ `keep_pinned=True` 时 pinned 条目**原样保留**、不参与替换 ——
|
||||
这是需求 3.2 里"pinned 保护"的落地:用户标了"必须保留"的东西,
|
||||
不能被一次总结合并掉。
|
||||
|
||||
返回写回了多少条。
|
||||
"""
|
||||
init()
|
||||
conn = _connect()
|
||||
kept = []
|
||||
if keep_pinned:
|
||||
kept = [dict(r) for r in conn.execute(
|
||||
'SELECT * FROM memories WHERE scope = ? AND pinned = 1', (scope,),
|
||||
).fetchall()]
|
||||
conn.execute('DELETE FROM memories WHERE scope = ?' + (' AND pinned = 0' if keep_pinned else ''),
|
||||
(scope,))
|
||||
n = 0
|
||||
for it in items or []:
|
||||
title = str((it or {}).get('title') or '').strip()
|
||||
content = str((it or {}).get('content') or '').strip()
|
||||
if not title and not content:
|
||||
continue
|
||||
conn.execute(
|
||||
'INSERT INTO memories (id, scope, title, content, pinned, author_agent, created_at) '
|
||||
'VALUES (?, ?, ?, ?, 0, ?, ?)',
|
||||
(new_id(), scope, title, content, str(it.get('author_agent') or ''), now_iso()),
|
||||
)
|
||||
n += 1
|
||||
conn.commit()
|
||||
return n + len(kept)
|
||||
|
||||
|
||||
def memory_titles(scope: str) -> list:
|
||||
"""只要标题清单(注入时先拼标题,正文按需检索 —— 见注入模板)"""
|
||||
init()
|
||||
rows = _connect().execute(
|
||||
'SELECT title FROM memories WHERE scope = ? ORDER BY pinned DESC, created_at ASC', (scope,),
|
||||
).fetchall()
|
||||
return [r['title'] for r in rows if r['title']]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 情绪(始终按智能体私有,即使绑定了世界观 —— 需求 3.5)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def emotion_get(agent_id: str) -> str:
|
||||
init()
|
||||
row = _connect().execute(
|
||||
'SELECT emotion FROM emotions WHERE agent_id = ?', (agent_id or '',),
|
||||
).fetchone()
|
||||
return row['emotion'] if row else ''
|
||||
|
||||
|
||||
def emotion_set(agent_id: str, emotion: str) -> str:
|
||||
init()
|
||||
conn = _connect()
|
||||
conn.execute(
|
||||
'INSERT INTO emotions (agent_id, emotion, updated_at) VALUES (?, ?, ?) '
|
||||
'ON CONFLICT(agent_id) DO UPDATE SET emotion = excluded.emotion, updated_at = excluded.updated_at',
|
||||
(agent_id or '', emotion or '', now_iso()),
|
||||
)
|
||||
conn.commit()
|
||||
return emotion or ''
|
||||
|
||||
|
||||
def peer_emotions(worldview_id: str, exclude_agent: str, agent_ids: list) -> list:
|
||||
"""
|
||||
同世界观、**其他**智能体的「名字 + 情绪」(情绪感知开关打开时才注入)。
|
||||
|
||||
[agent_ids] 是绑定了这个世界观的全部智能体 id(由调用方从 agents.json 里挑,
|
||||
这里不碰 JSON —— 数据层只管数据库里有什么)。返回 [(agent_id, emotion)]。
|
||||
"""
|
||||
init()
|
||||
out = []
|
||||
for aid in agent_ids or []:
|
||||
if not aid or aid == exclude_agent:
|
||||
continue
|
||||
out.append((aid, emotion_get(aid)))
|
||||
return out
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Token 统计
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def token_add(agent_id: str, model: str, input_tokens: int, output_tokens: int) -> None:
|
||||
"""
|
||||
记一次消耗。
|
||||
|
||||
★ 输入 / 输出**分开记**(需求 3.1),而且按**模型**分桶 ——
|
||||
"按模型"是靠每行带 model 名做到的:桶是查询时 group by 出来的,
|
||||
不是提前建好的。这样换模型不会有"桶没建好"的问题。
|
||||
"""
|
||||
init()
|
||||
conn = _connect()
|
||||
conn.execute(
|
||||
'INSERT INTO token_usage (agent_id, model, input, output, created_at) '
|
||||
'VALUES (?, ?, ?, ?, ?)',
|
||||
(agent_id or '', model or '', int(input_tokens or 0), int(output_tokens or 0), now_iso()),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def token_usage(agent_id: str) -> dict:
|
||||
"""
|
||||
这个智能体的累计用量。
|
||||
|
||||
返回 `{'total': {'input':..,'output':..}, 'byModel': [{'model':..,'input':..,'output':..}]}`
|
||||
"""
|
||||
init()
|
||||
conn = _connect()
|
||||
rows = conn.execute(
|
||||
'SELECT model, SUM(input) AS i, SUM(output) AS o FROM token_usage '
|
||||
'WHERE agent_id = ? GROUP BY model ORDER BY (SUM(input) + SUM(output)) DESC',
|
||||
(agent_id or '',),
|
||||
).fetchall()
|
||||
by_model = [
|
||||
{'model': r['model'] or '(未知)', 'input': int(r['i'] or 0), 'output': int(r['o'] or 0)}
|
||||
for r in rows
|
||||
]
|
||||
return {
|
||||
'total': {
|
||||
'input': sum(m['input'] for m in by_model),
|
||||
'output': sum(m['output'] for m in by_model),
|
||||
},
|
||||
'byModel': by_model,
|
||||
}
|
||||
|
||||
|
||||
def token_reset(agent_id: str) -> int:
|
||||
"""按智能体清零(需求 3.1 的"管理操作")。返回清掉了几行"""
|
||||
init()
|
||||
conn = _connect()
|
||||
cur = conn.execute('DELETE FROM token_usage WHERE agent_id = ?', (agent_id or '',))
|
||||
conn.commit()
|
||||
return cur.rowcount
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Skill 绑定
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
def skills_of(agent_id: str) -> list:
|
||||
"""这个智能体绑定的自定义 Skill id(**按绑定顺序** —— 注入要按顺序拼)"""
|
||||
init()
|
||||
rows = _connect().execute(
|
||||
'SELECT skill_id FROM agent_skills WHERE agent_id = ? ORDER BY ord ASC, skill_id ASC',
|
||||
(agent_id or '',),
|
||||
).fetchall()
|
||||
return [r['skill_id'] for r in rows]
|
||||
|
||||
|
||||
def bind_skills(agent_id: str, skill_ids: list) -> None:
|
||||
"""整体替换绑定关系(界面上的"勾选"就是一次整体替换,不用做增删接口)"""
|
||||
init()
|
||||
conn = _connect()
|
||||
conn.execute('DELETE FROM agent_skills WHERE agent_id = ?', (agent_id or '',))
|
||||
for i, sid in enumerate(skill_ids or []):
|
||||
if not sid:
|
||||
continue
|
||||
conn.execute(
|
||||
'INSERT OR REPLACE INTO agent_skills (agent_id, skill_id, ord) VALUES (?, ?, ?)',
|
||||
(agent_id or '', sid, i),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def unbind_agent(agent_id: str) -> None:
|
||||
"""智能体被删掉时的清理(记忆**不删** —— 那是用户的数据,删了他会心疼)"""
|
||||
init()
|
||||
conn = _connect()
|
||||
conn.execute('DELETE FROM agent_skills WHERE agent_id = ?', (agent_id or '',))
|
||||
conn.execute('DELETE FROM emotions WHERE agent_id = ?', (agent_id or '',))
|
||||
conn.commit()
|
||||
@@ -39,6 +39,9 @@ import providers
|
||||
import speech
|
||||
import store
|
||||
import timeouts
|
||||
import agentdb
|
||||
import agent_api
|
||||
import agent_context
|
||||
import tools_runtime
|
||||
import uploads
|
||||
from defaults import PROVIDER_PRESETS
|
||||
@@ -579,6 +582,17 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
'mcpConfig': mcp_client.read_mcp_config(),
|
||||
'conversations': store.list_conversations(),
|
||||
'agents': store.list_agents(),
|
||||
# ---- 智能体系统的另外三种资源(需求 v1.1)----
|
||||
# 都不大(几个到几十个),一次带给界面省得进页面再拉一次
|
||||
'worldviews': store.list_resource('worldviews'),
|
||||
'modelEntries': store.list_resource('models'),
|
||||
'skills': store.list_resource('skills'),
|
||||
# AI 提的"该整理记忆了"(按智能体存),界面据此显示按钮
|
||||
'memorySuggestions': {
|
||||
a.get('id'): store.peek_summary_suggestion(a.get('id') or '')
|
||||
for a in store.list_agents()
|
||||
if store.peek_summary_suggestion(a.get('id') or '')
|
||||
},
|
||||
'toolNames': tool_names,
|
||||
'suggestedAllow': tools_runtime.suggest_allowlist(tool_names),
|
||||
# 前端用它挑终端里的预设命令(安卓的 getprop / Windows 的 dir 不通用)
|
||||
@@ -1257,27 +1271,15 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
self.send_json(200, {'ok': True})
|
||||
return True
|
||||
|
||||
# 智能体
|
||||
if pathname == '/api/agents' and method == 'GET':
|
||||
self.send_json(200, {'agents': store.list_agents()})
|
||||
# 智能体系统的接口(记忆 / 情绪 / Token / 世界观 / 模型列表 / Skill / 导入导出)
|
||||
#
|
||||
# ★ 全部集中在 agent_api.py 里 —— app.py 已经 1800 行,二十多个新接口
|
||||
# 塞进来会让这个文件彻底没法看。
|
||||
# ★ 老的 /api/agents 那三个路由**删掉了**(原来在下面),由这里统一处理:
|
||||
# 留着就是两份实现,而新那份多了"内置智能体不能删"的保护 ——
|
||||
# 两份并存的话,哪份生效取决于顺序,这种 bug 最难查。
|
||||
if agent_api.handle(self, pathname, method):
|
||||
return True
|
||||
if pathname == '/api/agents' and method == 'POST':
|
||||
body = self.read_json_body()
|
||||
self.send_json(200, {'agent': store.create_agent(body)})
|
||||
return True
|
||||
agent_id = self._match_id(pathname, '/api/agents/')
|
||||
if agent_id is not None:
|
||||
if method in ('PATCH', 'PUT'):
|
||||
body = self.read_json_body()
|
||||
agent = store.update_agent(agent_id, body)
|
||||
if agent:
|
||||
self.send_json(200, {'agent': agent})
|
||||
else:
|
||||
self.send_json(404, {'error': '智能体不存在'})
|
||||
return True
|
||||
if method == 'DELETE':
|
||||
self.send_json(200 if store.delete_agent(agent_id) else 404, {'ok': True})
|
||||
return True
|
||||
|
||||
# 附件
|
||||
if pathname == '/api/upload' and method == 'POST':
|
||||
@@ -1426,7 +1428,19 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
)
|
||||
merged_agent = {'systemPrompt': sys_prompt, 'id': '', 'name': '判断器'}
|
||||
else:
|
||||
base = (agent or {}).get('systemPrompt') or cfg.get('systemPrompt') or ''
|
||||
# ★ 会议节点也走**同一套** system prompt 拼装(需求附录 C)。
|
||||
#
|
||||
# 以前这里是自己拼的(`agent.systemPrompt or cfg.systemPrompt`),
|
||||
# 于是同一个智能体在聊天里有记忆/情绪/世界观、在会议节点里没有 ——
|
||||
# "引擎改了另一端必须跟上"这条在这个仓库里踩过好几次,
|
||||
# 所以这次直接复用 agent_context,别再抄一份。
|
||||
#
|
||||
# ★ 节点的额外要求 / 输出要求 / 变量说明仍然**追加在后面**:
|
||||
# 它们是"这一轮的任务约束",比人设更具体,放最后模型才看得重。
|
||||
if agent:
|
||||
base = agent_context.build_system_prompt(store.read_settings(), agent)
|
||||
else:
|
||||
base = cfg.get('systemPrompt') or ''
|
||||
parts = [base] if base.strip() else []
|
||||
if extra:
|
||||
parts.append('【本次任务的额外要求】\n' + extra)
|
||||
@@ -1638,6 +1652,45 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
has_image = any(p.get('type') == 'image_url' for p in parts)
|
||||
user_content = parts if (has_image or len(parts) > 1) else text
|
||||
agent = store.get_agent(body.get('agentId')) or store.get_agent(settings.get('activeAgentId'))
|
||||
agent_id = (agent or {}).get('id') or ''
|
||||
|
||||
# ★★ Token 限额:**发起前**拦(需求 3.1)。
|
||||
#
|
||||
# 判定时机是"返回后结算 + 下一轮发起前检查"—— 所以这里查的是
|
||||
# **已经攒下来的**用量,超了就根本不发这一轮。
|
||||
#
|
||||
# ★ 拦在"写用户消息之前":拦住了还把用户那句话落库的话,
|
||||
# 他会看到自己发的消息挂在那儿、AI 永远不回,以为卡住了。
|
||||
#
|
||||
# ★ 豁免:记忆整理、导出这些**非对话生成**的操作不走这里
|
||||
# (它们有自己的接口),所以不会被限额挡住。
|
||||
try:
|
||||
limit = int(float((agent or {}).get('tokenLimit') or 0))
|
||||
except (TypeError, ValueError):
|
||||
limit = 0
|
||||
if limit > 0 and agent_id:
|
||||
used = sum(agentdb.token_usage(agent_id)['total'].values())
|
||||
if used >= limit:
|
||||
farewell = (settings.get('tokenLimitFarewell') or '我没力气再说话了……').strip()
|
||||
store.append_messages(conversation_id, [{
|
||||
'role': 'assistant',
|
||||
'content': farewell,
|
||||
'agentId': agent_id,
|
||||
# ★ 标一下"这不是模型生成的":界面据此把它显示成提示样式,
|
||||
# 而且重新生成时不会被当成一条正常的 AI 回复
|
||||
'limitNotice': True,
|
||||
'at': store.now_iso(),
|
||||
}])
|
||||
emit({
|
||||
'type': 'error',
|
||||
'code': 'token_limit',
|
||||
'message': f'{(agent or {}).get("name") or "这个智能体"}的 Token 额度用完了',
|
||||
'used': used,
|
||||
'limit': limit,
|
||||
'farewell': farewell,
|
||||
'hint': '可以清零重新开始,或者把限额调大 / 改成无限制。',
|
||||
})
|
||||
return
|
||||
|
||||
store.append_messages(conversation_id, [{
|
||||
'role': 'user',
|
||||
@@ -1661,14 +1714,28 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
send_depth=send_depth,
|
||||
)
|
||||
|
||||
# ★ 这一轮的 Token 用量(需求 4.1:对话界面显示"本次对话"的用量)。
|
||||
# 按轮记在消息上,会话级用量是**加起来**算的 —— 这样"重新生成"
|
||||
# 把上一条替换掉时,它的消耗也跟着消失,不会虚高。
|
||||
in_tok, out_tok = agent_loop.usage_pair(result.get('usage'))
|
||||
model_name = (store.provider_info(settings, agent) or {}).get('model') or ''
|
||||
|
||||
store.append_messages(conversation_id, [{
|
||||
'role': 'assistant',
|
||||
'content': result.get('content', ''),
|
||||
# 思维链也要落库,否则一刷新「思考过程」就没了
|
||||
'reasoning': result.get('reasoning', '') or '',
|
||||
'agentId': (agent or {}).get('id') or '',
|
||||
'agentId': agent_id,
|
||||
'usage': {'input': in_tok, 'output': out_tok},
|
||||
'at': store.now_iso(),
|
||||
}])
|
||||
# ★ 智能体级累计(需求 3.1):**按模型分桶、输入输出分开**。
|
||||
# 记失败不影响这一轮对话 —— 统计是附加价值,不能让它把回复搞崩。
|
||||
if agent_id and (in_tok or out_tok):
|
||||
try:
|
||||
agentdb.token_add(agent_id, model_name, in_tok, out_tok)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f'[usage] 记 Token 用量失败:{exc}', file=sys.stderr)
|
||||
conv = store.get_conversation(conversation_id) or {}
|
||||
emit({'type': 'saved', 'conversationId': conversation_id, 'title': conv.get('title')})
|
||||
except Exception as exc: # noqa: BLE001 - 出错也要以 error 事件收尾,前端才知道停了
|
||||
|
||||
@@ -344,3 +344,13 @@ BUILTIN_TOOLS = {
|
||||
'shell': {'spec': SHELL_TOOL, 'run': shell_run},
|
||||
'python_run': {'spec': PYTHON_RUN_TOOL, 'run': python_run},
|
||||
}
|
||||
|
||||
# 智能体系统的工具(记忆 / 情绪 / 用量)也走**进程内**实现 —— 它们要读写
|
||||
# `agent.db`,而电脑端的文件工具是子进程,根本 import 不到内核模块。
|
||||
#
|
||||
# ★ 合并进这一个字典而不是让 tools_runtime 从两处取:
|
||||
# 发现工具、找入口、判"要不要豁免超时"全都只认 BUILTIN_TOOLS,
|
||||
# 多一个来源就多一处"忘了查"的机会(加进来之后自动全部生效)。
|
||||
from agent_tools import AGENT_TOOLS # noqa: E402
|
||||
|
||||
BUILTIN_TOOLS.update(AGENT_TOOLS)
|
||||
|
||||
@@ -222,6 +222,69 @@ DEFAULT_SETTINGS = {
|
||||
|
||||
SECRET_KEYS = {'apiKey'}
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 智能体系统(需求 v1.1)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
# 内置 Skill:记忆 / 情绪 / 检索 / 用量这几个工具的**使用手册**(需求 3.7)。
|
||||
#
|
||||
# ★ 为什么不把这些写进工具自己的 description:
|
||||
# 工具的 description 只讲"这个工具怎么调",而 Skill 讲的是
|
||||
# "**什么时候该用、用完之后不许干什么**"—— 后者才是模型最容易犯错的地方
|
||||
# (最典型的是"只在嘴上说记住了、根本没调工具")。
|
||||
# 放在 <skills> 段里,每个智能体都能看到;自定义 Skill 按同样的方式追加。
|
||||
BUILTIN_SKILL = '\n'.join([
|
||||
'【记忆】你有自己的记忆库,**跨对话保留**:',
|
||||
'· 用户说了值得长期记住的事(称呼、偏好、重要事实、约定、他的项目),用 memory_add 记下来。',
|
||||
'· 记之前先看上面的记忆清单 —— 已经记过的不要再记一遍,否则清单会越来越乱。',
|
||||
'· 记错了/过时了用 memory_update 改;确实不该留的用 memory_forget 删(只能删你自己写的)。',
|
||||
'· 清单里只有标题,需要正文细节时用 memory_search 检索。',
|
||||
'★★ 绝对不要只在回复里说"我记住了"却不调用 memory_add。',
|
||||
' 说了要记就必须真的调工具;没调就别说这句话 —— 用户会当场发现你在骗他。',
|
||||
'',
|
||||
'【情绪】emotion_set 改的是**你自己**的情绪状态,下次对话还在。',
|
||||
' 情绪要跟着对话内容自然变化;别每轮都改,也别一直用同一个词。',
|
||||
'',
|
||||
'【用量】用户问"你还能说多少""用了多少 token"时,用 get_token_usage 查真实数字,别猜。',
|
||||
])
|
||||
|
||||
# system prompt 的注入模板(需求附录 C)。
|
||||
#
|
||||
# 顺序是**固定**的:人设 → skills → worldview → emotion → memory → peer_emotions。
|
||||
# 可以整段替换(存全局设置 promptTemplate),但占位符名字别改 ——
|
||||
# agent_context.py 就是按这些名字找段落、空段整段删掉的。
|
||||
DEFAULT_PROMPT_TEMPLATE = '\n'.join([
|
||||
'{prompt}',
|
||||
'',
|
||||
'<skills>',
|
||||
'{skills}',
|
||||
'</skills>',
|
||||
'',
|
||||
'<worldview>',
|
||||
'{worldview}',
|
||||
'</worldview>',
|
||||
'',
|
||||
'<emotion>',
|
||||
'{emotion}',
|
||||
'</emotion>',
|
||||
'',
|
||||
'<memory>',
|
||||
'{memory}',
|
||||
'</memory>',
|
||||
'',
|
||||
'<peer_emotions>',
|
||||
'{peer_emotions}',
|
||||
'</peer_emotions>',
|
||||
])
|
||||
|
||||
# 记忆注入时的条目模板(附录 C 的 `【标题1】内容1`)。
|
||||
#
|
||||
# ★ 是**全量注入**(标题 + 正文都进去)—— 需求 3.2 的"主动记忆:smartMemory
|
||||
# 全量注入 system prompt"。正文不进的话模型只知道"我记过这件事",
|
||||
# 每次要用都得再检索一次,白花一轮。
|
||||
DEFAULT_MEMORY_LINE = '【{title}】{content}'
|
||||
|
||||
|
||||
# 内置智能体(前端有同名头像,靠 avatar 字段对应)
|
||||
DEFAULT_AGENTS = [
|
||||
{
|
||||
|
||||
@@ -44,6 +44,11 @@ BUNDLED_TOOL_FILES = [
|
||||
'notifications.py',
|
||||
'apps.py',
|
||||
'volume.py',
|
||||
# ★ web_search.py 以前漏在清单外(对拍脚本抓出来的)。
|
||||
# 它其实**照样会被播种**(构建脚本遍历整个 tools/ 目录,
|
||||
# _seed_tools 又用那份源码整体补齐),所以功能上没缺 ——
|
||||
# 但清单是"内置工具一览"的文档,和现实不一致就会误导下一个人。
|
||||
'web_search.py',
|
||||
'_mcp_python_example.py',
|
||||
]
|
||||
|
||||
|
||||
@@ -86,6 +86,19 @@ class Paths:
|
||||
self.conversations_file = os.path.join(self.data_dir, 'conversations.json')
|
||||
self.agents_file = os.path.join(self.data_dir, 'agents.json')
|
||||
self.mcp_file = os.path.join(self.data_dir, 'mcp.servers.json')
|
||||
# ---- 智能体系统的另外三种资源(需求 v1.1)----
|
||||
#
|
||||
# ★ 和 agents.json 一样是 JSON、一人一个文件:它们的量级也是"几个到几十个",
|
||||
# 而且要人肉可读(用户会想直接看自己建的世界观写成什么样)。
|
||||
# 会**持续增长**的那些(记忆 / 情绪 / Token 统计)在 agent.db 里,
|
||||
# 分界线见 agentdb.py 的文件头。
|
||||
self.worldviews_file = os.path.join(self.data_dir, 'worldviews.json')
|
||||
self.models_file = os.path.join(self.data_dir, 'models.json')
|
||||
self.skills_file = os.path.join(self.data_dir, 'skills.json')
|
||||
# 智能体系统的 SQLite(记忆 / 情绪 / Token / 绑定关系)
|
||||
self.agent_db_file = os.path.join(self.data_dir, 'agent.db')
|
||||
# 智能体包解出来的图片等资源(导入 zip 时落到这儿)
|
||||
self.agent_assets_dir = os.path.join(self.data_dir, 'agent-assets')
|
||||
|
||||
@staticmethod
|
||||
def _resolve_web_core(explicit: str | None) -> str:
|
||||
@@ -103,7 +116,7 @@ class Paths:
|
||||
|
||||
def ensure_dirs(self) -> None:
|
||||
for folder in (self.data_dir, self.uploads_dir, self.tmp_dir, self.screens_dir,
|
||||
self.notes_dir):
|
||||
self.notes_dir, self.agent_assets_dir):
|
||||
try:
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
except OSError as exc: # 安卓上外部存储没授权时会失败,不能让它把进程打死
|
||||
|
||||
@@ -21,6 +21,7 @@ import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import paths
|
||||
import agentdb
|
||||
from defaults import DEFAULT_AGENTS, DEFAULT_SETTINGS, PROVIDER_PRESETS
|
||||
|
||||
_lock = threading.RLock()
|
||||
@@ -817,6 +818,38 @@ def clear_pending_ui(conv_id: str) -> None:
|
||||
_pending_ui.pop(conv_id, None)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 「建议整理记忆」的待处理队列
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# AI 用 memory_suggest_summary 提的建议 —— **只提示不执行**(需求 3.2)。
|
||||
# 界面读到之后给用户一个「整理记忆」按钮,用户点了才真的跑总结。
|
||||
#
|
||||
# ★ 为什么放内存而不是落库:它是一次性的提示,用户处理完就该消失。
|
||||
# 落库的话重启一次 App 会看到三天前那条建议,莫名其妙。
|
||||
# ★ 按智能体存(不是按会话):建议是"你的记忆该整理了",跟哪个会话无关。
|
||||
_pending_summary: dict = {}
|
||||
|
||||
|
||||
def add_pending_summary_suggestion(agent_id: str, reason: str) -> None:
|
||||
"""同一个人后来的建议**覆盖**前面的 —— 说两遍没有意义"""
|
||||
if not agent_id:
|
||||
return
|
||||
with _lock:
|
||||
_pending_summary[agent_id] = (reason or '').strip()
|
||||
|
||||
|
||||
def peek_summary_suggestion(agent_id: str) -> str:
|
||||
with _lock:
|
||||
return _pending_summary.get(agent_id or '', '')
|
||||
|
||||
|
||||
def take_summary_suggestion(agent_id: str) -> str:
|
||||
"""取走(取完就没了)"""
|
||||
with _lock:
|
||||
return _pending_summary.pop(agent_id or '', '')
|
||||
|
||||
|
||||
def create_conversation(title: str = '新对话', agent_id: str | None = None) -> dict:
|
||||
item = {
|
||||
'id': _rid_conv(),
|
||||
@@ -899,18 +932,74 @@ def store_file_path() -> str:
|
||||
# 提成常量是为了 create / update 两边不会漂移:
|
||||
# 之前这两个函数各写一份硬编码白名单,加字段时漏改一处,
|
||||
# 表现就是"界面上填了、保存后再打开又变空了"。
|
||||
AGENT_FIELDS = (
|
||||
#
|
||||
# ★ v1.1 新增(《智能体系统需求文档》),字段按类型分开,见下面的 _apply_agent_patch:
|
||||
# description 选择界面上展示的介绍文案(2.1)
|
||||
# image 外观四件套 front / back / border-main / border-info(2.5)
|
||||
# modelId 引用全局模型列表里的一个(3.3 多模型)
|
||||
# worldviewId 绑定的世界观(3.6)
|
||||
# emotionEnabled 情绪感知开关(3.5)
|
||||
# tokenLimit Token 限额,0 = 无限制(3.1)
|
||||
# skillIds 绑定的自定义 Skill(3.7;真正的绑定关系在 agent.db)
|
||||
AGENT_TEXT_FIELDS = (
|
||||
'name', 'avatar', 'tagline', 'description', 'systemPrompt',
|
||||
'provider', # 走哪家(留空 = 全局)
|
||||
'model', # 用哪个模型
|
||||
'baseUrl', # 自定义网关地址
|
||||
'ttsEngine', # 朗读引擎:system / volcv3 / volc / openai
|
||||
'ttsVoice', # 音色 —— 多人会议里靠它区分谁在说话
|
||||
'modelId', # ← 全局模型列表里的 id
|
||||
'worldviewId', # ← 绑定的世界观 id
|
||||
)
|
||||
AGENT_NUM_FIELDS = (
|
||||
'ttsSpeed', # 语速
|
||||
'tokenLimit', # 0 = 无限制(不是"限额为 0")
|
||||
)
|
||||
AGENT_BOOL_FIELDS = ('emotionEnabled',)
|
||||
AGENT_LIST_FIELDS = ('skillIds',)
|
||||
AGENT_DICT_FIELDS = ('image',)
|
||||
|
||||
#: 能被 patch 改的全部字段(界面上"这个智能体有哪些可配"就看它)
|
||||
AGENT_FIELDS = (
|
||||
AGENT_TEXT_FIELDS + AGENT_NUM_FIELDS + AGENT_BOOL_FIELDS
|
||||
+ AGENT_LIST_FIELDS + AGENT_DICT_FIELDS
|
||||
)
|
||||
|
||||
|
||||
def _rid_agent() -> str:
|
||||
return f'a_{_ts36()}_{_rand36(4)}'
|
||||
def _apply_agent_patch(agent: dict, patch: dict) -> dict:
|
||||
"""
|
||||
把 patch 里的字段规整进 agent。
|
||||
|
||||
★ **create 和 update 共用这一份** —— 它们以前各写一份白名单,
|
||||
加字段漏改一处就是"界面上填了、保存后再打开又变空了"这种查半天的 bug。
|
||||
★ 类型规整也在这里:从 HTTP 来的东西可能是字符串(`"true"`、`"3"`),
|
||||
直接存进去会让界面读到时类型不对(勾选框永远是空的)。
|
||||
"""
|
||||
patch = patch or {}
|
||||
for key in AGENT_TEXT_FIELDS:
|
||||
if patch.get(key) is not None:
|
||||
agent[key] = _as_text(patch[key])
|
||||
for key in AGENT_NUM_FIELDS:
|
||||
if patch.get(key) is not None:
|
||||
try:
|
||||
agent[key] = float(patch[key])
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
for key in AGENT_BOOL_FIELDS:
|
||||
if patch.get(key) is not None:
|
||||
agent[key] = bool(patch[key])
|
||||
for key in AGENT_LIST_FIELDS:
|
||||
if patch.get(key) is not None:
|
||||
raw = patch[key]
|
||||
agent[key] = [str(x) for x in raw] if isinstance(raw, list) else []
|
||||
for key in AGENT_DICT_FIELDS:
|
||||
if patch.get(key) is not None:
|
||||
raw = patch[key]
|
||||
agent[key] = (
|
||||
{str(k): _as_text(v) for k, v in raw.items()}
|
||||
if isinstance(raw, dict) else {}
|
||||
)
|
||||
return agent
|
||||
|
||||
|
||||
def list_agents() -> list:
|
||||
@@ -938,19 +1027,19 @@ def get_agent(agent_id: str | None):
|
||||
def create_agent(payload: dict) -> dict:
|
||||
payload = payload or {}
|
||||
state = {'agents': list_agents()}
|
||||
# ★ id 一律 UUID(需求附录 A):`name` 只是显示名,允许重复、允许随便改,
|
||||
# 所有关联(记忆作者、Token 统计、Skill 绑定)都挂在这个 id 上。
|
||||
# 老数据里的 `a_doubao` 这种短 id **保留不动** —— 会话语料引用着它们。
|
||||
agent = {
|
||||
'id': _rid_agent(),
|
||||
'id': agentdb.new_id(),
|
||||
'name': _as_text(payload.get('name') or '新智能体')[:24],
|
||||
'avatar': payload.get('avatar') or 'custom',
|
||||
'avatar': _as_text(payload.get('avatar') or 'custom'),
|
||||
'tagline': _as_text(payload.get('tagline'))[:40],
|
||||
'systemPrompt': _as_text(payload.get('systemPrompt')),
|
||||
'builtin': False,
|
||||
'createdAt': now_iso(),
|
||||
}
|
||||
# 智能体自己的模型/语音(留空 = 继承全局)
|
||||
for key in AGENT_FIELDS:
|
||||
if payload.get(key) is not None:
|
||||
agent[key] = _as_text(payload.get(key))
|
||||
_apply_agent_patch(agent, payload)
|
||||
state['agents'].append(agent)
|
||||
_write_json(paths.get().agents_file, state)
|
||||
return agent
|
||||
@@ -961,10 +1050,7 @@ def update_agent(agent_id: str, patch: dict):
|
||||
agent = next((a for a in state['agents'] if a.get('id') == agent_id), None)
|
||||
if not agent:
|
||||
return None
|
||||
patch = patch or {}
|
||||
for key in ('name', 'avatar', 'tagline', 'systemPrompt', *AGENT_FIELDS):
|
||||
if patch.get(key) is not None:
|
||||
agent[key] = patch[key]
|
||||
_apply_agent_patch(agent, patch)
|
||||
_write_json(paths.get().agents_file, state)
|
||||
return agent
|
||||
|
||||
@@ -976,6 +1062,141 @@ def delete_agent(agent_id: str) -> bool:
|
||||
return False
|
||||
state['agents'].pop(index)
|
||||
_write_json(paths.get().agents_file, state)
|
||||
# 清掉它在数据库里的绑定关系和情绪;**记忆不删** —— 那是用户的数据,
|
||||
# 删智能体顺手把他攒了几个月的记忆抹掉,他会心疼(而且没法恢复)
|
||||
try:
|
||||
agentdb.unbind_agent(agent_id)
|
||||
except Exception as exc: # noqa: BLE001 - 清理失败不该让删除失败
|
||||
print(f'[store] 清理 {agent_id} 的绑定关系失败:{exc}', file=sys.stderr)
|
||||
return True
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 通用资源表:世界观 / 全局模型 / Skill
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★ 三者的 CRUD 完全一样(列表 + 增 + 改 + 删 + UUID 主键),所以**只写一份** ——
|
||||
# 区别只是"有哪些字段",那部分在 RESOURCES 里声明。
|
||||
#
|
||||
# ★ 为什么不放 agent.db(SQLite):它们的量级和 agents.json 一样是"几个到几十个"
|
||||
# (用户自己会去数),而且要人肉可读。分界线见 agentdb.py 的文件头。
|
||||
|
||||
RESOURCES = {
|
||||
# 世界观(需求 3.6):名字 + 设定文本 + 外观四件套
|
||||
'worldviews': {
|
||||
'file': lambda: paths.get().worldviews_file,
|
||||
'key': 'worldviews',
|
||||
'text': ('name', 'setting'),
|
||||
'dict': ('image',),
|
||||
'label': '世界观',
|
||||
},
|
||||
# 全局模型列表(需求 3.3):名称 + API 端点 + Key + 模型标识 + 单价
|
||||
'models': {
|
||||
'file': lambda: paths.get().models_file,
|
||||
'key': 'models',
|
||||
'text': ('name', 'apiBase', 'apiKey', 'model', 'provider'),
|
||||
'num': ('pricePerK',), # 元/千 Token,0 = 不显示费用估算
|
||||
'label': '模型',
|
||||
},
|
||||
# Skill(需求 3.7):纯文本的"工具使用手册"
|
||||
'skills': {
|
||||
'file': lambda: paths.get().skills_file,
|
||||
'key': 'skills',
|
||||
'text': ('name', 'content'),
|
||||
'bool': ('builtin',),
|
||||
'label': 'Skill',
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _res(name: str) -> dict:
|
||||
cfg = RESOURCES.get(name)
|
||||
if not cfg:
|
||||
raise KeyError(f'没有这种资源:{name}')
|
||||
return cfg
|
||||
|
||||
|
||||
def list_resource(name: str) -> list:
|
||||
cfg = _res(name)
|
||||
file_path = cfg['file']()
|
||||
data = _read_json(file_path)
|
||||
if not isinstance(data, dict) or not isinstance(data.get(cfg['key']), list):
|
||||
return []
|
||||
return data[cfg['key']]
|
||||
|
||||
|
||||
def _write_resource(name: str, items: list) -> None:
|
||||
cfg = _res(name)
|
||||
_write_json(cfg['file'](), {cfg['key']: items})
|
||||
|
||||
|
||||
def get_resource(name: str, rid: str):
|
||||
if not rid:
|
||||
return None
|
||||
for item in list_resource(name):
|
||||
if item.get('id') == rid:
|
||||
return item
|
||||
return None
|
||||
|
||||
|
||||
def _apply_resource_patch(name: str, item: dict, patch: dict) -> dict:
|
||||
cfg = _res(name)
|
||||
patch = patch or {}
|
||||
for key in cfg.get('text', ()):
|
||||
if patch.get(key) is not None:
|
||||
item[key] = _as_text(patch[key])
|
||||
for key in cfg.get('num', ()):
|
||||
if patch.get(key) is not None:
|
||||
try:
|
||||
item[key] = float(patch[key])
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
for key in cfg.get('bool', ()):
|
||||
if patch.get(key) is not None:
|
||||
item[key] = bool(patch[key])
|
||||
for key in cfg.get('dict', ()):
|
||||
if patch.get(key) is not None:
|
||||
raw = patch[key]
|
||||
item[key] = (
|
||||
{str(k): _as_text(v) for k, v in raw.items()}
|
||||
if isinstance(raw, dict) else {}
|
||||
)
|
||||
return item
|
||||
|
||||
|
||||
def create_resource(name: str, payload: dict) -> dict:
|
||||
cfg = _res(name)
|
||||
items = list_resource(name)
|
||||
item = {
|
||||
'id': agentdb.new_id(), # ★ UUID(需求附录 A)
|
||||
'name': _as_text((payload or {}).get('name'))[:40],
|
||||
'builtin': False,
|
||||
'createdAt': now_iso(),
|
||||
}
|
||||
_apply_resource_patch(name, item, payload)
|
||||
# 重名不拦(需求 2.5:重名由用户自己区分),但界面要能看出来,
|
||||
# 所以这里不做任何"自动改名" —— 显示时加序号是界面的事
|
||||
items.append(item)
|
||||
_write_resource(name, items)
|
||||
return item
|
||||
|
||||
|
||||
def update_resource(name: str, rid: str, patch: dict):
|
||||
items = list_resource(name)
|
||||
item = next((x for x in items if x.get('id') == rid), None)
|
||||
if not item:
|
||||
return None
|
||||
_apply_resource_patch(name, item, patch)
|
||||
_write_resource(name, items)
|
||||
return item
|
||||
|
||||
|
||||
def delete_resource(name: str, rid: str) -> bool:
|
||||
items = list_resource(name)
|
||||
left = [x for x in items if x.get('id') != rid]
|
||||
if len(left) == len(items):
|
||||
return False
|
||||
_write_resource(name, left)
|
||||
return True
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user