feat(agents): 图片附件 + 修两个真 bug(版本 2.5.0 → 2.5.1)

老板要求「图片附件功能加上,其他的先不做」。

QwenPaw 侧格式(实测确认后再动手):{"type":"image","image_url":"<data-URI>"
—— 塞纯红 64×64 PNG 的 data URI,模型正确答出「红色」。

改动:
- app/adapters/qwenpaw_engine.py:放行图片内容块,并同时支持两种写法 ——
  AgentScope 原生 image 与 OpenAI 风格 image_url(前端发的是后者);
  新增 _image_url();缺 url 的块跳过;audio/video/file 仍忽略
- views/Agents.vue:对话输入区加附件按钮(pickImage 复用现有浏览器内压缩,最多 4 张)
  + 待发缩略图可删 + 消息气泡内渲染图片;允许「只发图不带字」
- lib/agents.ts:content 放宽为 string | any[]
- i18n 新增 4 键,中英对称 879/879

修掉两个真 bug(本轮才暴露):
1. image_url 写法被忽略 —— 分支只认 type=="image",而前端发 image_url
   → 图片会静默丢失(功能等于没做)。测试用例抓出来的。
2. /agents/{slug}/chat 500 —— 上轮加计量打标时 log.info(..., rounds) 写在
   rounds = ... 之前,UnboundLocalError → 端点 500。已加回归用例
   test_agent_chat_endpoint_source_order 固化(这类声明顺序错误跑不出来)。

上线实测:两张图(红+蓝)→ 模型答「红色,蓝色」顺序正确,system_suffix 同时生效,
usage wjd/24112 tokens/缓存 2048;浏览器路径也验证过(上传→缩略图→发送→渲染→无 JS 错误)。

已知引擎侧行为(非网关问题):QwenPaw SSE 只有 text 事件、无独立 reasoning 通道,
模型有时把思考写进正文;且上下文会污染视觉判断(同图脏上下文答「白色」、干净会话答「蓝色」)。

测试 218 → 219 全过。
This commit is contained in:
api-gateway committed 2026-09-29 14:00:49 +08:00
1 parent c0706d1846
commit c62be67aa8
9 files changed
+229 -15

No files matched your search

+44
View File
@@ -1,5 +1,49 @@
# CHANGELOG
## 2026-09-29 · 智能体支持图片附件(版本 2.5.0 → 2.5.1)
老板要求:「图片附件功能加上,其他的先不做」。
**QwenPaw 侧的格式(实测确认)**:`{"type":"image","image_url":"<data-URI 或 http URL>"}`
—— 塞一张纯红 64×64 PNG 的 data URI,模型正确答出「红色」。格式端到端验证通过后才动手。
**改动**:
- `app/adapters/qwenpaw_engine.py`:内容块转换**放行图片**,并**同时支持两种写法** ——
AgentScope 原生 `{"type":"image","image_url":"<uri>"}` 与 OpenAI 风格
`{"type":"image_url","image_url":{"url":"<uri>"}}`(前端「对话」页发的是后者)。
新增 `_image_url()` 提取函数;缺 `url` 的图片块跳过(不产生空块);
不支持的媒体类型(audio/video/file)仍忽略。
- 前端 `views/Agents.vue`:对话输入区加**附件按钮**(`pickImage` 复用现有浏览器内压缩,
最多 4 张)+ 待发缩略图(可单张删除)+ 消息气泡内渲染图片;允许「只发图不带字」。
- `lib/agents.ts`:`content` 类型放宽为 `string | any[]`(支持内容块数组)。
- i18n 新增 4 键(attach/imgMax/imgErr/imgCount),中英对称 **879/879**。
**踩到并修掉的两个真 bug(都是本轮才暴露)**:
1. **`image_url` 写法被忽略** —— 转换分支只认 `type == "image"`,而前端发的是
`{"type":"image_url", ...}` → 图片会**静默丢失**(功能等于没做)。测试用例抓出来的。
2. **`/agents/{slug}/chat` 500** —— 上一轮加「计量打标」日志时,`log.info(..., rounds)`
被写在 `rounds = ...` **之前**,`UnboundLocalError` → 整个端点 500。
**已加回归用例 `test_agent_chat_endpoint_source_order` 固化**(这类声明顺序错误跑不出来,
只能靠读代码或真机调用发现 —— 本轮就是因为"打标改完没重新真机验证"才漏过)。
**上线实测**:
```
POST /agents/code-review/chat(两张图:红 + 蓝)
→ 模型答「红色,蓝色」(顺序正确;system_suffix「只给结论」同时在生效)
→ usage: wjd / 24112 tokens / 缓存 2048
```
浏览器路径也验证过(上传 → 缩略图 → 发送 → 消息内渲染图片 → 无 JS 错误)。
**一个已知的引擎侧行为(非网关问题)**:QwenPaw 的 SSE **只有 `text` 事件、没有独立的
reasoning 通道** —— 模型有时会把思考过程写进正文一起发出来(实测见过
"The user asks: ... I'll just answer 蓝色")。网关无法分离(除非改 QwenPaw 的流协议)。
另外**上下文会污染视觉判断**:先让模型答错一次,它下一轮会被自己的错误答案带偏
(实测同一张蓝图,脏上下文答「白色」、干净会话答「蓝色」)。
**测试**:218 → **219 全过**(新增图片内容块转换用例,覆盖两种写法/只图/缺 url/不支持类型/多图顺序,
以及上面那条声明顺序回归)。
## 2026-09-29 · 新增「智能体」功能模块(路线 A:界面在网关,引擎 QwenPaw)
老板要求:「在 ai 网关里做智能体 agent,新的一个菜单」。**一期只对管理员开放**,成熟后下发普通用户。
+33 -3
View File
@@ -11,6 +11,7 @@
- 回 SSE(前缀固定 `data: `,**没有 event: 行**)
- 事件:`text` / `plugin_call` / `plugin_call_output` / `data` / `message` / `response` / `turn_usage`
- `role: "system"` 的输入消息**被接受且生效**(实测)→ `system_suffix` 走这条
- **图片输入**:`{"type":"image", "image_url":"<data-URI/URL>"}`(实测可识别)
- `model` 字段**被忽略**(实测)→ 模型是 profile 级,不在请求里指定
网关对前端的输出形状(自定义、简单):
@@ -67,7 +68,9 @@ def build_input(messages: list[dict[str, Any]], system_suffix: str = "") -> list
if role not in ("user", "assistant", "system"):
role = "user"
content = m.get("content")
# content 允许是字符串或 [{type:text,text}] 形状
# content 允许:字符串 / [{type:text,text}] / [{type:image,image_url}]
# 图片格式(2026-09-29 实测确认):{"type":"image","image_url":"<data-URI 或 http URL>"}
# —— 端到端验证过:塞一张纯红 64×64 PNG 的 data URI,模型正确答出"红色"。
if isinstance(content, str):
parts = [{"type": "text", "text": content}]
elif isinstance(content, list):
@@ -75,15 +78,42 @@ def build_input(messages: list[dict[str, Any]], system_suffix: str = "") -> list
for c in content:
if isinstance(c, str):
parts.append({"type": "text", "text": c})
elif isinstance(c, dict) and c.get("type") == "text":
elif isinstance(c, dict):
ctype = c.get("type")
if ctype == "text":
parts.append({"type": "text", "text": str(c.get("text") or "")})
# 图片等一期不支持,静默跳过(计划「一期不做图片/附件」)
elif ctype in ("image", "image_url"):
# 两种写法都认(实测见 test_qwenpaw_engine_image_content_passthrough):
# AgentScope 原生 `{"type":"image","image_url":"<uri>"}`
# OpenAI 风格 `{"type":"image_url","image_url":{"url":"<uri>"}}`
# —— 前端「对话」页发的是后者,所以必须同时支持。
url = _image_url(c)
if url:
parts.append({"type": "image", "image_url": url})
else:
log.debug("图片块缺 image_url,已跳过")
# 其余类型(audio/video/file)暂不支持,忽略
else:
parts = [{"type": "text", "text": str(content or "")}]
out.append({"role": role, "content": parts})
return out
def _image_url(block: dict[str, Any]) -> str:
"""从图片内容块里取出 URL。兼容两种写法:
- AgentScope 原生:`{"type":"image", "image_url":"data:image/png;base64,..."}`
- OpenAI 风格: `{"type":"image_url", "image_url":{"url":"..."}}`
"""
v = block.get("image_url")
if isinstance(v, str):
return v.strip()
if isinstance(v, dict):
u = v.get("url")
return str(u).strip() if u else ""
return ""
def build_body(messages: list[dict[str, Any]], session_id: str,
system_suffix: str = "") -> dict[str, Any]:
return {
+5 -4
View File
@@ -343,12 +343,13 @@ def install(app: FastAPI, *, store: AgentStore,
p = a.params or {}
suffix = str(p.get("system_suffix") or "")
# 第四十轮(计量打标):让日志能一眼看出"这次调用是网关的智能体发出的",
# 与管理员在「对话」页直接聊区分开。明细(谁/哪个智能体/多少 token)落 agent_runs。
log.info("agent chat: slug=%s account=%s session=%s rounds=%d",
slug, account, session_id, rounds)
started = time.time()
rounds = len([m for m in messages if isinstance(m, dict) and m.get("role") == "user"])
# 计量打标:让日志能一眼看出"这次调用是网关的智能体发出的",
# 与管理员在「对话」页直接聊区分开。明细(谁/哪个智能体/多少 token)落 agent_runs。
# 注意:这行必须在 rounds 赋值**之后**(曾因前置引用 rounds 导致 500)。
log.info("agent chat: slug=%s account=%s session=%s rounds=%d",
slug, account, session_id, rounds)
tool_count = 0
total_tokens = 0
status = "ok"
+2 -2
View File
@@ -336,9 +336,9 @@ _docs_on = config.server.docs_enabled # 安全默认关(report: /docs、/ope
# 本轮修复: 版本号收敛到单一常量。此前 "2.4.0" 硬编码在 FastAPI / / 导航 / /auth/login
# 三处,/health 干脆没返回版本 —— 前端「网关版本」一直显示 v-。
# 2026-09-29: 2.4.0 → 2.4.1(前端间距规范统一);2.4.1 → 2.5.0(新增「智能体」功能模块)。
# 2026-09-29: 2.4.0 → 2.4.1(前端间距规范统一);2.4.1 → 2.5.0(新增「智能体」功能模块);2.5.0 → 2.5.1(智能体支持图片附件)。
# ★ 版本号纪律:每次改动都要往上加,小改动加小版本号、大改动加大版本号(README 有专章)。
VERSION = "2.5.0"
VERSION = "2.5.1"
app = FastAPI(
title="API Gateway",
+1 -1
View File
@@ -100,7 +100,7 @@ export const stopAgent = (slug: string, chatId: string) =>
*/
export function streamAgentChat(
slug: string,
messages: { role: string; content: string }[],
messages: { role: string; content: string | any[] }[],
sessionId: string,
onEvent: (ev: AgentEvent) => void,
): () => void {
+4
View File
@@ -469,6 +469,10 @@ export default {
runOk: 'OK',
runStopped: 'Stopped',
runTimeout: 'Timeout',
attach: 'Attach image',
imgMax: 'Up to {n} images',
imgErr: 'Failed to pick image: {msg}',
imgCount: '{n}/{max}',
runDefaultTitle: 'Chat',
cacheHit: 'cache {n}',
meLabel: 'Me',
+4
View File
@@ -473,6 +473,10 @@ export default {
runOk: '成功',
runStopped: '已停止',
runTimeout: '超时',
attach: '添加图片',
imgMax: '最多 {n} 张',
imgErr: '选图失败:{msg}',
imgCount: '{n}/{max} 张',
runDefaultTitle: '对话',
cacheHit: '缓存 {n}',
meLabel: '我',
+64 -5
View File
@@ -171,6 +171,10 @@
</template>
</div>
<div v-if="m.images && m.images.length" class="msg-imgs">
<img v-for="(u, i) in m.images" :key="i" :src="u" alt="" />
</div>
<div v-if="m.text" v-html="render(m.text)" />
<div v-else-if="streaming && m.role === 'assistant'" class="typing">…</div>
@@ -189,10 +193,22 @@
:placeholder="t('agents.inputPlaceholder')"
@keydown.enter.exact.prevent="send"
/>
<div v-if="pendingImgs.length" class="pending">
<div v-for="(im, i) in pendingImgs" :key="i" class="pend-i">
<img :src="im.thumb || im.uri" alt="" />
<span class="pend-x" @click="removeImg(i)">×</span>
</div>
<span class="pend-hint">{{ t('agents.imgCount', { n: pendingImgs.length, max: MAX_IMGS }) }}</span>
</div>
<div class="bar">
<input ref="fileInput" type="file" accept="image/*" multiple hidden @change="onFiles" />
<button class="clip-btn" :disabled="streaming" :title="t('agents.attach')" @click="fileInput?.click()">
<Icon name="clip" :size="15" />
</button>
<span class="tok">{{ cur.engine_model || '—' }}</span>
<span style="flex:1" />
<el-button v-if="!streaming" type="primary" size="small" :disabled="!input.trim()" @click="send">
<el-button v-if="!streaming" type="primary" size="small"
:disabled="!input.trim() && !pendingImgs.length" @click="send">
<Icon name="send" :size="13" />{{ t('chat.send') }}
</el-button>
<el-button v-else size="small" class="stop-btn" @click="stopLocal">
@@ -351,6 +367,7 @@
<script setup lang="ts">
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import Icon from '../components/Icon.vue'
import {
type AgentEvent, type AgentItem, type AgentRun,
@@ -358,10 +375,11 @@ import {
restoreAgent, retireAgent, streamAgentChat, testAgent, updateAgent,
} from '../lib/agents'
import { renderMarkdown } from '../lib/markdown'
import { PRESETS, pickImage } from '../lib/upload'
const { t } = useI18n()
interface Msg { id: number; role: 'user' | 'assistant'; text: string; steps: Step[]; open?: boolean; meta?: string }
interface Msg { id: number; role: 'user' | 'assistant'; text: string; steps: Step[]; open?: boolean; meta?: string; images?: string[] }
interface Step { id: string; name?: string; args?: any; status: 'running' | 'done'; ms?: number; output?: any }
const err = ref('')
@@ -378,6 +396,9 @@ const messages = ref<Msg[]>([])
const sessions = ref<any[]>([])
const sessionId = ref('')
const input = ref('')
const pendingImgs = ref<{ uri: string; name: string; thumb: string }[]>([])
const MAX_IMGS = 4
const fileInput = ref<HTMLInputElement | null>(null)
const streaming = ref(false)
const stepsDone = ref(0)
const lastUsage = ref<any>(null)
@@ -503,9 +524,12 @@ async function persistSession() {
function send() {
const text = input.value.trim()
if (!text || streaming.value || !current.value) return
// 允许"只发图不带字"
if ((!text && !pendingImgs.value.length) || streaming.value || !current.value) return
err.value = ''
messages.value.push({ id: Date.now(), role: 'user', text, steps: [] })
const imgs = pendingImgs.value.map((x) => x.uri)
pendingImgs.value = []
messages.value.push({ id: Date.now(), role: 'user', text, steps: [], images: imgs })
const reply: Msg = { id: Date.now() + 1, role: 'assistant', text: '', steps: [], open: true, meta: '' }
messages.value.push(reply)
input.value = ''
@@ -518,7 +542,14 @@ function send() {
const history = messages.value
.filter((m) => m !== reply)
.map((m) => ({ role: m.role, content: m.text }))
.map((m) => {
const im = (m.images || []).filter(Boolean)
if (!im.length) return { role: m.role, content: m.text }
const parts: any[] = []
if (m.text) parts.push({ type: 'text', text: m.text })
for (const url of im) parts.push({ type: 'image', image_url: url })
return { role: m.role, content: parts }
})
abort = streamAgentChat(current.value, history, sessionId.value || `agent-${current.value}-${Date.now()}`, (ev: AgentEvent) => {
if (ev.type === 'start') { sessionId.value = ev.session_id }
@@ -546,6 +577,24 @@ function send() {
})
}
async function onFiles(ev: Event) {
const el = ev.target as HTMLInputElement
for (const f of Array.from(el.files || [])) {
if (pendingImgs.value.length >= MAX_IMGS) {
ElMessage.warning(t('agents.imgMax', { n: MAX_IMGS }))
break
}
try {
const m = await pickImage(f, PRESETS.chat)
pendingImgs.value.push({ uri: m.uri, name: m.name, thumb: m.thumb })
} catch (e: any) {
ElMessage.error(t('agents.imgErr', { msg: (e && e.message) || e }))
}
}
if (fileInput.value) fileInput.value.value = ''
}
function removeImg(i: number) { pendingImgs.value.splice(i, 1) }
function finish() {
streaming.value = false
elapsedText.value = `${((Date.now() - startedAt.value) / 1000).toFixed(1)}s`
@@ -690,6 +739,16 @@ onMounted(load)
.tok { font-size: 11.5px; color: var(--muted-2); font-family: ui-monospace, Menlo, monospace; }
.stop-btn { background: var(--err-soft); color: var(--err); border-color: transparent; }
.typing { color: var(--muted-2); }
.msg-imgs { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 8px; }
.msg-imgs img { max-width: 132px; max-height: 132px; border-radius: var(--radius-s); border: 1px solid var(--line); display: block; }
.pending { display: flex; align-items: center; gap: 8px; margin-top: var(--gap-sm); }
.pend-i { position: relative; }
.pend-i img { width: 46px; height: 46px; object-fit: cover; border-radius: var(--radius-sm, 8px); border: 1px solid var(--line); display: block; }
.pend-x { position: absolute; top: -6px; right: -6px; width: 17px; height: 17px; border-radius: 50%; background: var(--err); color: #fff; font-size: 12px; line-height: 17px; text-align: center; cursor: pointer; }
.pend-hint { font-size: 11px; color: var(--muted-2); }
.clip-btn { background: transparent; border: 0; color: var(--muted-2); cursor: pointer; padding: 4px; display: grid; place-items: center; }
.clip-btn:disabled { opacity: .4; cursor: not-allowed; }
.clip-btn:hover:not(:disabled) { color: var(--primary); }
.cfg-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--gap-lg); align-items: start; }
.cfg-grid > .card:first-child { grid-column: 1 / -1; }
.frow { display: flex; align-items: center; gap: 10px; margin-top: var(--gap-s); }
+72
View File
@@ -5967,6 +5967,78 @@ def test_agents_routes_installed():
assert need in paths, f"缺少端点 {need}"
def test_qwenpaw_engine_image_content_passthrough():
"""图片附件:内容块必须原样转成 AgentScope 的 image 形状(第三十九轮)。
QwenPaw 侧的格式已实测确认:`{"type":"image","image_url":"<data-URI 或 URL>"}`
—— 塞一张纯红 64×64 PNG 的 data URI,模型正确答出"红色"。
"""
from app.adapters.qwenpaw_engine import build_body, _image_url
uri = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg=="
# AgentScope 原生扁平写法
b = build_body([{"role": "user", "content": [
{"type": "text", "text": "这是什么颜色?"},
{"type": "image", "image_url": uri},
]}], "s1")
parts = b["input"][0]["content"]
assert parts[0] == {"type": "text", "text": "这是什么颜色?"}
assert parts[1] == {"type": "image", "image_url": uri}
# OpenAI 风格嵌套写法也要认(前端 Chat 页发的是这个形状)
b2 = build_body([{"role": "user", "content": [
{"type": "image_url", "image_url": {"url": uri}},
]}], "s2")
assert b2["input"][0]["content"][0]["image_url"] == uri
# 只发图不带字 → content 里只有图片块
b3 = build_body([{"role": "user", "content": [{"type": "image", "image_url": uri}]}], "s3")
assert len(b3["input"][0]["content"]) == 1
assert b3["input"][0]["content"][0]["type"] == "image"
# 缺 url 的图片块被跳过(不产生空块)
b4 = build_body([{"role": "user", "content": [
{"type": "text", "text": "x"}, {"type": "image"},
]}], "s4")
assert len(b4["input"][0]["content"]) == 1
# 不支持的媒体类型(audio/视频/文件)忽略,不炸
b5 = build_body([{"role": "user", "content": [
{"type": "text", "text": "x"}, {"type": "audio", "data": "..."},
]}], "s5")
assert len(b5["input"][0]["content"]) == 1
# _image_url 的两种取值
assert _image_url({"image_url": uri}) == uri
assert _image_url({"image_url": {"url": uri}}) == uri
assert _image_url({"image_url": {}}) == ""
assert _image_url({}) == ""
# 多图 + 文字混合顺序保持
b6 = build_body([{"role": "user", "content": [
{"type": "image", "image_url": "u1"},
{"type": "text", "text": "t"},
{"type": "image", "image_url": "u2"},
]}], "s6")
got = b6["input"][0]["content"]
assert [p["type"] for p in got] == ["image", "text", "image"]
def test_agent_chat_endpoint_source_order():
"""回归:agents_chat 里不能在 rounds 赋值**之前**引用它。
第三十九轮实测踩到 —— 打标日志被写在 `rounds = ...` 之前,
`log.info(..., rounds)` 直接 UnboundLocalError → 整个 /agents/{slug}/chat 返回 500。
这类「声明顺序」错误跑不出来,只能靠读代码或真机调用发现,所以固化成断言。
"""
import inspect
import app.agents_routes as ar
src = inspect.getsource(ar.install)
i_assign = src.find("rounds = len(")
i_use = src.find('log.info("agent chat:')
assert i_assign != -1 and i_use != -1, "端点源码结构变了,请更新本用例"
assert i_assign < i_use, "rounds 必须在打标日志之前赋值(否则 UnboundLocalError → 500)"
# 直接运行(非 pytest)—— 必须留在文件末尾,见上方 `test_image_request_goes_to_requested_model`
# 之前的旁注:运行器只会收集执行到这一行时已经存在的 globals。
if __name__ == "__main__":