feat(agents): 模型改为页面可选(方案 A)+ 修引擎模型读不到的静默 bug(版本 2.5.4 → 2.6.0)

推翻旧结论:模型不是全局唯一,而是每个 profile 各存一份 active_model
(PUT /api/models/active scope=agent → workspaces/<profile>/agent.json),
改完即时生效不用重启 —— 实测切模型后真对话 turn_usage 的 model_name 确实变了。

真 bug:refresh_engine_live() 读的是 /api/providers/active,那条是 404,
异常被吞 → engine_live['model'] 恒为空串 → 配置页模型栏一直显示「—」。
改用 ACTIVE_MODEL_PATH=/api/models/active + get_active_model()。

新增:
- 适配器 get_active_model / set_active_model(4xx 抛 EngineError 并透传引擎原文)
- GET /agents/engine/models(只列真能用的;实时 current,不走 TTL 缓存)
- PUT /agents/engine/model(带防自指护栏,不得指向 agent/*)
- 前端配置页模型栏:只读 → 可搜索下拉(按供应商分组 + 视觉标)+ 刷新;失败回滚
- i18n 删过期键、加 5 新键(中英 883/883 对称)
- 测试 +5(端点/路径常量回归/body 与头/4xx 抛错/防自指),224 passed

语义:方案 A = 所有智能体共用这一个模型(一个 profile 一个 active_model),
做不到 A 用 flash 且 B 用 pro 并存;那需方案 B(一智能体一 profile)。
This commit is contained in:
api-gateway committed 2026-09-30 14:40:58 +08:00
1 parent 42e2a31017
commit 0cb369ae80
9 files changed
+427 -26

No files matched your search

+52
View File
@@ -1,5 +1,57 @@
# CHANGELOG # CHANGELOG
## 2026-09-30 · 智能体模型改为「页面可选」(方案 A)+ 修引擎模型读不到的静默 bug(版本 2.5.4 → 2.6.0)
老板问「智能体当时为什么说不能自己设置模型」,并选择**方案 A**:能选、但不新增 profile。
**先推翻了自己的旧结论**(这是本轮最重要的一步):当初(第三十八轮)实测的是
「**请求体里带 `model` 会被忽略**」→ 据此推成「模型是 profile 级 ⇒ 所有智能体只能共用一个模型」。
**这个推论过头了。** 翻源码 + 实测后确认:
| 事实 | 证据 |
|---|---|
| 模型**不是全局唯一**,而是**每个 profile 各存一份** `active_model` | `PUT /api/models/active`(`scope=agent` + `agent_id`)写入 `workspaces/<profile>/agent.json` |
| 前缀是 **`/api/models/active`** | `routers/providers.py` 里 `APIRouter(prefix="/models")`;实测 `/api/providers/active` → **404** |
| 改完**即时生效**,不用重启 | `runtime/builder.py:324` 每轮都重读 `agent_config.active_model` |
| 端到端确实换了模型 | 切 `agnes-3.0-flash` 后真对话 `turn_usage` 回 `model_name=agnes-3.0-flash`、`context_size` 1M → 512K |
所以正确口径是:**请求级指定不行,改 profile 的 `active_model` 行**。
**顺手抓到一个静默 bug(真 bug)**:`agents_routes.py` 的 `refresh_engine_live()` 读的是
`/api/providers/active` —— **那条 404**,异常被 `except` 吞掉 → `engine_live["model"]` 恒为空串
→ **配置页模型栏一直显示 `—`、列表页模型名一直是空的**。它不报错、不抛异常,纯静默。
已改用新 helper `get_active_model()`(走正确路径),模型名现在能正常读出。
**新增(方案 A 的落地)**:
- **后端** `app/adapters/qwenpaw_engine.py`:`ACTIVE_MODEL_PATH = "/api/models/active"` +
`get_active_model()` / `set_active_model()`(后者 4xx 抛 `EngineError` 并**透传引擎原文**,
不自己编文案)。
- **后端** `app/agents_routes.py` 两个端点:
- `GET /agents/engine/models` —— 可选清单(**只列真的能用的**:`require_api_key` 为真但没配
Key 的供应商直接跳过,不列出来骗人)+ 实时 current(不用 TTL 缓存,刚改完要立刻看到)
- `PUT /agents/engine/model` —— 切换;带**防自指护栏**(不得指向 `agent/*`,与对话入口同款)
- **前端** `Agents.vue` 配置页「模型」栏:只读文字 → **可搜索下拉**(按供应商分组、视觉模型带
「视觉」标)+ 刷新按钮;失败**回滚选中值**并弹错。`lib/agents.ts` 加两个封装。
- **i18n**:删掉过期的 `cfgModelReadonly` / `cfgModelHint`,换成 5 个新键(中英 **883/883** 对称)。
**语义与取舍(必须讲清)**:方案 A 是**所有智能体共用这一个模型** —— 因为只有一个 profile,
`active_model` 是这一份 config 上的一个值,**做不到「A 用 flash、B 用 pro」并存**。
真要做到那样必须走方案 B(一智能体一 profile,有内存成本)。页面提示文案已按此口径重写。
**测试**:新增 5 条(端点挂载 / 路径常量回归(防再写回 `providers/active`)/ PUT 的 body 与头 /
4xx 抛错 / 防自指护栏),**224 passed / 0 failed**(原 219)。`ci_check.sh` 六道门禁全绿。
**附带发现(环境问题,非本轮引入)**:QwenPaw 里 `agnes` 供应商的 Key **已失效**
(切到 `agnes/agnes-3.0-flash` 报 401「无效的令牌」)。走网关的 `wangjinding` 正常
(网关侧 Agnes Key 是好的)。要用 Agnes 直连需先修 Key。
**上线**:`supervisorctl restart api-gateway:api-gateway_00` + `npm run build`;
线上 `version=2.6.0`、入口 `index-BQYagb1Q.js`、Agents chunk `Agents-CN_agann.js`;
真机验证:下拉 112 项 / 7 组 → 选 `wjd` → UI 显示 `wjd` → 磁盘 `agent.json`
`{"provider_id":"wangjinding","model":"wjd"}` → 引擎回读一致 → 列表页同步。
## 2026-09-30 · 智能体页「对话」与「配置」内容间距放宽(版本 2.5.3 → 2.5.4) ## 2026-09-30 · 智能体页「对话」与「配置」内容间距放宽(版本 2.5.3 → 2.5.4)
老板反馈:**智能体界面在「对话」和「配置」两个 Tab 里,内容间距也很挤,都优化下**。 老板反馈:**智能体界面在「对话」和「配置」两个 Tab 里,内容间距也很挤,都优化下**。
+68
View File
@@ -348,3 +348,71 @@ async def check_engine(base_url: str, *, timeout: float = 5.0) -> tuple[bool, st
return False, ENGINE_DOWN_MSG return False, ENGINE_DOWN_MSG
except Exception as exc: # noqa: BLE001 except Exception as exc: # noqa: BLE001
return False, f"引擎不可达:{exc}" return False, f"引擎不可达:{exc}"
# ── 引擎模型读写(第四十轮 · 「模型可选」方案 A)────────────────────────
#
# 事实(实测 + 源码):
# - 模型不是"全局唯一",而是**每个 profile 各存一份** `active_model`
# (落盘 `workspaces/<profile>/agent.json`)。所以改它 = 只影响这一个 profile。
# - 端点前缀是 **`/api/models/active`**(`routers/providers.py` 里 `prefix="/models"`)。
# ⚠️ 别写成 `/api/providers/active` —— 那条是 **404**(本项目旧代码就踩过这个坑,
# 导致模型名一直读不出来、页面显示 `—`)。
# - 改完 **即时生效**,不用重启引擎(每轮对话都会重读 agent_config)。
# - 我们这边所有智能体**共用 `ai-gateway` 一个 profile** ⇒ 改这个 profile 的模型
# 等于"换所有智能体用的模型"。这是方案 A 的既定语义(做不到 A/B 各用各的)。
ACTIVE_MODEL_PATH = "/api/models/active"
async def get_active_model(base_url: str, agent_id: str,
*, timeout: float = 8.0) -> dict[str, Any] | None:
"""读某个 profile 当前生效的模型。返回 `{provider_id, model}`,读不到返回 None。"""
url = base_url.rstrip("/") + ACTIVE_MODEL_PATH
try:
async with httpx.AsyncClient(timeout=timeout) as client:
r = await client.get(
url,
params={"scope": "agent", "agent_id": agent_id},
headers={"X-Agent-Id": agent_id},
)
if r.status_code >= 400:
return None
slot = (r.json() or {}).get("active_llm") or {}
if not slot.get("model"):
return None
return {"provider_id": slot.get("provider_id") or "", "model": slot.get("model") or ""}
except Exception: # noqa: BLE001
return None
async def set_active_model(base_url: str, agent_id: str,
provider_id: str, model: str,
*, timeout: float = 15.0) -> dict[str, Any]:
"""改某个 profile 的模型(即时生效)。校验失败抛 EngineError。
引擎会先 `_validate_model_slot()`(供应商/模型必须存在),所以这里
直接把上游的错误原文透出去,比自己编文案准确。
"""
url = base_url.rstrip("/") + ACTIVE_MODEL_PATH
payload = {"scope": "agent", "agent_id": agent_id,
"provider_id": provider_id, "model": model}
try:
async with httpx.AsyncClient(timeout=timeout) as client:
r = await client.put(url, json=payload, headers={"X-Agent-Id": agent_id})
except httpx.ConnectError:
raise EngineError(ENGINE_DOWN_MSG)
except Exception as exc: # noqa: BLE001
raise EngineError(f"引擎不可达:{exc}")
if r.status_code >= 400:
detail = ""
try:
b = r.json()
detail = b.get("detail") or b.get("message") or ""
except Exception: # noqa: BLE001
detail = (r.text or "")[:200]
raise EngineError(f"引擎拒绝该模型:{detail or f'HTTP {r.status_code}'}")
slot = (r.json() or {}).get("active_llm") or {}
return {"provider_id": slot.get("provider_id") or provider_id,
"model": slot.get("model") or model}
+88 -13
View File
@@ -29,7 +29,13 @@ from app.agents import (
AgentStore, AgentStore,
AgentsError, AgentsError,
) )
from app.adapters.qwenpaw_engine import check_engine, stream_chat from app.adapters.qwenpaw_engine import (
check_engine,
EngineError,
get_active_model,
set_active_model,
stream_chat,
)
log = logging.getLogger("api-gateway.agents") log = logging.getLogger("api-gateway.agents")
@@ -126,20 +132,16 @@ async def refresh_engine_live(store: AgentStore, *, force: bool = False) -> None
agent_id = agents[0].engine_agent_id if agents else DEFAULT_ENGINE_AGENT agent_id = agents[0].engine_agent_id if agents else DEFAULT_ENGINE_AGENT
ok, _why = await check_engine(base) ok, _why = await check_engine(base)
model = "" model = ""
provider_id = ""
if ok: if ok:
try: # ⚠️ 第四十轮修:旧代码读的是 `/api/providers/active` —— 那条**是 404**
async with httpx.AsyncClient(timeout=8.0) as c: # (真前缀是 `/api/models/active`),所以 model 一直是空串、页面显示 `—`。
r = await c.get( slot = await get_active_model(base, agent_id)
base.rstrip("/") + "/api/providers/active", if slot:
params={"scope": "agent", "agent_id": agent_id},
headers={"X-Agent-Id": agent_id},
)
if r.status_code < 400:
slot = (r.json() or {}).get("active_llm") or {}
model = slot.get("model") or "" model = slot.get("model") or ""
except Exception: # noqa: BLE001 provider_id = slot.get("provider_id") or ""
log.debug("读引擎 active_model 失败") engine_live.update({"model": model, "provider_id": provider_id,
engine_live.update({"model": model, "ready": ok, "checked_at": now}) "ready": ok, "checked_at": now})
def can_use_agent(a: Agent, role: str) -> bool: def can_use_agent(a: Agent, role: str) -> bool:
@@ -205,6 +207,79 @@ def install(app: FastAPI, *, store: AgentStore,
}, },
} }
# ── 引擎模型:可选清单 + 切换(第四十轮 · 方案 A)──────────────────
#
# 语义(老板 2026-09-30 拍板方案 A):所有智能体共用一个 profile
# ⇒ 这里切的模型是"所有智能体一起用的",不是各自独立的。
# 要"每个智能体各用各的"须走方案 B(一智能体一 profile),本轮不做。
@app.get("/agents/engine/models")
async def agents_engine_models(request: Request, _auth=Depends(require_auth)):
"""可选模型清单 = 网关自己的模型列表(都由 wangjinding 供应商送达引擎)。"""
require_admin(request)
store.reload_if_changed()
agents = store.list()
base = agents[0].engine_base_url if agents else DEFAULT_ENGINE_URL
agent_id = agents[0].engine_agent_id if agents else DEFAULT_ENGINE_AGENT
# ① 引擎里配好的、且真的能用的模型(有 Key 的供应商)
options: list[dict[str, Any]] = []
try:
async with httpx.AsyncClient(timeout=10.0) as c:
r = await c.get(base.rstrip("/") + "/api/models")
if r.status_code < 400:
for p in (r.json() or []):
pid = p.get("id") or ""
if p.get("require_api_key") and not p.get("api_key"):
continue # 没配 Key 的选不了,别列出来骗人
for m in (list(p.get("models") or []) + list(p.get("extra_models") or [])):
mid = m.get("id") if isinstance(m, dict) else m
if not mid:
continue
options.append({
"provider_id": pid,
"provider_name": p.get("name") or pid,
"model": mid,
"vision": bool(m.get("supports_image")) if isinstance(m, dict) else False,
})
except Exception: # noqa: BLE001
log.warning("读引擎模型清单失败(可选清单降级为空)")
# ② 当前生效的模型(实时读,别用 TTL 缓存 —— 用户刚改完要立刻看到)
current = await get_active_model(base, agent_id) or {}
ok, _why = await check_engine(base)
return {
"options": options,
"current": {"provider_id": current.get("provider_id", ""),
"model": current.get("model", "")},
"engine": {"base_url": base, "agent_id": agent_id, "ready": ok},
"scope_note": "shared", # 前端据此显示"所有智能体共用"提示
}
@app.put("/agents/engine/model")
async def agents_engine_set_model(request: Request, _auth=Depends(require_auth)):
"""切换引擎模型(即时生效,不用重启)。"""
require_admin(request)
body = await json_body(request)
provider_id = str(body.get("provider_id") or "").strip()
model = str(body.get("model") or "").strip()
if not provider_id or not model:
raise HTTPException(400, "provider_id 与 model 都不能为空")
# 防自指(与对话入口同一条护栏)
if model == "agent" or model.startswith("agent/"):
raise HTTPException(400, "不能把引擎模型指向智能体自身(agent/*)")
store.reload_if_changed()
agents = store.list()
base = agents[0].engine_base_url if agents else DEFAULT_ENGINE_URL
agent_id = agents[0].engine_agent_id if agents else DEFAULT_ENGINE_AGENT
try:
slot = await set_active_model(base, agent_id, provider_id, model)
except EngineError as e:
raise HTTPException(400, str(e))
# 立刻刷新缓存,让列表页同步
await refresh_engine_live(store, force=True)
log.info("引擎模型已切换:%s → %s/%s", agent_id, provider_id, model)
return {"status": "ok", "current": slot}
# ── 新建 / 修改 / 归档 / 恢复 ── # ── 新建 / 修改 / 归档 / 恢复 ──
@app.post("/agents") @app.post("/agents")
async def agents_create(request: Request, _auth=Depends(require_auth)): async def agents_create(request: Request, _auth=Depends(require_auth)):
+1 -1
View File
@@ -338,7 +338,7 @@ _docs_on = config.server.docs_enabled # 安全默认关(report: /docs、/ope
# 三处,/health 干脆没返回版本 —— 前端「网关版本」一直显示 v-。 # 三处,/health 干脆没返回版本 —— 前端「网关版本」一直显示 v-。
# 2026-09-29: 2.4.0 → 2.4.1(前端间距规范统一);2.4.1 → 2.5.0(新增「智能体」功能模块);2.5.0 → 2.5.1(智能体支持图片附件);2.5.1 → 2.5.2(智能体页间距与对齐优化);2.5.2 → 2.5.3(修 KPI 与下方块之间 0 间距)。 # 2026-09-29: 2.4.0 → 2.4.1(前端间距规范统一);2.4.1 → 2.5.0(新增「智能体」功能模块);2.5.0 → 2.5.1(智能体支持图片附件);2.5.1 → 2.5.2(智能体页间距与对齐优化);2.5.2 → 2.5.3(修 KPI 与下方块之间 0 间距)。
# ★ 版本号纪律:每次改动都要往上加,小改动加小版本号、大改动加大版本号(README 有专章)。 # ★ 版本号纪律:每次改动都要往上加,小改动加小版本号、大改动加大版本号(README 有专章)。
VERSION = "2.5.4" VERSION = "2.6.0"
app = FastAPI( app = FastAPI(
title="API Gateway", title="API Gateway",
+23
View File
@@ -89,6 +89,29 @@ export const testAgent = (slug: string) =>
export const agentSessions = (slug: string) => export const agentSessions = (slug: string) =>
req<{ slug: string; kind: string; items: any[] }>(`/agents/${slug}/sessions`) req<{ slug: string; kind: string; items: any[] }>(`/agents/${slug}/sessions`)
/** 引擎可选模型清单 + 当前生效模型(第四十轮 · 方案 A:所有智能体共用)。 */
export interface EngineModelOption {
provider_id: string
provider_name: string
model: string
vision: boolean
}
export interface EngineModelsResp {
options: EngineModelOption[]
current: { provider_id: string; model: string }
engine: { base_url: string; agent_id: string; ready: boolean }
scope_note: string
}
export const engineModels = () => req<EngineModelsResp>('/agents/engine/models')
/** 切换引擎模型(即时生效,不用重启)。 */
export const setEngineModel = (providerId: string, model: string) =>
req<{ status: string; current: { provider_id: string; model: string } }>(
'/agents/engine/model',
{ method: 'PUT', body: JSON.stringify({ provider_id: providerId, model }) },
)
export const stopAgent = (slug: string, chatId: string) => export const stopAgent = (slug: string, chatId: string) =>
req<{ status: string }>(`/agents/${slug}/stop?chat_id=${encodeURIComponent(chatId)}`, { method: 'POST' }) req<{ status: string }>(`/agents/${slug}/stop?chat_id=${encodeURIComponent(chatId)}`, { method: 'POST' })
+5 -2
View File
@@ -411,8 +411,11 @@ export default {
cfgDesc: 'Description', cfgDesc: 'Description',
cfgModel: 'Model', cfgModel: 'Model',
cfgModelSub: 'From the gateway models', cfgModelSub: 'From the gateway models',
cfgModelReadonly: 'Model is set by QwenPaw profile {profile}', cfgModelPick: 'Pick a model',
cfgModelHint: 'Engine model is a profile-level setting — all agents share one model. Change it in QwenPaw:', cfgModelRefresh: 'Refresh',
cfgModelVision: 'vision',
cfgModelSwitched: 'Switched to {model} (shared by all agents, takes effect immediately)',
cfgModelHintShared: 'All agents share this one model (the engine stores it per profile). Switching takes effect immediately, no restart. You can also change it in QwenPaw:',
cfgOpenQwenpaw: 'Open QwenPaw', cfgOpenQwenpaw: 'Open QwenPaw',
cfgExec: 'Execution', cfgExec: 'Execution',
cfgExecSub: 'Affects server safety, read-only for now', cfgExecSub: 'Affects server safety, read-only for now',
+5 -2
View File
@@ -414,8 +414,11 @@ export default {
cfgDesc: '描述', cfgDesc: '描述',
cfgModel: '模型', cfgModel: '模型',
cfgModelSub: '从网关的模型里选', cfgModelSub: '从网关的模型里选',
cfgModelReadonly: '模型由 QwenPaw 的 {profile} profile 决定', cfgModelPick: '选择模型',
cfgModelHint: '引擎的模型是 profile 级设置 —— 所有智能体共用同一个模型。要改请去 QwenPaw:', cfgModelRefresh: '刷新',
cfgModelVision: '视觉',
cfgModelSwitched: '已切换到 {model}(所有智能体共用,即时生效)',
cfgModelHintShared: '所有智能体共用这一个模型(引擎按 profile 存模型)。切换即时生效,不用重启引擎。也可以去 QwenPaw 改:',
cfgOpenQwenpaw: '打开 QwenPaw', cfgOpenQwenpaw: '打开 QwenPaw',
cfgExec: '执行', cfgExec: '执行',
cfgExecSub: '影响服务器安全,一期只读', cfgExecSub: '影响服务器安全,一期只读',
+80 -8
View File
@@ -101,7 +101,7 @@
<div class="ag-tabs"> <div class="ag-tabs">
<span :class="{ on: tab === 'chat' }" @click="tab = 'chat'">{{ t('agents.tabChat') }}</span> <span :class="{ on: tab === 'chat' }" @click="tab = 'chat'">{{ t('agents.tabChat') }}</span>
<span :class="{ on: tab === 'config' }" @click="tab = 'config'">{{ t('agents.tabConfig') }}</span> <span :class="{ on: tab === 'config' }" @click="tab = 'config'; loadEngineModels()">{{ t('agents.tabConfig') }}</span>
<span :class="{ on: tab === 'runs' }" @click="tab = 'runs'; loadRuns()">{{ t('agents.tabRuns') }}</span> <span :class="{ on: tab === 'runs' }" @click="tab = 'runs'; loadRuns()">{{ t('agents.tabRuns') }}</span>
</div> </div>
</div> </div>
@@ -255,13 +255,36 @@
<div class="card-h"><b>{{ t('agents.cfgModel') }}</b><span class="sub">{{ t('agents.cfgModelSub') }}</span></div> <div class="card-h"><b>{{ t('agents.cfgModel') }}</b><span class="sub">{{ t('agents.cfgModelSub') }}</span></div>
<div class="frow"> <div class="frow">
<div class="f-lab">{{ t('agents.cfgModel') }}</div> <div class="f-lab">{{ t('agents.cfgModel') }}</div>
<div class="f-val"> <div class="f-val model-pick">
<span class="code">{{ cur.engine_model || '—' }}</span> <el-select
<span class="f-lock"><Icon name="lock" :size="12" />{{ t('agents.cfgReadonly') }}</span> v-model="enginePick"
size="small"
filterable
:loading="engineLoading"
:placeholder="t('agents.cfgModelPick')"
style="flex:1;min-width:0"
@change="doSetModel"
>
<el-option-group
v-for="g in engineGroups" :key="g.provider_id"
:label="g.provider_name"
>
<el-option
v-for="o in g.items" :key="o.provider_id + '/' + o.model"
:label="o.model" :value="o.provider_id + '/' + o.model"
>
<span>{{ o.model }}</span>
<span v-if="o.vision" class="opt-vision">{{ t('agents.cfgModelVision') }}</span>
</el-option>
</el-option-group>
</el-select>
<el-button size="small" :loading="engineLoading" @click="loadEngineModels">
{{ t('agents.cfgModelRefresh') }}
</el-button>
</div> </div>
</div> </div>
<div class="f-hint"> <div class="f-hint">
{{ t('agents.cfgModelHint') }} {{ t('agents.cfgModelHintShared') }}
<a :href="qwenpawUrl" target="_blank" rel="noopener">{{ t('agents.cfgOpenQwenpaw') }} ↗</a> <a :href="qwenpawUrl" target="_blank" rel="noopener">{{ t('agents.cfgOpenQwenpaw') }} ↗</a>
</div> </div>
<div class="card-h" style="margin-top:var(--gap)"> <div class="card-h" style="margin-top:var(--gap)">
@@ -373,9 +396,9 @@ import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus' import { ElMessage } from 'element-plus'
import Icon from '../components/Icon.vue' import Icon from '../components/Icon.vue'
import { import {
type AgentEvent, type AgentItem, type AgentRun, type AgentEvent, type AgentItem, type AgentRun, type EngineModelOption,
agentRuns, agentSessions, createAgent, listAgents, agentRuns, agentSessions, createAgent, engineModels, listAgents,
restoreAgent, retireAgent, streamAgentChat, testAgent, updateAgent, restoreAgent, retireAgent, setEngineModel, streamAgentChat, testAgent, updateAgent,
} from '../lib/agents' } from '../lib/agents'
import { renderMarkdown } from '../lib/markdown' import { renderMarkdown } from '../lib/markdown'
import { PRESETS, pickImage } from '../lib/upload' import { PRESETS, pickImage } from '../lib/upload'
@@ -416,6 +439,19 @@ const create = reactive({ display_name: '', slug: '', description: '', system_su
const testing = ref(false) const testing = ref(false)
const testResult = ref<{ ok: boolean; ms: number; detail: string } | null>(null) const testResult = ref<{ ok: boolean; ms: number; detail: string } | null>(null)
// 引擎模型选择(第四十轮 · 方案 A):清单 + 当前值。`enginePick` 形如 "provider/model"。
const engineOptions = ref<EngineModelOption[]>([])
const enginePick = ref('')
const engineLoading = ref(false)
const engineGroups = computed(() => {
const by: Record<string, { provider_id: string; provider_name: string; items: EngineModelOption[] }> = {}
for (const o of engineOptions.value) {
if (!by[o.provider_id]) by[o.provider_id] = { provider_id: o.provider_id, provider_name: o.provider_name, items: [] }
by[o.provider_id].items.push(o)
}
return Object.values(by)
})
const cur = computed(() => data.agents.find((a) => a.slug === current.value) || null) const cur = computed(() => data.agents.find((a) => a.slug === current.value) || null)
const hasRetired = computed(() => data.agents.some((a) => a.status === 'retired')) const hasRetired = computed(() => data.agents.some((a) => a.status === 'retired'))
const activeCount = computed(() => data.agents.filter((a) => a.status !== 'retired').length) const activeCount = computed(() => data.agents.filter((a) => a.status !== 'retired').length)
@@ -645,6 +681,38 @@ async function doTest() {
finally { testing.value = false } finally { testing.value = false }
} }
/** 拉可选模型清单 + 当前生效模型(第四十轮 · 方案 A)。 */
async function loadEngineModels() {
engineLoading.value = true
try {
const j = await engineModels()
engineOptions.value = j.options || []
const c = j.current || {}
enginePick.value = c.model ? `${c.provider_id}/${c.model}` : ''
} catch (e: any) {
ElMessage.error(String(e?.message || e))
} finally { engineLoading.value = false }
}
/** 切换引擎模型 —— 即时生效(不用重启引擎)。 */
async function doSetModel(v: string) {
const i = String(v || '').indexOf('/')
if (i < 0) return
const provider_id = v.slice(0, i)
const model = v.slice(i + 1)
const prev = enginePick.value
try {
const j = await setEngineModel(provider_id, model)
const c = j.current || {}
enginePick.value = c.model ? `${c.provider_id}/${c.model}` : ''
ElMessage.success(t('agents.cfgModelSwitched', { model }))
await load() // 让列表页 / 头部同步新模型名
} catch (e: any) {
enginePick.value = prev // 失败回滚选中值
ElMessage.error(String(e?.message || e))
}
}
async function doRetire() { async function doRetire() {
if (!cur.value || !confirm(t('agents.confirmDelete'))) return if (!cur.value || !confirm(t('agents.confirmDelete'))) return
try { await retireAgent(cur.value.slug); await load(); pick(data.agents[0]?.slug || '') } try { await retireAgent(cur.value.slug); await load(); pick(data.agents[0]?.slug || '') }
@@ -790,6 +858,10 @@ onMounted(load)
.f-val { flex: 1; min-width: 0; display: flex; align-items: center; gap: 7px; font-size: 12.5px; padding: 8px 10px; border-radius: 9px; background: var(--chip); } .f-val { flex: 1; min-width: 0; display: flex; align-items: center; gap: 7px; font-size: 12.5px; padding: 8px 10px; border-radius: 9px; background: var(--chip); }
.f-val.code { font-family: ui-monospace, Menlo, monospace; font-size: 11.5px; } .f-val.code { font-family: ui-monospace, Menlo, monospace; font-size: 11.5px; }
.f-lock { margin-left: auto; display: inline-flex; align-items: center; gap: 4px; font-size: 10.5px; color: var(--muted-2); } .f-lock { margin-left: auto; display: inline-flex; align-items: center; gap: 4px; font-size: 10.5px; color: var(--muted-2); }
/* 模型下拉(第四十轮):撑满 f-val,右侧留刷新按钮 */
.model-pick { gap: var(--gap-sm); padding: 4px 6px 4px 4px; }
.model-pick .el-select { flex: 1; min-width: 0; }
.opt-vision { float: right; margin-left: 10px; font-size: 10.5px; color: var(--primary); opacity: .8; }
.f-hint { font-size: 11px; color: var(--muted-2); line-height: 1.65; margin: var(--gap-xs) 0 0 88px; } .f-hint { font-size: 11px; color: var(--muted-2); line-height: 1.65; margin: var(--gap-xs) 0 0 88px; }
.f-row-note { font-size: 11.5px; color: var(--muted); line-height: 1.6; margin-top: var(--gap-s); } .f-row-note { font-size: 11.5px; color: var(--muted); line-height: 1.6; margin-top: var(--gap-s); }
.row-actions { display: flex; align-items: center; gap: var(--gap-sm); margin-top: var(--gap-lg); } .row-actions { display: flex; align-items: center; gap: var(--gap-sm); margin-top: var(--gap-lg); }
+105
View File
@@ -5967,6 +5967,111 @@ def test_agents_routes_installed():
assert need in paths, f"缺少端点 {need}" assert need in paths, f"缺少端点 {need}"
def test_agents_engine_model_endpoints_installed():
"""引擎模型端点已挂上(第四十轮 · 方案 A)。"""
import app.main as m
paths = {r.path for r in m.app.routes if hasattr(r, "path")}
for need in ("/agents/engine/models", "/agents/engine/model"):
assert need in paths, f"缺少端点 {need}"
def test_engine_active_model_path_is_models_not_providers():
"""回归:读/写引擎 active_model 必须用 `/api/models/active`(第四十轮)。
旧代码写的是 `/api/providers/active` —— 那条**实测是 404**,导致
`engine_live["model"]` 一直是空串、配置页模型栏永远显示 `—`。
这是"静默失效"型 bug:不报错、不抛异常,只是值一直是空。
"""
from app.adapters import qwenpaw_engine as qe
assert qe.ACTIVE_MODEL_PATH == "/api/models/active"
assert "providers/active" not in qe.ACTIVE_MODEL_PATH
# 两个函数都要用这个常量(别再各写一份字面量)
import inspect
for fn in (qe.get_active_model, qe.set_active_model):
src = inspect.getsource(fn)
assert "ACTIVE_MODEL_PATH" in src, f"{fn.__name__} 未复用 ACTIVE_MODEL_PATH"
def test_engine_set_active_model_sends_agent_scope():
"""PUT 的 body 必须是 scope=agent + agent_id(profile 级写入)。"""
import asyncio, json as _json
from app.adapters import qwenpaw_engine as qe
captured = {}
class _Resp:
status_code = 200
def json(self):
return {"active_llm": {"provider_id": "wangjinding", "model": "wjd"}}
class _Client:
def __init__(self, *a, **k): pass
async def __aenter__(self): return self
async def __aexit__(self, *a): return False
async def put(self, url, json=None, headers=None):
captured["url"] = url
captured["json"] = json
captured["headers"] = headers
return _Resp()
orig = qe.httpx.AsyncClient
qe.httpx.AsyncClient = _Client
try:
out = asyncio.run(qe.set_active_model("http://127.0.0.1:8088", "ai-gateway",
"wangjinding", "wjd"))
finally:
qe.httpx.AsyncClient = orig
assert captured["url"].endswith("/api/models/active"), captured["url"]
assert captured["json"] == {"scope": "agent", "agent_id": "ai-gateway",
"provider_id": "wangjinding", "model": "wjd"}
assert captured["headers"].get("X-Agent-Id") == "ai-gateway"
assert out == {"provider_id": "wangjinding", "model": "wjd"}
def test_engine_set_active_model_raises_on_4xx():
"""引擎拒绝(如模型不存在)→ 抛 EngineError,错误原文透传(别吞成 ok)。"""
import asyncio
from app.adapters import qwenpaw_engine as qe
class _Resp:
status_code = 400
text = ""
def json(self):
return {"detail": "model 'nope' not found"}
class _Client:
def __init__(self, *a, **k): pass
async def __aenter__(self): return self
async def __aexit__(self, *a): return False
async def put(self, url, json=None, headers=None): return _Resp()
orig = qe.httpx.AsyncClient
qe.httpx.AsyncClient = _Client
try:
try:
asyncio.run(qe.set_active_model("http://x", "ai-gateway", "p", "nope"))
raise AssertionError("本应抛 EngineError")
except qe.EngineError as e:
assert "not found" in str(e), str(e)
finally:
qe.httpx.AsyncClient = orig
def test_agents_engine_set_model_rejects_agent_self_reference():
"""防自指:引擎模型不能指向 agent/*(否则引擎→智能体→引擎 死循环)。
这条护栏在对话端点也有;新增的切换端点必须同样拦住,否则用户可以从
模型下拉里把引擎指向智能体自身,把服务打成死循环。
"""
import inspect
import app.agents_routes as ar
src = inspect.getsource(ar.install)
# 切换端点里必须有这条检查(与对话入口同款)
assert "agent/" in src and "死循环" in src, "切换端点缺少防自指护栏"
def test_qwenpaw_engine_image_content_passthrough(): def test_qwenpaw_engine_image_content_passthrough():
"""图片附件:内容块必须原样转成 AgentScope 的 image 形状(第三十九轮)。 """图片附件:内容块必须原样转成 AgentScope 的 image 形状(第三十九轮)。