Files
xiaoyin-gateway/frontend/src/lib/agents.ts
T
api-gateway e12403fa15 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 全绿。
2026-09-29 13:22:12 +08:00

145 lines
5.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 智能体(第三十八轮 · 路线 A)—— 接口封装 + SSE 解析。
//
// 设计见 docs/agents-dev-plan.md;SSE 协议见 docs/qwenpaw-agent-api-sse.md。
// 后端把 QwenPaw 的事件翻译成这几种(前端不必懂 AgentScope):
import { getToken } from '../api'
export interface AgentItem {
slug: string
display_name: string
description: string
params?: { temperature?: number; max_tokens?: number; top_p?: number; system_suffix?: string }
engine?: { type: string; base_url: string; agent_id: string }
access?: { roles: string[]; users: string[] }
status: 'draft' | 'published' | 'retired'
created_at?: string
updated_at?: string
access_scope?: string
last_used_at?: string
run_total?: number
engine_model?: string
engine_ready?: boolean
}
export interface AgentListResp {
agents: AgentItem[]
max_agents: number
active: number
engine: { model: string; ready: boolean; base_url: string; agent_id: string }
}
export interface AgentRun {
at: string
account: string
rounds: number
tools: number
tokens: number
ms: number
status: string
}
/** 后端 SSE 的事件类型。 */
export type AgentEvent =
| { type: 'start'; slug: string; session_id: string }
| { type: 'text'; text: string }
| { type: 'step'; id: string; name?: string; args?: any; status: 'running' | 'done'; ms?: number; output?: any }
| { type: 'usage'; prompt: number; completion: number; cached: number; model: string; provider: string; context_ratio?: number }
| { type: 'done'; status: string }
| { type: 'error'; message: string }
function authHeaders(): Record<string, string> {
return { Authorization: `Bearer ${getToken()}` }
}
async function req<T>(path: string, init: RequestInit = {}): Promise<T> {
const r = await fetch(path, {
...init,
headers: { 'Content-Type': 'application/json', ...authHeaders(), ...(init.headers || {}) },
})
const body = await r.json().catch(() => null)
if (!r.ok) {
const msg = body?.error?.message || body?.detail || `HTTP ${r.status}`
throw new Error(typeof msg === 'string' ? msg : JSON.stringify(msg))
}
return body as T
}
export const listAgents = (includeRetired = false) =>
req<AgentListResp>(`/agents${includeRetired ? '?include_retired=true' : ''}`)
export const createAgent = (body: Record<string, any>) =>
req<{ status: string; agent: AgentItem }>('/agents', { method: 'POST', body: JSON.stringify(body) })
export const updateAgent = (slug: string, patch: Record<string, any>) =>
req<{ status: string; agent: AgentItem }>(`/agents/${slug}`, { method: 'PUT', body: JSON.stringify(patch) })
export const retireAgent = (slug: string) =>
req<{ status: string }>(`/agents/${slug}`, { method: 'DELETE' })
export const restoreAgent = (slug: string) =>
req<{ status: string; agent: AgentItem }>(`/agents/${slug}/restore`, { method: 'POST' })
export const agentRuns = (slug: string) =>
req<{ slug: string; total: number; last_used_at: string; items: AgentRun[] }>(`/agents/${slug}/runs`)
export const testAgent = (slug: string) =>
req<{ ok: boolean; ms: number; detail: string }>(`/agents/${slug}/test`, { method: 'POST' })
export const agentSessions = (slug: string) =>
req<{ slug: string; kind: string; items: any[] }>(`/agents/${slug}/sessions`)
export const stopAgent = (slug: string, chatId: string) =>
req<{ status: string }>(`/agents/${slug}/stop?chat_id=${encodeURIComponent(chatId)}`, { method: 'POST' })
/**
* 与智能体对话(SSE 流式)。逐事件回调 —— 与 Chat.vue 的流式处理同款思路。
*
* 返回一个 abort 函数(停止按钮用)。注意:网关侧的"停止"是转发给引擎的
* /console/chat/stop;前端 abort 只是断开本地连接,两者可同时用。
*/
export function streamAgentChat(
slug: string,
messages: { role: string; content: string }[],
sessionId: string,
onEvent: (ev: AgentEvent) => void,
): () => void {
const ctrl = new AbortController()
;(async () => {
try {
const r = await fetch(`/agents/${slug}/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...authHeaders() },
body: JSON.stringify({ messages, session_id: sessionId }),
signal: ctrl.signal,
})
if (!r.ok) {
const body = await r.json().catch(() => null)
const msg = body?.error?.message || body?.detail || `HTTP ${r.status}`
onEvent({ type: 'error', message: String(msg) })
return
}
const reader = r.body!.getReader()
const dec = new TextDecoder()
let buf = ''
for (;;) {
const { done, value } = await reader.read()
if (done) break
buf += dec.decode(value, { stream: true })
const parts = buf.split('\n\n')
buf = parts.pop() || ''
for (const part of parts) {
const line = part.trim()
if (!line.startsWith('data:')) continue
try {
onEvent(JSON.parse(line.slice(5).trim()) as AgentEvent)
} catch { /* 忽略坏帧 */ }
}
}
} catch (e: any) {
if (e?.name !== 'AbortError') onEvent({ type: 'error', message: String(e?.message || e) })
}
})()
return () => ctrl.abort()
}