Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(providers): preserve DeepSeek Flash proxy routing
chengyongruf49fe0ef66b3
diff --git a/docs/development.md b/docs/development.mdindex 62c2f9da6..b10779930 100644--- a/docs/development.md+++ b/docs/development.md@@ -13,6 +13,7 @@ ProviderSpec(name="myprovider",keywords=("myprovider", "mymodel"),env_key="MYPROVIDER_API_KEY",+ request_apis=("chat_completions", "responses"),display_name="My Provider",default_api_base="https://api.myprovider.com/v1",)@@ -28,6 +29,8 @@ class ProvidersConfig(BaseModel):Environment variables, config matching, provider status, and WebUI credential display derive from those two entries.+Every `ProviderSpec` must declare `request_apis`. This lists request formats implemented by the adapter; endpoint and model support are configured separately through connection and preset API declarations. Use `anthropic_messages` for native Anthropic adapters, `bedrock_converse` for Bedrock, and `transcription` for transcription-only providers.+Useful `ProviderSpec` options:| Field | Description |@@ -40,8 +43,29 @@ Useful `ProviderSpec` options:| `detect_by_base_keyword` | Match configured gateways by API base URL. || `strip_model_prefix` | Strip `provider/` before sending the model to the upstream API. || `supports_max_completion_tokens` | Use `max_completion_tokens` instead of `max_tokens`. |+| `responses` | `ResponsesCapabilities` with automatic model rules, reasoning replay, and fallback policy. || `is_transcription_only` | Provider has credentials but cannot serve chat completions. |+### Python API migration++Provider integrations must supply `ProviderSpec.request_apis`. Replace the former `responses_models` argument with `responses=ResponsesCapabilities(models=(...))`. Use `models` for rules shared by an endpoint and its proxies. For a rule tied to a specific endpoint, use `endpoint_models`:++```python+ResponsesCapabilities(+ endpoint_models=(("https://api.myprovider.com/v1", ("mymodel",)),),+)+```++Endpoint rules compare the URL origin and path, treating an optional trailing `/v1` as equivalent. Explicit preset API declarations override automatic rules.++Replace `OpenAICompatProvider(api_type=...)` with `OpenAICompatProvider(model_api=...)`. Omitting `model_api` preserves automatic selection. To require Responses, pass:++```python+ModelAPICapabilities(supported_apis=("responses",), preferred_api="responses")+```++These types are defined in `nanobot.providers.registry`. The temporary `apiType` configuration migration applies to JSON configuration and Settings inputs; it does not preserve the old Python constructor arguments.+## Adding a Transcription ProviderTranscription is intentionally split into two layers:@@ -68,6 +92,7 @@ ProviderSpec(name="my_stt",keywords=("my_stt",),env_key="MY_STT_API_KEY",+ request_apis=("transcription",),display_name="My STT",default_api_base="https://api.example.com/v1",is_transcription_only=True,diff --git a/docs/providers.md b/docs/providers.mdindex b4a460e15..26ebc433d 100644--- a/docs/providers.md+++ b/docs/providers.md@@ -357,6 +357,8 @@ Use [preset API declarations](./configuration.md#preset-request-api) to choose CDeepSeek's `deepseek-v4-flash`, `deepseek-v4-pro`, and `deepseek-v4-flash-vision-exp` automatically use its native Responses API. Its native `web_search` tool is enabled by default and shows its lifecycle in WebUI chat activity; set `providers.deepseek.extraBody.tools` to `[]` to disable it. OpenCode Go's `muse-spark-1.2-contributor` and `muse-spark-1.3-contributor` also use Responses by default.+The `deepseek-flash` alias uses Responses automatically at `https://api.deepseek.com`, including the `/v1` form. With a different `providers.deepseek.apiBase`, Auto uses Chat Completions for this alias. Select Responses in the preset if the proxy supports it. The V4 model names listed above use Responses with either endpoint configuration. Explicitly enabling native web search for this alias also selects Responses.+### Custom OpenAI-Compatible EndpointThe `custom` provider fits one OpenAI-compatible endpoint that is not represented by a named provider.diff --git a/nanobot/providers/registry.py b/nanobot/providers/registry.pyindex 1e1c23b01..a0f989df0 100644--- a/nanobot/providers/registry.py+++ b/nanobot/providers/registry.py@@ -14,6 +14,7 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom typing import Any, Literal, cast+from urllib.parse import urlsplitfrom pydantic.alias_generators import to_snake@@ -31,6 +32,18 @@ def is_direct_openai_base(api_base: str | None) -> bool:return "api.openai.com" in normalized and "openrouter" not in normalized+def _api_base_identity(api_base: str) -> tuple[str, str | None, int | None, str]:+ """Normalize an endpoint's origin and optional OpenAI-compatible /v1 suffix."""+ parsed = urlsplit(api_base.strip())+ port = parsed.port+ return (+ parsed.scheme,+ parsed.hostname,+ port if port is not None else {"http": 80, "https": 443}.get(parsed.scheme),+ parsed.path.rstrip("/").removesuffix("/v1"),+ )++def is_hosted_web_search_type(value: object) -> bool:return isinstance(value, str) and (value == "web_search" or value.startswith("web_search_")@@ -82,6 +95,8 @@ class ResponsesCapabilities:``reasoning_replay`` selects whether multi-turn reasoning is retained asencrypted server content, plaintext local history, or not requested.+ ``endpoint_models`` limits automatic model rules to named API bases;+ ``models`` applies those rules regardless of the configured endpoint."""models: tuple[str, ...] = ()@@ -91,22 +106,30 @@ class ResponsesCapabilities:reasoning_replay: Literal["none", "encrypted", "plaintext"] = "none"supports_native_compaction: bool = Falseallows_chat_fallback: bool = True+ endpoint_models: tuple[tuple[str, tuple[str, ...]], ...] = ()- def matches_model(self, model: str) -> bool:- """Return whether *model* is explicitly routed through Responses."""+ def matches_model(self, model: str, *, api_base: str | None = None) -> bool:+ """Match curated models, restricting endpoint defaults when a base is supplied."""model_name = model.lower()wire_name = model_name.rsplit("/", 1)[-1]+ supported_models = self.models + tuple(+ model_id+ for base, models in self.endpoint_models+ if api_base is None or _api_base_identity(api_base) == _api_base_identity(base)+ for model_id in models+ )return any(model_name == supported.lower()or model_name.endswith(f"/{supported.lower()}")- for supported in self.models+ for supported in supported_models) or any(wire_name.startswith(prefix.lower()) for prefix in self.model_prefixes)def model_api(self, model: str, reasoning_effort: str | None = None,+ *, api_base: str | None = None,) -> ModelAPICapabilities:"""Resolve the provider's curated API defaults for one model."""- if not self.matches_model(model) and not (+ if not self.matches_model(model, api_base=api_base) and not (self.route_reasoning and reasoning_effort and reasoning_effort.lower() != "none"):return ModelAPICapabilities()@@ -253,13 +276,17 @@ class ProviderSpec:if capabilities is None:return ModelAPICapabilities()model_name = self.request_model_name(model)- if hosted_web_search_enabled(extra_body or {}, self.responses_default_tools) and (- capabilities.route_reasoning or capabilities.matches_model(model_name)+ body = extra_body or {}+ effective_base = api_base or self.default_api_base or None+ # Explicit hosted tools require Responses; defaults follow the endpoint's model rules.+ search_model_base = None if hosted_web_search_enabled(body) else effective_base+ if hosted_web_search_enabled(body, self.responses_default_tools) and (+ capabilities.route_reasoning or capabilities.matches_model(model_name, api_base=search_model_base)):return ModelAPICapabilities(("responses",), "responses")if capabilities.requires_direct_openai_base and not is_direct_openai_base(api_base):return ModelAPICapabilities()- return capabilities.model_api(model_name, reasoning_effort)+ return capabilities.model_api(model_name, reasoning_effort, api_base=effective_base)@propertydef model_api_configurable(self) -> bool:@@ -710,11 +737,11 @@ PROVIDERS: tuple[ProviderSpec, ...] = (thinking_style="thinking_type",responses=ResponsesCapabilities(models=(- "deepseek-flash","deepseek-v4-flash","deepseek-v4-pro","deepseek-v4-flash-vision-exp",),+ endpoint_models=(("https://api.deepseek.com", ("deepseek-flash",)),),reasoning_replay="plaintext",),responses_default_tools=("web_search",),diff --git a/tests/providers/test_model_api_presets.py b/tests/providers/test_model_api_presets.pyindex a978fb286..dd56fe8f0 100644--- a/tests/providers/test_model_api_presets.py+++ b/tests/providers/test_model_api_presets.py@@ -92,13 +92,13 @@ def _answer(request: httpx.Request) -> httpx.Response:async def bind_transport():clients = []- def bind(provider, handler):+ def bind(provider, handler, *, api_base=None):original = provider._clientif original is not None:clients.append(original)client_type = AsyncAnthropic if isinstance(provider, AnthropicProvider) else AsyncOpenAIclient = client_type(- api_key="fixture", base_url=str(original.base_url) if original else "https://tenant.test/v1",+ api_key="fixture", base_url=api_base or (str(original.base_url) if original else "https://tenant.test/v1"),default_headers=original.default_headers if original else None,default_query=original.default_query if original else None,max_retries=0,@@ -146,6 +146,81 @@ async def test_automatic_preview_matches_actual_request(assert paths == ["/v1/responses" if api == "responses" else "/v1/chat/completions"][email protected]("stream", [False, True])[email protected](("model", "api_base", "api"), [+ ("deepseek-flash", "https://chat-proxy.test/v1", "chat_completions"),+ ("deepseek/deepseek-flash", "https://chat-proxy.test/v1", "chat_completions"),+ ("deepseek-flash", "https://api.deepseek.com", "responses"),+ ("deepseek-flash", "https://api.deepseek.com/v1/", "responses"),+ ("deepseek-v4-flash", "https://responses-proxy.test/v1", "responses"),+])+async def test_deepseek_automatic_api_preserves_endpoint_routing(+ bind_transport, tmp_path, stream, model, api_base, api,+):+ from nanobot.config.loader import load_config++ config_path = tmp_path / "config.json"+ config_path.write_text(json.dumps({+ "providers": {"deepseek": {"apiBase": api_base, "apiKey": "fixture"}},+ "modelPresets": {"deepseek": {"provider": "deepseek", "model": model}},+ "agents": {"defaults": {"modelPreset": "deepseek"}},+ }), encoding="utf-8")+ config = load_config(config_path)+ request_path = "responses" if api == "responses" else "chat/completions"+ expected_path = f"{httpx.URL(api_base).path.rstrip('/')}/{request_path}"+ requests = []++ def handler(request):+ requests.append(request)+ if request.url.path != expected_path:+ return httpx.Response(404, json={"error": {"message": "Endpoint not supported"}})+ return _answer(request)++ provider = bind_transport(make_provider(config), handler, api_base=api_base)+ invoke = provider.chat_stream if stream else provider.chat+ result = await invoke([{"role": "user", "content": "hello"}])+ assert result.content == "ok"+ assert [request.url.path for request in requests] == [expected_path]+ assert resolve_automatic_model_api(config, preset=config.resolve_preset()) == ("deepseek", api)+ body = json.loads(requests[0].content)+ assert body.get("tools", []) == ([{"type": "web_search"}] if api == "responses" else [])++[email protected]("stream", [False, True])[email protected](("api", "extra_body", "response_supported"), [+ ({"supportedApis": ["responses"]}, {}, True),+ (None, {"tools": [{"type": "web_search"}]}, True),+ ({"supportedApis": ["responses", "chat_completions"]}, {"tools": []}, False),+])+async def test_deepseek_proxy_accepts_explicit_responses_and_chat_fallback(+ bind_transport, stream, api, extra_body, response_supported,+):+ config = Config.model_validate({+ "providers": {"deepseek": {+ "apiBase": "https://tenant.test/v1", "apiKey": "fixture", "extraBody": extra_body,+ }},+ })+ preset = ModelPresetConfig.model_validate({"provider": "deepseek", "model": "deepseek-flash", "api": api})+ requests = []++ def handler(request):+ requests.append(request)+ if not response_supported and request.url.path.endswith("/responses"):+ return httpx.Response(404, json={"error": {"message": "Responses endpoint not supported"}})+ return _answer(request)++ provider = bind_transport(make_provider(config, preset=preset), handler)+ invoke = provider.chat_stream if stream else provider.chat+ result = await invoke([{"role": "user", "content": "hello"}])+ assert result.content == "ok"+ expected_paths = ["/v1/responses"] if response_supported else ["/v1/responses", "/v1/chat/completions"]+ assert [request.url.path for request in requests] == expected_paths+ expected_tools = [{"type": "web_search"}] if response_supported else []+ assert json.loads(requests[0].content).get("tools", []) == expected_tools+ if api is None:+ assert resolve_automatic_model_api(config, preset=preset) == ("deepseek", "responses")++@pytest.mark.parametrize("stream", [False, True])async def test_presets_route_same_gateway_independently(bind_transport, stream):config = _config()