fix(models): route image input by preset capability (#6651)

* fix(providers): preserve images across retries and recovery

Remove destructive text-only retries and validate tool image media at the boundary. Keep image identity across native transport preparation and compaction, and stop incomplete fallback or continuation without replaying tools.

Resolves NAN-442

* fix(models): route image input by preset capability

Replace the expanded image recovery and tool-format changes with an explicit supportsImages preset setting, capability-aware fallback selection, and an Image input switch in model settings. Keep original messages on retry and fail on actual non-transient image errors.

* docs(models): introduce image input settings positively

* test(agent): align image request fixtures with preset routing

Cover successful image requests and direct validation errors when attributing model responses. Configure the image-capability check for the existing text-only provider mocks so governance and override-reuse tests exercise their scripted primary/fallback paths.
This commit is contained in:
chengyongru authored and GitHub committed 2026-11-13 18:16:58 +08:00
1 parent 6a24b17629
commit 3f65a8f86c
36 files changed
+483 -444

No files matched your search

+5 -1
View File
@@ -134,6 +134,7 @@ class InlineFallbackConfig(RequestOverrides):
model: str
provider: str
supports_images: bool = True
max_tokens: int | None = None
context_window_tokens: int | None = None
temperature: float | None = None
@@ -149,6 +150,7 @@ class ModelPresetConfig(RequestOverrides):
model: str
provider: str = "auto"
supports_images: bool = True
max_tokens: int = 8192
context_window_tokens: int = 200_000
temperature: float = 0.1
@@ -172,6 +174,7 @@ class AgentDefaults(Base):
provider: str = (
"auto" # Provider name (e.g. "anthropic", "openrouter") or "auto" for auto-detection
)
supports_images: bool = True
max_tokens: int = 8192
context_window_tokens: int = 200_000
temperature: float = 0.1
@@ -552,7 +555,8 @@ class Config(BaseSettings):
"""Return the implicit `default` preset from agents.defaults fields."""
d = self.agents.defaults
return ModelPresetConfig(
model=d.model, provider=d.provider, max_tokens=d.max_tokens,
model=d.model, provider=d.provider, supports_images=d.supports_images,
max_tokens=d.max_tokens,
context_window_tokens=d.context_window_tokens,
temperature=d.temperature, reasoning_effort=d.reasoning_effort, api=d.api,
)
+19 -103
View File
@@ -467,6 +467,7 @@ class LLMProvider(ABC):
self.api_base = api_base
self.provider_name = provider_name
self.generation: GenerationSettings = GenerationSettings()
self.supports_images = True
self._llm_call_observer: LLMCallObserver | None = None
self._usage_estimation_slots = asyncio.Semaphore(2)
@@ -1011,31 +1012,6 @@ class LLMProvider(ABC):
return merged
@staticmethod
def _strip_image_content(messages: list[dict[str, Any]]) -> list[dict[str, Any]] | None:
"""Replace image_url blocks with text placeholder. Returns None if no images found."""
found = False
result: list[dict[str, Any]] = []
for msg in messages:
content = msg.get("content")
if isinstance(content, list):
new_content: list[Any] = []
for raw_block in cast(list[object], content):
block = cast(dict[str, Any], raw_block) if isinstance(raw_block, dict) else None
if block is not None and block.get("type") == "image_url":
placeholder = (
"[Image not delivered to model — "
"do not describe or reference it]"
)
new_content.append({"type": "text", "text": placeholder})
found = True
else:
new_content.append(raw_block)
result.append({**msg, "content": new_content})
else:
result.append(msg)
return result if found else None
@staticmethod
def _contains_image_content(value: object) -> bool:
"""Return whether a JSON-like provider payload contains an input image."""
@@ -1052,27 +1028,22 @@ class LLMProvider(ABC):
return False
@staticmethod
def _strip_image_content_inplace(messages: list[dict[str, Any]]) -> bool:
"""Replace image_url blocks with text placeholder *in-place*.
def _request_contains_images(messages: list[dict[str, Any]], context: ProviderCallContext | None = None) -> bool:
state = context.current_conversation_state if context is not None else None
return LLMProvider._contains_image_content([
messages, state.payload if state else None, state.pending_messages if state else None,
])
Mutates the content lists of the original message dicts so that
callers holding references to those dicts also see the stripped
version.
"""
found = False
for msg in messages:
content = msg.get("content")
if isinstance(content, list):
for i, raw_block in enumerate(cast(list[object], content)):
block = cast(dict[str, Any], raw_block) if isinstance(raw_block, dict) else None
if block is not None and block.get("type") == "image_url":
placeholder = (
"[Image not delivered to model — "
"do not describe or reference it]"
)
content[i] = {"type": "text", "text": placeholder}
found = True
return found
def _image_input_error(
self, messages: list[dict[str, Any]], context: ProviderCallContext | None = None,
) -> LLMResponse | None:
if self.supports_images or not self._request_contains_images(messages, context):
return None
return LLMResponse(
content="This model preset does not support image input. Select an image-capable preset in model settings.",
finish_reason="error", error_kind="invalid_request", error_code="unsupported_image",
error_should_retry=False,
)
async def _safe_chat(self, **kwargs: Any) -> LLMResponse:
started_at_ms = time.time_ns() // 1_000_000
@@ -1316,7 +1287,6 @@ class LLMProvider(ABC):
)
return await self._run_chat_with_retry(
kw,
messages,
stream=True,
retry_mode=retry_mode,
on_retry_wait=on_retry_wait,
@@ -1369,7 +1339,6 @@ class LLMProvider(ABC):
)
return await self._run_chat_with_retry(
kw,
messages,
stream=False,
retry_mode=retry_mode,
on_retry_wait=on_retry_wait,
@@ -1404,7 +1373,6 @@ class LLMProvider(ABC):
async def _run_chat_with_retry(
self,
kw: dict[str, Any],
original_messages: list[dict[str, Any]],
*,
stream: bool,
retry_mode: str,
@@ -1414,6 +1382,8 @@ class LLMProvider(ABC):
should_retry_guard: Callable[[], bool] | None = None,
on_stream_recover: Callable[[], Awaitable[None]] | None = None,
) -> LLMResponse:
if error := self._image_input_error(kw["messages"], kw.get("provider_context")):
return error
call = self._safe_chat_stream if stream else self._safe_chat
async def attributed_call(**kwargs: Any) -> LLMResponse:
@@ -1464,7 +1434,6 @@ class LLMProvider(ABC):
return await self._run_with_retry(
attributed_call,
kw,
original_messages,
retry_mode=retry_mode,
on_retry_wait=on_retry_wait,
on_retry_exhausted=on_retry_exhausted,
@@ -1617,7 +1586,6 @@ class LLMProvider(ABC):
self,
call: Callable[..., Awaitable[LLMResponse]],
kw: dict[str, Any],
original_messages: list[dict[str, Any]],
*,
retry_mode: str,
on_retry_wait: RetryEventCallback | None,
@@ -1681,13 +1649,7 @@ class LLMProvider(ABC):
identical_error_count = 1 if error_key else 0
if not self.is_transient_response(response):
response = await self._retry_without_images(
call, kw, original_messages, response,
)
await _finish_retry_status(
"recovered" if response.finish_reason != "error" else "cleared",
response,
)
await _finish_retry_status("cleared", response)
return response
if (
@@ -1747,52 +1709,6 @@ class LLMProvider(ABC):
await _finish_retry_status("exhausted", response)
return response
async def _retry_without_images(
self,
call: Callable[..., Awaitable[LLMResponse]],
kw: dict[str, Any],
original_messages: list[dict[str, Any]],
response: LLMResponse,
) -> LLMResponse:
# Removing the user's images cannot repair account access.
if (
(response.error_kind or "").lower() in {"authentication", "oauth_auth_required"}
or response.error_status_code in {401, 403}
or self.is_arrearage_response(response)
):
return response
provider_context = kw.get("provider_context")
if (
isinstance(provider_context, ProviderCallContext)
and provider_context.compaction_input_budget is not None
):
# Stateless image repair cannot satisfy required native compaction.
return response
stripped = self._strip_image_content(kw["messages"])
stripped_context: ProviderCallContext | None = None
if isinstance(provider_context, ProviderCallContext):
state = provider_context.conversation_state
if state is not None and (
stripped is not None
or self._strip_image_content(state.pending_messages) is not None
or self._contains_image_content(state.payload)
):
# Native payloads may retain images: rebuild from the public transcript.
stripped_context = replace(provider_context, conversation_state=None)
if stripped is None and stripped_context is None:
return response
logger.warning("Non-transient LLM error with image content, retrying without images")
retry_kw = dict(kw)
if stripped is not None:
retry_kw["messages"] = stripped
if stripped_context is not None:
retry_kw["provider_context"] = stripped_context
result = await call(**retry_kw)
# Keep later iterations from repeating the same image repair.
if result.finish_reason != "error":
self._strip_image_content_inplace(original_messages)
return result
async def aclose(self) -> None:
"""Close provider-owned transports after their active requests have stopped."""
+3
View File
@@ -153,6 +153,7 @@ def _make_provider_core(
)
provider.generation = preset.to_generation_settings()
provider.supports_images = preset.supports_images
return provider
@@ -163,6 +164,7 @@ def _inline_fallback_preset(
return ModelPresetConfig(
model=fallback.model,
provider=fallback.provider,
supports_images=fallback.supports_images,
max_tokens=fallback.max_tokens if fallback.max_tokens is not None else primary.max_tokens,
context_window_tokens=(
fallback.context_window_tokens
@@ -247,6 +249,7 @@ def _preset_provider_signature(
return (
preset.model,
preset.provider,
preset.supports_images,
provider_name,
config.get_api_key(preset.model, preset=preset),
config.get_api_base(preset.model, preset=preset),
+11 -6
View File
@@ -223,7 +223,6 @@ class FallbackProvider(LLMProvider):
async def _run_chat_with_retry(
self,
kw: dict[str, Any],
original_messages: list[dict[str, Any]],
*,
stream: bool,
retry_mode: str,
@@ -293,7 +292,6 @@ class FallbackProvider(LLMProvider):
return await self._retry_with_fallback(
_call_provider,
call_kwargs,
original_messages,
retry_mode=retry_mode,
on_retry_wait=on_retry_wait,
on_retry_exhausted=on_retry_exhausted,
@@ -348,7 +346,6 @@ class FallbackProvider(LLMProvider):
self,
call: Callable[[LLMProvider, dict[str, Any]], Awaitable[LLMResponse]],
kwargs: dict[str, Any],
original_messages: list[dict[str, Any]],
*,
retry_mode: str,
on_retry_wait: RetryEventCallback | None,
@@ -430,7 +427,6 @@ class FallbackProvider(LLMProvider):
return await self._run_with_retry(
_call_chain,
dict(kwargs),
original_messages,
retry_mode="persistent",
on_retry_wait=on_retry_wait,
on_retry_exhausted=on_retry_exhausted,
@@ -506,7 +502,12 @@ class FallbackProvider(LLMProvider):
# continuation, so the incoming primary state remains reusable.
preserve_primary_state = True
if self._primary_available():
has_images = self._request_contains_images(kwargs["messages"], kwargs.get("provider_context"))
image_error = self._primary._image_input_error(kwargs["messages"], kwargs.get("provider_context"))
if image_error is not None:
primary_response = image_error
primary_error = image_error.content or primary_error
elif self._primary_available():
primary_was_attempted = True
response, primary_exception = await self._call_provider(
call, self._primary, kwargs
@@ -563,6 +564,8 @@ class FallbackProvider(LLMProvider):
last_response = primary_response
primary_skipped = not primary_was_attempted
for idx, fallback in enumerate(self._fallback_presets):
if has_images and not fallback.supports_images:
continue
fallback_model = fallback.model
if has_streamed is not None and has_streamed[0]:
is_timeout = (
@@ -579,7 +582,9 @@ class FallbackProvider(LLMProvider):
await on_stream_recover()
else:
break
if idx == 0 and primary_skipped:
if image_error is not None:
logger.info("Primary model '{}' does not accept images; trying '{}'", primary_model, fallback_model)
elif idx == 0 and primary_skipped:
logger.info(
"Primary model '{}' circuit open, trying fallback '{}'",
primary_model, fallback_model,
+1 -12
View File
@@ -718,6 +718,7 @@ class OpenAICompatProvider(LLMProvider):
clean["tool_call_id"] = map_tool_result_id(clean["tool_call_id"])
if (
force_string_content
and not self._contains_image_content(clean.get("content"))
and not (clean.get("role") == "assistant" and clean.get("tool_calls"))
):
clean["content"] = self._coerce_content_to_string(clean.get("content"))
@@ -1777,18 +1778,6 @@ class OpenAICompatProvider(LLMProvider):
except Exception as e:
return self._handle_error(e, spec=self._spec, api_base=self.api_base)
async def _retry_without_images(
self,
call: Callable[..., Awaitable[LLMResponse]],
kw: dict[str, Any],
original_messages: list[dict[str, Any]],
response: LLMResponse,
) -> LLMResponse:
# Neither a callback nor a cleanup failure indicates image incompatibility.
if response.error_kind in {"callback", "cleanup"}:
return response
return await super()._retry_without_images(call, kw, original_messages, response)
def get_default_model(self) -> str:
return self.default_model
+15
View File
@@ -1104,6 +1104,7 @@ def model_settings_payload(
"max_tokens": defaults.max_tokens,
"context_window_tokens": defaults.context_window_tokens,
"temperature": defaults.temperature,
"supports_images": defaults.supports_images,
"reasoning_effort": defaults.reasoning_effort,
"api": defaults.api.model_dump(mode="json") if defaults.api is not None else None,
"reasoning_effort_values": reasoning_effort_values_for(
@@ -1132,6 +1133,7 @@ def model_settings_payload(
"max_tokens": preset.max_tokens,
"context_window_tokens": preset.context_window_tokens,
"temperature": preset.temperature,
"supports_images": preset.supports_images,
"reasoning_effort": preset.reasoning_effort,
"api": preset.api.model_dump(mode="json") if preset.api is not None else None,
**{
@@ -1158,6 +1160,7 @@ def model_settings_payload(
"max_tokens": effective_preset.max_tokens,
"context_window_tokens": effective_preset.context_window_tokens,
"temperature": effective_preset.temperature,
"supports_images": effective_preset.supports_images,
"reasoning_effort": effective_preset.reasoning_effort,
"api": (
effective_preset.api.model_dump(mode="json")
@@ -1349,6 +1352,9 @@ def create_model_configuration(
),
temperature=temperature if temperature is not None else base.temperature,
reasoning_effort=reasoning_effort,
supports_images=parse_bool(
query_first_alias(query, "supports_images", "supportsImages") or "true", "supports_images",
),
api=_parse_preset_api(config, model, provider, query_first(query, "api")),
)
config.model_presets[name] = _preset_with_request_updates(config, candidate, query)
@@ -1438,6 +1444,13 @@ def update_model_configuration(
if preset.reasoning_effort != reasoning_effort:
preset.reasoning_effort = reasoning_effort
changed = True
if "supports_images" in query or "supportsImages" in query:
supports_images = parse_bool(
query_first_alias(query, "supports_images", "supportsImages") or "", "supports_images",
)
if preset.supports_images != supports_images:
preset.supports_images = supports_images
changed = True
if "api" in query:
api = _parse_preset_api(config, preset.model, preset.provider, query_first(query, "api"))
if preset.api != api:
@@ -1541,6 +1554,7 @@ def migrate_model_configurations(
config.model_presets[name] = ModelPresetConfig(
model=primary.model,
provider=primary.provider,
supports_images=primary.supports_images,
max_tokens=primary.max_tokens,
context_window_tokens=primary.context_window_tokens,
temperature=primary.temperature,
@@ -1560,6 +1574,7 @@ def migrate_model_configurations(
config.model_presets[name] = ModelPresetConfig(
model=fallback.model,
provider=fallback.provider,
supports_images=fallback.supports_images,
max_tokens=(
fallback.max_tokens if fallback.max_tokens is not None else primary.max_tokens
),