Skip to content

Your lightweight open-source personal agent.

feat(webui): show resolved Auto API in preset selector

chengyongru73a27e07263e
diff --git a/docs/configuration.md b/docs/configuration.md
index 44b2ec70d..94e7289ef 100644
--- a/docs/configuration.md
+++ b/docs/configuration.md
@@ -1468,7 +1468,7 @@ Set `agents.defaults.modelPreset` to choose the preset followed by sessions that
### Preset request API
-Leave API selection on **Automatic (recommended)** unless your provider requires a specific endpoint. For OpenAI-compatible providers, including custom gateways, and GitHub Copilot, a preset can choose Responses or Chat Completions. Credentials and endpoint URLs stay in the provider. Two presets sharing a provider can select different APIs.
+Leave API selection on **Auto** unless your provider requires a specific endpoint. For OpenAI-compatible providers, including custom gateways, and GitHub Copilot, a preset can choose Responses or Chat Completions. Credentials and endpoint URLs stay in the provider. Two presets sharing a provider can select different APIs.
```json
{
@@ -1490,9 +1490,9 @@ Leave API selection on **Automatic (recommended)** unless your provider requires
Omit `api` or set it to `null` for automatic routing. An explicit declaration overrides provider API defaults, including legacy `providers.openai.apiType`. Automatic Copilot routing uses the account's last successfully discovered `supported_endpoints` when available; other automatic routes use registry defaults. Custom gateways default to Chat Completions until Responses support is declared. Protocol behavior such as reasoning replay and native compaction remains provider-owned; declaring Responses support does not enable OpenAI-native compaction on a custom gateway.
-In the WebUI, open **Settings → Models → a preset → API connection**. Choose **Automatic (recommended)**, **Responses**, or **Chat Completions**. Selecting Responses also reveals **Try Chat Completions if Responses is unsupported**, which starts off when selecting Responses and requires the same model to support both endpoints. The explanation below the selector describes the chosen behavior.
+In the WebUI, open **Settings → Models → a preset → API connection**. Choose **Auto**, **Responses**, or **Chat Completions**. Auto shows the default API in parentheses, such as **Auto (Responses)**, and updates when the provider, model, or reasoning setting changes. The gateway resolves this default using the same rules as model requests, without probing remote endpoints. The label describes the default preference; compatibility failures can still activate permitted Chat fallback. Hosts that do not advertise API resolution show **Auto** without a resolved label. Selecting Responses also reveals **Try Chat Completions if Responses is unsupported**, which starts off when selecting Responses and requires the same model to support both endpoints.
-Every provider adapter declares its request formats in `nanobot/providers/registry.py`. OpenAI Codex, xAI Grok subscriptions, and the Azure OpenAI adapter use Responses; Anthropic uses Messages, and Bedrock uses Converse. The WebUI shows these fixed connections with an explanation instead of an editable selector. Preset declarations cannot enable a format the adapter does not implement. An OpenAI-compatible adapter implementing both formats does not guarantee that a particular remote model supports both.
+Every provider adapter declares its request formats in `nanobot/providers/registry.py`. OpenAI Codex, xAI Grok subscriptions, and the Azure OpenAI adapter use Responses; Anthropic uses Messages, and Bedrock uses Converse. The WebUI shows the protocol name for these fixed connections instead of an editable selector. Preset declarations cannot enable a format the adapter does not implement. An OpenAI-compatible adapter implementing both formats does not guarantee that a particular remote model supports both.
Changing a preset's model or provider resets its API declaration to automatic unless the same update supplies a new declaration. Each fallback preset retains its own declaration. Legacy direct `agents.defaults.api` and inline fallback `api` values are preserved when converting to named presets.
diff --git a/nanobot/providers/factory.py b/nanobot/providers/factory.py
index b56031871..c2a1a09e1 100644
--- a/nanobot/providers/factory.py
+++ b/nanobot/providers/factory.py
@@ -8,7 +8,7 @@ from pathlib import Path
from nanobot.config.schema import Config, InlineFallbackConfig, ModelPresetConfig, ProviderConfig
from nanobot.providers.base import GenerationSettings, LLMProvider
from nanobot.providers.fallback_provider import FallbackProvider
-from nanobot.providers.registry import ProviderSpec, create_dynamic_spec, find_by_name
+from nanobot.providers.registry import ProviderAPI, ProviderSpec, create_dynamic_spec, find_by_name
@dataclass(frozen=True)
@@ -133,6 +133,34 @@ def _resolve_provider_setup(
)
+def resolve_automatic_model_api(
+ config: Config, *, preset: ModelPresetConfig,
+) -> tuple[str, ProviderAPI]:
+ """Preview the default request API without live requests or circuit-breaker state."""
+ setup = _resolve_provider_setup(config, preset=preset)
+ spec = setup.spec
+ if spec is None:
+ return setup.provider_name, "chat_completions"
+ if len(spec.request_apis) == 1:
+ return setup.provider_name, spec.request_apis[0]
+ provider_config = setup.provider_config
+ if setup.backend == "github_copilot":
+ from nanobot.providers.github_copilot_provider import cached_github_copilot_model_api
+
+ api = cached_github_copilot_model_api(
+ setup.model, provider_config.proxy if provider_config else None,
+ )
+ if api is not None:
+ return setup.provider_name, api.preferred_api
+ api = spec.default_model_api(
+ setup.model, preset.reasoning_effort,
+ api_base=config.get_api_base(setup.model, preset=preset),
+ api_type=provider_config.api_type if provider_config else "auto",
+ extra_body=provider_config.extra_body if provider_config else None,
+ )
+ return setup.provider_name, api.preferred_api
+
+
def validate_provider_setup(
config: Config,
*,
diff --git a/nanobot/providers/github_copilot_provider.py b/nanobot/providers/github_copilot_provider.py
index 2f6d0845e..3c1f07a03 100644
--- a/nanobot/providers/github_copilot_provider.py
+++ b/nanobot/providers/github_copilot_provider.py
@@ -241,10 +241,9 @@ class GitHubCopilotProvider(OpenAICompatProvider):
) -> ModelAPICapabilities:
if self._preset_model_api is not None:
return self._preset_model_api
- catalog = _GITHUB_COPILOT_MODEL_CATALOG.peek(cache_key=_copilot_catalog_cache_key(self._proxy))
- row = catalog.find(model or self.default_model) if catalog is not None else None
- if row is not None and row.api is not None:
- return row.api
+ api = cached_github_copilot_model_api(model or self.default_model, self._proxy)
+ if api is not None:
+ return api
return super()._model_api_capabilities(model, reasoning_effort)
async def _get_copilot_access_token(self) -> str:
@@ -349,6 +348,15 @@ class GitHubCopilotProvider(OpenAICompatProvider):
)
+def cached_github_copilot_model_api(
+ model: str, proxy: str | None = None,
+) -> ModelAPICapabilities | None:
+ """Read the account's known model APIs without refreshing the catalog."""
+ catalog = _GITHUB_COPILOT_MODEL_CATALOG.peek(cache_key=_copilot_catalog_cache_key(proxy))
+ row = catalog.find(model) if catalog is not None else None
+ return row.api if row is not None else None
+
+
def get_github_copilot_model_catalog(
proxy: str | None = None,
) -> OAuthModelCatalogSnapshot:
diff --git a/nanobot/providers/openai_compat_provider.py b/nanobot/providers/openai_compat_provider.py
index ebb3a74ac..7a03fe1eb 100644
--- a/nanobot/providers/openai_compat_provider.py
+++ b/nanobot/providers/openai_compat_provider.py
@@ -21,7 +21,6 @@ from typing import TYPE_CHECKING, Any, cast
from urllib.parse import urlparse
from loguru import logger
-from pydantic.alias_generators import to_snake
from nanobot.providers.base import (
LLMProvider,
@@ -36,7 +35,13 @@ from nanobot.providers.base import (
)
from nanobot.providers.images import prepare_inline_images
from nanobot.providers.openai_responses import ResponsesBackend, responses_state_matches
-from nanobot.providers.registry import ModelAPICapabilities, ResponsesCapabilities
+from nanobot.providers.registry import (
+ ModelAPICapabilities,
+ ResponsesCapabilities,
+ hosted_web_search_enabled,
+ is_direct_openai_base,
+ is_hosted_web_search_tool,
+)
if TYPE_CHECKING:
from openai import AsyncOpenAI as AsyncOpenAIType
@@ -51,19 +56,6 @@ AsyncOpenAI: Any = None
_GEMINI_SKIP_THOUGHT_SIGNATURE = "skip_thought_signature_validator"
-def _is_hosted_web_search_type(value: object) -> bool:
- return isinstance(value, str) and (
- value == "web_search" or value.startswith("web_search_")
- )
-
-
-def _is_hosted_web_search_tool(tool: object) -> bool:
- if not isinstance(tool, dict):
- return False
- tool_type = cast(dict[object, object], tool).get("type")
- return _is_hosted_web_search_type(tool_type)
-
-
def _is_named_function_tool(tool: object, name: str) -> bool:
"""Return whether a Responses tool is a function with the given name."""
if not isinstance(tool, dict):
@@ -160,10 +152,6 @@ def _model_slug(model_name: str) -> str:
return model_name.lower().rsplit("/", 1)[-1]
-def _provider_prefix_key(name: str) -> str:
- return to_snake(name.replace("-", "_")).lower()
-
-
def _requires_max_completion_tokens(model_name: str) -> bool:
"""Return True for models that require ``max_completion_tokens``."""
slug = _model_slug(model_name)
@@ -391,14 +379,6 @@ def _is_local_endpoint(
return addr.is_loopback or addr.is_private
-def _is_direct_openai_base(api_base: str | None) -> bool:
- """Return True for direct OpenAI endpoints, not generic OpenAI-compatible gateways."""
- if not api_base:
- return True
- normalized = api_base.strip().lower().rstrip("/")
- return "api.openai.com" in normalized and "openrouter" not in normalized
-
-
def _responses_circuit_key(
model: str | None,
default_model: str,
@@ -878,24 +858,7 @@ class OpenAICompatProvider(LLMProvider):
# ------------------------------------------------------------------
def _request_model_name(self, model_name: str) -> str:
- spec = self._spec
- if not spec or "/" not in model_name:
- return model_name
- if spec.strip_model_prefix:
- return model_name.split("/")[-1]
-
- route_prefixes = getattr(spec, "strip_model_prefixes", ())
- if not isinstance(route_prefixes, tuple) or not route_prefixes:
- return model_name
- typed_route_prefixes = cast(tuple[str, ...], route_prefixes)
- model_prefix, routed_model = model_name.split("/", 1)
- model_prefix_key = _provider_prefix_key(model_prefix)
- if any(
- _provider_prefix_key(prefix) == model_prefix_key
- for prefix in typed_route_prefixes
- ):
- return routed_model
- return model_name
+ return self._spec.request_model_name(model_name) if self._spec else model_name
@staticmethod
def _supports_temperature(
@@ -1129,22 +1092,12 @@ class OpenAICompatProvider(LLMProvider):
"""Apply a preset's declaration before the provider's curated defaults."""
if self._preset_model_api is not None:
return self._preset_model_api
- capabilities = self._responses_capabilities()
- if capabilities is None or self._api_type == "chat_completions":
+ if self._spec is None:
return ModelAPICapabilities()
- if self._api_type == "responses":
- return ModelAPICapabilities(("responses",), "responses")
- model_name = self._request_model_name(model or self.default_model)
- if self._hosted_web_search_enabled() and (
- capabilities.route_reasoning or capabilities.matches_model(model_name)
- ):
- return ModelAPICapabilities(("responses",), "responses")
- if (
- capabilities.requires_direct_openai_base
- and not _is_direct_openai_base(self._effective_base)
- ):
- return ModelAPICapabilities()
- return capabilities.model_api(model_name, reasoning_effort)
+ return self._spec.default_model_api(
+ model or self.default_model, reasoning_effort,
+ api_base=self._effective_base, api_type=self._api_type, extra_body=self._extra_body,
+ )
def _responses_is_required(
self, model: str | None = None, reasoning_effort: str | None = None,
@@ -1153,19 +1106,8 @@ class OpenAICompatProvider(LLMProvider):
return "chat_completions" not in api.supported_apis or self._hosted_web_search_enabled()
def _hosted_web_search_enabled(self) -> bool:
- extra_body = getattr(self, "_extra_body", {})
- configured_tools = extra_body.get("tools")
- if "tools" in extra_body:
- return isinstance(configured_tools, list) and any(
- _is_hosted_web_search_tool(tool)
- for tool in cast(list[object], configured_tools)
- )
- return bool(
- self._spec
- and any(
- _is_hosted_web_search_type(tool_type)
- for tool_type in getattr(self._spec, "responses_default_tools", ())
- )
+ return hosted_web_search_enabled(
+ self._extra_body, self._spec.responses_default_tools if self._spec else (),
)
def _responses_capabilities(self) -> ResponsesCapabilities | None:
@@ -1214,7 +1156,7 @@ class OpenAICompatProvider(LLMProvider):
return False
if (
capabilities.requires_direct_openai_base
- and not _is_direct_openai_base(self._effective_base)
+ and not is_direct_openai_base(self._effective_base)
):
return False
return True
@@ -1361,7 +1303,7 @@ class OpenAICompatProvider(LLMProvider):
for tool in cast(list[object], configured_tools):
if _is_named_function_tool(tool, "web_search"):
continue
- if _is_hosted_web_search_tool(tool):
+ if is_hosted_web_search_tool(tool):
if hosted_search_seen:
continue
hosted_search_seen = True
diff --git a/nanobot/providers/registry.py b/nanobot/providers/registry.py
index dfcbbbf0a..816e15ded 100644
--- a/nanobot/providers/registry.py
+++ b/nanobot/providers/registry.py
@@ -13,7 +13,7 @@ Every entry writes out all fields so you can copy-paste as a template.
from __future__ import annotations
from dataclasses import dataclass
-from typing import Any, Literal
+from typing import Any, Literal, cast
from pydantic.alias_generators import to_snake
@@ -23,6 +23,37 @@ ProviderAPI = Literal[
]
+def is_direct_openai_base(api_base: str | None) -> bool:
+ """Return whether the endpoint matches the direct OpenAI routing rule."""
+ if not api_base:
+ return True
+ normalized = api_base.strip().lower().rstrip("/")
+ return "api.openai.com" in normalized and "openrouter" not in normalized
+
+
+def is_hosted_web_search_type(value: object) -> bool:
+ return isinstance(value, str) and (
+ value == "web_search" or value.startswith("web_search_")
+ )
+
+
+def is_hosted_web_search_tool(tool: object) -> bool:
+ if not isinstance(tool, dict):
+ return False
+ return is_hosted_web_search_type(cast(dict[object, object], tool).get("type"))
+
+
+def hosted_web_search_enabled(
+ extra_body: dict[str, Any], default_tools: tuple[str, ...] = (),
+) -> bool:
+ if "tools" in extra_body:
+ tools = extra_body["tools"]
+ return isinstance(tools, list) and any(
+ is_hosted_web_search_tool(tool) for tool in cast(list[object], tools)
+ )
+ return any(is_hosted_web_search_type(value) for value in default_tools)
+
+
@dataclass(frozen=True)
class ModelAPICapabilities:
"""APIs declared for one model, including its preferred request surface."""
@@ -195,6 +226,48 @@ class ProviderSpec:
def label(self) -> str:
return self.display_name or self.name.title()
+ def request_model_name(self, model: str) -> str:
+ """Remove only the provider prefixes owned by this adapter."""
+ if "/" not in model:
+ return model
+ if self.strip_model_prefix:
+ return model.rsplit("/", 1)[-1]
+ prefix, routed_model = model.split("/", 1)
+ prefix_key = to_snake(prefix.replace("-", "_")).lower()
+ if any(
+ to_snake(value.replace("-", "_")).lower() == prefix_key
+ for value in self.strip_model_prefixes
+ ):
+ return routed_model
+ return model
+
+ def default_model_api(
+ self,
+ model: str,
+ reasoning_effort: str | None = None,
+ *,
+ api_base: str | None = None,
+ api_type: str = "auto",
+ extra_body: dict[str, Any] | None = None,
+ ) -> ModelAPICapabilities:
+ """Resolve automatic API defaults without constructing or probing a client."""
+ capabilities = self.responses
+ if capabilities is None:
+ return ModelAPICapabilities()
+ if capabilities.allows_api_type_override:
+ if api_type == "chat_completions":
+ return ModelAPICapabilities()
+ if api_type == "responses":
+ return ModelAPICapabilities(("responses",), "responses")
+ model_name = self.request_model_name(model)
+ if hosted_web_search_enabled(extra_body or {}, self.responses_default_tools) and (
+ capabilities.route_reasoning or capabilities.matches_model(model_name)
+ ):
+ return ModelAPICapabilities(("responses",), "responses")
+ if capabilities.requires_direct_openai_base and not is_direct_openai_base(api_base):
+ return ModelAPICapabilities()
+ return capabilities.model_api(model_name, reasoning_effort)
+
@property
def model_api_configurable(self) -> bool:
return "chat_completions" in self.request_apis and "responses" in self.request_apis
diff --git a/nanobot/webui/settings_api.py b/nanobot/webui/settings_api.py
index 3b79d9d55..768b64fb6 100644
--- a/nanobot/webui/settings_api.py
+++ b/nanobot/webui/settings_api.py
@@ -330,6 +330,14 @@ def update_provider_settings(
)
+def model_api_resolution_payload(
+ query: QueryParams,
+ *,
+ config_path: Path | None = None,
+) -> dict[str, Any]:
+ return models.model_api_resolution_payload(_load_settings_config(config_path), query)
+
+
def provider_models_payload(
query: QueryParams,
*,
diff --git a/nanobot/webui/settings_models.py b/nanobot/webui/settings_models.py
index c1d4b2118..e2062ad91 100644
--- a/nanobot/webui/settings_models.py
+++ b/nanobot/webui/settings_models.py
@@ -32,6 +32,7 @@ from nanobot.config.schema import (
ModelPresetConfig,
ProviderConfig,
)
+from nanobot.providers.factory import resolve_automatic_model_api
from nanobot.providers.image_generation import get_image_gen_provider
from nanobot.providers.oauth_guidance import OAUTH_CLI_KIT_MISSING_MESSAGE
from nanobot.providers.oauth_model_catalog import (
@@ -73,6 +74,7 @@ class ModelSettingsOperations:
update_provider: SettingsOperation
create_provider: SettingsOperation
provider_models: SettingsOperation
+ model_api: SettingsOperation
oauth_login: SettingsOperation
oauth_complete: SettingsOperation
oauth_logout: SettingsOperation
@@ -88,6 +90,7 @@ class ModelSettingsPayload(TypedDict):
model_call_order: list[str]
model_call_order_editable: bool
model_configuration_migratable: bool
+ model_api_resolution_supported: bool
providers: list[dict[str, Any]]
@@ -1013,6 +1016,25 @@ def reasoning_effort_values_for(provider_name: str, model: str) -> list[str]:
return list(_DEFAULT_REASONING_EFFORT_VALUES)
+def model_api_resolution_payload(config: Config, query: QueryParams) -> dict[str, Any]:
+ """Resolve a draft's automatic API using provider-owned routing rules."""
+ model = (query_first(query, "model") or "").strip()
+ if not model:
+ raise WebUISettingsError("model is required")
+ preset = ModelPresetConfig(
+ model=model,
+ provider=(query_first(query, "provider") or "auto").strip(),
+ reasoning_effort=(query_first(query, "reasoning_effort") or "").strip() or None,
+ )
+ try:
+ provider, api = resolve_automatic_model_api(
+ resolve_config_env_vars(config.model_copy(deep=True)), preset=preset,
+ )
+ except ValueError as exc:
+ raise WebUISettingsError(str(exc)) from exc
+ return {"provider": provider, "api": api}
+
+
def model_settings_payload(
config: Config,
*,
@@ -1102,6 +1124,7 @@ def model_settings_payload(
model_call_order, model_call_order_editable = _model_call_order_state(config)
return {
+ "model_api_resolution_supported": True,
"agent": {
"model": effective_preset.model,
"provider": selected_provider,
@@ -1886,6 +1909,12 @@ class ModelSettingsHandler:
),
)
+ if action == "model-api":
+ payload = await asyncio.to_thread(
+ self.settings.read, operations.model_api, request.query,
+ )
+ return SettingsRouteResult.success(payload)
+
if action == "provider-models":
try:
payload = await asyncio.to_thread(
diff --git a/nanobot/webui/settings_routes.py b/nanobot/webui/settings_routes.py
index c04693a2b..d693acb8b 100644
--- a/nanobot/webui/settings_routes.py
+++ b/nanobot/webui/settings_routes.py
@@ -44,6 +44,7 @@ from nanobot.webui.settings_api import (
login_oauth_provider,
logout_oauth_provider,
migrate_model_configurations,
+ model_api_resolution_payload,
provider_models_payload,
settings_payload,
settings_usage_payload,
@@ -112,6 +113,7 @@ _MODEL_ROUTES = {
"/api/settings/provider/update": "provider-update",
"/api/settings/provider/create": "provider-create",
"/api/settings/provider-models": "provider-models",
+ "/api/settings/model-api": "model-api",
"/api/settings/provider/oauth-login": "oauth-login",
"/api/settings/provider/oauth-login/complete": "oauth-complete",
"/api/settings/provider/oauth-logout": "oauth-logout",
@@ -484,6 +486,7 @@ class WebUISettingsRouter:
update_provider=update_provider_settings,
create_provider=create_provider_settings,
provider_models=provider_models_payload,
+ model_api=model_api_resolution_payload,
oauth_login=login_oauth_provider,
oauth_complete=complete_oauth_provider,
oauth_logout=logout_oauth_provider,
diff --git a/tests/providers/test_litellm_kwargs.py b/tests/providers/test_litellm_kwargs.py
index 53a397e10..9aeef3ff9 100644
--- a/tests/providers/test_litellm_kwargs.py
+++ b/tests/providers/test_litellm_kwargs.py
@@ -16,7 +16,7 @@ import pytest
from nanobot.providers.base import ProviderCallContext
from nanobot.providers.openai_compat_provider import OpenAICompatProvider
-from nanobot.providers.registry import find_by_name
+from nanobot.providers.registry import ModelAPICapabilities, find_by_name
def _fake_chat_response(content: str = "ok") -> SimpleNamespace:
@@ -320,8 +320,8 @@ async def test_openai_compat_chat_stream_forwards_reasoning_deltas_deepseek_styl
api_key="sk-test",
default_model="deepseek-v4-pro",
spec=spec,
+ model_api=ModelAPICapabilities(("chat_completions",), "chat_completions"),
)
- provider._api_type = "chat_completions"
result = await provider.chat_stream(
messages=[{"role": "user", "content": "hi"}],
model="deepseek-v4-pro",
diff --git a/tests/providers/test_model_api_presets.py b/tests/providers/test_model_api_presets.py
index 7b7d256c3..839b49ebb 100644
--- a/tests/providers/test_model_api_presets.py
+++ b/tests/providers/test_model_api_presets.py
@@ -8,7 +8,12 @@ from openai import AsyncOpenAI
from pydantic import ValidationError
from nanobot.config.schema import Config, InlineFallbackConfig, ModelAPIConfig, ModelPresetConfig
-from nanobot.providers.factory import make_provider, provider_signature, validate_provider_setup
+from nanobot.providers.factory import (
+ make_provider,
+ provider_signature,
+ resolve_automatic_model_api,
+ validate_provider_setup,
+)
from nanobot.providers.openai_compat_provider import _RESPONSES_FAILURE_THRESHOLD
@@ -77,6 +82,36 @@ async def bind_transport():
await client.close()
[email protected]("stream", [False, True])
[email protected](("provider_name", "model", "api_base", "effort"), [
+ ("tenant", "gpt-6-luna", "https://tenant.test/v1", "high"),
+ ("openai", "openai/gpt-6-luna", "https://api.openai.com/v1", None),
+ ("openai", "gpt-6-luna", "https://tenant.test/v1", "high"),
+ ("openai", "gpt-4o", "https://api.openai.com/v1", "high"),
+ ("opencode_go", "opencode-go/muse-spark-1.3-contributor", "https://opencode.ai/zen/go/v1", None),
+])
+async def test_automatic_preview_matches_actual_request(
+ bind_transport, stream, provider_name, model, api_base, effort,
+):
+ config = Config.model_validate({
+ "providers": {provider_name: {"apiBase": api_base, "apiKey": "fixture"}},
+ })
+ preset = ModelPresetConfig(model=model, provider=provider_name, reasoning_effort=effort)
+ resolved_provider, api = resolve_automatic_model_api(config, preset=preset)
+ paths = []
+
+ def handler(request):
+ paths.append(request.url.path)
+ return _answer(request)
+
+ provider = bind_transport(make_provider(config, preset=preset), handler)
+ invoke = provider.chat_stream if stream else provider.chat
+ response = await invoke([{"role": "user", "content": "hello"}], reasoning_effort=effort)
+ assert response.content == "ok"
+ assert resolved_provider == provider_name
+ assert paths == ["/v1/responses" if api == "responses" else "/v1/chat/completions"]
+
+
@pytest.mark.parametrize("stream", [False, True])
async def test_two_presets_route_same_gateway_model_independently(bind_transport, stream):
config = _config()
diff --git a/tests/providers/test_oauth_model_catalog.py b/tests/providers/test_oauth_model_catalog.py
index 314a5f1ea..c6a2924f8 100644
--- a/tests/providers/test_oauth_model_catalog.py
+++ b/tests/providers/test_oauth_model_catalog.py
@@ -356,6 +356,16 @@ def test_github_copilot_catalog_routes_advertised_model_apis(
provider = GitHubCopilotProvider(default_model="github-copilot/unknown-responses-only")
assert provider._should_use_responses_api(None, None)
assert not provider._should_use_responses_api("github-copilot/claude-sonnet", "high")
+ from nanobot.config.schema import Config, ModelPresetConfig
+ from nanobot.providers.factory import resolve_automatic_model_api
+
+ for model, effort, expected in (
+ ("github-copilot/unknown-responses-only", None, "responses"),
+ ("github-copilot/claude-sonnet", "high", "chat_completions"),
+ ):
+ assert resolve_automatic_model_api(Config(), preset=ModelPresetConfig(
+ provider="github_copilot", model=model, reasoning_effort=effort,
+ )) == ("github_copilot", expected)
assert len(captured) == 2
assert captured[0].headers["Authorization"] == "token github-secret"
assert captured[1].headers["Authorization"] == "Bearer copilot-secret"
diff --git a/tests/webui/test_settings_models.py b/tests/webui/test_settings_models.py
index e81e9af68..c8af321f0 100644
--- a/tests/webui/test_settings_models.py
+++ b/tests/webui/test_settings_models.py
@@ -57,9 +57,11 @@ def test_model_domain_owns_dto_and_config_updates() -> None:
"model_call_order",
"model_call_order_editable",
"model_configuration_migratable",
+ "model_api_resolution_supported",
"providers",
}
assert payload["agent"]["model"] == "openai/gpt-5.4"
+ assert payload["model_api_resolution_supported"] is True
@pytest.mark.parametrize("tokens", [128_000, 131_072, 1_000_000])
diff --git a/tests/webui/test_settings_routes.py b/tests/webui/test_settings_routes.py
index b655bebf9..4d9d1f5e8 100644
--- a/tests/webui/test_settings_routes.py
+++ b/tests/webui/test_settings_routes.py
@@ -156,6 +156,43 @@ async def test_full_settings_query_runs_off_the_event_loop(monkeypatch) -> None:
assert worker_threads and worker_threads[0] != calling_thread
[email protected](("provider", "model", "effort", "expected"), [
+ ("openai", "gpt-4o", "", "chat_completions"),
+ ("openai", "gpt-4o", "high", "responses"),
+ ("tenant", "gpt-6-luna", "high", "chat_completions"),
+ ("openai_codex", "gpt-6-astra", "", "responses"),
+])
+async def test_automatic_model_api_read_resolves_drafts_without_saving_or_probing(
+ tmp_path, monkeypatch, provider, model, effort, expected,
+) -> None:
+ from nanobot.config.loader import save_config
+ from nanobot.config.schema import Config
+
+ config_path = tmp_path / "config.json"
+ save_config(Config.model_validate({"providers": {
+ "openai": {"apiKey": "fixture"},
+ "tenant": {"apiBase": "https://tenant.test/v1"},
+ }}), config_path)
+ before = config_path.read_bytes()
+
+ def unexpected_client(*_args, **_kwargs):
+ pytest.fail("API resolution must not construct an HTTP client")
+
+ monkeypatch.setattr("httpx.Client", unexpected_client)
+ monkeypatch.setattr("httpx.AsyncClient", unexpected_client)
+ path = f"/api/settings/model-api?provider={provider}&model={model}&reasoning_effort={effort}"
+ request = SimpleNamespace(path=path, headers=Headers())
+ route = "/api/settings/model-api"
+ denied = await _router(authorized=False, config_path=config_path).dispatch(None, request, route)
+ assert denied is not None and denied.status_code == 401
+ response = await _router(config_path=config_path).dispatch(None, request, route)
+ assert response is not None and response.status_code == 200
+ assert json.loads(response.body) == {"provider": provider, "api": expected}
+ assert config_path.read_bytes() == before
+ assert WebUISettingsRouter.is_mutation_path(route) is False
+
+
@pytest.mark.asyncio
async def test_mcp_reload_callback_is_bounded(
monkeypatch: pytest.MonkeyPatch,
diff --git a/webui/src/components/settings/models/ModelAPIControl.tsx b/webui/src/components/settings/models/ModelAPIControl.tsx
index 3f4c588b2..d24465117 100644
--- a/webui/src/components/settings/models/ModelAPIControl.tsx
+++ b/webui/src/components/settings/models/ModelAPIControl.tsx
@@ -1,18 +1,11 @@
-import { useId } from "react";
-import { ChevronDown } from "lucide-react";
+import { useState } from "react";
import { useTranslation } from "react-i18next";
import { ToggleButton } from "@/components/settings/ToggleButton";
import { SettingsRow } from "@/components/settings/shared/SettingsControls";
-import { Button } from "@/components/ui/button";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuRadioGroup,
- DropdownMenuRadioItem,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
-import type { ModelAPIConfig, SettingsPayload } from "@/lib/types";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { cn } from "@/lib/utils";
+import type { ModelAPIConfig, ProviderRequestAPI, SettingsPayload } from "@/lib/types";
export function modelAPIConfigurable(provider: SettingsPayload["providers"][number] | undefined): boolean {
if (Array.isArray(provider?.request_apis)) {
@@ -32,115 +25,87 @@ export function modelAPISelection(api: ModelAPIConfig | null | undefined): strin
export function ModelAPIControl({
provider,
+ automaticAPI,
value,
onChange,
}: {
provider: SettingsPayload["providers"][number] | undefined;
+ automaticAPI?: ProviderRequestAPI;
value: ModelAPIConfig | null;
onChange: (api: ModelAPIConfig | null) => void;
}) {
const { t } = useTranslation();
- const helpId = useId();
- const fallbackHelpId = useId();
+ const [pointerFocus, setPointerFocus] = useState(false);
const requestAPIs = Array.isArray(provider?.request_apis) ? provider.request_apis : undefined;
const configurable = modelAPIConfigurable(provider);
const fixedAPI = requestAPIs?.length === 1 ? requestAPIs[0] : undefined;
- const fixedLabels = {
+ const labels = {
responses: "Responses",
chat_completions: "Chat Completions",
anthropic_messages: "Anthropic Messages",
bedrock_converse: "Bedrock Converse",
transcription: t("settings.models.apiTranscription"),
};
- const fixedLabel = fixedAPI ? fixedLabels[fixedAPI] : undefined;
+ const fixedLabel = fixedAPI ? labels[fixedAPI] : undefined;
const selection = modelAPISelection(value);
const selectedAPI = selection === "prefer_responses" ? "responses"
: selection === "prefer_chat" ? "chat_completions" : selection;
const allowChatFallback = selection === "prefer_responses";
const options = [
{
- value: "auto", label: t("settings.models.apiAuto"),
- help: t("settings.models.requestAPIHelp"),
- },
- {
- value: "responses", label: "Responses",
- help: t("settings.models.apiResponsesHelp"),
- },
- {
- value: "chat_completions", label: "Chat Completions",
- help: t("settings.models.apiChatHelp"),
+ value: "auto",
+ label: automaticAPI
+ ? `${t("settings.models.apiAuto")} (${labels[automaticAPI]})`
+ : t("settings.models.apiAuto"),
},
+ { value: "responses", label: "Responses" },
+ { value: "chat_completions", label: "Chat Completions" },
];
- const selected = options.find((option) => option.value === selectedAPI);
- const help = !configurable
- ? t("settings.models.apiProviderManagedHelp", { provider: provider?.label })
- : selectedAPI === "responses"
- ? t(allowChatFallback ? "settings.models.apiResponsesFallbackHelp" : "settings.models.apiResponsesOnlyHelp")
- : selected?.help;
if (!configurable && !fixedLabel) return null;
return (
<div>
<SettingsRow title={t("settings.models.requestAPI")}>
{configurable ? (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- type="button"
- variant="outline"
- aria-label={t("settings.models.requestAPI")}
- aria-describedby={helpId}
- className="h-9 w-full justify-between gap-3 rounded-full px-3 text-[13px]"
- >
- <span className="truncate">{selected?.label}</span>
- <ChevronDown className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-[min(340px,calc(100vw-2rem))]">
- <DropdownMenuRadioGroup value={selectedAPI} onValueChange={(api) => {
- if (api === selectedAPI) return;
- if (api === "auto") onChange(null);
- else if (api === "responses" || api === "chat_completions") {
- onChange({ supported_apis: [api], preferred_api: api });
- }
- }}>
- {options.map((option) => (
- <DropdownMenuRadioItem
- key={option.value}
- value={option.value}
- aria-label={option.label}
- className="items-start py-2.5"
- >
- <span>
- <span className="block text-[13px]">{option.label}</span>
- <span className="mt-0.5 block text-[12px] leading-5 text-muted-foreground">
- {option.help}
- </span>
- </span>
- </DropdownMenuRadioItem>
- ))}
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenu>
+ <Select value={selectedAPI} onValueChange={(api) => {
+ if (api === selectedAPI) return;
+ if (api === "auto") onChange(null);
+ else if (api === "responses" || api === "chat_completions") {
+ onChange({ supported_apis: [api], preferred_api: api });
+ }
+ }}>
+ <SelectTrigger
+ aria-label={t("settings.models.requestAPI")}
+ className={cn("w-full rounded-full", pointerFocus && "focus-visible:ring-0")}
+ onPointerDown={() => setPointerFocus(true)}
+ onKeyDown={() => setPointerFocus(false)}
+ onBlur={() => setPointerFocus(false)}
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent
+ onPointerUpCapture={() => setPointerFocus(true)}
+ onPointerDownOutside={() => setPointerFocus(true)}
+ onKeyDownCapture={() => setPointerFocus(false)}
+ onEscapeKeyDown={() => setPointerFocus(false)}
+ >
+ {options.map((option) => (
+ <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
) : (
<span className="block text-[13px] text-muted-foreground sm:text-right">{fixedLabel}</span>
)}
</SettingsRow>
- <p id={helpId} className="-mt-1 px-4 pb-3 text-[12px] leading-5 text-muted-foreground sm:px-5">
- {help}
- </p>
{configurable && selectedAPI === "responses" ? (
<div className="mx-4 mb-3 flex items-start justify-between gap-4 rounded-xl bg-muted/30 px-3 py-3 sm:mx-5">
<div className="min-w-0">
- <p className="text-[12px] font-medium leading-5 text-foreground">{t("settings.models.apiFallback")}</p>
- <p id={fallbackHelpId} className="mt-0.5 text-[12px] leading-5 text-muted-foreground">
- {t("settings.models.apiFallbackHelp")}
- </p>
+ <p className="text-[13px] leading-5 text-foreground">{t("settings.models.apiFallback")}</p>
</div>
<div className="pt-0.5">
<ToggleButton
checked={allowChatFallback}
- aria-describedby={fallbackHelpId}
label={t("settings.models.apiFallback")}
onChange={(checked) => onChange({
supported_apis: checked ? ["responses", "chat_completions"] : ["responses"],
diff --git a/webui/src/components/settings/models/ModelsSettings.tsx b/webui/src/components/settings/models/ModelsSettings.tsx
index e293be598..46a84001b 100644
--- a/webui/src/components/settings/models/ModelsSettings.tsx
+++ b/webui/src/components/settings/models/ModelsSettings.tsx
@@ -43,7 +43,8 @@ import {
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
-import type { ModelAPIConfig, SettingsPayload } from "@/lib/types";
+import { fetchAutomaticModelAPI } from "@/lib/api";
+import type { AutomaticModelAPIPayload, ModelAPIConfig, SettingsPayload } from "@/lib/types";
export interface AgentSettingsDraft {
model: string;
@@ -237,6 +238,29 @@ export function ModelsSettings({
const tx = (key: string, fallback: string, values?: Record<string, unknown>) =>
t(key, { defaultValue: fallback, ...(values ?? {}) });
const [editorOpen, setEditorOpen] = useState(false);
+ const [automaticAPI, setAutomaticAPI] = useState<{
+ scope: string;
+ result: AutomaticModelAPIPayload;
+ } | null>(null);
+ const automaticAPIScope = JSON.stringify([
+ token, form.provider, form.model, form.reasoningEffort, settings.providers,
+ ]);
+ useEffect(() => {
+ if (!editorOpen || settings.model_api_resolution_supported !== true || !form.model.trim()) return;
+ let cancelled = false;
+ const timer = window.setTimeout(() => {
+ void fetchAutomaticModelAPI(token, form.provider, form.model, form.reasoningEffort)
+ .then((result) => {
+ if (!cancelled) setAutomaticAPI({ scope: automaticAPIScope, result });
+ })
+ .catch(() => {
+ if (!cancelled) setAutomaticAPI(null);
+ });
+ }, 150);
+ return () => { cancelled = true; window.clearTimeout(timer); };
+ }, [editorOpen, settings.model_api_resolution_supported, automaticAPIScope, token, form]);
+ const resolvedAutomaticAPI = settings.model_api_resolution_supported === true
+ && automaticAPI?.scope === automaticAPIScope ? automaticAPI.result : null;
const editorTriggerRef = useRef<HTMLElement | null>(null);
const presetNameInputRef = useRef<HTMLInputElement>(null);
const suggestedPresetNameRef = useRef<string | null>(null);
@@ -509,8 +533,9 @@ export function ModelsSettings({
</SettingsRow>
<ModelAPIControl
provider={selectedProvider ?? settings.providers.find(
- (provider) => provider.name === selectedPreset?.resolved_provider,
+ (provider) => provider.name === (resolvedAutomaticAPI?.provider ?? selectedPreset?.resolved_provider),
)}
+ automaticAPI={resolvedAutomaticAPI?.api}
value={form.api}
onChange={(api) => setForm((prev) => ({ ...prev, api }))}
/>
diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json
index 59bd4a4d0..e5072a4f0 100644
--- a/webui/src/i18n/locales/en/common.json
+++ b/webui/src/i18n/locales/en/common.json
@@ -718,15 +718,8 @@
"presetNamePlaceholder": "e.g. Fast writing",
"advancedOptions": "Advanced options",
"requestAPI": "API connection",
- "requestAPIHelp": "Let nanobot choose for this provider and model. Usually no changes needed.",
- "apiAuto": "Automatic (recommended)",
- "apiResponsesHelp": "Use when your provider requires the Responses API.",
- "apiChatHelp": "Use the provider’s Chat Completions endpoint.",
+ "apiAuto": "Auto",
"apiFallback": "Try Chat Completions if Responses is unsupported",
- "apiFallbackHelp": "Retries with the same model. Your provider must support both APIs.",
- "apiResponsesOnlyHelp": "Uses Responses only, without switching to Chat Completions.",
- "apiResponsesFallbackHelp": "Uses Responses first, then tries Chat Completions for compatibility errors.",
- "apiProviderManagedHelp": "{{provider}} manages this connection. No configuration needed.",
"apiTranscription": "Transcription",
"contextSummary": "Context {{context}}",
"outputSummary": "Max {{max}} tokens",
diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json
index 5bf673bba..0d5d3b514 100644
--- a/webui/src/i18n/locales/es/common.json
+++ b/webui/src/i18n/locales/es/common.json
@@ -834,15 +834,8 @@
"presetNamePlaceholder": "p. ej., Escritura rápida",
"advancedOptions": "Opciones avanzadas",
"requestAPI": "Conexión API",
- "requestAPIHelp": "nanobot elige según el proveedor y el modelo. Normalmente no es necesario cambiar nada.",
- "apiAuto": "Automático (recomendado)",
- "apiResponsesHelp": "Elige esta opción si tu proveedor exige la API Responses.",
- "apiChatHelp": "Usa la API Chat Completions del proveedor.",
+ "apiAuto": "Auto",
"apiFallback": "Probar Chat Completions si Responses no es compatible",
- "apiFallbackHelp": "Reintenta con el mismo modelo. El proveedor debe admitir ambas API.",
- "apiResponsesOnlyHelp": "Usa solo Responses, sin cambiar a Chat Completions.",
- "apiResponsesFallbackHelp": "Usa Responses primero y prueba Chat Completions si hay errores de compatibilidad.",
- "apiProviderManagedHelp": "{{provider}} gestiona esta conexión. No requiere configuración.",
"apiTranscription": "Transcripción",
"contextSummary": "Contexto {{context}}",
"outputSummary": "Máx. {{max}} tokens",
diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json
index ea20f8532..e026d971b 100644
--- a/webui/src/i18n/locales/fr/common.json
+++ b/webui/src/i18n/locales/fr/common.json
@@ -834,15 +834,8 @@
"presetNamePlaceholder": "p. ex. Rédaction rapide",
"advancedOptions": "Options avancées",
"requestAPI": "Connexion API",
- "requestAPIHelp": "nanobot choisit selon le fournisseur et le modèle. Aucune modification n’est généralement nécessaire.",
- "apiAuto": "Automatique (recommandé)",
- "apiResponsesHelp": "À choisir si le fournisseur exige l’API Responses.",
- "apiChatHelp": "Utilise l’API Chat Completions du fournisseur.",
+ "apiAuto": "Auto",
"apiFallback": "Essayer Chat Completions si Responses n’est pas pris en charge",
- "apiFallbackHelp": "Réessaie avec le même modèle. Le fournisseur doit prendre en charge les deux API.",
- "apiResponsesOnlyHelp": "Utilise uniquement Responses, sans passer à Chat Completions.",
- "apiResponsesFallbackHelp": "Utilise Responses, puis essaie Chat Completions en cas d’erreur de compatibilité.",
- "apiProviderManagedHelp": "{{provider}} gère cette connexion. Aucune configuration nécessaire.",
"apiTranscription": "Transcription",
"contextSummary": "Contexte {{context}}",
"outputSummary": "Max. {{max}} tokens",
diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json
index a40674b15..cbef9f04a 100644
--- a/webui/src/i18n/locales/id/common.json
+++ b/webui/src/i18n/locales/id/common.json
@@ -834,15 +834,8 @@
"presetNamePlaceholder": "mis. Menulis cepat",
"advancedOptions": "Opsi lanjutan",
"requestAPI": "Koneksi API",
- "requestAPIHelp": "nanobot memilih sesuai penyedia dan model. Biasanya tidak perlu diubah.",
- "apiAuto": "Otomatis (disarankan)",
- "apiResponsesHelp": "Pilih jika penyedia mengharuskan API Responses.",
- "apiChatHelp": "Menggunakan API Chat Completions dari penyedia.",
+ "apiAuto": "Otomatis",
"apiFallback": "Coba Chat Completions jika Responses tidak didukung",
- "apiFallbackHelp": "Mencoba ulang dengan model yang sama. Penyedia harus mendukung kedua API.",
- "apiResponsesOnlyHelp": "Hanya menggunakan Responses, tanpa beralih ke Chat Completions.",
- "apiResponsesFallbackHelp": "Menggunakan Responses terlebih dahulu, lalu mencoba Chat Completions jika terjadi masalah kompatibilitas.",
- "apiProviderManagedHelp": "{{provider}} mengelola koneksi ini. Tidak perlu konfigurasi manual.",
"apiTranscription": "Transkripsi",
"contextSummary": "Konteks {{context}}",
"outputSummary": "Maks. {{max}} token",
diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json
index 3a844554f..056eaf9a8 100644
--- a/webui/src/i18n/locales/ja/common.json
+++ b/webui/src/i18n/locales/ja/common.json
@@ -834,15 +834,8 @@
"presetNamePlaceholder": "例:文章作成用",
"advancedOptions": "詳細オプション",
"requestAPI": "API 接続",
- "requestAPIHelp": "nanobot がプロバイダーとモデルに合わせて選択します。通常は変更不要です。",
- "apiAuto": "自動(推奨)",
- "apiResponsesHelp": "プロバイダーが Responses API を指定している場合に選択します。",
- "apiChatHelp": "プロバイダーの Chat Completions API を使用します。",
+ "apiAuto": "自動",
"apiFallback": "Responses が非対応の場合は Chat Completions を試す",
- "apiFallbackHelp": "同じモデルで再試行します。プロバイダーが両方の API に対応している必要があります。",
- "apiResponsesOnlyHelp": "Responses のみを使用し、Chat Completions には切り替えません。",
- "apiResponsesFallbackHelp": "Responses を優先し、互換性エラー時に Chat Completions を試します。",
- "apiProviderManagedHelp": "{{provider}} が接続を管理します。手動設定は不要です。",
"apiTranscription": "音声文字起こし",
"contextSummary": "コンテキスト {{context}}",
"outputSummary": "最大 {{max}} トークン",
diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json
index 3711319d0..0245f384c 100644
--- a/webui/src/i18n/locales/ko/common.json
+++ b/webui/src/i18n/locales/ko/common.json
@@ -834,15 +834,8 @@
"presetNamePlaceholder": "예: 빠른 작성",
"advancedOptions": "고급 옵션",
"requestAPI": "API 연결",
- "requestAPIHelp": "nanobot이 공급자와 모델에 맞게 선택합니다. 일반적으로 변경할 필요가 없습니다.",
- "apiAuto": "자동 선택 (권장)",
- "apiResponsesHelp": "공급자가 Responses API를 요구할 때 선택하세요.",
- "apiChatHelp": "공급자의 Chat Completions API를 사용합니다.",
+ "apiAuto": "자동",
"apiFallback": "Responses를 지원하지 않으면 Chat Completions 시도",
- "apiFallbackHelp": "같은 모델로 재시도합니다. 공급자가 두 API를 모두 지원해야 합니다.",
- "apiResponsesOnlyHelp": "Responses만 사용하며 Chat Completions로 전환하지 않습니다.",
- "apiResponsesFallbackHelp": "Responses를 먼저 사용하고 호환성 오류가 발생하면 Chat Completions를 시도합니다.",
- "apiProviderManagedHelp": "{{provider}}에서 연결을 관리합니다. 수동 설정이 필요하지 않습니다.",
"apiTranscription": "음성 전사",
"contextSummary": "컨텍스트 {{context}}",
"outputSummary": "최대 {{max}} 토큰",
diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json
index b597da5fe..e856208ba 100644
--- a/webui/src/i18n/locales/pt-BR/common.json
+++ b/webui/src/i18n/locales/pt-BR/common.json
@@ -532,15 +532,8 @@
"presetNamePlaceholder": "ex.: Escrita rápida",
"advancedOptions": "Opções avançadas",
"requestAPI": "Conexão API",
- "requestAPIHelp": "O nanobot escolhe conforme o provedor e o modelo. Geralmente não é preciso alterar.",
- "apiAuto": "Automático (recomendado)",
- "apiResponsesHelp": "Escolha quando o provedor exigir a API Responses.",
- "apiChatHelp": "Usa a API Chat Completions do provedor.",
+ "apiAuto": "Auto",
"apiFallback": "Tentar Chat Completions se Responses não for compatível",
- "apiFallbackHelp": "Tenta novamente com o mesmo modelo. O provedor deve aceitar ambas as APIs.",
- "apiResponsesOnlyHelp": "Usa apenas Responses, sem alternar para Chat Completions.",
- "apiResponsesFallbackHelp": "Usa Responses primeiro e tenta Chat Completions em caso de erro de compatibilidade.",
- "apiProviderManagedHelp": "{{provider}} gerencia esta conexão. Nenhuma configuração necessária.",
"apiTranscription": "Transcrição",
"contextSummary": "Contexto {{context}}",
"outputSummary": "Máx. {{max}} tokens",
diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json
index b86188db0..29d76044f 100644
--- a/webui/src/i18n/locales/vi/common.json
+++ b/webui/src/i18n/locales/vi/common.json
@@ -834,15 +834,8 @@
"presetNamePlaceholder": "ví dụ: Viết nhanh",
"advancedOptions": "Tùy chọn nâng cao",
"requestAPI": "Kết nối API",
- "requestAPIHelp": "nanobot tự chọn theo nhà cung cấp và mô hình. Thường không cần thay đổi.",
- "apiAuto": "Tự động (khuyến nghị)",
- "apiResponsesHelp": "Chọn khi nhà cung cấp yêu cầu API Responses.",
- "apiChatHelp": "Sử dụng API Chat Completions của nhà cung cấp.",
+ "apiAuto": "Tự động",
"apiFallback": "Thử Chat Completions nếu Responses không được hỗ trợ",
- "apiFallbackHelp": "Thử lại với cùng mô hình. Nhà cung cấp phải hỗ trợ cả hai API.",
- "apiResponsesOnlyHelp": "Chỉ dùng Responses, không chuyển sang Chat Completions.",
- "apiResponsesFallbackHelp": "Dùng Responses trước, rồi thử Chat Completions khi có lỗi tương thích.",
- "apiProviderManagedHelp": "{{provider}} quản lý kết nối này. Không cần cấu hình thủ công.",
"apiTranscription": "Chuyển giọng nói thành văn bản",
"contextSummary": "Ngữ cảnh {{context}}",
"outputSummary": "Tối đa {{max}} token",
diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json
index 78e3f653a..9a9b4400d 100644
--- a/webui/src/i18n/locales/zh-CN/common.json
+++ b/webui/src/i18n/locales/zh-CN/common.json
@@ -718,15 +718,8 @@
"presetNamePlaceholder": "例如:快速写作",
"advancedOptions": "高级选项",
"requestAPI": "连接方式",
- "requestAPIHelp": "nanobot 根据服务商和模型自动选择,通常无需修改。",
- "apiAuto": "自动选择(推荐)",
- "apiResponsesHelp": "服务商要求使用 Responses 接口时选择。",
- "apiChatHelp": "使用服务商的 Chat Completions 接口。",
+ "apiAuto": "自动",
"apiFallback": "Responses 不兼容时尝试 Chat Completions",
- "apiFallbackHelp": "使用同一模型重试,需要服务商同时支持两种接口。",
- "apiResponsesOnlyHelp": "只使用 Responses,不自动切换到 Chat Completions。",
- "apiResponsesFallbackHelp": "先使用 Responses,不兼容时尝试 Chat Completions。",
- "apiProviderManagedHelp": "由 {{provider}} 管理,无需手动配置。",
"apiTranscription": "语音转写",
"contextSummary": "上下文 {{context}}",
"outputSummary": "输出上限 {{max}} Token",
diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json
index 406e5defe..90100f5f1 100644
--- a/webui/src/i18n/locales/zh-TW/common.json
+++ b/webui/src/i18n/locales/zh-TW/common.json
@@ -834,15 +834,8 @@
"presetNamePlaceholder": "例如:快速寫作",
"advancedOptions": "進階選項",
"requestAPI": "連線方式",
- "requestAPIHelp": "nanobot 依服務商和模型自動選擇,通常無需修改。",
- "apiAuto": "自動選擇(建議)",
- "apiResponsesHelp": "服務商要求使用 Responses 介面時選擇。",
- "apiChatHelp": "使用服務商的 Chat Completions 介面。",
+ "apiAuto": "自動",
"apiFallback": "Responses 不相容時嘗試 Chat Completions",
- "apiFallbackHelp": "使用同一模型重試,需要服務商同時支援兩種介面。",
- "apiResponsesOnlyHelp": "只使用 Responses,不自動切換到 Chat Completions。",
- "apiResponsesFallbackHelp": "先使用 Responses,不相容時嘗試 Chat Completions。",
- "apiProviderManagedHelp": "由 {{provider}} 管理,無需手動設定。",
"apiTranscription": "語音轉錄",
"contextSummary": "上下文 {{context}}",
"outputSummary": "輸出上限 {{max}} Token",
diff --git a/webui/src/lib/api.ts b/webui/src/lib/api.ts
index a0b0514cd..b2f4cf407 100644
--- a/webui/src/lib/api.ts
+++ b/webui/src/lib/api.ts
@@ -3,6 +3,7 @@ import type {
AutomationChatsPayload,
AutomationChatUpdate,
AutomationsPayload,
+ AutomaticModelAPIPayload,
AutomationUpdatePayload,
ChannelConfigurePayload,
ChannelConnectPayload,
@@ -1045,6 +1046,27 @@ export async function cancelMcpOAuth(
);
}
+export async function fetchAutomaticModelAPI(
+ token: string,
+ provider: string,
+ model: string,
+ reasoningEffort: string,
+ base: string = "",
+): Promise<AutomaticModelAPIPayload> {
+ const query = new URLSearchParams({ provider, model, reasoning_effort: reasoningEffort });
+ const payload = await request<unknown>(
+ `${base}/api/settings/model-api?${query}`, token, undefined, API_READ_TIMEOUT_MS,
+ );
+ if (typeof payload !== "object" || payload === null) throw new Error("Invalid model API resolution");
+ const result = payload as Record<string, unknown>;
+ const api = result.api;
+ if (typeof result.provider !== "string" || (
+ api !== "chat_completions" && api !== "responses" && api !== "anthropic_messages"
+ && api !== "bedrock_converse" && api !== "transcription"
+ )) throw new Error("Invalid model API resolution");
+ return { provider: result.provider, api };
+}
+
export async function fetchProviderModels(
token: string,
provider: string,
diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.ts
index 01327a4cc..7d63a6390 100644
--- a/webui/src/lib/types.ts
+++ b/webui/src/lib/types.ts
@@ -600,6 +600,14 @@ export interface ModelAPIConfig {
preferred_api?: "chat_completions" | "responses" | null;
}
+export type ProviderRequestAPI =
+ "chat_completions" | "responses" | "anthropic_messages" | "bedrock_converse" | "transcription";
+
+export interface AutomaticModelAPIPayload {
+ provider: string;
+ api: ProviderRequestAPI;
+}
+
interface ProviderModelInfo {
id: string;
label?: string | null;
@@ -702,6 +710,8 @@ export interface SettingsPayload {
model_call_order_editable: boolean;
/** Whether an actual legacy model configuration is available to convert. */
model_configuration_migratable?: boolean;
+ /** Host can resolve the default request API for an unsaved model configuration. */
+ model_api_resolution_supported?: boolean;
created_model_preset?: string;
created_provider?: string;
providers: Array<{
@@ -718,9 +728,7 @@ export interface SettingsPayload {
model_catalog?: ProviderModelsPayload["catalog_kind"];
model_api_configurable?: boolean;
/** Request formats implemented by the host's provider adapter. */
- request_apis?: Array<
- "chat_completions" | "responses" | "anthropic_messages" | "bedrock_converse" | "transcription"
- >;
+ request_apis?: ProviderRequestAPI[];
api_type?: "auto" | "chat_completions" | "responses";
oauth_account?: string | null;
oauth_expires_at?: number | null;
diff --git a/webui/src/tests/settings-models.test.tsx b/webui/src/tests/settings-models.test.tsx
index 0051b4ad5..fa7d03ea0 100644
--- a/webui/src/tests/settings-models.test.tsx
+++ b/webui/src/tests/settings-models.test.tsx
@@ -1,4 +1,4 @@
-import { fireEvent, screen, waitFor, within } from "@testing-library/react";
+import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";
import { expect, it, vi } from "vitest";
import type { SettingsPayload } from "@/lib/types";
import { requestMutationMock, jsonResponse, settingsPayload, renderSettingsView, openPopover, installSettingsViewTestHooks } from "@/tests/settings-test-utils";
@@ -110,8 +110,8 @@ describe("Settings models", () => {
renderSettingsView({ initialSection: "models" });
await togglePresetEditor();
await openPopover(screen.getByLabelText("API connection"));
- expect(screen.getAllByRole("menuitemradio")).toHaveLength(3);
- fireEvent.click(screen.getByRole("menuitemradio", { name: "Responses" }));
+ expect(screen.getAllByRole("option")).toHaveLength(3);
+ fireEvent.click(screen.getByRole("option", { name: "Responses" }));
expect(screen.getByRole("switch", { name: "Try Chat Completions if Responses is unsupported" })).not.toBeChecked();
fireEvent.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
@@ -135,16 +135,97 @@ describe("Settings models", () => {
await togglePresetEditor();
expect(screen.getByRole("switch", { name: "Try Chat Completions if Responses is unsupported" })).toBeChecked();
await openPopover(screen.getByLabelText("API connection"));
- fireEvent.click(screen.getByRole("menuitemradio", { name: "Responses" }));
+ fireEvent.click(screen.getByRole("option", { name: "Responses" }));
expect(screen.getByRole("switch", { name: "Try Chat Completions if Responses is unsupported" })).toBeChecked();
expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();
await openPopover(screen.getByLabelText("API connection"));
- fireEvent.click(screen.getByRole("menuitemradio", { name: "Automatic (recommended)" }));
+ fireEvent.click(screen.getByRole("option", { name: "Auto" }));
expect(screen.queryByRole("switch", { name: "Try Chat Completions if Responses is unsupported" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
"settings.model_configuration.update", { name: "primary", api: null }, 20_000,
));
+ expect(vi.mocked(fetch).mock.calls.some(([url]) => String(url).includes("/model-api?"))).toBe(false);
+ });
+
+ it("shows the host's automatic API and discards an older reasoning resolution", async () => {
+ const payload = settingsPayload();
+ payload.model_api_resolution_supported = true;
+ payload.model_presets[0].provider = "openai";
+ payload.providers = [{
+ name: "openai", label: "OpenAI", configured: true,
+ request_apis: ["chat_completions", "responses"],
+ }];
+ let finishHigh!: (response: Response) => void;
+ const highResponse = new Promise<Response>((resolve) => { finishHigh = resolve; });
+ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
+ const url = new URL(String(input), "http://localhost");
+ if (url.pathname !== "/api/settings/model-api") return jsonResponse(payload);
+ if (url.searchParams.get("reasoning_effort") === "high") return highResponse;
+ return jsonResponse({ provider: "openai", api: "chat_completions" });
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ renderSettingsView({ initialSection: "models" });
+ await togglePresetEditor();
+ await waitFor(() => expect(screen.getByLabelText("API connection")).toHaveTextContent("Auto (Chat Completions)"));
+ expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();
+ await openPopover(screen.getByLabelText("API connection"));
+ expect(screen.getByRole("option", { name: "Auto (Chat Completions)" })).toHaveAttribute("aria-selected", "true");
+ fireEvent.click(screen.getByRole("option", { name: "Auto (Chat Completions)" }));
+ fireEvent.click(screen.getByRole("button", { name: /Advanced options/ }));
+ fireEvent.change(screen.getByLabelText("Reasoning effort"), { target: { value: "high" } });
+ await waitFor(() => expect(fetchMock.mock.calls.some(([url]) => String(url).includes("reasoning_effort=high"))).toBe(true));
+ fireEvent.change(screen.getByLabelText("Reasoning effort"), { target: { value: "none" } });
+ await waitFor(() => expect(fetchMock.mock.calls.some(([url]) => String(url).includes("reasoning_effort=none"))).toBe(true));
+ await waitFor(() => expect(screen.getByLabelText("API connection")).toHaveTextContent("Auto (Chat Completions)"));
+ await act(async () => { finishHigh(jsonResponse({ provider: "openai", api: "responses" })); });
+ expect(screen.getByLabelText("API connection")).toHaveTextContent("Auto (Chat Completions)");
+ expect(requestMutationMock).not.toHaveBeenCalled();
+ });
+
+ it("updates the Auto label from a valid host result without changing the preset declaration", async () => {
+ const payload = settingsPayload();
+ payload.model_api_resolution_supported = true;
+ payload.model_presets[0].provider = "openai";
+ payload.providers = [{
+ name: "openai", label: "OpenAI", configured: true,
+ request_apis: ["chat_completions", "responses"],
+ }];
+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
+ const url = new URL(String(input), "http://localhost");
+ if (url.pathname !== "/api/settings/model-api") return jsonResponse(payload);
+ return jsonResponse({
+ provider: "openai", api: url.searchParams.get("reasoning_effort") === "high" ? "responses" : "chat_completions",
+ });
+ }));
+ renderSettingsView({ initialSection: "models" });
+ await togglePresetEditor();
+ await waitFor(() => expect(screen.getByLabelText("API connection")).toHaveTextContent("Auto (Chat Completions)"));
+ fireEvent.click(screen.getByRole("button", { name: /Advanced options/ }));
+ fireEvent.change(screen.getByLabelText("Reasoning effort"), { target: { value: "high" } });
+ await waitFor(() => expect(screen.getByLabelText("API connection")).toHaveTextContent("Auto (Responses)"));
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+ await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
+ "settings.model_configuration.update", { name: "primary", reasoning_effort: "high" }, 20_000,
+ ));
+ });
+
+ it.each(["future_api", null])("leaves the automatic API unconfirmed for an unsupported host result (%s)", async (api) => {
+ const payload = settingsPayload();
+ payload.model_api_resolution_supported = true;
+ payload.providers = [{
+ name: "openai", label: "OpenAI", configured: true,
+ request_apis: ["chat_completions", "responses"],
+ }];
+ const fetchMock = vi.fn(async (input: RequestInfo | URL) => String(input).includes("/model-api?")
+ ? jsonResponse({ provider: "openai", api }) : jsonResponse(payload));
+ vi.stubGlobal("fetch", fetchMock);
+ renderSettingsView({ initialSection: "models" });
+ await togglePresetEditor();
+ await waitFor(() => expect(fetchMock.mock.calls.some(([url]) => String(url).includes("/model-api?"))).toBe(true));
+ await act(async () => { await Promise.resolve(); });
+ expect(screen.getByLabelText("API connection")).toHaveTextContent(/^Auto$/);
+ expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();
});
it.each([undefined, ["future_api"], "responses"])("hides API controls when host support is unconfirmed (%s)", async (requestAPIs) => {
@@ -155,7 +236,7 @@ describe("Settings models", () => {
})));
renderSettingsView({ initialSection: "models" });
await togglePresetEditor();
- expect(screen.queryByRole("button", { name: "API connection" })).not.toBeInTheDocument();
+ expect(screen.queryByRole("combobox", { name: "API connection" })).not.toBeInTheDocument();
});
it("uses the host's API declaration and preserves an existing Chat preference when renaming", async () => {
@@ -184,7 +265,7 @@ describe("Settings models", () => {
["openai_codex", "OpenAI Codex", "responses", "Responses"],
["anthropic", "Anthropic", "anthropic_messages", "Anthropic Messages"],
["bedrock", "AWS Bedrock", "bedrock_converse", "Bedrock Converse"],
- ] as const)("explains the provider-managed connection for %s", async (provider, label, api, apiLabel) => {
+ ] as const)("shows the fixed connection for %s", async (provider, label, api, apiLabel) => {
const payload = settingsPayload();
payload.providers = [{ name: provider, label, configured: true, request_apis: [api] }];
payload.model_presets[0].provider = provider;
@@ -193,8 +274,7 @@ describe("Settings models", () => {
renderSettingsView({ initialSection: "models" });
await togglePresetEditor();
expect(screen.getByText(apiLabel, { exact: true })).toBeVisible();
- expect(screen.getByText(`${label} manages this connection. No configuration needed.`)).toBeVisible();
- expect(screen.queryByRole("button", { name: "API connection" })).not.toBeInTheDocument();
+ expect(screen.queryByRole("combobox", { name: "API connection" })).not.toBeInTheDocument();
expect(screen.queryByRole("switch")).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();
});