GiantPandas commited on
Commit
787ce04
·
verified ·
1 Parent(s): 4ae06d1

Upload 4 files

Browse files
Files changed (4) hide show
  1. README.md +46 -9
  2. app.py +118 -28
  3. chat_backend.py +271 -13
  4. requirements.txt +1 -0
README.md CHANGED
@@ -12,7 +12,7 @@ pinned: false
12
 
13
  # vLLM Chat Studio
14
 
15
- 一个可部署到 **Hugging Face Spaces** 的中文对话界面,用于调用 vLLM 的 OpenAI 兼容接口。Space 只运行网页和 HTTP 转发逻辑,模型继续运行在你已有的 vLLM 服务上,因此前端 Space 不需要 GPU。
16
 
17
  默认 API 地址已经配置为:
18
 
@@ -20,7 +20,7 @@ pinned: false
20
  https://jo8bpbok8b8kcca5jahhqmdcpbd9cchm.openapi-inspire.inf.tech
21
  ```
22
 
23
- 程序自动使用 `/v1/models` 获取模型列表,向 `/v1/chat/completions` 发送对话请求。API Key 只从服务端环境变量读取。
24
 
25
  ## 1. 部署到 Hugging Face Spaces
26
 
@@ -47,13 +47,15 @@ https://jo8bpbok8b8kcca5jahhqmdcpbd9cchm.openapi-inspire.inf.tech
47
 
48
  `tests/` 目录是可选的测试代码,不影响 Space 启动。
49
 
 
 
50
  ### ZeroGPU 启动兼容
51
 
52
  如果启动页显示 `No @spaces.GPU function detected during startup`,说明 Space 正在使用 ZeroGPU,而应用没有注册该运行环境要求的 GPU 函数。这个界面把请求发送给已有的 vLLM 服务,本身不执行 GPU 推理。
53
 
54
  此版本已按 Hugging Face 官方 API 转发应用指引增加兼容处理:检测到平台设置的 `SPACES_ZERO_GPU` 时,注册一个不会被聊天操作调用的空 GPU 函数。发送、重新生成和模型发现仍使用普通服务端回调,不申请 GPU。无需自己设置 `SPACES_ZERO_GPU`,也不要给真实聊天函数添加 GPU 装饰器。HF 的 Gradio 运行环境已提供 `spaces` 包;普通 CPU 和本地运行不导入它。
55
 
56
- **从上一版升级:替换 `app.py` 并提交,等待 Space 重启即可。** API Key、模型地址和现有 Secrets 无需更改。另一种处理方式是到 **Settings → Space hardware** 切换到 CPU Basic(如果你的账号有此选项)。硬件选择在 Space 设置中完成;在 README YAML 中增加 `hardware:` 不会切换硬件。
57
 
58
  当前 Hugging Face 对新建 CPU Gradio/Docker Space 有账号套餐要求,CPU Basic 无小时费用并不代表所有账号都能使用;符合条件的免费账号可使用 ZeroGPU。以账号设置页面和[官方说明](https://huggingface.co/docs/hub/spaces-overview)为准。
59
 
@@ -69,6 +71,10 @@ https://jo8bpbok8b8kcca5jahhqmdcpbd9cchm.openapi-inspire.inf.tech
69
  | `INF_VERIFY_SSL` | Variable | `true` | 是否验证 HTTPS 证书。设为 `false` 时对应你原来 `curl -k` 的行为。 |
70
  | `INF_TIMEOUT` | Variable | `600` | HTTP 请求超时配置,单位为秒。 |
71
  | `MAX_CONCURRENT_REQUESTS` | Variable | `8` | 应用允许的并发生成请求数,按后端承载能力调整。 |
 
 
 
 
72
  | `APP_USERNAME` | Secret 或 Variable | 空 | 可选的应用登录用户名。需与 `APP_PASSWORD` 同时设置。 |
73
  | `APP_PASSWORD` | **Secret** | 空 | 可选的应用登录密码。需与 `APP_USERNAME` 同时设置。 |
74
 
@@ -90,23 +96,47 @@ INF_VERIFY_SSL=false
90
 
91
  ### 单次问答
92
 
93
- 每次请求仅包含当前 System Prompt 和当前问题。此前显示过的回答不作为下一次请求的上下文,适合测试提示词和对比调用参数。
94
 
95
  ### 多轮聊天
96
 
97
- 每次请求包含当前 System Prompt、已完成的历史问答和当前问题。可通过历史轮数参数限制发送最近多少轮完整问答,`0` 表示发送全部��完成历史。
98
 
99
  两种模式各自保存当前会话的记录;切换模式时不会把单次问答的内容混入多轮上下文。历史保存在当前应用会话中,不是永久聊天存档。
100
 
101
  ### 生成操作
102
 
103
  - **发送**:使用当前参数调用接口。
104
- - **停止生成**:中止当前生成,保留已显示的部分内容。
105
- - **重新生成**:重新回答最后一个问题,使用当前参数;不会将该问题重复追加为新一轮。
106
  - **清空**:清理当前模式的聊天记录。
107
 
108
  失败或主动停止的部分回答不会作为“已完成回答”传入后续多轮请求。可以使用重新生成重试该问题。
109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  ## 4. 调用参数
111
 
112
  | 参数 | 说明 |
@@ -126,8 +156,9 @@ INF_VERIFY_SSL=false
126
  | 历史轮数 | 多轮模式发送最近多少轮完整问答;`0` 为全部。 |
127
  | 沿用服务端采样默认值 | 勾选后省略并禁用 `temperature`、`top_p`、`top_k`、`min_p`、`repetition_penalty`、`presence_penalty`、`frequency_penalty` 七项控件;`max_tokens`、`seed`、`stop`、Thinking 和高级 JSON 仍生效。 |
128
  | 思考模式 | 默认 / 开启 / 关闭。开启或关闭通过 `chat_template_kwargs.enable_thinking` 传递,实际是否生效取决于模型模板。 |
 
129
 
130
- 界面可查看请求 JSON、返回的 token 用量、总耗时和首个文本片段延迟。首个文本片段延迟可作为 TTFT 的近似观察值;它包含客户端等到首个回答或推理文本片段的时间。请求预览只包含请求体,不包含 Authorization 请求头。
131
 
132
  如果接口返回独立的 `reasoning` 或 `reasoning_content`,界面会将它们与最终回答分开展示。后续上下文使用模型的回答文本,不会把界面中的思考面板格式回传给模型。
133
 
@@ -154,7 +185,7 @@ INF_VERIFY_SSL=false
154
 
155
  不要包一层 `extra_body`:`extra_body` 是 OpenAI Python SDK 的辅助参数,本项目直接发送 HTTP JSON,所以应直接填写它里面的字段。
156
 
157
- `messages`、`model`、`stream`、`n` 由界面控制,不能通过高级 JSON 覆盖。本项目提供文本对话,不运行工具调用循环,也不接受工具或函数定义。
158
 
159
  ### 关闭支持该选项的模型的思考模式
160
 
@@ -256,6 +287,10 @@ python -m unittest discover -s tests -v
256
  | 流式输出异常 | 尝试关闭流式 usage;仍异常时关闭流式输出,检查网关是否支持 SSE 转发。 |
257
  | 输入超过上下文长度 | 减少历史轮数、缩短问题或降低 `max_tokens`。 |
258
  | 未显示 token 用量 | 后端或网关可能没有返回 usage;界面不会将缺失的用量当作零。 |
 
 
 
 
259
 
260
  ## 8. 参考文档
261
 
@@ -265,5 +300,7 @@ python -m unittest discover -s tests -v
265
  - [Hugging Face 官方:ZeroGPU 注册回调要求](https://github.com/huggingface/skills/blob/main/skills/huggingface-spaces/references/zerogpu.md)
266
  - [Gradio 6 迁移指南](https://www.gradio.app/guides/gradio-6-migration-guide)
267
  - [vLLM OpenAI 兼容服务](https://docs.vllm.ai/en/latest/serving/online_serving/openai_compatible_server/)
 
 
268
  - [vLLM 思考输出](https://docs.vllm.ai/en/latest/features/reasoning_outputs/)
269
  - [vLLM SamplingParams](https://docs.vllm.ai/en/stable/api/vllm/sampling_params/)
 
12
 
13
  # vLLM Chat Studio
14
 
15
+ 一个可部署到 **Hugging Face Spaces** 的中文图文对话界面,支持文字、单张或多张图片,用于调用 vLLM 的 OpenAI 兼容接口。Space 只运行网页和 HTTP 转发逻辑,模型继续运行在你已有的 vLLM 服务上,因此前端 Space 不需要 GPU。
16
 
17
  默认 API 地址已经配置为:
18
 
 
20
  https://jo8bpbok8b8kcca5jahhqmdcpbd9cchm.openapi-inspire.inf.tech
21
  ```
