refactor(providers): migrate legacy API selector at input boundary
This commit is contained in:
1 parent
ed0eb89178
commit
7e2e804b5c
36 files changed
+294
-181
No files matched your search
+20
-6
@@ -316,20 +316,20 @@ Tracing covers the providers that go through nanobot's OpenAI-compatible client
|
||||
<details>
|
||||
<summary><b>OpenAI</b></summary>
|
||||
|
||||
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:
|
||||
Without an API declaration, direct OpenAI calls Chat Completions normally and routes GPT-5/GPT-6/o-series or explicit `reasoningEffort` requests through Responses. Set `providers.openai.api` to change the connection default, or use [preset API declarations](#preset-request-api) for individual models:
|
||||
|
||||
```json
|
||||
{
|
||||
"providers": {
|
||||
"openai": {
|
||||
"apiKey": "${OPENAI_API_KEY}",
|
||||
"apiType": "chat_completions"
|
||||
"api": { "supportedApis": ["chat_completions"], "preferredApi": "chat_completions" }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Valid `apiType` values are exactly `auto`, `chat_completions`, and `responses`.
|
||||
For OpenAI, the connection declaration is a default: explicit model presets can select any API supported by the adapter. Use only `chat_completions` and/or `responses`. Omit `api` or set it to `null` for automatic routing. A Responses-only declaration prevents Chat compatibility fallback; include both APIs to permit that fallback.
|
||||
|
||||
`extraBody` follows the selected OpenAI API surface. With Chat Completions, nanobot passes
|
||||
ordinary fields through as the SDK `extra_body` value; list-valued `extraBody.tools` is handled
|
||||
@@ -342,7 +342,7 @@ API body shape; nanobot merges ordinary top-level fields into the Responses requ
|
||||
"providers": {
|
||||
"openai": {
|
||||
"apiKey": "${OPENAI_API_KEY}",
|
||||
"apiType": "responses",
|
||||
"api": { "supportedApis": ["responses"], "preferredApi": "responses" },
|
||||
"extraBody": {
|
||||
"tools": [{ "type": "web_search" }],
|
||||
"include": ["web_search_call.action.sources"]
|
||||
@@ -352,7 +352,7 @@ API body shape; nanobot merges ordinary top-level fields into the Responses requ
|
||||
}
|
||||
```
|
||||
|
||||
The WebUI's OpenAI web-search switch writes the corresponding `apiType` and `extraBody.tools`
|
||||
The WebUI's OpenAI web-search switch writes a Responses-only `api` declaration and `extraBody.tools`
|
||||
fields. A hosted search tool replaces nanobot's same-name local `web_search` function for that
|
||||
request, while other tools such as `web_fetch` remain available.
|
||||
|
||||
@@ -1460,6 +1460,20 @@ For the built-in `custom` connection or any named custom provider, declare the p
|
||||
|
||||
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.
|
||||
|
||||
### Legacy OpenAI API selector migration
|
||||
|
||||
`providers.openai.apiType` (or `api_type`) is accepted only as temporary input compatibility.
|
||||
`chat_completions` and `responses` convert to a single-API connection declaration; `auto`
|
||||
leaves automatic routing enabled. If `api` is also present, it wins, including `api: null`.
|
||||
Saving configuration writes only the current declaration. Runtime adapters and the WebUI
|
||||
use `api`; the OpenAI connection default remains overridable by explicit model presets.
|
||||
|
||||
The conversion is supported for the first release containing this migration and the immediately
|
||||
following release. It will be removed before the third release. During this window, older clients'
|
||||
OpenAI settings mutations using `apiType` are converted at the settings input boundary as well.
|
||||
Save the configuration with a supported release to migrate it before upgrading beyond this window.
|
||||
See the [release removal checklist](./releasing.md#openai-api-selector-compatibility-window).
|
||||
|
||||
### Preset request API
|
||||
|
||||
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.
|
||||
@@ -1492,7 +1506,7 @@ Leave API selection on **Auto** unless your provider requires a specific endpoin
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
Omit `api` or set it to `null` for automatic routing. An explicit model declaration overrides the OpenAI connection default. 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.
|
||||
|
||||
|
||||
+2
-2
@@ -353,7 +353,7 @@ Named custom providers can also serve Anthropic Messages: declare `providers.<na
|
||||
}
|
||||
```
|
||||
|
||||
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`.
|
||||
Use [preset API declarations](./configuration.md#preset-request-api) to choose Chat Completions or Responses for each model and endpoint. Set `providers.openai.api` for the connection default; explicit presets override it. The old `apiType` input is converted during the [two-release compatibility window](./configuration.md#legacy-openai-api-selector-migration). 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'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.
|
||||
|
||||
@@ -422,7 +422,7 @@ If you have more than one custom OpenAI-compatible endpoint, give each endpoint
|
||||
}
|
||||
```
|
||||
|
||||
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`.
|
||||
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`. Declare the accepted protocols under `api` as described in [connection request APIs](./configuration.md#custom-connection-apis).
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -45,6 +45,19 @@ uploading to PyPI, and deploying the documentation are separate operations.
|
||||
tagging. Reconcile the final changelog and documentation source references. The tag must
|
||||
point to this verified commit, not an unchecked later `main` tip.
|
||||
|
||||
### OpenAI API selector compatibility window
|
||||
|
||||
The temporary `providers.openai.apiType` / `api_type` conversion is supported for exactly
|
||||
two consecutive releases: the first release containing `nanobot/config/provider_api_migration.py`
|
||||
and the next release. Record the first release tag and the final supported tag in release notes.
|
||||
Config saves write the new `api` declaration; there is no legacy runtime selector.
|
||||
|
||||
Before publishing the third release, remove `provider_api_migration.py`, its import and
|
||||
`ProvidersConfig._migrate_legacy_api_type`, and the legacy settings query conversion in
|
||||
`nanobot/webui/settings_models.py`. Remove the migration-specific tests and update the
|
||||
configuration documentation and release notes to require the current format. Keep the
|
||||
current-format routing, settings, and persistence regressions.
|
||||
|
||||
### TUI preflight without a release tag
|
||||
|
||||
Use Bun 1.3.13 and a clean checkout. The local build and packaging scripts do not require a
|
||||
|
||||
@@ -47,7 +47,7 @@ from nanobot.channels.websocket.runtime import (
|
||||
_parse_inbound_payload,
|
||||
)
|
||||
from nanobot.config.loader import load_config, save_config
|
||||
from nanobot.config.schema import Config, ModelPresetConfig
|
||||
from nanobot.config.schema import Config, ModelAPIConfig, ModelPresetConfig
|
||||
from nanobot.providers.base import LLMUsage
|
||||
from nanobot.runtime_context import RUNTIME_CONTEXT_INPUT_META, WEBUI_QUOTE_SOURCE
|
||||
from nanobot.security.workspace_access import WORKSPACE_SCOPE_METADATA_KEY
|
||||
@@ -4842,18 +4842,19 @@ def test_settings_payload_normalizes_camel_case_provider(
|
||||
assert body["agent"]["provider"] == "minimax_anthropic"
|
||||
|
||||
|
||||
def test_settings_payload_exposes_api_type_only_for_openai(monkeypatch, tmp_path) -> None:
|
||||
def test_settings_payload_exposes_openai_api_defaults(monkeypatch, tmp_path) -> None:
|
||||
config_path = tmp_path / "config.json"
|
||||
config = Config()
|
||||
config.providers.openai.api_type = "responses"
|
||||
config.providers.openai.api = ModelAPIConfig(supported_apis=("responses",), preferred_api="responses")
|
||||
save_config(config, config_path)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
|
||||
body = settings_payload()
|
||||
providers = {provider["name"]: provider for provider in body["providers"]}
|
||||
|
||||
assert providers["openai"]["api_type"] == "responses"
|
||||
assert "api_type" not in providers["custom"]
|
||||
assert providers["openai"]["api"] == {"supported_apis": ["responses"], "preferred_api": "responses"}
|
||||
assert providers["openai"]["request_apis"] == ["chat_completions", "responses"]
|
||||
assert providers["custom"]["api"] is None
|
||||
|
||||
|
||||
def test_settings_payload_reports_workspace_sandbox(monkeypatch, tmp_path) -> None:
|
||||
@@ -4908,7 +4909,7 @@ def test_update_provider_settings_ignores_api_type_for_non_openai(monkeypatch, t
|
||||
assert body["providers"]
|
||||
config = load_config(config_path)
|
||||
assert config.providers.custom.api_base == "https://example.test/v1"
|
||||
assert config.providers.custom.api_type == "auto"
|
||||
assert config.providers.custom.api is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Temporary input compatibility for the former OpenAI API selector.
|
||||
|
||||
Keep this conversion for the first two releases shipping it; remove it before
|
||||
the third release. The removal checklist is in docs/releasing.md.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def migrate_legacy_provider_api(
|
||||
values: dict[str, Any], *, provider_name: str,
|
||||
) -> dict[str, Any]:
|
||||
"""Consume old input keys; all callers receive the current API declaration."""
|
||||
if "apiType" not in values and "api_type" not in values:
|
||||
return values
|
||||
migrated = dict(values)
|
||||
legacy = migrated.pop("apiType", migrated.get("api_type", "auto"))
|
||||
migrated.pop("api_type", None)
|
||||
if "api" in migrated:
|
||||
return migrated
|
||||
if legacy not in ("auto", "chat_completions", "responses"):
|
||||
raise ValueError("apiType must be auto, chat_completions, or responses")
|
||||
if legacy == "auto":
|
||||
migrated["api"] = None
|
||||
return migrated
|
||||
if provider_name != "openai":
|
||||
raise ValueError("apiType is only supported for providers.openai")
|
||||
migrated["api"] = {"supported_apis": [legacy], "preferred_api": legacy}
|
||||
return migrated
|
||||
+14
-14
@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Any, ClassVar, Literal, cast
|
||||
from pydantic import AliasChoices, ConfigDict, Field, PrivateAttr, field_validator, model_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
from nanobot.config.provider_api_migration import migrate_legacy_provider_api
|
||||
from nanobot.config.timezone import detect_system_timezone
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.cron.types import CronSchedule
|
||||
@@ -83,7 +84,7 @@ class DreamConfig(Base):
|
||||
|
||||
|
||||
class ProviderAPIConfig(Base):
|
||||
"""Request APIs accepted by a custom endpoint and its default API."""
|
||||
"""Connection API defaults and custom endpoints' accepted request APIs."""
|
||||
|
||||
supported_apis: tuple[RequestAPI, ...] = Field(min_length=1)
|
||||
preferred_api: RequestAPI | None = None
|
||||
@@ -237,7 +238,6 @@ 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
|
||||
extra_query: dict[str, str] | None = None # Extra query params (e.g. api-version for Azure-style gateways)
|
||||
@@ -346,18 +346,18 @@ class ProvidersConfig(Base):
|
||||
self.model_extra[key] = ProviderConfig.model_validate(value)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _validate_api_type_scope(self) -> "ProvidersConfig":
|
||||
for name in self.__class__.model_fields:
|
||||
if name == "openai":
|
||||
continue
|
||||
provider = getattr(self, name, None)
|
||||
if isinstance(provider, ProviderConfig) and provider.api_type != "auto":
|
||||
raise ValueError("providers.<name>.api_type is only supported for providers.openai")
|
||||
for provider in (self.model_extra or {}).values():
|
||||
if isinstance(provider, ProviderConfig) and provider.api_type != "auto":
|
||||
raise ValueError("providers.<name>.api_type is only supported for providers.openai")
|
||||
return self
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _migrate_legacy_api_type(cls, value: Any) -> Any:
|
||||
# Temporary for two releases; remove with provider_api_migration.py.
|
||||
if not isinstance(value, dict):
|
||||
return value
|
||||
providers = cast(dict[str, Any], value)
|
||||
return {
|
||||
name: migrate_legacy_provider_api(cast(dict[str, Any], provider), provider_name=name)
|
||||
if isinstance(provider, dict) else provider
|
||||
for name, provider in providers.items()
|
||||
}
|
||||
|
||||
|
||||
class HeartbeatConfig(Base):
|
||||
|
||||
@@ -143,7 +143,6 @@ def _make_provider_core(
|
||||
extra_headers=_provider_extra_headers(spec, p),
|
||||
spec=spec,
|
||||
extra_body=p.extra_body if p else None,
|
||||
api_type=p.api_type if p else "auto",
|
||||
model_api=setup.model_api,
|
||||
extra_query=p.extra_query if p else None,
|
||||
proxy=p.proxy if p else None,
|
||||
@@ -245,7 +244,6 @@ def _preset_provider_signature(
|
||||
config.get_api_base(preset.model, preset=preset),
|
||||
_provider_extra_headers(find_by_name(provider_name) if provider_name else None, provider_config),
|
||||
provider_config.extra_body if provider_config else None,
|
||||
provider_config.api_type if provider_config else "auto",
|
||||
provider_config.api.model_dump_json() if provider_config and provider_config.api is not None else None,
|
||||
provider_config.extra_query if provider_config else None,
|
||||
getattr(provider_config, "region", None) if provider_config else None,
|
||||
|
||||
@@ -492,7 +492,6 @@ class OpenAICompatProvider(LLMProvider):
|
||||
extra_headers: dict[str, str] | None = None,
|
||||
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,
|
||||
@@ -504,12 +503,6 @@ class OpenAICompatProvider(LLMProvider):
|
||||
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 = (
|
||||
api_type
|
||||
if responses is not None and responses.allows_api_type_override
|
||||
else "auto"
|
||||
)
|
||||
self._extra_query = extra_query or {}
|
||||
self._proxy = proxy or None
|
||||
self._responses = ResponsesBackend()
|
||||
@@ -1096,7 +1089,7 @@ class OpenAICompatProvider(LLMProvider):
|
||||
return ModelAPICapabilities()
|
||||
return self._spec.default_model_api(
|
||||
model or self.default_model, reasoning_effort,
|
||||
api_base=self._effective_base, api_type=self._api_type, extra_body=self._extra_body,
|
||||
api_base=self._effective_base, extra_body=self._extra_body,
|
||||
)
|
||||
|
||||
def _responses_is_required(
|
||||
@@ -1151,8 +1144,6 @@ class OpenAICompatProvider(LLMProvider):
|
||||
return False
|
||||
if self._preset_model_api.preferred_api != "responses" and not self._hosted_web_search_enabled():
|
||||
return False
|
||||
elif self._api_type == "chat_completions":
|
||||
return False
|
||||
if (
|
||||
capabilities.requires_direct_openai_base
|
||||
and not is_direct_openai_base(self._effective_base)
|
||||
|
||||
@@ -88,7 +88,6 @@ class ResponsesCapabilities:
|
||||
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"
|
||||
supports_native_compaction: bool = False
|
||||
allows_chat_fallback: bool = True
|
||||
@@ -247,18 +246,12 @@ class ProviderSpec:
|
||||
reasoning_effort: str | None = None,
|
||||
*,
|
||||
api_base: str | None = None,
|
||||
api_type: str = "auto",
|
||||
extra_body: dict[str, Any] | None = None,
|
||||
) -> ModelAPICapabilities:
|
||||
"""Resolve automatic API defaults without constructing or probing a client."""
|
||||
capabilities = self.responses
|
||||
if capabilities is None:
|
||||
return ModelAPICapabilities()
|
||||
if capabilities.allows_api_type_override:
|
||||
if api_type == "chat_completions":
|
||||
return ModelAPICapabilities()
|
||||
if api_type == "responses":
|
||||
return ModelAPICapabilities(("responses",), "responses")
|
||||
model_name = self.request_model_name(model)
|
||||
if hosted_web_search_enabled(extra_body or {}, self.responses_default_tools) and (
|
||||
capabilities.route_reasoning or capabilities.matches_model(model_name)
|
||||
@@ -274,7 +267,9 @@ class ProviderSpec:
|
||||
|
||||
@property
|
||||
def provider_api_configurable(self) -> bool:
|
||||
return self.is_direct and self.backend == "openai_compat" and "anthropic_messages" in self.request_apis
|
||||
return self.name == "openai" or (
|
||||
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)
|
||||
@@ -577,7 +572,6 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
|
||||
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",
|
||||
supports_native_compaction=True,
|
||||
),
|
||||
|
||||
@@ -69,7 +69,8 @@ def resolve_model_api(
|
||||
if preset_api is not None:
|
||||
api = preset_api.to_capabilities()
|
||||
spec.validate_model_api(api)
|
||||
if connection_api is not None:
|
||||
# Built-in OpenAI declares defaults; custom endpoints declare an API ceiling.
|
||||
if connection_api is not None and spec.is_direct:
|
||||
unsupported = set(api.supported_apis) - set(connection_api.supported_apis)
|
||||
if unsupported:
|
||||
raise ValueError(
|
||||
@@ -178,7 +179,6 @@ def resolve_automatic_model_api(
|
||||
api = spec.default_model_api(
|
||||
setup.model, preset.reasoning_effort,
|
||||
api_base=config.get_api_base(setup.model, preset=preset),
|
||||
api_type=provider_config.api_type if provider_config else "auto",
|
||||
extra_body=provider_config.extra_body if provider_config else None,
|
||||
)
|
||||
return setup.provider_name, api.preferred_api
|
||||
|
||||
@@ -25,6 +25,7 @@ from typing import TYPE_CHECKING, Any, Awaitable, Callable, TypedDict, cast
|
||||
import httpx
|
||||
|
||||
from nanobot.config.loader import resolve_config_env_vars
|
||||
from nanobot.config.provider_api_migration import migrate_legacy_provider_api
|
||||
from nanobot.config.schema import (
|
||||
Config,
|
||||
FallbackCandidate,
|
||||
@@ -208,7 +209,6 @@ def _provider_config_updates(query: QueryParams) -> dict[str, Any]:
|
||||
string_fields = (
|
||||
("api_key", "apiKey"),
|
||||
("api_base", "apiBase"),
|
||||
("api_type", "apiType"),
|
||||
("proxy", "proxy"),
|
||||
("thinking_style", "thinkingStyle"),
|
||||
("region", "region"),
|
||||
@@ -218,7 +218,7 @@ def _provider_config_updates(query: QueryParams) -> dict[str, Any]:
|
||||
for snake, camel in string_fields:
|
||||
if query_has_alias(query, snake, camel):
|
||||
value = (query_first_alias(query, snake, camel) or "").strip()
|
||||
updates[snake] = value or ("auto" if snake == "api_type" else None)
|
||||
updates[snake] = value or None
|
||||
|
||||
for snake, camel in (
|
||||
("extra_headers", "extraHeaders"),
|
||||
@@ -232,6 +232,9 @@ def _provider_config_updates(query: QueryParams) -> dict[str, Any]:
|
||||
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
|
||||
# Temporary input compatibility for older clients during the two-release window.
|
||||
if query_has_alias(query, "api_type", "apiType"):
|
||||
updates["api_type"] = query_first_alias(query, "api_type", "apiType") or "auto"
|
||||
return updates
|
||||
|
||||
|
||||
@@ -451,8 +454,6 @@ def _provider_advanced_field_names(name: str, spec: Any) -> list[str]:
|
||||
fields.extend(("extra_query", "proxy"))
|
||||
if spec.name in _OAUTH_PROXY_PROVIDERS and "proxy" not in fields:
|
||||
fields.append("proxy")
|
||||
if spec.name == "openai":
|
||||
fields.append("api_type")
|
||||
if spec.backend == "bedrock":
|
||||
fields.extend(("region", "profile"))
|
||||
if find_by_name(name) is None:
|
||||
@@ -468,7 +469,10 @@ def _provider_settings_row(
|
||||
) -> dict[str, Any]:
|
||||
oauth_status = oauth_status_reader(spec) if spec.is_oauth else None
|
||||
is_custom = find_by_name(name) is None
|
||||
request_apis = provider_config.api.supported_apis if provider_config.api else spec.request_apis
|
||||
request_apis = (
|
||||
provider_config.api.supported_apis
|
||||
if provider_config.api is not None and spec.is_direct else spec.request_apis
|
||||
)
|
||||
row = {
|
||||
"name": name,
|
||||
"label": spec.label,
|
||||
@@ -503,8 +507,6 @@ def _provider_settings_row(
|
||||
row["oauth_account"] = oauth_status["account"]
|
||||
row["oauth_expires_at"] = oauth_status["expires_at"]
|
||||
row["oauth_login_supported"] = oauth_status["login_supported"]
|
||||
if spec.name == "openai":
|
||||
row["api_type"] = provider_config.api_type
|
||||
return row
|
||||
|
||||
|
||||
@@ -1559,7 +1561,6 @@ def create_provider_settings(config: Config, query: QueryParams) -> str:
|
||||
|
||||
provider_key = _custom_provider_key(config, display_name)
|
||||
updates["display_name"] = display_name
|
||||
updates["api_type"] = "auto"
|
||||
provider_config = _validated_provider_config(None, updates)
|
||||
setattr(config.providers, provider_key, provider_config)
|
||||
return provider_key
|
||||
@@ -1580,6 +1581,10 @@ def update_provider_settings(
|
||||
updates = _provider_config_updates(query)
|
||||
if not spec.is_oauth and spec.name != "openai":
|
||||
updates.pop("api_type", None)
|
||||
try:
|
||||
updates = migrate_legacy_provider_api(updates, provider_name=provider_key)
|
||||
except ValueError as exc:
|
||||
raise WebUISettingsError(str(exc)) from None
|
||||
if spec.is_oauth:
|
||||
if spec.name not in _OAUTH_PROXY_PROVIDERS:
|
||||
raise WebUISettingsError("unknown provider")
|
||||
|
||||
@@ -72,26 +72,38 @@ def test_agent_timezones_use_packaged_data_without_system_database() -> None:
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
|
||||
def test_provider_api_type_accepts_exact_values_only() -> None:
|
||||
config = Config.model_validate({
|
||||
"providers": {
|
||||
"openai": {
|
||||
"apiKey": "sk-test",
|
||||
"apiType": "responses",
|
||||
}
|
||||
}
|
||||
})
|
||||
assert config.providers.openai.api_type == "responses"
|
||||
@pytest.mark.parametrize("field", ["apiType", "api_type"])
|
||||
@pytest.mark.parametrize("legacy", ["auto", "chat_completions", "responses"])
|
||||
def test_legacy_provider_api_migrates_and_saves_current_format(tmp_path, field, legacy):
|
||||
from nanobot.config.loader import load_config, save_config
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
Config.model_validate({
|
||||
"providers": {
|
||||
"openai": {
|
||||
"apiKey": "sk-test",
|
||||
"apiType": "response",
|
||||
}
|
||||
}
|
||||
})
|
||||
path = tmp_path / "config.json"
|
||||
path.write_text(json.dumps({"providers": {"openai": {"apiKey": "sk-test", field: legacy}}}))
|
||||
config = load_config(path)
|
||||
expected = None if legacy == "auto" else {
|
||||
"supportedApis": [legacy], "preferredApi": legacy,
|
||||
}
|
||||
save_config(config, path)
|
||||
saved = json.loads(path.read_text())["providers"]["openai"]
|
||||
assert saved.get("api") == expected
|
||||
assert field not in saved # The seeded legacy field must not survive a save.
|
||||
assert load_config(path).providers.openai.api == config.providers.openai.api
|
||||
|
||||
|
||||
@pytest.mark.parametrize("api", [None, {"supportedApis": ["chat_completions"]}])
|
||||
def test_current_provider_api_takes_precedence_over_legacy_input(api):
|
||||
config = Config.model_validate({"providers": {"openai": {
|
||||
"apiType": "responses", "api": api,
|
||||
}}})
|
||||
if api is None:
|
||||
assert config.providers.openai.api is None
|
||||
else:
|
||||
assert config.providers.openai.api.to_capabilities().preferred_api == "chat_completions"
|
||||
|
||||
|
||||
def test_legacy_provider_api_rejects_invalid_selector():
|
||||
with pytest.raises(ValueError, match="apiType must be"):
|
||||
Config.model_validate({"providers": {"openai": {"apiType": "response"}}})
|
||||
|
||||
|
||||
def test_provider_api_type_is_openai_only() -> None:
|
||||
|
||||
@@ -21,7 +21,6 @@ def _make_copilot_provider() -> OpenAICompatProvider:
|
||||
p.default_model = "github_copilot/gpt-5.4-mini"
|
||||
p._spec = find_by_name("github_copilot")
|
||||
p._effective_base = "https://api.githubcopilot.com"
|
||||
p._api_type = "auto"
|
||||
p._responses_failures = {}
|
||||
p._responses_tripped_at = {}
|
||||
return p
|
||||
|
||||
@@ -18,7 +18,7 @@ from nanobot.providers.base import ProviderCallContext
|
||||
from nanobot.providers.bedrock_provider import BedrockProvider
|
||||
from nanobot.providers.github_copilot_provider import GitHubCopilotProvider
|
||||
from nanobot.providers.openai_compat_provider import OpenAICompatProvider
|
||||
from nanobot.providers.registry import find_by_name
|
||||
from nanobot.providers.registry import ModelAPICapabilities, find_by_name
|
||||
from nanobot.providers.xai_grok_provider import XAIGrokProvider
|
||||
|
||||
|
||||
@@ -120,7 +120,7 @@ async def image_peer(monkeypatch):
|
||||
await runner.cleanup()
|
||||
|
||||
|
||||
def _provider(adapter, url, monkeypatch, api_type=None):
|
||||
def _provider(adapter, url, monkeypatch):
|
||||
if adapter == "azure":
|
||||
return AzureOpenAIProvider(api_key="fixture", api_base=url, default_model="gpt-5.4")
|
||||
if adapter == "anthropic":
|
||||
@@ -140,7 +140,9 @@ def _provider(adapter, url, monkeypatch, api_type=None):
|
||||
return OpenAICompatProvider(
|
||||
api_key="fixture", api_base=f"{url}/v1", spec=spec,
|
||||
default_model="deepseek-v4-flash-vision-exp" if adapter == "deepseek" else "gpt-5.4",
|
||||
api_type=api_type or ("chat_completions" if adapter == "chat" else "responses"), extra_body={"tools": []},
|
||||
model_api=ModelAPICapabilities(("chat_completions",), "chat_completions") if adapter == "chat"
|
||||
else ModelAPICapabilities(("responses",), "responses") if adapter != "deepseek" else None,
|
||||
extra_body={"tools": []},
|
||||
)
|
||||
|
||||
|
||||
@@ -250,7 +252,7 @@ async def test_responses_image_rejection_discards_replay_and_retries_once(
|
||||
@pytest.mark.parametrize("streaming", [False, True])
|
||||
async def test_auto_responses_fallback_keeps_prepared_images(image_peer, image_blocks, monkeypatch, streaming):
|
||||
url, requests, reject = image_peer
|
||||
provider = _provider("deepseek", url, monkeypatch, api_type="auto")
|
||||
provider = _provider("deepseek", url, monkeypatch)
|
||||
reject["images"] = True
|
||||
try:
|
||||
result = await (provider.chat_stream if streaming else provider.chat)(_messages(image_blocks))
|
||||
@@ -267,7 +269,7 @@ async def test_text_only_model_keeps_its_image_policy(image_peer, image_blocks,
|
||||
url, requests, _ = image_peer
|
||||
provider = OpenAICompatProvider(
|
||||
api_key="fixture", api_base=f"{url}/v1", spec=find_by_name("deepseek"),
|
||||
default_model="deepseek-v4-flash", api_type="responses", extra_body={"tools": []},
|
||||
default_model="deepseek-v4-flash", extra_body={"tools": []},
|
||||
)
|
||||
try:
|
||||
result = await (provider.chat_stream if streaming else provider.chat)(_messages(image_blocks))
|
||||
|
||||
@@ -16,7 +16,7 @@ from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.providers.azure_openai_provider import AzureOpenAIProvider
|
||||
from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest
|
||||
from nanobot.providers.openai_compat_provider import OpenAICompatProvider
|
||||
from nanobot.providers.registry import find_by_name
|
||||
from nanobot.providers.registry import ModelAPICapabilities, find_by_name
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
|
||||
|
||||
@@ -97,7 +97,7 @@ async def make_provider(monkeypatch):
|
||||
provider = OpenAICompatProvider(
|
||||
api_key="test", default_model="gpt-5.2",
|
||||
spec=find_by_name("openai"),
|
||||
api_type="chat_completions" if api == "chat" else "responses",
|
||||
model_api=ModelAPICapabilities(("chat_completions",), "chat_completions") if api == "chat" else ModelAPICapabilities(("responses",), "responses"),
|
||||
)
|
||||
provider._client = client
|
||||
provider._CHAT_RETRY_DELAYS = ()
|
||||
|
||||
@@ -1074,7 +1074,7 @@ async def test_gpt6_temperature_requires_explicit_none_effort(
|
||||
api_key="sk-test-key",
|
||||
default_model=model,
|
||||
spec=find_by_name("openai"),
|
||||
api_type=api_type,
|
||||
model_api=ModelAPICapabilities((api_type,), api_type),
|
||||
)
|
||||
result = await provider.chat(
|
||||
messages=[{"role": "user", "content": "hello"}],
|
||||
|
||||
@@ -324,13 +324,13 @@ def test_fixed_provider_validates_preset_api_before_loading_client():
|
||||
(("chat_completions",), "chat_completions"),
|
||||
(("chat_completions", "responses"), "chat_completions"),
|
||||
])
|
||||
async def test_preset_overrides_legacy_openai_default_and_scopes_compaction(bind_transport, apis, preferred):
|
||||
async def test_preset_overrides_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"
|
||||
config.providers.openai.api = ModelAPIConfig(supported_apis=("chat_completions",))
|
||||
requests = []
|
||||
|
||||
def handler(request):
|
||||
@@ -452,3 +452,40 @@ async def test_explicit_model_api_overrides_connection_default(bind_transport, p
|
||||
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]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("legacy,path", [
|
||||
("auto", "/v1/chat/completions"),
|
||||
("chat_completions", "/v1/chat/completions"),
|
||||
("responses", "/v1/responses"),
|
||||
])
|
||||
async def test_migrated_openai_default_routes_and_allows_model_override(bind_transport, tmp_path, legacy, path):
|
||||
from nanobot.config.loader import load_config, save_config
|
||||
|
||||
config_path = tmp_path / "config.json"
|
||||
config_path.write_text(json.dumps({
|
||||
"providers": {"openai": {"apiKey": "fixture", "apiType": legacy}},
|
||||
"agents": {"defaults": {"model": "gpt-4o", "provider": "openai"}},
|
||||
}))
|
||||
config = load_config(config_path)
|
||||
save_config(config, config_path)
|
||||
config = load_config(config_path)
|
||||
requests = []
|
||||
|
||||
def handler(request):
|
||||
requests.append(request.url.path)
|
||||
return _answer(request)
|
||||
|
||||
provider = bind_transport(make_provider(config), handler)
|
||||
assert (await provider.chat([{"role": "user", "content": "hello"}])).content == "ok"
|
||||
assert requests == [path]
|
||||
assert resolve_automatic_model_api(config, preset=config.resolve_preset())[1] == (
|
||||
"responses" if legacy == "responses" else "chat_completions"
|
||||
)
|
||||
opposite = "chat_completions" if legacy == "responses" else "responses"
|
||||
config.model_presets["override"] = ModelPresetConfig(
|
||||
model="gpt-4o", provider="openai", api=ModelAPIConfig(supported_apis=(opposite,)),
|
||||
)
|
||||
override = bind_transport(make_provider(config, preset_name="override"), handler)
|
||||
assert (await override.chat([{"role": "user", "content": "hello"}])).content == "ok"
|
||||
assert requests[-1] == ("/v1/responses" if opposite == "responses" else "/v1/chat/completions")
|
||||
@@ -10,7 +10,7 @@ import pytest
|
||||
from nanobot.config.schema import Config, ProvidersConfig
|
||||
from nanobot.providers.base import ProviderCallContext
|
||||
from nanobot.providers.openai_compat_provider import OpenAICompatProvider
|
||||
from nanobot.providers.registry import PROVIDERS, find_by_name
|
||||
from nanobot.providers.registry import PROVIDERS, ModelAPICapabilities, find_by_name
|
||||
|
||||
|
||||
def test_opencode_config_fields_exist() -> None:
|
||||
@@ -250,7 +250,7 @@ async def test_opencode_wire_affinity(monkeypatch, api_type, stream, configured_
|
||||
headers[configured_header] = "configured"
|
||||
provider = OpenAICompatProvider(
|
||||
api_key="test", api_base="https://opencode.ai/zen/v1",
|
||||
spec=find_by_name("openai"), api_type=api_type, extra_headers=headers,
|
||||
spec=find_by_name("openai"), model_api=ModelAPICapabilities((api_type,), api_type), extra_headers=headers,
|
||||
default_model="gpt-5",
|
||||
extra_body={"context_management": [{"type": "compaction"}]} if compaction else None,
|
||||
)
|
||||
|
||||
@@ -12,7 +12,7 @@ from nanobot.providers.azure_openai_provider import AzureOpenAIProvider
|
||||
from nanobot.providers.base import ProviderCallContext
|
||||
from nanobot.providers.github_copilot_provider import GitHubCopilotProvider
|
||||
from nanobot.providers.openai_compat_provider import OpenAICompatProvider
|
||||
from nanobot.providers.registry import find_by_name
|
||||
from nanobot.providers.registry import ModelAPICapabilities, find_by_name
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -102,7 +102,7 @@ async def test_adapters_replay_tool_results_and_reasoning(responses_peer, monkey
|
||||
provider = OpenAICompatProvider(
|
||||
api_key="fixture", api_base=f"{url}/v1", spec=find_by_name(adapter),
|
||||
default_model="deepseek-v4-flash" if adapter == "deepseek" else "gpt-5.4",
|
||||
api_type="responses", extra_body={"store": True} if adapter == "openai" else None,
|
||||
model_api=ModelAPICapabilities(("responses",), "responses"), extra_body={"store": True} if adapter == "openai" else None,
|
||||
provider_name=adapter,
|
||||
)
|
||||
progress = []
|
||||
|
||||
@@ -12,6 +12,7 @@ from nanobot.providers.openai_compat_provider import (
|
||||
)
|
||||
from nanobot.providers.openai_responses.state import build_responses_state
|
||||
from nanobot.providers.registry import (
|
||||
ModelAPICapabilities,
|
||||
ProviderSpec,
|
||||
ResponsesCapabilities,
|
||||
find_by_name,
|
||||
@@ -25,7 +26,6 @@ def provider():
|
||||
p.default_model = "gpt-5"
|
||||
p._spec = find_by_name("openai")
|
||||
p._effective_base = "https://api.openai.com/v1"
|
||||
p._api_type = "auto"
|
||||
p._responses_failures = {}
|
||||
p._responses_tripped_at = {}
|
||||
return p
|
||||
@@ -120,33 +120,26 @@ def test_direct_openai_enables_server_compaction(provider):
|
||||
assert body["include"] == ["reasoning.encrypted_content"]
|
||||
|
||||
|
||||
def test_api_type_chat_completions_disables_responses(provider):
|
||||
provider._api_type = "chat_completions"
|
||||
def test_chat_declaration_disables_responses(provider):
|
||||
provider._preset_model_api = ModelAPICapabilities(("chat_completions",), "chat_completions")
|
||||
assert provider._should_use_responses_api("gpt-5", None) is False
|
||||
|
||||
|
||||
def test_api_type_responses_forces_responses_for_openai(provider):
|
||||
def test_responses_declaration_routes_other_models(provider):
|
||||
provider.default_model = "gpt-4o"
|
||||
provider._api_type = "responses"
|
||||
provider._preset_model_api = ModelAPICapabilities(("responses",), "responses")
|
||||
assert provider._should_use_responses_api("gpt-4o", None) is True
|
||||
|
||||
|
||||
def test_api_type_responses_ignores_circuit_breaker(provider):
|
||||
def test_responses_only_declaration_ignores_circuit_breaker(provider):
|
||||
provider.default_model = "gpt-4o"
|
||||
provider._api_type = "responses"
|
||||
provider._preset_model_api = ModelAPICapabilities(("responses",), "responses")
|
||||
provider._responses_failures = {"gpt-4o|gpt-4o|": _RESPONSES_FAILURE_THRESHOLD}
|
||||
provider._responses_tripped_at = {"gpt-4o|gpt-4o|": 0.0}
|
||||
|
||||
assert provider._should_use_responses_api("gpt-4o", None) is True
|
||||
|
||||
|
||||
def test_api_type_responses_does_not_force_non_openai(provider):
|
||||
provider._spec = find_by_name("custom")
|
||||
provider._api_type = "responses"
|
||||
|
||||
assert provider._should_use_responses_api("gpt-4o", None) is False
|
||||
|
||||
|
||||
def test_circuit_opens_after_threshold(provider):
|
||||
for _ in range(_RESPONSES_FAILURE_THRESHOLD):
|
||||
provider._record_responses_failure("gpt-5", None)
|
||||
|
||||
@@ -1041,7 +1041,7 @@ def test_update_provider_settings_persists_provider_specific_advanced_options(
|
||||
)
|
||||
|
||||
saved = load_config(config_path)
|
||||
assert saved.providers.openai.api_type == "responses"
|
||||
assert saved.providers.openai.api.to_capabilities().preferred_api == "responses"
|
||||
assert saved.providers.openai.proxy == "http://127.0.0.1:7890"
|
||||
assert saved.providers.openai.extra_headers == {"X-Trace": "enabled"}
|
||||
assert saved.providers.openai.extra_body == {"service_tier": "priority"}
|
||||
@@ -2742,3 +2742,15 @@ def test_custom_connection_cannot_remove_api_used_by_legacy_or_inline_model(tmp_
|
||||
"provider": ["tenant"], "api": [json.dumps({"supportedApis": ["responses"]})],
|
||||
})
|
||||
assert config_path.read_bytes() == before
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["apiType", "api_type"])
|
||||
def test_legacy_openai_settings_can_return_to_auto(monkeypatch, tmp_path, field):
|
||||
config_path = tmp_path / "config.json"
|
||||
config = Config.model_validate({"providers": {"openai": {
|
||||
"apiKey": "fixture", "api": {"supportedApis": ["responses"]},
|
||||
}}})
|
||||
save_config(config, config_path)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
update_provider_settings({"provider": ["openai"], field: ["auto"]})
|
||||
assert load_config(config_path).providers.openai.api is None
|
||||
@@ -11,15 +11,18 @@ import type { ModelAPIConfig, ProviderRequestAPI, SettingsPayload } from "@/lib/
|
||||
export function ModelAPIControl({
|
||||
provider,
|
||||
automaticAPI,
|
||||
title,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
provider: SettingsPayload["providers"][number] | undefined;
|
||||
automaticAPI?: ProviderRequestAPI;
|
||||
title?: string;
|
||||
value: ModelAPIConfig | null;
|
||||
onChange: (api: ModelAPIConfig | null) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const controlTitle = title ?? t("settings.models.requestAPI");
|
||||
const [pointerFocus, setPointerFocus] = useState(false);
|
||||
const requestAPIs = Array.isArray(provider?.request_apis) ? provider.request_apis : undefined;
|
||||
const configurable = modelAPIConfigurable(provider);
|
||||
@@ -47,7 +50,7 @@ export function ModelAPIControl({
|
||||
|
||||
return (
|
||||
<div>
|
||||
<SettingsRow title={t("settings.models.requestAPI")}>
|
||||
<SettingsRow title={controlTitle}>
|
||||
{configurable ? (
|
||||
<Select value={selectedAPI} onValueChange={(api) => {
|
||||
if (api === selectedAPI) return;
|
||||
@@ -57,7 +60,7 @@ export function ModelAPIControl({
|
||||
}
|
||||
}}>
|
||||
<SelectTrigger
|
||||
aria-label={t("settings.models.requestAPI")}
|
||||
aria-label={controlTitle}
|
||||
className={cn("w-full rounded-full", pointerFocus && "focus-visible:ring-0")}
|
||||
onPointerDown={() => setPointerFocus(true)}
|
||||
onKeyDown={() => setPointerFocus(false)}
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
SettingsSectionTitle,
|
||||
} from "@/components/settings/shared/SettingsControls";
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import { ModelAPIControl } from "@/components/settings/models/ModelAPIControl";
|
||||
import { ProviderAPIControl } from "@/components/settings/models/ProviderAPIControl";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -60,7 +61,6 @@ import type {
|
||||
SettingsPayload,
|
||||
} from "@/lib/types";
|
||||
|
||||
type ProviderApiType = "auto" | "chat_completions" | "responses";
|
||||
type ProviderAdvancedField = NonNullable<
|
||||
SettingsPayload["providers"][number]["advanced_fields"]
|
||||
>[number];
|
||||
@@ -68,7 +68,6 @@ export type ProviderForm = {
|
||||
displayName: string;
|
||||
apiKey: string;
|
||||
apiBase: string;
|
||||
apiType: ProviderApiType;
|
||||
api: ModelAPIConfig | null;
|
||||
proxy: string;
|
||||
extraHeaders: string;
|
||||
@@ -198,7 +197,7 @@ function updateProviderRequestOption(
|
||||
return {
|
||||
extraBody: providerJsonValue(extraBody),
|
||||
...(option.forceResponses && enabled
|
||||
? { apiType: "responses" as const }
|
||||
? { api: { supported_apis: ["responses"], preferred_api: "responses" } satisfies ModelAPIConfig }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
@@ -210,7 +209,6 @@ export function providerFormFromRow(
|
||||
displayName: provider.is_custom ? provider.label : "",
|
||||
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),
|
||||
@@ -228,7 +226,6 @@ function emptyCustomProviderDraft(): CustomProviderDraft {
|
||||
displayName: "",
|
||||
apiKey: "",
|
||||
apiBase: "",
|
||||
apiType: "auto",
|
||||
api: { supported_apis: ["chat_completions"], preferred_api: "chat_completions" },
|
||||
proxy: "",
|
||||
extraHeaders: "",
|
||||
@@ -240,12 +237,6 @@ function emptyCustomProviderDraft(): CustomProviderDraft {
|
||||
};
|
||||
}
|
||||
|
||||
const OPENAI_API_TYPE_OPTIONS: Array<{ value: ProviderApiType; label: string }> = [
|
||||
{ value: "auto", label: "Auto" },
|
||||
{ value: "chat_completions", label: "Chat Completions" },
|
||||
{ value: "responses", label: "Responses" },
|
||||
];
|
||||
|
||||
const LOCAL_UNCONFIGURED_PROVIDER_ORDER = new Map(
|
||||
["vllm", "ollama", "lm_studio", "atomic_chat", "ovms"].map((name, index) => [
|
||||
name,
|
||||
@@ -411,14 +402,17 @@ export function ProviderOAuthLoginDialog({
|
||||
function ProviderRequestOptions({
|
||||
providerName,
|
||||
form,
|
||||
apiConfigurable,
|
||||
onChange,
|
||||
}: {
|
||||
providerName: string;
|
||||
form: ProviderForm;
|
||||
apiConfigurable: boolean;
|
||||
onChange: (value: Partial<ProviderForm>) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const options = PROVIDER_REQUEST_OPTIONS[providerName] ?? [];
|
||||
const options = (PROVIDER_REQUEST_OPTIONS[providerName] ?? [])
|
||||
.filter((option) => !option.forceResponses || apiConfigurable);
|
||||
if (options.length === 0) return null;
|
||||
const extraBody = parseProviderExtraBody(form.extraBody) ?? {};
|
||||
|
||||
@@ -509,42 +503,6 @@ function ProviderAdvancedOptions({
|
||||
<DisclosureContent id={contentId} open={open}>
|
||||
<div className="py-3">
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
{enabled.has("api_type") ? (
|
||||
<label className="block space-y-1.5">
|
||||
<span className="text-[12px] font-medium text-muted-foreground">
|
||||
{tx("settings.providers.apiType", "API type")}
|
||||
</span>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="h-9 w-full justify-between rounded-full px-3 text-[13px]"
|
||||
>
|
||||
<span>
|
||||
{OPENAI_API_TYPE_OPTIONS.find(
|
||||
(option) => option.value === form.apiType,
|
||||
)?.label ?? form.apiType}
|
||||
</span>
|
||||
<ChevronDown
|
||||
className="h-3.5 w-3.5 text-muted-foreground"
|
||||
aria-hidden
|
||||
/>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="min-w-[220px]">
|
||||
{OPENAI_API_TYPE_OPTIONS.map((option) => (
|
||||
<DropdownMenuItem
|
||||
key={option.value}
|
||||
onSelect={() => onChange({ apiType: option.value })}
|
||||
>
|
||||
{option.label}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</label>
|
||||
) : null}
|
||||
{enabled.has("thinking_style") ? (
|
||||
<label className="block space-y-1.5">
|
||||
<span className="text-[12px] font-medium text-muted-foreground">
|
||||
@@ -910,6 +868,7 @@ export function ProvidersSettings({
|
||||
</div>
|
||||
<ProviderRequestOptions
|
||||
providerName={provider.name}
|
||||
apiConfigurable={provider.provider_api_configurable === true}
|
||||
form={form}
|
||||
onChange={(value) => onChangeProviderForm(provider.name, value)}
|
||||
/>
|
||||
@@ -1040,15 +999,23 @@ export function ProvidersSettings({
|
||||
</label>
|
||||
<ProviderRequestOptions
|
||||
providerName={provider.name}
|
||||
apiConfigurable={provider.provider_api_configurable === true}
|
||||
form={form}
|
||||
onChange={(value) => onChangeProviderForm(provider.name, value)}
|
||||
/>
|
||||
{provider.provider_api_configurable && (
|
||||
{provider.provider_api_configurable && (provider.name === "openai" ? (
|
||||
<ModelAPIControl
|
||||
provider={provider}
|
||||
title={t("settings.providers.defaultAPI")}
|
||||
value={form.api}
|
||||
onChange={(api) => onChangeProviderForm(provider.name, { api })}
|
||||
/>
|
||||
) : (
|
||||
<ProviderAPIControl
|
||||
value={form.api}
|
||||
onChange={(api) => onChangeProviderForm(provider.name, { api })}
|
||||
/>
|
||||
)}
|
||||
))}
|
||||
<ProviderAdvancedOptions
|
||||
fields={advancedFields}
|
||||
form={form}
|
||||
|
||||
@@ -410,7 +410,6 @@ export function useModelSettingsActions({
|
||||
if (provider.provider_api_configurable) update.api = providerForm.api;
|
||||
}
|
||||
for (const field of provider.advanced_fields ?? []) {
|
||||
if (field === "api_type") update.apiType = providerForm.apiType;
|
||||
if (field === "proxy") update.proxy = providerForm.proxy.trim();
|
||||
if (field === "extra_headers") {
|
||||
update.extraHeaders = providerForm.extraHeaders.trim();
|
||||
|
||||
@@ -1197,7 +1197,6 @@
|
||||
"supportedAPIs": "Supported APIs",
|
||||
"defaultAPI": "Default API",
|
||||
"declareAPIs": "Set supported APIs",
|
||||
"apiType": "API type",
|
||||
"proxy": "Network proxy",
|
||||
"thinkingStyle": "Reasoning format",
|
||||
"region": "Region",
|
||||
|
||||
@@ -777,7 +777,6 @@
|
||||
"supportedAPIs": "API compatibles",
|
||||
"defaultAPI": "API predeterminada",
|
||||
"declareAPIs": "Configurar API compatibles",
|
||||
"apiType": "Tipo de API",
|
||||
"proxy": "Proxy de red",
|
||||
"thinkingStyle": "Formato de razonamiento",
|
||||
"region": "Región",
|
||||
|
||||
@@ -777,7 +777,6 @@
|
||||
"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",
|
||||
"region": "Région",
|
||||
|
||||
@@ -777,7 +777,6 @@
|
||||
"supportedAPIs": "API yang didukung",
|
||||
"defaultAPI": "API default",
|
||||
"declareAPIs": "Atur API yang didukung",
|
||||
"apiType": "Jenis API",
|
||||
"proxy": "Proksi jaringan",
|
||||
"thinkingStyle": "Format penalaran",
|
||||
"region": "Wilayah",
|
||||
|
||||
@@ -777,7 +777,6 @@
|
||||
"supportedAPIs": "対応する API",
|
||||
"defaultAPI": "デフォルトの API",
|
||||
"declareAPIs": "対応する API を設定",
|
||||
"apiType": "API タイプ",
|
||||
"proxy": "ネットワークプロキシ",
|
||||
"thinkingStyle": "推論の形式",
|
||||
"region": "リージョン",
|
||||
|
||||
@@ -777,7 +777,6 @@
|
||||
"supportedAPIs": "지원 API",
|
||||
"defaultAPI": "기본 API",
|
||||
"declareAPIs": "지원 API 설정",
|
||||
"apiType": "API 유형",
|
||||
"proxy": "네트워크 프록시",
|
||||
"thinkingStyle": "추론 형식",
|
||||
"region": "리전",
|
||||
|
||||
@@ -1011,7 +1011,6 @@
|
||||
"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",
|
||||
"region": "Região",
|
||||
|
||||
@@ -777,7 +777,6 @@
|
||||
"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",
|
||||
"region": "Khu vực",
|
||||
|
||||
@@ -1197,7 +1197,6 @@
|
||||
"supportedAPIs": "支持的协议",
|
||||
"defaultAPI": "默认协议",
|
||||
"declareAPIs": "设置支持的协议",
|
||||
"apiType": "API 类型",
|
||||
"proxy": "网络代理",
|
||||
"thinkingStyle": "推理格式",
|
||||
"region": "区域",
|
||||
|
||||
@@ -777,7 +777,6 @@
|
||||
"supportedAPIs": "支援的協定",
|
||||
"defaultAPI": "預設協定",
|
||||
"declareAPIs": "設定支援的協定",
|
||||
"apiType": "API 類型",
|
||||
"proxy": "網路代理",
|
||||
"thinkingStyle": "推理格式",
|
||||
"region": "區域",
|
||||
|
||||
@@ -735,13 +735,11 @@ export interface SettingsPayload {
|
||||
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;
|
||||
oauth_login_supported?: boolean;
|
||||
proxy?: string | null;
|
||||
advanced_fields?: Array<
|
||||
| "api_type"
|
||||
| "extra_headers"
|
||||
| "extra_body"
|
||||
| "extra_query"
|
||||
@@ -1354,7 +1352,6 @@ export interface ProviderSettingsUpdate {
|
||||
displayName?: string;
|
||||
apiKey?: string;
|
||||
apiBase?: string;
|
||||
apiType?: "auto" | "chat_completions" | "responses";
|
||||
api?: ModelAPIConfig | null;
|
||||
proxy?: string;
|
||||
extraHeaders?: string;
|
||||
|
||||
@@ -696,8 +696,9 @@ describe("Settings providers", () => {
|
||||
api_key_required: true,
|
||||
api_key_hint: "sk-••••test",
|
||||
api_base: "https://api.openai.com/v1",
|
||||
api_type: "auto",
|
||||
advanced_fields: ["api_type", "extra_body"],
|
||||
provider_api_configurable: true,
|
||||
request_apis: ["chat_completions", "responses"],
|
||||
advanced_fields: ["extra_body"],
|
||||
extra_body: null,
|
||||
},
|
||||
];
|
||||
@@ -769,11 +770,11 @@ describe("Settings providers", () => {
|
||||
.map(([, values]) => {
|
||||
const update = values as {
|
||||
provider: string;
|
||||
apiType?: string;
|
||||
api?: { supported_apis: string[]; preferred_api: string };
|
||||
extraBody?: string;
|
||||
};
|
||||
return [update.provider, {
|
||||
...(update.apiType ? { apiType: update.apiType } : {}),
|
||||
...(update.api ? { api: update.api } : {}),
|
||||
extraBody: JSON.parse(update.extraBody ?? "{}"),
|
||||
}] as const;
|
||||
});
|
||||
@@ -782,7 +783,7 @@ describe("Settings providers", () => {
|
||||
["openai_codex", { extraBody: { service_tier: "priority" } }],
|
||||
["deepseek", { extraBody: { tools: [] } }],
|
||||
["openai", {
|
||||
apiType: "responses",
|
||||
api: { supported_apis: ["responses"], preferred_api: "responses" },
|
||||
extraBody: { tools: [{ type: "web_search" }] },
|
||||
}],
|
||||
]);
|
||||
@@ -800,8 +801,9 @@ describe("Settings providers", () => {
|
||||
api_key_required: true,
|
||||
api_key_hint: "sk-••••test",
|
||||
api_base: "https://api.openai.com/v1",
|
||||
api_type: "auto",
|
||||
advanced_fields: ["api_type", "extra_body"],
|
||||
provider_api_configurable: true,
|
||||
request_apis: ["chat_completions", "responses"],
|
||||
advanced_fields: ["extra_body"],
|
||||
extra_body: {
|
||||
metadata: { owner: "legacy-config" },
|
||||
tools: [
|
||||
@@ -1038,4 +1040,59 @@ describe("Settings providers", () => {
|
||||
expect(screen.queryByRole("group", { name: "Supported APIs" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("saves and reopens OpenAI defaults, including automatic routing", async () => {
|
||||
const user = userEvent.setup();
|
||||
let payload = settingsPayload();
|
||||
payload.providers = [{
|
||||
name: "openai", label: "OpenAI", configured: true,
|
||||
provider_api_configurable: true, request_apis: ["chat_completions", "responses"],
|
||||
api: { supported_apis: ["responses"], preferred_api: "responses" },
|
||||
}];
|
||||
requestMutationMock.mockImplementation(async (_action, args) => {
|
||||
payload = { ...payload, providers: [{ ...payload.providers[0], api: args.api }] };
|
||||
return payload;
|
||||
});
|
||||
renderSettingsView({ initialSection: "models", initialSettings: payload });
|
||||
await user.click(screen.getByRole("button", { name: "OpenAI", exact: true }));
|
||||
expect(screen.getByRole("combobox", { name: "Default API" })).toHaveTextContent("Responses");
|
||||
await user.click(screen.getByRole("combobox", { name: "Default API" }));
|
||||
await user.click(screen.getByRole("option", { name: "Chat Completions", exact: true }));
|
||||
await user.click(screen.getByRole("button", { name: "Save provider" }));
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
|
||||
expect(requestMutationMock).toHaveBeenCalledWith("settings.provider.update", expect.objectContaining({
|
||||
provider: "openai", api: { supported_apis: ["chat_completions"], preferred_api: "chat_completions" },
|
||||
}), 20_000);
|
||||
await user.click(screen.getByRole("button", { name: "OpenAI", exact: true }));
|
||||
expect(screen.getByRole("combobox", { name: "Default API" })).toHaveTextContent("Chat Completions");
|
||||
await user.click(screen.getByRole("combobox", { name: "Default API" }));
|
||||
await user.click(screen.getByRole("option", { name: "Auto", exact: true }));
|
||||
await user.click(screen.getByRole("button", { name: "Save provider" }));
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
|
||||
expect(requestMutationMock).toHaveBeenCalledWith("settings.provider.update", expect.objectContaining({
|
||||
provider: "openai", api: null,
|
||||
}), 20_000);
|
||||
await user.click(screen.getByRole("button", { name: "OpenAI", exact: true }));
|
||||
expect(screen.getByRole("combobox", { name: "Default API" })).toHaveTextContent("Auto");
|
||||
});
|
||||
|
||||
it("keeps ordinary OpenAI edits available on hosts without API declarations", async () => {
|
||||
const payload = settingsPayload();
|
||||
payload.providers = [{
|
||||
name: "openai", label: "OpenAI", configured: true,
|
||||
api_base: "https://api.openai.com/v1", advanced_fields: ["extra_body"],
|
||||
extra_body: { tools: [{ type: "web_search" }] },
|
||||
}];
|
||||
renderSettingsView({ initialSection: "models", initialSettings: payload });
|
||||
fireEvent.click(screen.getByRole("button", { name: "OpenAI", exact: true }));
|
||||
expect(screen.queryByRole("combobox", { name: "Default API" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("switch", { name: "OpenAI web search" })).not.toBeInTheDocument();
|
||||
fireEvent.change(screen.getByLabelText("API base URL"), { target: { value: "https://gateway.test/v1" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Save provider" }));
|
||||
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith("settings.provider.update", expect.objectContaining({
|
||||
provider: "openai", apiBase: "https://gateway.test/v1",
|
||||
}), 20_000));
|
||||
const update = requestMutationMock.mock.calls.at(-1)?.[1];
|
||||
expect(JSON.parse(update.extraBody)).toEqual({ tools: [{ type: "web_search" }] });
|
||||
});
|
||||
|
||||
});
|
||||
Reference in new issue
Block a user