feat(agents): 新增「智能体」功能模块(路线 A)+ 版本 2.5.0

老板要求「在 ai 网关里做智能体 agent,新的一个菜单」,一期仅管理员、成熟后下发。
完整设计(27 条决策,4 轮评审)见 docs/agents-dev-plan.md。

架构(路线 A):界面与权限在网关,执行在 QwenPaw(独立 profile ai-gateway)。
网关当门面(鉴权/计量/灰度/审计),引擎提供工具能力(文件/命令/浏览器)。

Step -1 技术验证(实测,全部改变或确认了设计):
- 请求级指定模型【无效】:传 model 被忽略,turn_usage 回 provider_id=opencode、
  model_name=deepseek-v4.1-flash;AgentRequest 无 model 字段。模型是 profile 级。
  → 甲案:所有智能体共用 ai-gateway 一个 profile ⇒ 共用同一模型,配置页模型栏只读。
- role:"system"【被接受且生效】:塞入「只用英文回答」后模型真的用英文
  → params.system_suffix 走注入 system 消息。
- SSE 事件谱已录制 → tests/fixtures/sse-tool-flow.sse + docs/qwenpaw-agent-api-sse.md

后端:
- app/agents.py:AgentStore(data/agents.yaml,600/原子写/mtime 热载)+ 严格校验
  (slug 三重查重:模型 id/别名/QwenPaw profile;params 4 键白名单;suffix 限长 2000;
   max_agents=5 软上限,归档不计入;restore 可恢复)
- app/adapters/qwenpaw_engine.py:OpenAI 形状 ↔ AgentScope Agent API + SSE 翻译器
  (text 累积、delta:false 快照忽略、plugin_call→轨迹、call_id 配对 output、turn_usage→计量)
