feat(models): declare request APIs per preset
Bind API support and preference to the preset's provider and model. Carry the API declaration through factory selection, fallback chains, hot reload and WebUI persistence. Use Copilot endpoint metadata for automatic routing and keep reasoning replay and compaction defaults in provider capability profiles. Consolidate Responses follow-ups from #5906, #5935, #6020, #6051 and #5834; acknowledge equivalent contributions in #6105 and #5863. Co-authored-by: Parman Mohammadalizadeh <prmma23@gmail.com> Co-authored-by: Lanre Shittu <136805224+Shizoqua@users.noreply.github.com> Co-authored-by: kkkhoo <128304090+kkkhoo@users.noreply.github.com> Co-authored-by: pei711 <199601925+pei711@users.noreply.github.com> Co-authored-by: Steven Huang <134844631+remote-controlled-man@users.noreply.github.com> Co-authored-by: Louis Yue <179701714+selfucker@users.noreply.github.com> Co-authored-by: iuiuiu <92971770+iuiu-py@users.noreply.github.com>
This commit is contained in:
1 parent
3c866d63ac
commit
b5808e47de
23 files changed
+738
-63
No files matched your search
@@ -0,0 +1,196 @@
|
||||
"""Preset API declarations control requests through OpenAI-compatible gateways."""
|
||||
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from openai import AsyncOpenAI
|
||||
from pydantic import ValidationError
|
||||
|
||||
from nanobot.config.schema import Config, InlineFallbackConfig, ModelAPIConfig
|
||||
from nanobot.providers.factory import make_provider, provider_signature
|
||||
from nanobot.providers.openai_compat_provider import _RESPONSES_FAILURE_THRESHOLD
|
||||
|
||||
|
||||
def _config() -> Config:
|
||||
return Config.model_validate({
|
||||
"agents": {"defaults": {"modelPreset": "responses"}},
|
||||
"providers": {"tenant": {"apiBase": "https://tenant.test/v1", "apiKey": "fixture"}},
|
||||
"modelPresets": {
|
||||
"responses": {
|
||||
"provider": "tenant", "model": "gpt-6-luna", "reasoningEffort": "high",
|
||||
"api": {"supportedApis": ["responses"], "preferredApi": "responses"},
|
||||
},
|
||||
"chat": {
|
||||
"provider": "tenant", "model": "gpt-6-luna",
|
||||
"api": {"supportedApis": ["chat_completions"]},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
def _answer(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path.endswith("/responses"):
|
||||
response = {
|
||||
"id": "resp_fixture", "object": "response", "status": "completed",
|
||||
"output": [{
|
||||
"id": "msg_fixture", "type": "message", "role": "assistant", "status": "completed",
|
||||
"content": [{"type": "output_text", "text": "ok", "annotations": []}],
|
||||
}],
|
||||
}
|
||||
events = [
|
||||
{"type": "response.output_text.delta", "delta": "ok"},
|
||||
{"type": "response.completed", "response": response},
|
||||
]
|
||||
else:
|
||||
response = {"id": "chat_fixture", "choices": [{
|
||||
"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop",
|
||||
}]}
|
||||
events = [{"choices": [{"index": 0, "delta": {"content": "ok"}, "finish_reason": "stop"}]}]
|
||||
if not json.loads(request.content).get("stream"):
|
||||
return httpx.Response(200, json=response)
|
||||
return httpx.Response(
|
||||
200, headers={"content-type": "text/event-stream"},
|
||||
content="".join(f"data: {json.dumps(event)}\n\n" for event in events),
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def bind_transport():
|
||||
clients = []
|
||||
|
||||
def bind(provider, handler):
|
||||
original = provider._client
|
||||
if original is not None:
|
||||
clients.append(original)
|
||||
client = AsyncOpenAI(
|
||||
api_key="fixture", base_url="https://tenant.test/v1", max_retries=0,
|
||||
http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)),
|
||||
)
|
||||
clients.append(client)
|
||||
provider._client = client
|
||||
provider._CHAT_RETRY_DELAYS = ()
|
||||
return provider
|
||||
|
||||
yield bind
|
||||
for client in clients:
|
||||
await client.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stream", [False, True])
|
||||
async def test_two_presets_route_same_gateway_model_independently(bind_transport, stream):
|
||||
config = _config()
|
||||
requests = []
|
||||
|
||||
def handler(request):
|
||||
requests.append(request)
|
||||
return _answer(request)
|
||||
|
||||
tools = [{"type": "function", "function": {
|
||||
"name": "lookup", "parameters": {"type": "object", "properties": {}},
|
||||
}}]
|
||||
for name in ("responses", "chat"):
|
||||
provider = bind_transport(make_provider(config, preset_name=name), handler)
|
||||
invoke = provider.chat_stream if stream else provider.chat
|
||||
result = await invoke(
|
||||
[{"role": "user", "content": "hello"}], tools=tools,
|
||||
reasoning_effort=provider.generation.reasoning_effort,
|
||||
)
|
||||
assert result.content == "ok"
|
||||
assert [request.url.path for request in requests] == ["/v1/responses", "/v1/chat/completions"]
|
||||
body = json.loads(requests[0].content)
|
||||
assert body["model"] == "gpt-6-luna"
|
||||
assert body["reasoning"] == {"effort": "high"}
|
||||
assert body["tools"][0]["name"] == "lookup"
|
||||
assert "context_management" not in body
|
||||
assert "include" not in body
|
||||
|
||||
|
||||
@pytest.mark.parametrize("allow_chat", [False, True])
|
||||
@pytest.mark.parametrize("stream", [False, True])
|
||||
async def test_chat_compatibility_fallback_requires_preset_support(bind_transport, allow_chat, stream):
|
||||
config = _config()
|
||||
if allow_chat:
|
||||
config.model_presets["responses"].api = ModelAPIConfig(
|
||||
supported_apis=("responses", "chat_completions"), preferred_api="responses",
|
||||
)
|
||||
requests = []
|
||||
|
||||
def handler(request):
|
||||
requests.append(request.url.path)
|
||||
if request.url.path.endswith("/responses"):
|
||||
return httpx.Response(404, json={"error": {"message": "Responses endpoint not supported", "type": "invalid_request_error"}})
|
||||
return _answer(request)
|
||||
|
||||
provider = bind_transport(make_provider(config), handler)
|
||||
invoke = provider.chat_stream if stream else provider.chat
|
||||
for _ in range(_RESPONSES_FAILURE_THRESHOLD + 1):
|
||||
result = await invoke([{"role": "user", "content": "hello"}])
|
||||
assert result.finish_reason == ("stop" if allow_chat else "error")
|
||||
if allow_chat:
|
||||
assert requests == ["/v1/responses", "/v1/chat/completions"] * _RESPONSES_FAILURE_THRESHOLD + ["/v1/chat/completions"]
|
||||
else:
|
||||
assert requests == ["/v1/responses"] * (_RESPONSES_FAILURE_THRESHOLD + 1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("inline", [False, True])
|
||||
async def test_fallback_preset_keeps_its_api_and_invalidates_runtime(bind_transport, monkeypatch, inline):
|
||||
config = _config()
|
||||
fallback = config.model_presets["chat"]
|
||||
config.agents.defaults.fallback_models = [
|
||||
InlineFallbackConfig.model_validate(fallback.model_dump()) if inline else "chat",
|
||||
]
|
||||
requests = []
|
||||
|
||||
def handler(request):
|
||||
requests.append(request.url.path)
|
||||
if request.url.path.endswith("/responses"):
|
||||
return httpx.Response(401, json={"error": {"message": "invalid_api_key", "type": "authentication_error"}})
|
||||
return _answer(request)
|
||||
|
||||
from nanobot.providers import factory
|
||||
|
||||
original = factory._make_provider_core
|
||||
monkeypatch.setattr(factory, "_make_provider_core", lambda *args, **kwargs: bind_transport(original(*args, **kwargs), handler))
|
||||
provider = make_provider(config)
|
||||
result = await provider.chat(messages=[{"role": "user", "content": "hello"}])
|
||||
assert result.content == "ok"
|
||||
assert requests == ["/v1/responses", "/v1/chat/completions"]
|
||||
previous = provider_signature(config)
|
||||
candidate = config.agents.defaults.fallback_models[0] if inline else config.model_presets["chat"]
|
||||
candidate.api = ModelAPIConfig(supported_apis=("responses",))
|
||||
assert provider_signature(config) != previous
|
||||
config.agents.defaults.fallback_models = []
|
||||
previous = provider_signature(config)
|
||||
config.model_presets["responses"].api = None
|
||||
assert provider_signature(config) != previous
|
||||
|
||||
|
||||
def test_preset_api_preference_must_be_supported():
|
||||
with pytest.raises(ValidationError, match="preferred_api must be one of supported_apis"):
|
||||
ModelAPIConfig.model_validate({"supportedApis": ["chat_completions"], "preferredApi": "responses"})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("apis,preferred", [
|
||||
(("responses",), "responses"),
|
||||
(("chat_completions",), "chat_completions"),
|
||||
(("chat_completions", "responses"), "chat_completions"),
|
||||
])
|
||||
async def test_preset_overrides_legacy_openai_default_and_scopes_compaction(bind_transport, apis, preferred):
|
||||
config = _config()
|
||||
preset = config.model_presets["responses"]
|
||||
preset.provider = "openai"
|
||||
preset.api = ModelAPIConfig(supported_apis=apis, preferred_api=preferred)
|
||||
config.providers.openai.api_key = "fixture"
|
||||
config.providers.openai.api_type = "chat_completions"
|
||||
requests = []
|
||||
|
||||
def handler(request):
|
||||
requests.append(request.url.path)
|
||||
return _answer(request)
|
||||
|
||||
provider = bind_transport(make_provider(config), handler)
|
||||
assert provider.supports_native_compaction() is (preferred == "responses")
|
||||
result = await provider.chat(messages=[{"role": "user", "content": "hello"}])
|
||||
assert result.content == "ok"
|
||||
assert requests == ["/v1/responses" if preferred == "responses" else "/v1/chat/completions"]
|
||||
@@ -263,7 +263,7 @@ def test_xai_inference_classifies_typed_reauth() -> None:
|
||||
"responses_model",
|
||||
["gpt-5.4-mini", "gpt-6-astra", "gpt-6-sol", "gpt-6-luna"],
|
||||
)
|
||||
def test_github_copilot_catalog_only_lists_compatible_chat_models(
|
||||
def test_github_copilot_catalog_routes_advertised_model_apis(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
tmp_path: Path,
|
||||
responses_model: str,
|
||||
@@ -345,9 +345,17 @@ def test_github_copilot_catalog_only_lists_compatible_chat_models(
|
||||
assert [model.id for model in catalog.models] == [
|
||||
"github-copilot/claude-sonnet",
|
||||
f"github-copilot/{responses_model}",
|
||||
"github-copilot/unknown-responses-only",
|
||||
]
|
||||
assert catalog.models[0].context_window == 200_000
|
||||
assert catalog.models[0].reasoning_efforts == ("low", "high")
|
||||
assert catalog.models[0].api.supported_apis == ("chat_completions",)
|
||||
assert catalog.models[2].api.supported_apis == ("responses",)
|
||||
from nanobot.providers.github_copilot_provider import GitHubCopilotProvider
|
||||
|
||||
provider = GitHubCopilotProvider(default_model="github-copilot/unknown-responses-only")
|
||||
assert provider._should_use_responses_api(None, None)
|
||||
assert not provider._should_use_responses_api("github-copilot/claude-sonnet", "high")
|
||||
assert len(captured) == 2
|
||||
assert captured[0].headers["Authorization"] == "token github-secret"
|
||||
assert captured[1].headers["Authorization"] == "Bearer copilot-secret"
|
||||
|
||||
@@ -7,6 +7,7 @@ from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from loguru import logger
|
||||
from openai.types.responses import ResponseFunctionToolCall
|
||||
|
||||
from nanobot.providers.base import LLMUsage
|
||||
from nanobot.providers.openai_responses.converters import (
|
||||
@@ -33,6 +34,33 @@ from nanobot.providers.openai_responses.state import (
|
||||
responses_state_items,
|
||||
)
|
||||
|
||||
|
||||
async def test_sdk_tool_alias_survives_capture_and_next_request_replay():
|
||||
item = ResponseFunctionToolCall.model_validate({
|
||||
"type": "function_call", "id": "fc_alias", "call_id": "call_alias",
|
||||
"name": "lookup", "arguments": "{}", "async": True,
|
||||
})
|
||||
events = [SimpleNamespace(
|
||||
type="response.completed",
|
||||
response=SimpleNamespace(status="completed", usage=None, output=[item]),
|
||||
)]
|
||||
|
||||
async def stream():
|
||||
for event in events:
|
||||
yield event
|
||||
|
||||
capture = ResponsesStreamCapture()
|
||||
await consume_sdk_stream(stream(), capture=capture)
|
||||
state = build_responses_state(
|
||||
provider="fixture", model="fixture", input_items=[], output_items=capture.output_items,
|
||||
)
|
||||
_, items, replayed = prepare_responses_input(
|
||||
[], state=state, provider="fixture", model="fixture",
|
||||
)
|
||||
assert replayed
|
||||
assert items[0]["async"] is True
|
||||
assert "async_" not in items[0]
|
||||
|
||||
# ======================================================================
|
||||
# converters - split_tool_call_id
|
||||
# ======================================================================
|
||||
|
||||
@@ -9,7 +9,7 @@ import httpx
|
||||
import pytest
|
||||
|
||||
from nanobot.config.loader import load_config, save_config
|
||||
from nanobot.config.schema import Config, InlineFallbackConfig, ModelPresetConfig
|
||||
from nanobot.config.schema import Config, InlineFallbackConfig, ModelAPIConfig, ModelPresetConfig
|
||||
from nanobot.llm_usage import get_llm_usage_store
|
||||
from nanobot.llm_usage.models import LLMCallRecord
|
||||
from nanobot.providers.base import LLMUsage
|
||||
@@ -746,6 +746,81 @@ def test_model_configuration_advanced_options_round_trip(
|
||||
assert row["reasoning_effort"] is None
|
||||
|
||||
|
||||
def test_custom_preset_api_round_trip_and_reset(tmp_path, monkeypatch):
|
||||
config_path = tmp_path / "config.json"
|
||||
config = Config.model_validate({"providers": {
|
||||
"tenant": {"apiBase": "https://tenant.test/v1"},
|
||||
}})
|
||||
save_config(config, config_path)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
api = {"supported_apis": ["responses"], "preferred_api": "responses"}
|
||||
created = create_model_configuration({
|
||||
"name": ["reasoning"], "provider": ["tenant"], "model": ["gpt-6-luna"],
|
||||
"api": [json.dumps(api)],
|
||||
})
|
||||
row = next(row for row in created["model_presets"] if row["name"] == "reasoning")
|
||||
assert row["api"] == api
|
||||
providers = {row["name"]: row for row in created["providers"]}
|
||||
assert providers["tenant"]["model_api_configurable"] is True
|
||||
assert providers["github_copilot"]["model_api_configurable"] is True
|
||||
assert providers["anthropic"]["model_api_configurable"] is False
|
||||
saved = load_config(config_path)
|
||||
assert saved.model_presets["reasoning"].api.to_capabilities().preferred_api == "responses"
|
||||
assert json.loads(config_path.read_text())["modelPresets"]["reasoning"]["api"] == {
|
||||
"supportedApis": ["responses"], "preferredApi": "responses",
|
||||
}
|
||||
|
||||
update_model_call_order({"order": [json.dumps(["reasoning"])]})
|
||||
assert settings_payload()["agent"]["api"] == api
|
||||
update_model_configuration({"name": ["reasoning"], "temperature": ["0.3"]})
|
||||
assert settings_payload()["agent"]["api"] == api
|
||||
reset = update_model_configuration({"name": ["reasoning"], "api": [""]})
|
||||
assert next(row for row in reset["model_presets"] if row["name"] == "reasoning")["api"] is None
|
||||
assert load_config(config_path).model_presets["reasoning"].api is None
|
||||
update_model_configuration({"name": ["reasoning"], "api": [json.dumps(api)]})
|
||||
update_model_configuration({"name": ["reasoning"], "model": ["another-model"]})
|
||||
assert load_config(config_path).model_presets["reasoning"].api is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("provider,api,error", [
|
||||
("openai", {"supportedApis": ["chat_completions"], "preferredApi": "responses"}, "api must declare"),
|
||||
("anthropic", {"supportedApis": ["responses"]}, "provider does not support"),
|
||||
])
|
||||
def test_create_preset_rejects_invalid_api_without_saving(tmp_path, monkeypatch, provider, api, error):
|
||||
config_path = tmp_path / "config.json"
|
||||
config = Config()
|
||||
config.providers.openai.api_key = "fixture"
|
||||
config.providers.anthropic.api_key = "fixture"
|
||||
save_config(config, config_path)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
with pytest.raises(WebUISettingsError, match=error):
|
||||
create_model_configuration({
|
||||
"name": ["test"], "provider": [provider], "model": ["test-model"],
|
||||
"api": [json.dumps(api)],
|
||||
})
|
||||
assert load_config(config_path).model_presets == {}
|
||||
|
||||
|
||||
def test_legacy_migration_preserves_primary_and_fallback_apis(tmp_path, monkeypatch):
|
||||
config_path = tmp_path / "config.json"
|
||||
config = Config.model_validate({"providers": {
|
||||
"tenant": {"apiBase": "https://tenant.test/v1"},
|
||||
}})
|
||||
defaults = config.agents.defaults
|
||||
defaults.model = "tenant/reasoning"
|
||||
defaults.provider = "tenant"
|
||||
defaults.api = ModelAPIConfig(supported_apis=("responses",))
|
||||
defaults.fallback_models = [InlineFallbackConfig(
|
||||
provider="tenant", model="tenant/chat", api=ModelAPIConfig(supported_apis=("chat_completions",)),
|
||||
)]
|
||||
save_config(config, config_path)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
migrate_model_configurations()
|
||||
saved = load_config(config_path)
|
||||
assert saved.model_presets["reasoning"].api == defaults.api
|
||||
assert saved.model_presets["chat"].api == defaults.fallback_models[0].api
|
||||
|
||||
|
||||
def test_delete_model_configuration_protects_primary_and_removes_fallback_references(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
|
||||
Reference in new issue
Block a user