Skip to content

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

Open
JosephTian876 wants to merge 5 commits into
AstrBotDevs:masterfrom
JosephTian876:fix/gemini-history-image-degradation
Open

JosephTian876 wants to merge 5 commits 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
        -> process_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. process_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. process_image_url also
    serves current-turn parts, so the wording names the payload rather than the
    history. A turn that still has text keeps exactly that text, so replayed
    prompt content is unchanged; only a turn left with no parts gets a single
    space part. A None result from strict resolution (not produced today) takes
    the same warning-and-skip path through an explicit is None branch, so the
    optional is narrowed without an assert that python -O would strip.
  • A history user turn whose only content was a failed image still produces a
    valid, non-empty UserContent (a single space text part), so the request
    stays well-formed.
  • 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.

Why this is safe

  • 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.

Tests

Tests that pin the fix fail on the previous code; the two boundary tests keep
the catch narrow and the recoverability guard in place:

  • tests/test_media_utils.py:: test_image_base64_data_degrades_for_download_http_error_when_not_strict:
    a mocked download_file raising DownloadFileHTTPError degrades to None
    in non-strict mode, cleans up its temp file, and still raises in strict mode.
  • tests/test_media_utils.py:: test_image_base64_data_degrades_declared_recoverable_errors: ClientError,
    SyntaxError, EOFError and struct.error all degrade to None.
  • tests/test_media_utils.py:: test_image_base64_data_propagates_undeclared_errors: OSError(ENOMEM) and a
    plain RuntimeError still propagate. Narrowing the catch to
    DownloadFileHTTPError fails the declared-recoverable test above; dropping
    the recoverability guard fails this one.
  • tests/test_gemini_source.py:: test_gemini_prepare_conversation_skips_history_image_download_failure:
    a three-message history whose last turn has text plus a failing image_url
    produces three contents with exactly the text part, and logs the skipped
    reference together with the exception type; the type assertion fails without
    the warning change.
  • tests/test_gemini_source.py:: test_gemini_prepare_conversation_keeps_non_empty_user_turn_for_failed_image:
    an image-only failed turn yields one non-empty UserContent.
  • tests/test_gemini_source.py:: test_gemini_prepare_conversation_skips_image_resolved_to_no_data: a resolver
    monkeypatched to return None skips the image with a warning and keeps the
    text part; it fails on the previous assert-based narrowing.
  • tests/test_tool_loop_agent_runner.py:: test_degraded_history_image_does_not_switch_to_fallback_provider: a
    runner-level request through a Gemini provider with a failing history image
    calls the primary provider once and never the fallback provider.

Verification:

  • Affected suites: tests/test_media_utils.py,
    tests/test_gemini_source.py, tests/test_tool_loop_agent_runner.py —
    167 passed.
  • Full suite at the final commit (uv run python -m pytest -q .): 5050 passed,
    79 skipped, 3 failed, in 341s. The 3 failures are the pre-existing Windows
    managed-shell TimeoutError tests in tests/test_local_shell_component.py;
    the same 3 fail on a clean origin/master checkout.
  • ruff format --check . and ruff check . pass.
  • Diff: 5 files changed, 349 insertions(+), 12 deletions(-).

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).

Summary by Sourcery

Skip recoverable image materialization failures during Gemini conversation preparation without failing the turn or switching providers.

Bug Fixes:

  • Prevent undownloadable Gemini conversation images from aborting the request or triggering fallback-provider selection.
  • Allow declared-recoverable media resolution failures, including download and image parsing errors, to degrade safely in non-strict mode.

Enhancements:

  • Keep Gemini conversation payloads valid when an image-only user turn is skipped, while preserving any remaining text and logging the skipped media reference and error type.

Tests:

  • Add media resolver, Gemini conversation, and agent-runner coverage for recoverable image failures, unrecoverable error propagation, valid image-only turns, and fallback avoidance.

@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 ✨

to_base64_data only caught OSError and ValueError, but DownloadFileHTTPError and aiohttp ClientError subclass RuntimeError and is_recoverable_image_error already declares them skippable. Catch broadly and keep propagating anything outside that set so non-strict image payload assembly can still skip a bad reference.
Replayed history images were resolved with strict=True, so one unavailable image aborted the whole turn and the runner classified it as a provider failure, switching to a fallback provider. Resolve history images in non-strict mode, log and skip the failed reference, and keep image-only user turns valid with an empty text part.
Non-strict image resolution degraded only DownloadFileHTTPError was pinned. Add coverage for the other declared-recoverable errors (aiohttp ClientError, SyntaxError, EOFError, struct.error) and for errors that must still propagate (OSError ENOMEM, plain RuntimeError).
process_image_url also serves current-turn image parts, so the warning must not claim to skip history, and the exception type tells a failed download apart from a corrupt payload. Resolve strictly and reuse is_recoverable_image_error, the same boundary astr_main_agent uses.
Strict resolution raises instead of returning None today, so the assert narrowing the optional was unreachable. An assert disappears under python -O, so a future None would surface as an AttributeError further down. Branch on None explicitly and reuse the failure path's warning-and-skip behaviour.

The added test pins that skip branch.
@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 6cfb39c

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

# Requirement Status Notes
1 A failed image must not abort the Gemini request or trigger an unnecessary provider fallback. ✅ Met Gemini skips recoverable image failures in conversation preparation; the runner-level test confirms the primary provider is used without switching to fallback.
2 Handle a failed image individually while preserving user text and other valid images. ✅ Met Only the failed image part is skipped; remaining parts are retained, and the unavailable reference is logged.
3 Keep image-only user turns valid when their image cannot be downloaded. ✅ Met Gemini adds a single space text part if skipping images leaves the user turn with no parts.
4 Allow recoverable image materialization failures to degrade without swallowing unrecoverable errors. ✅ Met Non-strict resolution returns None for declared-recoverable failures, while strict resolution and undeclared failures still propagate.

@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!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: In Progress

Development

Successfully merging this pull request may close these issues.

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

3 participants