Skip to content

Your lightweight open-source personal agent.

feat(models): declare request APIs per preset

chengyongrub5808e47de53
diff --git a/docs/configuration.md b/docs/configuration.md
index f0d057565..d1af450ea 100644
--- a/docs/configuration.md
+++ b/docs/configuration.md
@@ -316,7 +316,7 @@ Tracing covers the providers that go through nanobot's OpenAI-compatible client
<details>
<summary><b>OpenAI</b></summary>
-By default, OpenAI uses `apiType: "auto"`: nanobot calls Chat Completions normally and routes GPT-5/o-series or explicit `reasoningEffort` requests through the Responses API when useful. You can force a specific API surface:
+Without a preset API declaration, direct OpenAI uses `apiType: "auto"`: nanobot calls Chat Completions normally and routes GPT-5/GPT-6/o-series or explicit `reasoningEffort` requests through Responses. Prefer [preset API declarations](#preset-request-api) to select an API for each model and endpoint. The legacy provider-wide default remains available:
```json
{
@@ -1460,11 +1460,38 @@ Older configs may still contain a `label` inside a preset. It is accepted when l
| `contextWindowTokens` | Context window size used by prompt building and consolidation decisions. |
| `temperature` | Sampling temperature. |
| `reasoningEffort` | Optional reasoning/thinking setting. Provider support varies. |
+| `api` | Optional supported APIs and preferred API for this model at the configured endpoint. |
`default` is reserved and always means the implicit preset built from direct `agents.defaults.*` fields; do not define `modelPresets.default`. Use `/model default` to switch back to those direct fields in an existing config.
Set `agents.defaults.modelPreset` to choose the preset followed by sessions that have no saved model selection. When `modelPreset` is `null` or omitted, such sessions follow the implicit `default` preset from direct `agents.defaults.*` fields. `/model <preset>` saves an override in the current session, so its future turns keep that preset across process restarts while other sessions remain unchanged. The command does not write the selection back to `config.json`.
+### Preset request API
+
+Declare API support in the preset for OpenAI-compatible providers, including custom gateways, and GitHub Copilot. Credentials and endpoint URLs stay in the provider. Two presets sharing a provider can select different APIs.
+
+```json
+{
+ "modelPresets": {
+ "gatewayReasoning": {
+ "provider": "companyProxy",
+ "model": "gpt-6-luna",
+ "reasoningEffort": "high",
+ "api": {
+ "supportedApis": ["responses"],
+ "preferredApi": "responses"
+ }
+ }
+ }
+}
+```
+
+`supportedApis` is a nonempty list containing `chat_completions`, `responses`, or both. `preferredApi` must belong to that list; when omitted, it defaults to the first entry. A Responses-only preset never falls back to Chat Completions. Declare both APIs with `preferredApi: "responses"` to allow Chat fallback for classified Responses compatibility errors. Other failures retain their normal error handling. Native hosted search uses Responses when it is supported by the preset.
+
+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 → Request API** to choose automatic routing, either API, or Responses with Chat fallback. 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.
+
### Model Fallbacks
`agents.defaults.fallbackModels` defines an ordered failover chain for the active model configuration. The primary model is still selected by `agents.defaults.modelPreset` or, in older configs, by the implicit `default` preset from direct `agents.defaults.*` fields.
diff --git a/docs/guides/configure-openai-compatible-provider.md b/docs/guides/configure-openai-compatible-provider.md
index e61182ac2..8ef55afe0 100644
--- a/docs/guides/configure-openai-compatible-provider.md
+++ b/docs/guides/configure-openai-compatible-provider.md
@@ -70,6 +70,7 @@ nanobot agent -m "Hello!"
- Use a placeholder key such as `EMPTY` only when the endpoint requires a
non-empty key but does not validate it.
- Leave `apiType` unset for OpenAI-compatible custom endpoints.
+- For models requiring Responses, declare `api.supportedApis: ["responses"]` in their [model preset](../configuration.md#preset-request-api), or select Responses in the WebUI preset editor.
## Security notes
diff --git a/docs/providers.md b/docs/providers.md
index 3dbb279a4..41b6ec4ec 100644
--- a/docs/providers.md
+++ b/docs/providers.md
@@ -353,9 +353,9 @@ Arbitrary custom provider names are OpenAI-compatible only; they do not use the
}
```
-`providers.openai.apiType` may be set when you need to force a specific OpenAI API surface. Other providers reject `apiType`; leave it unset outside `providers.openai`. Replace the model with a model ID available to your OpenAI account. Direct OpenAI Responses, OpenAI Codex, Azure OpenAI Responses, and eligible GitHub Copilot models share [opaque Responses state retention](./configuration.md#responses-state-and-compaction); native compaction is enabled only where the backend supports it. The WebUI exposes provider-native switches for OpenAI web search, Codex Fast mode, DeepSeek web search, and Grok X Search. These switches write the corresponding raw provider request fields under `extraBody`.
+Use [preset API declarations](./configuration.md#preset-request-api) to choose Chat Completions or Responses for each model and endpoint. The legacy `providers.openai.apiType` remains a provider default for presets without a declaration; other providers reject provider-level `apiType`. Replace the model with a model ID available to your account. Direct OpenAI Responses, OpenAI Codex, Azure OpenAI Responses, and eligible GitHub Copilot models share [opaque Responses state retention](./configuration.md#responses-state-and-compaction); native compaction is enabled only where the backend supports it. The WebUI exposes provider-native switches for OpenAI web search, Codex Fast mode, DeepSeek web search, and Grok X Search. These switches write the corresponding raw provider request fields under `extraBody`.
-DeepSeek is the model-level exception in the OpenAI-compatible provider: `deepseek-v4-flash` and `deepseek-v4-pro` automatically use DeepSeek's native Responses API. Its native `web_search` tool is enabled by default and shows its lifecycle in WebUI chat activity; set `providers.deepseek.extraBody.tools` to `[]` to disable it.
+DeepSeek's `deepseek-v4-flash`, `deepseek-v4-pro`, and `deepseek-v4-flash-vision-exp` automatically use its native Responses API. Its native `web_search` tool is enabled by default and shows its lifecycle in WebUI chat activity; set `providers.deepseek.extraBody.tools` to `[]` to disable it. OpenCode Go's `muse-spark-1.2-contributor` and `muse-spark-1.3-contributor` also use Responses by default.
### Custom OpenAI-Compatible Endpoint
diff --git a/nanobot/config/schema.py b/nanobot/config/schema.py
index 7d12da8b3..eba245885 100644
--- a/nanobot/config/schema.py
+++ b/nanobot/config/schema.py
@@ -10,6 +10,7 @@ from pydantic_settings import BaseSettings, SettingsConfigDict
from nanobot.config.timezone import detect_system_timezone
from nanobot.config_base import Base
from nanobot.cron.types import CronSchedule
+from nanobot.providers.registry import ModelAPICapabilities, RequestAPI
if TYPE_CHECKING:
from nanobot.agent.tools.cli_apps import CliAppsToolConfig
@@ -81,6 +82,25 @@ class DreamConfig(Base):
return f"every {hours}h"
+class ModelAPIConfig(Base):
+ """API support and preference scoped to a model preset's endpoint."""
+
+ supported_apis: tuple[RequestAPI, ...] = Field(min_length=1)
+ preferred_api: RequestAPI | None = None
+
+ @model_validator(mode="after")
+ def _validate_preference(self) -> "ModelAPIConfig":
+ if self.preferred_api is not None and self.preferred_api not in self.supported_apis:
+ raise ValueError("preferred_api must be one of supported_apis")
+ return self
+
+ def to_capabilities(self) -> ModelAPICapabilities:
+ return ModelAPICapabilities(
+ supported_apis=self.supported_apis,
+ preferred_api=self.preferred_api or self.supported_apis[0],
+ )
+
+
class InlineFallbackConfig(Base):
"""One inline fallback model configuration."""
@@ -90,6 +110,7 @@ class InlineFallbackConfig(Base):
context_window_tokens: int | None = None
temperature: float | None = None
reasoning_effort: str | None = None
+ api: ModelAPIConfig | None = None
FallbackCandidate = str | InlineFallbackConfig
@@ -104,6 +125,7 @@ class ModelPresetConfig(Base):
context_window_tokens: int = 200_000
temperature: float = 0.1
reasoning_effort: str | None = None
+ api: ModelAPIConfig | None = None
def to_generation_settings(self) -> Any:
from nanobot.providers.base import GenerationSettings
@@ -139,6 +161,7 @@ class AgentDefaults(Base):
serialization_alias="toolHintMaxLength",
) # Max characters for tool hint display (e.g. "$ cd …/project && npm test")
reasoning_effort: str | None = None # low / medium / high / xhigh / max / adaptive / none — LLM thinking effort; None preserves the provider default
+ api: ModelAPIConfig | None = None
timezone: str = "UTC" # Effective IANA timezone, e.g. "Asia/Shanghai"
timezone_mode: Literal["auto", "manual"] = "auto"
bot_name: str = "nanobot" # Display name shown in CLI prompts (e.g. "{name} is thinking...")
@@ -476,7 +499,7 @@ class Config(BaseSettings):
return ModelPresetConfig(
model=d.model, provider=d.provider, max_tokens=d.max_tokens,
context_window_tokens=d.context_window_tokens,
- temperature=d.temperature, reasoning_effort=d.reasoning_effort,
+ temperature=d.temperature, reasoning_effort=d.reasoning_effort, api=d.api,
)
def resolve_preset(self, name: str | None = None) -> ModelPresetConfig:
diff --git a/nanobot/providers/factory.py b/nanobot/providers/factory.py
index 8411140d5..51bea768f 100644
--- a/nanobot/providers/factory.py
+++ b/nanobot/providers/factory.py
@@ -97,6 +97,8 @@ def _resolve_provider_setup(
if spec and spec.is_transcription_only:
raise ValueError(f"Provider '{provider_name}' only supports transcription.")
backend = spec.backend if spec else "openai_compat"
+ if preset.api is not None and backend not in {"openai_compat", "github_copilot"}:
+ raise ValueError("preset.api is supported for OpenAI-compatible and GitHub Copilot providers")
if p and p.proxy and backend not in {"openai_compat", "openai_codex", "xai_grok"}:
raise ValueError(
f"providers.{provider_name}.proxy is only supported for "
@@ -197,7 +199,10 @@ def _make_provider_core(
elif backend == "github_copilot":
from nanobot.providers.github_copilot_provider import GitHubCopilotProvider
- provider = GitHubCopilotProvider(default_model=model, provider_name=provider_name)
+ provider = GitHubCopilotProvider(
+ default_model=model, provider_name=provider_name,
+ model_api=preset.api.to_capabilities() if preset.api is not None else None,
+ )
elif backend == "anthropic":
from nanobot.providers.anthropic_provider import AnthropicProvider
@@ -231,6 +236,7 @@ def _make_provider_core(
spec=spec,
extra_body=p.extra_body if p else None,
api_type=p.api_type if p else "auto",
+ model_api=preset.api.to_capabilities() if preset.api is not None else None,
extra_query=p.extra_query if p else None,
proxy=p.proxy if p else None,
provider_name=provider_name,
@@ -257,6 +263,7 @@ def _inline_fallback_preset(
fallback.temperature if fallback.temperature is not None else primary.temperature
),
reasoning_effort=fallback.reasoning_effort,
+ api=fallback.api,
)
@@ -347,6 +354,7 @@ def provider_signature(
fallback.temperature,
fallback.reasoning_effort,
fallback.context_window_tokens,
+ fallback.api.model_dump_json() if fallback.api is not None else None,
getattr(fp, "proxy", None) if fp else None,
fp.thinking_style if fp else None,
)
@@ -368,6 +376,7 @@ def provider_signature(
resolved.temperature,
resolved.reasoning_effort,
resolved.context_window_tokens,
+ resolved.api.model_dump_json() if resolved.api is not None else None,
getattr(p, "proxy", None) if p else None,
p.thinking_style if p else None,
tuple(
diff --git a/nanobot/providers/github_copilot_provider.py b/nanobot/providers/github_copilot_provider.py
index 165096b1c..2f6d0845e 100644
--- a/nanobot/providers/github_copilot_provider.py
+++ b/nanobot/providers/github_copilot_provider.py
@@ -25,7 +25,12 @@ from nanobot.providers.oauth_model_catalog import (
OAuthModelCatalogSnapshot,
)
from nanobot.providers.openai_compat_provider import OpenAICompatProvider
-from nanobot.providers.registry import ProviderModelSpec, find_by_name
+from nanobot.providers.registry import (
+ ModelAPICapabilities,
+ ProviderModelSpec,
+ RequestAPI,
+ find_by_name,
+)
DEFAULT_GITHUB_DEVICE_CODE_URL = "https://github.com/login/device/code"
DEFAULT_GITHUB_ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token"
@@ -212,6 +217,7 @@ class GitHubCopilotProvider(OpenAICompatProvider):
default_model: str = "github-copilot/gpt-4.1",
*,
provider_name: str = "github_copilot",
+ model_api: ModelAPICapabilities | None = None,
):
self._copilot_access_token: str | None = None
self._copilot_expires_at: float = 0.0
@@ -227,8 +233,20 @@ class GitHubCopilotProvider(OpenAICompatProvider):
},
spec=find_by_name("github_copilot"),
provider_name=provider_name,
+ model_api=model_api,
)
+ def _model_api_capabilities(
+ self, model: str | None = None, reasoning_effort: str | None = None,
+ ) -> 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
+ return super()._model_api_capabilities(model, reasoning_effort)
+
async def _get_copilot_access_token(self) -> str:
now = time.time()
if self._copilot_access_token and now < self._copilot_expires_at - _EXPIRY_SKEW_SECONDS:
@@ -334,14 +352,19 @@ class GitHubCopilotProvider(OpenAICompatProvider):
def get_github_copilot_model_catalog(
proxy: str | None = None,
) -> OAuthModelCatalogSnapshot:
+ return _GITHUB_COPILOT_MODEL_CATALOG.get(
+ cache_key=_copilot_catalog_cache_key(proxy), proxy=proxy,
+ )
+
+
+def _copilot_catalog_cache_key(proxy: str | None = None) -> str:
storage = get_storage()
token = storage.load()
account_key = _catalog_account_key(getattr(token, "account_id", None))
- cache_key = (
+ return (
f"{storage.get_token_path()}\0{account_key}\0"
f"{_resolve('NANOBOT_COPILOT_BASE_URL', DEFAULT_COPILOT_BASE_URL)}\0{proxy or ''}"
)
- return _GITHUB_COPILOT_MODEL_CATALOG.get(cache_key=cache_key, proxy=proxy)
def invalidate_github_copilot_model_catalog() -> None:
@@ -409,12 +432,13 @@ def _parse_github_copilot_models(payload: Any) -> tuple[ProviderModelSpec, ...]:
wire_id = _catalog_first_text(row, "id")
policy = _catalog_mapping(row.get("policy"))
endpoints = row.get("supported_endpoints")
+ api = _copilot_model_api(wire_id, endpoints)
if (
not wire_id
or wire_id in seen
or row.get("model_picker_enabled") is not True
or policy.get("state") == "disabled"
- or not _copilot_transport_supported(wire_id, endpoints)
+ or (isinstance(endpoints, list) and api is None)
):
continue
seen.add(wire_id)
@@ -436,20 +460,27 @@ def _parse_github_copilot_models(payload: Any) -> tuple[ProviderModelSpec, ...]:
or (fallback.context_window if fallback is not None else None)
),
reasoning_efforts=_catalog_reasoning_efforts(supports.get("reasoning_effort")),
+ api=api,
)
)
return tuple(models)
-def _copilot_transport_supported(wire_id: str, endpoints: object) -> bool:
+def _copilot_model_api(wire_id: str, endpoints: object) -> ModelAPICapabilities | None:
if not isinstance(endpoints, list):
- return True
- supported = cast(list[object], endpoints)
- if "/chat/completions" in supported:
- return True
- model = wire_id.lower()
- return "/responses" in supported and any(
- token in model for token in ("gpt-5", "gpt-6", "o1", "o3", "o4")
+ return None
+ supported: list[RequestAPI] = []
+ if "/responses" in endpoints:
+ supported.append("responses")
+ if "/chat/completions" in endpoints:
+ supported.append("chat_completions")
+ if not supported:
+ return None
+ spec = find_by_name("github_copilot")
+ assert spec is not None and spec.responses is not None
+ preferred = spec.responses.model_api(wire_id).preferred_api
+ return ModelAPICapabilities(
+ tuple(supported), preferred if preferred in supported else supported[0],
)
diff --git a/nanobot/providers/oauth_model_catalog.py b/nanobot/providers/oauth_model_catalog.py
index 4b120bd2a..3bee949ca 100644
--- a/nanobot/providers/oauth_model_catalog.py
+++ b/nanobot/providers/oauth_model_catalog.py
@@ -170,6 +170,12 @@ class OAuthModelCatalog:
self._failures.clear()
self._condition.notify_all()
+ def peek(self, *, cache_key: str) -> OAuthModelCatalogSnapshot | None:
+ """Read the last successful metadata for this identity without discovery."""
+ with self._condition:
+ entry = self._entries.get(cache_key)
+ return entry.snapshot if entry is not None else None
+
def _cached_result(self, cache_key: str) -> OAuthModelCatalogSnapshot | None:
now = self._monotonic()
entry = self._entries.get(cache_key)
diff --git a/nanobot/providers/openai_compat_provider.py b/nanobot/providers/openai_compat_provider.py
index b826d0011..ebb3a74ac 100644
--- a/nanobot/providers/openai_compat_provider.py
+++ b/nanobot/providers/openai_compat_provider.py
@@ -36,11 +36,12 @@ 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
if TYPE_CHECKING:
from openai import AsyncOpenAI as AsyncOpenAIType
- from nanobot.providers.registry import ProviderSpec, ResponsesCapabilities
+ from nanobot.providers.registry import ProviderSpec
# Module-level placeholder — set lazily by _ensure_client on first real
# use, or replaced by tests via ``patch(...)``. Kept as a plain name so
@@ -512,6 +513,7 @@ class OpenAICompatProvider(LLMProvider):
spec: ProviderSpec | None = None,
extra_body: dict[str, Any] | None = None,
api_type: str = "auto",
+ model_api: ModelAPICapabilities | None = None,
extra_query: dict[str, str] | None = None,
proxy: str | None = None,
provider_name: str = "openai",
@@ -520,6 +522,7 @@ class OpenAICompatProvider(LLMProvider):
self.default_model = default_model
self.extra_headers = extra_headers or {}
self._spec = spec
+ self._preset_model_api = model_api
self._extra_body = dict(extra_body or {})
responses = spec.responses if spec is not None else None
self._api_type = (
@@ -1111,41 +1114,43 @@ class OpenAICompatProvider(LLMProvider):
reasoning_effort: str | None,
) -> bool:
"""Choose Responses for providers/models that explicitly support it."""
- if self._api_type == "chat_completions":
- return False
- capabilities = self._responses_capabilities()
- if capabilities is None:
+ api = self._model_api_capabilities(model, reasoning_effort)
+ if self._hosted_web_search_enabled() and "responses" in api.supported_apis:
+ return True
+ if api.preferred_api != "responses":
return False
- model_name = self._request_model_name(model or self.default_model).lower()
- if self._api_type == "responses":
- # Explicit configuration means Responses is mandatory; do not
- # consult the circuit breaker or fall back to Chat Completions.
+ if self._responses_is_required(model, reasoning_effort):
return True
+ return self._responses_circuit_allows_probe(model, reasoning_effort)
- explicitly_supported = capabilities.matches_model(model_name)
+ def _model_api_capabilities(
+ self, model: str | None = None, reasoning_effort: str | None = None,
+ ) -> ModelAPICapabilities:
+ """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":
+ 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.auto_route or explicitly_supported
+ capabilities.route_reasoning or capabilities.matches_model(model_name)
):
- # Provider-hosted tools require Responses on models that the
- # capability profile declares eligible for that transport.
- return True
+ return ModelAPICapabilities(("responses",), "responses")
if (
capabilities.requires_direct_openai_base
and not _is_direct_openai_base(self._effective_base)
):
- return False
-
- wants_auto_route = capabilities.auto_route and (
- (reasoning_effort is not None and reasoning_effort.lower() != "none")
- or any(token in model_name for token in ("gpt-5", "gpt-6", "o1", "o3", "o4"))
- )
- if not explicitly_supported and not wants_auto_route:
- return False
+ return ModelAPICapabilities()
+ return capabilities.model_api(model_name, reasoning_effort)
- return self._responses_circuit_allows_probe(model, reasoning_effort)
-
- def _responses_is_required(self) -> bool:
- return self._api_type == "responses" or self._hosted_web_search_enabled()
+ def _responses_is_required(
+ self, model: str | None = None, reasoning_effort: str | None = None,
+ ) -> bool:
+ api = self._model_api_capabilities(model, reasoning_effort)
+ 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", {})
@@ -1164,6 +1169,8 @@ class OpenAICompatProvider(LLMProvider):
)
def _responses_capabilities(self) -> ResponsesCapabilities | None:
+ if self._preset_model_api is not None and "responses" in self._preset_model_api.supported_apis:
+ return self._spec.responses if self._spec and self._spec.responses else ResponsesCapabilities()
return self._spec.responses if self._spec is not None else None
def _responses_state_provider(self) -> str:
@@ -1187,11 +1194,20 @@ class OpenAICompatProvider(LLMProvider):
def supports_native_compaction(self, model: str | None = None) -> bool:
"""Enable server compaction only on direct OpenAI Responses endpoints."""
- _ = model
capabilities = self._responses_capabilities()
if (
not self._responses.native_compaction_available
- or self._api_type == "chat_completions"
+ or (
+ self._preset_model_api is not None
+ and (
+ "responses" not in self._preset_model_api.supported_apis
+ or (
+ self._preset_model_api.preferred_api != "responses"
+ and not self._hosted_web_search_enabled()
+ )
+ )
+ )
+ or (self._preset_model_api is None and self._api_type == "chat_completions")
or capabilities is None
or not capabilities.supports_native_compaction
):
@@ -1951,10 +1967,7 @@ class OpenAICompatProvider(LLMProvider):
self._record_responses_success(model, reasoning_effort)
return result
except Exception as responses_error:
- capabilities = self._responses_capabilities()
- if capabilities is not None and not capabilities.allows_chat_fallback:
- raise
- if self._responses_is_required():
+ if self._responses_is_required(model, reasoning_effort):
raise
if not self._should_fallback_from_responses_error(responses_error):
raise
@@ -2008,10 +2021,7 @@ class OpenAICompatProvider(LLMProvider):
self._record_responses_success(model, reasoning_effort)
return result
except Exception as responses_error:
- capabilities = self._responses_capabilities()
- if capabilities is not None and not capabilities.allows_chat_fallback:
- raise
- if self._responses_is_required():
+ if self._responses_is_required(model, reasoning_effort):
raise
if not self._should_fallback_from_responses_error(responses_error):
raise
diff --git a/nanobot/providers/registry.py b/nanobot/providers/registry.py
index 79b02f199..6785ee8f0 100644
--- a/nanobot/providers/registry.py
+++ b/nanobot/providers/registry.py
@@ -17,6 +17,16 @@ from typing import Any, Literal
from pydantic.alias_generators import to_snake
+RequestAPI = Literal["chat_completions", "responses"]
+
+
+@dataclass(frozen=True)
+class ModelAPICapabilities:
+ """APIs declared for one model, including its preferred request surface."""
+
+ supported_apis: tuple[RequestAPI, ...] = ("chat_completions",)
+ preferred_api: RequestAPI = "chat_completions"
+
@dataclass(frozen=True)
class ProviderModelSpec:
@@ -29,6 +39,7 @@ class ProviderModelSpec:
context_window: int | None = None
reasoning_efforts: tuple[str, ...] = ()
supports_backend_search: bool = False
+ api: ModelAPICapabilities | None = None
@dataclass(frozen=True)
@@ -40,7 +51,8 @@ class ResponsesCapabilities:
"""
models: tuple[str, ...] = ()
- auto_route: bool = False
+ model_prefixes: tuple[str, ...] = ()
+ route_reasoning: bool = False
requires_direct_openai_base: bool = False
allows_api_type_override: bool = False
reasoning_replay: Literal["none", "encrypted", "plaintext"] = "none"
@@ -50,11 +62,25 @@ class ResponsesCapabilities:
def matches_model(self, model: str) -> bool:
"""Return whether *model* is explicitly routed through Responses."""
model_name = model.lower()
+ wire_name = model_name.rsplit("/", 1)[-1]
return any(
model_name == supported.lower()
or model_name.endswith(f"/{supported.lower()}")
for supported in self.models
+ ) or any(wire_name.startswith(prefix.lower()) for prefix in self.model_prefixes)
+
+ def model_api(
+ self, model: str, reasoning_effort: str | None = None,
+ ) -> ModelAPICapabilities:
+ """Resolve the provider's curated API defaults for one model."""
+ if not self.matches_model(model) and not (
+ self.route_reasoning and reasoning_effort and reasoning_effort.lower() != "none"
+ ):
+ return ModelAPICapabilities()
+ apis: tuple[RequestAPI, ...] = (
+ ("responses", "chat_completions") if self.allows_chat_fallback else ("responses",)
)
+ return ModelAPICapabilities(supported_apis=apis, preferred_api="responses")
@dataclass(frozen=True)
@@ -433,7 +459,8 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
backend="openai_compat",
supports_max_completion_tokens=True,
responses=ResponsesCapabilities(
- auto_route=True,
+ model_prefixes=("gpt-5", "gpt-6", "o1", "o3", "o4"),
+ route_reasoning=True,
requires_direct_openai_base=True,
allows_api_type_override=True,
reasoning_replay="encrypted",
@@ -553,7 +580,8 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
is_oauth=True,
supports_max_completion_tokens=True,
responses=ResponsesCapabilities(
- auto_route=True,
+ model_prefixes=("gpt-5", "gpt-6", "o1", "o3", "o4"),
+ route_reasoning=True,
reasoning_replay="encrypted",
allows_chat_fallback=False,
),
diff --git a/nanobot/webui/settings_models.py b/nanobot/webui/settings_models.py
index d224171dd..a8e73888b 100644
--- a/nanobot/webui/settings_models.py
+++ b/nanobot/webui/settings_models.py
@@ -25,7 +25,13 @@ from typing import TYPE_CHECKING, Any, Awaitable, Callable, TypedDict, cast
import httpx
from nanobot.config.loader import resolve_config_env_vars
-from nanobot.config.schema import Config, FallbackCandidate, ModelPresetConfig, ProviderConfig
+from nanobot.config.schema import (
+ Config,
+ FallbackCandidate,
+ ModelAPIConfig,
+ ModelPresetConfig,
+ ProviderConfig,
+)
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 (
@@ -469,6 +475,7 @@ def _provider_settings_row(
"default_api_base": spec.default_api_base or None,
"model_selectable": not spec.is_transcription_only,
"model_catalog": model_catalog_kind(spec),
+ "model_api_configurable": spec.backend in {"openai_compat", "github_copilot"},
"advanced_fields": _provider_advanced_field_names(name, spec),
"extra_headers": _redact_provider_secret_values(provider_config.extra_headers),
"extra_body": _redact_provider_secret_values(provider_config.extra_body),
@@ -677,6 +684,12 @@ def provider_models_payload(
"context_window": model.context_window,
"reasoning_efforts": list(model.reasoning_efforts),
"supports_backend_search": model.supports_backend_search,
+ **({
+ "api": {
+ "supported_apis": list(model.api.supported_apis),
+ "preferred_api": model.api.preferred_api,
+ },
+ } if model.api is not None else {}),
}
for model in catalog.models
]
@@ -1050,6 +1063,7 @@ def model_settings_payload(
"context_window_tokens": defaults.context_window_tokens,
"temperature": defaults.temperature,
"reasoning_effort": defaults.reasoning_effort,
+ "api": defaults.api.model_dump(mode="json") if defaults.api is not None else None,
"reasoning_effort_values": reasoning_effort_values_for(
config.get_provider_name(
defaults.model,
@@ -1077,6 +1091,7 @@ def model_settings_payload(
"context_window_tokens": preset.context_window_tokens,
"temperature": preset.temperature,
"reasoning_effort": preset.reasoning_effort,
+ "api": preset.api.model_dump(mode="json") if preset.api is not None else None,
"reasoning_effort_values": reasoning_effort_values_for(
resolved_preset_provider,
preset.model,
@@ -1096,6 +1111,10 @@ def model_settings_payload(
"context_window_tokens": effective_preset.context_window_tokens,
"temperature": effective_preset.temperature,
"reasoning_effort": effective_preset.reasoning_effort,
+ "api": (
+ effective_preset.api.model_dump(mode="json")
+ if effective_preset.api is not None else None
+ ),
"timezone": defaults.timezone,
"tool_hint_max_length": defaults.tool_hint_max_length,
},
@@ -1118,6 +1137,7 @@ def update_agent_model_settings(
) -> bool:
defaults = config.agents.defaults
changed = False
+ identity_changed = False
if "model_preset" in query or "modelPreset" in query:
preset = (query_first_alias(query, "model_preset", "modelPreset") or "").strip()
@@ -1136,6 +1156,7 @@ def update_agent_model_settings(
if defaults.model != model:
defaults.model = model
changed = True
+ identity_changed = True
provider = query_first(query, "provider")
if provider is not None:
@@ -1146,6 +1167,7 @@ def update_agent_model_settings(
if defaults.provider != provider:
defaults.provider = provider
changed = True
+ identity_changed = True
context_window_tokens = _parse_positive_int(
query_first_alias(query, "context_window_tokens", "contextWindowTokens"),
@@ -1157,9 +1179,38 @@ def update_agent_model_settings(
):
defaults.context_window_tokens = context_window_tokens
changed = True
+ if "api" in query:
+ api = _parse_preset_api(config, defaults.model, defaults.provider, query_first(query, "api"))
+ if defaults.api != api:
+ defaults.api = api
+ changed = True
+ elif identity_changed:
+ defaults.api = None
return changed
+def _parse_preset_api(
+ config: Config, model: str, provider: str, raw: str | None,
+) -> ModelAPIConfig | None:
+ if not raw:
+ return None
+ try:
+ value: object = json.loads(raw)
+ api = ModelAPIConfig.model_validate(value) if value is not None else None
+ except ValueError:
+ raise WebUISettingsError(
+ "api must declare supportedApis and a preferredApi from that list",
+ ) from None
+ if api is None:
+ return None
+ preset = ModelPresetConfig(model=model, provider=provider)
+ provider_name = config.get_provider_name(model, preset=preset) or provider
+ entry = resolve_settings_provider(config, provider_name)
+ if entry is None or entry[0].backend not in {"openai_compat", "github_copilot"}:
+ raise WebUISettingsError("provider does not support configurable model APIs")
+ return api
+
+
def create_model_configuration(
config: Config,
query: QueryParams,
@@ -1217,6 +1268,7 @@ def create_model_configuration(
),
temperature=temperature if temperature is not None else base.temperature,
reasoning_effort=reasoning_effort,
+ api=_parse_preset_api(config, model, provider, query_first(query, "api")),
)
if activate_as_primary:
config.agents.defaults.model_preset = name
@@ -1239,6 +1291,7 @@ def update_model_configuration(
raise WebUISettingsError("unknown model configuration")
changed = False
+ identity_changed = False
new_name_value = query_first_alias(query, "new_name", "newName")
if new_name_value is not None:
new_name = _model_configuration_name(new_name_value)
@@ -1254,6 +1307,7 @@ def update_model_configuration(
if preset.model != model:
preset.model = model
changed = True
+ identity_changed = True
provider = query_first(query, "provider")
if provider is not None:
@@ -1264,6 +1318,7 @@ def update_model_configuration(
if preset.provider != provider:
preset.provider = provider
changed = True
+ identity_changed = True
context_window_tokens = _parse_positive_int(
query_first_alias(query, "context_window_tokens", "contextWindowTokens"),
@@ -1296,6 +1351,13 @@ def update_model_configuration(
if preset.reasoning_effort != reasoning_effort:
preset.reasoning_effort = reasoning_effort
changed = True
+ if "api" in query:
+ api = _parse_preset_api(config, preset.model, preset.provider, query_first(query, "api"))
+ if preset.api != api:
+ preset.api = api
+ changed = True
+ elif identity_changed:
+ preset.api = None
return changed
@@ -1372,6 +1434,7 @@ def migrate_model_configurations(
context_window_tokens=primary.context_window_tokens,
temperature=primary.temperature,
reasoning_effort=primary.reasoning_effort,
+ api=primary.api,
)
defaults.model_preset = name
created.append(name)
@@ -1400,6 +1463,7 @@ def migrate_model_configurations(
else primary.temperature
),
reasoning_effort=fallback.reasoning_effort,
+ api=fallback.api,
)
fallback_models.append(name)
created.append(name)
diff --git a/tests/providers/test_model_api_presets.py b/tests/providers/test_model_api_presets.py
new file mode 100644
index 000000000..dcdbab9fe
--- /dev/null
+++ b/tests/providers/test_model_api_presets.py
@@ -0,0 +1,196 @@
+"""Preset API declarations control requests through OpenAI-compatible gateways."""
+
+import json
+
+import httpx
+import pytest
+from openai import AsyncOpenAI
+from pydantic import ValidationError
+
+from nanobot.config.schema import Config, InlineFallbackConfig, ModelAPIConfig
+from nanobot.providers.factory import make_provider, provider_signature
+from nanobot.providers.openai_compat_provider import _RESPONSES_FAILURE_THRESHOLD
+
+
+def _config() -> Config:
+ return Config.model_validate({
+ "agents": {"defaults": {"modelPreset": "responses"}},
+ "providers": {"tenant": {"apiBase": "https://tenant.test/v1", "apiKey": "fixture"}},
+ "modelPresets": {
+ "responses": {
+ "provider": "tenant", "model": "gpt-6-luna", "reasoningEffort": "high",
+ "api": {"supportedApis": ["responses"], "preferredApi": "responses"},
+ },
+ "chat": {
+ "provider": "tenant", "model": "gpt-6-luna",
+ "api": {"supportedApis": ["chat_completions"]},
+ },
+ },
+ })
+
+
+def _answer(request: httpx.Request) -> httpx.Response:
+ if request.url.path.endswith("/responses"):
+ response = {
+ "id": "resp_fixture", "object": "response", "status": "completed",
+ "output": [{
+ "id": "msg_fixture", "type": "message", "role": "assistant", "status": "completed",
+ "content": [{"type": "output_text", "text": "ok", "annotations": []}],
+ }],
+ }
+ events = [
+ {"type": "response.output_text.delta", "delta": "ok"},
+ {"type": "response.completed", "response": response},
+ ]
+ else:
+ response = {"id": "chat_fixture", "choices": [{
+ "index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop",
+ }]}
+ events = [{"choices": [{"index": 0, "delta": {"content": "ok"}, "finish_reason": "stop"}]}]
+ if not json.loads(request.content).get("stream"):
+ return httpx.Response(200, json=response)
+ return httpx.Response(
+ 200, headers={"content-type": "text/event-stream"},
+ content="".join(f"data: {json.dumps(event)}\n\n" for event in events),
+ )
+
+
+async def bind_transport():
+ clients = []
+
+ def bind(provider, handler):
+ original = provider._client
+ if original is not None:
+ clients.append(original)
+ client = AsyncOpenAI(
+ api_key="fixture", base_url="https://tenant.test/v1", max_retries=0,
+ http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)),
+ )
+ clients.append(client)
+ provider._client = client
+ provider._CHAT_RETRY_DELAYS = ()
+ return provider
+
+ yield bind
+ for client in clients:
+ await client.close()
+
+
[email protected]("stream", [False, True])
+async def test_two_presets_route_same_gateway_model_independently(bind_transport, stream):
+ config = _config()
+ requests = []
+
+ def handler(request):
+ requests.append(request)
+ return _answer(request)
+
+ tools = [{"type": "function", "function": {
+ "name": "lookup", "parameters": {"type": "object", "properties": {}},
+ }}]
+ for name in ("responses", "chat"):
+ provider = bind_transport(make_provider(config, preset_name=name), handler)
+ invoke = provider.chat_stream if stream else provider.chat
+ result = await invoke(
+ [{"role": "user", "content": "hello"}], tools=tools,
+ reasoning_effort=provider.generation.reasoning_effort,
+ )
+ assert result.content == "ok"
+ assert [request.url.path for request in requests] == ["/v1/responses", "/v1/chat/completions"]
+ body = json.loads(requests[0].content)
+ assert body["model"] == "gpt-6-luna"
+ assert body["reasoning"] == {"effort": "high"}
+ assert body["tools"][0]["name"] == "lookup"
+ assert "context_management" not in body
+ assert "include" not in body
+
+
[email protected]("allow_chat", [False, True])
[email protected]("stream", [False, True])
+async def test_chat_compatibility_fallback_requires_preset_support(bind_transport, allow_chat, stream):
+ config = _config()
+ if allow_chat:
+ config.model_presets["responses"].api = ModelAPIConfig(
+ supported_apis=("responses", "chat_completions"), preferred_api="responses",
+ )
+ requests = []
+
+ def handler(request):
+ requests.append(request.url.path)
+ if request.url.path.endswith("/responses"):
+ return httpx.Response(404, json={"error": {"message": "Responses endpoint not supported", "type": "invalid_request_error"}})
+ return _answer(request)
+
+ provider = bind_transport(make_provider(config), handler)
+ invoke = provider.chat_stream if stream else provider.chat
+ for _ in range(_RESPONSES_FAILURE_THRESHOLD + 1):
+ result = await invoke([{"role": "user", "content": "hello"}])
+ assert result.finish_reason == ("stop" if allow_chat else "error")
+ if allow_chat:
+ assert requests == ["/v1/responses", "/v1/chat/completions"] * _RESPONSES_FAILURE_THRESHOLD + ["/v1/chat/completions"]
+ else:
+ assert requests == ["/v1/responses"] * (_RESPONSES_FAILURE_THRESHOLD + 1)
+
+
[email protected]("inline", [False, True])
+async def test_fallback_preset_keeps_its_api_and_invalidates_runtime(bind_transport, monkeypatch, inline):
+ config = _config()
+ fallback = config.model_presets["chat"]
+ config.agents.defaults.fallback_models = [
+ InlineFallbackConfig.model_validate(fallback.model_dump()) if inline else "chat",
+ ]
+ requests = []
+
+ def handler(request):
+ requests.append(request.url.path)
+ if request.url.path.endswith("/responses"):
+ return httpx.Response(401, json={"error": {"message": "invalid_api_key", "type": "authentication_error"}})
+ return _answer(request)
+
+ from nanobot.providers import factory
+
+ original = factory._make_provider_core
+ monkeypatch.setattr(factory, "_make_provider_core", lambda *args, **kwargs: bind_transport(original(*args, **kwargs), handler))
+ provider = make_provider(config)
+ result = await provider.chat(messages=[{"role": "user", "content": "hello"}])
+ assert result.content == "ok"
+ assert requests == ["/v1/responses", "/v1/chat/completions"]
+ previous = provider_signature(config)
+ candidate = config.agents.defaults.fallback_models[0] if inline else config.model_presets["chat"]
+ candidate.api = ModelAPIConfig(supported_apis=("responses",))
+ assert provider_signature(config) != previous
+ config.agents.defaults.fallback_models = []
+ previous = provider_signature(config)
+ config.model_presets["responses"].api = None
+ assert provider_signature(config) != previous
+
+
+def test_preset_api_preference_must_be_supported():
+ with pytest.raises(ValidationError, match="preferred_api must be one of supported_apis"):
+ ModelAPIConfig.model_validate({"supportedApis": ["chat_completions"], "preferredApi": "responses"})
+
+
[email protected]("apis,preferred", [
+ (("responses",), "responses"),
+ (("chat_completions",), "chat_completions"),
+ (("chat_completions", "responses"), "chat_completions"),
+])
+async def test_preset_overrides_legacy_openai_default_and_scopes_compaction(bind_transport, apis, preferred):
+ config = _config()
+ preset = config.model_presets["responses"]
+ preset.provider = "openai"
+ preset.api = ModelAPIConfig(supported_apis=apis, preferred_api=preferred)
+ config.providers.openai.api_key = "fixture"
+ config.providers.openai.api_type = "chat_completions"
+ requests = []
+
+ def handler(request):
+ requests.append(request.url.path)
+ return _answer(request)
+
+ provider = bind_transport(make_provider(config), handler)
+ assert provider.supports_native_compaction() is (preferred == "responses")
+ result = await provider.chat(messages=[{"role": "user", "content": "hello"}])
+ assert result.content == "ok"
+ assert requests == ["/v1/responses" if preferred == "responses" else "/v1/chat/completions"]
diff --git a/tests/providers/test_oauth_model_catalog.py b/tests/providers/test_oauth_model_catalog.py
index 48130d2f5..314a5f1ea 100644
--- a/tests/providers/test_oauth_model_catalog.py
+++ b/tests/providers/test_oauth_model_catalog.py
@@ -263,7 +263,7 @@ def test_xai_inference_classifies_typed_reauth() -> None:
"responses_model",
["gpt-5.4-mini", "gpt-6-astra", "gpt-6-sol", "gpt-6-luna"],
)
-def test_github_copilot_catalog_only_lists_compatible_chat_models(
+def test_github_copilot_catalog_routes_advertised_model_apis(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
responses_model: str,
@@ -345,9 +345,17 @@ def test_github_copilot_catalog_only_lists_compatible_chat_models(
assert [model.id for model in catalog.models] == [
"github-copilot/claude-sonnet",
f"github-copilot/{responses_model}",
+ "github-copilot/unknown-responses-only",
]
assert catalog.models[0].context_window == 200_000
assert catalog.models[0].reasoning_efforts == ("low", "high")
+ assert catalog.models[0].api.supported_apis == ("chat_completions",)
+ assert catalog.models[2].api.supported_apis == ("responses",)
+ from nanobot.providers.github_copilot_provider import GitHubCopilotProvider
+
+ 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")
assert len(captured) == 2
assert captured[0].headers["Authorization"] == "token github-secret"
assert captured[1].headers["Authorization"] == "Bearer copilot-secret"
diff --git a/tests/providers/test_openai_responses.py b/tests/providers/test_openai_responses.py
index 35768ff38..683c9ea2c 100644
--- a/tests/providers/test_openai_responses.py
+++ b/tests/providers/test_openai_responses.py
@@ -7,6 +7,7 @@ from unittest.mock import MagicMock, patch
import pytest
from loguru import logger
+from openai.types.responses import ResponseFunctionToolCall
from nanobot.providers.base import LLMUsage
from nanobot.providers.openai_responses.converters import (
@@ -33,6 +34,33 @@ from nanobot.providers.openai_responses.state import (
responses_state_items,
)
+
+async def test_sdk_tool_alias_survives_capture_and_next_request_replay():
+ item = ResponseFunctionToolCall.model_validate({
+ "type": "function_call", "id": "fc_alias", "call_id": "call_alias",
+ "name": "lookup", "arguments": "{}", "async": True,
+ })
+ events = [SimpleNamespace(
+ type="response.completed",
+ response=SimpleNamespace(status="completed", usage=None, output=[item]),
+ )]
+
+ async def stream():
+ for event in events:
+ yield event
+
+ capture = ResponsesStreamCapture()
+ await consume_sdk_stream(stream(), capture=capture)
+ state = build_responses_state(
+ provider="fixture", model="fixture", input_items=[], output_items=capture.output_items,
+ )
+ _, items, replayed = prepare_responses_input(
+ [], state=state, provider="fixture", model="fixture",
+ )
+ assert replayed
+ assert items[0]["async"] is True
+ assert "async_" not in items[0]
+
# ======================================================================
# converters - split_tool_call_id
# ======================================================================
diff --git a/tests/webui/test_settings_api.py b/tests/webui/test_settings_api.py
index 0cc2c9588..bd48f94fe 100644
--- a/tests/webui/test_settings_api.py
+++ b/tests/webui/test_settings_api.py
@@ -9,7 +9,7 @@ import httpx
import pytest
from nanobot.config.loader import load_config, save_config
-from nanobot.config.schema import Config, InlineFallbackConfig, ModelPresetConfig
+from nanobot.config.schema import Config, InlineFallbackConfig, ModelAPIConfig, ModelPresetConfig
from nanobot.llm_usage import get_llm_usage_store
from nanobot.llm_usage.models import LLMCallRecord
from nanobot.providers.base import LLMUsage
@@ -746,6 +746,81 @@ def test_model_configuration_advanced_options_round_trip(
assert row["reasoning_effort"] is None
+def test_custom_preset_api_round_trip_and_reset(tmp_path, monkeypatch):
+ config_path = tmp_path / "config.json"
+ config = Config.model_validate({"providers": {
+ "tenant": {"apiBase": "https://tenant.test/v1"},
+ }})
+ save_config(config, config_path)
+ monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
+ api = {"supported_apis": ["responses"], "preferred_api": "responses"}
+ created = create_model_configuration({
+ "name": ["reasoning"], "provider": ["tenant"], "model": ["gpt-6-luna"],
+ "api": [json.dumps(api)],
+ })
+ row = next(row for row in created["model_presets"] if row["name"] == "reasoning")
+ assert row["api"] == api
+ providers = {row["name"]: row for row in created["providers"]}
+ assert providers["tenant"]["model_api_configurable"] is True
+ assert providers["github_copilot"]["model_api_configurable"] is True
+ assert providers["anthropic"]["model_api_configurable"] is False
+ saved = load_config(config_path)
+ assert saved.model_presets["reasoning"].api.to_capabilities().preferred_api == "responses"
+ assert json.loads(config_path.read_text())["modelPresets"]["reasoning"]["api"] == {
+ "supportedApis": ["responses"], "preferredApi": "responses",
+ }
+
+ update_model_call_order({"order": [json.dumps(["reasoning"])]})
+ assert settings_payload()["agent"]["api"] == api
+ update_model_configuration({"name": ["reasoning"], "temperature": ["0.3"]})
+ assert settings_payload()["agent"]["api"] == api
+ reset = update_model_configuration({"name": ["reasoning"], "api": [""]})
+ assert next(row for row in reset["model_presets"] if row["name"] == "reasoning")["api"] is None
+ assert load_config(config_path).model_presets["reasoning"].api is None
+ update_model_configuration({"name": ["reasoning"], "api": [json.dumps(api)]})
+ update_model_configuration({"name": ["reasoning"], "model": ["another-model"]})
+ assert load_config(config_path).model_presets["reasoning"].api is None
+
+
[email protected]("provider,api,error", [
+ ("openai", {"supportedApis": ["chat_completions"], "preferredApi": "responses"}, "api must declare"),
+ ("anthropic", {"supportedApis": ["responses"]}, "provider does not support"),
+])
+def test_create_preset_rejects_invalid_api_without_saving(tmp_path, monkeypatch, provider, api, error):
+ config_path = tmp_path / "config.json"
+ config = Config()
+ config.providers.openai.api_key = "fixture"
+ config.providers.anthropic.api_key = "fixture"
+ save_config(config, config_path)
+ monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
+ with pytest.raises(WebUISettingsError, match=error):
+ create_model_configuration({
+ "name": ["test"], "provider": [provider], "model": ["test-model"],
+ "api": [json.dumps(api)],
+ })
+ assert load_config(config_path).model_presets == {}
+
+
+def test_legacy_migration_preserves_primary_and_fallback_apis(tmp_path, monkeypatch):
+ config_path = tmp_path / "config.json"
+ config = Config.model_validate({"providers": {
+ "tenant": {"apiBase": "https://tenant.test/v1"},
+ }})
+ defaults = config.agents.defaults
+ defaults.model = "tenant/reasoning"
+ defaults.provider = "tenant"
+ defaults.api = ModelAPIConfig(supported_apis=("responses",))
+ defaults.fallback_models = [InlineFallbackConfig(
+ provider="tenant", model="tenant/chat", api=ModelAPIConfig(supported_apis=("chat_completions",)),
+ )]
+ save_config(config, config_path)
+ monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
+ migrate_model_configurations()
+ saved = load_config(config_path)
+ assert saved.model_presets["reasoning"].api == defaults.api
+ assert saved.model_presets["chat"].api == defaults.fallback_models[0].api
+
+
def test_delete_model_configuration_protects_primary_and_removes_fallback_references(
tmp_path,
monkeypatch: pytest.MonkeyPatch,
diff --git a/webui/src/components/settings/models/ModelAPIControl.tsx b/webui/src/components/settings/models/ModelAPIControl.tsx
new file mode 100644
index 000000000..113b68584
--- /dev/null
+++ b/webui/src/components/settings/models/ModelAPIControl.tsx
@@ -0,0 +1,75 @@
+import { ChevronDown } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import { SettingsRow } from "@/components/settings/shared/SettingsControls";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import type { ModelAPIConfig } from "@/lib/types";
+
+export function modelAPISelection(api: ModelAPIConfig | null | undefined): string {
+ if (!api) return "auto";
+ if (!api.supported_apis.includes("responses")) return "chat_completions";
+ if (!api.supported_apis.includes("chat_completions")) return "responses";
+ return (api.preferred_api ?? api.supported_apis[0]) === "responses"
+ ? "prefer_responses"
+ : "prefer_chat";
+}
+
+export function ModelAPIControl({
+ value,
+ onChange,
+}: {
+ value: ModelAPIConfig | null;
+ onChange: (api: ModelAPIConfig | null) => void;
+}) {
+ const { t } = useTranslation();
+ const options: Array<{ value: string; label: string; api: ModelAPIConfig | null }> = [
+ { value: "auto", label: t("settings.models.apiAuto"), api: null },
+ {
+ value: "chat_completions", label: "Chat Completions",
+ api: { supported_apis: ["chat_completions"], preferred_api: "chat_completions" },
+ },
+ {
+ value: "responses", label: "Responses",
+ api: { supported_apis: ["responses"], preferred_api: "responses" },
+ },
+ {
+ value: "prefer_responses", label: t("settings.models.apiPreferResponses"),
+ api: { supported_apis: ["responses", "chat_completions"], preferred_api: "responses" },
+ },
+ {
+ value: "prefer_chat", label: t("settings.models.apiPreferChat"),
+ api: { supported_apis: ["chat_completions", "responses"], preferred_api: "chat_completions" },
+ },
+ ];
+ const selected = options.find((option) => option.value === modelAPISelection(value));
+ return (
+ <SettingsRow title={t("settings.models.requestAPI")} description={t("settings.models.requestAPIHelp")}>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="button"
+ variant="outline"
+ aria-label={t("settings.models.requestAPI")}
+ 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="min-w-[220px]">
+ {options.map((option) => (
+ <DropdownMenuItem key={option.value} onSelect={() => onChange(option.api)}>
+ {option.label}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </SettingsRow>
+ );
+}
diff --git a/webui/src/components/settings/models/ModelsSettings.tsx b/webui/src/components/settings/models/ModelsSettings.tsx
index cf4e7a1ba..c4bc4c991 100644
--- a/webui/src/components/settings/models/ModelsSettings.tsx
+++ b/webui/src/components/settings/models/ModelsSettings.tsx
@@ -1,4 +1,5 @@
import { ProviderIcon } from "@/components/settings/models/ProviderSettings";
+import { ModelAPIControl } from "@/components/settings/models/ModelAPIControl";
import { ToggleButton } from "@/components/settings/ToggleButton";
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
import { useEffect, useId, useRef, useState, type Dispatch, type SetStateAction } from "react";
@@ -42,7 +43,7 @@ import {
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
-import type { SettingsPayload } from "@/lib/types";
+import type { ModelAPIConfig, SettingsPayload } from "@/lib/types";
export interface AgentSettingsDraft {
model: string;
@@ -52,6 +53,7 @@ export interface AgentSettingsDraft {
contextWindowTokens: number;
temperature: number;
reasoningEffort: string;
+ api: ModelAPIConfig | null;
timezone: string;
toolHintMaxLength: number;
}
@@ -92,6 +94,7 @@ export const DEFAULT_AGENT_SETTINGS_DRAFT: AgentSettingsDraft = {
contextWindowTokens: 200_000,
temperature: 0.1,
reasoningEffort: "",
+ api: null,
timezone: "UTC",
toolHintMaxLength: 40,
};
@@ -115,6 +118,7 @@ export function agentDraftFromPayload(
),
temperature: activePreset?.temperature ?? payload.agent.temperature,
reasoningEffort: activePreset?.reasoning_effort ?? "",
+ api: activePreset ? activePreset.api ?? null : payload.agent.api ?? null,
timezone: payload.agent.timezone,
toolHintMaxLength: payload.agent.tool_hint_max_length,
};
@@ -337,6 +341,7 @@ export function ModelsSettings({
contextWindowTokens: normalizeContextWindowTokens(preset.context_window_tokens),
temperature: preset.temperature,
reasoningEffort: preset.reasoning_effort ?? "",
+ api: preset.api ?? null,
}));
setEditorRowKey(rowKey);
setEditorOpen(true);
@@ -446,6 +451,7 @@ export function ModelsSettings({
...prev,
provider,
model: provider === prev.provider ? prev.model : "",
+ api: provider === prev.provider ? prev.api : null,
modelPreset: clearSuggestedName ? "" : prev.modelPreset,
}));
}}
@@ -495,11 +501,20 @@ export function ModelsSettings({
setForm((prev) => ({
...prev,
model,
+ api: model === prev.model ? prev.api : null,
modelPreset: canSuggestName ? suggestion : prev.modelPreset,
}));
}}
/>
</SettingsRow>
+ {(selectedProvider ?? settings.providers.find(
+ (provider) => provider.name === selectedPreset?.resolved_provider,
+ ))?.model_api_configurable === true ? (
+ <ModelAPIControl
+ value={form.api}
+ onChange={(api) => setForm((prev) => ({ ...prev, api }))}
+ />
+ ) : null}
<button
type="button"
aria-expanded={advancedOpen}
diff --git a/webui/src/components/settings/models/useModelSettingsActions.ts b/webui/src/components/settings/models/useModelSettingsActions.ts
index 4dba28b20..167df43f2 100644
--- a/webui/src/components/settings/models/useModelSettingsActions.ts
+++ b/webui/src/components/settings/models/useModelSettingsActions.ts
@@ -7,6 +7,7 @@ import type {
PendingRestartSections,
} from "@/components/settings/contracts";
import { agentDraftFromPayload } from "@/components/settings/models/ModelsSettings";
+import { modelAPISelection } from "@/components/settings/models/ModelAPIControl";
import {
CUSTOM_PROVIDER_CREATION_KEY,
providerFormFromRow,
@@ -195,6 +196,8 @@ export function useModelSettingsActions({
contextWindowTokens: form.contextWindowTokens,
temperature: form.temperature,
reasoningEffort: form.reasoningEffort || null,
+ api: settings.providers.find((row) => row.name === provider)?.model_api_configurable === true
+ ? form.api : undefined,
});
const createdPreset = payload.created_model_preset;
const nextOrder = createdPreset ? [...modelCallOrder, createdPreset] : null;
@@ -257,6 +260,11 @@ export function useModelSettingsActions({
form.temperature !== selectedPreset.temperature ? form.temperature : undefined,
reasoningEffort:
reasoningEffort !== selectedPreset.reasoning_effort ? reasoningEffort : undefined,
+ api: settings.providers.find((row) => row.name === (
+ form.provider === "auto" ? selectedPreset.resolved_provider : form.provider
+ ))?.model_api_configurable === true &&
+ modelAPISelection(form.api) !== modelAPISelection(selectedPreset.api)
+ ? form.api : undefined,
});
applyPayload(payload);
setForm(agentDraftFromPayload(payload, nextName));
@@ -290,6 +298,7 @@ export function useModelSettingsActions({
modelPreset: "",
provider,
model: "",
+ api: null,
maxTokens: primaryPreset?.max_tokens ?? settings.agent.max_tokens,
contextWindowTokens: normalizeContextWindowTokens(
primaryPreset?.context_window_tokens ?? settings.agent.context_window_tokens,
diff --git a/webui/src/components/settings/useSettingsController.ts b/webui/src/components/settings/useSettingsController.ts
index c9c7e47e0..6f5908226 100644
--- a/webui/src/components/settings/useSettingsController.ts
+++ b/webui/src/components/settings/useSettingsController.ts
@@ -20,6 +20,7 @@ import type {
SettingsSectionKey,
} from "@/components/settings/contracts";
import { agentDraftFromPayload } from "@/components/settings/models/ModelsSettings";
+import { modelAPISelection } from "@/components/settings/models/ModelAPIControl";
import { useModelSettingsActions } from "@/components/settings/models/useModelSettingsActions";
import {
useProviderFormsSync,
@@ -298,7 +299,8 @@ export function useSettingsController({
form.maxTokens !== selectedPreset.max_tokens ||
form.contextWindowTokens !== normalizeContextWindowTokens(selectedPreset.context_window_tokens) ||
form.temperature !== selectedPreset.temperature ||
- form.reasoningEffort !== (selectedPreset.reasoning_effort ?? "")
+ form.reasoningEffort !== (selectedPreset.reasoning_effort ?? "") ||
+ modelAPISelection(form.api) !== modelAPISelection(selectedPreset.api)
);
}, [form, modelPresetEditingName, settings]);
diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json
index a6ad62029..7541b19c5 100644
--- a/webui/src/i18n/locales/en/common.json
+++ b/webui/src/i18n/locales/en/common.json
@@ -717,6 +717,11 @@
"presetNameDuplicate": "A preset with this name already exists.",
"presetNamePlaceholder": "e.g. Fast writing",
"advancedOptions": "Advanced options",
+ "requestAPI": "Request API",
+ "requestAPIHelp": "Applies to this preset. Select Responses for gateways that require it; allow Chat fallback only when the model supports both APIs.",
+ "apiAuto": "Automatic",
+ "apiPreferResponses": "Responses with Chat fallback",
+ "apiPreferChat": "Chat preferred (both APIs)",
"contextSummary": "Context {{context}}",
"outputSummary": "Max {{max}} tokens",
"contextWindowHint": "{{tokens}} tokens",
diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json
index 7ee5a5f58..0dae5785c 100644
--- a/webui/src/i18n/locales/zh-CN/common.json
+++ b/webui/src/i18n/locales/zh-CN/common.json
@@ -717,6 +717,11 @@
"presetNameDuplicate": "已存在同名预设。",
"presetNamePlaceholder": "例如:快速写作",
"advancedOptions": "高级选项",
+ "requestAPI": "请求 API",
+ "requestAPIHelp": "仅用于此预设。网关要求 Responses 时可在这里选择;只有模型支持两种 API 时才允许回退到 Chat。",
+ "apiAuto": "自动",
+ "apiPreferResponses": "Responses(可回退 Chat)",
+ "apiPreferChat": "优先 Chat(支持两种 API)",
"contextSummary": "上下文 {{context}}",
"outputSummary": "输出上限 {{max}} Token",
"contextWindowHint": "{{tokens}} Token",
diff --git a/webui/src/lib/api.ts b/webui/src/lib/api.ts
index f725b6045..a0b0514cd 100644
--- a/webui/src/lib/api.ts
+++ b/webui/src/lib/api.ts
@@ -1152,7 +1152,7 @@ export async function fetchSidebarState(
function modelGenerationSettingsPayload(
configuration: Pick<
ModelConfigurationCreate,
- "maxTokens" | "contextWindowTokens" | "temperature" | "reasoningEffort"
+ "maxTokens" | "contextWindowTokens" | "temperature" | "reasoningEffort" | "api"
>,
): Record<string, unknown> {
const payload: Record<string, unknown> = {};
@@ -1168,6 +1168,9 @@ function modelGenerationSettingsPayload(
if (configuration.reasoningEffort !== undefined) {
payload.reasoning_effort = configuration.reasoningEffort ?? "";
}
+ if (configuration.api !== undefined) {
+ payload.api = configuration.api;
+ }
return payload;
}
diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.ts
index a8b3afa97..f192ed7fd 100644
--- a/webui/src/lib/types.ts
+++ b/webui/src/lib/types.ts
@@ -595,6 +595,11 @@ export interface RuntimeCapabilities {
can_export_diagnostics: boolean;
}
+export interface ModelAPIConfig {
+ supported_apis: Array<"chat_completions" | "responses">;
+ preferred_api?: "chat_completions" | "responses" | null;
+}
+
interface ProviderModelInfo {
id: string;
label?: string | null;
@@ -603,6 +608,7 @@ interface ProviderModelInfo {
context_window?: number | null;
reasoning_efforts?: string[];
supports_backend_search?: boolean;
+ api?: ModelAPIConfig | null;
}
export interface ProviderModelsPayload {
@@ -672,6 +678,7 @@ export interface SettingsPayload {
context_window_tokens: number;
temperature: number;
reasoning_effort: string | null;
+ api?: ModelAPIConfig | null;
timezone: string;
tool_hint_max_length: number;
};
@@ -689,6 +696,7 @@ export interface SettingsPayload {
temperature: number;
reasoning_effort: string | null;
reasoning_effort_values?: string[];
+ api?: ModelAPIConfig | null;
}>;
model_call_order: string[];
model_call_order_editable: boolean;
@@ -708,6 +716,7 @@ export interface SettingsPayload {
default_api_base?: string | null;
model_selectable?: boolean;
model_catalog?: ProviderModelsPayload["catalog_kind"];
+ model_api_configurable?: boolean;
api_type?: "auto" | "chat_completions" | "responses";
oauth_account?: string | null;
oauth_expires_at?: number | null;
@@ -1307,6 +1316,7 @@ export interface ModelConfigurationCreate {
contextWindowTokens?: number;
temperature?: number;
reasoningEffort?: string | null;
+ api?: ModelAPIConfig | null;
}
export interface ModelConfigurationUpdate {
@@ -1318,6 +1328,7 @@ export interface ModelConfigurationUpdate {
contextWindowTokens?: number;
temperature?: number;
reasoningEffort?: string | null;
+ api?: ModelAPIConfig | null;
}
export interface ProviderSettingsUpdate {
diff --git a/webui/src/tests/settings-models.test.tsx b/webui/src/tests/settings-models.test.tsx
index d6b01ed4c..7e15aeb2e 100644
--- a/webui/src/tests/settings-models.test.tsx
+++ b/webui/src/tests/settings-models.test.tsx
@@ -89,6 +89,50 @@ async function togglePresetEditor(name = "primary") {
describe("Settings models", () => {
installSettingsViewTestHooks();
+ it("saves and restores a preset API declaration, then returns to automatic", async () => {
+ let payload = settingsPayload();
+ payload.providers = [{ name: "openai", label: "OpenAI", configured: true, model_api_configurable: true }];
+ payload.model_presets[0].provider = "openai";
+ vi.stubGlobal("fetch", vi.fn(async () => jsonResponse(payload)));
+ requestMutationMock.mockImplementation(async (action, args) => {
+ expect(action).toBe("settings.model_configuration.update");
+ payload = {
+ ...payload,
+ model_presets: payload.model_presets.map((preset) => ({ ...preset, api: args.api })),
+ };
+ return payload;
+ });
+ renderSettingsView({ initialSection: "models" });
+ await togglePresetEditor();
+ await openPopover(screen.getByLabelText("Request API"));
+ fireEvent.click(screen.getByRole("menuitem", { name: "Responses" }));
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+ await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
+ "settings.model_configuration.update",
+ { name: "primary", api: { supported_apis: ["responses"], preferred_api: "responses" } },
+ 20_000,
+ ));
+ await waitFor(() => expect(screen.getByRole("button", { name: "Save" })).toBeDisabled());
+ fireEvent.click(screen.getByRole("button", { name: "Close", exact: true }));
+ await togglePresetEditor();
+ expect(screen.getByLabelText("Request API")).toHaveTextContent("Responses");
+ await openPopover(screen.getByLabelText("Request API"));
+ fireEvent.click(screen.getByRole("menuitem", { name: "Automatic" }));
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+ await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
+ "settings.model_configuration.update", { name: "primary", api: null }, 20_000,
+ ));
+ });
+
+ it("hides API controls when the host omits preset API support", async () => {
+ const payload = settingsPayload();
+ payload.providers = [{ name: "openai", label: "OpenAI", configured: true }];
+ vi.stubGlobal("fetch", vi.fn(async () => jsonResponse(payload)));
+ renderSettingsView({ initialSection: "models" });
+ await togglePresetEditor();
+ expect(screen.queryByRole("button", { name: "Request API" })).not.toBeInTheDocument();
+ });
+
it.each(["manual", "poll", "direct"])("reauthenticates from the catalog and preserves the preset draft (%s)", async (mode) => {
const payload = settingsPayload();
payload.providers = [{