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:
1 parent
6a24b17629
commit
3f65a8f86c
36 files changed
+483
-444
No files matched your search
@@ -1512,6 +1512,10 @@ OpenAI Codex, xAI Grok subscriptions, and Azure OpenAI use Responses; Anthropic
|
||||
|
||||
**Advanced options** opens in a separate dialog; closing it returns to the preset editor. Changing a preset's model or provider resets its API selection to Auto unless the same update supplies a new declaration. Each fallback preset keeps its own API settings. Existing `agents.defaults.api` and inline fallback `api` values are preserved when converting to named presets.
|
||||
|
||||
Use the **Image input** switch in each preset to match the model's image capability. It is enabled by default; turn it off for text-only models. Requests containing images follow the configured primary and fallback order, using presets with **Image input** enabled. Text-only requests use the full configured order. If every candidate is text-only, nanobot returns an image-input error before sending the request.
|
||||
|
||||
For manual configuration, set `supportsImages` on a named preset, the implicit `agents.defaults` preset, or an inline fallback. Each defaults independently to `true`; use `false` for a text-only model. Transient retries preserve the original messages and images, and API validation errors are returned directly.
|
||||
|
||||
### Model Fallbacks
|
||||
|
||||
In **Settings → Models**, create the primary and backup presets, then use **Enable preset** and arrange their order. The first enabled preset is primary; later entries are tried as fallbacks. Save and test each preset before relying on the chain.
|
||||
|
||||
@@ -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
@@ -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."""
|
||||
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -26,6 +26,7 @@ def configured_override(monkeypatch):
|
||||
def construct(owned, *, preset, model=None):
|
||||
factory.validate_provider_setup(owned, preset=preset, model=model)
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
provider._image_input_error.return_value = None
|
||||
provider.generation = preset.to_generation_settings()
|
||||
provider.provider_name = owned.get_provider_name(preset=preset)
|
||||
provider.get_default_model.return_value = model or preset.model
|
||||
|
||||
@@ -163,9 +163,9 @@ async def test_auxiliary_calls_do_not_publish_response_identity():
|
||||
|
||||
|
||||
@pytest.mark.parametrize("with_tools", [False, True])
|
||||
@pytest.mark.parametrize("with_images", [False, True])
|
||||
@pytest.mark.parametrize(("with_images", "image_error"), [(False, False), (True, False), (True, True)])
|
||||
@pytest.mark.parametrize("fallback", [False, True])
|
||||
async def test_attribution_does_not_change_provider_requests(with_tools, with_images, fallback):
|
||||
async def test_attribution_does_not_change_provider_requests(with_tools, with_images, image_error, fallback):
|
||||
requests = []
|
||||
|
||||
class CapturingProvider(AnswerProvider):
|
||||
@@ -173,7 +173,7 @@ async def test_attribution_does_not_change_provider_requests(with_tools, with_im
|
||||
requests.append((self.provider_name, deepcopy({
|
||||
key: value for key, value in kwargs.items() if not key.startswith("on_")
|
||||
})))
|
||||
if with_images and len(requests) == 1:
|
||||
if image_error and len(requests) == 1:
|
||||
return LLMResponse(content="Images unsupported", finish_reason="error",
|
||||
error_status_code=400)
|
||||
return await super().chat(**kwargs)
|
||||
@@ -201,7 +201,12 @@ async def test_attribution_does_not_change_provider_requests(with_tools, with_im
|
||||
messages=deepcopy(messages), tools=tools, model="same-model",
|
||||
provider_context=ProviderCallContext(events=EventSink(AsyncMock()), response_preset=preset),
|
||||
)
|
||||
assert result.content == "answer"
|
||||
assert result.content == ("Images unsupported" if image_error else "answer")
|
||||
assert result.finish_reason == ("error" if image_error else "stop")
|
||||
assert len(requests) == (1 if image_error else 1 + int(fallback))
|
||||
assert all(request["messages"] == original for _, request in requests)
|
||||
if image_error:
|
||||
assert result.error_status_code == 400
|
||||
results.append(deepcopy(requests))
|
||||
assert results[0] == results[1]
|
||||
assert messages == original
|
||||
|
||||
@@ -1005,6 +1005,7 @@ async def test_reported_usage_floor_triggers_pressure_despite_low_estimate(monke
|
||||
|
||||
async def test_runner_does_not_compact_primary_request_from_fallback_usage(monkeypatch):
|
||||
primary = MagicMock(spec=LLMProvider)
|
||||
primary._image_input_error.return_value = None
|
||||
primary.provider_name = "primary"
|
||||
primary.generation = GenerationSettings(max_tokens=100)
|
||||
primary.supports_native_compaction.return_value = False
|
||||
|
||||
@@ -425,3 +425,20 @@ def test_transcription_only_provider_is_not_chat_fallback() -> None:
|
||||
})
|
||||
|
||||
assert config.get_provider_name() is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("supports_images", [False, True])
|
||||
def test_image_capability_round_trip_for_defaults_named_and_inline_presets(supports_images):
|
||||
config = Config.model_validate({
|
||||
"agents": {"defaults": {"supportsImages": supports_images, "fallbackModels": [
|
||||
"vision", {"model": "inline", "provider": "custom", "supportsImages": supports_images},
|
||||
]}},
|
||||
"modelPresets": {"vision": {"model": "vision", "supportsImages": supports_images}},
|
||||
})
|
||||
restored = Config.model_validate(config.model_dump(mode="json", by_alias=True))
|
||||
assert restored.resolve_default_preset().supports_images is supports_images
|
||||
assert restored.resolve_preset("vision").supports_images is supports_images
|
||||
inline = restored.agents.defaults.fallback_models[1]
|
||||
assert not isinstance(inline, str)
|
||||
assert inline.supports_images is supports_images
|
||||
assert Config().resolve_preset().supports_images is True
|
||||
@@ -0,0 +1,131 @@
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.config.schema import Config, ModelPresetConfig
|
||||
from nanobot.providers.base import (
|
||||
LLMProvider,
|
||||
LLMResponse,
|
||||
ProviderCallContext,
|
||||
ProviderConversationState,
|
||||
)
|
||||
from nanobot.providers.factory import make_provider, provider_signature
|
||||
from nanobot.providers.fallback_provider import FallbackProvider
|
||||
|
||||
_IMAGE = {"type": "image_url", "image_url": {"url": "data:image/png;base64,c3ludGhldGlj"}}
|
||||
|
||||
|
||||
class ImageProvider(LLMProvider):
|
||||
def __init__(self, supports_images: bool = True, response: LLMResponse | None = None):
|
||||
super().__init__(provider_name="custom")
|
||||
self.supports_images = supports_images
|
||||
self.response = response or LLMResponse("accepted")
|
||||
self.calls: list[dict[str, Any]] = []
|
||||
|
||||
def get_default_model(self) -> str:
|
||||
return "custom/model"
|
||||
|
||||
async def chat(self, **kwargs: Any) -> LLMResponse:
|
||||
self.calls.append(deepcopy(kwargs))
|
||||
return self.response
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stream", [False, True])
|
||||
@pytest.mark.parametrize("native", [False, True])
|
||||
async def test_text_only_preset_rejects_images_before_request(stream, native):
|
||||
provider = ImageProvider(False)
|
||||
messages = [{"role": "user", "content": "Continue" if native else [_IMAGE]}]
|
||||
state = ProviderConversationState(
|
||||
kind="fixture", provider="custom", model="custom/model", version=1,
|
||||
payload={"items": [{"role": "user", "content": [{"type": "input_image", "image_url": _IMAGE["image_url"]["url"]}]}]},
|
||||
) if native else None
|
||||
before = deepcopy(messages)
|
||||
call = provider.chat_stream_with_retry if stream else provider.chat_with_retry
|
||||
response = await call(messages=messages, provider_context=ProviderCallContext(conversation_state=state))
|
||||
assert response.finish_reason == "error"
|
||||
assert response.error_code == "unsupported_image"
|
||||
assert response.error_should_retry is False
|
||||
assert provider.calls == []
|
||||
assert messages == before
|
||||
text_response = await call(messages=[{"role": "user", "content": "Text only"}])
|
||||
assert text_response.content == "accepted"
|
||||
assert len(provider.calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stream", [False, True])
|
||||
@pytest.mark.parametrize("primary_supports", [False, True])
|
||||
async def test_image_fallback_skips_text_only_candidates_without_counting_capability_as_outage(stream, primary_supports):
|
||||
primary = ImageProvider(primary_supports, LLMResponse("unavailable", finish_reason="error", error_status_code=503))
|
||||
vision = ImageProvider()
|
||||
created = []
|
||||
|
||||
def factory(preset):
|
||||
created.append(preset.model)
|
||||
return vision
|
||||
|
||||
chain = FallbackProvider(primary, [
|
||||
ModelPresetConfig(model="text-only", supports_images=False),
|
||||
ModelPresetConfig(model="vision"),
|
||||
], factory)
|
||||
messages = [{"role": "user", "content": [_IMAGE]}]
|
||||
before = deepcopy(messages)
|
||||
call = chain.chat_stream_with_context if stream else chain.chat_with_context
|
||||
response = await call(messages=messages, provider_context=ProviderCallContext())
|
||||
assert response.content == "accepted"
|
||||
assert response.is_fallback
|
||||
assert created == ["vision"]
|
||||
assert len(primary.calls) == int(primary_supports)
|
||||
assert chain._primary_failures == int(primary_supports)
|
||||
assert vision.calls[0]["messages"] == before
|
||||
assert messages == before
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stream", [False, True])
|
||||
async def test_no_image_capable_candidate_fails_without_sending_or_stripping(stream):
|
||||
primary = ImageProvider(False)
|
||||
created = []
|
||||
chain = FallbackProvider(primary, [ModelPresetConfig(model="text", supports_images=False)], lambda preset: created.append(preset))
|
||||
call = chain.chat_stream_with_retry if stream else chain.chat_with_retry
|
||||
response = await call(messages=[{"role": "user", "content": [_IMAGE]}])
|
||||
assert response.error_code == "unsupported_image"
|
||||
assert response.error_should_retry is False
|
||||
assert primary.calls == created == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stream", [False, True])
|
||||
async def test_declared_vision_does_not_hide_actual_upstream_rejection(stream):
|
||||
upstream = LLMResponse("unsupported image format", finish_reason="error", error_status_code=400)
|
||||
primary = ImageProvider(True, upstream)
|
||||
created = []
|
||||
chain = FallbackProvider(primary, [ModelPresetConfig(model="vision")], lambda preset: created.append(preset))
|
||||
messages = [{"role": "user", "content": [_IMAGE]}]
|
||||
before = deepcopy(messages)
|
||||
call = chain.chat_stream_with_retry if stream else chain.chat_with_retry
|
||||
response = await call(messages=messages)
|
||||
assert response.content == upstream.content
|
||||
assert response.error_status_code == 400
|
||||
assert len(primary.calls) == 1
|
||||
assert created == []
|
||||
assert messages == before
|
||||
|
||||
|
||||
def test_factory_resolves_independent_capabilities_and_refresh_signature():
|
||||
config = Config.model_validate({
|
||||
"agents": {"defaults": {"modelPreset": "text", "fallbackModels": ["vision", {"provider": "custom", "model": "inline"}]}},
|
||||
"providers": {"custom": {"apiBase": "https://provider.example/v1"}},
|
||||
"modelPresets": {
|
||||
"text": {"model": "text", "provider": "custom", "supportsImages": False},
|
||||
"vision": {"model": "vision", "provider": "custom"},
|
||||
},
|
||||
})
|
||||
provider = make_provider(config)
|
||||
assert isinstance(provider, FallbackProvider)
|
||||
assert provider._primary.supports_images is False
|
||||
assert [preset.supports_images for preset in provider._fallback_presets] == [True, True]
|
||||
signature = provider_signature(config)
|
||||
config.model_presets["vision"].supports_images = False
|
||||
assert provider_signature(config) != signature
|
||||
signature = provider_signature(config)
|
||||
config.model_presets["text"].supports_images = True
|
||||
assert provider_signature(config) != signature
|
||||
@@ -221,9 +221,8 @@ async def test_bedrock_prepares_images_before_native_conversion(image_blocks, st
|
||||
|
||||
|
||||
@pytest.mark.parametrize("streaming", [False, True])
|
||||
@pytest.mark.parametrize("reject_text", [False, True])
|
||||
async def test_responses_image_rejection_discards_replay_and_retries_once(
|
||||
image_peer, image_blocks, monkeypatch, streaming, reject_text,
|
||||
async def test_responses_image_rejection_preserves_input_and_original_error(
|
||||
image_peer, image_blocks, monkeypatch, streaming,
|
||||
):
|
||||
url, requests, reject = image_peer
|
||||
provider = _provider("azure", url, monkeypatch)
|
||||
@@ -233,16 +232,17 @@ async def test_responses_image_rejection_discards_replay_and_retries_once(
|
||||
assert first.provider_state is not None
|
||||
pending = {"role": "user", "content": "Continue."}
|
||||
messages.extend([{"role": "assistant", "content": first.content}, pending])
|
||||
reject.update(images=True, text=reject_text)
|
||||
original = json.dumps(messages)
|
||||
reject["images"] = True
|
||||
call = provider.chat_stream_with_retry if streaming else provider.chat_with_retry
|
||||
result = await call(messages, provider_context=ProviderCallContext(
|
||||
session_id="image-rejection", conversation_state=first.provider_state.with_pending_messages([pending]),
|
||||
))
|
||||
assert result.finish_reason == ("error" if reject_text else "stop")
|
||||
assert len(requests) == 3
|
||||
assert result.finish_reason == "error"
|
||||
assert result.error_status_code == 400
|
||||
assert len(requests) == 2
|
||||
assert "input_image" in json.dumps(requests[1][1]["input"])
|
||||
assert "input_image" not in json.dumps(requests[2][1]["input"])
|
||||
assert "not delivered to model" in json.dumps(requests[2][1]["input"])
|
||||
assert json.dumps(messages) == original
|
||||
finally:
|
||||
await provider.aclose()
|
||||
|
||||
@@ -263,7 +263,7 @@ async def test_auto_responses_fallback_keeps_prepared_images(image_peer, image_b
|
||||
|
||||
|
||||
@pytest.mark.parametrize("streaming", [False, True])
|
||||
async def test_text_only_model_keeps_its_image_policy(image_peer, image_blocks, streaming):
|
||||
async def test_model_metadata_does_not_override_preset_image_policy(image_peer, image_blocks, streaming):
|
||||
url, requests, _ = image_peer
|
||||
provider = OpenAICompatProvider(
|
||||
api_key="fixture", api_base=f"{url}/v1", spec=find_by_name("deepseek"),
|
||||
@@ -272,8 +272,7 @@ async def test_text_only_model_keeps_its_image_policy(image_peer, image_blocks,
|
||||
try:
|
||||
result = await (provider.chat_stream if streaming else provider.chat)(_messages(image_blocks))
|
||||
assert result.content == "answer"
|
||||
assert "input_image" not in json.dumps(requests[0][1])
|
||||
assert "data:image/" not in json.dumps(requests[0][1])
|
||||
_assert_prepared(_received_images(requests[0][1]), image_blocks)
|
||||
assert "Read these images." in json.dumps(requests[0][1])
|
||||
finally:
|
||||
await provider.aclose()
|
||||
@@ -784,7 +784,7 @@ async def test_chat_callback_error_wins_over_close_error(chat_sdk, cleanup_warni
|
||||
|
||||
@pytest.mark.parametrize("close_fails", [False, True])
|
||||
@pytest.mark.parametrize("error_type", [RuntimeError, ConnectionError])
|
||||
async def test_chat_callback_error_does_not_retry_without_images(chat_sdk, close_fails, error_type):
|
||||
async def test_chat_callback_error_preserves_input_without_retry(chat_sdk, close_fails, error_type):
|
||||
stream = _ControlledChatStream(
|
||||
[_chat_event({"reasoning_content": "thinking"})],
|
||||
close_error=httpx.CloseError("connection reset") if close_fails else None,
|
||||
@@ -803,6 +803,7 @@ async def test_chat_callback_error_does_not_retry_without_images(chat_sdk, close
|
||||
result = await provider.chat_stream_with_retry(messages, on_thinking_delta=on_thinking)
|
||||
|
||||
assert result.finish_reason == "error" and "callback failed" in result.content
|
||||
assert result.error_kind == "callback" and result.error_should_retry is False
|
||||
assert len(requests) == 1
|
||||
assert messages == original
|
||||
assert stream.closed
|
||||
|
||||
@@ -48,7 +48,7 @@ def _mock_codex_token(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
[(None, False, False), (1000, False, False), (1000, True, False), (1000, False, True)],
|
||||
ids=["optional", "compaction-error", "generation-error", "persistent-fallback"],
|
||||
)
|
||||
async def test_image_retry_cannot_bypass_required_compaction(
|
||||
async def test_image_failure_preserves_input_and_required_compaction(
|
||||
monkeypatch, stream, input_budget, fail_after_compaction, with_fallback,
|
||||
) -> None:
|
||||
_mock_codex_token(monkeypatch)
|
||||
@@ -82,7 +82,7 @@ async def test_image_retry_cannot_bypass_required_compaction(
|
||||
))
|
||||
if len(submitted) == (2 if fail_after_compaction else 1):
|
||||
raise _CodexHTTPError("fixture rejection", status_code=400, error_code="unsupported_value")
|
||||
return provider_base.LLMResponse(content="accepted without images")
|
||||
return provider_base.LLMResponse(content="unexpected repeated generation")
|
||||
|
||||
monkeypatch.setattr("nanobot.providers.openai_codex_provider._request_codex", request)
|
||||
caller = FallbackProvider(
|
||||
@@ -116,10 +116,12 @@ async def test_image_retry_cannot_bypass_required_compaction(
|
||||
else:
|
||||
assert response.preserve_provider_state_on_error is True
|
||||
else:
|
||||
assert submitted == ["generation", "generation"]
|
||||
assert response.content == "accepted without images"
|
||||
assert "data:image/png;base64,abc" not in str(bodies[-1])
|
||||
assert question["content"][1]["type"] == "text"
|
||||
assert submitted == ["generation"]
|
||||
assert response.finish_reason == "error"
|
||||
assert response.error_status_code == 400
|
||||
assert response.error_code == "unsupported_value"
|
||||
assert "data:image/png;base64,abc" in str(bodies[-1])
|
||||
assert question["content"][1]["type"] == "image_url"
|
||||
finally:
|
||||
await provider.aclose()
|
||||
|
||||
|
||||
@@ -1784,7 +1784,7 @@ def test_deepseek_vision_preserves_multimodal_content(
|
||||
|
||||
|
||||
@pytest.mark.parametrize("responses", [False, True])
|
||||
def test_deepseek_pro_remains_text_only(responses: bool) -> None:
|
||||
def test_deepseek_text_coercion_preserves_image_content(responses: bool) -> None:
|
||||
provider = OpenAICompatProvider(
|
||||
api_key="k", default_model="deepseek-v4-pro", spec=find_by_name("deepseek"),
|
||||
)
|
||||
@@ -1799,10 +1799,16 @@ def test_deepseek_pro_remains_text_only(responses: bool) -> None:
|
||||
)
|
||||
if responses:
|
||||
assert body["input"] == [{
|
||||
"role": "user", "content": [{"type": "input_text", "text": "describe the image"}],
|
||||
"role": "user", "content": [
|
||||
{"type": "input_text", "text": "describe the image"},
|
||||
{"type": "input_image", "image_url": "data:image/png;base64,AA==", "detail": "auto"},
|
||||
],
|
||||
}]
|
||||
else:
|
||||
assert body["messages"] == [{"role": "user", "content": "describe the image"}]
|
||||
assert body["messages"][0]["content"] == [
|
||||
{"type": "text", "text": "describe the image"},
|
||||
{"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}},
|
||||
]
|
||||
|
||||
|
||||
def test_non_deepseek_keeps_list_content() -> None:
|
||||
|
||||
@@ -441,7 +441,7 @@ async def test_chat_with_retry_explicit_override_beats_defaults() -> None:
|
||||
),
|
||||
LLMResponse(content="billing", finish_reason="error", error_status_code=402),
|
||||
])
|
||||
async def test_account_failure_does_not_retry_without_images(error: LLMResponse) -> None:
|
||||
async def test_account_failure_preserves_images_without_retry(error: LLMResponse) -> None:
|
||||
provider = ScriptedProvider([error])
|
||||
messages = copy.deepcopy(_IMAGE_MSG)
|
||||
original = copy.deepcopy(messages)
|
||||
@@ -466,175 +466,125 @@ _IMAGE_MSG = [
|
||||
]},
|
||||
]
|
||||
|
||||
_IMAGE_MSG_NO_META = [
|
||||
{"role": "user", "content": [
|
||||
{"type": "text", "text": "describe this"},
|
||||
{"type": "image_url", "image_url": {"url": "data:image/png;base64,abc"}},
|
||||
]},
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_transient_error_with_images_retries_without_images() -> None:
|
||||
provider = ScriptedProvider([
|
||||
LLMResponse(content="API调用参数有误,请检查文档", finish_reason="error"),
|
||||
LLMResponse(content="ok, no image"),
|
||||
])
|
||||
|
||||
response = await provider.chat_with_retry(messages=copy.deepcopy(_IMAGE_MSG))
|
||||
|
||||
assert response.content == "ok, no image"
|
||||
assert provider.calls == 2
|
||||
msgs_on_retry = provider.last_kwargs["messages"]
|
||||
for msg in msgs_on_retry:
|
||||
content = msg.get("content")
|
||||
if isinstance(content, list):
|
||||
assert all(b.get("type") != "image_url" for b in content)
|
||||
assert any("not delivered" in (b.get("text") or "").lower() for b in content)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_successful_image_retry_mutates_original_messages_in_place() -> None:
|
||||
provider = ScriptedProvider([
|
||||
LLMResponse(content="model does not support images", finish_reason="error"),
|
||||
LLMResponse(content="ok, no image"),
|
||||
])
|
||||
@pytest.mark.parametrize("streaming", [False, True])
|
||||
@pytest.mark.parametrize("error", [
|
||||
LLMResponse(content="API调用参数有误,请检查文档", finish_reason="error", error_status_code=400),
|
||||
LLMResponse(
|
||||
content="model does not support images", finish_reason="error",
|
||||
error_status_code=400, error_code="unsupported_image", error_should_retry=False,
|
||||
),
|
||||
])
|
||||
async def test_nontransient_image_error_returns_original_response(streaming, error) -> None:
|
||||
provider = ScriptedProvider([error, LLMResponse(content="unexpected text-only answer")])
|
||||
messages = copy.deepcopy(_IMAGE_MSG)
|
||||
original = copy.deepcopy(messages)
|
||||
call = provider.chat_stream_with_retry if streaming else provider.chat_with_retry
|
||||
|
||||
response = await provider.chat_with_retry(messages=messages)
|
||||
response = await call(messages=messages)
|
||||
|
||||
assert response.content == "ok, no image"
|
||||
content = messages[0]["content"]
|
||||
assert isinstance(content, list)
|
||||
assert all(block.get("type") != "image_url" for block in content)
|
||||
assert any("not delivered" in (block.get("text") or "").lower() for block in content)
|
||||
assert response is error
|
||||
assert provider.calls == 1
|
||||
assert messages == original
|
||||
assert LLMProvider.public_error_kind(response) == "unknown"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
("messages", "payload", "pending_messages"),
|
||||
[
|
||||
(_IMAGE_MSG, {}, _IMAGE_MSG),
|
||||
(
|
||||
[{"role": "user", "content": "continue"}],
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"type": "message",
|
||||
"role": "user",
|
||||
"content": [
|
||||
{
|
||||
"type": "input_image",
|
||||
"image_url": "data:image/png;base64,abc",
|
||||
}
|
||||
],
|
||||
}
|
||||
]
|
||||
},
|
||||
[],
|
||||
),
|
||||
],
|
||||
ids=["pending-image", "opaque-payload-image"],
|
||||
)
|
||||
async def test_image_retry_discards_provider_state_with_images(
|
||||
messages,
|
||||
payload,
|
||||
pending_messages,
|
||||
@pytest.mark.parametrize("streaming", [False, True])
|
||||
@pytest.mark.parametrize("budget", [None, 128])
|
||||
@pytest.mark.parametrize("transient", [False, True])
|
||||
async def test_image_requests_preserve_native_context_and_compaction_budget(
|
||||
monkeypatch, streaming, budget, transient,
|
||||
) -> None:
|
||||
class ContextScriptedProvider(ScriptedProvider):
|
||||
def __init__(self, responses):
|
||||
super().__init__(responses)
|
||||
self.contexts: list[ProviderCallContext] = []
|
||||
self.inputs: list[list[dict]] = []
|
||||
|
||||
async def chat_with_context(
|
||||
self,
|
||||
*,
|
||||
provider_context: ProviderCallContext,
|
||||
**kwargs,
|
||||
) -> LLMResponse:
|
||||
async def chat_with_context(self, *, provider_context, **kwargs) -> LLMResponse:
|
||||
self.contexts.append(provider_context)
|
||||
self.inputs.append(copy.deepcopy(kwargs["messages"]))
|
||||
return await self.chat(**kwargs)
|
||||
|
||||
provider = ContextScriptedProvider([
|
||||
LLMResponse(content="model does not support images", finish_reason="error"),
|
||||
LLMResponse(content="ok, no image"),
|
||||
])
|
||||
messages = copy.deepcopy(messages)
|
||||
state = ProviderConversationState(
|
||||
kind="openai_responses",
|
||||
provider="openai:test",
|
||||
model="gpt-5.6",
|
||||
version=1,
|
||||
payload=copy.deepcopy(payload),
|
||||
pending_messages=copy.deepcopy(pending_messages),
|
||||
)
|
||||
async def chat_stream_with_context(self, *, provider_context, **kwargs) -> LLMResponse:
|
||||
self.contexts.append(provider_context)
|
||||
self.inputs.append(copy.deepcopy(kwargs["messages"]))
|
||||
return await self.chat_stream(**kwargs)
|
||||
|
||||
response = await provider.chat_with_retry(
|
||||
error = LLMResponse(
|
||||
content="request failed", finish_reason="error",
|
||||
error_status_code=503 if transient else 400,
|
||||
)
|
||||
success = LLMResponse(content="answer with images")
|
||||
provider = ContextScriptedProvider([error, success])
|
||||
messages = copy.deepcopy(_IMAGE_MSG)
|
||||
original = copy.deepcopy(messages)
|
||||
state = ProviderConversationState(
|
||||
kind="openai_responses", provider="openai:test", model="gpt-5.6", version=1,
|
||||
payload={"items": [{"type": "message", "role": "user", "content": [
|
||||
{"type": "input_image", "image_url": "data:image/png;base64,abc"},
|
||||
]}]},
|
||||
pending_messages=copy.deepcopy(_IMAGE_MSG),
|
||||
)
|
||||
original_state = state.to_private_record()
|
||||
delays = []
|
||||
|
||||
async def sleep(delay):
|
||||
delays.append(delay)
|
||||
|
||||
monkeypatch.setattr("nanobot.providers.base.asyncio.sleep", sleep)
|
||||
call = provider.chat_stream_with_retry if streaming else provider.chat_with_retry
|
||||
response = await call(
|
||||
messages=messages,
|
||||
provider_context=ProviderCallContext(
|
||||
conversation_state=state,
|
||||
session_id="webui:cache-test",
|
||||
response_preset="saved fallback",
|
||||
response_is_fallback=True,
|
||||
conversation_state=state, session_id="webui:cache-test",
|
||||
response_preset="saved preset", compaction_input_budget=budget,
|
||||
),
|
||||
)
|
||||
|
||||
assert response.content == "ok, no image"
|
||||
retry_context = provider.contexts[-1]
|
||||
assert isinstance(retry_context, ProviderCallContext)
|
||||
assert retry_context.conversation_state is None
|
||||
assert retry_context.session_id == "webui:cache-test"
|
||||
assert retry_context.response_preset == "saved fallback"
|
||||
assert retry_context.response_is_fallback is True
|
||||
public_content = messages[0]["content"]
|
||||
if isinstance(public_content, list):
|
||||
assert all(block.get("type") != "image_url" for block in public_content)
|
||||
assert response is (success if transient else error)
|
||||
assert provider.calls == (2 if transient else 1)
|
||||
assert messages == original
|
||||
assert state.to_private_record() == original_state
|
||||
assert provider.inputs == [original] * provider.calls
|
||||
for context in provider.contexts:
|
||||
assert context.conversation_state is state
|
||||
assert context.compaction_input_budget == budget
|
||||
assert context.session_id == "webui:cache-test"
|
||||
assert context.response_preset == "saved preset"
|
||||
assert context.compaction is provider.contexts[0].compaction
|
||||
assert len(delays) == (1 if transient else 0)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_transient_error_without_images_no_retry() -> None:
|
||||
@pytest.mark.parametrize("streaming", [False, True])
|
||||
async def test_transient_then_terminal_image_error_preserves_input(monkeypatch, streaming) -> None:
|
||||
error = LLMResponse(content="invalid request", finish_reason="error", error_status_code=400)
|
||||
provider = ScriptedProvider([
|
||||
LLMResponse(content="401 unauthorized", finish_reason="error"),
|
||||
LLMResponse(content="unavailable", finish_reason="error", error_status_code=503),
|
||||
error,
|
||||
LLMResponse(content="unexpected text-only answer"),
|
||||
])
|
||||
messages = copy.deepcopy(_IMAGE_MSG)
|
||||
original = copy.deepcopy(messages)
|
||||
statuses = []
|
||||
|
||||
response = await provider.chat_with_retry(
|
||||
messages=[{"role": "user", "content": "hello"}],
|
||||
)
|
||||
async def sleep(_delay):
|
||||
return None
|
||||
|
||||
assert provider.calls == 1
|
||||
assert response.finish_reason == "error"
|
||||
async def status(event):
|
||||
statuses.append(event)
|
||||
|
||||
monkeypatch.setattr("nanobot.providers.base.asyncio.sleep", sleep)
|
||||
call = provider.chat_stream_with_retry if streaming else provider.chat_with_retry
|
||||
response = await call(messages=messages, on_retry_status=status)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_image_fallback_returns_error_on_second_failure() -> None:
|
||||
provider = ScriptedProvider([
|
||||
LLMResponse(content="some model error", finish_reason="error"),
|
||||
LLMResponse(content="still failing", finish_reason="error"),
|
||||
])
|
||||
|
||||
response = await provider.chat_with_retry(messages=copy.deepcopy(_IMAGE_MSG))
|
||||
|
||||
assert response is error
|
||||
assert provider.calls == 2
|
||||
assert response.content == "still failing"
|
||||
assert response.finish_reason == "error"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_image_fallback_without_meta_uses_default_placeholder() -> None:
|
||||
provider = ScriptedProvider([
|
||||
LLMResponse(content="error", finish_reason="error"),
|
||||
LLMResponse(content="ok"),
|
||||
])
|
||||
|
||||
response = await provider.chat_with_retry(messages=copy.deepcopy(_IMAGE_MSG_NO_META))
|
||||
|
||||
assert response.content == "ok"
|
||||
assert provider.calls == 2
|
||||
msgs_on_retry = provider.last_kwargs["messages"]
|
||||
for msg in msgs_on_retry:
|
||||
content = msg.get("content")
|
||||
if isinstance(content, list):
|
||||
assert any("not delivered" in (b.get("text") or "").lower() for b in content)
|
||||
assert messages == original
|
||||
assert [event.state for event in statuses] == ["waiting", "cleared"]
|
||||
assert statuses[-1].error_kind == "unknown"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -1,155 +0,0 @@
|
||||
"""Tests for LLMProvider._strip_image_content and _strip_image_content_inplace.
|
||||
|
||||
Regression test for #4345: image-strip fallback should not leak file paths
|
||||
or produce text that makes the model hallucinate about unseen images.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from nanobot.providers.base import LLMProvider
|
||||
|
||||
|
||||
class TestStripImageContent:
|
||||
|
||||
def test_replaces_image_url_with_nondescriptive_placeholder(self):
|
||||
messages = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": "What is this?"},
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {"url": "data:image/png;base64,abc"},
|
||||
"_meta": {"path": "/tmp/screenshot.png"},
|
||||
},
|
||||
],
|
||||
}
|
||||
]
|
||||
result = LLMProvider._strip_image_content(messages)
|
||||
assert result is not None
|
||||
content = result[0]["content"]
|
||||
assert len(content) == 2
|
||||
assert content[0] == {"type": "text", "text": "What is this?"}
|
||||
assert content[1]["type"] == "text"
|
||||
placeholder = content[1]["text"]
|
||||
assert "/tmp/screenshot.png" not in placeholder
|
||||
assert "screenshot" not in placeholder
|
||||
assert "not delivered" in placeholder.lower()
|
||||
|
||||
def test_returns_none_when_no_images(self):
|
||||
messages = [
|
||||
{"role": "user", "content": [{"type": "text", "text": "hello"}]}
|
||||
]
|
||||
assert LLMProvider._strip_image_content(messages) is None
|
||||
|
||||
def test_handles_multiple_images(self):
|
||||
messages = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": "Look at these:"},
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {"url": "data:image/png;base64,abc"},
|
||||
"_meta": {"path": "/a.png"},
|
||||
},
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {"url": "data:image/png;base64,def"},
|
||||
"_meta": {"path": "/b.png"},
|
||||
},
|
||||
],
|
||||
}
|
||||
]
|
||||
result = LLMProvider._strip_image_content(messages)
|
||||
assert result is not None
|
||||
content = result[0]["content"]
|
||||
assert len(content) == 3
|
||||
for block in content[1:]:
|
||||
assert block["type"] == "text"
|
||||
assert "/a.png" not in block["text"]
|
||||
assert "/b.png" not in block["text"]
|
||||
|
||||
def test_handles_image_without_meta(self):
|
||||
messages = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {"url": "data:image/png;base64,abc"},
|
||||
},
|
||||
],
|
||||
}
|
||||
]
|
||||
result = LLMProvider._strip_image_content(messages)
|
||||
assert result is not None
|
||||
placeholder = result[0]["content"][0]["text"]
|
||||
assert "not delivered" in placeholder.lower()
|
||||
|
||||
def test_preserves_non_image_content(self):
|
||||
messages = [
|
||||
{"role": "system", "content": "You are helpful."},
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": "Hello"},
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {"url": "data:image/png;base64,abc"},
|
||||
"_meta": {"path": "/x.png"},
|
||||
},
|
||||
],
|
||||
},
|
||||
{"role": "assistant", "content": "Hi there!"},
|
||||
]
|
||||
result = LLMProvider._strip_image_content(messages)
|
||||
assert result is not None
|
||||
assert result[0]["content"] == "You are helpful."
|
||||
assert result[2]["content"] == "Hi there!"
|
||||
assert result[1]["content"][0]["type"] == "text"
|
||||
|
||||
|
||||
class TestStripImageContentInplace:
|
||||
|
||||
def test_replaces_image_url_with_nondescriptive_placeholder(self):
|
||||
messages = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": "What is this?"},
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {"url": "data:image/png;base64,abc"},
|
||||
"_meta": {"path": "/tmp/photo.jpg"},
|
||||
},
|
||||
],
|
||||
}
|
||||
]
|
||||
found = LLMProvider._strip_image_content_inplace(messages)
|
||||
assert found is True
|
||||
content = messages[0]["content"]
|
||||
assert len(content) == 2
|
||||
placeholder = content[1]["text"]
|
||||
assert "/tmp/photo.jpg" not in placeholder
|
||||
assert "not delivered" in placeholder.lower()
|
||||
|
||||
def test_returns_false_when_no_images(self):
|
||||
messages = [
|
||||
{"role": "user", "content": [{"type": "text", "text": "hello"}]}
|
||||
]
|
||||
assert LLMProvider._strip_image_content_inplace(messages) is False
|
||||
|
||||
def test_mutates_original_messages(self):
|
||||
original_content = [
|
||||
{"type": "text", "text": "see this"},
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {"url": "data:image/png;base64,abc"},
|
||||
"_meta": {"path": "/img.png"},
|
||||
},
|
||||
]
|
||||
messages = [{"role": "user", "content": original_content}]
|
||||
LLMProvider._strip_image_content_inplace(messages)
|
||||
assert original_content[1]["type"] == "text"
|
||||
assert "/img.png" not in original_content[1]["text"]
|
||||
@@ -686,6 +686,7 @@ def test_migrate_model_configurations_preserves_legacy_chain(
|
||||
config.agents.defaults.provider = "openai"
|
||||
config.agents.defaults.max_tokens = 4096
|
||||
config.agents.defaults.temperature = 0.25
|
||||
config.agents.defaults.supports_images = False
|
||||
config.agents.defaults.fallback_models = [
|
||||
InlineFallbackConfig(
|
||||
model="anthropic/claude-sonnet-4",
|
||||
@@ -708,6 +709,8 @@ def test_migrate_model_configurations_preserves_legacy_chain(
|
||||
assert saved.agents.defaults.model_preset == "gpt-4o"
|
||||
assert saved.agents.defaults.fallback_models == ["claude-sonnet-4"]
|
||||
assert saved.model_presets["gpt-4o"].temperature == 0.25
|
||||
assert saved.model_presets["gpt-4o"].supports_images is False
|
||||
assert saved.model_presets["claude-sonnet-4"].supports_images is True
|
||||
assert saved.model_presets["claude-sonnet-4"].max_tokens == 4096
|
||||
assert saved.model_presets["claude-sonnet-4"].temperature == 0.25
|
||||
|
||||
@@ -2931,3 +2934,25 @@ def test_openai_settings_can_return_to_auto(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
update_provider_settings({"provider": ["openai"], "api": ["null"]})
|
||||
assert load_config(config_path).providers.openai.api is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["supports_images", "supportsImages"])
|
||||
def test_preset_image_capability_persists_and_preserves_unrelated_edits(tmp_path, monkeypatch, field):
|
||||
config_path = tmp_path / "config.json"
|
||||
config = Config()
|
||||
config.providers.openai.api_key = "sk-test"
|
||||
save_config(config, config_path)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
created = create_model_configuration({
|
||||
"name": ["Text"], "provider": ["openai"], "model": ["gpt-4.1"], field: ["false"],
|
||||
})
|
||||
assert next(row for row in created["model_presets"] if row["name"] == "Text")["supports_images"] is False
|
||||
update_model_call_order({"order": [json.dumps(["Text"])]})
|
||||
assert settings_payload()["agent"]["supports_images"] is False
|
||||
update_model_configuration({"name": ["Text"], "temperature": ["0.3"]})
|
||||
assert load_config(config_path).model_presets["Text"].supports_images is False
|
||||
updated = update_model_configuration({"name": ["Text"], field: ["true"]})
|
||||
assert next(row for row in updated["model_presets"] if row["name"] == "Text")["supports_images"] is True
|
||||
assert json.loads(config_path.read_text(encoding="utf-8"))["modelPresets"]["Text"]["supportsImages"] is True
|
||||
defaulted = create_model_configuration({"name": ["Default vision"], "provider": ["openai"], "model": ["gpt-4.1"]})
|
||||
assert next(row for row in defaulted["model_presets"] if row["name"] == "Default vision")["supports_images"] is True
|
||||
@@ -18,5 +18,19 @@ for (const width of [390, 1280]) {
|
||||
await model.hover();
|
||||
await expect(page.getByRole("tooltip")).toHaveText("openai-codex/gpt-6.1-sol");
|
||||
}
|
||||
|
||||
await page.getByRole("button", { name: "New preset", exact: true }).click();
|
||||
const dialog = page.getByRole("dialog", { name: "New preset", exact: true });
|
||||
const imageInput = dialog.getByRole("switch", { name: "Image input", exact: true });
|
||||
await expect(imageInput).toBeVisible();
|
||||
await expect(imageInput).toBeChecked();
|
||||
await imageInput.focus();
|
||||
await imageInput.press("Space");
|
||||
await expect(imageInput).not.toBeChecked();
|
||||
expect(await dialog.evaluate((element) => element.scrollWidth <= element.clientWidth + 1)).toBe(true);
|
||||
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await expect(dialog).not.toBeVisible();
|
||||
await page.getByRole("button", { name: "New preset", exact: true }).click();
|
||||
await expect(imageInput).toBeChecked();
|
||||
});
|
||||
}
|
||||
@@ -59,6 +59,7 @@ export interface AgentSettingsDraft {
|
||||
contextWindowTokens: number;
|
||||
temperature: number;
|
||||
reasoningEffort: string;
|
||||
supportsImages: boolean;
|
||||
api: ModelAPIConfig | null;
|
||||
extraHeaders: string;
|
||||
extraQuery: string;
|
||||
@@ -103,6 +104,7 @@ export const DEFAULT_AGENT_SETTINGS_DRAFT: AgentSettingsDraft = {
|
||||
contextWindowTokens: 200_000,
|
||||
temperature: 0.1,
|
||||
reasoningEffort: "",
|
||||
supportsImages: true,
|
||||
api: null,
|
||||
extraHeaders: "",
|
||||
extraQuery: "",
|
||||
@@ -130,6 +132,7 @@ export function agentDraftFromPayload(
|
||||
),
|
||||
temperature: activePreset?.temperature ?? payload.agent.temperature,
|
||||
reasoningEffort: activePreset?.reasoning_effort ?? "",
|
||||
supportsImages: (activePreset ? activePreset.supports_images : payload.agent.supports_images) ?? true,
|
||||
api: activePreset ? activePreset.api ?? null : payload.agent.api ?? null,
|
||||
extraHeaders: providerJsonValue(activePreset?.extra_headers),
|
||||
extraQuery: providerJsonValue(activePreset?.extra_query),
|
||||
@@ -403,6 +406,7 @@ export function ModelsSettings({
|
||||
contextWindowTokens: normalizeContextWindowTokens(preset.context_window_tokens),
|
||||
temperature: preset.temperature,
|
||||
reasoningEffort: preset.reasoning_effort ?? "",
|
||||
supportsImages: preset.supports_images ?? true,
|
||||
api: preset.api ?? null,
|
||||
extraHeaders: providerJsonValue(preset.extra_headers),
|
||||
extraQuery: providerJsonValue(preset.extra_query),
|
||||
@@ -542,6 +546,20 @@ export function ModelsSettings({
|
||||
}}
|
||||
/>
|
||||
</SettingsRow>
|
||||
<SettingsRow
|
||||
title={t("settings.models.imageInput")}
|
||||
description={t("settings.models.imageInputHelp")}
|
||||
>
|
||||
<ToggleButton
|
||||
checked={form.supportsImages}
|
||||
label={t("settings.models.imageInput")}
|
||||
disabled={saving || creatingSaving}
|
||||
onChange={(supportsImages) => {
|
||||
edits.complete();
|
||||
setForm((prev) => ({ ...prev, supportsImages }));
|
||||
}}
|
||||
/>
|
||||
</SettingsRow>
|
||||
<SettingsRow title={tx("settings.models.reasoningEffort", "Reasoning effort")}>
|
||||
<ReasoningEffortPicker
|
||||
onSelect={edits.complete}
|
||||
|
||||
@@ -209,6 +209,7 @@ export function useModelSettingsActions({
|
||||
contextWindowTokens: form.contextWindowTokens,
|
||||
temperature: form.temperature,
|
||||
reasoningEffort: form.reasoningEffort || null,
|
||||
supportsImages: form.supportsImages,
|
||||
api: form.api ?? undefined,
|
||||
...(settings.model_request_overrides_supported ? {
|
||||
extraHeaders: form.extraHeaders,
|
||||
@@ -272,6 +273,8 @@ export function useModelSettingsActions({
|
||||
form.temperature !== selectedPreset.temperature ? form.temperature : undefined,
|
||||
reasoningEffort:
|
||||
reasoningEffort !== selectedPreset.reasoning_effort ? reasoningEffort : undefined,
|
||||
supportsImages: form.supportsImages !== (selectedPreset.supports_images ?? true)
|
||||
? form.supportsImages : undefined,
|
||||
api: modelAPISelection(form.api) !== modelAPISelection(selectedPreset.api)
|
||||
? form.api : undefined,
|
||||
...(settings.model_request_overrides_supported ? {
|
||||
@@ -336,6 +339,7 @@ export function useModelSettingsActions({
|
||||
modelPreset: "",
|
||||
provider,
|
||||
model: "",
|
||||
supportsImages: true,
|
||||
api: null,
|
||||
extraHeaders: "",
|
||||
extraQuery: "",
|
||||
|
||||
@@ -268,6 +268,7 @@ export function useSettingsController({
|
||||
form.contextWindowTokens !== normalizeContextWindowTokens(selectedPreset.context_window_tokens) ||
|
||||
form.temperature !== selectedPreset.temperature ||
|
||||
form.reasoningEffort !== (selectedPreset.reasoning_effort ?? "") ||
|
||||
form.supportsImages !== (selectedPreset.supports_images ?? true) ||
|
||||
modelAPISelection(form.api) !== modelAPISelection(selectedPreset.api) ||
|
||||
form.extraHeaders !== providerJsonValue(selectedPreset.extra_headers) ||
|
||||
form.extraQuery !== providerJsonValue(selectedPreset.extra_query) ||
|
||||
|
||||
@@ -880,6 +880,8 @@
|
||||
"contextWindowError": "Enter a positive token count, such as 200k, 1m, or 131072.",
|
||||
"maxTokens": "Max output tokens",
|
||||
"temperature": "Temperature",
|
||||
"imageInput": "Image input",
|
||||
"imageInputHelp": "When off, requests containing images skip this preset.",
|
||||
"reasoningEffort": "Reasoning effort",
|
||||
"convertTitle": "Convert setup",
|
||||
"convertHelp": "Convert primary and fallback models to presets.",
|
||||
|
||||
@@ -1060,6 +1060,8 @@
|
||||
"contextWindowError": "Introduce una cantidad positiva de tokens, como 200k, 1m o 131072.",
|
||||
"maxTokens": "Máx. tokens de salida",
|
||||
"temperature": "Temperatura",
|
||||
"imageInput": "Entrada de imágenes",
|
||||
"imageInputHelp": "Al desactivarla, las solicitudes con imágenes omiten este preajuste.",
|
||||
"reasoningEffort": "Esfuerzo de razonamiento",
|
||||
"convertTitle": "Convertir ajustes",
|
||||
"convertHelp": "Convierte los modelos principal y de respaldo en preajustes.",
|
||||
|
||||
@@ -1060,6 +1060,8 @@
|
||||
"contextWindowError": "Saisissez un nombre positif de tokens, par exemple 200k, 1m ou 131072.",
|
||||
"maxTokens": "Tokens de sortie max.",
|
||||
"temperature": "Température",
|
||||
"imageInput": "Entrée d’images",
|
||||
"imageInputHelp": "Si désactivée, les requêtes contenant des images ignorent ce préréglage.",
|
||||
"reasoningEffort": "Effort de raisonnement",
|
||||
"convertTitle": "Convertir les réglages",
|
||||
"convertHelp": "Convertissez les modèles principal et de secours en préréglages.",
|
||||
|
||||
@@ -1060,6 +1060,8 @@
|
||||
"contextWindowError": "Masukkan jumlah token positif, seperti 200k, 1m, atau 131072.",
|
||||
"maxTokens": "Maks. token keluaran",
|
||||
"temperature": "Temperatur",
|
||||
"imageInput": "Input gambar",
|
||||
"imageInputHelp": "Jika dinonaktifkan, permintaan berisi gambar akan melewati preset ini.",
|
||||
"reasoningEffort": "Upaya penalaran",
|
||||
"convertTitle": "Konversi pengaturan",
|
||||
"convertHelp": "Ubah model utama dan cadangan menjadi preset.",
|
||||
|
||||
@@ -1060,6 +1060,8 @@
|
||||
"contextWindowError": "200k、1m、131072 など、正のトークン数を入力してください。",
|
||||
"maxTokens": "最大出力トークン",
|
||||
"temperature": "温度",
|
||||
"imageInput": "画像入力",
|
||||
"imageInputHelp": "オフにすると、画像を含むリクエストではこのプリセットをスキップします。",
|
||||
"reasoningEffort": "推論の強度",
|
||||
"convertTitle": "設定を変換",
|
||||
"convertHelp": "主モデルと予備モデルをプリセットに変換します。",
|
||||
|
||||
@@ -1060,6 +1060,8 @@
|
||||
"contextWindowError": "200k, 1m, 131072처럼 양수 토큰 수를 입력하세요.",
|
||||
"maxTokens": "최대 출력 토큰",
|
||||
"temperature": "온도",
|
||||
"imageInput": "이미지 입력",
|
||||
"imageInputHelp": "끄면 이미지가 포함된 요청에서 이 프리셋을 건너뜁니다.",
|
||||
"reasoningEffort": "추론 강도",
|
||||
"convertTitle": "설정 변환",
|
||||
"convertHelp": "주 모델과 대체 모델을 프리셋으로 변환하세요.",
|
||||
|
||||
@@ -700,6 +700,8 @@
|
||||
"contextWindowError": "Insira uma quantidade positiva de tokens, como 200k, 1m ou 131072.",
|
||||
"maxTokens": "Máx. de tokens de saída",
|
||||
"temperature": "Temperatura",
|
||||
"imageInput": "Entrada de imagens",
|
||||
"imageInputHelp": "Quando desativada, solicitações com imagens ignoram esta predefinição.",
|
||||
"reasoningEffort": "Esforço de raciocínio",
|
||||
"convertTitle": "Converter ajustes",
|
||||
"convertHelp": "Converta os modelos principal e alternativo em presets.",
|
||||
|
||||
@@ -1060,6 +1060,8 @@
|
||||
"contextWindowError": "Nhập số lượng token dương, chẳng hạn 200k, 1m hoặc 131072.",
|
||||
"maxTokens": "Token đầu ra tối đa",
|
||||
"temperature": "Nhiệt độ",
|
||||
"imageInput": "Đầu vào hình ảnh",
|
||||
"imageInputHelp": "Khi tắt, yêu cầu chứa hình ảnh sẽ bỏ qua cấu hình này.",
|
||||
"reasoningEffort": "Mức suy luận",
|
||||
"convertTitle": "Chuyển thiết lập",
|
||||
"convertHelp": "Chuyển mô hình chính và dự phòng thành bộ thiết lập.",
|
||||
|
||||
@@ -880,6 +880,8 @@
|
||||
"contextWindowError": "请输入正数 Token 数量,例如 200k、1m 或 131072。",
|
||||
"maxTokens": "输出 Token 上限",
|
||||
"temperature": "温度",
|
||||
"imageInput": "图像输入",
|
||||
"imageInputHelp": "关闭后,含图片的请求会跳过此预设。",
|
||||
"reasoningEffort": "推理强度",
|
||||
"convertTitle": "转换设置",
|
||||
"convertHelp": "将主模型和备用模型转为预设",
|
||||
|
||||
@@ -1060,6 +1060,8 @@
|
||||
"contextWindowError": "請輸入正數 Token 數量,例如 200k、1m 或 131072。",
|
||||
"maxTokens": "輸出 Token 上限",
|
||||
"temperature": "溫度",
|
||||
"imageInput": "圖像輸入",
|
||||
"imageInputHelp": "關閉後,含圖片的請求會略過此預設。",
|
||||
"reasoningEffort": "推理強度",
|
||||
"convertTitle": "轉換設定",
|
||||
"convertHelp": "將主模型和備用模型轉為預設",
|
||||
|
||||
@@ -1417,7 +1417,7 @@ export async function fetchSidebarState(
|
||||
function modelGenerationSettingsPayload(
|
||||
configuration: Pick<
|
||||
ModelConfigurationCreate,
|
||||
"maxTokens" | "contextWindowTokens" | "temperature" | "reasoningEffort" | "api" | "extraHeaders" | "extraQuery" | "extraBody"
|
||||
"maxTokens" | "contextWindowTokens" | "temperature" | "reasoningEffort" | "supportsImages" | "api" | "extraHeaders" | "extraQuery" | "extraBody"
|
||||
>,
|
||||
): Record<string, unknown> {
|
||||
const payload: Record<string, unknown> = {};
|
||||
@@ -1430,6 +1430,9 @@ function modelGenerationSettingsPayload(
|
||||
if (configuration.temperature !== undefined) {
|
||||
payload.temperature = configuration.temperature;
|
||||
}
|
||||
if (configuration.supportsImages !== undefined) {
|
||||
payload.supports_images = configuration.supportsImages;
|
||||
}
|
||||
if (configuration.reasoningEffort !== undefined) {
|
||||
payload.reasoning_effort = configuration.reasoningEffort ?? "";
|
||||
}
|
||||
|
||||
@@ -754,6 +754,7 @@ export interface SettingsPayload {
|
||||
context_window_tokens: number;
|
||||
temperature: number;
|
||||
reasoning_effort: string | null;
|
||||
supports_images?: boolean;
|
||||
api?: ModelAPIConfig | null;
|
||||
timezone: string;
|
||||
tool_hint_max_length: number;
|
||||
@@ -772,6 +773,7 @@ export interface SettingsPayload {
|
||||
temperature: number;
|
||||
reasoning_effort: string | null;
|
||||
reasoning_effort_values?: string[];
|
||||
supports_images?: boolean;
|
||||
api?: ModelAPIConfig | null;
|
||||
extra_headers?: Record<string, string> | null;
|
||||
extra_query?: Record<string, string> | null;
|
||||
@@ -1407,6 +1409,7 @@ export interface ModelConfigurationCreate {
|
||||
contextWindowTokens?: number;
|
||||
temperature?: number;
|
||||
reasoningEffort?: string | null;
|
||||
supportsImages?: boolean;
|
||||
api?: ModelAPIConfig | null;
|
||||
extraHeaders?: string;
|
||||
extraQuery?: string;
|
||||
@@ -1422,6 +1425,7 @@ export interface ModelConfigurationUpdate {
|
||||
contextWindowTokens?: number;
|
||||
temperature?: number;
|
||||
reasoningEffort?: string | null;
|
||||
supportsImages?: boolean;
|
||||
api?: ModelAPIConfig | null;
|
||||
extraHeaders?: string;
|
||||
extraQuery?: string;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";
|
||||
import { act, cleanup, fireEvent, screen, waitFor, within } from "@testing-library/react";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import type { ProviderModelsPayload, SettingsPayload } from "@/lib/types";
|
||||
import { requestMutationMock, jsonResponse, settingsPayload, renderSettingsView as renderSettingsViewBase, openPopover, installSettingsViewTestHooks } from "@/tests/settings-test-utils";
|
||||
@@ -1194,6 +1194,7 @@ describe("Settings models", () => {
|
||||
...payload.model_presets[0],
|
||||
name: "Writer",
|
||||
label: "Writer",
|
||||
supports_images: false,
|
||||
active: false,
|
||||
model: "openai/gpt-4o-mini",
|
||||
provider: "openai",
|
||||
@@ -1246,6 +1247,8 @@ describe("Settings models", () => {
|
||||
target: { value: "openai/gpt-4o-mini" },
|
||||
});
|
||||
fireEvent.keyDown(modelSearch, { key: "Enter" });
|
||||
expect(screen.getByRole("switch", { name: "Image input" })).toBeChecked();
|
||||
fireEvent.click(screen.getByRole("switch", { name: "Image input" }));
|
||||
const saveButton = presetSaveButton();
|
||||
expect(saveButton).toBeEnabled();
|
||||
fireEvent.click(saveButton);
|
||||
@@ -1254,8 +1257,8 @@ describe("Settings models", () => {
|
||||
expect(requestMutationMock).toHaveBeenCalledWith(
|
||||
"settings.model_configuration.create",
|
||||
expect.objectContaining(optimized
|
||||
? { name: "Writer", append_to_order: true, include_usage: false }
|
||||
: { name: "Writer" }),
|
||||
? { name: "Writer", supports_images: false, append_to_order: true, include_usage: false }
|
||||
: { name: "Writer", supports_images: false }),
|
||||
20_000,
|
||||
);
|
||||
if (optimized) {
|
||||
@@ -2277,3 +2280,56 @@ describe("Settings models", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("Model preset image input", () => {
|
||||
installSettingsViewTestHooks();
|
||||
|
||||
it("saves image input capability per preset and restores it after reopening", async () => {
|
||||
let { payload } = settingsPayloadWithBackup();
|
||||
vi.stubGlobal("fetch", vi.fn(async () => jsonResponse(payload)));
|
||||
requestMutationMock.mockImplementation(async (_action: string, args: Record<string, unknown>) => {
|
||||
payload = {
|
||||
...payload,
|
||||
model_presets: payload.model_presets.map((preset) => preset.name === args.name
|
||||
? { ...preset, supports_images: args.supports_images as boolean } : preset),
|
||||
};
|
||||
return payload;
|
||||
});
|
||||
renderSettingsView({ initialSection: "models", initialSettings: payload });
|
||||
await togglePresetEditor();
|
||||
const control = screen.getByRole("switch", { name: "Image input" });
|
||||
expect(control).toBeChecked();
|
||||
fireEvent.click(control);
|
||||
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
|
||||
"settings.model_configuration.update", { name: "primary", supports_images: false, include_usage: false }, 20_000,
|
||||
));
|
||||
await waitFor(() => expect(control).toBeEnabled());
|
||||
expect(control).not.toBeChecked();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Close" }));
|
||||
await togglePresetEditor("backup");
|
||||
expect(screen.getByRole("switch", { name: "Image input" })).toBeChecked();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Close" }));
|
||||
expect(requestMutationMock).toHaveBeenCalledTimes(1);
|
||||
cleanup();
|
||||
renderSettingsView({ initialSection: "models", initialSettings: payload });
|
||||
await togglePresetEditor();
|
||||
expect(screen.getByRole("switch", { name: "Image input" })).not.toBeChecked();
|
||||
});
|
||||
|
||||
it("starts new presets with image input enabled and discards cancelled changes", async () => {
|
||||
const { payload } = settingsPayloadWithBackup();
|
||||
payload.model_presets[0] = { ...payload.model_presets[0], supports_images: false };
|
||||
vi.stubGlobal("fetch", vi.fn(async () => jsonResponse(payload)));
|
||||
renderSettingsView({ initialSection: "models", initialSettings: payload });
|
||||
fireEvent.click(screen.getByRole("button", { name: "New preset" }));
|
||||
const control = screen.getByRole("switch", { name: "Image input" });
|
||||
expect(control).toBeChecked();
|
||||
fireEvent.click(control);
|
||||
expect(control).not.toBeChecked();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
|
||||
expect(requestMutationMock).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole("button", { name: "New preset" }));
|
||||
expect(screen.getByRole("switch", { name: "Image input" })).toBeChecked();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user