From b92d15eb8e721efac6c54ecab8dbbb0fb4c17ff8 Mon Sep 17 00:00:00 2001 From: JosephTian876 <204833675+JosephTian876@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:08:15 +0800 Subject: [PATCH 1/5] fix(media): degrade recoverable image errors in non-strict mode 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. --- astrbot/core/utils/media_utils.py | 9 ++++++--- tests/test_media_utils.py | 24 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/astrbot/core/utils/media_utils.py b/astrbot/core/utils/media_utils.py index 687ece38be..9ee7cb1a92 100644 --- a/astrbot/core/utils/media_utils.py +++ b/astrbot/core/utils/media_utils.py @@ -865,9 +865,12 @@ async def to_base64_data( # assembly relies on to skip bad image refs. try: resolved = await self._resolve_path(target_format=target_format) - except (OSError, ValueError) as exc: - # ValueError covers non-regular sources, which is_recoverable_image_error - # already treats as skippable. + except Exception as exc: # noqa: BLE001 + # Declared-recoverable image errors are not limited to OSError + # and ValueError: DownloadFileHTTPError and aiohttp ClientError + # are RuntimeError subclasses, and image sniffing can raise + # SyntaxError, EOFError or struct.error. Anything outside that + # set still propagates, strict or not. if strict or not is_recoverable_image_error(exc): raise return None diff --git a/tests/test_media_utils.py b/tests/test_media_utils.py index bcfba8ac9a..a4a0244134 100644 --- a/tests/test_media_utils.py +++ b/tests/test_media_utils.py @@ -15,6 +15,7 @@ from astrbot.core.file_token_service import FileTokenService from astrbot.core.message.components import File, Image, Record, Video from astrbot.core.provider.entities import ProviderRequest +from astrbot.core.utils.io import DownloadFileHTTPError from astrbot.core.utils.path_util import path_Mapping from astrbot.core.utils.tencent_record_helper import wav_to_tencent_silk @@ -647,6 +648,29 @@ async def fail_download(url: str, target_path: str) -> None: assert not list(tmp_path.iterdir()) +@pytest.mark.asyncio +async def test_image_base64_data_degrades_for_download_http_error_when_not_strict( + tmp_path, monkeypatch +): + monkeypatch.setattr(media_utils, "get_astrbot_temp_path", lambda: str(tmp_path)) + url = "https://example.com/expired.png" + + async def fail_download(media_ref: str, target_path: str) -> None: + # DownloadFileHTTPError subclasses RuntimeError, not OSError. + Path(target_path).write_bytes(b"partial") + raise DownloadFileHTTPError( + f"Failed to download file from {media_ref}. HTTP status code: 400" + ) + + monkeypatch.setattr(media_utils, "download_file", fail_download) + + assert await media_utils.resolve_image_ref_to_base64_data(url) is None + assert not list(tmp_path.iterdir()) + + with pytest.raises(DownloadFileHTTPError): + await media_utils.resolve_image_ref_to_base64_data(url, strict=True) + + @pytest.mark.asyncio @pytest.mark.parametrize("media_type", ["image", "audio", "file"]) async def test_media_resolver_rejects_directory_ref(tmp_path, media_type): From d60920e0181f578cac50072cdb80ad95519cb48a Mon Sep 17 00:00:00 2001 From: JosephTian876 <204833675+JosephTian876@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:08:20 +0800 Subject: [PATCH 2/5] fix(gemini): skip undownloadable history images instead of failing 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. --- .../core/provider/sources/gemini_source.py | 19 ++-- tests/test_gemini_source.py | 88 ++++++++++++++++++ tests/test_tool_loop_agent_runner.py | 90 +++++++++++++++++++ 3 files changed, 192 insertions(+), 5 deletions(-) diff --git a/astrbot/core/provider/sources/gemini_source.py b/astrbot/core/provider/sources/gemini_source.py index ee4ed09249..7f7e761a03 100644 --- a/astrbot/core/provider/sources/gemini_source.py +++ b/astrbot/core/provider/sources/gemini_source.py @@ -417,17 +417,20 @@ def create_text_part(text: str) -> types.Part: logger.warning("Text content is empty, added a space as placeholder.") return types.Part.from_text(text=content_a) - async def process_image_url(image_url_dict: dict) -> types.Part: + async def process_image_url(image_url_dict: dict) -> types.Part | None: url = image_url_dict["url"] image_data = await resolve_media_ref_to_base64_data( url, media_type="image", - strict=True, ) if image_data is None: - raise ValueError( - f"Failed to resolve Gemini history image: {describe_media_ref(url)}" + # A history image that cannot be materialized is skipped so one + # stale reference does not fail the whole replayed turn. + logger.warning( + "Skipping Gemini history image that could not be resolved: %s", + describe_media_ref(url), ) + return None return types.Part.from_bytes( data=base64.b64decode(image_data.base64_data), mime_type=image_data.mime_type, @@ -471,9 +474,15 @@ def append_or_extend( if item["type"] == "text": parts.append(types.Part.from_text(text=item["text"] or " ")) elif item["type"] == "image_url": - parts.append(await process_image_url(item["image_url"])) + image_part = await process_image_url(item["image_url"]) + if image_part is not None: + parts.append(image_part) elif item["type"] == "audio_url": parts.append(await process_audio_url(item["audio_url"])) + if not parts: + # An image-only turn whose image was skipped still needs + # a non-empty UserContent for a valid request. + parts = [types.Part.from_text(text=" ")] else: parts = [create_text_part(content)] append_or_extend(gemini_contents, parts, types.UserContent) diff --git a/tests/test_gemini_source.py b/tests/test_gemini_source.py index c39aa7cace..d5e8fd00e6 100644 --- a/tests/test_gemini_source.py +++ b/tests/test_gemini_source.py @@ -1,3 +1,4 @@ +import logging from types import SimpleNamespace import httpx @@ -10,6 +11,8 @@ from astrbot.core.exceptions import EmptyModelOutputError from astrbot.core.provider.entities import LLMResponse from astrbot.core.provider.sources.gemini_source import ProviderGoogleGenAI +from astrbot.core.utils import media_utils +from astrbot.core.utils.io import DownloadFileHTTPError @pytest.mark.asyncio @@ -183,6 +186,91 @@ async def fake_resolve_media_ref(media_ref, *, media_type, strict): assert contents[-1].parts[-1].text == "Reply in text." +@pytest.mark.asyncio +async def test_gemini_prepare_conversation_skips_history_image_download_failure( + tmp_path, monkeypatch, caplog +): + """One undownloadable history image must not fail the whole replayed turn.""" + url = "https://example.com/expired-history.png" + + monkeypatch.setattr(media_utils, "get_astrbot_temp_path", lambda: str(tmp_path)) + + async def fail_download(media_ref: str, target_path: str) -> None: + raise DownloadFileHTTPError( + f"Failed to download file from {media_ref}. HTTP status code: 404" + ) + + monkeypatch.setattr(media_utils, "download_file", fail_download) + + provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI) + with caplog.at_level(logging.WARNING): + contents = await provider._prepare_conversation( + { + "messages": [ + {"role": "user", "content": "first user turn"}, + {"role": "assistant", "content": "assistant turn"}, + { + "role": "user", + "content": [ + {"type": "text", "text": "what is in this image?"}, + { + "type": "image_url", + "image_url": {"url": url}, + }, + ], + }, + ] + } + ) + + assert [type(content) for content in contents] == [ + types.UserContent, + types.ModelContent, + types.UserContent, + ] + assert contents[-1].parts is not None + assert len(contents[-1].parts) == 1 + assert contents[-1].parts[0].text == "what is in this image?" + assert "expired-history.png" in caplog.text + + +@pytest.mark.asyncio +async def test_gemini_prepare_conversation_keeps_non_empty_user_turn_for_failed_image( + tmp_path, monkeypatch +): + """A turn made only of an undownloadable image must still be valid content.""" + monkeypatch.setattr(media_utils, "get_astrbot_temp_path", lambda: str(tmp_path)) + + async def fail_download(media_ref: str, target_path: str) -> None: + raise DownloadFileHTTPError( + f"Failed to download file from {media_ref}. HTTP status code: 404" + ) + + monkeypatch.setattr(media_utils, "download_file", fail_download) + + provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI) + contents = await provider._prepare_conversation( + { + "messages": [ + { + "role": "user", + "content": [ + { + "type": "image_url", + "image_url": {"url": "https://example.com/expired.png"}, + } + ], + } + ] + } + ) + + assert len(contents) == 1 + assert isinstance(contents[0], types.UserContent) + assert contents[0].parts + assert contents[0].parts[0].text == " " + + def test_gemini_empty_output_raises_empty_model_output_error(): llm_response = LLMResponse(role="assistant") diff --git a/tests/test_tool_loop_agent_runner.py b/tests/test_tool_loop_agent_runner.py index 5665a254d8..b2ac207b56 100644 --- a/tests/test_tool_loop_agent_runner.py +++ b/tests/test_tool_loop_agent_runner.py @@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMock import pytest +from google.genai import types # 将项目根目录添加到 sys.path sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) @@ -24,6 +25,10 @@ from astrbot.core.message.message_event_result import MessageChain from astrbot.core.provider.entities import LLMResponse, ProviderRequest, TokenUsage from astrbot.core.provider.provider import Provider +from astrbot.core.provider.sources import gemini_source +from astrbot.core.provider.sources.gemini_source import ProviderGoogleGenAI +from astrbot.core.utils import media_utils +from astrbot.core.utils.io import DownloadFileHTTPError async def next_event(iterator, kind): @@ -1304,6 +1309,91 @@ async def test_fallback_provider_used_when_primary_returns_err( assert fallback_provider.call_count == 1 +@pytest.mark.asyncio +async def test_degraded_history_image_does_not_switch_to_fallback_provider( + runner, mock_tool_executor, mock_hooks, tmp_path, monkeypatch +): + """A skipped history image must not be classified as a provider failure.""" + url = "https://example.com/expired-history.png" + generate_calls: list[dict] = [] + + monkeypatch.setattr(media_utils, "get_astrbot_temp_path", lambda: str(tmp_path)) + + async def fail_download(media_ref: str, target_path: str) -> None: + raise DownloadFileHTTPError( + f"Failed to download file from {media_ref}. HTTP status code: 404" + ) + + async def generate_content(**kwargs): + generate_calls.append(kwargs) + return SimpleNamespace( + candidates=[ + SimpleNamespace( + content=SimpleNamespace( + parts=[types.Part.from_text(text="primary answer")] + ), + finish_reason=types.FinishReason.STOP, + ) + ], + response_id="resp-primary", + usage_metadata=None, + ) + + async def passthrough_retry(_provider_name, request_factory, max_attempts=None): + return await request_factory() + + monkeypatch.setattr(media_utils, "download_file", fail_download) + monkeypatch.setattr(gemini_source, "retry_provider_request", passthrough_retry) + + primary_provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI) + primary_provider.provider_config = {"id": "gemini-primary", "model": "gemini-stub"} + primary_provider.provider_settings = {} + primary_provider.model_name = "gemini-stub" + primary_provider.safety_settings = [] + primary_provider.api_keys = ["stub-key"] + primary_provider.client = SimpleNamespace( + models=SimpleNamespace(generate_content=generate_content) + ) + fallback_provider = MockProvider() + fallback_provider.should_call_tools = False + + request = ProviderRequest( + prompt=None, + func_tool=None, + contexts=[ + {"role": "user", "content": "first user turn"}, + {"role": "assistant", "content": "assistant turn"}, + { + "role": "user", + "content": [ + {"type": "text", "text": "what is in this image?"}, + {"type": "image_url", "image_url": {"url": url}}, + ], + }, + ], + ) + + await runner.reset( + provider=primary_provider, + request=request, + run_context=ContextWrapper(context=None), + tool_executor=mock_tool_executor, + agent_hooks=mock_hooks, + streaming=False, + fallback_providers=[fallback_provider], + ) + + async for _ in runner.step_until_done(5): + pass + + final_resp = runner.get_final_llm_resp() + assert final_resp is not None + assert final_resp.role == "assistant" + assert final_resp.completion_text == "primary answer" + assert len(generate_calls) == 1 + assert fallback_provider.call_count == 0 + + @pytest.mark.asyncio async def test_empty_output_is_retried_before_succeeding( runner, provider_request, mock_tool_executor, mock_hooks, monkeypatch From 1cc8c2e1bb458d8fc779472ffd94a1ef49aae3fd Mon Sep 17 00:00:00 2001 From: JosephTian876 <204833675+JosephTian876@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:41:08 +0800 Subject: [PATCH 3/5] test(media): pin recoverable image error boundaries 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). --- tests/test_media_utils.py | 61 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/tests/test_media_utils.py b/tests/test_media_utils.py index a4a0244134..1ed8d44460 100644 --- a/tests/test_media_utils.py +++ b/tests/test_media_utils.py @@ -1,4 +1,5 @@ import base64 +import errno import math import os import struct @@ -10,6 +11,7 @@ from urllib.parse import quote import pytest +from aiohttp import ClientError import astrbot.core.utils.media_utils as media_utils from astrbot.core.file_token_service import FileTokenService @@ -671,6 +673,65 @@ async def fail_download(media_ref: str, target_path: str) -> None: await media_utils.resolve_image_ref_to_base64_data(url, strict=True) +@pytest.mark.asyncio +@pytest.mark.parametrize( + "error", + [ + pytest.param(ClientError("connection reset"), id="client-error"), + pytest.param(SyntaxError("invalid image header"), id="syntax-error"), + pytest.param(EOFError("truncated image"), id="eof-error"), + pytest.param(struct.error("unpack requires a buffer"), id="struct-error"), + ], +) +async def test_image_base64_data_degrades_declared_recoverable_errors( + tmp_path, monkeypatch, error +): + """Declared-recoverable errors are not only DownloadFileHTTPError.""" + monkeypatch.setattr(media_utils, "get_astrbot_temp_path", lambda: str(tmp_path)) + + async def fail_download(media_ref: str, target_path: str) -> None: + Path(target_path).write_bytes(b"partial") + raise error + + monkeypatch.setattr(media_utils, "download_file", fail_download) + + assert ( + await media_utils.resolve_image_ref_to_base64_data( + "https://example.com/expired.png" + ) + is None + ) + assert not list(tmp_path.iterdir()) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "error", + [ + pytest.param( + OSError(errno.ENOMEM, "Cannot allocate memory"), id="out-of-memory" + ), + pytest.param(RuntimeError("unexpected failure"), id="runtime-error"), + ], +) +async def test_image_base64_data_propagates_undeclared_errors( + tmp_path, monkeypatch, error +): + """Non-strict mode must not swallow errors outside the declared set.""" + monkeypatch.setattr(media_utils, "get_astrbot_temp_path", lambda: str(tmp_path)) + + async def fail_download(media_ref: str, target_path: str) -> None: + raise error + + monkeypatch.setattr(media_utils, "download_file", fail_download) + + with pytest.raises(type(error)) as excinfo: + await media_utils.resolve_image_ref_to_base64_data( + "https://example.com/expired.png" + ) + assert excinfo.value is error + + @pytest.mark.asyncio @pytest.mark.parametrize("media_type", ["image", "audio", "file"]) async def test_media_resolver_rejects_directory_ref(tmp_path, media_type): From 3fc6c30d88f2d8fd43e36b50b483c3723633d085 Mon Sep 17 00:00:00 2001 From: JosephTian876 <204833675+JosephTian876@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:41:08 +0800 Subject: [PATCH 4/5] fix(gemini): log the cause when skipping an unavailable payload image 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. --- .../core/provider/sources/gemini_source.py | 23 ++++++++++++------- tests/test_gemini_source.py | 7 +++++- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/astrbot/core/provider/sources/gemini_source.py b/astrbot/core/provider/sources/gemini_source.py index 7f7e761a03..442f280c28 100644 --- a/astrbot/core/provider/sources/gemini_source.py +++ b/astrbot/core/provider/sources/gemini_source.py @@ -22,6 +22,7 @@ from astrbot.core.provider.func_tool_manager import ToolSet from astrbot.core.utils.media_utils import ( describe_media_ref, + is_recoverable_image_error, resolve_media_ref_to_base64_data, ) from astrbot.core.utils.network_utils import is_connection_error, log_connection_failure @@ -419,18 +420,24 @@ def create_text_part(text: str) -> types.Part: async def process_image_url(image_url_dict: dict) -> types.Part | None: url = image_url_dict["url"] - image_data = await resolve_media_ref_to_base64_data( - url, - media_type="image", - ) - if image_data is None: - # A history image that cannot be materialized is skipped so one - # stale reference does not fail the whole replayed turn. + try: + image_data = await resolve_media_ref_to_base64_data( + url, + media_type="image", + strict=True, + ) + except Exception as exc: + if not is_recoverable_image_error(exc): + raise + # Strict resolution exposes the cause. A declared-recoverable + # image error drops only this image, not the whole request. logger.warning( - "Skipping Gemini history image that could not be resolved: %s", + "Conversation payload image is unavailable (%s): %s", + type(exc).__name__, describe_media_ref(url), ) return None + assert image_data is not None, "strict image resolution returned no data" return types.Part.from_bytes( data=base64.b64decode(image_data.base64_data), mime_type=image_data.mime_type, diff --git a/tests/test_gemini_source.py b/tests/test_gemini_source.py index d5e8fd00e6..647d23ec31 100644 --- a/tests/test_gemini_source.py +++ b/tests/test_gemini_source.py @@ -190,7 +190,11 @@ async def fake_resolve_media_ref(media_ref, *, media_type, strict): async def test_gemini_prepare_conversation_skips_history_image_download_failure( tmp_path, monkeypatch, caplog ): - """One undownloadable history image must not fail the whole replayed turn.""" + """One undownloadable image must not fail the whole replayed conversation. + + The warning must also carry the cause, so the log distinguishes a failed + download from a corrupt payload. + """ url = "https://example.com/expired-history.png" monkeypatch.setattr(media_utils, "get_astrbot_temp_path", lambda: str(tmp_path)) @@ -232,6 +236,7 @@ async def fail_download(media_ref: str, target_path: str) -> None: assert len(contents[-1].parts) == 1 assert contents[-1].parts[0].text == "what is in this image?" assert "expired-history.png" in caplog.text + assert "DownloadFileHTTPError" in caplog.text @pytest.mark.asyncio From 6cfb39cdb5691c4fabdde778bf998ce93b936019 Mon Sep 17 00:00:00 2001 From: JosephTian876 <204833675+JosephTian876@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:27:50 +0800 Subject: [PATCH 5/5] fix(gemini): skip payload images that resolve to no data 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. --- .../core/provider/sources/gemini_source.py | 10 ++++- tests/test_gemini_source.py | 42 +++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/astrbot/core/provider/sources/gemini_source.py b/astrbot/core/provider/sources/gemini_source.py index 442f280c28..c63e36e628 100644 --- a/astrbot/core/provider/sources/gemini_source.py +++ b/astrbot/core/provider/sources/gemini_source.py @@ -437,7 +437,15 @@ async def process_image_url(image_url_dict: dict) -> types.Part | None: describe_media_ref(url), ) return None - assert image_data is not None, "strict image resolution returned no data" + if image_data is None: + # Strict resolution raises instead of returning None today, so + # a future contract change must still skip the image rather + # than fail when the data is dereferenced below. + logger.warning( + "Conversation payload image is unavailable (no data): %s", + describe_media_ref(url), + ) + return None return types.Part.from_bytes( data=base64.b64decode(image_data.base64_data), mime_type=image_data.mime_type, diff --git a/tests/test_gemini_source.py b/tests/test_gemini_source.py index 647d23ec31..6065fee564 100644 --- a/tests/test_gemini_source.py +++ b/tests/test_gemini_source.py @@ -186,6 +186,48 @@ async def fake_resolve_media_ref(media_ref, *, media_type, strict): assert contents[-1].parts[-1].text == "Reply in text." +@pytest.mark.asyncio +async def test_gemini_prepare_conversation_skips_image_resolved_to_no_data( + monkeypatch, caplog +): + """A None result must skip the image instead of being dereferenced. + + Strict resolution raises rather than returning None today; this pins the + skip so a future contract change cannot turn it into an AttributeError. + """ + + async def resolve_to_none(*args, **kwargs) -> None: + return None + + monkeypatch.setattr( + gemini_source, "resolve_media_ref_to_base64_data", resolve_to_none + ) + + provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI) + with caplog.at_level(logging.WARNING): + contents = await provider._prepare_conversation( + { + "messages": [ + { + "role": "user", + "content": [ + {"type": "text", "text": "what is in this image?"}, + { + "type": "image_url", + "image_url": {"url": "https://example.com/no-data.png"}, + }, + ], + } + ] + } + ) + + assert len(contents) == 1 + assert contents[0].parts is not None + assert [part.text for part in contents[0].parts] == ["what is in this image?"] + assert "no-data.png" in caplog.text + + @pytest.mark.asyncio async def test_gemini_prepare_conversation_skips_history_image_download_failure( tmp_path, monkeypatch, caplog