AstrBot icon indicating copy to clipboard operation
AstrBot copied to clipboard

fix: sanitize unsupported image MIME types (e.g. GIF) in context cleaner

Open xiaoyuyu6420 opened this issue 4 months ago • 1 comments

Issue / 问题

Fixes #9295.

When a quoted animated GIF is added to conversation history, it can be persisted as data:image/gif;base64,.... Some OpenAI-compatible Gemini gateways declare image modality support but reject image/gif, so every later request fails with mime type is not supported / convert_request_failed until the session history is cleared.

sanitize_contexts_by_modalities() previously only checked coarse modality flags (image / audio / tool_use) and short-circuited when all three were enabled, so GIF MIME cleanup never ran for the reporter's configuration.

Modifications / 改动点

  • Keep a narrow unsupported MIME list (image/gif) in astrbot/core/provider/modalities.py.

  • Extract image MIME best-effort from OpenAI-style image_url data URLs and .gif HTTP URLs.

  • Replace unsupported GIF image blocks with [Image] even when the provider claims image support.

  • Preserve existing full image stripping when image modality is absent, and preserve JPEG/PNG/WebP / unknown-MIME images when image is supported.

  • Add unit tests for the reporter scenario and related edge cases.

  • [x] This is NOT a breaking change. / 这不是一个破坏性变更。

Screenshots or Test Results / 运行截图或测试结果

.venv/bin/ruff format --check astrbot/core/provider/modalities.py tests/unit/test_modalities_sanitize.py
.venv/bin/ruff check astrbot/core/provider/modalities.py tests/unit/test_modalities_sanitize.py
.venv/bin/pytest tests/unit/test_modalities_sanitize.py -q
.venv/bin/pytest tests/agent/test_context_manager.py tests/unit/test_astr_main_agent.py tests/test_tool_loop_agent_runner.py -q

Results:

  • ruff format: 2 files already formatted
  • ruff check: All checks passed
  • new unit tests: 12 passed
  • related regression suite: 185 passed

Trade-off note

This intentionally uses a narrow hard-coded MIME blacklist (image/gif) instead of a new provider config switch, to keep the fix minimal and focused on the reported failure mode. Providers that truly accept GIF will lose GIF image blocks and receive a text placeholder instead. If maintainers prefer a configurable MIME whitelist/blacklist, that can be layered on later without reverting this safety net.

Checklist / 检查清单

  • [x] 😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc. / 如果 PR 中有新加入的功能,已经通过 Issue / 邮件等方式和作者讨论过。

  • [x] 👀 My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above. / 我的更改经过了良好的测试,并已在上方提供了“验证步骤”和“运行截图”。

  • [x] 🤓 I have ensured that no new warnings or errors are introduced. / 我已确保没有引入新的警告或错误。

Summary by Sourcery

Sanitize conversation contexts to strip unsupported image MIME types (notably GIF) even when providers claim image support, preventing incompatible gateways from rejecting subsequent requests.

Bug Fixes:

  • Ensure animated GIF image parts are replaced with text placeholders instead of being sent to providers that reject image/gif, avoiding persistent request failures.
  • Preserve existing behavior of fully stripping images when image modality is unavailable while keeping supported or unknown image types intact when image is allowed.

Tests:

  • Add unit tests covering GIF data URLs, GIF HTTP URLs, mixed content, non-GIF formats, unknown MIME handling, and empty inputs to verify the updated sanitization logic.

xiaoyuyu6420 avatar Jul 20 '26 17:07 xiaoyuyu6420

Pushed an iteration addressing the review feedback. Summary of decisions:

Adopted

  • source.media_type and mimeType/mime_type now strip parameters (e.g. image/gif; charset=binary → image/gif) and surrounding whitespace before comparison, matching how data URLs were already handled. Adds regression tests.
  • Image URLs are .strip()-ed defensively.
  • http(s) URL path extraction switched to urllib.parse.urlsplit, which keeps percent-encoded ?/# inside the path (more robust than the manual split).

Not adopted — extension point / config injection for _UNSUPPORTED_IMAGE_MIMES Kept this a narrow, code-level blocklist on purpose. Today only image/gif is known to be rejected by some Gemini-flavored OpenAI gateways, so a single-element check is the smallest change that fixes the reported bug. Adding a config knob or overridable helper right now would be speculative generality with no second use case. Happy to promote it to a configurable list once there is a real second MIME that needs different handling per provider.

Note on scope (issue #9295) This PR focuses on preventing new GIFs from being sent to / persisted in request payloads. The reporter also raised two related asks that are deliberately out of scope here, to keep this change reviewable:

  • sanitizing already-poisoned session history in storage, and
  • auto-retry once on convert_request_failed / mime type is not supported.

If maintainers want either, I can follow up in a separate PR rather than expand this one.

Tests: 16 passed (11 existing + 5 new). ruff format / ruff check clean.

xiaoyuyu6420 avatar Jul 21 '26 01:07 xiaoyuyu6420

这样实现会不会太粗暴了,直接拒绝了所有模型使用 GIF (虽然我也不知道哪个模型支持 GIF)。 在 模型配置的 模型能力处,能不能给 image 做一个 子选项,让用户勾选模型支持的 MIME。这样更优雅吧(当然也更难实现


This implementation might be too heavy-handed as it completely blocks GIFs for all models (unclear if any models even support GIFs). A more elegant approach ( though harder to implement ) would be adding an 'image' sub-option under model capability configuration, letting users check the supported MIME types.

sujoshua avatar Jul 24 '26 09:07 sujoshua

Hi @sujoshua, thanks for the feedback! I agree the hardcoded blocklist was too blunt.

I just pushed an update that adds a configurable image MIME whitelist (supported_image_mimes) to the provider settings. Users can now check which image formats the model supports (JPEG/PNG/WebP/GIF).

Behavior:

  • Unchecked (default): Fallback blocklist applies — GIF is filtered on known-problematic gateways (preserves the original #9295 fix for backward compatibility).
  • Checked: Strict whitelist mode — only the selected formats are kept.

The WebUI auto-generates a checkbox group from the schema, so no Vue changes were needed.

Would love your thoughts on this approach!

xiaoyuyu6420 avatar Jul 28 '26 03:07 xiaoyuyu6420