Skip to content

fix(gemini): skip undownloadable history images instead of failing the turn - #10894

Merged
mantoujun12 merged 1 commit into
AstrBotDevs:masterfrom
JosephTian876:fix/gemini-history-image-degradation
Dec 1, 2026
Merged

mantoujun12 merged 1 commit into
AstrBotDevs:masterfrom
JosephTian876:fix/gemini-history-image-degradation

Conversation

@JosephTian876

@JosephTian876 JosephTian876 commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #10884.

Problem

When a Gemini provider replays conversation history that contains an image
reference (for example an OneBot image URL), a failed download of that single
image is treated as a failure of the main model:

  • the turn aborts with DownloadFileHTTPError, or
  • the agent runner catches it as a provider error and switches to a fallback
    provider, even though only one image in the replayed history could not be
    materialized.

Root cause

The real failure path is:

ToolLoopAgentRunner._iter_llm_responses_with_fallback
  -> provider.text_chat
    -> ProviderGoogleGenAI._query
      -> _prepare_conversation
        -> resolve_image_url              (strict=True)
          -> resolve_media_ref_to_base64_data
            -> MediaResolver.to_base64_data
              -> _resolve_path
                -> _materialize_media_ref
                  -> download_file
                     raises DownloadFileHTTPError

Two independent defects stack up on that path:

  1. DownloadFileHTTPError (astrbot/core/utils/io.py) subclasses
    RuntimeError, and aiohttp's ClientError, SyntaxError, EOFError and
    struct.error are likewise not OSError/ValueError. MediaResolver.to_base64_data
    only caught (OSError, ValueError), so the documented "an image that cannot
    be materialized degrades to None in non-strict mode" behavior never applied
    to download failures — even though is_recoverable_image_error() explicitly
    lists DownloadFileHTTPError.
  2. resolve_image_url passed strict=True and turned a None result into a
    ValueError, so even a corrected resolver could not degrade: it would
    necessarily raise, and the runner's per-candidate except Exception
    translated that into "the model failed".

This is a classification bug, not a design decision. The same repository
already degrades one image at a time in astr_main_agent.py ([Image unavailable] text part and continue), in provider/entities.py, and in
Gemini's own assemble_context for the current turn. Only the Gemini history
replay path and the media_utils catch were inconsistent, so no new contract
or configuration switch is needed.

Behavior after the fix

  • MediaResolver.to_base64_data(strict=True) still raises for an image that
    cannot be materialized; strict callers are unchanged.
  • In non-strict mode, a declared-recoverable image error (OSError,
    ValueError, SyntaxError, EOFError, struct.error, ClientError,
    DownloadFileHTTPError) degrades to None. Unrecoverable failures such as
    resource exhaustion (ENOMEM, EMFILE, ENFILE) and programming errors
    still propagate.
  • Gemini resolves each image in the conversation payload strictly and handles
    the declared-recoverable errors at its own boundary, the same shape
    astr_main_agent uses: one warning carrying the exception type and the
    log-safe reference, then skip only that image. A turn that still has text
    keeps exactly that text; only a turn left with no parts gets a single space
    part so the UserContent remains valid and non-empty. A None result from
    strict resolution takes the same warning-and-skip path via an explicit
    is None branch.
  • A degraded history image no longer reaches the agent runner as an exception,
    so the primary provider is used and no fallback provider is switched in.

