Preserve existing same-name custom provider settings

This commit is contained in:
Xubin Ren committed 2026-11-14 20:44:28 +08:00
1 parent 259c05e747
commit 8d64e22fbb
8 files changed
+121 -20

No files matched your search

+1 -1
View File
@@ -305,7 +305,7 @@ A Base URL is the service address nanobot sends model requests to. Change it onl
> - **VolcEngine / BytePlus Coding Plan**: Subscription endpoints are configured through dedicated providers `volcengineCodingPlan` or `byteplusCodingPlan`, separate from the pay-per-use `volcengine` / `byteplus` providers.
> - **OpenCode Zen / Go**: `providers.opencode` (canonical Zen), the legacy-compatible `providers.opencodeZen`, and `providers.opencodeGo` use the same `OPENCODE_API_KEY`, but route to different OpenCode gateways. These providers use OpenCode's OpenAI-compatible `chat/completions` endpoints; choose model IDs from that endpoint family.
> - **ShengSuanYun (胜算云)**: Select **ShengSuanYun Router** in **Settings → Models → Add provider** or in the Quick Start wizard (`nanobot onboard --wizard`). The built-in connection `providers.shengsuanyun` uses the [Router API URL](https://lean.shengsuanyun.com/apidocs/guides/quick-start). Use the full model ID, such as `deepseek/deepseek-v4-flash`. The default is Chat Completions; select Responses only for models that support it.
> If you previously used the exact key `shengsuanyun` for a hand-written custom connection, give it a different key and update matching provider references before upgrading. Custom connections created through the WebUI already have distinct keys and do not need changes.
> An existing `shengsuanyun` connection with a custom API declaration, name, thinking style, alternate API URL, or an explicit URL without a key continues to use its custom settings. To add the built-in connection alongside it, rename the custom key and update its matching provider references and any model IDs prefixed with `shengsuanyun/`. Custom connections created through the WebUI already use distinct keys.
> - **Zhipu Coding Plan**: If you're on Zhipu's coding plan, open the zhipu connection in **Settings → Models** and set its base URL to `https://open.bigmodel.cn/api/coding/paas/v4`.
> - **Alibaba Cloud BaiLian**: The built-in `dashscope` provider already defaults to `https://dashscope.aliyuncs.com/compatible-mode/v1`; no endpoint override is needed for that service.
> - **ModelScope**: The built-in `modelscope` provider already defaults to `https://api-inference.modelscope.cn/v1`; no endpoint override is needed for that service.
+10 -1
View File
@@ -1565,6 +1565,8 @@ def _select_quick_start_api_base(
def _configure_quick_start_provider(config: Config) -> bool | object:
from nanobot.providers.registry import find_by_name
while True:
_show_quick_start_progress(1)
@@ -1578,6 +1580,14 @@ def _configure_quick_start_provider(config: Config) -> bool | object:
assert isinstance(answer, str)
provider_name = provider_choices[answer]
provider_info = _get_quick_start_provider_info().get(provider_name)
provider_config = getattr(config.providers, provider_name, None)
spec = find_by_name(provider_name)
if spec and provider_config and spec.uses_legacy_custom_config(provider_config):
console.print(
f"[yellow]! {answer} already names a custom connection. "
"Keep using it, or rename it and its model references before configuring the built-in provider.[/yellow]"
)
return False
api_base = provider_info.default_api_base if provider_info else ""
base_was_prompted = False
@@ -1618,7 +1628,6 @@ def _configure_quick_start_provider(config: Config) -> bool | object:
api_base_result,
)
provider_config = getattr(config.providers, provider_name, None)
if provider_config is None:
console.print(f"[red]Unknown provider: {provider_name}[/red]")
return False
+15 -4
View File
@@ -613,6 +613,13 @@ class Config(BaseSettings):
model_prefix = model_lower.split("/", 1)[0] if "/" in model_lower else ""
normalized_prefix = model_prefix.replace("-", "_")
prefixed_provider = find_by_name(model_prefix) if model_prefix else None
legacy_connections = {
spec.name: provider
for spec in PROVIDERS
if spec.accepts_legacy_custom_config
and isinstance(provider := getattr(self.providers, spec.name, None), ProviderConfig)
and spec.uses_legacy_custom_config(provider)
}
def _kw_matches(kw: str) -> bool:
kw = kw.lower()
@@ -624,7 +631,7 @@ class Config(BaseSettings):
continue
p = getattr(self.providers, spec.name, None)
if p and model_prefix and normalized_prefix == spec.name:
if spec.is_oauth or spec.is_local or spec.is_direct or p.api_key:
if spec.is_oauth or spec.is_local or spec.is_direct or p.api_key or spec.name in legacy_connections:
return p, spec.name
# Check for custom provider by prefix (e.g., "companyProxy/gpt-4").
@@ -637,7 +644,7 @@ class Config(BaseSettings):
return custom
for spec in PROVIDERS:
if spec.is_transcription_only:
if spec.is_transcription_only or spec.name in legacy_connections:
continue
p = getattr(self.providers, spec.name, None)
if p and any(_kw_matches(kw) for kw in spec.keywords):
@@ -681,7 +688,7 @@ class Config(BaseSettings):
# OAuth providers are NOT valid fallbacks — they require explicit model selection
for spec in PROVIDERS:
if spec.is_oauth or spec.is_transcription_only:
if spec.is_oauth or spec.is_transcription_only or spec.name in legacy_connections:
continue
p = getattr(self.providers, spec.name, None)
if p and p.api_key:
@@ -691,6 +698,10 @@ class Config(BaseSettings):
if isinstance(p, ProviderConfig) and p.api_base:
return p, attr_name
for attr_name, p in legacy_connections.items():
if p.api_base:
return p, attr_name
return None, None
def get_provider(
@@ -737,7 +748,7 @@ class Config(BaseSettings):
return p.api_base
if name:
spec = find_by_name(name)
if spec and spec.default_api_base:
if spec and spec.default_api_base and (p is None or not spec.uses_legacy_custom_config(p)):
return spec.default_api_base
return None
+28 -1
View File
@@ -13,7 +13,7 @@ Every entry writes out all fields so you can copy-paste as a template.
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
from typing import TYPE_CHECKING, Any
from pydantic.alias_generators import to_snake
@@ -26,6 +26,9 @@ from nanobot.providers.model_api import is_direct_openai_base as is_direct_opena
from nanobot.providers.model_api import is_hosted_web_search_tool as is_hosted_web_search_tool
from nanobot.providers.model_api import is_hosted_web_search_type as is_hosted_web_search_type
if TYPE_CHECKING:
from nanobot.config.schema import ProviderConfig
@dataclass(frozen=True)
class ProviderModelSpec:
@@ -79,6 +82,8 @@ class ProviderSpec:
detect_by_key_prefix: str = "" # match api_key prefix, e.g. "sk-or-"
detect_by_base_keyword: str = "" # match substring in api_base URL
default_api_base: str = ""
accepts_legacy_custom_config: bool = False # This key previously allowed a named custom connection.
is_named_custom: bool = False # Created by create_dynamic_spec.
strip_model_prefix: bool = False # strip "provider/" before sending to gateway
strip_model_prefixes: tuple[str, ...] = () # strip only when the first model segment matches
@@ -146,6 +151,26 @@ class ProviderSpec:
def label(self) -> str:
return self.display_name or self.name.title()
def uses_legacy_custom_config(self, config: ProviderConfig) -> bool:
"""Keep the previous interpretation when this connection has custom settings."""
if not self.accepts_legacy_custom_config:
return False
return bool(
config.api is not None or config.display_name or config.thinking_style
or (config.api_base and (
not config.api_key or config.api_base.rstrip("/") != self.default_api_base.rstrip("/")
))
)
def for_connection(self, config: ProviderConfig) -> ProviderSpec:
if not self.uses_legacy_custom_config(config):
return self
return create_dynamic_spec(
self.name,
display_name=config.display_name or "",
thinking_style=config.thinking_style or "",
)
def request_model_name(self, model: str) -> str:
"""Remove only the provider prefixes owned by this adapter."""
if "/" not in model:
@@ -289,6 +314,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
display_name="ShengSuanYun Router",
is_gateway=True,
default_api_base="https://router.shengsuanyun.com/api/v1",
accepts_legacy_custom_config=True,
strip_model_prefixes=("shengsuanyun",),
),
# Eden AI: OpenAI-compatible gateway. Models use the "provider/model"
@@ -956,6 +982,7 @@ def create_dynamic_spec(
display_name=display_name or name.replace("-", " ").replace("_", " ").title(),
backend="openai_compat",
is_direct=True,
is_named_custom=True,
strip_model_prefixes=strip_prefixes,
thinking_style=thinking_style,
)
+1 -1
View File
@@ -53,7 +53,7 @@ def _provider_spec_for_config(
display_name=provider_config.display_name or "",
thinking_style=provider_config.thinking_style or "",
)
return spec
return spec.for_connection(provider_config) if spec is not None and provider_config is not None else spec
def resolve_model_api(
+17 -12
View File
@@ -321,7 +321,7 @@ def resolve_settings_provider(
if spec is not None:
provider_config = getattr(config.providers, spec.name, None)
if isinstance(provider_config, ProviderConfig):
return spec, spec.name, provider_config
return spec.for_connection(provider_config), spec.name, provider_config
return None
normalized = provider_name.replace("-", "_")
@@ -339,7 +339,7 @@ def resolve_settings_provider(
return None
def _provider_advanced_field_names(name: str, spec: Any) -> list[str]:
def _provider_advanced_field_names(spec: ProviderSpec) -> list[str]:
fields: list[str] = []
if spec.backend in {"openai_compat", "anthropic"}:
fields.append("extra_headers")
@@ -351,7 +351,7 @@ def _provider_advanced_field_names(name: str, spec: Any) -> list[str]:
fields.append("use_proxy")
if spec.backend == "bedrock":
fields.extend(("region", "profile"))
if find_by_name(name) is None:
if spec.is_named_custom:
fields.append("thinking_style")
return fields
@@ -363,7 +363,6 @@ def _provider_settings_row(
oauth_status_reader: OAuthStatusReader,
) -> 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 is not None and spec.is_direct else spec.request_apis
@@ -371,7 +370,7 @@ def _provider_settings_row(
row = {
"name": name,
"label": spec.label,
"is_custom": is_custom,
"is_custom": spec.is_named_custom,
"configured": (
bool(oauth_status["configured"])
if oauth_status is not None
@@ -389,7 +388,7 @@ def _provider_settings_row(
"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(request_apis) > 1,
"advanced_fields": _provider_advanced_field_names(name, spec),
"advanced_fields": _provider_advanced_field_names(spec),
"extra_headers": request_settings.redact_request_secrets(provider_config.extra_headers),
"extra_body": request_settings.redact_request_secrets(provider_config.extra_body),
"extra_query": request_settings.redact_request_secrets(provider_config.extra_query),
@@ -434,8 +433,10 @@ def _provider_settings_rows(
provider_config = getattr(config.providers, chosen.name, None)
if provider_config is None:
continue
row = _provider_settings_row(chosen.name, chosen, provider_config, oauth_status)
row["label"] = canonical.label
spec = chosen.for_connection(provider_config)
row = _provider_settings_row(chosen.name, spec, provider_config, oauth_status)
if not spec.is_named_custom:
row["label"] = canonical.label
rows.append(row)
return rows
@@ -900,8 +901,12 @@ def _provider_display_name_exists(
exclude_key: str | None = None,
) -> bool:
normalized = display_name.strip().casefold()
if any(spec.label.strip().casefold() == normalized for spec in PROVIDERS):
return True
for base_spec in PROVIDERS:
if base_spec.name == exclude_key:
continue
provider_config = getattr(config.providers, base_spec.name)
if base_spec.for_connection(provider_config).label.strip().casefold() == normalized:
return True
for provider_key, provider_config in _dynamic_provider_items(config):
if provider_key == exclude_key:
continue
@@ -1692,9 +1697,9 @@ def update_provider_settings(
allowed = {
"api_key",
"api_base",
*_provider_advanced_field_names(provider_key, spec),
*_provider_advanced_field_names(spec),
}
if find_by_name(provider_key) is None:
if spec.is_named_custom:
allowed.add("display_name")
if spec.provider_api_configurable:
allowed.add("api")
+12
View File
@@ -1306,6 +1306,18 @@ class TestMainMenuInteraction:
assert config.model_presets["primary"].provider == "ollama"
assert config.model_presets["primary"].model == "llama3.2"
def test_quick_start_does_not_write_over_legacy_custom_connection(self, monkeypatch, capsys):
config = Config.model_validate({"providers": {
"shengsuanyun": {"apiBase": "https://private-proxy.test/v1"},
}})
original = config.model_dump()
monkeypatch.setattr(onboard_wizard, "_show_quick_start_progress", lambda *_args: None)
monkeypatch.setattr(onboard_wizard, "_select_with_back", lambda *a, **kw: "ShengSuanYun Router")
assert onboard_wizard._configure_quick_start_provider(config) is False
assert config.model_dump() == original
assert "already names a custom connection" in capsys.readouterr().out
def test_quick_start_openai_stores_key_and_model_without_base(self, monkeypatch):
config = Config()
+37
View File
@@ -17,6 +17,7 @@ from nanobot.llm_usage.models import LLMCallRecord
from nanobot.providers.base import LLMUsage
from nanobot.providers.oauth_model_catalog import OAuthModelCatalogSnapshot
from nanobot.providers.registry import ProviderModelSpec, find_by_name
from nanobot.providers.routing import resolve_provider_route
from nanobot.session.manager import SessionManager
from nanobot.session.model_selection import SESSION_MODEL_PRESET_METADATA_KEY
from nanobot.webui.settings_api import (
@@ -1291,6 +1292,42 @@ def test_settings_payload_includes_dynamic_custom_provider(
assert providers[DYNAMIC_PROVIDER_NAME]["api_base"] == DYNAMIC_PROVIDER_API_BASE
@pytest.mark.parametrize(("api_base", "api_key"), [
("https://legacy-private.test/v1", None),
("https://router.shengsuanyun.com/api/v1", "legacy-test-key"),
])
def test_legacy_shengsuanyun_keeps_custom_route_and_settings(tmp_path, api_base, api_key):
config_path = tmp_path / "legacy.json"
config_path.write_text(json.dumps({
"agents": {"defaults": {"model": "shengsuanyun/example-model"}},
"providers": {
"openrouter": {"apiKey": "must-not-route-here"},
"shengsuanyun": {
"apiBase": api_base, "apiKey": api_key,
"api": {"supportedApis": ["chat_completions"]},
},
},
}), encoding="utf-8")
initial = settings_payload(config_path=config_path)
assert initial["agent"]["resolved_provider"] == "shengsuanyun"
initial_row = next(row for row in initial["providers"] if row["name"] == "shengsuanyun")
assert initial_row["is_custom"] and initial_row["provider_api_configurable"]
update_provider_settings(
{"provider": ["shengsuanyun"], "display_name": ["My private router"]},
config_path=config_path,
)
saved = load_config(config_path)
route = resolve_provider_route(saved, preset=saved.resolve_preset())
assert route.provider_name == "shengsuanyun"
assert saved.get_api_base() == api_base
assert route.model_api is not None and route.model_api.preferred_api == "chat_completions"
assert route.spec is not None and route.spec.request_model_name(route.model) == "example-model"
row = next(row for row in settings_payload(config_path=config_path)["providers"] if row["name"] == "shengsuanyun")
assert row["label"] == "My private router"
def test_settings_payload_resolves_provider_for_each_auto_preset(
tmp_path,
monkeypatch: pytest.MonkeyPatch,