Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(deepseek): align model capabilities with the official API (#6283)
chengyongru0a8b18fa58ae
diff --git a/docs/providers.md b/docs/providers.mdindex 01d7ebafd..38bf75bc4 100644--- a/docs/providers.md+++ b/docs/providers.md@@ -268,7 +268,9 @@ For OpenCode Go, switch the provider block and preset:</details>-OpenCode documents model IDs with `opencode/<model-id>` for Zen and `opencode-go/<model-id>` for Go. nanobot accepts those prefixes and strips them before sending the request to OpenCode. Use model IDs that OpenCode lists under the `chat/completions` endpoint; models listed only under `responses`, `messages`, or provider-specific endpoints are not handled by this OpenAI-compatible provider path.+OpenCode documents model IDs with `opencode/<model-id>` for Zen and `opencode-go/<model-id>` for Go. nanobot accepts those prefixes and strips them before sending the request to OpenCode. Choose a model served through Chat Completions or Responses by the matching Zen or Go service; models that require Anthropic Messages or another provider-specific API are not supported by these connections.++Leave API selection on **Auto** for OpenCode Go's `muse-spark-1.2-contributor` and `muse-spark-1.3-contributor`; these models use Responses automatically. Other models use Chat Completions by default. If another model requires Responses, select it in the preset's **Advanced options** only when the service supports it. See [preset API settings](./configuration.md#preset-request-api).### Anthropic Direct@@ -360,11 +362,15 @@ For a named custom provider serving Anthropic Messages, set `providers.<name>.apReplace the model with a model ID available to your account. Leave API selection on Auto unless you need to choose Chat Completions or Responses in the preset's **Advanced options**. See [preset API settings](./configuration.md#preset-request-api) for WebUI and JSON configuration. `providers.openai.api` sets the connection default; explicit presets override it. If your configuration still uses `apiType`, follow the [migration instructions](./configuration.md#legacy-openai-api-selector-migration).-Direct OpenAI Responses, OpenAI Codex, Azure OpenAI Responses, and eligible GitHub Copilot models can retain server-provided conversation state; [native context compaction](./configuration.md#responses-state-and-compaction) depends on provider support. The WebUI offers switches for OpenAI web search, Codex Fast mode, and Grok X Search.+### DeepSeek++Select **DeepSeek** in **Settings → Models**. Use `deepseek-flash` for text and image input, or `deepseek-v4-pro` for text-only input. The official service also accepts `deepseek-v4-flash` and `deepseek-v4-flash-vision-exp` as Flash aliases; see [current model details](https://api-docs.deepseek.com/quick_start/pricing) for availability.++Known Flash and Pro models offer `none`, `low`, `high`, and `max` reasoning settings. Leave reasoning effort empty to follow the provider default (currently thinking enabled at `high`), or choose `none` to disable thinking. The output budget covers both reasoning and the final answer.-DeepSeek's `deepseek-v4-flash`, `deepseek-v4-pro`, and `deepseek-v4-flash-vision-exp` automatically use its native Responses API. For web search, use nanobot's [web search tool](./configuration.md#web-search). OpenCode Go's `muse-spark-1.2-contributor` and `muse-spark-1.3-contributor` also use Responses by default.+**Auto** uses Responses for these models at the official endpoint (`https://api.deepseek.com`, with or without `/v1`). With a proxy, keep the model ID it documents: `deepseek-flash` defaults to Chat Completions on other endpoints, while the V4 names above default to Responses. Select Responses explicitly for `deepseek-flash` only if your proxy supports it; see [preset API settings](./configuration.md#preset-request-api).-The `deepseek-flash` alias uses Responses automatically at `https://api.deepseek.com`, including the `/v1` form. With a different `providers.deepseek.apiBase`, Auto uses Chat Completions for this alias. Select Responses in the preset if the proxy supports it. The V4 model names listed above use Responses with either endpoint configuration.+For web search, configure nanobot's [web search tool](./guides/configure-web-search.md). Selecting a DeepSeek model does not enable DeepSeek-hosted search.### Custom OpenAI-Compatible Endpoint@@ -704,6 +710,10 @@ Pin `provider` in presets when using gateway catalog IDs such as `anthropic/clauModel presets are the recommended model configuration surface. Use them when you want named model choices, runtime `/model` switching, or reusable fallback targets.+When available, the selected provider's model catalog supplies reasoning-effort suggestions; you can still enter a custom value. Choosing a catalog model for a new preset can initialize its context window. Existing presets and manually entered context values are preserved, and catalog output limits do not raise the preset's output budget. See [preset fields](./configuration.md#model-presets) for configuration details.++Direct OpenAI Responses, OpenAI Codex, Azure OpenAI Responses, and eligible GitHub Copilot models can retain server-provided conversation state; [native context compaction](./configuration.md#responses-state-and-compaction) depends on provider support. The WebUI offers switches for OpenAI web search, Codex Fast mode, and Grok X Search.+<details><summary>Manual configuration</summary>diff --git a/nanobot/providers/openai_compat_provider.py b/nanobot/providers/openai_compat_provider.pyindex ca0b022d5..322dcd6e4 100644--- a/nanobot/providers/openai_compat_provider.py+++ b/nanobot/providers/openai_compat_provider.py@@ -98,10 +98,6 @@ _KIMI_SERVER_MANAGED_TEMPERATURE_MODELS: frozenset[str] = frozenset({"kimi-k2.5","kimi-k2.6",})-_DEEPSEEK_MULTIMODAL_MODELS: frozenset[str] = frozenset({- "deepseek-flash",- "deepseek-v4-flash-vision-exp",-})_TEXT_TOOL_CALL_RE = re.compile(r"<tool_call>\s*(.*?)\s*</tool_call>", re.DOTALL)# Thinking-capable MiMo models per Xiaomi docs (see# tests/providers/test_xiaomi_mimo_thinking.py). mimo-v2-flash is omitted@@ -690,11 +686,10 @@ class OpenAICompatProvider(LLMProvider):sanitized = LLMProvider._sanitize_request_messages(messages, _ALLOWED_MSG_KEYS)id_map: dict[str, str] = {}pending_tool_ids: dict[str, deque[str]] = {}- is_deepseek = bool(self._spec and self._spec.name == "deepseek")- model_name = model or self.default_model- force_string_content = (- is_deepseek and _model_slug(model_name) not in _DEEPSEEK_MULTIMODAL_MODELS- )+ force_string_content = False+ if self._spec and self._spec.name == "deepseek":+ metadata = self._spec.model_metadata(model or self.default_model)+ force_string_content = metadata is None or "image" not in metadata.input_modalitiesnormalize_tool_ids = self._should_normalize_tool_call_ids()strip_reasoning = bool(self._specdiff --git a/nanobot/providers/registry.py b/nanobot/providers/registry.pyindex 45c5a5f7a..2cf6efeed 100644--- a/nanobot/providers/registry.py+++ b/nanobot/providers/registry.py@@ -39,6 +39,11 @@ class ProviderModelSpec:reasoning_efforts: tuple[str, ...] = ()supports_backend_search: bool = Falseapi: ModelAPICapabilities | None = None+ aliases: tuple[str, ...] = ()+ max_output_tokens: int | None = None+ input_modalities: tuple[str, ...] = ()+ output_modalities: tuple[str, ...] = ()+ default_reasoning_effort: str | None = None@dataclass(frozen=True)@@ -161,6 +166,14 @@ class ProviderSpec:return routed_modelreturn model+ def model_metadata(self, model: str) -> ProviderModelSpec | None:+ """Look up curated metadata without rewriting configured or wire model IDs."""+ model_id = model.rsplit("/", 1)[-1].lower()+ return next((+ entry for entry in self.builtin_models+ if model_id == entry.id or model_id in entry.aliases+ ), None)+def default_model_api(self,model: str,@@ -197,6 +210,8 @@ class ProviderSpec:# PROVIDERS — the registry. Order = priority. Copy any entry as template.# ---------------------------------------------------------------------------+_DEEPSEEK_REASONING_EFFORTS = ("none", "low", "high", "max")+PROVIDERS: tuple[ProviderSpec, ...] = (# === Custom (direct OpenAI-compatible endpoint) ========================ProviderSpec(@@ -621,6 +636,27 @@ PROVIDERS: tuple[ProviderSpec, ...] = (backend="openai_compat",default_api_base="https://api.deepseek.com",thinking_style="thinking_type",+ builtin_models=(+ ProviderModelSpec(+ id="deepseek-flash",+ aliases=("deepseek-v4-flash", "deepseek-v4-flash-vision-exp"),+ context_window=1_000_000,+ max_output_tokens=393_216,+ input_modalities=("text", "image"),+ output_modalities=("text",),+ reasoning_efforts=_DEEPSEEK_REASONING_EFFORTS,+ default_reasoning_effort="high",+ ),+ ProviderModelSpec(+ id="deepseek-v4-pro",+ context_window=1_000_000,+ max_output_tokens=393_216,+ input_modalities=("text",),+ output_modalities=("text",),+ reasoning_efforts=_DEEPSEEK_REASONING_EFFORTS,+ default_reasoning_effort="high",+ ),+ ),responses=ResponsesCapabilities(models=("deepseek-v4-flash",diff --git a/nanobot/webui/settings_models.py b/nanobot/webui/settings_models.pyindex c6cb995ec..10757e62a 100644--- a/nanobot/webui/settings_models.py+++ b/nanobot/webui/settings_models.py@@ -21,7 +21,7 @@ from contextlib import suppressfrom dataclasses import dataclassfrom datetime import date, datetime, timezonefrom pathlib import Path-from typing import TYPE_CHECKING, Any, Awaitable, Callable, TypedDict, cast+from typing import TYPE_CHECKING, Any, Awaitable, Callable, NotRequired, TypedDict, castimport httpx@@ -40,7 +40,13 @@ from nanobot.providers.oauth_model_catalog import (get_oauth_model_catalog,invalidate_oauth_model_catalog,)-from nanobot.providers.registry import PROVIDERS, ProviderSpec, create_dynamic_spec, find_by_name+from nanobot.providers.registry import (+ PROVIDERS,+ ProviderModelSpec,+ ProviderSpec,+ create_dynamic_spec,+ find_by_name,+)from nanobot.providers.request_overrides import isolate_request_overridesfrom nanobot.providers.routing import resolve_automatic_model_api, resolve_model_apifrom nanobot.webui import request_settings@@ -100,6 +106,22 @@ class ModelSettingsPayload(TypedDict):providers: list[dict[str, Any]]+class ProviderModelMetadataPayload(TypedDict, total=False):+ max_output_tokens: int+ input_modalities: list[str]+ output_modalities: list[str]+ reasoning_efforts: list[str]+ default_reasoning_effort: str+++class ProviderModelRowPayload(ProviderModelMetadataPayload):+ id: str+ label: str | None+ owned_by: str | None+ context_window: int | None+ description: NotRequired[str]++_OAUTH_PROXY_PROVIDERS = {"openai_codex", "xai_grok"}_WEBUI_OAUTH_TIMEOUT_S = 600_MODEL_CONFIGURATION_SLUG_RE = re.compile(r"[^a-z0-9_-]+")@@ -437,12 +459,12 @@ def model_catalog_kind(spec: Any) -> str:return "official"-def _model_id_from_row(row: Any) -> str | None:+def _model_id_from_row(row: object) -> str | None:if isinstance(row, str):return row.strip() or Noneif not isinstance(row, dict):return None- row_mapping = cast(dict[str, Any], row)+ row_mapping = cast(dict[str, object], row)for key in ("id", "name", "model"):value = row_mapping.get(key)if isinstance(value, str) and value.strip():@@ -450,10 +472,31 @@ def _model_id_from_row(row: Any) -> str | None:return None-def _model_context_window(row: Any) -> int | None:+def _model_positive_int(value: object) -> int | None:+ if isinstance(value, int) and not isinstance(value, bool) and value > 0:+ return value+ return None+++def _model_string_values(value: object) -> list[str] | None:+ if not isinstance(value, list):+ return None+ values: list[str] = []+ seen: set[str] = set()+ for item in cast(list[object], value):+ if not isinstance(item, str):+ return None+ normalized = item.strip()+ if normalized and normalized not in seen:+ seen.add(normalized)+ values.append(normalized)+ return values+++def _model_context_window(row: object) -> int | None:if not isinstance(row, dict):return None- row_mapping = cast(dict[str, Any], row)+ row_mapping = cast(dict[str, object], row)for key in ("context_window","context_length",@@ -462,17 +505,20 @@ def _model_context_window(row: Any) -> int | None:"max_input_tokens",):value = row_mapping.get(key)- if isinstance(value, int) and value > 0:- return value- if isinstance(value, float) and value > 0:- return int(value)+ parsed = _model_positive_int(value)+ if parsed is not None:+ return parsed+ if isinstance(value, float) and math.isfinite(value) and value > 0:+ parsed = _model_positive_int(int(value))+ if parsed is not None:+ return parsedreturn None-def _model_shutdown_date(row: Any) -> date | None:+def _model_shutdown_date(row: object) -> date | None:if not isinstance(row, dict):return None- row_mapping = cast(dict[str, Any], row)+ row_mapping = cast(dict[str, object], row)raw = row_mapping.get("shutdown_date")if not isinstance(raw, str) or not raw.strip():return None@@ -482,7 +528,7 @@ def _model_shutdown_date(row: Any) -> date | None:return None-def _model_catalog_row_active(row: Any, *, on: date | None = None) -> bool:+def _model_catalog_row_active(row: object, *, on: date | None = None) -> bool:"""True when a provider catalog row should stay in the advisory model list."""shutdown = _model_shutdown_date(row)if shutdown is None:@@ -491,15 +537,71 @@ def _model_catalog_row_active(row: Any, *, on: date | None = None) -> bool:return shutdown > reference-def _model_row_payload(row: Any) -> dict[str, Any] | None:+def _model_metadata_payload(+ row: object,+ metadata: ProviderModelSpec | None,+) -> ProviderModelMetadataPayload:+ row_mapping = cast(dict[str, object], row) if isinstance(row, dict) else {}+ effort = row_mapping.get("effort")+ effort_mapping = cast(dict[str, object], effort) if isinstance(effort, dict) else {}+ max_output_tokens = _model_positive_int(row_mapping.get("max_output_tokens"))+ input_modalities = _model_string_values(row_mapping.get("input_modalities"))+ output_modalities = _model_string_values(row_mapping.get("output_modalities"))+ reasoning_efforts = _model_string_values(effort_mapping.get("supported_levels"))+ raw_default = effort_mapping.get("default_level")+ default_effort = raw_default.strip() if isinstance(raw_default, str) else None++ if metadata is not None:+ if max_output_tokens is None:+ max_output_tokens = metadata.max_output_tokens+ if input_modalities is None and metadata.input_modalities:+ input_modalities = list(metadata.input_modalities)+ if output_modalities is None and metadata.output_modalities:+ output_modalities = list(metadata.output_modalities)+ if reasoning_efforts is None and metadata.reasoning_efforts:+ reasoning_efforts = list(metadata.reasoning_efforts)+ elif (+ reasoning_efforts is not None+ and "none" in metadata.reasoning_efforts+ and "none" not in reasoning_efforts+ ):+ # Catalogs may list only enabled thinking levels, not the explicit off control.+ reasoning_efforts = ["none", *reasoning_efforts]+ if default_effort not in (reasoning_efforts or []):+ default_effort = metadata.default_reasoning_effort++ payload: ProviderModelMetadataPayload = {}+ if max_output_tokens is not None:+ payload["max_output_tokens"] = max_output_tokens+ if input_modalities is not None:+ payload["input_modalities"] = input_modalities+ if output_modalities is not None:+ payload["output_modalities"] = output_modalities+ if reasoning_efforts is not None:+ payload["reasoning_efforts"] = reasoning_efforts+ if default_effort and default_effort in reasoning_efforts:+ payload["default_reasoning_effort"] = default_effort+ return payload+++def _model_row_payload(+ row: object,+ *,+ spec: ProviderSpec | None = None,+) -> ProviderModelRowPayload | None:model_id = _model_id_from_row(row)if not model_id:return None+ metadata = spec.model_metadata(model_id) if spec is not None else None+ context_window = _model_context_window(row)+ if context_window is None and metadata is not None:+ context_window = metadata.context_window+ metadata_payload = _model_metadata_payload(row, metadata)label: str | None = Nonedescription: str | None = Noneowned_by: str | None = Noneif isinstance(row, dict):- row_mapping = cast(dict[str, Any], row)+ row_mapping = cast(dict[str, object], row)raw_label = row_mapping.get("display_name") or row_mapping.get("label") or row_mapping.get("name")if isinstance(raw_label, str) and raw_label.strip() and raw_label.strip() != model_id:label = raw_label.strip()@@ -509,27 +611,32 @@ def _model_row_payload(row: Any) -> dict[str, Any] | None:raw_owner = row_mapping.get("owned_by") or row_mapping.get("owner") or row_mapping.get("organization")if isinstance(raw_owner, str) and raw_owner.strip():owned_by = raw_owner.strip()- payload = {+ payload: ProviderModelRowPayload = {"id": model_id,"label": label,"owned_by": owned_by,- "context_window": _model_context_window(row),+ "context_window": context_window,+ **metadata_payload,}if description:payload["description"] = descriptionreturn payload-def _extract_model_rows(body: Any) -> list[dict[str, Any]]:- raw_rows = cast(dict[str, Any], body).get("data") if isinstance(body, dict) else body+def _extract_model_rows(+ body: object,+ *,+ spec: ProviderSpec | None = None,+) -> list[ProviderModelRowPayload]:+ raw_rows = cast(dict[str, object], body).get("data") if isinstance(body, dict) else bodyif not isinstance(raw_rows, list):return []- rows: list[dict[str, Any]] = []+ rows: list[ProviderModelRowPayload] = []seen: set[str] = set()for raw_row in cast(list[object], raw_rows):if not _model_catalog_row_active(raw_row):continue- row = _model_row_payload(raw_row)+ row = _model_row_payload(raw_row, spec=spec)if row is None or row["id"] in seen:continueseen.add(row["id"])@@ -657,7 +764,7 @@ def provider_models_payload(follow_redirects=False,)response.raise_for_status()- rows = _extract_model_rows(response.json())+ rows = _extract_model_rows(response.json(), spec=spec)except httpx.HTTPStatusError as exc:status = exc.response.status_codeif status in {401, 403}:@@ -917,6 +1024,10 @@ def reasoning_effort_values_for(provider_name: str, model: str) -> list[str]:if implicit and any(pattern in model_lower for pattern in implicit):return [""]+ metadata = spec.model_metadata(model)+ if metadata is not None and metadata.reasoning_efforts:+ return ["", *metadata.reasoning_efforts]+remap = getattr(spec, "reasoning_effort_remap", ())if remap:wire_values: list[str] = []diff --git a/tests/providers/test_inline_images.py b/tests/providers/test_inline_images.pyindex e6c51e7e5..94120c528 100644--- a/tests/providers/test_inline_images.py+++ b/tests/providers/test_inline_images.py@@ -269,7 +269,7 @@ async def test_text_only_model_keeps_its_image_policy(image_peer, image_blocks,url, requests, _ = image_peerprovider = OpenAICompatProvider(api_key="fixture", api_base=f"{url}/v1", spec=find_by_name("deepseek"),- default_model="deepseek-v4-flash", extra_body={"tools": []},+ default_model="deepseek-v4-pro", extra_body={"tools": []},)try:result = await (provider.chat_stream if streaming else provider.chat)(_messages(image_blocks))diff --git a/tests/providers/test_openai_compat_spec.py b/tests/providers/test_openai_compat_spec.pyindex 95061f9db..0bc0e4051 100644--- a/tests/providers/test_openai_compat_spec.py+++ b/tests/providers/test_openai_compat_spec.py@@ -1700,6 +1700,7 @@ def test_deepseek_coerces_list_content_to_string() -> None:@pytest.mark.parametrize("model", ["deepseek-flash",+ "deepseek-v4-flash","deepseek-v4-flash-vision-exp",])@pytest.mark.parametrize("prefixed", [False, True])@@ -1743,6 +1744,28 @@ def test_deepseek_vision_preserves_multimodal_content(assert kw["messages"][0]["content"] == content[email protected]("responses", [False, True])+def test_deepseek_pro_remains_text_only(responses: bool) -> None:+ provider = OpenAICompatProvider(+ api_key="k", default_model="deepseek-v4-pro", spec=find_by_name("deepseek"),+ )+ build_request = provider._build_responses_body if responses else provider._build_kwargs+ body = build_request(+ messages=[{"role": "user", "content": [+ {"type": "text", "text": "describe the image"},+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}},+ ]}],+ tools=None, model="deepseek-v4-pro", max_tokens=1024,+ temperature=0.7, reasoning_effort=None, tool_choice=None,+ )+ if responses:+ assert body["input"] == [{+ "role": "user", "content": [{"type": "input_text", "text": "describe the image"}],+ }]+ else:+ assert body["messages"] == [{"role": "user", "content": "describe the image"}]++def test_non_deepseek_keeps_list_content() -> None:"""Only DeepSeek should force string content; OpenAI-compatible providers keep blocks."""spec = find_by_name("openai")diff --git a/tests/webui/test_settings_models.py b/tests/webui/test_settings_models.pyindex e4f22be83..aeac9fbc4 100644--- a/tests/webui/test_settings_models.py+++ b/tests/webui/test_settings_models.py@@ -1,10 +1,13 @@from __future__ import annotations+from collections.abc import Callablefrom typing import Any+import httpximport pytestfrom nanobot.config.schema import Config+from nanobot.providers.registry import find_by_namefrom nanobot.webui.settings_models import (WebUISettingsError,create_model_configuration,@@ -201,3 +204,166 @@ def test_provider_model_refresh_reaches_oauth_catalog(monkeypatch, provider, refprovider_models_payload(config, query, http_get=Mock())catalog.assert_called_once_with(provider, proxy=None, refresh=refresh)+++def _catalog_http_get(body: object) -> Callable[..., httpx.Response]:+ def get(url: str, **_kwargs: object) -> httpx.Response:+ return httpx.Response(200, json=body, request=httpx.Request("GET", url))++ return get+++def test_provider_catalog_normalizes_official_model_metadata_without_changing_budgets() -> None:+ config = Config()+ config.providers.deepseek.api_key = "fixture"+ before = config.model_dump()+ payload = provider_models_payload(config, {"provider": ["deepseek"]}, http_get=_catalog_http_get({+ "data": [{+ "id": "deepseek-flash",+ "name": "DeepSeek Flash",+ "owned_by": "deepseek",+ "context_window": 1_048_576,+ "max_output_tokens": 131_072,+ "input_modalities": [" text ", "image", "text", "future-signal"],+ "output_modalities": ["text", " text "],+ "effort": {+ "supported_levels": [" low ", "high", "max", "adaptive", "max"],+ "default_level": " adaptive ",+ },+ "api_capabilities": {"anthropic_messages": {"system_prompt_update": True}},+ "vendor_details": {"arbitrary": "not part of the DTO"},+ }],+ }))++ assert payload["status"] == "available"+ assert payload["model_count"] == 1+ assert payload["models"] == [{+ "id": "deepseek-flash",+ "label": "DeepSeek Flash",+ "owned_by": "deepseek",+ "context_window": 1_048_576,+ "max_output_tokens": 131_072,+ "input_modalities": ["text", "image", "future-signal"],+ "output_modalities": ["text"],+ "reasoning_efforts": ["none", "low", "high", "max", "adaptive"],+ "default_reasoning_effort": "adaptive",+ }]+ assert config.model_dump() == before+++def test_provider_catalog_enriches_legacy_known_ids_but_not_unknown_or_custom_models() -> None:+ spec = find_by_name("deepseek")+ assert spec is not None+ known_ids = [model_id for model in spec.builtin_models for model_id in (model.id, *model.aliases)]+ config = Config.model_validate({"providers": {+ "deepseek": {"apiKey": "fixture"},+ "tenant": {"apiKey": "fixture", "apiBase": "https://catalog.test/v1"},+ }})+ raw_rows = [{"id": model_id} for model_id in [*known_ids, "deepseek-unlisted"]]+ payload = provider_models_payload(+ config, {"provider": ["deepseek"]}, http_get=_catalog_http_get({"data": raw_rows}),+ )++ assert [row["id"] for row in payload["models"]] == [*known_ids, "deepseek-unlisted"]+ for row in payload["models"][:-1]:+ metadata = spec.model_metadata(row["id"])+ assert metadata is not None+ assert row["context_window"] == metadata.context_window+ assert row["max_output_tokens"] == metadata.max_output_tokens+ assert row["input_modalities"] == list(metadata.input_modalities)+ assert row["output_modalities"] == list(metadata.output_modalities)+ assert row["reasoning_efforts"] == list(metadata.reasoning_efforts)+ assert row["default_reasoning_effort"] == metadata.default_reasoning_effort+ assert payload["models"][-1] == {+ "id": "deepseek-unlisted", "label": None, "owned_by": None, "context_window": None,+ }++ custom = provider_models_payload(+ config, {"provider": ["tenant"]}, http_get=_catalog_http_get([{"id": known_ids[0]}]),+ )+ assert custom["models"] == [{+ "id": known_ids[0], "label": None, "owned_by": None, "context_window": None,+ }]+++def test_provider_catalog_discards_malformed_optional_fields_not_model_rows() -> None:+ config = Config()+ config.providers.deepseek.api_key = "fixture"+ payload = provider_models_payload(config, {"provider": ["deepseek"]}, http_get=_catalog_http_get({+ "data": [+ {+ "id": "invalid-types", "context_window": True, "max_output_tokens": True,+ "input_modalities": ["text", {"type": "image"}], "output_modalities": "text",+ "effort": {"supported_levels": ["low", 7], "default_level": {"level": "low"}},+ "api_capabilities": {"anthropic_messages": {}},+ },+ {+ "id": "future-model", "max_output_tokens": -1,+ "input_modalities": ["", " "], "output_modalities": {"text": True},+ "effort": {"supported_levels": [" none ", "adaptive", "none"], "default_level": "low"},+ },+ {+ "id": "legacy-context", "context_length": 8192.5, "max_output_tokens": 4096.5,+ "input_modalities": None, "output_modalities": [False], "effort": "high",+ },+ ],+ }))++ assert payload["status"] == "available"+ assert payload["model_count"] == 3+ assert payload["models"] == [+ {"id": "invalid-types", "label": None, "owned_by": None, "context_window": None},+ {+ "id": "future-model", "label": None, "owned_by": None, "context_window": None,+ "input_modalities": [], "reasoning_efforts": ["none", "adaptive"],+ },+ {"id": "legacy-context", "label": None, "owned_by": None, "context_window": 8192},+ ]+++def test_provider_catalog_combines_valid_online_fields_with_known_fallback() -> None:+ config = Config()+ config.providers.deepseek.api_key = "fixture"+ payload = provider_models_payload(config, {"provider": ["deepseek"]}, http_get=_catalog_http_get({+ "data": [{+ "id": "deepseek-flash", "max_output_tokens": True, "input_modalities": [],+ "effort": {"supported_levels": ["none", "adaptive"], "default_level": "high"},+ }],+ }))++ assert payload["models"] == [{+ "id": "deepseek-flash", "label": None, "owned_by": None, "context_window": 1_000_000,+ "max_output_tokens": 393_216, "input_modalities": [], "output_modalities": ["text"],+ "reasoning_efforts": ["none", "adaptive"],+ }]+++def test_known_reasoning_efforts_preserve_default_none_and_custom_roundtrips() -> None:+ config = Config()+ config.providers.deepseek.api_key = "fixture"+ name = create_model_configuration(config, {+ "name": ["Reasoning"], "provider": ["deepseek"], "model": ["deepseek-v4-flash"],+ "reasoning_effort": [""],+ }, oauth_status=_oauth_status)++ def saved_row() -> dict[str, Any]:+ roundtripped = Config.model_validate(config.model_dump())+ payload = model_settings_payload(roundtripped, oauth_status=_oauth_status)+ return next(row for row in payload["model_presets"] if row["name"] == name)++ assert saved_row()["reasoning_effort"] is None+ assert saved_row()["reasoning_effort_values"] == ["", "none", "low", "high", "max"]+ for effort in ("none", "provider-native-mode", ""):+ assert update_model_configuration(config, {+ "name": [name], "reasoning_effort": [effort],+ }, oauth_status=_oauth_status)+ assert saved_row()["reasoning_effort"] == (effort or None)++ unknown = create_model_configuration(config, {+ "name": ["Future"], "provider": ["deepseek"], "model": ["deepseek-unlisted"],+ "reasoning_effort": ["future-effort"],+ }, oauth_status=_oauth_status)+ row = next(row for row in model_settings_payload(config, oauth_status=_oauth_status)["model_presets"]+ if row["name"] == unknown)+ assert row["reasoning_effort"] == "future-effort"+ assert row["reasoning_effort_values"] == ["", "low", "medium", "high"]diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.tsindex 997acae45..83c65a872 100644--- a/webui/src/lib/types.ts+++ b/webui/src/lib/types.ts@@ -613,7 +613,11 @@ interface ProviderModelInfo {description?: string | null;owned_by?: string | null;context_window?: number | null;+ max_output_tokens?: number;+ input_modalities?: string[];+ output_modalities?: string[];reasoning_efforts?: string[];+ default_reasoning_effort?: string;supports_backend_search?: boolean;api?: ModelAPIConfig | null;}diff --git a/webui/src/tests/settings-models.test.tsx b/webui/src/tests/settings-models.test.tsxindex f0d3bd9f7..a2bdcd3b2 100644--- a/webui/src/tests/settings-models.test.tsx+++ b/webui/src/tests/settings-models.test.tsx@@ -1,6 +1,6 @@import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";import { expect, it, vi } from "vitest";-import type { SettingsPayload } from "@/lib/types";+import type { ProviderModelsPayload, SettingsPayload } from "@/lib/types";import { requestMutationMock, jsonResponse, settingsPayload, renderSettingsView, openPopover, installSettingsViewTestHooks } from "@/tests/settings-test-utils";@@ -2031,25 +2031,40 @@ describe("Settings models", () => {));});- it("offers model-specific reasoning levels and retains manual values", async () => {+ it("offers catalog reasoning levels including max and none, distinct from Default, and retains manual values", async () => {const payload = settingsPayload();- payload.model_presets[0].provider = "openai";+ payload.model_presets[0].provider = "deepseek";+ payload.model_presets[0].resolved_provider = "deepseek";+ payload.model_presets[0].model = "deepseek-flash";payload.model_presets[0].reasoning_effort = "high";- payload.providers = [{ name: "openai", label: "OpenAI", configured: true }];- vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => String(input).includes("/provider-models?")- ? jsonResponse({ provider: "openai", status: "available", catalog_kind: "official", models: [- { id: payload.model_presets[0].model, reasoning_efforts: ["low", "high"] },+ payload.model_presets[0].reasoning_effort_values = ["", "low", "medium", "high"];+ payload.providers = [{ name: "deepseek", label: "DeepSeek", configured: true }];+ const catalog: ProviderModelsPayload = {+ provider: "deepseek", label: "DeepSeek", status: "available", catalog_kind: "official",+ models: [+ {+ id: payload.model_presets[0].model, max_output_tokens: 393_216,+ input_modalities: ["text", "image"], output_modalities: ["text"],+ reasoning_efforts: ["none", "low", "high", "max"], default_reasoning_effort: "high",+ },{ id: "another-model", reasoning_efforts: ["ultra"] },- ], model_count: 2 }) : jsonResponse(payload)));+ ], model_count: 2,+ };+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => String(input).includes("/provider-models?")+ ? jsonResponse(catalog) : jsonResponse(payload)));requestMutationMock.mockResolvedValue(payload);renderSettingsView({ initialSection: "models", initialSettings: payload });await togglePresetEditor();const input = screen.getByRole("combobox", { name: "Reasoning effort" });fireEvent.click(input);- fireEvent.click(await screen.findByRole("option", { name: "low", exact: true }));- await waitFor(() => expect(input).toHaveValue("low"));+ fireEvent.click(await screen.findByRole("option", { name: "max", exact: true }));+ await waitFor(() => expect(input).toHaveValue("max"));fireEvent.click(input);expect(screen.queryByRole("option", { name: "ultra", exact: true })).not.toBeInTheDocument();+ expect(screen.queryByRole("option", { name: "medium", exact: true })).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("option", { name: "none", exact: true }));+ await waitFor(() => expect(input).toHaveValue("none"));+ fireEvent.click(input);fireEvent.click(screen.getByRole("option", { name: "Default", exact: true }));await waitFor(() => expect(input).toHaveValue(""));fireEvent.click(input);