feat(providers): declare supported APIs for custom connections

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-10 01:33:02 +08:00
1 parent 73a27e0726
commit 34fd4ed75a
29 files changed
+799 -108

No files matched your search

+40 -36
View File
@@ -262,8 +262,8 @@ Tracing covers the providers that go through nanobot's OpenAI-compatible client
> - **Step Fun (Mainland China)**: If your API key is from Step Fun's mainland China platform (stepfun.com), set `"apiBase": "https://api.stepfun.com/v1"` in your stepfun provider config.
> - **Xiaomi MiMo thinking mode**: MiMo models (e.g. `mimo-v2.5-pro`) default to enabled thinking. Use `agents.defaults.reasoningEffort: "none"` to disable it, or `"low"` / `"medium"` / `"high"` to keep it on. Omitting the field preserves the provider's per-model default.
> - **Xiaomi MiMo Token Plan**: If you're on MiMo's token plan, set `"apiBase": "https://token-plan-sgp.xiaomimimo.com/v1"` in your xiaomi_mimo provider config.
> - **Custom OpenAI-compatible providers**: Besides the built-in `custom` provider, any extra key under `providers` can define its own OpenAI-compatible endpoint. For example, `providers.companyProxy.apiBase` plus `modelPresets.primary.provider: "companyProxy"` creates a separate custom provider. Set `apiBase`; set `apiKey` only when the endpoint requires it. This named-custom path uses the OpenAI-compatible request format only. For Anthropic-compatible proxies, use `providers.anthropic.apiBase` with `provider: "anthropic"`.
> - **Provider-scoped proxy**: `providers.<name>.proxy` routes only that provider through an HTTP proxy. It is supported for OpenAI-compatible providers, `openai_codex`, and `xai_grok`. Native provider backends such as `anthropic`, `bedrock`, `azure_openai`, and `github_copilot` reject `proxy`.
> - **Custom providers**: Besides the built-in `custom` provider, any extra key under `providers` can define its own endpoint. For example, `providers.companyProxy.apiBase` plus `modelPresets.primary.provider: "companyProxy"` creates a separate custom provider. Set `apiBase`; set `apiKey` only when the endpoint requires it. Declare accepted protocols with `providers.<name>.api`; custom connections can use Chat Completions, Responses, or Anthropic Messages. See [custom connection APIs](#custom-connection-apis).
> - **Provider-scoped proxy**: `providers.<name>.proxy` routes only that provider through an HTTP proxy. It is supported for OpenAI-compatible providers, Anthropic Messages, `openai_codex`, and `xai_grok`. Native `bedrock`, `azure_openai`, and `github_copilot` backends reject `proxy`.
| Provider | Purpose | Get API Key |
|----------|---------|-------------|
@@ -1089,36 +1089,7 @@ Connects directly to any OpenAI-compatible endpoint — llama.cpp, Together AI,
> For local servers that don't require authentication, set `apiKey` to `null`.
>
> `custom` is the right choice for providers that expose an OpenAI-compatible **chat completions** API. It does **not** force third-party endpoints onto the OpenAI/Azure **Responses API**.
>
> If your proxy or gateway is specifically Responses-API-compatible, configure the `azure_openai` provider shape and point `apiBase` at that endpoint:
>
> ```json
> {
> "providers": {
> "azure_openai": {
> "apiKey": "your-api-key",
> "apiBase": "https://api.your-provider.com",
> "defaultModel": "your-model-name"
> }
> },
> "modelPresets": {
> "responsesProxy": {
> "provider": "azure_openai",
> "model": "your-model-name"
> }
> },
> "agents": {
> "defaults": {
> "modelPreset": "responsesProxy"
> }
> }
> }
> ```
>
> Anthropic-compatible endpoints are separate: use `providers.anthropic.apiBase` and set the preset provider to `anthropic`. Arbitrary custom provider names do not use the Anthropic Messages API format.
>
> In short: **chat-completions-compatible endpoint → `custom` or a named custom provider**; **Responses-compatible endpoint → `azure_openai`**; **Anthropic-compatible endpoint → `anthropic` with `apiBase`**.
> Custom connections default to Chat Completions when no API declaration is configured. For a Responses-only endpoint, set `providers.custom.api.supportedApis` to `["responses"]`. For an Anthropic-compatible endpoint, use `["anthropic_messages"]`. Named custom providers accept the same declaration. Native Anthropic credentials and proxies can also use `providers.anthropic`. See [custom connection APIs](#custom-connection-apis).
Some OpenAI-compatible gateways expose request-body extensions such as vLLM guided decoding or local sampling controls. Put those under `extraBody`; nanobot merges them into the chat-completions request body after its provider defaults:
@@ -1466,9 +1437,32 @@ Older configs may still contain a `label` inside a preset. It is accepted when l
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`.
### Custom connection APIs
For the built-in `custom` connection or any named custom provider, declare the protocols accepted by the endpoint under `providers.<name>.api`:
```json
{
"providers": {
"companyProxy": {
"apiBase": "https://gateway.example.com",
"apiKey": "${COMPANY_API_KEY}",
"api": {
"supportedApis": ["responses", "anthropic_messages"],
"preferredApi": "anthropic_messages"
}
}
}
}
```
`supportedApis` is a nonempty list of `chat_completions`, `responses`, and/or `anthropic_messages`. `preferredApi` must belong to that list and defaults to its first entry. A model preset using Auto inherits this default. A preset's explicit API list must be a subset of the connection's list. A connection can accept both Anthropic and OpenAI formats; automatic fallback stays within the selected API family.
The WebUI custom provider creation and editing forms expose **Supported APIs** and **Default API**. New connections start with Chat Completions; select the protocols your endpoint accepts. Existing connections without an `api` declaration retain their previous automatic routing. Use **Set supported APIs** to add a declaration. Removing a protocol used by an existing explicit model configuration is rejected; update the model configuration first.
### Preset request API
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.
Leave API selection on **Auto** unless your provider requires a specific endpoint. For OpenAI-compatible providers and GitHub Copilot, a preset can choose Responses or Chat Completions. Custom gateways also allow Anthropic Messages. Credentials and endpoint URLs stay in the provider. Two presets sharing a provider can select different APIs.
```json
{
@@ -1481,16 +1475,26 @@ Leave API selection on **Auto** unless your provider requires a specific endpoin
"supportedApis": ["responses"],
"preferredApi": "responses"
}
},
"gatewayClaude": {
"provider": "companyProxy",
"model": "claude-sonnet-4-6",
"api": {
"supportedApis": ["anthropic_messages"],
"preferredApi": "anthropic_messages"
}
}
}
}
```
`supportedApis` is a nonempty list of APIs this preset is allowed to use: `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, when the endpoint serves that model through both APIs. Other failures retain their normal error handling. Native hosted search uses Responses when it is allowed by the preset.
`supportedApis` is a nonempty list of APIs this preset is allowed to use: `chat_completions`, `responses`, or `anthropic_messages`. `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 OpenAI APIs with `preferredApi: "responses"` to allow Chat fallback for classified Responses compatibility errors, when the endpoint serves that model through both APIs. Anthropic Messages must be declared alone; automatic fallback across Anthropic and OpenAI protocols is not supported. Separate fallback presets can use different protocols. Other failures retain their normal error handling. Native hosted search uses Responses when it is allowed 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.
A custom preset declaring `anthropic_messages` uses the Anthropic adapter for message history, tools, thinking, and streaming. Its connection retains the provider's key, base URL, headers, query parameters, body additions, and explicit proxy. Anthropic requests target `/v1/messages`; a trailing `/v1` in the configured base is normalized by the adapter. Model names use the connection's existing prefix rules. Selecting this protocol does not change other presets sharing the connection.
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.
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 use their connection API default when declared, otherwise Chat Completions. A preset can override that default only within the connection's declared supported APIs. 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 **Auto**, **Responses**, **Chat Completions**, or **Anthropic Messages**, according to the host's declared adapter support. 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 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.
@@ -69,8 +69,9 @@ nanobot agent -m "Hello!"
- Use separate provider names for separate endpoints.
- 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.
- Leave `apiType` unset for custom endpoints. Declare the endpoint's supported protocols and default with [`providers.<name>.api`](../configuration.md#custom-connection-apis), or use Supported APIs and Default API in the WebUI connection editor. Auto model presets inherit this default.
- 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.
- Custom gateways serving Anthropic Messages can use `api.supportedApis: ["anthropic_messages"]` in the preset, or select Anthropic Messages in the editor. This uses `/v1/messages` with the same provider connection.
## Security notes
+5 -5
View File
@@ -80,11 +80,11 @@ These fields answer different questions:
| `model` | `modelPresets.<name>.model` | The model ID expected by that provider or gateway. |
| `apiKey` | `providers.<provider>.apiKey` | Credential for that provider. Use `${ENV_VAR}` for secrets. |
| `apiBase` | `providers.<provider>.apiBase` | HTTP base URL of the provider endpoint. |
| `proxy` | `providers.<provider>.proxy` | Optional HTTP proxy for this provider only. Supported for OpenAI-compatible providers, OpenAI Codex, and xAI OAuth. |
| `proxy` | `providers.<provider>.proxy` | Optional HTTP proxy for this provider only. Supported for OpenAI-compatible providers, Anthropic Messages, OpenAI Codex, and xAI OAuth. |
You usually omit `apiBase` for hosted built-in providers such as OpenRouter, Anthropic direct, OpenAI direct, Groq, or Bedrock because nanobot knows their default endpoints. Set `apiBase` for `custom`, local OpenAI-compatible servers, provider proxies, regional endpoints, or subscription endpoints. Include the API version path when the endpoint requires it, for example `https://api.example.com/v1` or `http://localhost:11434/v1`.
Use `proxy` when one provider must send HTTP traffic through a proxy without changing process-wide `HTTP_PROXY` / `HTTPS_PROXY`. This is supported for providers that use nanobot's OpenAI-compatible client, including `openai`, `custom`, named custom providers, OpenRouter-style gateways, local OpenAI-compatible servers, and similar registry entries. It is also supported for `openai_codex` and `xai_grok`, including OAuth token exchange/refresh and model requests. Native provider backends such as `anthropic`, `bedrock`, `azure_openai`, and `github_copilot` reject `proxy`; use their endpoint-specific configuration instead.
Use `proxy` when one provider must send HTTP traffic through a proxy without changing process-wide `HTTP_PROXY` / `HTTPS_PROXY`. This is supported for providers that use nanobot's OpenAI-compatible client, including `openai`, `custom`, named custom providers, OpenRouter-style gateways, local OpenAI-compatible servers, and similar registry entries. It is also supported for Anthropic Messages, `openai_codex`, and `xai_grok`, including OAuth token exchange/refresh and model requests. Native `bedrock`, `azure_openai`, and `github_copilot` backends reject `proxy`; use their endpoint-specific configuration instead.
## Inline Image Requests
@@ -326,7 +326,7 @@ If you use an Anthropic-compatible proxy, keep the provider as `anthropic` and o
}
```
Arbitrary custom provider names are OpenAI-compatible only; they do not use the Anthropic Messages API request format.
Named custom providers can also serve Anthropic Messages: declare `providers.<name>.api.supportedApis: ["anthropic_messages"]`. Auto presets then use the Anthropic adapter with that connection's credentials and endpoint.
### OpenAI Direct
@@ -422,11 +422,11 @@ If you have more than one custom OpenAI-compatible endpoint, give each endpoint
}
```
Custom provider keys are treated as direct OpenAI-compatible providers. `apiBase` is required because nanobot cannot know the endpoint URL. `apiKey` is optional for local servers or private proxies that do not require one. Choose a name that does not conflict with a built-in provider name or alias, such as `openai`, `openai-codex`, `github-copilot`, or `lm-studio`. Do not set `apiType` on custom provider keys; `apiType` is only for `providers.openai`.
Custom provider keys define direct connections. Without an API declaration, they use OpenAI-compatible Chat Completions. `apiBase` is required because nanobot cannot know the endpoint URL. `apiKey` is optional for local servers or private proxies that do not require one. Choose a name that does not conflict with a built-in provider name or alias, such as `openai`, `openai-codex`, `github-copilot`, or `lm-studio`. Do not set `apiType` on custom provider keys; `apiType` is only for `providers.openai`.
If your custom endpoint documents a nonstandard thinking toggle, set `providers.<name>.thinkingStyle` to `thinking_type`, `enable_thinking`, or `reasoning_split`; nanobot then maps `reasoningEffort` onto that provider-specific request body. Leave it unset for ordinary OpenAI-compatible endpoints.
This named custom provider path is not for Anthropic-compatible endpoints. For Anthropic-compatible proxies, use `providers.anthropic.apiBase` and set the preset provider to `anthropic`.
Set `providers.<name>.api` to declare the connection's accepted protocols and default protocol. It accepts `chat_completions`, `responses`, and `anthropic_messages`; see [custom connection APIs](configuration.md#custom-connection-apis).
### ModelScope
+16 -3
View File
@@ -82,14 +82,14 @@ class DreamConfig(Base):
return f"every {hours}h"
class ModelAPIConfig(Base):
"""Allowed request APIs and preference for a model preset's endpoint."""
class ProviderAPIConfig(Base):
"""Request APIs accepted by a custom endpoint and its default API."""
supported_apis: tuple[RequestAPI, ...] = Field(min_length=1)
preferred_api: RequestAPI | None = None
@model_validator(mode="after")
def _validate_preference(self) -> "ModelAPIConfig":
def _validate_preference(self) -> "ProviderAPIConfig":
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
@@ -101,6 +101,18 @@ class ModelAPIConfig(Base):
)
class ModelAPIConfig(ProviderAPIConfig):
"""Allowed request APIs and preference for a model preset's endpoint."""
@model_validator(mode="after")
def _validate_api_family(self) -> "ModelAPIConfig":
if "anthropic_messages" in self.supported_apis and set(self.supported_apis) != {
"anthropic_messages",
}:
raise ValueError("anthropic_messages cannot be combined with OpenAI request APIs")
return self
class InlineFallbackConfig(Base):
"""One inline fallback model configuration."""
@@ -224,6 +236,7 @@ class ProviderConfig(Base):
)
api_key: str | None = Field(default=None, repr=False)
api_base: str | None = None
api: ProviderAPIConfig | None = Field(default=None, exclude_if=lambda value: value is None)
api_type: Literal["auto", "chat_completions", "responses"] = "auto" # Request API surface
extra_headers: dict[str, str] | None = None # Custom headers (e.g. APP-Code for AiHubMix)
extra_body: dict[str, Any] | None = None # Extra provider request fields; shape depends on provider/API surface
+24 -3
View File
@@ -10,7 +10,7 @@ import secrets
import string
from collections import deque
from collections.abc import Awaitable, Callable, Iterable
from typing import Any, cast
from typing import TYPE_CHECKING, Any, cast
from loguru import logger
@@ -24,6 +24,9 @@ from nanobot.providers.base import (
)
from nanobot.providers.images import prepare_message_images
if TYPE_CHECKING:
from nanobot.providers.registry import ProviderSpec
_ALNUM = string.ascii_letters + string.digits
@@ -94,12 +97,18 @@ class AnthropicProvider(LLMProvider):
extra_headers: dict[str, str] | None = None,
*,
provider_name: str = "anthropic",
extra_body: dict[str, Any] | None = None,
extra_query: dict[str, str] | None = None,
proxy: str | None = None,
spec: ProviderSpec | None = None,
):
super().__init__(api_key, api_base, provider_name=provider_name)
self.default_model = default_model
self.extra_headers = extra_headers or {}
self._extra_body = dict(extra_body or {})
self._spec = spec
from anthropic import AsyncAnthropic
from anthropic import AsyncAnthropic, DefaultAsyncHttpxClient
client_kw: dict[str, Any] = {}
if api_key:
@@ -108,6 +117,10 @@ class AnthropicProvider(LLMProvider):
client_kw["base_url"] = self._normalize_base_url(api_base)
if extra_headers:
client_kw["default_headers"] = extra_headers
if extra_query:
client_kw["default_query"] = extra_query
if proxy:
client_kw["http_client"] = DefaultAsyncHttpxClient(proxy=proxy, trust_env=False)
# Keep retries centralized in LLMProvider._run_with_retry to avoid retry amplification.
client_kw["max_retries"] = 0
self._client = AsyncAnthropic(**client_kw)
@@ -586,7 +599,10 @@ class AnthropicProvider(LLMProvider):
tool_choice: str | dict[str, Any] | None,
supports_caching: bool = True,
) -> dict[str, Any]:
model_name = self._strip_prefix(model or self.default_model)
model_name = (
self._spec.request_model_name(model or self.default_model)
if self._spec is not None else self._strip_prefix(model or self.default_model)
)
system, anthropic_msgs = self._convert_messages(self._sanitize_empty_content(messages))
anthropic_tools = self._convert_tools(tools)
@@ -649,6 +665,8 @@ class AnthropicProvider(LLMProvider):
if self.extra_headers:
kwargs["extra_headers"] = self.extra_headers
if self._extra_body:
kwargs["extra_body"] = self._extra_body
return kwargs
@@ -867,3 +885,6 @@ class AnthropicProvider(LLMProvider):
def get_default_model(self) -> str:
return self.default_model
async def aclose(self) -> None:
await self._client.close()
+70 -11
View File
@@ -5,10 +5,23 @@ from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from nanobot.config.schema import Config, InlineFallbackConfig, ModelPresetConfig, ProviderConfig
from nanobot.config.schema import (
Config,
InlineFallbackConfig,
ModelAPIConfig,
ModelPresetConfig,
ProviderConfig,
)
from nanobot.providers.base import GenerationSettings, LLMProvider
from nanobot.providers.fallback_provider import FallbackProvider
from nanobot.providers.registry import ProviderAPI, ProviderSpec, create_dynamic_spec, find_by_name
from nanobot.providers.registry import (
ModelAPICapabilities,
ProviderAPI,
ProviderSpec,
RequestAPI,
create_dynamic_spec,
find_by_name,
)
@dataclass(frozen=True)
@@ -28,6 +41,7 @@ class _ProviderSetup:
provider_config: ProviderConfig | None
spec: ProviderSpec | None
backend: str
model_api: ModelAPICapabilities | None
def _resolve_model_preset(
@@ -73,6 +87,37 @@ def _provider_spec_for_config(
return spec
def resolve_model_api(
spec: ProviderSpec,
provider_config: ProviderConfig | None,
preset_api: ModelAPIConfig | None,
) -> ModelAPICapabilities | None:
"""Apply the connection's API ceiling and default to a model declaration."""
connection_api = provider_config.api if provider_config else None
if connection_api is not None:
if not spec.provider_api_configurable:
raise ValueError(f"Provider '{spec.name}' does not support connection API declarations.")
spec.validate_model_api(connection_api.to_capabilities())
if preset_api is not None:
api = preset_api.to_capabilities()
spec.validate_model_api(api)
if connection_api is not None:
unsupported = set(api.supported_apis) - set(connection_api.supported_apis)
if unsupported:
raise ValueError(
f"Provider '{spec.name}' does not accept request APIs: {', '.join(sorted(unsupported))}"
)
return api
if connection_api is None:
return None
api = connection_api.to_capabilities()
# Selecting a default adapter does not authorize fallback across API families.
supported: tuple[RequestAPI, ...] = ("anthropic_messages",) if api.preferred_api == "anthropic_messages" else tuple(
item for item in api.supported_apis if item != "anthropic_messages"
)
return ModelAPICapabilities(supported_apis=supported, preferred_api=api.preferred_api)
def _resolve_provider_setup(
config: Config,
*,
@@ -97,19 +142,20 @@ 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 spec is not None:
spec.validate_model_api(preset.api.to_capabilities())
if p and p.proxy and backend not in {"openai_compat", "openai_codex", "xai_grok"}:
model_api = resolve_model_api(spec, p, preset.api) if spec is not None else None
if model_api is not None and model_api.preferred_api == "anthropic_messages":
backend = "anthropic"
if p and p.proxy and backend not in {"openai_compat", "openai_codex", "xai_grok", "anthropic"}:
raise ValueError(
f"providers.{provider_name}.proxy is only supported for "
"OpenAI-compatible providers, OpenAI Codex, and xAI Grok."
"OpenAI-compatible providers, Anthropic Messages, OpenAI Codex, and xAI Grok."
)
if backend == "azure_openai":
if not p or not p.api_base:
raise ValueError("Azure OpenAI requires api_base in config.")
elif (
backend == "openai_compat"
backend in {"openai_compat", "anthropic"}
and spec
and spec.is_direct
and not spec.default_api_base
@@ -130,6 +176,7 @@ def _resolve_provider_setup(
provider_config=p,
spec=spec,
backend=backend,
model_api=model_api,
)
@@ -137,7 +184,9 @@ 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)
setup = _resolve_provider_setup(config, preset=preset.model_copy(update={"api": None}))
if setup.model_api is not None:
return setup.provider_name, setup.model_api.preferred_api
spec = setup.spec
if spec is None:
return setup.provider_name, "chat_completions"
@@ -229,16 +278,24 @@ def _make_provider_core(
provider = GitHubCopilotProvider(
default_model=model, provider_name=provider_name,
model_api=preset.api.to_capabilities() if preset.api is not None else None,
model_api=setup.model_api,
)
elif backend == "anthropic":
from nanobot.providers.anthropic_provider import AnthropicProvider
custom_spec = spec if spec and spec.backend == "openai_compat" else None
api_key = p.api_key if p else None
if custom_spec is not None:
api_key = api_key or "no-key"
provider = AnthropicProvider(
api_key=p.api_key if p else None,
api_key=api_key,
api_base=config.get_api_base(model, preset=preset),
default_model=model,
extra_headers=_provider_extra_headers(spec, p),
extra_body=p.extra_body if p else None,
extra_query=p.extra_query if p else None,
proxy=p.proxy if p else None,
spec=custom_spec,
provider_name=provider_name,
)
elif backend == "bedrock":
@@ -264,7 +321,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,
model_api=setup.model_api,
extra_query=p.extra_query if p else None,
proxy=p.proxy if p else None,
provider_name=provider_name,
@@ -375,6 +432,7 @@ def provider_signature(
_provider_extra_headers(find_by_name(provider_name) if provider_name else None, fp),
fp.extra_body if fp else None,
fp.api_type if fp else "auto",
fp.api.model_dump_json() if fp and fp.api is not None else None,
fp.extra_query if fp else None,
getattr(fp, "region", None) if fp else None,
getattr(fp, "profile", None) if fp else None,
@@ -397,6 +455,7 @@ def provider_signature(
_provider_extra_headers(find_by_name(provider_name) if provider_name else None, p),
p.extra_body if p else None,
p.api_type if p else "auto",
p.api.model_dump_json() if p and p.api is not None else None,
p.extra_query if p else None,
getattr(p, "region", None) if p else None,
getattr(p, "profile", None) if p else None,
+10 -6
View File
@@ -17,7 +17,7 @@ from typing import Any, Literal, cast
from pydantic.alias_generators import to_snake
RequestAPI = Literal["chat_completions", "responses"]
RequestAPI = Literal["chat_completions", "responses", "anthropic_messages"]
ProviderAPI = Literal[
"chat_completions", "responses", "anthropic_messages", "bedrock_converse", "transcription",
]
@@ -130,8 +130,8 @@ class ProviderSpec:
name: str # config field name, e.g. "dashscope"
keywords: tuple[str, ...] # model-name keywords for matching (lowercase)
env_key: str # env var for API key, e.g. "DASHSCOPE_API_KEY"
# Request formats implemented by this adapter. Remote model support is
# separate: a compatible adapter does not guarantee both endpoint APIs.
# Request formats available through this provider's adapters. Remote model
# support is separate: an adapter does not guarantee endpoint support.
request_apis: tuple[ProviderAPI, ...]
display_name: str = "" # shown in `nanobot status`
model_catalog: str = "auto" # WebUI model-list source, including builtin/hybrid
@@ -270,7 +270,11 @@ class ProviderSpec:
@property
def model_api_configurable(self) -> bool:
return "chat_completions" in self.request_apis and "responses" in self.request_apis
return len(self.request_apis) > 1
@property
def provider_api_configurable(self) -> bool:
return self.is_direct and self.backend == "openai_compat" and "anthropic_messages" in self.request_apis
def validate_model_api(self, api: ModelAPICapabilities) -> None:
unsupported = set(api.supported_apis).difference(self.request_apis)
@@ -291,7 +295,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
name="custom",
keywords=(),
env_key="",
request_apis=("chat_completions", "responses"),
request_apis=("chat_completions", "responses", "anthropic_messages"),
display_name="Custom",
backend="openai_compat",
is_direct=True,
@@ -1022,7 +1026,7 @@ def create_dynamic_spec(
name=normalized,
keywords=(),
env_key="",
request_apis=("chat_completions", "responses"),
request_apis=("chat_completions", "responses", "anthropic_messages"),
display_name=display_name or name.replace("-", " ").replace("_", " ").title(),
backend="openai_compat",
is_direct=True,
+32 -6
View File
@@ -32,7 +32,7 @@ from nanobot.config.schema import (
ModelPresetConfig,
ProviderConfig,
)
from nanobot.providers.factory import resolve_automatic_model_api
from nanobot.providers.factory import resolve_automatic_model_api, resolve_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 (
@@ -91,6 +91,7 @@ class ModelSettingsPayload(TypedDict):
model_call_order_editable: bool
model_configuration_migratable: bool
model_api_resolution_supported: bool
provider_api_configuration_supported: bool
providers: list[dict[str, Any]]
@@ -226,6 +227,11 @@ def _provider_config_updates(query: QueryParams) -> dict[str, Any]:
):
if query_has_alias(query, snake, camel):
updates[snake] = _provider_json_setting(query, snake, camel)
if query_has_alias(query, "api", "api"):
try:
updates["api"] = json.loads(query_first(query, "api") or "null")
except ValueError as exc:
raise WebUISettingsError("api must declare supportedApis and a preferredApi from that list") from exc
return updates
@@ -439,9 +445,9 @@ def _provider_advanced_field_names(name: str, spec: Any) -> list[str]:
fields: list[str] = []
if spec.backend in {"openai_compat", "anthropic"}:
fields.append("extra_headers")
if spec.backend in {"openai_compat", "bedrock", "openai_codex", "xai_grok"}:
if spec.backend in {"openai_compat", "anthropic", "bedrock", "openai_codex", "xai_grok"}:
fields.append("extra_body")
if spec.backend == "openai_compat":
if spec.backend in {"openai_compat", "anthropic"}:
fields.extend(("extra_query", "proxy"))
if spec.name in _OAUTH_PROXY_PROVIDERS and "proxy" not in fields:
fields.append("proxy")
@@ -478,8 +484,11 @@ 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),
"request_apis": list(spec.request_apis),
"model_api_configurable": spec.model_api_configurable,
"request_apis": list(provider_config.api.supported_apis if provider_config.api else spec.request_apis),
"adapter_request_apis": list(spec.request_apis),
"api": provider_config.api.model_dump(mode="json") if provider_config.api else None,
"provider_api_configurable": spec.provider_api_configurable,
"model_api_configurable": len(provider_config.api.supported_apis) > 1 if provider_config.api else spec.model_api_configurable,
"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),
@@ -1125,6 +1134,7 @@ def model_settings_payload(
model_call_order, model_call_order_editable = _model_call_order_state(config)
return {
"model_api_resolution_supported": True,
"provider_api_configuration_supported": True,
"agent": {
"model": effective_preset.model,
"provider": selected_provider,
@@ -1233,7 +1243,7 @@ def _parse_preset_api(
if entry is None:
raise WebUISettingsError("unknown provider")
try:
entry[0].validate_model_api(api.to_capabilities())
resolve_model_api(entry[0], entry[2], api)
except ValueError as exc:
raise WebUISettingsError(str(exc)) from None
return api
@@ -1533,6 +1543,7 @@ def create_provider_settings(config: Config, query: QueryParams) -> str:
"extra_query",
"thinking_style",
"display_name",
"api",
}
unsupported = set(updates) - allowed
if unsupported:
@@ -1583,6 +1594,8 @@ def update_provider_settings(
}
if find_by_name(provider_key) is None:
allowed.add("display_name")
if spec.provider_api_configurable:
allowed.add("api")
unsupported = set(updates) - allowed
if unsupported:
field = sorted(unsupported)[0]
@@ -1598,6 +1611,19 @@ def update_provider_settings(
raise WebUISettingsError("provider already exists", status=409)
updated_provider_config = _validated_provider_config(provider_config, updates)
if updated_provider_config.api != provider_config.api:
candidates = [
*config.model_presets.values(), config.agents.defaults,
*(fallback for fallback in config.agents.defaults.fallback_models if not isinstance(fallback, str)),
]
try:
resolve_model_api(spec, updated_provider_config, None)
for candidate in candidates:
preset = ModelPresetConfig(model=candidate.model, provider=candidate.provider, api=candidate.api)
if config.get_provider_name(preset.model, preset=preset) == provider_key:
resolve_model_api(spec, updated_provider_config, preset.api)
except ValueError as exc:
raise WebUISettingsError(str(exc)) from None
changed = updated_provider_config != provider_config
if changed:
setattr(config.providers, provider_key, updated_provider_config)
+224 -12
View File
@@ -4,10 +4,18 @@ import json
import httpx
import pytest
from anthropic import AsyncAnthropic
from openai import AsyncOpenAI
from pydantic import ValidationError
from nanobot.config.schema import Config, InlineFallbackConfig, ModelAPIConfig, ModelPresetConfig
from nanobot.config.schema import (
Config,
InlineFallbackConfig,
ModelAPIConfig,
ModelPresetConfig,
ProviderAPIConfig,
)
from nanobot.providers.anthropic_provider import AnthropicProvider
from nanobot.providers.factory import (
make_provider,
provider_signature,
@@ -30,6 +38,11 @@ def _config() -> Config:
"provider": "tenant", "model": "gpt-6-luna",
"api": {"supportedApis": ["chat_completions"]},
},
"messages": {
"provider": "tenant", "model": "tenant/claude-sonnet-4-6",
"reasoningEffort": "high",
"api": {"supportedApis": ["anthropic_messages"]},
},
},
})
@@ -47,6 +60,21 @@ def _answer(request: httpx.Request) -> httpx.Response:
{"type": "response.output_text.delta", "delta": "ok"},
{"type": "response.completed", "response": response},
]
elif request.url.path.endswith("/messages"):
response = {
"id": "msg_fixture", "type": "message", "role": "assistant",
"model": "claude-sonnet-4-6", "content": [{"type": "text", "text": "ok"}],
"stop_reason": "end_turn", "stop_sequence": None,
"usage": {"input_tokens": 3, "output_tokens": 2},
}
events = [
{"type": "message_start", "message": {**response, "content": [], "stop_reason": None}},
{"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},
{"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "ok"}},
{"type": "content_block_stop", "index": 0},
{"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": None}, "usage": {"output_tokens": 2}},
{"type": "message_stop"},
]
else:
response = {"id": "chat_fixture", "choices": [{
"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop",
@@ -56,7 +84,7 @@ def _answer(request: httpx.Request) -> httpx.Response:
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),
content="".join(f"event: {event.get('type', 'message')}\ndata: {json.dumps(event)}\n\n" for event in events),
)
@@ -68,8 +96,12 @@ async def bind_transport():
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,
client_type = AsyncAnthropic if isinstance(provider, AnthropicProvider) else AsyncOpenAI
client = client_type(
api_key="fixture", base_url=str(original.base_url) if original else "https://tenant.test/v1",
default_headers=original.default_headers if original else None,
default_query=original.default_query if original else None,
max_retries=0,
http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)),
)
clients.append(client)
@@ -113,7 +145,7 @@ async def test_automatic_preview_matches_actual_request(
@pytest.mark.parametrize("stream", [False, True])
async def test_two_presets_route_same_gateway_model_independently(bind_transport, stream):
async def test_presets_route_same_gateway_independently(bind_transport, stream):
config = _config()
requests = []
@@ -124,7 +156,7 @@ async def test_two_presets_route_same_gateway_model_independently(bind_transport
tools = [{"type": "function", "function": {
"name": "lookup", "parameters": {"type": "object", "properties": {}},
}}]
for name in ("responses", "chat"):
for name in ("responses", "chat", "messages"):
provider = bind_transport(make_provider(config, preset_name=name), handler)
invoke = provider.chat_stream if stream else provider.chat
result = await invoke(
@@ -132,13 +164,20 @@ async def test_two_presets_route_same_gateway_model_independently(bind_transport
reasoning_effort=provider.generation.reasoning_effort,
)
assert result.content == "ok"
assert [request.url.path for request in requests] == ["/v1/responses", "/v1/chat/completions"]
assert [request.url.path for request in requests] == [
"/v1/responses", "/v1/chat/completions", "/v1/messages",
]
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
messages_body = json.loads(requests[2].content)
assert messages_body["model"] == "claude-sonnet-4-6"
assert messages_body["thinking"] == {"type": "enabled", "budget_tokens": 8192}
assert messages_body["tools"][0]["name"] == "lookup"
assert messages_body["tools"][0]["input_schema"] == tools[0]["function"]["parameters"]
@pytest.mark.parametrize("allow_chat", [False, True])
@@ -169,11 +208,12 @@ async def test_chat_compatibility_fallback_requires_preset_support(bind_transpor
@pytest.mark.parametrize("inline", [False, True])
async def test_fallback_preset_keeps_its_api_and_invalidates_runtime(bind_transport, monkeypatch, inline):
@pytest.mark.parametrize("fallback_name", ["chat", "messages"])
async def test_fallback_preset_keeps_its_api_and_invalidates_runtime(bind_transport, monkeypatch, inline, fallback_name):
config = _config()
fallback = config.model_presets["chat"]
fallback = config.model_presets[fallback_name]
config.agents.defaults.fallback_models = [
InlineFallbackConfig.model_validate(fallback.model_dump()) if inline else "chat",
InlineFallbackConfig.model_validate(fallback.model_dump()) if inline else fallback_name,
]
requests = []
@@ -190,9 +230,9 @@ async def test_fallback_preset_keeps_its_api_and_invalidates_runtime(bind_transp
provider = make_provider(config)
result = await provider.chat(messages=[{"role": "user", "content": "hello"}])
assert result.content == "ok"
assert requests == ["/v1/responses", "/v1/chat/completions"]
assert requests == ["/v1/responses", "/v1/messages" if fallback_name == "messages" else "/v1/chat/completions"]
previous = provider_signature(config)
candidate = config.agents.defaults.fallback_models[0] if inline else config.model_presets["chat"]
candidate = config.agents.defaults.fallback_models[0] if inline else fallback
candidate.api = ModelAPIConfig(supported_apis=("responses",))
assert provider_signature(config) != previous
config.agents.defaults.fallback_models = []
@@ -206,6 +246,68 @@ def test_preset_api_preference_must_be_supported():
ModelAPIConfig.model_validate({"supportedApis": ["chat_completions"], "preferredApi": "responses"})
@pytest.mark.parametrize("other_api", ["responses", "chat_completions"])
def test_messages_rejects_cross_protocol_fallback(other_api):
with pytest.raises(ValidationError, match="cannot be combined"):
ModelAPIConfig(supported_apis=("anthropic_messages", other_api))
@pytest.mark.parametrize("provider_name", ["tenant", "custom", "anthropic", "openai"])
async def test_messages_declaration_validates_adapter_before_loading_client(provider_name):
config = _config()
config.providers.custom.api_base = "https://tenant.test/v1"
config.providers.custom.api_key = "fixture"
config.providers.anthropic.api_key = "fixture"
config.providers.openai.api_key = "fixture"
preset = config.model_presets["messages"].model_copy(update={"provider": provider_name})
if provider_name == "openai":
with pytest.raises(ValueError, match="does not support anthropic_messages"):
make_provider(config, preset=preset)
else:
provider = make_provider(config, preset=preset)
assert isinstance(provider, AnthropicProvider)
await provider._client.close()
@pytest.mark.parametrize("stream", [False, True])
async def test_custom_messages_keeps_connection_options_and_tool_history(bind_transport, stream):
config = _config()
connection = config.get_provider(preset=config.model_presets["messages"])
connection.extra_headers = {"X-Gateway": "fixture"}
connection.extra_query = {"route": "claude"}
connection.extra_body = {"metadata": {"user_id": "fixture"}}
requests = []
def handler(request):
requests.append(request)
return _answer(request)
provider = bind_transport(make_provider(config, preset_name="messages"), handler)
invoke = provider.chat_stream if stream else provider.chat
result = await invoke([
{"role": "system", "content": "Use the lookup result."},
{"role": "user", "content": "lookup"},
{"role": "assistant", "content": "", "tool_calls": [{
"id": "toolu_fixture", "type": "function",
"function": {"name": "lookup", "arguments": "{}"},
}]},
{"role": "tool", "tool_call_id": "toolu_fixture", "content": "found"},
])
assert result.content == "ok"
assert len(requests) == 1
request = requests[0]
assert request.url.path == "/v1/messages"
assert request.url.params["route"] == "claude"
assert request.headers["X-Gateway"] == "fixture"
body = json.loads(request.content)
assert body["metadata"] == {"user_id": "fixture"}
assert body["model"] == "claude-sonnet-4-6"
assert body["system"][0]["text"] == "Use the lookup result."
assert body["messages"][-2]["content"][0]["type"] == "tool_use"
assert body["messages"][-1]["content"][0]["type"] == "tool_result"
assert body["messages"][-1]["content"][0]["tool_use_id"] == "toolu_fixture"
def test_fixed_provider_validates_preset_api_before_loading_client():
config = Config()
preset = ModelPresetConfig(
@@ -240,3 +342,113 @@ async def test_preset_overrides_legacy_openai_default_and_scopes_compaction(bind
result = await provider.chat(messages=[{"role": "user", "content": "hello"}])
assert result.content == "ok"
assert requests == ["/v1/responses" if preferred == "responses" else "/v1/chat/completions"]
async def test_custom_messages_uses_its_proxy_and_does_not_inherit_native_credentials(monkeypatch):
from anthropic import DefaultAsyncHttpxClient
config = _config()
connection = config.get_provider(preset=config.model_presets["messages"])
connection.api_key = None
connection.proxy = "http://proxy.test:8080"
monkeypatch.setenv("ANTHROPIC_API_KEY", "native-key")
monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "native-token")
requests = []
def handler(request):
requests.append(request)
return _answer(request)
def transport(**kwargs):
assert kwargs.pop("proxy") == connection.proxy
assert kwargs["trust_env"] is False
return DefaultAsyncHttpxClient(transport=httpx.MockTransport(handler), **kwargs)
monkeypatch.setattr("anthropic.DefaultAsyncHttpxClient", transport)
provider = make_provider(config, preset_name="messages")
try:
response = await provider.chat([{"role": "user", "content": "hello"}])
assert response.content == "ok"
assert len(requests) == 1
assert requests[0].headers["x-api-key"] == "no-key"
assert "authorization" not in requests[0].headers
finally:
await provider.aclose()
assert provider._client.is_closed()
@pytest.mark.parametrize("stream", [False, True])
@pytest.mark.parametrize("provider_name", ["tenant", "custom"])
@pytest.mark.parametrize("preferred,path", [
("chat_completions", "/v1/chat/completions"),
("responses", "/v1/responses"),
("anthropic_messages", "/v1/messages"),
])
async def test_connection_default_matches_auto_preview_and_wire(bind_transport, stream, provider_name, preferred, path):
config = Config.model_validate({"providers": {provider_name: {
"apiBase": "https://tenant.test/v1",
"api": {
"supportedApis": [preferred] if provider_name == "custom" else ["chat_completions", "responses", "anthropic_messages"],
"preferredApi": preferred,
},
}}})
preset = ModelPresetConfig(provider=provider_name, model=f"{provider_name}/served-model")
assert resolve_automatic_model_api(config, preset=preset) == (provider_name, preferred)
paths = []
def handler(request):
paths.append(request.url.path)
return _answer(request)
provider = bind_transport(make_provider(config, preset=preset), handler)
messages = [{"role": "user", "content": "hello"}]
invoke = provider.chat_stream if stream else provider.chat
assert (await invoke(messages, model=preset.model)).content == "ok"
assert paths == [path]
@pytest.mark.parametrize("preferred", ["responses", "anthropic_messages"])
def test_connection_single_api_constrains_presets_and_reload_signature(preferred):
config = _config()
before = provider_signature(config, preset_name="chat")
connection = config.providers.model_extra["tenant"]
connection.api = ProviderAPIConfig(supported_apis=(preferred,))
assert provider_signature(config, preset_name="chat") != before
auto = ModelPresetConfig(provider="tenant", model="served-model")
assert resolve_automatic_model_api(config, preset=auto) == ("tenant", preferred)
validate_provider_setup(config, preset=auto)
with pytest.raises(ValueError, match="does not accept request APIs"):
validate_provider_setup(config, preset_name="chat")
matching = "responses" if preferred == "responses" else "messages"
validate_provider_setup(config, preset_name=matching)
def test_custom_messages_requires_an_explicit_endpoint():
config = Config()
preset = ModelPresetConfig(
provider="custom", model="served-model",
api=ModelAPIConfig(supported_apis=("anthropic_messages",)),
)
with pytest.raises(ValueError, match="requires api_base"):
validate_provider_setup(config, preset=preset)
@pytest.mark.parametrize("preset_name,path", [
("responses", "/v1/responses"), ("chat", "/v1/chat/completions"), ("messages", "/v1/messages"),
])
async def test_explicit_model_api_overrides_connection_default(bind_transport, preset_name, path):
config = _config()
config.providers.model_extra["tenant"].api = ProviderAPIConfig(
supported_apis=("chat_completions", "responses", "anthropic_messages"),
preferred_api="anthropic_messages",
)
preset = config.model_presets[preset_name]
paths = []
def handler(request):
paths.append(request.url.path)
return _answer(request)
provider = bind_transport(make_provider(config, preset=preset), handler)
assert (await provider.chat([{"role": "user", "content": "hello"}], model=preset.model)).content == "ok"
assert paths == [path]
+91 -5
View File
@@ -746,14 +746,15 @@ 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):
@pytest.mark.parametrize("protocol", ["responses", "anthropic_messages"])
def test_custom_preset_api_round_trip_and_reset(tmp_path, monkeypatch, protocol):
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"}
api = {"supported_apis": [protocol], "preferred_api": protocol}
created = create_model_configuration({
"name": ["reasoning"], "provider": ["tenant"], "model": ["gpt-6-luna"],
"api": [json.dumps(api)],
@@ -764,14 +765,14 @@ def test_custom_preset_api_round_trip_and_reset(tmp_path, monkeypatch):
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
assert providers["tenant"]["request_apis"] == ["chat_completions", "responses"]
assert providers["tenant"]["request_apis"] == ["chat_completions", "responses", "anthropic_messages"]
assert providers["openai_codex"]["request_apis"] == ["responses"]
assert providers["anthropic"]["request_apis"] == ["anthropic_messages"]
assert providers["bedrock"]["request_apis"] == ["bedrock_converse"]
saved = load_config(config_path)
assert saved.model_presets["reasoning"].api.to_capabilities().preferred_api == "responses"
assert saved.model_presets["reasoning"].api.to_capabilities().preferred_api == protocol
assert json.loads(config_path.read_text(encoding="utf-8"))["modelPresets"]["reasoning"]["api"] == {
"supportedApis": ["responses"], "preferredApi": "responses",
"supportedApis": [protocol], "preferredApi": protocol,
}
update_model_call_order({"order": [json.dumps(["reasoning"])]})
@@ -789,6 +790,8 @@ def test_custom_preset_api_round_trip_and_reset(tmp_path, monkeypatch):
@pytest.mark.parametrize("provider,api,error", [
("openai", {"supportedApis": ["chat_completions"], "preferredApi": "responses"}, "api must declare"),
("anthropic", {"supportedApis": ["responses"]}, "does not support"),
("openai", {"supportedApis": ["anthropic_messages"]}, "does not support"),
("anthropic", {"supportedApis": ["anthropic_messages", "responses"]}, "api must declare"),
])
def test_create_preset_rejects_invalid_api_without_saving(tmp_path, monkeypatch, provider, api, error):
config_path = tmp_path / "config.json"
@@ -2656,3 +2659,86 @@ def test_azure_openai_spec_no_longer_requires_api_key() -> None:
spec = find_by_name("azure_openai")
assert spec is not None
assert _provider_requires_api_key(spec) is False
@pytest.mark.parametrize("protocol", ["chat_completions", "responses", "anthropic_messages"])
def test_custom_connection_api_create_edit_and_preset_ceiling(tmp_path, monkeypatch, protocol):
config_path = tmp_path / "config.json"
save_config(Config(), config_path)
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
api = {"supported_apis": [protocol], "preferred_api": protocol}
payload = create_provider_settings({
"name": ["Protocol Gateway"], "apiBase": ["https://tenant.test/v1"],
"api": [json.dumps(api)],
})
key = payload["created_provider"]
row = next(row for row in payload["providers"] if row["name"] == key)
assert payload["provider_api_configuration_supported"] is True
assert row["api"] == api
assert row["request_apis"] == [protocol]
assert row["adapter_request_apis"] == ["chat_completions", "responses", "anthropic_messages"]
assert row["provider_api_configurable"] is True
assert row["model_api_configurable"] is False
assert load_config(config_path).providers.model_extra[key].api.to_capabilities().preferred_api == protocol
create_model_configuration({
"name": ["supported"], "provider": [key], "model": ["served-model"],
"api": [json.dumps(api)],
})
other = "responses" if protocol != "responses" else "anthropic_messages"
before = config_path.read_bytes()
with pytest.raises(WebUISettingsError, match="does not accept request APIs"):
create_model_configuration({
"name": ["unsupported"], "provider": [key], "model": ["served-model"],
"api": [json.dumps({"supportedApis": [other]})],
})
with pytest.raises(WebUISettingsError, match="does not accept request APIs"):
update_provider_settings({
"provider": [key], "api": [json.dumps({"supportedApis": [other]})],
})
assert config_path.read_bytes() == before
expanded = {"supported_apis": [protocol, other], "preferred_api": other}
update_provider_settings({"provider": [key], "api": [json.dumps(expanded)]})
update_provider_settings({"provider": [key], "apiBase": ["https://changed.test/v1"]})
assert load_config(config_path).providers.model_extra[key].api.model_dump(mode="json") == expanded
update_provider_settings({"provider": [key], "api": ["null"]})
assert load_config(config_path).providers.model_extra[key].api is None
@pytest.mark.parametrize("api", [
{"supportedApis": []},
{"supportedApis": ["responses"], "preferredApi": "anthropic_messages"},
{"supportedApis": ["unknown"]},
])
def test_custom_connection_invalid_api_is_not_saved(tmp_path, monkeypatch, api):
config_path = tmp_path / "config.json"
save_config(Config(), config_path)
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
before = config_path.read_bytes()
with pytest.raises(WebUISettingsError):
create_provider_settings({
"name": ["Invalid"], "apiBase": ["https://tenant.test/v1"], "api": [json.dumps(api)],
})
assert config_path.read_bytes() == before
@pytest.mark.parametrize("target", ["default", "inline_fallback"])
def test_custom_connection_cannot_remove_api_used_by_legacy_or_inline_model(tmp_path, monkeypatch, target):
config = Config.model_validate({"providers": {"tenant": {"apiBase": "https://tenant.test/v1"}}})
api = ModelAPIConfig(supported_apis=("anthropic_messages",))
if target == "default":
config.agents.defaults.provider = "tenant"
config.agents.defaults.model = "served-model"
config.agents.defaults.api = api
else:
config.agents.defaults.fallback_models = [InlineFallbackConfig(
provider="tenant", model="served-model", api=api,
)]
config_path = tmp_path / "config.json"
save_config(config, config_path)
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
before = config_path.read_bytes()
with pytest.raises(WebUISettingsError, match="does not accept request APIs"):
update_provider_settings({
"provider": ["tenant"], "api": [json.dumps({"supportedApis": ["responses"]})],
})
assert config_path.read_bytes() == before
+1
View File
@@ -58,6 +58,7 @@ def test_model_domain_owns_dto_and_config_updates() -> None:
"model_call_order_editable",
"model_configuration_migratable",
"model_api_resolution_supported",
"provider_api_configuration_supported",
"providers",
}
assert payload["agent"]["model"] == "openai/gpt-5.4"
@@ -9,13 +9,16 @@ import type { ModelAPIConfig, ProviderRequestAPI, SettingsPayload } from "@/lib/
export function modelAPIConfigurable(provider: SettingsPayload["providers"][number] | undefined): boolean {
if (Array.isArray(provider?.request_apis)) {
return provider.request_apis.includes("chat_completions") && provider.request_apis.includes("responses");
const supported = provider.request_apis;
return (["chat_completions", "responses", "anthropic_messages"] as const)
.filter((api) => supported.includes(api)).length > 1;
}
return provider?.model_api_configurable === true;
}
export function modelAPISelection(api: ModelAPIConfig | null | undefined): string {
if (!api) return "auto";
if (api.supported_apis.includes("anthropic_messages")) return "anthropic_messages";
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"
@@ -58,8 +61,9 @@ export function ModelAPIControl({
? `${t("settings.models.apiAuto")} (${labels[automaticAPI]})`
: t("settings.models.apiAuto"),
},
{ value: "responses", label: "Responses" },
{ value: "chat_completions", label: "Chat Completions" },
...(["responses", "chat_completions", "anthropic_messages"] as const)
.filter((api) => requestAPIs ? requestAPIs.includes(api) : api !== "anthropic_messages")
.map((api) => ({ value: api, label: labels[api] })),
];
if (!configurable && !fixedLabel) return null;
@@ -70,7 +74,7 @@ export function ModelAPIControl({
<Select value={selectedAPI} onValueChange={(api) => {
if (api === selectedAPI) return;
if (api === "auto") onChange(null);
else if (api === "responses" || api === "chat_completions") {
else if (api === "responses" || api === "chat_completions" || api === "anthropic_messages") {
onChange({ supported_apis: [api], preferred_api: api });
}
}}>
@@ -98,7 +102,7 @@ export function ModelAPIControl({
<span className="block text-[13px] text-muted-foreground sm:text-right">{fixedLabel}</span>
)}
</SettingsRow>
{configurable && selectedAPI === "responses" ? (
{configurable && selectedAPI === "responses" && (!requestAPIs || requestAPIs.includes("chat_completions")) ? (
<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-[13px] leading-5 text-foreground">{t("settings.models.apiFallback")}</p>
@@ -242,14 +242,15 @@ export function ModelsSettings({
scope: string;
result: AutomaticModelAPIPayload;
} | null>(null);
const { provider: apiProvider, model: apiModel, reasoningEffort: apiReasoningEffort } = form;
const automaticAPIScope = JSON.stringify([
token, form.provider, form.model, form.reasoningEffort, settings.providers,
token, apiProvider, apiModel, apiReasoningEffort, settings.providers,
]);
useEffect(() => {
if (!editorOpen || settings.model_api_resolution_supported !== true || !form.model.trim()) return;
if (!editorOpen || settings.model_api_resolution_supported !== true || !apiModel.trim()) return;
let cancelled = false;
const timer = window.setTimeout(() => {
void fetchAutomaticModelAPI(token, form.provider, form.model, form.reasoningEffort)
void fetchAutomaticModelAPI(token, apiProvider, apiModel, apiReasoningEffort)
.then((result) => {
if (!cancelled) setAutomaticAPI({ scope: automaticAPIScope, result });
})
@@ -258,7 +259,7 @@ export function ModelsSettings({
});
}, 150);
return () => { cancelled = true; window.clearTimeout(timer); };
}, [editorOpen, settings.model_api_resolution_supported, automaticAPIScope, token, form]);
}, [editorOpen, settings.model_api_resolution_supported, automaticAPIScope, token, apiProvider, apiModel, apiReasoningEffort]);
const resolvedAutomaticAPI = settings.model_api_resolution_supported === true
&& automaticAPI?.scope === automaticAPIScope ? automaticAPI.result : null;
const editorTriggerRef = useRef<HTMLElement | null>(null);
@@ -0,0 +1,73 @@
import { useTranslation } from "react-i18next";
import { ToggleButton } from "@/components/settings/ToggleButton";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import type { ModelAPIConfig, ModelRequestAPI } from "@/lib/types";
const APIS: Array<{ value: ModelRequestAPI; label: string }> = [
{ value: "chat_completions", label: "Chat Completions" },
{ value: "responses", label: "Responses" },
{ value: "anthropic_messages", label: "Anthropic Messages" },
];
export function ProviderAPIControl({ value, onChange }: {
value: ModelAPIConfig | null;
onChange: (api: ModelAPIConfig) => void;
}) {
const { t } = useTranslation();
if (value === null) {
return (
<Button variant="outline" className="rounded-full" onClick={() => onChange({
supported_apis: ["chat_completions"], preferred_api: "chat_completions",
})}>
{t("settings.providers.declareAPIs")}
</Button>
);
}
const supported = value.supported_apis;
const preferred = value.preferred_api ?? supported[0];
return (
<div className="space-y-3">
<fieldset className="space-y-3 rounded-xl border border-border/60 p-3">
<legend className="px-1 text-[12px] font-medium text-muted-foreground">
{t("settings.providers.supportedAPIs")}
</legend>
{APIS.map((api) => {
const checked = supported.includes(api.value);
return (
<div key={api.value} className="flex items-center justify-between gap-3 text-[13px]">
<span>{api.label}</span>
<ToggleButton
label={api.label}
checked={checked}
disabled={checked && supported.length === 1}
onChange={(enabled) => {
const next = enabled ? [...supported, api.value] : supported.filter((item) => item !== api.value);
onChange({ supported_apis: next, preferred_api: next.includes(preferred) ? preferred : next[0] });
}}
/>
</div>
);
})}
</fieldset>
<div className="space-y-1.5">
<span className="text-[12px] font-medium text-muted-foreground">
{t("settings.providers.defaultAPI")}
</span>
<Select value={preferred} onValueChange={(api) => onChange({
supported_apis: supported, preferred_api: api as ModelRequestAPI,
})}>
<SelectTrigger aria-label={t("settings.providers.defaultAPI")} className="w-full rounded-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
{APIS.filter((api) => supported.includes(api.value)).map((api) => (
<SelectItem key={api.value} value={api.value}>{api.label}</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
);
}
@@ -25,6 +25,7 @@ import {
SettingsSectionTitle,
} from "@/components/settings/shared/SettingsControls";
import { ToggleButton } from "@/components/settings/ToggleButton";
import { ProviderAPIControl } from "@/components/settings/models/ProviderAPIControl";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -54,6 +55,7 @@ import { cn } from "@/lib/utils";
import { copyTextToClipboard } from "@/lib/clipboard";
import type {
NanobotFeaturesPayload,
ModelAPIConfig,
ProviderOAuthAuthorizationRequired,
SettingsPayload,
} from "@/lib/types";
@@ -67,6 +69,7 @@ export type ProviderForm = {
apiKey: string;
apiBase: string;
apiType: ProviderApiType;
api: ModelAPIConfig | null;
proxy: string;
extraHeaders: string;
extraBody: string;
@@ -208,6 +211,7 @@ export function providerFormFromRow(
apiKey: "",
apiBase: provider.api_base ?? provider.default_api_base ?? "",
apiType: provider.api_type ?? "auto",
api: provider.api ?? null,
proxy: provider.proxy ?? "",
extraHeaders: providerJsonValue(provider.extra_headers),
extraBody: providerJsonValue(provider.extra_body),
@@ -225,6 +229,7 @@ function emptyCustomProviderDraft(): CustomProviderDraft {
apiKey: "",
apiBase: "",
apiType: "auto",
api: { supported_apis: ["chat_completions"], preferred_api: "chat_completions" },
proxy: "",
extraHeaders: "",
extraBody: "",
@@ -1038,6 +1043,12 @@ export function ProvidersSettings({
form={form}
onChange={(value) => onChangeProviderForm(provider.name, value)}
/>
{provider.provider_api_configurable && (
<ProviderAPIControl
value={form.api}
onChange={(api) => onChangeProviderForm(provider.name, { api })}
/>
)}
<ProviderAdvancedOptions
fields={advancedFields}
form={form}
@@ -1178,6 +1189,12 @@ export function ProvidersSettings({
</Button>
</div>
</label>
{settings.provider_api_configuration_supported && (
<ProviderAPIControl
value={customProviderDraft.api}
onChange={(api) => setCustomProviderDraft((current) => ({ ...current, api }))}
/>
)}
<ProviderAdvancedOptions
fields={CUSTOM_PROVIDER_ADVANCED_FIELDS}
form={customProviderDraft}
@@ -7,7 +7,7 @@ import type {
PendingRestartSections,
} from "@/components/settings/contracts";
import { agentDraftFromPayload } from "@/components/settings/models/ModelsSettings";
import { modelAPIConfigurable, modelAPISelection } from "@/components/settings/models/ModelAPIControl";
import { modelAPISelection } from "@/components/settings/models/ModelAPIControl";
import {
CUSTOM_PROVIDER_CREATION_KEY,
providerFormFromRow,
@@ -196,8 +196,7 @@ export function useModelSettingsActions({
contextWindowTokens: form.contextWindowTokens,
temperature: form.temperature,
reasoningEffort: form.reasoningEffort || null,
api: modelAPIConfigurable(settings.providers.find((row) => row.name === provider))
? form.api : undefined,
api: form.api ?? undefined,
});
const createdPreset = payload.created_model_preset;
const nextOrder = createdPreset ? [...modelCallOrder, createdPreset] : null;
@@ -260,10 +259,7 @@ export function useModelSettingsActions({
form.temperature !== selectedPreset.temperature ? form.temperature : undefined,
reasoningEffort:
reasoningEffort !== selectedPreset.reasoning_effort ? reasoningEffort : undefined,
api: modelAPIConfigurable(settings.providers.find((row) => row.name === (
form.provider === "auto" ? selectedPreset.resolved_provider : form.provider
))) &&
modelAPISelection(form.api) !== modelAPISelection(selectedPreset.api)
api: modelAPISelection(form.api) !== modelAPISelection(selectedPreset.api)
? form.api : undefined,
});
applyPayload(payload);
@@ -411,6 +407,7 @@ export function useModelSettingsActions({
update.apiKey = apiKey || undefined;
update.apiBase = providerForm.apiBase.trim();
if (provider.is_custom) update.displayName = providerForm.displayName.trim();
if (provider.provider_api_configurable) update.api = providerForm.api;
}
for (const field of provider.advanced_fields ?? []) {
if (field === "api_type") update.apiType = providerForm.apiType;
@@ -464,6 +461,7 @@ export function useModelSettingsActions({
name: draft.name.trim(),
apiKey: draft.apiKey.trim() || undefined,
apiBase: draft.apiBase.trim(),
...(settings?.provider_api_configuration_supported ? { api: draft.api } : {}),
proxy: draft.proxy.trim(),
extraHeaders: draft.extraHeaders.trim(),
extraBody: draft.extraBody.trim(),
+3
View File
@@ -1194,6 +1194,9 @@
"saveProvider": "Save provider",
"advancedOptions": "Advanced options",
"saveAdvancedBeforeSignIn": "Save advanced changes before signing in.",
"supportedAPIs": "Supported APIs",
"defaultAPI": "Default API",
"declareAPIs": "Set supported APIs",
"apiType": "API type",
"proxy": "Network proxy",
"thinkingStyle": "Reasoning format",
+3
View File
@@ -774,6 +774,9 @@
"saveProvider": "Guardar proveedor",
"advancedOptions": "Opciones avanzadas",
"saveAdvancedBeforeSignIn": "Guarda los cambios avanzados antes de iniciar sesión.",
"supportedAPIs": "API compatibles",
"defaultAPI": "API predeterminada",
"declareAPIs": "Configurar API compatibles",
"apiType": "Tipo de API",
"proxy": "Proxy de red",
"thinkingStyle": "Formato de razonamiento",
+3
View File
@@ -774,6 +774,9 @@
"saveProvider": "Enregistrer le fournisseur",
"advancedOptions": "Options avancées",
"saveAdvancedBeforeSignIn": "Enregistrez les options avancées avant de vous connecter.",
"supportedAPIs": "API prises en charge",
"defaultAPI": "API par défaut",
"declareAPIs": "Définir les API prises en charge",
"apiType": "Type d’API",
"proxy": "Proxy réseau",
"thinkingStyle": "Format du raisonnement",
+3
View File
@@ -774,6 +774,9 @@
"saveProvider": "Simpan penyedia",
"advancedOptions": "Opsi lanjutan",
"saveAdvancedBeforeSignIn": "Simpan perubahan lanjutan sebelum masuk.",
"supportedAPIs": "API yang didukung",
"defaultAPI": "API default",
"declareAPIs": "Atur API yang didukung",
"apiType": "Jenis API",
"proxy": "Proksi jaringan",
"thinkingStyle": "Format penalaran",
+3
View File
@@ -774,6 +774,9 @@
"saveProvider": "プロバイダーを保存",
"advancedOptions": "詳細オプション",
"saveAdvancedBeforeSignIn": "サインインする前に詳細オプションを保存してください。",
"supportedAPIs": "対応する API",
"defaultAPI": "デフォルトの API",
"declareAPIs": "対応する API を設定",
"apiType": "API タイプ",
"proxy": "ネットワークプロキシ",
"thinkingStyle": "推論の形式",
+3
View File
@@ -774,6 +774,9 @@
"saveProvider": "제공업체 저장",
"advancedOptions": "고급 옵션",
"saveAdvancedBeforeSignIn": "로그인하기 전에 고급 옵션을 저장하세요.",
"supportedAPIs": "지원 API",
"defaultAPI": "기본 API",
"declareAPIs": "지원 API 설정",
"apiType": "API 유형",
"proxy": "네트워크 프록시",
"thinkingStyle": "추론 형식",
+3
View File
@@ -1008,6 +1008,9 @@
"saveProvider": "Salvar provedor",
"advancedOptions": "Opções avançadas",
"saveAdvancedBeforeSignIn": "Salve as alterações avançadas antes de entrar.",
"supportedAPIs": "APIs compatíveis",
"defaultAPI": "API padrão",
"declareAPIs": "Definir APIs compatíveis",
"apiType": "Tipo de API",
"proxy": "Proxy de rede",
"thinkingStyle": "Formato de raciocínio",
+3
View File
@@ -774,6 +774,9 @@
"saveProvider": "Lưu nhà cung cấp",
"advancedOptions": "Tùy chọn nâng cao",
"saveAdvancedBeforeSignIn": "Lưu các thay đổi nâng cao trước khi đăng nhập.",
"supportedAPIs": "API được hỗ trợ",
"defaultAPI": "API mặc định",
"declareAPIs": "Đặt API được hỗ trợ",
"apiType": "Loại API",
"proxy": "Proxy mạng",
"thinkingStyle": "Định dạng suy luận",
+3
View File
@@ -1194,6 +1194,9 @@
"saveProvider": "保存提供商",
"advancedOptions": "高级选项",
"saveAdvancedBeforeSignIn": "请先保存高级选项再登录。",
"supportedAPIs": "支持的协议",
"defaultAPI": "默认协议",
"declareAPIs": "设置支持的协议",
"apiType": "API 类型",
"proxy": "网络代理",
"thinkingStyle": "推理格式",
+3
View File
@@ -774,6 +774,9 @@
"saveProvider": "儲存供應商",
"advancedOptions": "進階選項",
"saveAdvancedBeforeSignIn": "請先儲存進階選項再登入。",
"supportedAPIs": "支援的協定",
"defaultAPI": "預設協定",
"declareAPIs": "設定支援的協定",
"apiType": "API 類型",
"proxy": "網路代理",
"thinkingStyle": "推理格式",
+11 -3
View File
@@ -595,9 +595,11 @@ export interface RuntimeCapabilities {
can_export_diagnostics: boolean;
}
export type ModelRequestAPI = "chat_completions" | "responses" | "anthropic_messages";
export interface ModelAPIConfig {
supported_apis: Array<"chat_completions" | "responses">;
preferred_api?: "chat_completions" | "responses" | null;
supported_apis: ModelRequestAPI[];
preferred_api?: ModelRequestAPI | null;
}
export type ProviderRequestAPI =
@@ -712,6 +714,7 @@ export interface SettingsPayload {
model_configuration_migratable?: boolean;
/** Host can resolve the default request API for an unsaved model configuration. */
model_api_resolution_supported?: boolean;
provider_api_configuration_supported?: boolean;
created_model_preset?: string;
created_provider?: string;
providers: Array<{
@@ -727,8 +730,11 @@ export interface SettingsPayload {
model_selectable?: boolean;
model_catalog?: ProviderModelsPayload["catalog_kind"];
model_api_configurable?: boolean;
/** Request formats implemented by the host's provider adapter. */
/** Request formats allowed by this connection, or adapter formats when undeclared. */
request_apis?: ProviderRequestAPI[];
adapter_request_apis?: ProviderRequestAPI[];
provider_api_configurable?: boolean;
api?: ModelAPIConfig | null;
api_type?: "auto" | "chat_completions" | "responses";
oauth_account?: string | null;
oauth_expires_at?: number | null;
@@ -1349,6 +1355,7 @@ export interface ProviderSettingsUpdate {
apiKey?: string;
apiBase?: string;
apiType?: "auto" | "chat_completions" | "responses";
api?: ModelAPIConfig | null;
proxy?: string;
extraHeaders?: string;
extraBody?: string;
@@ -1362,6 +1369,7 @@ export interface ProviderCreationUpdate {
name: string;
apiKey?: string;
apiBase: string;
api?: ModelAPIConfig | null;
proxy?: string;
extraHeaders?: string;
extraBody?: string;
+77 -1
View File
@@ -148,6 +148,82 @@ describe("Settings models", () => {
expect(vi.mocked(fetch).mock.calls.some(([url]) => String(url).includes("/model-api?"))).toBe(false);
});
it("saves and restores Anthropic Messages for a custom gateway", async () => {
let payload = settingsPayload();
payload.providers = [{
name: "tenant", label: "Tenant", configured: true,
request_apis: ["chat_completions", "responses", "anthropic_messages"],
}];
payload.model_presets[0].provider = "tenant";
payload.model_presets[0].resolved_provider = "tenant";
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("API connection"));
expect(screen.getAllByRole("option")).toHaveLength(4);
fireEvent.click(screen.getByRole("option", { name: "Anthropic Messages" }));
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: { supported_apis: ["anthropic_messages"], preferred_api: "anthropic_messages" } },
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("API connection")).toHaveTextContent("Anthropic Messages");
expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();
await openPopover(screen.getByLabelText("API connection"));
fireEvent.click(screen.getByRole("option", { name: "Responses" }));
expect(screen.getByRole("switch", { name: "Try Chat Completions if Responses is unsupported" })).not.toBeChecked();
});
it("saves an explicit API after an Auto provider resolves the changed model to a new connection", async () => {
const payload = settingsPayload();
payload.model_api_resolution_supported = true;
payload.model_presets[0] = {
...payload.model_presets[0], provider: "auto", model: "anthropic/claude-sonnet-4",
resolved_provider: "anthropic",
};
payload.providers = [
{ name: "anthropic", label: "Anthropic", configured: true, request_apis: ["anthropic_messages"] },
{ 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(url.searchParams.get("model")?.startsWith("gpt")
? { provider: "openai", api: "chat_completions" }
: { provider: "anthropic", api: "anthropic_messages" });
}));
requestMutationMock.mockResolvedValue(payload);
renderSettingsView({ initialSection: "models", initialSettings: payload });
await togglePresetEditor();
await openPopover(screen.getByRole("button", { name: "anthropic/claude-sonnet-4", exact: true }));
const search = screen.getByRole("combobox", { name: "Search or type model ID" });
fireEvent.change(search, { target: { value: "gpt-4o" } });
fireEvent.keyDown(search, { key: "Enter" });
await waitFor(() => expect(screen.getByLabelText("API connection")).toHaveTextContent("Auto (Chat Completions)"));
await openPopover(screen.getByLabelText("API connection"));
fireEvent.click(screen.getByRole("option", { name: "Responses" }));
fireEvent.click(screen.getByRole("button", { name: "Save", exact: true }));
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
"settings.model_configuration.update", {
name: "primary", model: "gpt-4o",
api: { supported_apis: ["responses"], preferred_api: "responses" },
}, 20_000,
));
});
it("shows the host's automatic API and discards an older reasoning resolution", async () => {
const payload = settingsPayload();
payload.model_api_resolution_supported = true;
@@ -228,7 +304,7 @@ describe("Settings models", () => {
expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();
});
it.each([undefined, ["future_api"], "responses"])("hides API controls when host support is unconfirmed (%s)", async (requestAPIs) => {
it.each([undefined, ["future_api"], ["future_api", "future_api_v2"], "responses"])("hides API controls when host support is unconfirmed (%s)", async (requestAPIs) => {
const payload = settingsPayload();
vi.stubGlobal("fetch", vi.fn(async () => jsonResponse({
...payload,
@@ -981,4 +981,61 @@ describe("Settings providers", () => {
screen.getByRole("button", { name: "Add provider" }),
).toBeInTheDocument();
});
it("declares custom connection APIs on creation and preserves them when editing", async () => {
const user = userEvent.setup();
let payload = settingsPayload();
payload.provider_api_configuration_supported = true;
const api = { supported_apis: ["anthropic_messages" as const], preferred_api: "anthropic_messages" as const };
requestMutationMock.mockImplementation(async (action, args) => {
if (action === "settings.provider.create") {
payload = {
...payload,
providers: [...payload.providers, {
name: "tenant", label: "Tenant", is_custom: true, configured: true,
api_base: args.apiBase, api: args.api,
provider_api_configurable: true,
request_apis: args.api.supported_apis,
}],
};
}
if (action === "settings.provider.update") {
payload = { ...payload, providers: payload.providers.map((row) => row.name === "tenant"
? { ...row, api: args.api, request_apis: args.api.supported_apis } : row) };
}
return payload;
});
renderSettingsView({ initialSection: "models", initialSettings: payload });
await user.click(screen.getByRole("button", { name: "Add provider" }));
await user.click(screen.getByRole("button", { name: "Custom provider" }));
await user.type(screen.getByPlaceholderText("My model provider"), "Tenant");
await user.type(screen.getByPlaceholderText("https://api.example.com/v1"), "https://tenant.test");
expect(screen.getByRole("switch", { name: "Chat Completions" })).toBeDisabled();
await user.click(screen.getByRole("switch", { name: "Anthropic Messages" }));
await user.click(screen.getByRole("switch", { name: "Chat Completions" }));
expect(screen.getByRole("combobox", { name: "Default API" })).toHaveTextContent("Anthropic Messages");
expect(screen.getByRole("switch", { name: "Anthropic Messages" })).toBeDisabled();
await user.click(screen.getByRole("button", { name: "Save provider" }));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(requestMutationMock).toHaveBeenCalledWith("settings.provider.create", expect.objectContaining({ api }), 20_000);
await user.click(screen.getByRole("button", { name: "Tenant", exact: true }));
expect(screen.getByRole("combobox", { name: "Default API" })).toHaveTextContent("Anthropic Messages");
await user.click(screen.getByRole("switch", { name: "Responses" }));
await user.click(screen.getByRole("combobox", { name: "Default API" }));
await user.click(screen.getByRole("option", { name: "Responses" }));
await user.click(screen.getByRole("button", { name: "Save provider" }));
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith("settings.provider.update", expect.objectContaining({
provider: "tenant", api: { supported_apis: ["anthropic_messages", "responses"], preferred_api: "responses" },
}), 20_000));
await user.click(screen.getByRole("button", { name: "Tenant", exact: true }));
expect(screen.getByRole("combobox", { name: "Default API" })).toHaveTextContent("Responses");
});
it("hides connection API declarations on hosts without the capability", async () => {
renderSettingsView({ initialSection: "models", initialSettings: settingsPayload() });
fireEvent.click(screen.getByRole("button", { name: "Add provider" }));
fireEvent.click(screen.getByRole("button", { name: "Custom provider" }));
expect(screen.queryByRole("combobox", { name: "Default API" })).not.toBeInTheDocument();
expect(screen.queryByRole("group", { name: "Supported APIs" })).not.toBeInTheDocument();
});
});