22
 
23
+ 程序自动使用 `/v1/models` 获取模型列表,向 `/v1/chat/completions` 发送对话请求。API Key 只从服务端环境变量读取。图片在 Space 服务端读取并转换为 OpenAI `image_url` 数据块,再发送给你的模型接口。
24
 
25
  ## 1. 部署到 Hugging Face Spaces
26
 
 
47
 
48
  `tests/` 目录是可选的测试代码,不影响 Space 启动。
49
 
50
+ **从上一版升级到图文版:一起替换 `app.py`、`chat_backend.py` 和 `requirements.txt`,并同步更新 `README.md`;提交后等待 Space 重建、重启。** 图片处理逻辑和依赖都有更新,不能只替换 `app.py`。API Key、模型地址和现有 Secrets 无需更改。
51
+
52
  ### ZeroGPU 启动兼容
53
 
54
  如果启动页显示 `No @spaces.GPU function detected during startup`,说明 Space 正在使用 ZeroGPU,而应用没有注册该运行环境要求的 GPU 函数。这个界面把请求发送给已有的 vLLM 服务,本身不执行 GPU 推理。
55
 
56
  此版本已按 Hugging Face 官方 API 转发应用指引增加兼容处理:检测到平台设置的 `SPACES_ZERO_GPU` 时,注册一个不会被聊天操作调用的空 GPU 函数。发送、重新生成和模型发现仍使用普通服务端回调,不申请 GPU。无需自己设置 `SPACES_ZERO_GPU`,也不要给真实聊天函数添加 GPU 装饰器。HF 的 Gradio 运行环境已提供 `spaces` 包;普通 CPU 和本地运行不导入它。
57
 
58
+ 另一种处理方式是到 **Settings → Space hardware** 切换到 CPU Basic(如果你的账号有此选项)。硬件选择在 Space 设置中完成;在 README YAML 中增加 `hardware:` 不会切换硬件。
59
 
