Register ShengSuanYun as a standard provider
This commit is contained in:
1 parent
0b9e546672
commit
259c05e747
17 files changed
+265
-503
No files matched your search
@@ -304,7 +304,8 @@ A Base URL is the service address nanobot sends model requests to. Change it onl
|
||||
> - **Kimi Coding Plan**: Use `providers.kimiCoding` with `provider: "kimi_coding"` for Kimi's dedicated Anthropic Messages API endpoint. The endpoint requires a Claude-compatible `User-Agent`; nanobot sends `claude-code/0.1.0` by default, and you can override it with `extraHeaders.User-Agent` if your account requires a different value.
|
||||
> - **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 (胜算云)**: Search for **ShengSuanYun Router** in **Add provider**, or select it under **Quick Start** in `nanobot onboard --wizard`. Both prefill the [Router API URL](https://lean.shengsuanyun.com/apidocs/guides/quick-start) for a custom connection. Enter your API key and use the full model ID, for example `deepseek/deepseek-v4-flash`. The wizard saves a separate model preset and keeps any configured default model. Chat Completions is the default; select Responses in a preset's **Advanced options** only for a model that supports it.
|
||||
> - **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.
|
||||
> - **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.
|
||||
|
||||
@@ -48,10 +48,6 @@ Useful `ProviderSpec` options:
|
||||
| `responses` | `ResponsesCapabilities` with automatic model rules, reasoning replay, and fallback policy. |
|
||||
| `is_transcription_only` | Provider has credentials but cannot serve chat completions. |
|
||||
|
||||
### Setup templates for compatible endpoints
|
||||
|
||||
If a provider only needs a prefilled URL and request API options, add an entry to `PROVIDER_SETUP_TEMPLATES` in [`nanobot/providers/setup.py`](../nanobot/providers/setup.py). Quick Start and WebUI read the same declaration. A template creates an ordinary custom connection; it does not reserve a runtime provider ID or add a new adapter.
|
||||
|
||||
### Request API routing
|
||||
|
||||
`resolve_provider_route` in `nanobot/providers/routing.py` validates connection and preset declarations and selects the adapter. Built-in OpenAI connection declarations set an overridable default; custom connection declarations also limit the preset's allowed APIs.
|
||||
|
||||
+103
-99
@@ -29,14 +29,8 @@ from nanobot.cli.models import (
|
||||
get_model_context_limit,
|
||||
)
|
||||
from nanobot.config.loader import get_config_path, load_config
|
||||
from nanobot.config.schema import Config, ModelPresetConfig, ProviderConfig
|
||||
from nanobot.config.schema import Config, ModelPresetConfig
|
||||
from nanobot.providers.oauth_guidance import OAUTH_CLI_KIT_MISSING_MESSAGE
|
||||
from nanobot.providers.setup import (
|
||||
PROVIDER_SETUP_TEMPLATES,
|
||||
ProviderSetupTemplate,
|
||||
custom_provider_key,
|
||||
setup_template_names,
|
||||
)
|
||||
|
||||
console = Console()
|
||||
|
||||
@@ -1391,13 +1385,17 @@ def _show_summary(config: Config) -> None:
|
||||
_pause()
|
||||
|
||||
|
||||
def _pause(message: str = "Press Enter to continue...") -> bool:
|
||||
return _get_questionary().text(message, default="").ask() is not None
|
||||
def _pause(message: str = "Press Enter to continue...") -> None:
|
||||
_get_questionary().text(message, default="").ask()
|
||||
|
||||
|
||||
def _set_primary_quick_start_preset(config: Config, provider_name: str, model: str) -> None:
|
||||
config.model_presets["primary"] = ModelPresetConfig(model=model, provider=provider_name)
|
||||
config.model_presets["primary"] = ModelPresetConfig(
|
||||
model=model,
|
||||
provider=provider_name,
|
||||
)
|
||||
config.agents.defaults.model_preset = "primary"
|
||||
_sync_preset_cache(config)
|
||||
|
||||
|
||||
def _show_quick_start_progress(active_step: int) -> None:
|
||||
@@ -1438,18 +1436,18 @@ def _get_quick_start_provider_info() -> dict[str, _QuickStartProviderInfo]:
|
||||
return result
|
||||
|
||||
|
||||
def _get_quick_start_provider_choices() -> dict[str, str | ProviderSetupTemplate]:
|
||||
choices: dict[str, str | ProviderSetupTemplate] = {}
|
||||
def _get_quick_start_provider_choices() -> dict[str, str]:
|
||||
choices: dict[str, str] = {}
|
||||
for provider_name, info in _get_quick_start_provider_info().items():
|
||||
choices.setdefault(info.display_name, provider_name)
|
||||
for template in PROVIDER_SETUP_TEMPLATES:
|
||||
alias, _, _ = template.search_aliases.partition(" ")
|
||||
label = f"{template.label} ({alias})" if alias else template.label
|
||||
choices.setdefault(label, template)
|
||||
choices[_QUICK_START_CUSTOM_PROVIDER_CHOICE] = "custom"
|
||||
return choices
|
||||
|
||||
|
||||
def _quick_start_requires_api_key(provider_name: str, info: _QuickStartProviderInfo | None) -> bool:
|
||||
return provider_name == "custom" or not (info and (info.is_local or info.is_oauth))
|
||||
|
||||
|
||||
def _quick_start_codex_proxy(config: Config) -> str | None:
|
||||
return config.network.resolve_proxy(config.providers.openai_codex.use_proxy)
|
||||
|
||||
@@ -1517,6 +1515,8 @@ def _quick_start_oauth_is_authenticated(config: Config, provider_name: str) -> b
|
||||
def _quick_start_requires_base_url(provider_name: str, info: _QuickStartProviderInfo | None) -> bool:
|
||||
if provider_name == "custom":
|
||||
return True
|
||||
if provider_name in _QUICK_START_ENDPOINT_CHOICES:
|
||||
return False
|
||||
if info is None or info.default_api_base:
|
||||
return False
|
||||
return info.backend == "azure_openai" or (
|
||||
@@ -1524,22 +1524,47 @@ def _quick_start_requires_base_url(provider_name: str, info: _QuickStartProvider
|
||||
)
|
||||
|
||||
|
||||
def _select_quick_start_endpoint(
|
||||
def _select_quick_start_api_base(
|
||||
provider_name: str,
|
||||
provider_display: str,
|
||||
endpoint_choices: tuple[_QuickStartEndpointChoice, ...],
|
||||
) -> str | object:
|
||||
choices = {choice.label: choice.api_base for choice in endpoint_choices}
|
||||
answer = _select_with_back(
|
||||
f"Which {provider_display} endpoint should Quick Start use?",
|
||||
list(choices) + ["<- Back"],
|
||||
default=endpoint_choices[0].label,
|
||||
info: _QuickStartProviderInfo | None,
|
||||
) -> tuple[str, bool] | None | object:
|
||||
endpoint_choices = _QUICK_START_ENDPOINT_CHOICES.get(provider_name)
|
||||
if endpoint_choices:
|
||||
choices = {choice.label: choice.api_base for choice in endpoint_choices}
|
||||
answer = _select_with_back(
|
||||
f"Which {provider_display} endpoint should Quick Start use?",
|
||||
list(choices) + ["<- Back"],
|
||||
default=endpoint_choices[0].label,
|
||||
)
|
||||
if answer is _BACK_PRESSED or answer == "<- Back":
|
||||
return _BACK_PRESSED
|
||||
if answer is None:
|
||||
return None
|
||||
assert isinstance(answer, str)
|
||||
return choices[answer], True
|
||||
|
||||
api_base = info.default_api_base if info else ""
|
||||
if not _quick_start_requires_base_url(provider_name, info):
|
||||
return api_base, False
|
||||
|
||||
base_answer = _input_text(
|
||||
"Provider base URL",
|
||||
api_base,
|
||||
"str",
|
||||
)
|
||||
if answer is _BACK_PRESSED or answer == "<- Back":
|
||||
if base_answer is _BACK_PRESSED:
|
||||
return _BACK_PRESSED
|
||||
return choices[answer] if isinstance(answer, str) else None
|
||||
if base_answer is None:
|
||||
return None
|
||||
api_base = base_answer.strip().rstrip("/")
|
||||
if not api_base:
|
||||
console.print("[yellow]! Provider base URL is required for this provider[/yellow]")
|
||||
return None
|
||||
return api_base, True
|
||||
|
||||
|
||||
def _configure_quick_start_provider(config: Config) -> str | object:
|
||||
def _configure_quick_start_provider(config: Config) -> bool | object:
|
||||
while True:
|
||||
_show_quick_start_progress(1)
|
||||
|
||||
@@ -1551,67 +1576,59 @@ def _configure_quick_start_provider(config: Config) -> str | object:
|
||||
if answer is _BACK_PRESSED or answer is None or answer == "<- Back":
|
||||
return _BACK_PRESSED
|
||||
assert isinstance(answer, str)
|
||||
choice = provider_choices[answer]
|
||||
template = choice if isinstance(choice, ProviderSetupTemplate) else None
|
||||
provider_name = choice if isinstance(choice, str) else "custom"
|
||||
provider_name = provider_choices[answer]
|
||||
provider_info = _get_quick_start_provider_info().get(provider_name)
|
||||
|
||||
api_base = ""
|
||||
if endpoints := _QUICK_START_ENDPOINT_CHOICES.get(provider_name):
|
||||
api_base_result = _select_quick_start_endpoint(answer, endpoints)
|
||||
api_base = provider_info.default_api_base if provider_info else ""
|
||||
base_was_prompted = False
|
||||
if provider_name in _QUICK_START_ENDPOINT_CHOICES:
|
||||
api_base_result = _select_quick_start_api_base(provider_name, answer, provider_info)
|
||||
if api_base_result is _BACK_PRESSED:
|
||||
continue
|
||||
if not isinstance(api_base_result, str):
|
||||
if api_base_result is None:
|
||||
return False
|
||||
api_base = api_base_result
|
||||
api_base, base_was_prompted = cast(
|
||||
tuple[str, bool],
|
||||
api_base_result,
|
||||
)
|
||||
|
||||
api_key: str | None = None
|
||||
if not (provider_info and (provider_info.is_local or provider_info.is_oauth)):
|
||||
prompt = f"{answer} API key"
|
||||
key_answer = _input_secret(prompt) if template else _input_text(prompt, "", "str")
|
||||
if key_answer is _BACK_PRESSED:
|
||||
if _quick_start_requires_api_key(provider_name, provider_info):
|
||||
api_key = _input_text(f"{answer} API key", "", "str")
|
||||
if api_key is _BACK_PRESSED:
|
||||
continue
|
||||
if key_answer is None:
|
||||
if api_key is None:
|
||||
return False
|
||||
api_key = cast(str, key_answer).strip()
|
||||
api_key = api_key.strip()
|
||||
if not api_key:
|
||||
console.print("[yellow]! API key is required for Quick Start[/yellow]")
|
||||
return False
|
||||
|
||||
if not (endpoints or template) and _quick_start_requires_base_url(provider_name, provider_info):
|
||||
base_answer = _input_text("Provider base URL", "", "str")
|
||||
if base_answer is _BACK_PRESSED:
|
||||
if (
|
||||
provider_name not in _QUICK_START_ENDPOINT_CHOICES
|
||||
and _quick_start_requires_base_url(provider_name, provider_info)
|
||||
):
|
||||
api_base_result = _select_quick_start_api_base(provider_name, answer, provider_info)
|
||||
if api_base_result is _BACK_PRESSED:
|
||||
continue
|
||||
if base_answer is None:
|
||||
if api_base_result is None:
|
||||
return False
|
||||
api_base = base_answer.strip().rstrip("/")
|
||||
if not api_base:
|
||||
console.print("[yellow]! Provider base URL is required for this provider[/yellow]")
|
||||
return False
|
||||
|
||||
catalog_config = config.model_copy(deep=True)
|
||||
preset_name = "primary"
|
||||
if template:
|
||||
label, preset_name = setup_template_names(config, template)
|
||||
provider_name = custom_provider_key(config, label)
|
||||
catalog_provider = ProviderConfig(
|
||||
display_name=label,
|
||||
api_base=template.api_base,
|
||||
api=template.api.model_copy(),
|
||||
api_base, base_was_prompted = cast(
|
||||
tuple[str, bool],
|
||||
api_base_result,
|
||||
)
|
||||
setattr(catalog_config.providers, provider_name, catalog_provider)
|
||||
else:
|
||||
catalog_provider = getattr(catalog_config.providers, provider_name, None)
|
||||
if catalog_provider is None:
|
||||
|
||||
provider_config = getattr(config.providers, provider_name, None)
|
||||
if provider_config is None:
|
||||
console.print(f"[red]Unknown provider: {provider_name}[/red]")
|
||||
return False
|
||||
|
||||
catalog_config = config.model_copy(deep=True)
|
||||
catalog_provider = getattr(catalog_config.providers, provider_name)
|
||||
if api_key is not None:
|
||||
catalog_provider.api_key = api_key
|
||||
if api_base:
|
||||
if api_base and (base_was_prompted or not catalog_provider.api_base):
|
||||
catalog_provider.api_base = api_base
|
||||
elif not catalog_provider.api_base and provider_info and provider_info.default_api_base:
|
||||
catalog_provider.api_base = provider_info.default_api_base
|
||||
|
||||
model = _input_model_with_autocomplete(
|
||||
"Model ID",
|
||||
@@ -1630,19 +1647,20 @@ def _configure_quick_start_provider(config: Config) -> str | object:
|
||||
if not _quick_start_oauth_login(config, provider_name):
|
||||
return False
|
||||
|
||||
use_template_as_default = (
|
||||
template is not None
|
||||
and config.agents.defaults.model_preset is None
|
||||
and config.get_provider() is None
|
||||
if api_key is not None:
|
||||
provider_config.api_key = api_key
|
||||
if api_base:
|
||||
if base_was_prompted:
|
||||
provider_config.api_base = api_base
|
||||
elif not provider_config.api_base:
|
||||
provider_config.api_base = api_base
|
||||
|
||||
_set_primary_quick_start_preset(
|
||||
config,
|
||||
provider_name,
|
||||
model,
|
||||
)
|
||||
setattr(config.providers, provider_name, catalog_provider)
|
||||
if template is None:
|
||||
_set_primary_quick_start_preset(config, provider_name, model)
|
||||
return "primary"
|
||||
config.model_presets[preset_name] = ModelPresetConfig(model=model, provider=provider_name)
|
||||
if use_template_as_default:
|
||||
config.agents.defaults.model_preset = preset_name
|
||||
return preset_name
|
||||
return True
|
||||
|
||||
|
||||
def _enable_quick_start_websocket_defaults(config: Config) -> bool:
|
||||
@@ -1689,14 +1707,9 @@ def _enable_quick_start_websocket_defaults(config: Config) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def _quick_start_websocket_enabled(config: Config) -> bool:
|
||||
websocket: Any = getattr(config.channels, "websocket", None)
|
||||
return bool(websocket and websocket.get("enabled"))
|
||||
|
||||
|
||||
def _show_quick_start_summary(config: Config, preset_name: str) -> None:
|
||||
def _show_quick_start_summary(config: Config) -> None:
|
||||
_show_quick_start_progress(3)
|
||||
preset = config.model_presets.get(preset_name)
|
||||
preset = config.model_presets.get("primary")
|
||||
provider_label = "AI provider"
|
||||
credentials_ready = True
|
||||
credential_name = "API key"
|
||||
@@ -1722,11 +1735,8 @@ def _show_quick_start_summary(config: Config, preset_name: str) -> None:
|
||||
|
||||
rows = [
|
||||
("Status", status),
|
||||
("Model preset", preset_name),
|
||||
("WebSocket channel", "enabled" if _quick_start_websocket_enabled(config) else "disabled"),
|
||||
("WebSocket channel", "enabled"),
|
||||
]
|
||||
if config.agents.defaults.model_preset != preset_name:
|
||||
rows.insert(2, ("Default model", f"unchanged (switch with /model {preset_name})"))
|
||||
_print_summary_panel(rows, "Quick Start")
|
||||
|
||||
|
||||
@@ -1740,22 +1750,16 @@ def _configure_quick_start(config: Config) -> bool:
|
||||
provider_result = _configure_quick_start_provider(draft)
|
||||
if provider_result is _BACK_PRESSED:
|
||||
return False
|
||||
if not isinstance(provider_result, str):
|
||||
if not provider_result:
|
||||
_pause()
|
||||
return False
|
||||
needs_websocket_setup = provider_result == "primary" or (
|
||||
draft.agents.defaults.model_preset == provider_result
|
||||
and getattr(draft.channels, "websocket", None) is None
|
||||
)
|
||||
if needs_websocket_setup and not _enable_quick_start_websocket_defaults(draft):
|
||||
if not _enable_quick_start_websocket_defaults(draft):
|
||||
_pause()
|
||||
return False
|
||||
_show_quick_start_summary(draft, provider_result)
|
||||
if not _pause("Press Enter to save and exit..."):
|
||||
return False
|
||||
_show_quick_start_summary(draft)
|
||||
_pause("Press Enter to save and exit...")
|
||||
for field_name in type(config).model_fields:
|
||||
setattr(config, field_name, getattr(draft, field_name))
|
||||
_sync_preset_cache(config)
|
||||
return True
|
||||
|
||||
|
||||
|
||||
@@ -324,6 +324,7 @@ class ProvidersConfig(Base):
|
||||
openai: ProviderConfig = Field(default_factory=ProviderConfig)
|
||||
openrouter: ProviderConfig = Field(default_factory=ProviderConfig)
|
||||
orcarouter: ProviderConfig = Field(default_factory=ProviderConfig)
|
||||
shengsuanyun: ProviderConfig = Field(default_factory=ProviderConfig)
|
||||
assemblyai: ProviderConfig = Field(default_factory=ProviderConfig)
|
||||
huggingface: ProviderConfig = Field(default_factory=ProviderConfig)
|
||||
skywork: ProviderConfig = Field(default_factory=ProviderConfig)
|
||||
|
||||
@@ -281,6 +281,16 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
|
||||
detect_by_base_keyword="orcarouter",
|
||||
default_api_base="https://api.orcarouter.ai/v1",
|
||||
),
|
||||
ProviderSpec(
|
||||
name="shengsuanyun",
|
||||
keywords=("shengsuanyun",),
|
||||
env_key="SHENGSUANYUN_API_KEY",
|
||||
request_apis=("chat_completions", "responses"),
|
||||
display_name="ShengSuanYun Router",
|
||||
is_gateway=True,
|
||||
default_api_base="https://router.shengsuanyun.com/api/v1",
|
||||
strip_model_prefixes=("shengsuanyun",),
|
||||
),
|
||||
# Eden AI: OpenAI-compatible gateway. Models use the "provider/model"
|
||||
# naming scheme (e.g. "anthropic/claude-sonnet-4-5"); the full id is sent upstream.
|
||||
ProviderSpec(
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
"""Setup templates create ordinary custom connections, not runtime providers."""
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
from nanobot.config.schema import Config, ProviderAPIConfig, ProviderConfig
|
||||
from nanobot.providers.registry import PROVIDERS, find_by_name
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ProviderSetupTemplate:
|
||||
id: str
|
||||
label: str
|
||||
api_base: str
|
||||
api: ProviderAPIConfig
|
||||
search_aliases: str = ""
|
||||
|
||||
|
||||
PROVIDER_SETUP_TEMPLATES = (
|
||||
ProviderSetupTemplate(
|
||||
id="shengsuanyun",
|
||||
label="ShengSuanYun Router",
|
||||
api_base="https://router.shengsuanyun.com/api/v1",
|
||||
api=ProviderAPIConfig(
|
||||
supported_apis=("chat_completions", "responses"), preferred_api="chat_completions",
|
||||
),
|
||||
search_aliases="胜算云 勝算雲",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def dynamic_provider_items(config: Config) -> list[tuple[str, ProviderConfig]]:
|
||||
return [
|
||||
(key, provider)
|
||||
for key, provider in (config.providers.model_extra or {}).items()
|
||||
if isinstance(provider, ProviderConfig)
|
||||
]
|
||||
|
||||
|
||||
def custom_provider_key(config: Config, display_name: str) -> str:
|
||||
slug = re.sub(r"[^a-z0-9_-]+", "-", display_name.strip().lower()).strip("-_")
|
||||
base = f"custom-{slug or 'provider'}"[:56].rstrip("-_")
|
||||
existing = {key.replace("_", "-").lower() for key, _ in dynamic_provider_items(config)}
|
||||
candidate = base
|
||||
suffix = 2
|
||||
while candidate.replace("_", "-") in existing or find_by_name(candidate):
|
||||
candidate = f"{base}-{suffix}"
|
||||
suffix += 1
|
||||
return candidate
|
||||
|
||||
|
||||
def provider_display_name_exists(
|
||||
config: Config, display_name: str, *, exclude_key: str | None = None,
|
||||
) -> bool:
|
||||
normalized = display_name.strip().casefold()
|
||||
if any(spec.label.strip().casefold() == normalized for spec in PROVIDERS):
|
||||
return True
|
||||
return any(
|
||||
key != exclude_key
|
||||
and (provider.display_name or key.replace("-", " ").replace("_", " ")).strip().casefold()
|
||||
== normalized
|
||||
for key, provider in dynamic_provider_items(config)
|
||||
)
|
||||
|
||||
|
||||
def setup_template_names(config: Config, template: ProviderSetupTemplate) -> tuple[str, str]:
|
||||
"""Pick an unused display name and preset name for a new connection."""
|
||||
presets = {"default", "primary", *(name.casefold() for name in config.model_presets)}
|
||||
label, preset = template.label, template.id
|
||||
index = 2
|
||||
while preset.casefold() in presets or provider_display_name_exists(config, label):
|
||||
label, preset = f"{template.label} {index}", f"{template.id}-{index}"
|
||||
index += 1
|
||||
return label, preset
|
||||
@@ -49,13 +49,6 @@ from nanobot.providers.registry import (
|
||||
)
|
||||
from nanobot.providers.request_overrides import isolate_request_overrides
|
||||
from nanobot.providers.routing import resolve_automatic_model_api, resolve_model_api
|
||||
from nanobot.providers.setup import (
|
||||
PROVIDER_SETUP_TEMPLATES,
|
||||
custom_provider_key,
|
||||
dynamic_provider_items,
|
||||
provider_display_name_exists,
|
||||
setup_template_names,
|
||||
)
|
||||
from nanobot.runtime_admission import RuntimeAdmission
|
||||
from nanobot.webui import request_settings
|
||||
from nanobot.webui.settings_contracts import (
|
||||
@@ -112,7 +105,6 @@ class ModelSettingsPayload(TypedDict):
|
||||
provider_api_configuration_supported: bool
|
||||
model_request_overrides_supported: bool
|
||||
providers: list[dict[str, Any]]
|
||||
provider_setup_templates: list[dict[str, Any]]
|
||||
|
||||
|
||||
class ProviderModelMetadataPayload(TypedDict, total=False):
|
||||
@@ -312,6 +304,15 @@ def provider_configured_for_settings(
|
||||
)
|
||||
|
||||
|
||||
def _dynamic_provider_items(config: Config) -> list[tuple[str, ProviderConfig]]:
|
||||
model_extra = config.providers.model_extra or {}
|
||||
return [
|
||||
(name, provider_config)
|
||||
for name, provider_config in model_extra.items()
|
||||
if isinstance(provider_config, ProviderConfig)
|
||||
]
|
||||
|
||||
|
||||
def resolve_settings_provider(
|
||||
config: Config,
|
||||
provider_name: str,
|
||||
@@ -324,7 +325,7 @@ def resolve_settings_provider(
|
||||
return None
|
||||
|
||||
normalized = provider_name.replace("-", "_")
|
||||
for extra_name, provider_config in dynamic_provider_items(config):
|
||||
for extra_name, provider_config in _dynamic_provider_items(config):
|
||||
if provider_name == extra_name or normalized == extra_name.replace("-", "_"):
|
||||
return (
|
||||
create_dynamic_spec(
|
||||
@@ -875,6 +876,44 @@ def _rename_model_configuration(config: Config, old_name: str, new_name: str) ->
|
||||
return True
|
||||
|
||||
|
||||
def _custom_provider_key(config: Config, display_name: str) -> str:
|
||||
slug = _MODEL_CONFIGURATION_SLUG_RE.sub("-", display_name.strip().lower()).strip("-_")
|
||||
base = f"custom-{slug or 'provider'}"
|
||||
if len(base) > 56:
|
||||
base = base[:56].rstrip("-_")
|
||||
existing = {
|
||||
name.replace("_", "-").lower()
|
||||
for name, _provider_config in _dynamic_provider_items(config)
|
||||
}
|
||||
candidate = base
|
||||
suffix = 2
|
||||
while candidate.replace("_", "-").lower() in existing or find_by_name(candidate):
|
||||
candidate = f"{base}-{suffix}"
|
||||
suffix += 1
|
||||
return candidate
|
||||
|
||||
|
||||
def _provider_display_name_exists(
|
||||
config: Config,
|
||||
display_name: str,
|
||||
*,
|
||||
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 provider_key, provider_config in _dynamic_provider_items(config):
|
||||
if provider_key == exclude_key:
|
||||
continue
|
||||
label = (
|
||||
provider_config.display_name
|
||||
or provider_key.replace("-", " ").replace("_", " ").title()
|
||||
)
|
||||
if label.strip().casefold() == normalized:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _unique_model_configuration_name(config: Config, label: str) -> str:
|
||||
try:
|
||||
base = _model_configuration_slug(label)
|
||||
@@ -1034,7 +1073,7 @@ def model_settings_payload(
|
||||
selected_provider = spec.name if spec else provider_name
|
||||
|
||||
providers = _provider_settings_rows(config, selected_provider, oauth_status)
|
||||
for provider_key, provider_config in dynamic_provider_items(config):
|
||||
for provider_key, provider_config in _dynamic_provider_items(config):
|
||||
providers.append(
|
||||
_provider_settings_row(
|
||||
provider_key,
|
||||
@@ -1139,17 +1178,6 @@ def model_settings_payload(
|
||||
oauth_status,
|
||||
),
|
||||
"providers": providers,
|
||||
"provider_setup_templates": [
|
||||
{
|
||||
"id": template.id,
|
||||
"label": template.label,
|
||||
"suggested_name": setup_template_names(config, template)[0],
|
||||
"search_aliases": template.search_aliases,
|
||||
"api_base": template.api_base,
|
||||
"api": template.api.model_dump(mode="json", exclude_none=True),
|
||||
}
|
||||
for template in PROVIDER_SETUP_TEMPLATES
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@@ -1620,10 +1648,10 @@ def create_provider_settings(config: Config, query: QueryParams) -> str:
|
||||
api_base = str(updates.get("api_base") or "")
|
||||
if not api_base:
|
||||
raise WebUISettingsError("API base is required")
|
||||
if provider_display_name_exists(config, display_name):
|
||||
if _provider_display_name_exists(config, display_name):
|
||||
raise WebUISettingsError("provider already exists", status=409)
|
||||
|
||||
provider_key = custom_provider_key(config, display_name)
|
||||
provider_key = _custom_provider_key(config, display_name)
|
||||
updates["display_name"] = display_name
|
||||
provider_config = request_settings.validate_request_config(None, updates)
|
||||
setattr(config.providers, provider_key, provider_config)
|
||||
@@ -1681,7 +1709,7 @@ def update_provider_settings(
|
||||
raise WebUISettingsError("provider name is required")
|
||||
if len(display_name) > 80:
|
||||
raise WebUISettingsError("provider name must be 80 characters or fewer")
|
||||
if provider_display_name_exists(config, display_name, exclude_key=provider_key):
|
||||
if _provider_display_name_exists(config, display_name, exclude_key=provider_key):
|
||||
raise WebUISettingsError("provider already exists", status=409)
|
||||
|
||||
updated_provider_config = request_settings.validate_request_config(provider_config, updates)
|
||||
|
||||
@@ -2,13 +2,11 @@ from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, cast
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from prompt_toolkit.application import create_app_session
|
||||
from prompt_toolkit.input import create_pipe_input
|
||||
from prompt_toolkit.output import DummyOutput
|
||||
from pydantic import BaseModel, Field
|
||||
from typer.testing import CliRunner
|
||||
|
||||
from nanobot.cli import onboard as onboard_wizard
|
||||
from nanobot.cli.onboard import (
|
||||
@@ -21,11 +19,8 @@ from nanobot.cli.onboard import (
|
||||
_input_text,
|
||||
run_onboard,
|
||||
)
|
||||
from nanobot.config import home as instance_home
|
||||
from nanobot.config import loader
|
||||
from nanobot.config.loader import load_config, merge_missing_defaults, save_config
|
||||
from nanobot.config.loader import merge_missing_defaults
|
||||
from nanobot.config.schema import Config, ModelPresetConfig
|
||||
from nanobot.providers.routing import resolve_provider_route
|
||||
from nanobot.utils.helpers import sync_workspace_templates
|
||||
|
||||
|
||||
@@ -902,7 +897,7 @@ class TestMainMenuInteraction:
|
||||
from nanobot.providers.registry import PROVIDERS
|
||||
|
||||
choices = onboard_wizard._get_quick_start_provider_choices()
|
||||
selected_provider_names = {choice for choice in choices.values() if isinstance(choice, str)}
|
||||
selected_provider_names = set(choices.values())
|
||||
expected_provider_names = set()
|
||||
seen_display_names: set[str] = set()
|
||||
for spec in PROVIDERS:
|
||||
@@ -958,7 +953,7 @@ class TestMainMenuInteraction:
|
||||
or True,
|
||||
)
|
||||
|
||||
assert onboard_wizard._configure_quick_start_provider(config) == "primary"
|
||||
assert onboard_wizard._configure_quick_start_provider(config) is True
|
||||
|
||||
assert oauth_calls == [(config, "openai_codex")]
|
||||
assert model_prompts == [
|
||||
@@ -1118,7 +1113,6 @@ class TestMainMenuInteraction:
|
||||
|
||||
def test_quick_start_summary_reports_missing_codex_oauth(self, monkeypatch):
|
||||
config = Config()
|
||||
config.channels.websocket = {"enabled": True}
|
||||
config.model_presets["primary"] = ModelPresetConfig(
|
||||
model="openai-codex/gpt-5.6-sol",
|
||||
provider="openai_codex",
|
||||
@@ -1137,7 +1131,7 @@ class TestMainMenuInteraction:
|
||||
lambda rows, _title: captured.setdefault("rows", rows),
|
||||
)
|
||||
|
||||
onboard_wizard._show_quick_start_summary(config, "primary")
|
||||
onboard_wizard._show_quick_start_summary(config)
|
||||
|
||||
rows = dict(captured["rows"])
|
||||
assert rows["Status"] == "OpenAI Codex OAuth login missing"
|
||||
@@ -1177,11 +1171,7 @@ class TestMainMenuInteraction:
|
||||
)
|
||||
monkeypatch.setattr(onboard_wizard, "_configure_pydantic_model", fail_websocket_config)
|
||||
monkeypatch.setattr(onboard_wizard, "_print_summary_panel", lambda *a, **kw: None)
|
||||
def pause(message=""):
|
||||
pause_messages.append(message)
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(onboard_wizard, "_pause", pause)
|
||||
monkeypatch.setattr(onboard_wizard, "_pause", lambda message="": pause_messages.append(message))
|
||||
|
||||
assert onboard_wizard._configure_quick_start(config) is True
|
||||
|
||||
@@ -1267,29 +1257,31 @@ class TestMainMenuInteraction:
|
||||
assert config.model_dump(by_alias=True) == original
|
||||
assert getattr(config.channels, "websocket", None) is None
|
||||
|
||||
@pytest.mark.parametrize("existing_base", [None, "https://my-router.example/v1"])
|
||||
def test_quick_start_provider_choice_asks_for_model_id(self, monkeypatch, existing_base):
|
||||
@pytest.mark.parametrize(("label", "provider", "api_base", "model"), [
|
||||
("OpenRouter", "openrouter", "https://openrouter.ai/api/v1", "openai/gpt-4o-mini"),
|
||||
("ShengSuanYun Router", "shengsuanyun", "https://router.shengsuanyun.com/api/v1", "deepseek/deepseek-v4-flash"),
|
||||
])
|
||||
def test_quick_start_provider_choice_asks_for_model_id(self, monkeypatch, label, provider, api_base, model):
|
||||
config = Config()
|
||||
config.providers.openrouter.api_base = existing_base
|
||||
model_prompts: list[tuple[str, str, str]] = []
|
||||
|
||||
monkeypatch.setattr(onboard_wizard, "_show_quick_start_progress", lambda *_args: None)
|
||||
monkeypatch.setattr(onboard_wizard, "_select_with_back", lambda *a, **kw: "OpenRouter")
|
||||
monkeypatch.setattr(onboard_wizard, "_input_text", lambda *a, **kw: "sk-or-test")
|
||||
monkeypatch.setattr(onboard_wizard, "_select_with_back", lambda *a, **kw: label)
|
||||
monkeypatch.setattr(onboard_wizard, "_input_text", lambda *a, **kw: "test-key")
|
||||
|
||||
def fake_model_input(prompt, current, provider, *, config):
|
||||
model_prompts.append((prompt, current, provider))
|
||||
return "openai/gpt-4o-mini"
|
||||
return model
|
||||
|
||||
monkeypatch.setattr(onboard_wizard, "_input_model_with_autocomplete", fake_model_input)
|
||||
|
||||
assert onboard_wizard._configure_quick_start_provider(config) == "primary"
|
||||
assert onboard_wizard._configure_quick_start_provider(config) is True
|
||||
|
||||
assert model_prompts == [("Model ID", "", "openrouter")]
|
||||
assert config.providers.openrouter.api_key == "sk-or-test"
|
||||
assert config.providers.openrouter.api_base == (existing_base or "https://openrouter.ai/api/v1")
|
||||
assert config.model_presets["primary"].provider == "openrouter"
|
||||
assert config.model_presets["primary"].model == "openai/gpt-4o-mini"
|
||||
assert model_prompts == [("Model ID", "", provider)]
|
||||
assert getattr(config.providers, provider).api_key == "test-key"
|
||||
assert getattr(config.providers, provider).api_base == api_base
|
||||
assert config.model_presets["primary"].provider == provider
|
||||
assert config.model_presets["primary"].model == model
|
||||
|
||||
def test_quick_start_local_provider_skips_api_key(self, monkeypatch):
|
||||
config = Config()
|
||||
@@ -1307,7 +1299,7 @@ class TestMainMenuInteraction:
|
||||
lambda *a, **kw: "llama3.2",
|
||||
)
|
||||
|
||||
assert onboard_wizard._configure_quick_start_provider(config) == "primary"
|
||||
assert onboard_wizard._configure_quick_start_provider(config) is True
|
||||
|
||||
assert config.providers.ollama.api_key is None
|
||||
assert config.providers.ollama.api_base == "http://localhost:11434/v1"
|
||||
@@ -1326,7 +1318,7 @@ class TestMainMenuInteraction:
|
||||
lambda *a, **kw: "gpt-4o-mini",
|
||||
)
|
||||
|
||||
assert onboard_wizard._configure_quick_start_provider(config) == "primary"
|
||||
assert onboard_wizard._configure_quick_start_provider(config) is True
|
||||
|
||||
assert config.providers.openai.api_key == "sk-openai-test"
|
||||
assert config.providers.openai.api_base is None
|
||||
@@ -1353,7 +1345,7 @@ class TestMainMenuInteraction:
|
||||
lambda *a, **kw: "gpt-4o-mini",
|
||||
)
|
||||
|
||||
assert onboard_wizard._configure_quick_start_provider(config) == "primary"
|
||||
assert onboard_wizard._configure_quick_start_provider(config) is True
|
||||
|
||||
assert selected_providers == ["DeepSeek", "OpenAI"]
|
||||
assert config.providers.deepseek.api_key is None
|
||||
@@ -1362,7 +1354,6 @@ class TestMainMenuInteraction:
|
||||
|
||||
def test_quick_start_zhipu_coding_plan_uses_coding_base_url(self, monkeypatch):
|
||||
config = Config()
|
||||
config.providers.zhipu.api_base = "https://open.bigmodel.cn/api/paas/v4"
|
||||
choices = iter(["Zhipu AI", "Coding Plan"])
|
||||
|
||||
monkeypatch.setattr(onboard_wizard, "_show_quick_start_progress", lambda *_args: None)
|
||||
@@ -1374,7 +1365,7 @@ class TestMainMenuInteraction:
|
||||
lambda *a, **kw: "glm-4.6",
|
||||
)
|
||||
|
||||
assert onboard_wizard._configure_quick_start_provider(config) == "primary"
|
||||
assert onboard_wizard._configure_quick_start_provider(config) is True
|
||||
|
||||
assert config.providers.zhipu.api_key == "zhipu-key"
|
||||
assert config.providers.zhipu.api_base == "https://open.bigmodel.cn/api/coding/paas/v4"
|
||||
@@ -1394,7 +1385,7 @@ class TestMainMenuInteraction:
|
||||
lambda *a, **kw: "MiniMax-M2",
|
||||
)
|
||||
|
||||
assert onboard_wizard._configure_quick_start_provider(config) == "primary"
|
||||
assert onboard_wizard._configure_quick_start_provider(config) is True
|
||||
|
||||
assert config.providers.minimax.api_key == "minimax-key"
|
||||
assert config.providers.minimax.api_base == "https://api.minimaxi.com/v1"
|
||||
@@ -1414,7 +1405,7 @@ class TestMainMenuInteraction:
|
||||
lambda *a, **kw: "step-3.5-flash",
|
||||
)
|
||||
|
||||
assert onboard_wizard._configure_quick_start_provider(config) == "primary"
|
||||
assert onboard_wizard._configure_quick_start_provider(config) is True
|
||||
|
||||
assert config.providers.stepfun.api_key == "stepfun-key"
|
||||
assert config.providers.stepfun.api_base == "https://api.stepfun.ai/step_plan/v1"
|
||||
@@ -1434,7 +1425,7 @@ class TestMainMenuInteraction:
|
||||
lambda *a, **kw: "mimo-v2.5-pro",
|
||||
)
|
||||
|
||||
assert onboard_wizard._configure_quick_start_provider(config) == "primary"
|
||||
assert onboard_wizard._configure_quick_start_provider(config) is True
|
||||
|
||||
assert config.providers.xiaomi_mimo.api_key == "mimo-key"
|
||||
assert config.providers.xiaomi_mimo.api_base == "https://token-plan-sgp.xiaomimimo.com/v1"
|
||||
@@ -1458,107 +1449,13 @@ class TestMainMenuInteraction:
|
||||
lambda *a, **kw: "custom-model",
|
||||
)
|
||||
|
||||
assert onboard_wizard._configure_quick_start_provider(config) == "primary"
|
||||
assert onboard_wizard._configure_quick_start_provider(config) is True
|
||||
|
||||
assert config.providers.custom.api_key == "sk-custom-test"
|
||||
assert config.providers.custom.api_base == "https://api.example.test/v1"
|
||||
assert config.model_presets["primary"].provider == "custom"
|
||||
assert config.model_presets["primary"].model == "custom-model"
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"existing, cancel_at",
|
||||
[(False, None), (True, None), (True, "model"), (True, "review")],
|
||||
ids=["first-run", "existing-setup", "cancel-model", "cancel-review"],
|
||||
)
|
||||
def test_shengsuanyun_quick_start_saves_separate_connection(
|
||||
self, tmp_path, monkeypatch, prompt_input, existing, cancel_at,
|
||||
):
|
||||
from nanobot.cli.commands import app
|
||||
|
||||
path = tmp_path / "config.json"
|
||||
monkeypatch.setattr(loader, "_current_config_path", None)
|
||||
monkeypatch.setattr(instance_home, "_home_path", None)
|
||||
if existing:
|
||||
old = Config.model_validate({
|
||||
"agents": {"defaults": {"workspace": str(tmp_path / "workspace"), "modelPreset": "primary"}},
|
||||
"providers": {
|
||||
"custom": {"apiBase": "https://old.example/v1", "apiKey": "old-key"},
|
||||
"Custom_ShengSuanYun_Router": {"apiBase": "https://other.example/v1"},
|
||||
},
|
||||
"modelPresets": {
|
||||
"primary": {"model": "old-model", "provider": "custom"},
|
||||
"shengsuanyun": {"model": "other-model", "provider": "Custom_ShengSuanYun_Router"},
|
||||
},
|
||||
"channels": {"websocket": {"enabled": True, "tokenIssueSecret": "old-password"}},
|
||||
})
|
||||
save_config(old, path)
|
||||
before = path.read_bytes()
|
||||
|
||||
model_id = "deepseek/example-model"
|
||||
model_url = "https://router.shengsuanyun.com/api/v1/models"
|
||||
calls = []
|
||||
|
||||
def get(url, **kwargs):
|
||||
calls.append((url, kwargs["headers"]["Authorization"]))
|
||||
return httpx.Response(200, request=httpx.Request("GET", url), json={"data": [{"id": model_id}]})
|
||||
|
||||
keys = ["\r", "\x1b[A" * 3 + "\r", "router-test-key\r"]
|
||||
if cancel_at == "model":
|
||||
keys.extend(["\x1b", "\x1b[D"])
|
||||
else:
|
||||
keys.append(f"{model_id}\r")
|
||||
if not existing:
|
||||
keys.append("webui-test-password\r")
|
||||
if cancel_at:
|
||||
keys.append("\x1b[A\r")
|
||||
inputs = iter(keys)
|
||||
ask_prompt = onboard_wizard._ask_prompt
|
||||
pause = onboard_wizard._pause
|
||||
|
||||
def ask_with_input(prompt):
|
||||
prompt_input.send_text(next(inputs))
|
||||
return ask_prompt(prompt)
|
||||
|
||||
def review_with_input(message):
|
||||
prompt_input.send_text("\x03" if cancel_at == "review" else "\r")
|
||||
return pause(message)
|
||||
|
||||
monkeypatch.setattr(httpx, "get", get)
|
||||
monkeypatch.setattr(onboard_wizard, "_ask_prompt", ask_with_input)
|
||||
monkeypatch.setattr(onboard_wizard, "_pause", review_with_input)
|
||||
monkeypatch.setattr(
|
||||
onboard_wizard._get_questionary(), "confirm",
|
||||
lambda *args, **kwargs: SimpleNamespace(ask=lambda: True),
|
||||
)
|
||||
|
||||
result = CliRunner().invoke(app, ["--home", str(tmp_path), "onboard", "--wizard"])
|
||||
assert result.exit_code == 0, result.output
|
||||
assert "router-test-key" not in result.output
|
||||
assert calls == [(model_url, "Bearer router-test-key")]
|
||||
if cancel_at:
|
||||
assert "Configuration discarded" in result.output
|
||||
assert path.read_bytes() == before
|
||||
return
|
||||
saved = load_config(path)
|
||||
preset_name = "shengsuanyun-2" if existing else "shengsuanyun"
|
||||
route = resolve_provider_route(saved, preset=saved.resolve_preset(preset_name))
|
||||
assert route.model == model_id
|
||||
assert route.provider_name == ("custom-shengsuanyun-router-2" if existing else "custom-shengsuanyun-router")
|
||||
assert route.provider_config is not None
|
||||
assert route.provider_config.api_base == model_url.removesuffix("/models")
|
||||
assert route.model_api is not None and route.model_api.preferred_api == "chat_completions"
|
||||
if existing:
|
||||
assert saved.resolve_preset() == old.resolve_preset()
|
||||
assert saved.agents.defaults.model_preset == "primary"
|
||||
assert saved.channels.websocket == old.channels.websocket
|
||||
for key, provider in (old.providers.model_extra or {}).items():
|
||||
assert getattr(saved.providers, key) == provider
|
||||
assert saved.providers.custom == old.providers.custom
|
||||
assert saved.model_presets["shengsuanyun"] == old.model_presets["shengsuanyun"]
|
||||
else:
|
||||
assert saved.agents.defaults.model_preset == preset_name
|
||||
assert saved.channels.websocket["enabled"] is True
|
||||
|
||||
def test_quick_start_provider_without_default_base_url_prompts_for_base(self, monkeypatch):
|
||||
config = Config()
|
||||
text_answers = iter(["azure-key", "https://azure.example.test/openai"])
|
||||
@@ -1572,7 +1469,7 @@ class TestMainMenuInteraction:
|
||||
lambda *a, **kw: "deployment-name",
|
||||
)
|
||||
|
||||
assert onboard_wizard._configure_quick_start_provider(config) == "primary"
|
||||
assert onboard_wizard._configure_quick_start_provider(config) is True
|
||||
|
||||
assert config.providers.azure_openai.api_key == "azure-key"
|
||||
assert config.providers.azure_openai.api_base == "https://azure.example.test/openai"
|
||||
@@ -1686,7 +1583,6 @@ class TestMainMenuInteraction:
|
||||
|
||||
def test_quick_start_summary_calls_out_missing_api_key(self, monkeypatch):
|
||||
config = Config()
|
||||
config.channels.websocket = {"enabled": True}
|
||||
config.model_presets["primary"] = ModelPresetConfig(
|
||||
model="deepseek-v4-flash",
|
||||
provider="deepseek",
|
||||
@@ -1701,7 +1597,7 @@ class TestMainMenuInteraction:
|
||||
lambda rows, _title: captured.setdefault("rows", rows),
|
||||
)
|
||||
|
||||
onboard_wizard._show_quick_start_summary(config, "primary")
|
||||
onboard_wizard._show_quick_start_summary(config)
|
||||
|
||||
rows = dict(captured["rows"])
|
||||
assert rows["Status"] == "DeepSeek API key missing"
|
||||
|
||||
@@ -180,6 +180,37 @@ async def bind_transport():
|
||||
await client.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("model", "wire_model", "request_api", "path"), [
|
||||
("deepseek/deepseek-v4-flash", "deepseek/deepseek-v4-flash", None, "chat/completions"),
|
||||
("shengsuanyun/deepseek/deepseek-v4-flash", "deepseek/deepseek-v4-flash", None, "chat/completions"),
|
||||
("openai/gpt-5.4", "openai/gpt-5.4", "responses", "responses"),
|
||||
])
|
||||
async def test_shengsuanyun_sends_catalog_model_id_to_router(bind_transport, model, wire_model, request_api, path):
|
||||
preset = ModelPresetConfig(
|
||||
model=model, provider="shengsuanyun",
|
||||
api=ModelAPIConfig(supported_apis=(request_api,)) if request_api else None,
|
||||
)
|
||||
config = Config.model_validate({
|
||||
"providers": {"shengsuanyun": {"apiKey": "fixture"}},
|
||||
})
|
||||
requests = []
|
||||
|
||||
def handler(request):
|
||||
requests.append(request)
|
||||
return _answer(request)
|
||||
|
||||
provider = make_provider(config, preset=preset)
|
||||
await provider._ensure_client()
|
||||
bind_transport(provider, handler)
|
||||
reply = await provider.chat(messages=[{"role": "user", "content": "hello"}], model=model)
|
||||
|
||||
assert reply.content == "ok"
|
||||
request, = requests
|
||||
assert str(request.url) == f"https://router.shengsuanyun.com/api/v1/{path}"
|
||||
assert request.headers["authorization"] == "Bearer fixture"
|
||||
assert json.loads(request.content)["model"] == wire_model
|
||||
|
||||
|
||||
@pytest.mark.parametrize("preset_name", ["chat", "responses", "messages"])
|
||||
async def test_preset_overrides_isolate_requests_and_preserve_prompt_prefix(bind_transport, preset_name):
|
||||
config = _config()
|
||||
|
||||
@@ -17,7 +17,6 @@ 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 (
|
||||
@@ -2686,40 +2685,39 @@ def test_provider_models_payload_requires_gateway_key(
|
||||
assert payload["models"] == []
|
||||
|
||||
|
||||
def test_provider_models_payload_fetches_orcarouter_catalog(
|
||||
@pytest.mark.parametrize(("provider", "api_base", "models"), [
|
||||
("orcarouter", "https://api.orcarouter.ai/v1", ["orcarouter/auto", "anthropic/claude-sonnet-4.6"]),
|
||||
("shengsuanyun", "https://router.shengsuanyun.com/api/v1", ["deepseek/deepseek-v4-flash"]),
|
||||
])
|
||||
def test_provider_models_payload_fetches_router_catalog(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
provider: str,
|
||||
api_base: str,
|
||||
models: list[str],
|
||||
) -> None:
|
||||
config_path = tmp_path / "config.json"
|
||||
config = Config()
|
||||
config.providers.orcarouter.api_key = "sk-orca-test"
|
||||
getattr(config.providers, provider).api_key = "router-test-key"
|
||||
save_config(config, config_path)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
|
||||
def fake_get(url: str, **kwargs):
|
||||
assert url == "https://api.orcarouter.ai/v1/models"
|
||||
assert kwargs["headers"]["Authorization"] == "Bearer sk-orca-test"
|
||||
assert url == f"{api_base}/models"
|
||||
assert kwargs["headers"]["Authorization"] == "Bearer router-test-key"
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"data": [
|
||||
{"id": "orcarouter/auto", "owned_by": "orcarouter"},
|
||||
{"id": "anthropic/claude-sonnet-4.6", "owned_by": "anthropic"},
|
||||
]
|
||||
},
|
||||
json={"data": [{"id": model} for model in models]},
|
||||
request=httpx.Request("GET", url),
|
||||
)
|
||||
|
||||
monkeypatch.setattr("nanobot.webui.settings_api.httpx.get", fake_get)
|
||||
|
||||
payload = provider_models_payload({"provider": ["orcarouter"]})
|
||||
payload = provider_models_payload({"provider": [provider]})
|
||||
|
||||
assert payload["status"] == "available"
|
||||
assert payload["catalog_kind"] == "catalog"
|
||||
assert [model["id"] for model in payload["models"]] == [
|
||||
"orcarouter/auto",
|
||||
"anthropic/claude-sonnet-4.6",
|
||||
]
|
||||
assert [model["id"] for model in payload["models"]] == models
|
||||
|
||||
|
||||
def test_model_catalog_kind_uses_provider_spec_metadata() -> None:
|
||||
@@ -2886,50 +2884,6 @@ def test_custom_connection_api_create_edit_and_preset_ceiling(tmp_path, monkeypa
|
||||
assert load_config(config_path).providers.model_extra[key].api is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("legacy_key", ["shengsuanyun_router", "shengsuanyun-router"])
|
||||
def test_setup_template_keeps_existing_provider_with_matching_name(tmp_path, monkeypatch, legacy_key):
|
||||
config_path = tmp_path / "config.json"
|
||||
legacy_config = {
|
||||
"providers": {legacy_key: {
|
||||
"apiBase": "https://legacy.example/api",
|
||||
"apiKey": "legacy-key",
|
||||
"api": {"supportedApis": ["anthropic_messages"]},
|
||||
}},
|
||||
"agents": {"defaults": {"model": "anthropic/old-model", "provider": legacy_key}},
|
||||
}
|
||||
config_path.write_text(json.dumps(legacy_config), encoding="utf-8")
|
||||
before = load_config(config_path)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
|
||||
settings = settings_payload()
|
||||
template = next(item for item in settings["provider_setup_templates"] if item["id"] == "shengsuanyun")
|
||||
assert template["label"] == "ShengSuanYun Router"
|
||||
assert "胜算云" in template["search_aliases"].split()
|
||||
assert template["suggested_name"] == "ShengSuanYun Router 2"
|
||||
assert any(provider["name"] == legacy_key for provider in settings["providers"])
|
||||
payload = create_provider_settings({
|
||||
"name": [template["suggested_name"]],
|
||||
"apiBase": [template["api_base"]],
|
||||
"apiKey": ["new-key"],
|
||||
"api": [json.dumps(template["api"])],
|
||||
})
|
||||
key = payload["created_provider"]
|
||||
saved = load_config(config_path)
|
||||
assert saved.get_provider_name() == legacy_key
|
||||
assert saved.get_provider() == before.get_provider()
|
||||
assert resolve_provider_route(saved, preset=saved.resolve_preset()).backend == "anthropic"
|
||||
|
||||
def fake_get(url: str, **kwargs):
|
||||
assert url == "https://router.shengsuanyun.com/api/v1/models"
|
||||
assert kwargs["headers"]["Authorization"] == "Bearer new-key"
|
||||
return httpx.Response(200, json={"data": [{"id": "deepseek/deepseek-v4-flash"}]},
|
||||
request=httpx.Request("GET", url))
|
||||
|
||||
monkeypatch.setattr("nanobot.webui.settings_api.httpx.get", fake_get)
|
||||
catalog = provider_models_payload({"provider": [key]})
|
||||
assert catalog["models"][0]["id"] == "deepseek/deepseek-v4-flash"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("api", [
|
||||
{"supportedApis": []},
|
||||
{"supportedApis": ["responses"], "preferredApi": "anthropic_messages"},
|
||||
|
||||
@@ -160,7 +160,6 @@ def test_model_domain_owns_dto_and_config_updates() -> None:
|
||||
"model_api_resolution_supported",
|
||||
"provider_api_configuration_supported",
|
||||
"model_request_overrides_supported",
|
||||
"provider_setup_templates",
|
||||
"providers",
|
||||
}
|
||||
assert payload["agent"]["model"] == "openai/gpt-5.4"
|
||||
|
||||
@@ -26,6 +26,7 @@ const PROVIDER_SEARCH_ALIASES: Record<string, string> = {
|
||||
volcengine_coding_plan: "火山引擎 豆包 doubao",
|
||||
minimax: "海螺 稀宇",
|
||||
minimax_anthropic: "海螺 稀宇",
|
||||
shengsuanyun: "胜算云 勝算雲",
|
||||
siliconflow: "硅基流动 矽基流動 硅基流動",
|
||||
stepfun: "阶跃星辰 階躍星辰",
|
||||
xiaomi_mimo: "小米 mimo",
|
||||
@@ -34,12 +35,8 @@ const PROVIDER_SEARCH_ALIASES: Record<string, string> = {
|
||||
ant_ling: "蚂蚁 螞蟻 百灵 百靈",
|
||||
};
|
||||
|
||||
type ProviderSearchOption = Pick<
|
||||
SettingsPayload["providers"][number], "name" | "label" | "auth_type" | "model_catalog"
|
||||
> & { searchAliases?: string; icon?: string };
|
||||
|
||||
export function ProviderSearchList({ providers, showBrandLogos, query, onQueryChange, onSelect, onCustom, onClose }: {
|
||||
providers: ProviderSearchOption[];
|
||||
providers: SettingsPayload["providers"];
|
||||
showBrandLogos: boolean;
|
||||
query: string;
|
||||
onQueryChange: (query: string) => void;
|
||||
@@ -58,7 +55,7 @@ export function ProviderSearchList({ providers, showBrandLogos, query, onQueryCh
|
||||
const normalize = (value: string) => value.toLocaleLowerCase().replace(/[\s_.-]+/g, "");
|
||||
const normalizedQuery = normalize(query);
|
||||
return providers.filter((provider) => normalize(
|
||||
`${provider.name} ${provider.label} ${provider.searchAliases ?? PROVIDER_SEARCH_ALIASES[provider.name] ?? ""}`,
|
||||
`${provider.name} ${provider.label} ${PROVIDER_SEARCH_ALIASES[provider.name] ?? ""}`,
|
||||
).includes(normalizedQuery));
|
||||
}, [providers, query]);
|
||||
const groups = useMemo(() => PROVIDER_GROUPS.map((group) => ({
|
||||
@@ -94,7 +91,7 @@ export function ProviderSearchList({ providers, showBrandLogos, query, onQueryCh
|
||||
{group.providers.map((provider) => <ComboboxOption key={provider.name} {...getOptionProps(provider.name)}
|
||||
aria-label={provider.label}
|
||||
className="min-h-11 min-w-0 gap-2 rounded-xl px-2 py-2 text-[13px] font-normal sm:gap-3 sm:px-3 sm:text-sm">
|
||||
<ProviderIcon provider={provider.icon ?? provider.name} showBrandLogos={showBrandLogos} compact />
|
||||
<ProviderIcon provider={provider.name} showBrandLogos={showBrandLogos} compact />
|
||||
<TruncatedTextTooltip text={provider.label} className="flex-1" />
|
||||
</ComboboxOption>)}
|
||||
</div>
|
||||
@@ -115,7 +112,7 @@ export function ProviderSearchList({ providers, showBrandLogos, query, onQueryCh
|
||||
</>;
|
||||
}
|
||||
|
||||
function providerGroup(provider: ProviderSearchOption): typeof PROVIDER_GROUPS[number]["id"] {
|
||||
function providerGroup(provider: SettingsPayload["providers"][number]): typeof PROVIDER_GROUPS[number]["id"] {
|
||||
if (provider.auth_type === "oauth") return "oauth";
|
||||
return provider.model_catalog === "local" ? "local" : "api_key";
|
||||
}
|
||||
|
||||
@@ -63,7 +63,6 @@ import type {
|
||||
NanobotFeaturesPayload,
|
||||
ModelAPIConfig,
|
||||
ProviderOAuthAuthorizationRequired,
|
||||
ProviderSetupTemplate,
|
||||
SettingsPayload,
|
||||
} from "@/lib/types";
|
||||
|
||||
@@ -526,8 +525,7 @@ export type ProviderSettingsEntry =
|
||||
| { kind: "edit"; provider: string };
|
||||
|
||||
type ProviderSettingsView =
|
||||
| { kind: "list" | "picker" }
|
||||
| { kind: "custom"; requiresApiKey: boolean }
|
||||
| { kind: "list" | "picker" | "custom" }
|
||||
| { kind: "provider"; name: string; adding: boolean };
|
||||
|
||||
export function ProvidersSettings({
|
||||
@@ -593,22 +591,13 @@ export function ProvidersSettings({
|
||||
emptyCustomProviderDraft,
|
||||
);
|
||||
const configuredProviders = settings.providers.filter((provider) => provider.configured);
|
||||
const { providerOptions, templatesByOption } = useMemo(() => {
|
||||
const providerOptions = settings.providers.filter((provider) => !provider.configured && provider.name !== "custom");
|
||||
const occupied = new Set(providerOptions.map((provider) => provider.name));
|
||||
const entries = (settings.provider_setup_templates ?? []).map((template) => {
|
||||
const icon = `template:${template.id}`;
|
||||
// Picker IDs must not shadow saved connection IDs.
|
||||
let name = icon;
|
||||
while (occupied.has(name)) name += ":";
|
||||
occupied.add(name);
|
||||
return { template, option: { name, label: template.label, icon, searchAliases: template.search_aliases } };
|
||||
});
|
||||
return {
|
||||
providerOptions: [...providerOptions, ...entries.map(({ option }) => option)],
|
||||
templatesByOption: new Map(entries.map(({ option, template }) => [option.name, template])),
|
||||
};
|
||||
}, [settings.providers, settings.provider_setup_templates]);
|
||||
const unconfiguredProviders = useMemo(
|
||||
() =>
|
||||
settings.providers.filter(
|
||||
(provider) => !provider.configured && provider.name !== "custom",
|
||||
),
|
||||
[settings.providers],
|
||||
);
|
||||
const customProviderSaving = providerSaving === CUSTOM_PROVIDER_CREATION_KEY;
|
||||
const selectedProvider = view.kind === "provider"
|
||||
? settings.providers.find((provider) => provider.name === view.name)
|
||||
@@ -650,16 +639,10 @@ export function ProvidersSettings({
|
||||
returnToOrigin();
|
||||
}
|
||||
};
|
||||
const beginCustomProviderCreation = (template?: ProviderSetupTemplate) => {
|
||||
const draft = emptyCustomProviderDraft();
|
||||
if (template) {
|
||||
draft.name = template.suggested_name;
|
||||
draft.apiBase = template.api_base;
|
||||
draft.api = template.api;
|
||||
}
|
||||
setCustomProviderDraft(draft);
|
||||
const beginCustomProviderCreation = () => {
|
||||
setCustomProviderDraft(emptyCustomProviderDraft());
|
||||
setCustomProviderKeyVisible(false);
|
||||
setView({ kind: "custom", requiresApiKey: Boolean(template) });
|
||||
setView({ kind: "custom" });
|
||||
};
|
||||
const saveCustomProvider = async () => {
|
||||
if (customProviderSaving) return;
|
||||
@@ -1085,8 +1068,7 @@ export function ProvidersSettings({
|
||||
disabled={
|
||||
customProviderSaving ||
|
||||
!customProviderDraft.name.trim() ||
|
||||
!customProviderDraft.apiBase.trim() ||
|
||||
(view.requiresApiKey && !customProviderDraft.apiKey.trim())
|
||||
!customProviderDraft.apiBase.trim()
|
||||
}
|
||||
className="rounded-full"
|
||||
>
|
||||
@@ -1146,15 +1128,10 @@ export function ProvidersSettings({
|
||||
</div>
|
||||
</div>
|
||||
) : view.kind === "picker" ? (
|
||||
<ProviderSearchList providers={providerOptions} showBrandLogos={showBrandLogos}
|
||||
<ProviderSearchList providers={unconfiguredProviders} showBrandLogos={showBrandLogos}
|
||||
query={providerSearch} onQueryChange={setProviderSearch}
|
||||
onSelect={(name) => {
|
||||
const template = templatesByOption.get(name);
|
||||
if (template) beginCustomProviderCreation(template);
|
||||
else editProvider(name, true);
|
||||
}}
|
||||
onCustom={() => beginCustomProviderCreation()}
|
||||
onClose={entry.kind === "manage" ? goBack : closePanel} />
|
||||
onSelect={(name) => editProvider(name, true)}
|
||||
onCustom={beginCustomProviderCreation} onClose={entry.kind === "manage" ? goBack : closePanel} />
|
||||
) : (
|
||||
<div className="min-h-0 space-y-4 overflow-y-auto overscroll-contain px-5 pb-5">
|
||||
{view.kind === "custom" ? customProviderForm : selectedProvider ? renderProviderForm(selectedProvider) : null}
|
||||
|
||||
@@ -227,10 +227,10 @@ const PROVIDER_BRANDS: Record<string, ProviderBrand> = {
|
||||
color: "#3050FF",
|
||||
initials: "SX",
|
||||
},
|
||||
siliconflow: brand("siliconflow.cn", "#111827", "SF"),
|
||||
"template:shengsuanyun": { ...brand("shengsuanyun.com", "#5742EE", "SSY", [
|
||||
shengsuanyun: { ...brand("shengsuanyun.com", "#5742EE", "SSY", [
|
||||
"https://www.shengsuanyun.com/svg/logo-C_e87Vaj.svg",
|
||||
]), logoLayout: "tile" },
|
||||
siliconflow: brand("siliconflow.cn", "#111827", "SF"),
|
||||
skywork: brand("skywork.ai", "#5B5BF6", "SW"),
|
||||
stepfun: brand("stepfun.com", "#2F6BFF", "SF", [
|
||||
"https://www.stepfun.com/step_favicon.svg",
|
||||
|
||||
@@ -734,15 +734,6 @@ export interface SandboxCheck {
|
||||
supported_backend: "bwrap" | "seatbelt" | null;
|
||||
}
|
||||
|
||||
export interface ProviderSetupTemplate {
|
||||
id: string;
|
||||
label: string;
|
||||
suggested_name: string;
|
||||
search_aliases: string;
|
||||
api_base: string;
|
||||
api: ModelAPIConfig;
|
||||
}
|
||||
|
||||
export interface SettingsPayload {
|
||||
runtime_config?: Record<string, RuntimeConfigValue>;
|
||||
surface?: RuntimeSurface;
|
||||
@@ -798,7 +789,6 @@ export interface SettingsPayload {
|
||||
model_request_overrides_supported?: boolean;
|
||||
created_model_preset?: string;
|
||||
created_provider?: string;
|
||||
provider_setup_templates?: ProviderSetupTemplate[];
|
||||
providers: Array<{
|
||||
name: string;
|
||||
label: string;
|
||||
|
||||
@@ -48,7 +48,7 @@ describe("settings provider icons", () => {
|
||||
|
||||
it.each([
|
||||
"aihubmix", "bedrock", "exa", "groq", "lm_studio", "minimax", "minimax_anthropic",
|
||||
"modelscope", "moonshot", "olostep", "template:shengsuanyun", "tavily", "xiaomi_mimo", "zhipu",
|
||||
"modelscope", "moonshot", "olostep", "shengsuanyun", "tavily", "xiaomi_mimo", "zhipu",
|
||||
])(
|
||||
"does not double-frame %s's primary tile, but preserves unknown fallback assets",
|
||||
(provider) => {
|
||||
|
||||
@@ -21,54 +21,6 @@ async function chooseProviderToConfigure(label: string) {
|
||||
describe("Settings providers", () => {
|
||||
installSettingsViewTestHooks();
|
||||
|
||||
it("sets up ShengSuanYun as a custom connection without updating an existing provider", async () => {
|
||||
const user = userEvent.setup();
|
||||
const payload = settingsPayload();
|
||||
const existing = { name: "shengsuanyun_router", label: "ShengSuanYun Router", configured: true };
|
||||
const unconfigured = { name: "template:shengsuanyun", label: "Existing custom connection", configured: false };
|
||||
payload.providers = [existing, unconfigured];
|
||||
payload.provider_api_configuration_supported = true;
|
||||
payload.provider_setup_templates = [{
|
||||
id: "shengsuanyun",
|
||||
label: "ShengSuanYun Router",
|
||||
suggested_name: "ShengSuanYun Router 2",
|
||||
search_aliases: "胜算云 勝算雲",
|
||||
api_base: "https://router.shengsuanyun.com/api/v1",
|
||||
api: { supported_apis: ["chat_completions", "responses"], preferred_api: "chat_completions" },
|
||||
}];
|
||||
requestMutationMock.mockResolvedValueOnce({
|
||||
...payload,
|
||||
created_provider: "custom-shengsuanyun-router-2",
|
||||
providers: [existing, unconfigured, { name: "custom-shengsuanyun-router-2", label: "ShengSuanYun Router 2", configured: true, is_custom: true }],
|
||||
});
|
||||
renderProviderManager({ initialSection: "models", initialSettings: payload });
|
||||
await user.click(screen.getByRole("button", { name: "Add provider" }));
|
||||
await user.click(screen.getByRole("option", { name: unconfigured.label }));
|
||||
const existingForm = screen.getByRole("dialog", { name: unconfigured.label });
|
||||
await user.click(within(existingForm).getByRole("button", { name: "Back to providers" }));
|
||||
await user.type(screen.getByRole("combobox", { name: "Search providers" }), "胜算云");
|
||||
await user.keyboard("{ArrowDown}{Enter}");
|
||||
const form = screen.getByRole("dialog", { name: "Custom" });
|
||||
expect(within(form).getByPlaceholderText("My model provider")).toHaveValue("ShengSuanYun Router 2");
|
||||
expect(within(form).getByLabelText("API URL")).toHaveValue("https://router.shengsuanyun.com/api/v1");
|
||||
expect(requestMutationMock).not.toHaveBeenCalled();
|
||||
const save = within(form).getByRole("button", { name: "Add provider" });
|
||||
expect(save).toBeDisabled();
|
||||
await user.type(within(form).getByPlaceholderText("Enter API key"), "test-key");
|
||||
await user.click(save);
|
||||
expect(requestMutationMock).toHaveBeenCalledTimes(1);
|
||||
const [action, values] = requestMutationMock.mock.calls[0];
|
||||
expect(action).toBe("settings.provider.create");
|
||||
expect(values).toMatchObject({
|
||||
name: "ShengSuanYun Router 2",
|
||||
apiKey: "test-key",
|
||||
apiBase: "https://router.shengsuanyun.com/api/v1",
|
||||
api: { supported_apis: ["chat_completions", "responses"], preferred_api: "chat_completions" },
|
||||
});
|
||||
expect(await screen.findByRole("button", { name: "ShengSuanYun Router 2" })).toBeVisible();
|
||||
expect(await screen.findByRole("button", { name: "ShengSuanYun Router" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("manages providers unused by presets and returns focus through the manager", async () => {
|
||||
const user = userEvent.setup();
|
||||
const payload = settingsPayload();
|
||||
|
||||
Reference in new issue
Block a user