- app/agents_routes.py:GET/POST/PUT/DELETE /agents、/restore、/chat(SSE)、/stop、
  /runs、/sessions、/test + 新增 GET /auth/me(灰度通道,features.agents 后端权威);
  权限唯一入口 can_use_agent();防自指(引擎模型不得指向 agent/*)
- app/history.py:会话类别扩展支持 agent_<slug>(复用现有存储)
- data/agents.yaml(配置,入库);data/agent_runs.json(运行时,gitignore)

前端:
- views/Agents.vue(列表 + 对话/配置/运行记录)+ lib/agents.ts(SSE 解析)
- 菜单核心组第 5 位 + 图标 bot;router meta.admin 双层守卫;i18n 中英对称 871/871

上线实测:真实对话跑通 —— 让智能体 read_file 读 /etc/hostname,前端正确显示
「执行了 1 步」+ 工具参数、正文、计量(wjd · 47196 tokens · 缓存 13696)、终态;
引擎调用经 wangjinding 过网关(计量闭环)。

测试 209 → 217 全过(新增 8 条,含用真实夹具验证 SSE 翻译器);ci_check 全绿。
This commit is contained in:
api-gateway committed 2026-09-29 13:22:12 +08:00
1 parent 4c04a5ed0e
commit c0706d1846
19 files changed
+3064 -26

No files matched your search

+38 -15
View File
@@ -148,24 +148,31 @@
## 2. 开发步骤
### Step -1 · 技术验证(约 0.5h)★ 动手前先做
### Step -1 · 技术验证 ✅ **已完成**(2026-09-29)
```
1. ✔ 已做:核实"请求级指定模型"不可行(见 ⑲)→ 方案已按甲案修正
2. ✔ 已做:确认 PUT/GET /api/providers/active 支持 scope=agent + agent_id
3. 待做:录一段**完整真实 SSE 事件流**(含工具调用)当 Step 2 的测试夹具
4. 待做:确认 X-Agent-Id 选 profile 的行为(新建 profile 后)
4b. ★ 待做:**QwenPaw 的 `input` 接不接受 `role: "system"` 的消息**(决定 `system_suffix` 的注入方式,见 ㉖)
· 接受 → 网关插入一条 system 消息(干净)
· 不接受 → 改成拼进首条 user 消息前缀(UI 标注)
5. 待做:确认 ai-gateway profile 的 active_model 指向哪个 provider/model
(建议指向网关自己的 wangjinding provider + 别名 wjd,
这样引擎调模型也过网关,计量闭环)
```
| # | 验证项 | 结论 |
|---|---|---|
| 1 | 请求级指定模型是否可行 | ❌ **不可行** → 方案已按甲案修正(见 ⑲) |
| 2 | `PUT/GET /api/providers/active` 的 scope | ✅ 支持 `scope=agent` + `agent_id` |
| 3 | **SSE 事件谱 + 夹具** | ✅ **已录制并落盘** → 见下 |
| 4 | `X-Agent-Id` 选 profile | ✅ 生效(实测带 `X-Agent-Id: default` 走 default 的会话/记忆) |
| 4b | **`input` 接不接受 `role:"system"`** | ✅ **接受且真的生效** → `system_suffix` 用方案 ④(注入 system 消息) |
| 5 | `ai-gateway` 的 active_model 指向 | ✅ 已确认为 `wangjinding` / `wjd`(引擎调用过网关,计量闭环成立) |
**验收**:5 项都有明确结论;SSE 夹具落盘。
**产出物**:
- `tests/fixtures/sse-tool-flow.sse` —— 真实含工具调用的 SSE(14,900 字节 / 57 事件)
- `docs/qwenpaw-agent-api-sse.md` —— **完整事件谱 + 适配器映射表**(Step 2 实现依据)
### Step 0 · 建 QwenPaw profile `ai-gateway`(约 1h)★ 新增
**事件谱要点(实测)**:`text`(36,正文增量,`delta:true` 累积 / `delta:false` 是快照要忽略) ·
`plugin_call`(工具调用,名在 `content[0].data.name`、参数是 JSON 字符串) ·
`plugin_call_output`(结果,在 `data.output`,用 `call_id` 配对) · `data`(分片,**忽略**) ·
`response`(终态,`status: completed/failed/cancelled`) · `turn_usage`(**记 token/成本 的直接来源**,
带 `model_name` 与缓存字段)。
**顺序**:文本 → 工具调用 → 工具结果 → 更多文本 → … → `response` → `turn_usage`(同一响应内穿插)。
**另一条实测**:`GET /healthz` **只回 `{"status":"ok"}` 不含版本** —— 验版本要读 `GET /` 的 `version`。
### Step 0 · 建 QwenPaw profile `ai-gateway` ✅ **已完成**(2026-09-29)
```
0. 备份:cp ~/.qwenpaw/config.json → config.json.bak-<日期>(记回滚方式)
@@ -184,6 +191,22 @@
```
**验收**:`X-Agent-Id: ai-gateway` 跑通一轮对话;`default` 行为与之前一致。
**实际完成情况(实测)**:
| 项 | 结果 |
|---|---|
| 备份 | `config.json.bak-20260929-agents` |
| 工作区 | `<工作区>/`(**全新空白,未复制 default 的任何私人文件**) |
| 提示词 | 新写 `SOUL.md` + `AGENTS.md`(网关智能体版);`system_prompt_files: ["AGENTS.md","SOUL.md"]`(**不含 PROFILE.md**) |
| 注册 | `config.json` 的 `agents.profiles` + `agent_order` 均已加 `ai-gateway` |
| 工具 | ✅ **全开 27 个**(决策⑪);`approval_level: OFF` |
| 模型 | `active_model = {provider_id: "wangjinding", model: "wjd"}` |
| 引擎 Key | 新建 `agent-engine`(label),明文暂存 `/tmp/agent_engine_key`(600),待写入 QwenPaw 配置 |
| **profile 可用性** | ✅ 实测 `X-Agent-Id: ai-gateway` 跑通,"网关就绪"正常返回 |
| **模型指向** | ✅ `turn_usage` 明证 `provider_id: wangjinding / model_name: wjd` → **引擎过网关,计量闭环** |
| **隔离验证** | ✅ 问"你是谁/认识老板吗",答"没有个人身份、没有个人记忆…没有任何关于「老板」的信息",并实际检查了工作区记忆文件 |
| `default` 是否受影响 | ✅ 无影响(新建 profile 不动已有 profile) |
**注意**:改 `config.json` 会触发配置重载。实测口径是"新增 profile 不影响已有 profile",
但**仍要先备份**;若发现 `default` 会话中断,立即回滚。
+169
View File
@@ -0,0 +1,169 @@
# QwenPaw Agent API · SSE 事件谱(2026-09-29 实测录制)
> 来源:真实打 `POST http://127.0.0.1:8088/api/console/chat`(带 `X-Agent-Id: default`),
> 让它执行一次 `read_file` 工具调用,全程录下 SSE。
> 原始夹具:`tests/fixtures/sse-tool-flow.sse`(14,900 字节 / 57 个事件)
> 用途:**Step 2 引擎适配器的映射依据** + 单测夹具。
---
## 1. 事件总览(本次录制)
| 事件 `type` | 次数 | 含义 |
|---|---|---|
| `text` | 36 | 正文增量(**流式的主体**) |
| `data` | 9 | 结构化数据块(工具调用的参数/输出分片) |
| `message` | 4 | 一条完整消息(开始/结束快照) |
| `response` | 3 | 整个响应的开始/结束(**终态在这里**) |
| `plugin_call` | 2 | 工具调用(开始) |
| `plugin_call_output` | 2 | 工具执行结果 |
| `turn_usage` | 1 | 本轮 token 用量 + 上下文占用(**在最后**) |
每条 SSE 行的前缀固定是 `data: `,后跟一个 JSON 对象(**没有 `event:` 行**)。
---
## 2. 事件序列时序(实测顺序)
```
0. response ← 响应开始(status=created)
1. response ← status=in_progress
2. message ← 助手消息开始(content=[])
3-6. text ×4 ← 正文增量:"I" / "'ll read that" / " file for" / " you.\n\n"
7. text ← delta=false,整段快照("I'll read that file for you.")
8. message ← 助手消息完成(status=completed,含完整 content)
9. plugin_call ← 工具调用开始(role=assistant,name=read_file)
10-15. data ×6 ← 工具参数分片(call_id / name / arguments)
16. plugin_call ← 工具调用的完整快照
17. plugin_call_output ← 工具执行结果(开始)
18-19. data ×2 ← 工具输出分片(call_id / name / output)
...
N. text ×N ← 工具结果喂回模型后,继续输出正文
N+1. message ← 完成
N+2. response ← ★ 终态(status=completed,output 数组含全部消息)
N+3. turn_usage ← ★ token 用量与上下文占用
```
**关键**:工具调用不是"单独一条流",而是**穿插在同一个响应里** ——
文本 → 工具调用 → 工具结果 → 更多文本 → …… → 终态。
---
## 3. 关键事件的结构
### `text`(正文增量)★ 最常用
```json
{
"type": "text", "delta": true, "index": 0, "status": null,
"object": "content", "msg_id": "msg_...",
"text": "I'll read that",
"sequence_number": 4
}
```
- `delta: true` = 增量片段;`delta: false` = **整段快照**(去重用,别重复追加)
- 追加逻辑:只累积 `delta: true` 的 `text` 字段
### `plugin_call`(工具调用)
```json
{
"id": "msg_...", "type": "plugin_call", "role": "assistant",
"content": [{
"type": "data", "delta": false, "index": null, "status": "completed",
"object": "content", "msg_id": null,
"data": {
"call_id": "chatcmpl-tool-b207f3da7699c9fa",
"name": "read_file",
"arguments": "{\"file_path\": \"/tmp/probe-agent.txt\"}"
}
}],
"status": "completed", "metadata": null, "name": "assistant",
"object": "message", "sequence_number": 9
}
```
- **工具名**:`content[0].data.name`
- **参数**:`content[0].data.arguments`(**JSON 字符串**,要二次解析)
- **调用 id**:`content[0].data.call_id`(与 output 配对用)
### `plugin_call_output`(工具结果)
结构同上,`data` 里的键是 **`call_id` / `name` / `output`**(输出在 `output`,不是 `arguments`)。
### `data`(分片)
工具参数/输出会**先以 `data` 事件分片流式到达**(`call_id` / `name` / `arguments|output` 陆续出现),
最后再来一条完整的 `plugin_call` / `plugin_call_output` 快照。
→ **适配器只需认快照事件**(`plugin_call` / `plugin_call_output`),分片 `data` 可忽略(避免重复渲染)。
### `response`(终态)
```json
{
"id": "response_...", "output": [ ...全部消息... ],
"status": "completed", // ← completed / failed / cancelled
"created_at": "...", "completed_at": "...",
"object": "response", "session_id": "probe-tool-flow",
"sequence_number": 57,
"usage": { "input_tokens": 13767, "output_tokens": 21 }
}
```
**这是结束标志**,也是拿最终全文最可靠的地方(`output` 里每条消息带完整 content)。
### `turn_usage`(用量,最后一条)
```json
{
"type": "turn_usage", "session_id": "probe-tool-flow",
"usage": {
"provider_id": "opencode", "model_name": "deepseek-v4.1-flash",
"prompt_tokens": 13767, "completion_tokens": 21, "total_tokens": 13788,
"cache_read_tokens": 1024, "cache_observed": true, "cache_hit_rate": 7.43,
"context_size": 1000000, "compact_threshold": 0.8
},
"context_usage": { "estimated_tokens": 27, "max_input_length": 1000000, "context_usage_ratio": 0.0027 }
}
```
**这是网关侧记 token / 算成本的直接来源**(比从 `response.usage` 拿更全:带 model_name 和缓存字段)。
---
## 4. 适配器映射表(Step 2 实现依据)
| QwenPaw 事件 | 网关要做什么 |
|---|---|
| `text` with `delta:true` | 累积 `text` → 作为正文增量推给前端(`{type:"text", text}`) |
| `text` with `delta:false` | **忽略**(快照,避免重复) |
| `plugin_call` | 新增一条"轨迹步骤":`{name, arguments(解析后), call_id}`,状态=运行中 |
| `plugin_call_output` | 用 `call_id` 匹配上一步 → 标记完成 + 记 `output` |
| `data` | **忽略**(分片,快照已覆盖) |
| `message` | 可用于"消息边界"(本次实现可忽略,靠 text 累积) |
| `response` (`status:completed`) | 结束流;用它校验最终全文 |
| `response` (`status:failed`) | 结束流 + 报错 |
| `turn_usage` | **记 token / 成本 / model_name**(网关计量) |
| 任意事件含 `status:cancelled` | 用户点了停止 → 正常结束 |
---
## 5. 已确认的其他事实(Step -1 结论)
| 项 | 结论 |
|---|---|
| **`role: "system"` 是否被接受** | ✅ **接受且生效** —— 实测塞一条 `{"role":"system","content":[{"type":"text","text":"从现在起你只用英文回答"}]}`,模型随后**真的用英文回答**。→ `system_suffix` 用**方案 ④**(网关每轮注入一条 system 消息),最干净。 |
| **请求里带 `model` 是否生效** | ❌ **被忽略**(见计划 ⑲)→ 甲案:所有智能体共用同一模型 |
| **`/healthz` 是否含版本** | ❌ 只回 `{"status":"ok"}`;**版本号要读 `GET /`** 的 `version` 字段 |
| **本机免鉴权** | ✅ `allow_no_auth_hosts` 含 `127.0.0.1`/`::1`,网关内网直连不需要 token |
| **X-Agent-Id 选 profile** | ✅ 生效(实测带 `X-Agent-Id: default` 走的就是 default 的会话与记忆) |
---
## 6. 复现方式
```bash
# 录一段含工具调用的流(本机免鉴权)
curl -s --max-time 150 -X POST http://127.0.0.1:8088/api/console/chat \
-H 'Content-Type: application/json' -H 'X-Agent-Id: default' \
-d '{"input":[{"role":"user","content":[{"type":"text","text":"用 read_file 读 /tmp/probe-agent.txt 并告诉我内容"}]}],
"stream":true,"session_id":"probe-tool-flow"}' \
-o tests/fixtures/sse-tool-flow.sse
```