Skip to content
Merged
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
47 changes: 38 additions & 9 deletions astrbot/core/provider/sources/gemini_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,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 @@ -441,17 +442,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 resolve_image_url(image_url_dict: dict) -> tuple[bytes, str]:
async def resolve_image_url(image_url_dict: dict) -> tuple[bytes, str] | 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 base64.b64decode(image_data.base64_data), image_data.mime_type

async def process_audio_url(audio_url_dict: dict) -> types.Part:
Expand Down Expand Up @@ -501,7 +519,10 @@ def append_or_extend(
parts.append(types.Part.from_text(text=item["text"] or " "))
elif item["type"] == "image_url":
image_url = item["image_url"]
data, mime_type = await resolve_image_url(image_url)
resolved_image = await resolve_image_url(image_url)
if resolved_image is None:
continue
data, mime_type = resolved_image
response = tool_responses.get(
image_url.get("tool_result_index")
)
Expand All @@ -525,6 +546,14 @@ def append_or_extend(
)
elif item["type"] == "audio_url":
parts.append(await process_audio_url(item["audio_url"]))
if not parts and not (
gemini_contents
and isinstance(gemini_contents[-1], types.UserContent)
and gemini_contents[-1].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 @@ -960,9 +960,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
25 changes: 25 additions & 0 deletions tests/test_gemini_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from astrbot.core.exceptions import EmptyModelOutputError
from astrbot.core.provider.entities import LLMResponse, ProviderRequest
from astrbot.core.provider.sources.gemini_source import ProviderGoogleGenAI
from astrbot.core.utils.io import DownloadFileHTTPError


@pytest.mark.asyncio
Expand Down Expand Up @@ -595,3 +596,27 @@ async def stream():
for content in sent_contents
for part in content.parts
)


@pytest.mark.asyncio
async def test_gemini_prepare_conversation_skips_undownloadable_images(monkeypatch):
err = DownloadFileHTTPError("HTTP 400")
resolver = AsyncMock(side_effect=[err, None, RuntimeError("boom")])
monkeypatch.setattr(gemini_source, "resolve_media_ref_to_base64_data", resolver)
provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI)
img = {"type": "image_url", "image_url": {"url": "https://example.com/a.jpg"}}
contents = await provider._prepare_conversation(
{
"messages": [
{"role": "user", "content": [{"type": "text", "text": "keep"}, img]},
{"role": "assistant", "content": "ok"},
{"role": "user", "content": [img]},
]
}
)
assert [p.text for p in contents[0].parts or []] == ["keep"]
assert [p.text for p in contents[2].parts or []] == [" "]
with pytest.raises(RuntimeError, match="boom"):
await provider._prepare_conversation(
{"messages": [{"role": "user", "content": [img]}]}
)
17 changes: 17 additions & 0 deletions tests/test_media_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from io import BytesIO
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock
from urllib.parse import quote

import pytest
Expand Down Expand Up @@ -1265,3 +1266,19 @@ def test_convert_image_bytes_reencodes_large_in_range_input(tmp_path, monkeypatc
assert result is not source
assert result[:2] == b"\xff\xd8"
assert len(result) < media_utils.MODEL_IMAGE_MAX_BYTES


@pytest.mark.asyncio
async def test_image_base64_data_degrades_download_http_error(tmp_path, monkeypatch):
monkeypatch.setattr(media_utils, "get_astrbot_temp_path", lambda: str(tmp_path))
resolve = media_utils.resolve_media_ref_to_base64_data
url = "https://example.com/expired.jpg"
err = media_utils.DownloadFileHTTPError("HTTP status code: 400")
monkeypatch.setattr(media_utils, "download_file", AsyncMock(side_effect=err))
assert await resolve(url, media_type="image") is None
with pytest.raises(media_utils.DownloadFileHTTPError):
await resolve(url, media_type="image", strict=True)
boom = RuntimeError("unexpected")
monkeypatch.setattr(media_utils, "download_file", AsyncMock(side_effect=boom))
with pytest.raises(RuntimeError, match="unexpected"):
await resolve(url, media_type="image")
Loading