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
|
||||
Reference in New Issue
Block a user