refactor(config)!: retire the old OpenAI API selector (#6615)

Co-authored-by: chengyongru <chengyongru.ai@gmail.com>
This commit is contained in:
Xubin Renandchengyongru authored and GitHub committed 2026-11-11 17:07:18 +08:00
1 parent e3a1af2ed3
commit 5c1083df7f
14 files changed
+112 -141

No files matched your search

-8
View File
@@ -1463,14 +1463,6 @@ In `config.json`, set `providers.<name>.api` for the built-in `custom` provider
`supportedApis` must contain at least one of `chat_completions`, `responses`, or `anthropic_messages`. `preferredApi` must belong to that list and defaults to its first entry. Auto presets inherit this default; explicit presets can only use protocols in the connection's list. Before removing a protocol used by an explicit preset, update that preset first.
### Legacy OpenAI API selector migration
If your configuration uses `providers.openai.apiType` (or `api_type`), save it with a version that supports the migration before upgrading further. Saving replaces the old field with `api`: `chat_completions` or `responses` becomes a single-API declaration, while `auto` keeps automatic selection. If both fields are present, `api` takes precedence, including `api: null`.
The migration also accepts the `NANOBOT_PROVIDERS__OPENAI__API_TYPE` and `NANOBOT_PROVIDERS__OPENAI__APITYPE` environment variables.
The old field is accepted in the first release containing this migration and the immediately following release. The third release will require the current `api` format.
### Preset request API
Leave API selection on **Auto** unless your service requires a specific protocol. To change it, open **Settings → Models → a preset → Advanced options → API connection**. Choose **Responses**, **Chat Completions**, or **Anthropic Messages** from the available options. Hover, focus, or tap a setting label for help. Credentials and endpoint URLs stay in the provider; two presets sharing a provider can select different APIs.
+1 -1
View File
@@ -74,7 +74,7 @@ Replace `OpenAICompatProvider(api_type=...)` with `OpenAICompatProvider(model_ap
ModelAPICapabilities(supported_apis=("responses",), preferred_api="responses")
```
API types and automatic selection rules are defined in `nanobot.providers.model_api`. The registry owns `ProviderSpec`, model metadata, and provider declarations; it also re-exports the API types. The temporary `apiType` configuration migration applies to JSON configuration and Settings inputs; it does not preserve the old Python constructor arguments.
API types and automatic selection rules are defined in `nanobot.providers.model_api`. The registry owns `ProviderSpec`, model metadata, and provider declarations; it also re-exports the API types. JSON configuration and Settings inputs use the `api` object; the old `apiType` field no longer selects a request API.
## Adding a Transcription Provider
+1 -1
View File
@@ -222,7 +222,7 @@ Verify:
OPENAI_API_KEY="sk-..." nanobot agent -m "Hello!"
```
If your shell cannot use inline environment variables, set `OPENAI_API_KEY` first and then run `nanobot agent -m "Hello!"`. Leave API selection on Auto unless you need a specific API in the preset's **Advanced options**; see [preset API settings](./configuration.md#preset-request-api). If your configuration still uses `apiType`, follow the [migration instructions](./configuration.md#legacy-openai-api-selector-migration).
If your shell cannot use inline environment variables, set `OPENAI_API_KEY` first and then run `nanobot agent -m "Hello!"`. Leave API selection on Auto unless you need a specific API in the preset's **Advanced options**; see [preset API settings](./configuration.md#preset-request-api).
## Recipe: Anthropic Direct
+1 -1
View File
@@ -364,7 +364,7 @@ For a named custom provider serving Anthropic Messages, set `providers.<name>.ap
</details>
Replace the model with a model ID available to your account. Leave API selection on Auto unless you need to choose Chat Completions or Responses in the preset's **Advanced options**. See [preset API settings](./configuration.md#preset-request-api) for WebUI and JSON configuration. `providers.openai.api` sets the connection default; explicit presets override it. If your configuration still uses `apiType`, follow the [migration instructions](./configuration.md#legacy-openai-api-selector-migration).
Replace the model with a model ID available to your account. Leave API selection on Auto unless you need to choose Chat Completions or Responses in the preset's **Advanced options**. See [preset API settings](./configuration.md#preset-request-api) for WebUI and JSON configuration. `providers.openai.api` sets the connection default; explicit presets override it.
### DeepSeek
+1 -1
View File
@@ -52,7 +52,7 @@ Older versions cannot read newly saved SQLite display history. A downgrade is no
Legacy proxy configuration migration remains supported in 0.4.x and is removed in 0.5.0. Review the migrated shared proxy and per-service choices before saving; a browser's proxy settings are separate from the gateway's. See [Configuration](../configuration.md).
v0.4.0 is the first stable release with the temporary OpenAI `apiType` / `api_type` → `api` migration. It remains supported for the immediately following release; its exact tag must be recorded when that release is allocated. Save configurations in the current `api` format during this window. The third release containing this change will no longer accept the old selector. This is a separate compatibility window from the 0.4.x JSONL/proxy window. See [API selector migration](../configuration.md#legacy-openai-api-selector-migration).
v0.4.0 and v0.4.1 include the temporary OpenAI `apiType` / `api_type` → `api` conversion. Save configurations that use an explicit old selection in the current `api` format before upgrading beyond v0.4.1; update launcher environment variables separately. The old `auto` default needs no action. This compatibility window is separate from the 0.4.x JSONL/proxy window.
### Installation and platform boundaries
+1 -3
View File
@@ -82,9 +82,7 @@ Retain legacy model JSONL, WebUI JSONL / segments and per-feature proxy migratio
### OpenAI API selector compatibility window
The temporary `providers.openai.apiType` / `api_type` conversion lasts exactly two consecutive releases: the first containing `nanobot/config/provider_api_migration.py` and the next. Record the first and final supported tags in release notes. Config saves write `api`; there is no legacy runtime selector.
Before the third release, remove `provider_api_migration.py`, its import, `ProvidersConfig._migrate_legacy_api_type`, the legacy settings query conversion in `nanobot/webui/settings_models.py` and migration-specific tests. Update configuration docs and release notes to require the current format. Keep current-format routing, settings and persistence regressions.
v0.4.0 and v0.4.1 included automatic conversion of `providers.openai.apiType` / `api_type`. The first release without conversion must note in its release notes that users can save old configuration with v0.4.1 and must update launcher environment variables separately.
### TUI preflight without a release tag
-31
View File
@@ -1,31 +0,0 @@
"""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 and "apitype" not in values:
return values
migrated = dict(values)
# Case-insensitive settings sources normalize the former apiType env alias.
legacy = migrated.pop("apiType", migrated.get("api_type", migrated.get("apitype", "auto")))
migrated.pop("api_type", None)
migrated.pop("apitype", 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
+20 -14
View File
@@ -5,6 +5,7 @@ from typing import Any, ClassVar, Literal, cast
from pydantic import AliasChoices, ConfigDict, Field, PrivateAttr, field_validator, model_validator
from pydantic.fields import FieldInfo
from pydantic_core import PydanticCustomError
from pydantic_settings import BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict
from nanobot.agent.tools.cli_apps_config import CliAppsToolConfig
@@ -21,7 +22,6 @@ from nanobot.agent.tools.web_config import (
from nanobot.agent.tools.web_config import WebToolsConfig
from nanobot.config.home import get_default_workspace
from nanobot.config.network import NetworkConfig, migrate_legacy_proxy_config
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
@@ -266,6 +266,25 @@ class ProviderConfig(Base):
"reasoning_split",
)
@model_validator(mode="before")
@classmethod
def _reject_retired_api_selector(cls, value: object) -> object:
if not isinstance(value, dict):
return value
provider = cast(dict[object, object], value)
# Older releases wrote the default Auto to every provider. Auto is
# already the default, and a current declaration always takes priority.
if "api" not in provider and any(
key in provider and provider[key] != "auto"
for key in ("apiType", "api_type", "apitype")
):
raise PydanticCustomError(
"retired_provider_api_selector",
"The apiType setting was removed. Replace it with an api object that declares supportedApis, "
"or remove it for Auto.",
)
return provider
@field_validator("thinking_style")
@classmethod
def _validate_thinking_style(cls, v: str | None) -> str | None:
@@ -359,19 +378,6 @@ class ProvidersConfig(Base):
self.model_extra[key] = ProviderConfig.model_validate(value)
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):
"""Heartbeat service configuration (now backed by cron)."""
+13 -12
View File
@@ -26,7 +26,6 @@ from typing import TYPE_CHECKING, Any, Awaitable, Callable, NotRequired, TypedDi
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,
@@ -131,7 +130,14 @@ _ENV_REF_RE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
_PROVIDER_STRUCTURED_FIELDS = ("extra_headers", "extra_body", "extra_query")
def _provider_config_updates(query: QueryParams) -> dict[str, Any]:
def _provider_config_updates(
query: QueryParams, *, ignore_retired_api_type: bool = False,
) -> dict[str, Any]:
if not ignore_retired_api_type and query_has_alias(query, "api_type", "apiType"):
raise WebUISettingsError(
"This client sent the retired apiType setting. Update the client or use the WebUI "
"served by the gateway to save the provider settings."
)
updates: dict[str, Any] = {}
string_fields = (
("api_key", "apiKey"),
@@ -161,9 +167,6 @@ 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
@@ -1639,18 +1642,16 @@ def update_provider_settings(
if resolved_provider is None:
raise WebUISettingsError("unknown provider")
spec, provider_key, provider_config = resolved_provider
updates = _provider_config_updates(query)
# Keep the current declaration authoritative and preserve saves from old
# clients that also sent this irrelevant field for other providers.
updates = _provider_config_updates(
query, ignore_retired_api_type="api" in query or (not spec.is_oauth and spec.name != "openai"),
)
if updates.get("use_proxy"):
try:
config.network.resolve_proxy(True)
except ValueError as exc:
raise WebUISettingsError(str(exc)) from None
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")
+13 -43
View File
@@ -72,60 +72,30 @@ def test_agent_timezones_use_packaged_data_without_system_database() -> None:
assert result.returncode == 0, result.stderr
@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):
def test_old_installation_defaults_load_without_changing_provider_api(tmp_path):
from nanobot.config.loader import load_config, save_config
path = tmp_path / "config.json"
path.write_text(json.dumps({"providers": {"openai": {"apiKey": "sk-test", field: legacy}}}), encoding="utf-8")
path.write_text(json.dumps({"providers": {
"openai": {"apiType": "auto", "apiKey": "fixture"},
"custom": {"apiType": "auto", "apiBase": "https://example.test/v1"},
}}), encoding="utf-8")
config = load_config(path)
expected = None if legacy == "auto" else {
"supportedApis": [legacy], "preferredApi": legacy,
}
assert config.providers.openai.api is None
assert config.providers.custom.api is None
save_config(config, path)
saved = json.loads(path.read_text(encoding="utf-8"))["providers"]["openai"]
assert saved.get("api") == expected
assert field not in saved
assert load_config(path).providers.openai.api == config.providers.openai.api
assert load_config(path).providers.custom.api_base == "https://example.test/v1"
@pytest.mark.parametrize("api", [None, {"supportedApis": ["chat_completions"]}])
def test_current_provider_api_takes_precedence_over_legacy_input(api):
def test_current_provider_api_stays_authoritative_if_old_key_remains(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:
with pytest.raises(ValueError, match="only supported"):
Config.model_validate({
"providers": {
"custom": {
"apiBase": "https://example.test/v1",
"apiType": "responses",
}
}
})
with pytest.raises(ValueError, match="only supported"):
Config.model_validate({
"providers": {
"my-company-api": {
"apiBase": "https://example.test/v1",
"apiType": "responses",
}
}
})
resolved = config.providers.openai.api
assert (resolved.to_capabilities().preferred_api if resolved else None) == (
"chat_completions" if api else None
)
@pytest.mark.parametrize("provider_name", ["openai-codex", "github-copilot", "lm-studio"])
+16 -10
View File
@@ -707,17 +707,20 @@ async def test_explicit_model_api_overrides_connection_default(bind_transport, p
assert paths == [path]
@pytest.mark.parametrize("legacy,path", [
@pytest.mark.parametrize("selector,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):
async def test_openai_connection_api_round_trip_and_model_override(bind_transport, tmp_path, selector, 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}},
"providers": {"openai": {
"apiKey": "fixture",
"api": None if selector == "auto" else {"supportedApis": [selector]},
}},
"agents": {"defaults": {"model": "gpt-4o", "provider": "openai"}},
}), encoding="utf-8")
config = load_config(config_path)
@@ -733,9 +736,9 @@ async def test_migrated_openai_default_routes_and_allows_model_override(bind_tra
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"
"responses" if selector == "responses" else "chat_completions"
)
opposite = "chat_completions" if legacy == "responses" else "responses"
opposite = "chat_completions" if selector == "responses" else "responses"
config.model_presets["override"] = ModelPresetConfig(
model="gpt-4o", provider="openai", api=ModelAPIConfig(supported_apis=(opposite,)),
)
@@ -744,18 +747,21 @@ async def test_migrated_openai_default_routes_and_allows_model_override(bind_tra
assert requests[-1] == ("/v1/responses" if opposite == "responses" else "/v1/chat/completions")
@pytest.mark.parametrize("env_field", ["API_TYPE", "APITYPE"])
@pytest.mark.parametrize("legacy,path", [
@pytest.mark.parametrize("selector,path", [
("auto", "/v1/chat/completions"),
("chat_completions", "/v1/chat/completions"),
("responses", "/v1/responses"),
])
async def test_legacy_openai_environment_selector_keeps_request_api(
bind_transport, tmp_path, monkeypatch, env_field, legacy, path,
async def test_openai_environment_api_object_selects_request_api(
bind_transport, tmp_path, monkeypatch, selector, path,
):
from nanobot.config.loader import load_config
monkeypatch.setenv(f"NANOBOT_PROVIDERS__OPENAI__{env_field}", legacy)
if selector != "auto":
monkeypatch.setenv(
"NANOBOT_PROVIDERS__OPENAI__API",
json.dumps({"supportedApis": [selector]}),
)
config_path = tmp_path / "config.json"
config_path.write_text(json.dumps({
"providers": {"openai": {"apiKey": "fixture", "apiBase": "https://tenant.test/v1"}},
+3 -4
View File
@@ -998,7 +998,7 @@ def test_update_provider_settings_persists_provider_specific_advanced_options(
update_provider_settings(
{
"provider": ["openai"],
"apiType": ["responses"],
"api": [json.dumps({"supportedApis": ["responses"]})],
"use_proxy": ["true"],
"extraHeaders": [json.dumps({"X-Trace": "enabled"})],
"extraBody": [json.dumps({"service_tier": "priority"})],
@@ -2852,13 +2852,12 @@ def test_custom_connection_cannot_remove_api_used_by_legacy_or_inline_model(tmp_
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):
def test_openai_settings_can_return_to_auto(monkeypatch, tmp_path):
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"]})
update_provider_settings({"provider": ["openai"], "api": ["null"]})
assert load_config(config_path).providers.openai.api is None
+19
View File
@@ -764,6 +764,25 @@ async def test_model_update_route_forwards_session_rename_dependency(monkeypatch
refresh_runtime_config.assert_called_once_with()
@pytest.mark.asyncio
async def test_older_client_does_not_partially_update_provider_settings(tmp_path) -> None:
config_path = tmp_path / "config.json"
before = '{"providers":{"openai":{"apiKey":"fixture","api":{"supportedApis":["responses"]}}}}'
config_path.write_text(before, encoding="utf-8")
refresh = MagicMock()
router = _router(config_path=config_path, refresh_runtime_config=refresh)
path = "/api/settings/provider/update"
request = _mutation_request(path, {"provider": "openai", "apiType": "auto", "apiBase": "https://example.test/v1"})
response = await router.dispatch(None, request, path)
assert response is not None
assert response.status_code == 400
assert "Update the client" in json.loads(response.body)["error"]
assert config_path.read_text(encoding="utf-8") == before
refresh.assert_not_called()
@pytest.mark.asyncio
async def test_settings_get_mutation_route_is_method_not_allowed() -> None:
path = "/api/settings/provider/update"
+23 -12
View File
@@ -80,22 +80,33 @@ test("reduced motion keeps the canvas fade but switches the icon directly", asyn
const icon = toggle.locator("svg");
const core = icon.locator(":scope > circle");
await expect(core).toHaveCSS("r", "5px");
const capture = await page.locator(".workbench-pane").evaluateHandle(node => {
const sample = { transitions: 0, middle: "" };
const observer = new MutationObserver(() => {
if (document.documentElement.classList.contains("dark")) return;
observer.disconnect();
// Capture at the class commit, before a protocol round-trip can outlive the fade.
const transitions = node.getAnimations().filter(animation => animation instanceof CSSTransition
&& animation.transitionProperty === "background-color");
sample.transitions = transitions.length;
for (const transition of transitions) {
transition.pause();
transition.currentTime = 140;
}
sample.middle = getComputedStyle(node).backgroundColor;
for (const transition of transitions) transition.play();
});
observer.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] });
return sample;
});
await toggle.click();
await expect(page.locator("html")).not.toHaveClass(/dark/);
await expect(core).toHaveCSS("r", "8px");
expect(await icon.evaluate(node => node.getAnimations({ subtree: true }).length)).toBe(0);
const middle = await page.locator(".workbench-pane").evaluate(async node => {
await new Promise(requestAnimationFrame);
const transitions = node.getAnimations();
for (const transition of transitions) {
transition.pause();
transition.currentTime = 140;
}
const color = getComputedStyle(node).backgroundColor;
for (const transition of transitions) transition.play();
return color;
});
const red = Number(middle.match(/[\d.]+/)![0]);
const sample = await capture.jsonValue();
await capture.dispose();
expect(sample.transitions).toBe(1);
const red = Number(sample.middle.match(/[\d.]+/)![0]);
expect(red).toBeGreaterThan(48);
expect(red).toBeLessThan(255);
await expect.poll(() => page.locator("html").getAttribute("data-theme-transition")).toBeNull();