Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(imagegen): retry with image-only modalities when both are unsupported (#1353)

evan188199-techc8e33e757e90
diff --git a/deeptutor/services/imagegen/adapters/chat_completions.py b/deeptutor/services/imagegen/adapters/chat_completions.py
index 79b9ba66f..aff563bae 100644
--- a/deeptutor/services/imagegen/adapters/chat_completions.py
+++ b/deeptutor/services/imagegen/adapters/chat_completions.py
@@ -49,13 +49,24 @@ class ChatCompletionsImagegenAdapter(BaseImagegenAdapter):
payload: dict[str, Any] = {
"model": config.model,
"messages": [{"role": "user", "content": prompt}],
- "modalities": ["image", "text"],
}
logger.debug("imagegen(chat) url=%s model=%s", url, config.model)
try:
async with httpx.AsyncClient(timeout=config.request_timeout) as client:
- resp = await client.post(url, headers=headers, json=payload)
+ modalities_attempts: list[list[str]] = [["image", "text"], ["image"]]
+ resp: httpx.Response | None = None
+ last_404: httpx.Response | None = None
+ for modalities in modalities_attempts:
+ attempt_payload = {**payload, "modalities": modalities}
+ resp = await client.post(url, headers=headers, json=attempt_payload)
+ if resp.status_code == 404 and "modalit" in resp.text.lower():
+ last_404 = resp
+ continue
+ break
+ if resp is None:
+ resp = last_404
+ assert resp is not None
raise_for_provider(resp, "Image generation")
images = [
await self._materialize(client, src) for src in self._extract_sources(resp)
diff --git a/tests/services/imagegen/__init__.py b/tests/services/imagegen/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/services/imagegen/test_chat_completions_modalities.py b/tests/services/imagegen/test_chat_completions_modalities.py
new file mode 100644
index 000000000..fcdcdaa85
--- /dev/null
+++ b/tests/services/imagegen/test_chat_completions_modalities.py
@@ -0,0 +1,84 @@
+"""Tests for OpenRouter imagegen modality fallback."""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import httpx
+import pytest
+
+from deeptutor.services.imagegen.adapters.chat_completions import (
+ ChatCompletionsImagegenAdapter,
+)
+from deeptutor.services.imagegen.config import ImagegenConfig
+
+
+def _config() -> ImagegenConfig:
+ return ImagegenConfig(
+ provider_name="openrouter",
+ base_url="https://openrouter.ai/api/v1",
+ api_key="test-key",
+ model="bytedance-seed/seedream-5-0-lite",
+ adapter="chat_completions",
+ )
+
+
+def _resp(status: int, body: dict) -> httpx.Response:
+ return httpx.Response(status_code=status, json=body, request=httpx.Request("POST", "https://x"))
+
+
+class TestModalitiesFallback:
+ @pytest.mark.asyncio
+ async def test_retries_with_image_only_on_modality_404(self):
+ data_uri = "data:image/png;base64,aGVsbG8="
+ success_body = {
+ "choices": [
+ {"message": {"images": [{"type": "image_url", "image_url": {"url": data_uri}}]}}
+ ]
+ }
+ responses = [
+ _resp(
+ 404,
+ {
+ "error": {
+ "message": "No endpoints found that support the requested output modalities: image, text"
+ }
+ },
+ ),
+ _resp(200, success_body),
+ ]
+ adapter = ChatCompletionsImagegenAdapter()
+
+ calls: list[dict] = []
+
+ async def fake_post(url, *, headers, json):
+ calls.append(json)
+ return responses[len(calls) - 1]
+
+ with patch.object(httpx.AsyncClient, "post", side_effect=fake_post):
+ images = await adapter.generate("draw a cat", _config())
+
+ assert len(images) == 1
+ assert calls[0]["modalities"] == ["image", "text"]
+ assert calls[1]["modalities"] == ["image"]
+
+ @pytest.mark.asyncio
+ async def test_success_with_both_modalities_no_retry(self):
+ data_uri = "data:image/png;base64,aGVsbG8="
+ success_body = {
+ "choices": [
+ {"message": {"images": [{"type": "image_url", "image_url": {"url": data_uri}}]}}
+ ]
+ }
+ adapter = ChatCompletionsImagegenAdapter()
+
+ calls: list[dict] = []
+
+ async def fake_post(url, *, headers, json):
+ calls.append(json)
+ return _resp(200, success_body)
+
+ with patch.object(httpx.AsyncClient, "post", side_effect=fake_post):
+ images = await adapter.generate("draw a cat", _config())
+
+ assert len(images) == 1
+ assert len(calls) == 1
+ assert calls[0]["modalities"] == ["image", "text"]