60
  当前 Hugging Face 对新建 CPU Gradio/Docker Space 有账号套餐要求,CPU Basic 无小时费用并不代表所有账号都能使用;符合条件的免费账号可使用 ZeroGPU。以账号设置页面和[官方说明](https://huggingface.co/docs/hub/spaces-overview)为准。
61
 
 
71
  | `INF_VERIFY_SSL` | Variable | `true` | 是否验证 HTTPS 证书。设为 `false` 时对应你原来 `curl -k` 的行为。 |
72
  | `INF_TIMEOUT` | Variable | `600` | HTTP 请求超时配置,单位为秒。 |
73
  | `MAX_CONCURRENT_REQUESTS` | Variable | `8` | 应用允许的并发生成请求数,按后端承载能力调整。 |
74
+ | `MAX_IMAGES_PER_REQUEST` | Variable | `8` | 单次请求图片总数上限,包含多轮模式携带的历史图片;本次新上传的图片也计入。 |
75
+ | `MAX_IMAGE_MB` | Variable | `20` | 每张上传图片及其转换结果的文件大小上限,单位 MiB。 |
76
+ | `MAX_IMAGE_PIXELS` | Variable | `40000000` | 单张图片的像素数上限,即约 4000 万像素;按宽 × 高检查。 |
77
+ | `MAX_IMAGE_PAYLOAD_MB` | Variable | `64` | 单次请求所有图片 Data URL 的累计编码字节上限,包含 Base64、Data URL 前缀及历史图片;单位 MiB。 |
78
  | `APP_USERNAME` | Secret 或 Variable | 空 | 可选的应用登录用户名。需与 `APP_PASSWORD` 同时设置。 |
79
  | `APP_PASSWORD` | **Secret** | 空 | 可选的应用登录密码。需与 `APP_USERNAME` 同时设置。 |
80
 
 
96
 
97
  ### 单次问答
98
 
99
+ 每次请求仅包含当前 System Prompt、当前问题和本次上传的图片。此前显示过的文字和图片不作为下一次请求的上下文,适合测试提示词、OCR 和对比调用参数。
100
 
101
  ### 多轮聊天
102
 
103
+ 每次请求包含当前 System Prompt、已完成的历史问答及其图片,以及当前问题和新上传的图片。第一轮上传图片后,可以直接继续追问,不必每轮重复上传。可通过历史轮数参数限制发送最近多少轮完整问答,`0` 表示发送全部已完成历史;超出所保留轮数的旧图片不会继续发送。
104
 
105
  两种模式各自保存当前会话的记录;切换模式时不会把单次问答的内容混入多轮上下文。历史保存在当前应用会话中,不是永久聊天存档。
106
 
107
  ### 生成操作
108
 
109
  - **发送**:使用当前参数调用接口。
110
+ - **停止生成**:中止当前生成,保留已显示的部分内容,并恢复该问题的文字和上传附件。
111
+ - **重新生成**:重新回答最后一个问题及其图片,使用当前参数;不会将该问题重复追加为新一轮。
112
  - **清空**:清理当前模式的聊天记录。
113
 
114
  失败或主动停止的部分回答不会作为“已完成回答”传入后续多轮请求。可以使用重新生成重试该问题。
115
 
116
+ ### 图片输入与保真
117
+
118
+ 在消息输入框中上传图片后可以同时输入问题,也可以只发图片。支持一次选择多张图片;聊天记录显示图片预览,文字和图片作为同一轮问题发送。
119
+
120
+ - 默认图片长边上限为 **`0`**,表示客户端保持原始分辨率。JPEG、PNG、WebP 在不需要调整时保留原始字节,避免为 OCR 或文档解析默认降低清晰度;模型服务仍可能按自身视觉处理配置缩放。
121
+ - 可以指定图片长边上限,例如 `2048`,按比例缩小超过该尺寸的图片;不会放大较小的图片。修改后重新生成会从最后一轮的原始上传附件重新处理,因此也可以恢复为原尺寸。
122
+ - 图片如带有需矫正的 EXIF 方向,会按方向校正;BMP 和单页静态 TIFF 会转为 PNG。这些情况下需要重新编码。
123
+ - 动画图片和多页图片会明确拒绝,避免只发送其中一帧或一页。本项目不接收 PDF、音频或视频。
124
+ - 图片数限制计算的是**整个请求**:当前图片加上保留的历史图片。超过限制时,可减少携带历史轮数、清空当前会话或在单次问答模式下重新发送。
125
+
126
+ “本次请求 JSON”中的图片 Base64 会以占位文字隐藏,便于查看消息结构;实际发给 vLLM 的请求仍包含完整图片数据。该预览不会删除或缩减实际请求中的图片。`MAX_IMAGE_PAYLOAD_MB` 按编码后的 Data URL 总字节数检查,因此它与原始图片文件大小之和不同;Base64 通常会让数据体积增加约三分之一。
127
+
128
+ ### vLLM 服务端要求
129
+
130
+ 所选模型必须支持视觉输入。纯文本模型即使使用同一个聊天接口,也不能因为界面允许上传就获得图像理解能力。
131
+
132
+ 如果要在一个请求里携带多张图片,请确保 vLLM 服务端允许足够的图片数量。例如,在你原有的启动命令中使用:
133
+
134
+ ```bash
135
+ --limit-mm-per-prompt '{"image": 8}'
136
+ ```
137
+
138
+ 这是 **vLLM 启动参数**,不应粘贴到界面的高级请求 JSON 中。上限应覆盖当前图片及历史图片的总和,并结合模型能力和显存调整;Space 中的 `MAX_IMAGES_PER_REQUEST` 不会自动修改 vLLM 配置。
139
+
140
  ## 4. 调用参数
141
 
142
  | 参数 | 说明 |
 
156
  | 历史轮数 | 多轮模式发送最近多少轮完整问答;`0` 为全部。 |
157
  | 沿用服务端采样默认值 | 勾选后省略并禁用 `temperature`、`top_p`、`top_k`、`min_p`、`repetition_penalty`、`presence_penalty`、`frequency_penalty` 七项控件;`max_tokens`、`seed`、`stop`、Thinking 和高级 JSON 仍生效。 |
158
  | 思考模式 | 默认 / 开启 / 关闭。开启或关闭通过 `chat_template_kwargs.enable_thinking` 传递,实际是否生效取决于模型模板。 |
159
+ | 图片最长边 · 像素 | `0` 保持原图;正整数表示按比例缩小超过该长边尺寸的上传图片,重新生成时也按当前值处理原始附件。 |
160
 
161
+ 界面可查看请求 JSON、返回的 token 用量、总耗时和首个文本片段延迟。首个文本片段延迟可作为 TTFT 的近似观察值;它包含客户端等到首个回答或推理文本片段的时间。请求预览只包含请求体,不包含 Authorization 请求头;图片 Base64 已替换为便于阅读的占位文字。
162
 
163
  如果接口返回独立的 `reasoning` 或 `reasoning_content`,界面会将它们与最终回答分开展示。后续上下文使用模型的回答文本,不会把界面中的思考面板格式回传给模型。
164
 
 
185
 
186
  不要包一层 `extra_body`:`extra_body` 是 OpenAI Python SDK 的辅助参数,本项目直接发送 HTTP JSON,所以应直接填写它里面的字段。
187
 
188
+ `messages`、`model`、`stream`、`n` 由界面控制,不能通过高级 JSON 覆盖。本项目提供文字和图片对话,不运行工具调用循环,也不接受工具或函数定义。
189
 
190
  ### 关闭支持该选项的模型的思考模式
191
 
 
287
  | 流式输出异常 | 尝试关闭流式 usage;仍异常时关闭流式输出,检查网关是否支持 SSE 转发。 |
288
  | 输入超过上下文长度 | 减少历史轮数、缩短问题或降低 `max_tokens`。 |
289
  | 未显示 token 用量 | 后端或网关可能没有返回 usage;界面不会将缺失的用量当作零。 |
290
+ | 上传图片后接口报不支持多模态 | 确认选择的是视觉语言模型,且 vLLM 部署支持该模型的图片输入。 |
291
+ | 提示图片数量超限 | 检查当前图片与多轮历史图片的总数,以及 Space 和 vLLM 两侧各自的数量限制。 |
292
+ | 提示图片文件过大或像素过多 | 先在本地缩小或压缩图片,再重新上传;需要时再调整管理员设置的上限。 |
293
+ | 提示动画或多页文件不支持 | 将需要识别的帧或页面导出为独立 PNG/JPEG,再作为多张图片上传。 |
294
 
295
  ## 8. 参考文档
296
 
 
300
  - [Hugging Face 官方:ZeroGPU 注册回调要求](https://github.com/huggingface/skills/blob/main/skills/huggingface-spaces/references/zerogpu.md)
301
  - [Gradio 6 迁移指南](https://www.gradio.app/guides/gradio-6-migration-guide)
302
  - [vLLM OpenAI 兼容服务](https://docs.vllm.ai/en/latest/serving/online_serving/openai_compatible_server/)
303
+ - [vLLM 多模态输入](https://docs.vllm.ai/en/stable/features/multimodal_inputs/)
304
+ - [vLLM 多模态服务端配置](https://docs.vllm.ai/en/stable/configuration/engine_args/#multimodal-config)
305
  - [vLLM 思考输出](https://docs.vllm.ai/en/latest/features/reasoning_outputs/)
306
  - [vLLM SamplingParams](https://docs.vllm.ai/en/stable/api/vllm/sampling_params/)
app.py CHANGED
@@ -5,11 +5,14 @@ from __future__ import annotations
5
  import asyncio
6
  import html
7
  import json
 
 
8
  import os
9
  import time
10
  import uuid
11
  from contextlib import aclosing
12
  from functools import partial
 
13
 
14
  os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "False")
15
 
@@ -31,13 +34,16 @@ else:
31
 
32
  import gradio as gr
33
 
34
- from chat_backend import ChatAPIError, ChatBackend, Config, build_payload, safe_error
 
 
 
35
 
36
 
37
  OPTION_KEYS = (
38
  "max_tokens", "inherit_defaults", "temperature", "top_p", "top_k", "min_p",
39
  "repetition_penalty", "presence_penalty", "frequency_penalty", "seed", "stop",
40
- "stream", "include_usage", "history_turns", "thinking", "extra_json",
41
  )
42
 
43
  CSS = """
@@ -77,10 +83,10 @@ body {background: #f5f7f6;}
77
 
78
  HEADER = """
79
  <div id="hero">
80
- <span class="badge">OpenAI-compatible · vLLM</span>
81
  <div class="eyebrow">INFERENCE WORKSPACE</div>
82
  <h1>vLLM Chat Studio</h1>
83
- <p>单次测试,或接着聊。让每一次生成都可调、可查看。</p>
84
  </div>
85
  """
86
 
@@ -91,11 +97,66 @@ def new_session():
91
  "run_id": None, "active_mode": None}
92
 
93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  def visible_messages(turns):
95
  """Presentation messages are never reused as the backend conversation."""
96
  messages = []
97
  for turn in turns:
98
- messages.append({"role": "user", "content": turn["user"]})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  reasoning = turn.get("reasoning", "")
100
  if reasoning:
101
  messages.append({
@@ -135,8 +196,8 @@ def metrics_html(turn=None):
135
 
136
  def mode_note(mode):
137
  if mode == "single":
138
- return "每次只发送 System Prompt 和当前问题;下面的历史记录仅供对照。"
139
- return "自动携带已完成的历史问答;可在「会话与输出」中限制携带轮数。"
140
 
141
 
142
  def snapshot(mode, state, *, input_value=None, model_value=None):
@@ -173,6 +234,8 @@ def format_status(turn):
173
 
174
 
175
  def make_handlers(backend):
 
 
176
  async def refresh_models(current):
177
  try:
178
  models = await backend.list_models()
@@ -194,27 +257,26 @@ def make_handlers(backend):
194
  if not turns:
195
  raise gr.Error("还没有可以重新生成的问题。")
196
  question = turns[-1]["user"]
 
197
  previous = turns[:-1]
198
  else:
199
- question = prompt or ""
200
  previous = turns[:]
201
- if not question.strip():
202
- raise gr.Error("请先输入问题。")
203
  options = dict(zip(OPTION_KEYS, values, strict=True))
 
 
 
204
  model_id = (model or "").strip() or backend.config.default_model
205
- # Validate options before modifying a conversation or clearing the editor.
206
- try:
207
- payload = build_payload(model_id or "__auto__", system_prompt, question,
208
- previous, mode == "single", options)
209
- except Exception as exc:
210
- raise gr.Error(safe_error(exc, backend.config)) from None
211
 
212
  run_id = uuid.uuid4().hex
213
  state.update(busy=True, run_id=run_id, active_mode=mode)
214
  turn = {"user": question, "content": "", "reasoning": "", "status": "generating",
215
- "status_text": "正在连接模型…", "usage": {}, "payload": None,
 
 
216
  "elapsed": None, "ttft": None, "finish_reason": None}
217
- # Keep the replaced answer until a new request has passed local validation.
218
  if retry:
219
  state["turns"][mode] = previous + [turn]
220
  else:
@@ -222,6 +284,16 @@ def make_handlers(backend):
222
  started = time.monotonic()
223
  try:
224
  yield snapshot(mode, state, input_value="")
 
 
 
 
 
 
 
 
 
 
225
  if not model_id:
226
  models = await backend.list_models()
227
  if not models:
@@ -230,7 +302,9 @@ def make_handlers(backend):
230
  if state["run_id"] != run_id:
231
  return
232
  payload["model"] = model_id
233
- turn["payload"] = payload
 
 
234
  turn["status_text"] = "正在等待模型输出…"
235
  yield snapshot(mode, state, model_value=model_id)
236
  async with aclosing(backend.generate(payload)) as updates:
@@ -260,7 +334,7 @@ def make_handlers(backend):
260
  state.update(busy=False, run_id=None, active_mode=None)
261
  # The stop action owns its final UI update; do not overwrite a newer run.
262
  if not state["busy"] and state["turns"][mode] and state["turns"][mode][-1] is turn:
263
- restore = question if turn["status"] == "error" else None
264
  yield snapshot(mode, state, input_value=restore)
265
 
266
  def stop(mode, state):
@@ -272,7 +346,7 @@ def make_handlers(backend):
272
  if turn["status"] in {"generating", "stopped"}:
273
  turn["status"] = "stopped"
274
  turn["status_text"] = "已停止 · 未完成的回答不会进入后续上下文。"
275
- restore = turn["user"]
276
  state.update(busy=False, run_id=None, active_mode=None)
277
  return snapshot(mode, state, input_value=restore)
278
 
@@ -293,6 +367,7 @@ def make_handlers(backend):
293
  def create_app(config=None, backend=None):
294
  config = config or Config.from_env()
295
  backend = backend or ChatBackend(config)
 
296
  run, refresh_models, stop, clear, switch = make_handlers(backend)
297
  concurrency = int(os.getenv("MAX_CONCURRENT_REQUESTS", "8"))
298
  if concurrency < 1:
@@ -355,6 +430,16 @@ def create_app(config=None, backend=None):
355
  choices=[("服务端默认", "default"), ("开启", "on"), ("关闭", "off")],
356
  value="default", label="Thinking", info="通过 chat_template_kwargs.enable_thinking 控制;需要模型模板支持。",
357
  )
 
 
 
 
 
 
 
 
 
 
358
  with gr.Accordion("高级 JSON 参数", open=False):
359
  gr.Markdown("直接填写请求体字段。可覆盖采样参数;不覆盖模型、消息或流式开关。")
360
  extra = gr.Code(value="{}", language="json", lines=9, interactive=True,
@@ -371,15 +456,19 @@ def create_app(config=None, backend=None):
371
  value=[], label="对话", show_label=False, height=510, min_height=320,
372
  elem_id="chat", buttons=["copy"], layout="bubble", sanitize_html=True,
373
  allow_tags=False,
374
- placeholder="<strong>从一个问题开始</strong><br>选择模型,调整参数,查看回答与推理过程。",
375
  latex_delimiters=[{"left": "$$", "right": "$$", "display": True},
376
  {"left": "$", "right": "$", "display": False},
377
  {"left": "\\[", "right": "\\]", "display": True},
378
  {"left": "\\(", "right": "\\)", "display": False}],
379
  )
380
- prompt = gr.Textbox(
381
- label="消息", show_label=False, placeholder="输入你的问题…", lines=3,
 
382
  max_lines=10, elem_id="composer", interactive=True,
 
 
 
383
  )
384
  with gr.Row():
385
  send = gr.Button("发送", variant="primary", scale=3, elem_id="send")
@@ -390,16 +479,16 @@ def create_app(config=None, backend=None):
390
  metrics = gr.HTML(metrics_html())
391
  with gr.Accordion("本次请求 JSON", open=False):
392
  request_json = gr.Code(value="{}", language="json", lines=15,
393
- interactive=False, label="实际发送的请求体")
394
- gr.Markdown("此处不包含 Authorization;不包含系统环境变量。")
395
  gr.Markdown(
396
- "聊天记录保留在当前浏览器会话对应的服务端内存中。刷新或 Space 重启后可能清空。",
397
  elem_id="footer-note",
398
  )
399
 
400
  options = [max_tokens, inherit, temperature, top_p, top_k, min_p, repetition,
401
  presence, frequency, seed, stops, streaming, include_usage,
402
- history_turns, thinking, extra]
403
  inputs = [prompt, mode, session, model, system, *options]
404
  outputs = [chat, session, status, request_json, metrics, prompt, send, stop_btn,
405
  retry, clear_btn, mode, note, model]
@@ -461,6 +550,7 @@ def main():
461
  auth=(username, password) if username else None,
462
  auth_message="登录以使用此 vLLM 工作台。" if username else None,
463
  enable_monitoring=False,
 
464
  )
465
 
466
 
 
5
  import asyncio
6
  import html
7
  import json
8
+ import math
9
+ import mimetypes
10
  import os
11
  import time
12
  import uuid
13
  from contextlib import aclosing
14
  from functools import partial
15
+ from pathlib import Path
16
 
17
  os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "False")
18
 
 
34
 
35
  import gradio as gr
36
 
37
+ from chat_backend import (
38
+ ChatAPIError, ChatBackend, Config, build_payload, prepare_images,
39
+ redact_image_payload, safe_error,
40
+ )
41
 
42
 
43
  OPTION_KEYS = (
44
  "max_tokens", "inherit_defaults", "temperature", "top_p", "top_k", "min_p",
45
  "repetition_penalty", "presence_penalty", "frequency_penalty", "seed", "stop",
46
+ "stream", "include_usage", "history_turns", "thinking", "extra_json", "resize_long_edge",
47
  )
48
 
49
  CSS = """
 
83
 
84
  HEADER = """
85
  <div id="hero">
86
+ <span class="badge">IMAGE + TEXT · vLLM</span>
87
  <div class="eyebrow">INFERENCE WORKSPACE</div>
88
  <h1>vLLM Chat Studio</h1>
89
+ <p>上传图片,带着上下文继续聊。让每一次生成都可调、可查看。</p>
90
  </div>
91
  """
92
 
 
97
  "run_id": None, "active_mode": None}
98
 
99
 
100
+ def image_settings():
101
+ settings = {}
102
+ for field, variable, default, integer in (
103
+ ("max_images", "MAX_IMAGES_PER_REQUEST", 8, True),
104
+ ("max_image_mb", "MAX_IMAGE_MB", 20, False),
105
+ ("max_image_pixels", "MAX_IMAGE_PIXELS", 40000000, True),
106
+ ("max_image_payload_mb", "MAX_IMAGE_PAYLOAD_MB", 64, False),
107
+ ):
108
+ try:
109
+ raw = os.getenv(variable, str(default))
110
+ value = int(raw) if integer else float(raw)
111
+ if not math.isfinite(value) or value <= 0:
112
+ raise ValueError
113
+ except (ValueError, OverflowError):
114
+ raise ValueError(f"{variable} 必须是正{'整数' if integer else '数值'}。") from None
115
+ settings[field] = value
116
+ return settings
117
+
118
+
119
+ def split_composer(value):
120
+ """Only use Gradio-preprocessed upload paths, never a path entered as text."""
121
+ if isinstance(value, str) or value is None:
122
+ return value or "", []
123
+ if not isinstance(value, dict):
124
+ raise gr.Error("消息格式无效,请重新输入文字或上传图片。")
125
+ text, files = value.get("text") or "", value.get("files") or []
126
+ if not isinstance(text, str) or not isinstance(files, list) or any(
127
+ not isinstance(path, str) for path in files
128
+ ):
129
+ raise gr.Error("图片上传信息无效,请重新上传。")
130
+ return text, files[:]
131
+
132
+
133
+ def composer_value(turn):
134
+ files = turn.get("input_files", [])
135
+ return {"text": turn["user"], "files": files[:]} if files else turn["user"]
136
+
137
+
138
  def visible_messages(turns):
139
  """Presentation messages are never reused as the backend conversation."""
140
  messages = []
141
  for turn in turns:
142
+ images = turn.get("images") or [
143
+ {"path": path, "name": Path(path).name,
144
+ "mime_type": mimetypes.guess_type(path)[0] or "image/png"}
145
+ for path in turn.get("input_files", [])
146
+ ]
147
+ if images:
148
+ content = ([{"type": "text", "text": turn["user"]}]
149
+ if turn["user"] else [])
150
+ for picture in images:
151
+ content.append({
152
+ "type": "file",
153
+ "file": {"path": picture["path"], "orig_name": picture["name"],
154
+ "mime_type": picture["mime_type"]},
155
+ "alt_text": picture["name"],
156
+ })
157
+ messages.append({"role": "user", "content": content})
158
+ else:
159
+ messages.append({"role": "user", "content": turn["user"]})
160
  reasoning = turn.get("reasoning", "")
161
  if reasoning:
162
  messages.append({
 
196
 
197
  def mode_note(mode):
198
  if mode == "single":
199
+ return "每次只发送 System Prompt 和本次图文;下面的历史记录仅供对照。"
200
+ return "自动携带已完成的历史图文;追问同一张图片无需重复上传。"
201
 
202
 
203
  def snapshot(mode, state, *, input_value=None, model_value=None):
 
234
 
235
 
236
  def make_handlers(backend):
237
+ limits = image_settings()
238
+
239
  async def refresh_models(current):
240
  try:
241
  models = await backend.list_models()
 
257
  if not turns:
258
  raise gr.Error("还没有可以重新生成的问题。")
259
  question = turns[-1]["user"]
260
+ input_files = turns[-1].get("input_files", [])[:]
261
  previous = turns[:-1]
262
  else:
263
+ question, input_files = split_composer(prompt)
264
  previous = turns[:]
265
+ if not question.strip() and not input_files:
266
+ raise gr.Error("请输入问题,或上传至少一张图片。")
267
  options = dict(zip(OPTION_KEYS, values, strict=True))
268
+ resize_long_edge = options.pop("resize_long_edge", 0)
269
+ options["max_images_per_request"] = limits["max_images"]
270
+ options["max_image_payload_mb"] = limits["max_image_payload_mb"]
271
  model_id = (model or "").strip() or backend.config.default_model
 
 
 
 
 
 
272
 
273
  run_id = uuid.uuid4().hex
274
  state.update(busy=True, run_id=run_id, active_mode=mode)
275
  turn = {"user": question, "content": "", "reasoning": "", "status": "generating",
276
+ "input_files": input_files, "images": [],
277
+ "status_text": "正在读取图片…" if input_files else "正在连接模型…",
278
+ "usage": {}, "payload": None,
279
  "elapsed": None, "ttft": None, "finish_reason": None}
 
280
  if retry:
281
  state["turns"][mode] = previous + [turn]
282
  else:
 
284
  started = time.monotonic()
285
  try:
286
  yield snapshot(mode, state, input_value="")
287
+ pictures = await asyncio.to_thread(
288
+ prepare_images, input_files,
289
+ max_images=limits["max_images"], max_image_mb=limits["max_image_mb"],
290
+ max_image_pixels=limits["max_image_pixels"], resize_long_edge=resize_long_edge,
291
+ ) if input_files else []
292
+ if state["run_id"] != run_id:
293
+ return
294
+ turn["images"] = pictures
295
+ payload = build_payload(model_id or "__auto__", system_prompt, question,
296
+ previous, mode == "single", options, images=pictures)
297
  if not model_id:
298
  models = await backend.list_models()
299
  if not models:
 
302
  if state["run_id"] != run_id:
303
  return
304
  payload["model"] = model_id
305
+ # Keep the real Base64 in server-side image records and the outgoing
306
+ # request only. The preview must not repeat large image data per token.
307
+ turn["payload"] = redact_image_payload(payload)
308
  turn["status_text"] = "正在等待模型输出…"
309
  yield snapshot(mode, state, model_value=model_id)
310
  async with aclosing(backend.generate(payload)) as updates:
 
334
  state.update(busy=False, run_id=None, active_mode=None)
335
  # The stop action owns its final UI update; do not overwrite a newer run.
336
  if not state["busy"] and state["turns"][mode] and state["turns"][mode][-1] is turn:
337
+ restore = composer_value(turn) if turn["status"] == "error" else None
338
  yield snapshot(mode, state, input_value=restore)
339
 
340
  def stop(mode, state):
 
346
  if turn["status"] in {"generating", "stopped"}:
347
  turn["status"] = "stopped"
348
  turn["status_text"] = "已停止 · 未完成的回答不会进入后续上下文。"
349
+ restore = composer_value(turn)
350
  state.update(busy=False, run_id=None, active_mode=None)
351
  return snapshot(mode, state, input_value=restore)
352
 
 
367
  def create_app(config=None, backend=None):
368
  config = config or Config.from_env()
369
  backend = backend or ChatBackend(config)
370
+ limits = image_settings()
371
  run, refresh_models, stop, clear, switch = make_handlers(backend)
372
  concurrency = int(os.getenv("MAX_CONCURRENT_REQUESTS", "8"))
373
  if concurrency < 1:
 
430
  choices=[("服务端默认", "default"), ("开启", "on"), ("关闭", "off")],
431
  value="default", label="Thinking", info="通过 chat_template_kwargs.enable_thinking 控制;需要模型模板支持。",
432
  )
433
+ with gr.Accordion("图片设置", open=False):
434
+ resize_long_edge = gr.Number(
435
+ value=0, minimum=0, precision=0, label="图片最长边 · 像素",
436
+ info="0 = 原尺寸;正数只缩小更大的图片,不放大。修改后也适用于重新生成。",
437
+ )
438
+ gr.Markdown(
439
+ f"支持 PNG、JPEG、WebP、BMP、单页 TIFF。每张最多 **{limits['max_image_mb']:g} MiB**,"
440
+ f"每次请求最多 **{limits['max_images']} 张**(包含历史图片)。\n\n"
441
+ "默认保留原分辨率;模型服务仍可能按自己的视觉处理配置缩放。"
442
+ )
443
  with gr.Accordion("高级 JSON 参数", open=False):
444
  gr.Markdown("直接填写请求体字段。可覆盖采样参数;不覆盖模型、消息或流式开关。")
445
  extra = gr.Code(value="{}", language="json", lines=9, interactive=True,
 
456
  value=[], label="对话", show_label=False, height=510, min_height=320,
457
  elem_id="chat", buttons=["copy"], layout="bubble", sanitize_html=True,
458
  allow_tags=False,
459
+ placeholder="<strong>发一张图,或者问个问题</strong><br>文档、图表、截图都可以。请选择支持图片输入的模型。",
460
  latex_delimiters=[{"left": "$$", "right": "$$", "display": True},
461
  {"left": "$", "right": "$", "display": False},
462
  {"left": "\\[", "right": "\\]", "display": True},
463
  {"left": "\\(", "right": "\\)", "display": False}],
464
  )
465
+ prompt = gr.MultimodalTextbox(
466
+ label="消息与图片", show_label=False,
467
+ placeholder="输入问题,或点击 + 上传图片;也可拖入图片…", lines=3,
468
  max_lines=10, elem_id="composer", interactive=True,
469
+ sources=["upload"], file_count="multiple",
470
+ file_types=[".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tif", ".tiff"],
471
+ submit_btn=False, max_plain_text_length=1000000,
472
  )
473
  with gr.Row():
474
  send = gr.Button("发送", variant="primary", scale=3, elem_id="send")
 
479
  metrics = gr.HTML(metrics_html())
480
  with gr.Accordion("本次请求 JSON", open=False):
481
  request_json = gr.Code(value="{}", language="json", lines=15,
482
+ interactive=False, label="请求体结构 · 图片 Base64 已省略")
483
+ gr.Markdown("图片编码只在此预览中省略,发送给模型时包含完整图片;此处不包含 Authorization。")
484
  gr.Markdown(
485
+ "文字与图片记录保留在当前会话中。刷新或 Space 重启后可能清空。",
486
  elem_id="footer-note",
487
  )
488
 
489
  options = [max_tokens, inherit, temperature, top_p, top_k, min_p, repetition,
490
  presence, frequency, seed, stops, streaming, include_usage,
491
+ history_turns, thinking, extra, resize_long_edge]
492
  inputs = [prompt, mode, session, model, system, *options]
493
  outputs = [chat, session, status, request_json, metrics, prompt, send, stop_btn,
494
  retry, clear_btn, mode, note, model]
 
550
  auth=(username, password) if username else None,
551
  auth_message="登录以使用此 vLLM 工作台。" if username else None,
552
  enable_monitoring=False,
553
+ max_file_size=int(image_settings()["max_image_mb"] * 1024 * 1024),
554
  )
555
 
556
 
chat_backend.py CHANGED
@@ -6,19 +6,27 @@ previews contain JSON bodies, never authentication headers.
6
 
7
  from __future__ import annotations
8
 
 
9
  import copy
 
 
10
  import html
11
  import json
12
  import math
13
  import os
14
  import re
 
 
15
  import time
 
16
  from collections.abc import AsyncIterator, Mapping, Sequence
17
  from dataclasses import dataclass, field
 
18
  from typing import Any
19
  from urllib.parse import urlsplit, urlunsplit
20
 
21
  import httpx
 
22
 
23
 
24
  DEFAULT_ORIGIN = "https://jo8bpbok8b8kcca5jahhqmdcpbd9cchm.openapi-inspire.inf.tech"
@@ -105,13 +113,25 @@ class Config:
105
  )
106
 
107
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  def _clean_text(value: Any, config: Config, limit: int = 700) -> str:
109
- text = str(value or "")
110
  # Redact before truncation, so a shortened secret can never survive.
111
  if config.api_key:
112
  text = text.replace(config.api_key, "[已隐藏密钥]")
113
  text = re.sub(r"(?i)\bBearer\s+[^\s\"'<>]+", "Bearer [已隐藏密钥]", text)
114
- text = html.unescape(text)
115
  if config.api_key:
116
  text = text.replace(config.api_key, "[已隐藏密钥]")
117
  text = re.sub(r"<[^>]*>", " ", text)
@@ -256,6 +276,227 @@ def _stop_value(value: Any, *, from_editor: bool = False) -> list[str] | str | N
256
  return value or None
257
 
258
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259
  _SAMPLING_DEFAULTS = {
260
  "temperature": 0.7,
261
  "top_p": 0.9,
@@ -270,7 +511,8 @@ _CLIENT_ONLY = {
270
  "api_key", "base_url", "url", "headers", "extra_headers", "extra_query", "query",
271
  "timeout", "request_timeout", "http_client", "transport", "verify", "verify_ssl",
272
  "inherit_defaults", "include_usage", "history_turns", "single_turn", "system_prompt",
273
- "prompt", "thinking", "extra_json",
 
274
  }
275
  _TOOL_FIELDS = {"tools", "tool_choice", "parallel_tool_calls", "functions", "function_call"}
276
 
@@ -328,18 +570,26 @@ def build_payload(
328
  turns: Sequence[Mapping[str, Any]] | None,
329
  single_turn: bool,
330
  options: Mapping[str, Any] | None,
 
 
331
  ) -> dict[str, Any]:
332
  """Build one request; advanced JSON overrides controls at the top level.
333
 
334
  ``inherit_defaults`` omits the seven numeric sampling controls. Explicit
335
  token limit, seed, stop, reasoning preference and advanced JSON still apply.
336
  Only completed turns enter history; UI-only reasoning is never replayed.
 
337
  """
338
  options = dict(options or {})
 
339
  if not isinstance(model, str) or not model.strip():
340
  raise ChatAPIError("请选择或输入模型 ID,也可设置 Space 变量 INF_MODEL。")
341
- if not isinstance(prompt, str) or not prompt.strip():
342
- raise ChatAPIError("请先输入问题。")
 
 
 
 
343
  if not isinstance(system_prompt, str):
344
  raise ChatAPIError("系统提示词必须是文本。")
345
  _bool_option(single_turn, "single_turn")
@@ -347,9 +597,8 @@ def build_payload(
347
  stream = _bool_option(options.get("stream", True), "stream")
348
  include_usage = _bool_option(options.get("include_usage", True), "include_usage")
349
  history_turns = _integer(options.get("history_turns", 0), "history_turns", 0)
350
- messages: list[dict[str, str]] = []
351
- if system_prompt.strip():
352
- messages.append({"role": "system", "content": system_prompt})
353
  if not single_turn:
354
  completed = [turn for turn in (turns or []) if turn.get("status") == "complete"]
355
  if history_turns:
@@ -358,11 +607,20 @@ def build_payload(
358
  user, content = turn.get("user"), turn.get("content")
359
  if not isinstance(user, str) or not isinstance(content, str):
360
  raise ChatAPIError("历史消息格式无效,请清空会话后重试。")
361
- messages.extend((
362
- {"role": "user", "content": user},
363
- {"role": "assistant", "content": content},
364
- ))
365
- messages.append({"role": "user", "content": prompt})
 
 
 
 
 
 
 
 
 
366
  payload: dict[str, Any] = {
367
  "model": model.strip(),
368
  "messages": messages,
 
6
 
7
  from __future__ import annotations
8
 
9
+ import base64
10
  import copy
11
+ import hashlib
12
+ import io
13
  import html
14
  import json
15
  import math
16
  import os
17
  import re
18
+ import stat
19
+ import tempfile
20
  import time
21
+ import warnings
22
  from collections.abc import AsyncIterator, Mapping, Sequence
23
  from dataclasses import dataclass, field
24
+ from pathlib import Path
25
  from typing import Any
26
  from urllib.parse import urlsplit, urlunsplit
27
 
28
  import httpx
29
+ from PIL import Image, ImageOps, UnidentifiedImageError
30
 
31
 
32
  DEFAULT_ORIGIN = "https://jo8bpbok8b8kcca5jahhqmdcpbd9cchm.openapi-inspire.inf.tech"
 
113
  )
114
 
115
 
116
+ # Also accept escaped slashes/newlines in a server's JSON error echo. Remove
117
+ # image data before truncating so an arbitrarily long Base64 prefix cannot leak.
118
+ _IMAGE_ECHO_RE = re.compile(
119
+ r"data:image(?:/|\\/)[A-Za-z0-9.+-]+;base64,[A-Za-z0-9+/=_\\\-\s]+",
120
+ re.IGNORECASE,
121
+ )
122
+
123
+
124
+ def _redact_image_text(text: str) -> str:
125
+ return _IMAGE_ECHO_RE.sub("[已隐藏图片 Base64 数据]", text)
126
+
127
+
128
  def _clean_text(value: Any, config: Config, limit: int = 700) -> str:
129
+ text = _redact_image_text(str(value or ""))
130
  # Redact before truncation, so a shortened secret can never survive.
131
  if config.api_key:
132
  text = text.replace(config.api_key, "[已隐藏密钥]")
133
  text = re.sub(r"(?i)\bBearer\s+[^\s\"'<>]+", "Bearer [已隐藏密钥]", text)
134
+ text = _redact_image_text(html.unescape(text))
135
  if config.api_key:
136
  text = text.replace(config.api_key, "[已隐藏密钥]")
137
  text = re.sub(r"<[^>]*>", " ", text)
 
276
  return value or None
277
 
278
 
279
+ _IMAGE_FORMATS = ("PNG", "JPEG", "WEBP", "BMP", "TIFF")
280
+ _IMAGE_MIME = {"PNG": "image/png", "JPEG": "image/jpeg", "WEBP": "image/webp"}
281
+ _IMAGE_DATA_RE = re.compile(r"data:(image/(?:png|jpeg|webp));base64,([A-Za-z0-9+/]+={0,2})\Z")
282
+
283
+
284
+ def _image_signature(header: bytes) -> bool:
285
+ return (
286
+ header.startswith(b"\x89PNG\r\n\x1a\n")
287
+ or header.startswith(b"\xff\xd8\xff")
288
+ or (header.startswith(b"RIFF") and header[8:12] == b"WEBP")
289
+ or header.startswith(b"BM")
290
+ or header.startswith((b"II*\x00", b"MM\x00*", b"II+\x00", b"MM\x00+"))
291
+ )
292
+
293
+
294
+ def _read_uploaded_image(path: Path, max_bytes: int) -> bytes:
295
+ """Check type and size before reading a bounded uploaded image file."""
296
+ try:
297
+ fd = os.open(path, os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0))
298
+ with os.fdopen(fd, "rb") as stream:
299
+ info = os.fstat(stream.fileno())
300
+ if not stat.S_ISREG(info.st_mode):
301
+ raise ChatAPIError("上传图片必须是普通文件。")
302
+ if info.st_size <= 0:
303
+ raise ChatAPIError("上传图片为空。")
304
+ if info.st_size > max_bytes:
305
+ raise ChatAPIError("单张图片超过大小限制,请压缩图片或调整 MAX_IMAGE_MB。")
306
+ header = stream.read(min(32, max_bytes + 1))
307
+ if len(header) > max_bytes:
308
+ raise ChatAPIError("单张图片超过大小限制,请压缩图片或调整 MAX_IMAGE_MB。")
309
+ if not _image_signature(header):
310
+ raise ChatAPIError("仅支持 PNG、JPEG、WebP、BMP 或 TIFF 静态图片;文件内容与图片格式不符。")
311
+ data = header + stream.read(max_bytes - len(header) + 1)
312
+ if len(data) > max_bytes:
313
+ raise ChatAPIError("单张图片超过大小限制,请压缩图片或调整 MAX_IMAGE_MB。")
314
+ return data
315
+ except ChatAPIError:
316
+ raise
317
+ except (OSError, ValueError):
318
+ raise ChatAPIError("无法读取上传图片,请重新上传后重试。") from None
319
+
320
+
321
+ def _save_prepared_png(source: Path, data: bytes) -> str:
322
+ """Keep the browser preview and the API image byte-for-byte identical."""
323
+ target = source.parent / f"prepared-{hashlib.sha256(data).hexdigest()}.png"
324
+ temporary = None
325
+ try:
326
+ with tempfile.NamedTemporaryFile(dir=source.parent, prefix=".prepared-", suffix=".png", delete=False) as stream:
327
+ temporary = stream.name
328
+ stream.write(data)
329
+ os.replace(temporary, target)
330
+ temporary = None
331
+ return str(target)
332
+ except OSError:
333
+ raise ChatAPIError("无法保存处理后的图片,请重新上传后重试。") from None
334
+ finally:
335
+ if temporary:
336
+ try:
337
+ os.unlink(temporary)
338
+ except OSError:
339
+ pass
340
+
341
+
342
+ def _png_image(image: Image.Image, *, resizing: bool) -> Image.Image:
343
+ if image.mode == "P" and resizing:
344
+ return image.convert("RGBA" if "transparency" in image.info else "RGB")
345
+ if image.mode == "1" and resizing:
346
+ return image.convert("L")
347
+ if image.mode in {"CMYK", "YCbCr", "LAB", "HSV"}:
348
+ return image.convert("RGB")
349
+ if image.mode.startswith("I;16"):
350
+ return image.convert("I" if resizing else "I;16")
351
+ if image.mode not in {"1", "L", "LA", "P", "RGB", "RGBA", "I"}:
352
+ raise ChatAPIError("此图片的像素格式暂不支持,请先转换为普通 PNG 或 JPEG。")
353
+ return image
354
+
355
+
356
+ def prepare_images(
357
+ paths: Sequence[str | os.PathLike[str]] | str | os.PathLike[str] | None,
358
+ *,
359
+ max_images: int = 8,
360
+ max_image_mb: float = 20,
361
+ max_image_pixels: int = 40_000_000,
362
+ resize_long_edge: int = 0,
363
+ ) -> list[dict[str, Any]]:
364
+ """Validate local uploads and prepare static OpenAI-compatible data URLs.
365
+
366
+ PNG/JPEG/WebP bytes are preserved unless EXIF orientation or an explicitly
367
+ requested resize changes the image. Transformed images and BMP/TIFF become
368
+ lossless PNG, with a matching preview next to the original uploaded file.
369
+ ``size_bytes`` is the final decoded image size; MB settings use 1024**2.
370
+ """
371
+ count_limit = _integer(max_images, "max_images", 1)
372
+ pixel_limit = _integer(max_image_pixels, "max_image_pixels", 1)
373
+ long_edge = _integer(resize_long_edge, "resize_long_edge", 0)
374
+ byte_limit = int(_number(max_image_mb, "max_image_mb", 0, open_low=True) * 1024**2)
375
+ if byte_limit < 1:
376
+ raise ChatAPIError("max_image_mb 至少需要允许 1 字节。")
377
+ if paths is None:
378
+ return []
379
+ if isinstance(paths, (str, os.PathLike)):
380
+ paths = [paths]
381
+ if not isinstance(paths, Sequence):
382
+ raise ChatAPIError("上传图片列表格式无效,请重新上传。")
383
+ if len(paths) > count_limit:
384
+ raise ChatAPIError(f"本次最多上传 {count_limit} 张图片,请减少图片数量。")
385
+ records = []
386
+ for supplied in paths:
387
+ if not isinstance(supplied, (str, os.PathLike)):
388
+ raise ChatAPIError("上传图片路径格式无效,请重新上传。")
389
+ path = Path(supplied).absolute()
390
+ raw = _read_uploaded_image(path, byte_limit)
391
+ try:
392
+ with warnings.catch_warnings():
393
+ warnings.simplefilter("error", Image.DecompressionBombWarning)
394
+ with Image.open(io.BytesIO(raw), formats=list(_IMAGE_FORMATS)) as image:
395
+ if getattr(image, "is_animated", False) or getattr(image, "n_frames", 1) != 1:
396
+ raise ChatAPIError("暂不支持动图或多页图片,请将需要的帧或页面另存为静态图片。")
397
+ if image.width <= 0 or image.height <= 0 or image.width * image.height > pixel_limit:
398
+ raise ChatAPIError(f"图片像素数超过限制(最多 {pixel_limit:,} 像素),请先缩小图片。")
399
+ image.verify()
400
+ # Loading after verify catches incomplete compressed pixel data.
401
+ with Image.open(io.BytesIO(raw), formats=list(_IMAGE_FORMATS)) as image:
402
+ image.load()
403
+ orientation = image.getexif().get(274, 1)
404
+ rotated = orientation in {2, 3, 4, 5, 6, 7, 8}
405
+ output = ImageOps.exif_transpose(image) if rotated else image
406
+ resizing = bool(long_edge and max(output.size) > long_edge)
407
+ as_png = rotated or resizing or image.format not in _IMAGE_MIME
408
+ if as_png:
409
+ output = _png_image(output, resizing=resizing)
410
+ if resizing:
411
+ ratio = long_edge / max(output.size)
412
+ size = tuple(max(1, round(dimension * ratio)) for dimension in output.size)
413
+ output = output.resize(size, Image.Resampling.LANCZOS)
414
+ if output.mode == "I":
415
+ low, high = output.getextrema()
416
+ if low < 0 or high > 65535:
417
+ raise ChatAPIError("此 TIFF 的像素范围暂不支持,请先转换为普通 PNG 或 JPEG。")
418
+ output = output.convert("I;16")
419
+ buffer = io.BytesIO()
420
+ output.save(buffer, format="PNG")
421
+ encoded, mime = buffer.getvalue(), "image/png"
422
+ else:
423
+ encoded, mime = raw, _IMAGE_MIME[image.format]
424
+ width, height = output.size
425
+ except ChatAPIError:
426
+ raise
427
+ except (Image.DecompressionBombError, Image.DecompressionBombWarning):
428
+ raise ChatAPIError("图片像素数过大,请先缩小图片再上传。") from None
429
+ except (UnidentifiedImageError, OSError, ValueError, SyntaxError, EOFError):
430
+ raise ChatAPIError("图片已损坏或格式无效,无法完整解码;请重新导出图片后上传。") from None
431
+ if len(encoded) > byte_limit:
432
+ raise ChatAPIError("图片转换为 PNG 后超过大小限制,请设置较小的图片最长边,或调整 MAX_IMAGE_MB。")
433
+ preview = _save_prepared_png(path, encoded) if as_png else str(path)
434
+ records.append({
435
+ "path": preview,
436
+ "name": path.name,
437
+ "mime_type": mime,
438
+ "data_url": f"data:{mime};base64," + base64.b64encode(encoded).decode("ascii"),
439
+ "width": width,
440
+ "height": height,
441
+ "size_bytes": len(encoded),
442
+ })
443
+ return records
444
+
445
+
446
+ def _image_records(images: Sequence[Mapping[str, Any]] | None) -> list[Mapping[str, Any]]:
447
+ if images is None:
448
+ return []
449
+ if not isinstance(images, (list, tuple)) or any(not isinstance(item, Mapping) for item in images):
450
+ raise ChatAPIError("图片记录格式无效,请重新上传图片。")
451
+ return list(images)
452
+
453
+
454
+ def _image_message(text: str, images: Sequence[Mapping[str, Any]]) -> str | list[dict[str, Any]]:
455
+ if not images:
456
+ return text
457
+ blocks = [{"type": "text", "text": text}] if text.strip() else []
458
+ blocks.extend({"type": "image_url", "image_url": {"url": record["data_url"]}} for record in images)
459
+ return blocks
460
+
461
+
462
+ def _validate_request_images(images: Sequence[Mapping[str, Any]], options: Mapping[str, Any]) -> None:
463
+ count_limit = _integer(options.get("max_images_per_request", 8), "max_images_per_request", 1)
464
+ budget = _number(options.get("max_image_payload_mb", 64), "max_image_payload_mb", 0, open_low=True)
465
+ if len(images) > count_limit:
466
+ raise ChatAPIError(
467
+ f"当前请求共包含 {len(images)} 张图片,超过每次请求 {count_limit} 张的限制。"
468
+ "历史图片也计入总数,请减少携带的历史轮数、清空会话,或移除当前图片。"
469
+ )
470
+ total = 0
471
+ for record in images:
472
+ data_url = record.get("data_url")
473
+ if not isinstance(data_url, str):
474
+ raise ChatAPIError("图片数据缺失,请重新上传图片。")
475
+ total += len(data_url)
476
+ if total > budget * 1024**2:
477
+ raise ChatAPIError(
478
+ f"当前请求的图片 Base64 数据超过 {budget:g} MiB 限制(包含历史图片和编码膨胀)。"
479
+ "请减少历史轮数、图片数量,或设置较小的图片最长边。"
480
+ )
481
+ match = _IMAGE_DATA_RE.fullmatch(data_url)
482
+ if not match or (match.end(2) - match.start(2)) % 4 or record.get("mime_type", match.group(1)) != match.group(1):
483
+ raise ChatAPIError("图片数据格式无效,请重新上传图片。")
484
+
485
+
486
+ def redact_image_payload(payload: Any) -> Any:
487
+ """Copy a JSON preview without embedding uploaded image bytes in the UI."""
488
+ if isinstance(payload, dict):
489
+ return {key: redact_image_payload(value) for key, value in payload.items()}
490
+ if isinstance(payload, list):
491
+ return [redact_image_payload(value) for value in payload]
492
+ if isinstance(payload, str) and "data:image" in payload.lower():
493
+ match = _IMAGE_DATA_RE.fullmatch(payload)
494
+ if match:
495
+ return f"[图片 {match.group(1)};Base64 已隐藏,编码长度 {match.end(2) - match.start(2)} 字符]"
496
+ return _redact_image_text(payload)
497
+ return copy.deepcopy(payload)
498
+
499
+
500
  _SAMPLING_DEFAULTS = {
501
  "temperature": 0.7,
502
  "top_p": 0.9,
 
511
  "api_key", "base_url", "url", "headers", "extra_headers", "extra_query", "query",
512
  "timeout", "request_timeout", "http_client", "transport", "verify", "verify_ssl",
513
  "inherit_defaults", "include_usage", "history_turns", "single_turn", "system_prompt",
514
+ "prompt", "thinking", "extra_json", "images", "image_paths", "resize_long_edge",
515
+ "max_images_per_request", "max_image_payload_mb", "max_images", "max_image_mb", "max_image_pixels",
516
  }
517
  _TOOL_FIELDS = {"tools", "tool_choice", "parallel_tool_calls", "functions", "function_call"}
518
 
 
570
  turns: Sequence[Mapping[str, Any]] | None,
571
  single_turn: bool,
572
  options: Mapping[str, Any] | None,
573
+ *,
574
+ images: Sequence[Mapping[str, Any]] | None = None,
575
  ) -> dict[str, Any]:
576
  """Build one request; advanced JSON overrides controls at the top level.
577
 
578
  ``inherit_defaults`` omits the seven numeric sampling controls. Explicit
579
  token limit, seed, stop, reasoning preference and advanced JSON still apply.
580
  Only completed turns enter history; UI-only reasoning is never replayed.
581
+ Image limits cover all retained historical images and the current uploads.
582
  """
583
  options = dict(options or {})
584
+ current_images = _image_records(images)
585
  if not isinstance(model, str) or not model.strip():
586
  raise ChatAPIError("请选择或输入模型 ID,也可设置 Space 变量 INF_MODEL。")
587
+ if prompt is None:
588
+ prompt = ""
589
+ if not isinstance(prompt, str):
590
+ raise ChatAPIError("问题必须是文本。")
591
+ if not prompt.strip() and not current_images:
592
+ raise ChatAPIError("请先输入问题或上传图片。")
593
  if not isinstance(system_prompt, str):
594
  raise ChatAPIError("系统提示词必须是文本。")
595
  _bool_option(single_turn, "single_turn")
 
597
  stream = _bool_option(options.get("stream", True), "stream")
598
  include_usage = _bool_option(options.get("include_usage", True), "include_usage")
599
  history_turns = _integer(options.get("history_turns", 0), "history_turns", 0)
600
+ history = []
601
+ all_images = []
 
602
  if not single_turn:
603
  completed = [turn for turn in (turns or []) if turn.get("status") == "complete"]
604
  if history_turns:
 
607
  user, content = turn.get("user"), turn.get("content")
608
  if not isinstance(user, str) or not isinstance(content, str):
609
  raise ChatAPIError("历史消息格式无效,请清空会话后重试。")
610
+ historical_images = _image_records(turn.get("images"))
611
+ all_images.extend(historical_images)
612
+ history.append((user, content, historical_images))
613
+ all_images.extend(current_images)
614
+ _validate_request_images(all_images, options)
615
+ messages: list[dict[str, Any]] = []
616
+ if system_prompt.strip():
617
+ messages.append({"role": "system", "content": system_prompt})
618
+ for user, content, historical_images in history:
619
+ messages.extend((
620
+ {"role": "user", "content": _image_message(user, historical_images)},
621
+ {"role": "assistant", "content": content},
622
+ ))
623
+ messages.append({"role": "user", "content": _image_message(prompt, current_images)})
624
  payload: dict[str, Any] = {
625
  "model": model.strip(),
626
  "messages": messages,
requirements.txt CHANGED
@@ -1,2 +1,3 @@
1
  gradio==6.31.0
2
  httpx[socks]==0.28.1
 
 
1
  gradio==6.31.0
2
  httpx[socks]==0.28.1
3
+ pillow==12.3.0