Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 33 additions & 9 deletions astrbot/core/provider/sources/gemini_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -417,17 +418,34 @@ 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,
)
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(
"Conversation payload image is unavailable (%s): %s",
type(exc).__name__,
describe_media_ref(url),
)
return None
if image_data is None:
raise ValueError(
f"Failed to resolve Gemini history image: {describe_media_ref(url)}"
# 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,
Expand Down Expand Up @@ -471,9 +489,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)
Expand Down
9 changes: 6 additions & 3 deletions astrbot/core/utils/media_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
135 changes: 135 additions & 0 deletions tests/test_gemini_source.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
from types import SimpleNamespace

import httpx
Expand All @@ -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
Expand Down Expand Up @@ -183,6 +186,138 @@ 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
):
"""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))

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
assert "DownloadFileHTTPError" 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")

Expand Down
85 changes: 85 additions & 0 deletions tests/test_media_utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import base64
import errno
import math
import os
import struct
Expand All @@ -10,11 +11,13 @@
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
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

Expand Down Expand Up @@ -647,6 +650,88 @@ 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(
"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):
Expand Down
Loading
Loading