Scope & safety

  • No configuration, public API, or provider contract changes.
  • Unrecoverable media errors are re-raised exactly as before.
  • The current-turn image path already behaved this way; history now matches it.
  • Audio out of scope (accepted for follow-up): This PR intentionally covers
    images only (fixing [Bug] OneBot 图片下载失败被误判为模型故障,导致回复中断或触发模型回退 #10884). process_audio_url in gemini_source.py still
    uses strict=True and raises on undownloadable history audio; graceful audio
    degradation is accepted as a separate follow-up PR.

Changed files

  • astrbot/core/provider/sources/gemini_source.py (+38 / -9)
  • astrbot/core/utils/media_utils.py (+6 / -3)
  • tests/test_gemini_source.py (+25 / -0)
  • tests/test_media_utils.py (+17 / -0)

Diff summary: 4 files changed, 86 insertions(+), 12 deletions(-).

Tests

Compact regression tests pinning both boundaries (42 lines total):

  • tests/test_media_utils.py::test_image_base64_data_degrades_download_http_error:
    verifies a mocked download_file raising DownloadFileHTTPError degrades to
    None when strict=False, still raises when strict=True, and an undeclared
    RuntimeError still propagates when strict=False.
  • tests/test_gemini_source.py::test_gemini_prepare_conversation_skips_undownloadable_images:
    verifies _prepare_conversation skips an undownloadable history image
    (DownloadFileHTTPError) while keeping the turn's text, produces a non-empty
    UserContent placeholder (" ") when an image-only turn resolves to no data,
    and still propagates an unrecoverable RuntimeError.

Verification:

  • Targeted suites (tests/test_media_utils.py, tests/test_gemini_source.py,
    tests/test_tool_loop_agent_runner.py): 199 passed, 1 skipped.
  • ruff format --check . and ruff check .: passed (0 issues).

Suggested merge order

Logically independent of #10961, #11185, and #11298 (all touch distinct sections of astrbot/core/provider/sources/gemini_source.py). Suggested order: #10961 → #10894 → #11185 → #11298 (any order works).

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've reviewed your changes and they look great!

Linked issues

#10884 [Bug] OneBot 图片下载失败被误判为模型故障,导致回复中断或触发模型回退 · 3 of 3 met

# Requirement Status Notes
1 Treat failed image downloads as recoverable image-input failures, not model-request failures. ✅ Met The media resolver now catches the declared recoverable image errors in non-strict mode, including DownloadFileHTTPError, while preserving propagation for undeclared errors.
2 Skip only the failed image, preserving the user’s text and other valid images so the model call can proceed. ✅ Met Gemini’s payload processing skips a recoverably unavailable image and continues processing the remaining parts; if no parts remain, it adds a placeholder text part.
3 Do not trigger a fallback provider because an image in the conversation history could not be downloaded. ✅ Met The Gemini boundary handles recoverable image errors before they reach the agent runner; the added runner test checks that the primary provider is called and the fallback is not.

Sourcery assessment

Approved.


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

@JosephTian876

Copy link
Copy Markdown
Contributor Author

Rebased onto latest master (feb3e82) alongside the #11143 URL audio changes; no behavioral changes to the approved diff.

@JosephTian876
JosephTian876 force-pushed the fix/gemini-history-image-degradation branch from be10e5b to 6cfb39c Compare November 21, 2026 21:17
@sourcery-ai

sourcery-ai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Linked issues

Checked at commit c4d84a4

#10884 [Bug] OneBot 图片下载失败被误判为模型故障,导致回复中断或触发模型回退 · 3 of 3 met

# Requirement Status Notes
1 Treat a failed image separately while preserving user text and other valid images, and continue the model call normally. ✅ Met Gemini logs and skips each recoverable image independently; the surrounding user content and successfully resolved images remain in the request.
2 In non-strict image resolution, return None for declared-recoverable failures while strict resolution and unrecoverable failures still raise. ✅ Met MediaResolver now checks recoverability around path resolution; Gemini handles recoverable errors at its own boundary while allowing other exceptions to propagate.
3 Avoid turning a failed history image into a model failure or an unnecessary provider fallback. ✅ Met The Gemini history preparation path skips recoverable image failures, and supplies a space part when an image-only user turn would otherwise be empty.

@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 93.75000% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
astrbot/core/provider/sources/gemini_source.py 93.33% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@JosephTian876
JosephTian876 force-pushed the fix/gemini-history-image-degradation branch 2 times, most recently from aa72c81 to b543d8e Compare November 30, 2026 04:55
@JosephTian876

Copy link
Copy Markdown
Contributor Author

Rebased onto latest master (a084409) and trimmed newly added test files per .github/copilot-instructions.md to keep the diff focused on production changes.

Local Verification

  • Pre-trim regression tests: 207 passed (test_gemini_source.py, test_media_utils.py, test_tool_loop_agent_runner.py)
  • Existing upstream test suite: 197 passed (test_gemini_source.py, test_media_utils.py, test_tool_loop_agent_runner.py)
  • ruff check and ruff format --check: passed (0 issues)

建议合并顺序

  1. #10894(修复历史图片无法下载导致对话失败,改动最小,优先合入)
  2. #10202 → #11018 → #11019(原生视频输入模态与遗留路径视频槽位修复,已依次堆叠)
  3. #11298 → #11185(Gemini 中转站 usageMetadata 回填与流式工具调用批次/ID 保留,均改动 _query_stream,按序合入后次序者轻微对齐即可)

@JosephTian876

Copy link
Copy Markdown
Contributor Author

Hi @camera-2018, this PR has been rebased cleanly onto latest master (a084409, b543d8e) with all CI checks green — whenever you have a moment, it's ready for a quick re-review/re-approval. Thanks!

@mantoujun12 mantoujun12 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The core fix is correct: DownloadFileHTTPError now degrades in non-strict resolution, and Gemini skips the failed history image instead of failing the turn or switching to the fallback provider. I reproduced the bug on the merge base and confirmed it is gone on this branch; I'm only blocking on the two points below.

  1. The description says 5 files / 349 insertions and lists six regression tests, but the actual diff is 2 files / +44/-12 with zero test changes. Looks like the tests were dropped in a force-push. Please restore them or update the description, otherwise nothing stops someone from narrowing the catch back to (OSError, ValueError) later.
  2. The fix only covers images. process_audio_url still uses strict=True and raises, so a single undownloadable history audio still aborts the turn or triggers the fallback provider. Might be out of scope, but it should be called out explicitly or handled in a follow-up.

Approving once the tests are back, or once the description is corrected and the audio gap is explicitly accepted.

@JosephTian876
JosephTian876 force-pushed the fix/gemini-history-image-degradation branch from b543d8e to c4d84a4 Compare November 30, 2026 13:37
@JosephTian876

Copy link
Copy Markdown
Contributor Author

Thanks for reproducing the issue and catching both points, @mantoujun12! Both blockers are now resolved in c4d84a48:

  1. Compact regression tests restored & PR description synced: The earlier oversized test additions had been trimmed in a prior cleanup push without refreshing the PR body. I've restored two compact, focused regression tests (42 lines total) directly guarding the catch and degradation boundaries, and updated the PR description so the file list, diffstat (4 files changed, +86/-12), and test list match the live diff 100%:

    • tests/test_media_utils.py::test_image_base64_data_degrades_download_http_error — pins DownloadFileHTTPError -> None when strict=False, raising when strict=True, and continued propagation of undeclared RuntimeError.
    • tests/test_gemini_source.py::test_gemini_prepare_conversation_skips_undownloadable_images — pins skipping DownloadFileHTTPError while keeping turn text, keeping a non-empty UserContent placeholder (" ") when an image-only turn resolves to None, and propagating unrecoverable RuntimeError.
    • Local verification: 199 passed, 1 skipped (test_media_utils.py, test_gemini_source.py, test_tool_loop_agent_runner.py); ruff check . & ruff format --check . passed (0 issues).
  2. Audio scope explicitly accepted: Confirmed — process_audio_url (strict=True) is intentionally out of scope for #10884 (image-only fix) and accepted as a separate follow-up PR. This scope boundary is now explicitly called out in the PR description as well.

Ready for re-review whenever you have a moment — thank you!

@mantoujun12
mantoujun12 merged commit 44db8cb into AstrBotDevs:master Dec 1, 2026
8 checks passed
@github-project-automation github-project-automation Bot moved this from In Progress to Done in AstrBot Roadmap Dec 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

[Bug] OneBot 图片下载失败被误判为模型故障,导致回复中断或触发模型回退

4 participants