Files
AiRouter/tests/test_providers.py
T

834 lines
27 KiB
Python

from __future__ import annotations
import asyncio
import json
from dataclasses import replace
from datetime import datetime, timedelta, timezone
from email.utils import format_datetime
from pathlib import Path
import httpx
import pytest
import airouter.config as config_module
import airouter.models as models_module
import airouter.provider as provider_module
import airouter.providers as providers_module
from airouter.auth import Token, resolve_profile_tokens, resolve_tokens
from airouter.config import (
DEFAULT_BASE_URL,
PROVIDER_PRESETS,
Config,
ConfigError,
LimitsConfig,
ProviderConfig,
ProviderProfile,
UIConfig,
load_config,
save_provider_profiles,
)
from airouter.models import ModelInfo, fetch_models
from airouter.provider import OpenAIClient, ProviderError
from airouter.providers import ProviderRegistry
@pytest.fixture(autouse=True)
def isolated_environment(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(config_module, "GLOBAL_CONFIG", tmp_path / "global.toml")
monkeypatch.setattr(config_module, "GLOBAL_PROVIDERS", tmp_path / "providers.json")
monkeypatch.setattr(models_module, "CACHE_DIR", tmp_path / "model-cache")
for name in (
"AIROUTER_TOKEN",
"AIROUTER_BASE_URL",
"AIROUTER_MODEL",
"AIROUTER_WORKER_MODEL",
"OPENCODE_API_KEY",
"OPENCODE_GO_API_KEY",
"OPENAI_API_KEY",
"OPENROUTER_API_KEY",
"GROQ_API_KEY",
"TOGETHER_API_KEY",
"DEEPSEEK_API_KEY",
"MISTRAL_API_KEY",
"OLLAMA_API_KEY",
):
monkeypatch.delenv(name, raising=False)
def run(coro):
return asyncio.run(coro)
def profile(provider_id: str, **changes) -> ProviderProfile:
base = PROVIDER_PRESETS[provider_id]
values = {"models": list(base.models), **changes}
return replace(base, id=provider_id, **values)
def routing_config(**changes) -> Config:
options = {"active_provider": "opencode", **changes}
return Config(
providers={
"opencode": profile("opencode"),
"openai": profile("openai"),
"openrouter": profile("openrouter"),
"ollama": profile("ollama"),
},
**options,
)
def test_presets_and_legacy_defaults_are_backward_compatible(tmp_path: Path):
required = {
"opencode",
"openai",
"openrouter",
"groq",
"together",
"deepseek",
"mistral",
"ollama",
"lmstudio",
"vllm",
"llamacpp",
"custom",
}
assert required <= set(PROVIDER_PRESETS)
for provider_id, preset in PROVIDER_PRESETS.items():
assert preset.id == provider_id
assert preset.token is None
if preset.base_url:
assert preset.base_url.startswith(("http://", "https://"))
for provider_id in ("ollama", "lmstudio", "vllm", "llamacpp"):
assert PROVIDER_PRESETS[provider_id].auto_auth is False
config = Config()
assert config.provider == ProviderConfig()
assert config.active_provider == "opencode"
assert config.providers["opencode"].base_url == DEFAULT_BASE_URL
assert config.resolve_model_ref("model") == ("opencode", "model")
project_path = tmp_path / "project.toml"
global_path = tmp_path / "global.toml"
positional = Config(
ProviderConfig(),
LimitsConfig(),
UIConfig(),
"main",
"worker",
{},
{},
project_path,
global_path,
)
assert positional.project_config_path == project_path
assert positional.global_config_path == global_path
assert positional.active_provider == "opencode"
loaded = load_config(tmp_path)
assert loaded.provider.base_url == DEFAULT_BASE_URL
assert loaded.providers["opencode"].base_url == DEFAULT_BASE_URL
assert loaded.active_provider == "opencode"
def test_config_parses_profiles_and_preserves_custom_legacy_default(tmp_path: Path):
(tmp_path / ".airouter.toml").write_text(
"""
active_provider = "openai"
orchestrator_provider = "openrouter"
worker_provider = "openai"
[provider]
base_url = "https://legacy.example/v1"
token = "legacy-secret"
max_retries = 4
request_timeout = 42.5
[providers.openai]
name = "Work OpenAI"
token_env = "WORK_OPENAI_KEY"
enabled = false
max_retries = 5
request_timeout = 12.0
default_model = "gpt-work"
models = ["gpt-work", "gpt-small"]
[providers.openrouter]
models = ["router-model"]
[providers.ollama]
base_url = "http://127.0.0.1:11435/v1"
auto_auth = false
models = ["llama-local"]
""",
encoding="utf-8",
)
config = load_config(tmp_path)
assert config.provider.base_url == "https://legacy.example/v1"
assert config.provider.token == "legacy-secret"
assert config.active_provider == "openai"
assert config.orchestrator_provider == "openrouter"
assert config.worker_provider == "openai"
assert config.providers["default"].base_url == "https://legacy.example/v1"
assert config.providers["default"].token == "legacy-secret"
assert config.providers["default"].max_retries == 4
assert config.providers["default"].request_timeout == 42.5
openai = config.providers["openai"]
assert openai.name == "Work OpenAI"
assert openai.base_url == "https://api.openai.com/v1"
assert openai.token_env == "WORK_OPENAI_KEY"
assert openai.enabled is False
assert openai.max_retries == 5
assert openai.request_timeout == 12.0
assert openai.default_model == "gpt-work"
assert openai.models == ["gpt-work", "gpt-small"]
assert config.providers["ollama"].models == ["llama-local"]
def test_custom_legacy_provider_remains_active_with_explicit_profiles(tmp_path: Path):
(tmp_path / ".airouter.toml").write_text(
"""
[provider]
base_url = "http://localhost:9999/v1"
[providers.openai]
models = ["gpt-4o-mini"]
""",
encoding="utf-8",
)
config = load_config(tmp_path)
assert config.active_provider == "default"
assert set(config.providers) == {"default", "openai"}
assert config.resolve_model_ref("local-model") == ("default", "local-model")
def test_global_catalog_is_loaded_before_toml_overrides(tmp_path: Path):
catalog_path = tmp_path / "providers.json"
save_provider_profiles(
{
"openai": profile("openai", name="Saved", models=["saved-model"]),
"groq": profile("groq", models=["groq-saved"]),
},
path=catalog_path,
)
(tmp_path / ".airouter.toml").write_text(
"""
[providers.openai]
name = "TOML override"
max_retries = 7
models = ["toml-model"]
""",
encoding="utf-8",
)
config = load_config(tmp_path)
assert config.providers["openai"].name == "TOML override"
assert config.providers["openai"].base_url == "https://api.openai.com/v1"
assert config.providers["openai"].token_env == "OPENAI_API_KEY"
assert config.providers["openai"].max_retries == 7
assert config.providers["openai"].models == ["toml-model"]
assert config.providers["groq"].models == ["groq-saved"]
assert "opencode" in config.providers
def test_save_provider_profiles_strips_inline_tokens(tmp_path: Path):
path = tmp_path / "providers.json"
secret = "never-write-this-secret"
save_provider_profiles(
{"openai": profile("openai", token=secret, token_env="WORK_KEY")}, path=path
)
text = path.read_text(encoding="utf-8")
assert secret not in text
payload = json.loads(text)
assert "token" not in payload["providers"]["openai"]
assert payload["providers"]["openai"]["token_env"] == "WORK_KEY"
config = load_config(tmp_path)
assert config.providers["openai"].token is None
@pytest.mark.parametrize(
"contents",
[
'[provider]\nbase_url = "not-a-url"\n',
'[provider]\nbase_url = "ftp://example.com/v1"\n',
'[provider]\nmax_retries = 0\n',
'[provider]\nmax_retries = 1.5\n',
'[providers.openai]\nbase_url = "http://"\n',
'[providers.openai]\nmax_retries = -2\n',
'[providers.openai]\nmodels = "not-an-array"\n',
],
)
def test_invalid_profile_settings_raise_config_error(tmp_path: Path, contents: str):
(tmp_path / ".airouter.toml").write_text(contents, encoding="utf-8")
with pytest.raises(ConfigError):
load_config(tmp_path)
def test_provider_prefix_and_role_resolution():
config = routing_config(
orchestrator_provider="openrouter", worker_provider="openai"
)
assert config.resolve_model_ref("gpt-work") == ("openai", "gpt-work")
assert config.resolve_model_ref("gpt-main", role="orchestrator") == (
"openrouter",
"gpt-main",
)
assert config.resolve_model_ref("ollama/llama-local") == (
"ollama",
"llama-local",
)
assert config.resolve_model_ref("openrouter/anthropic/claude") == (
"openrouter",
"anthropic/claude",
)
# Config only recognizes configured providers; it does not guess that a
# slash in an arbitrary model ID is a provider separator.
assert config.resolve_model_ref("unknown/model") == ("openai", "unknown/model")
def test_profile_token_isolation_and_local_no_auth(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setenv("OPENCODE_API_KEY", "opencode-secret")
monkeypatch.setenv("OPENAI_API_KEY", "openai-secret")
monkeypatch.setenv("AIROUTER_TOKEN", "generic-secret")
config = routing_config()
opencode_tokens = resolve_profile_tokens(config, config.providers["opencode"])
openai_tokens = resolve_profile_tokens(config, config.providers["openai"])
assert "opencode-secret" in {token.value for token in opencode_tokens}
assert "opencode-secret" not in {token.value for token in openai_tokens}
assert "openai-secret" in {token.value for token in openai_tokens}
assert "generic-secret" in {token.value for token in openai_tokens}
accidental = replace(
config.providers["openai"], token_env="OPENCODE_API_KEY"
)
assert "opencode-secret" not in {
token.value for token in resolve_profile_tokens(config, accidental)
}
spoofed_opencode = replace(
config.providers["opencode"],
kind="openai",
base_url="https://third-party.example/v1",
)
assert "opencode-secret" not in {
token.value for token in resolve_profile_tokens(config, spoofed_opencode)
}
assert resolve_profile_tokens(config, config.providers["ollama"]) == []
assert resolve_profile_tokens(
config, replace(config.providers["ollama"], token="local-secret")
)[0].value == "local-secret"
legacy = Config(
provider=ProviderConfig(base_url="https://third-party.example/v1")
)
legacy_values = {token.value for token in resolve_tokens(legacy)}
assert "opencode-secret" not in legacy_values
assert "openai-secret" not in legacy_values
assert "generic-secret" in legacy_values
legacy_openai = Config(
provider=ProviderConfig(base_url="https://api.openai.com/v1")
)
assert "openai-secret" in {
token.value for token in resolve_tokens(legacy_openai)
}
legacy_opencode = Config()
assert "opencode-secret" in {
token.value for token in resolve_tokens(legacy_opencode)
}
class FakeClient:
instances: list["FakeClient"] = []
def __init__(self, config: Config, tokens: list[Token]):
self.config = config
self.tokens = tokens
self.closed = False
self.profile_id = None
self.instances.append(self)
async def aclose(self):
self.closed = True
def test_registry_routes_caches_and_isolates_tokens(monkeypatch: pytest.MonkeyPatch):
FakeClient.instances.clear()
monkeypatch.setattr(providers_module, "OpenAIClient", FakeClient)
monkeypatch.setenv("OPENCODE_API_KEY", "oc-only")
monkeypatch.setenv("OPENAI_API_KEY", "oa-only")
initial = [Token(value="initial", source="test")]
config = routing_config(orchestrator_provider="openrouter")
registry = ProviderRegistry(config, tokens=initial)
opencode = registry.client("default-model")
assert registry.client("another-model") is opencode
assert opencode.profile_id == "opencode"
assert opencode.config.provider.request_timeout == 600.0
assert {token.value for token in opencode.tokens} >= {"initial", "oc-only"}
openai = registry.client("openai/gpt-work")
assert openai is not opencode
assert openai.profile_id == "openai"
assert "initial" not in {token.value for token in openai.tokens}
assert "oc-only" not in {token.value for token in openai.tokens}
assert "oa-only" in {token.value for token in openai.tokens}
client, provider_id, bare = registry.resolve("openrouter/anthropic/claude")
assert client.profile_id == provider_id == "openrouter"
assert bare == "anthropic/claude"
assert registry.default_client("orchestrator") is client
assert registry.default_client("worker") is opencode
assert registry.client("library/model", provider_id="ollama").profile_id == "ollama"
with pytest.raises(ConfigError, match="Неизвестный провайдер"):
registry.client("missing/model")
with pytest.raises(ConfigError, match="Неизвестный провайдер"):
registry.client("gpt", provider_id="missing")
disabled = replace(config.providers["openai"], enabled=False)
config.providers["openai"] = disabled
with pytest.raises(ConfigError, match="отключён"):
registry.client("openai/gpt")
assert "oc-only" not in repr(registry)
run(registry.aclose())
assert all(client.closed for client in FakeClient.instances)
def test_registry_upsert_remove_and_per_profile_retry_settings(
monkeypatch: pytest.MonkeyPatch,
):
FakeClient.instances.clear()
monkeypatch.setattr(providers_module, "OpenAIClient", FakeClient)
config = routing_config(active_provider="openai")
registry = ProviderRegistry(config)
old = registry.client("gpt")
registry.upsert(
replace(
config.providers["openai"],
base_url="https://replacement.example/v1",
max_retries=9,
request_timeout=3.5,
)
)
new = registry.client("gpt")
assert new is not old
assert new.config.provider.base_url == "https://replacement.example/v1"
assert new.config.provider.max_retries == 9
assert new.config.provider.request_timeout == 3.5
async def scenario():
registry.remove("openai")
assert config.active_provider == "opencode"
await registry.aclose()
run(scenario())
assert old.closed
assert new.closed
def test_registry_catalog_merges_configured_models_and_metadata(
monkeypatch: pytest.MonkeyPatch,
):
config = Config(
providers={
"opencode": profile(
"opencode", models=["configured-local"], default_model="main-default"
),
"openai": profile("openai", models=["configured-cloud"]),
"ollama": profile("ollama", models=["offline-model"]),
},
active_provider="opencode",
)
fetched_tokens: list[str | None] = []
def fake_fetch(base_url, **kwargs):
fetched_tokens.append(kwargs.get("token"))
if "11434" in base_url:
raise httpx.ConnectError("offline")
return [ModelInfo(id="remote-model", name="Remote")]
monkeypatch.setattr(providers_module, "fetch_models", fake_fetch)
registry = ProviderRegistry(config, tokens=[Token(value="initial", source="test")])
catalog = registry.catalog(timeout=0.5)
assert fetched_tokens == ["initial", None, None]
by_ref = {(item.provider, item.id): item for item in catalog}
assert ("opencode", "configured-local") in by_ref
assert ("opencode", "main-default") in by_ref
assert ("openai", "configured-cloud") in by_ref
assert ("ollama", "offline-model") in by_ref
assert by_ref[("openai", "remote-model")].provider_name == "OpenAI"
static_ids = {item["id"] for item in models_module.STATIC_MODELS}
assert not any(item.id in static_ids and item.provider == "ollama" for item in catalog)
def test_model_metadata_and_custom_unavailable_does_not_return_static_models(
monkeypatch: pytest.MonkeyPatch,
):
class OfflineClient:
def __init__(self, timeout):
self.timeout = timeout
def __enter__(self):
return self
def __exit__(self, *args):
return None
def get(self, url, headers):
raise httpx.ConnectError("offline")
monkeypatch.setattr(models_module.httpx, "Client", OfflineClient)
assert fetch_models("http://localhost:11434/v1", provider="ollama") == []
opencode = fetch_models(DEFAULT_BASE_URL, refresh=True)
assert opencode
assert {item.id for item in opencode} == {
item["id"] for item in models_module.STATIC_MODELS
}
assert all(item.provider == "opencode" for item in opencode)
assert all(item.provider_name == "OpenCode" for item in opencode)
info = ModelInfo.from_api({"id": "m", "name": "Model"}, provider="p", profile_name="Profile")
assert (info.provider, info.provider_name) == ("p", "Profile")
assert ModelInfo(id="plain").provider == ""
def test_model_cache_is_provider_aware_and_never_stores_tokens(
monkeypatch: pytest.MonkeyPatch,
):
calls: list[str | None] = []
class Response:
def raise_for_status(self):
return None
def json(self):
return {"data": [{"id": f"model-{len(calls)}", "name": "Model"}]}
class FakeSyncClient:
def __init__(self, timeout):
self.timeout = timeout
def __enter__(self):
return self
def __exit__(self, *args):
return None
def get(self, url, headers):
calls.append(headers.get("Authorization"))
return Response()
monkeypatch.setattr(models_module.httpx, "Client", FakeSyncClient)
url = "https://shared.example/v1"
first = fetch_models(url, token="secret-a", provider="a", refresh=True)
second = fetch_models(url, token="secret-b", provider="b")
cached = fetch_models(url, token="secret-a", provider="a")
assert [item.id for item in first] == ["model-1"]
assert [item.id for item in second] == ["model-2"]
assert [item.id for item in cached] == ["model-1"]
assert len(calls) == 2
assert first[0].provider == "a"
assert second[0].provider == "b"
for path in models_module.CACHE_DIR.glob("*.json"):
text = path.read_text(encoding="utf-8")
assert "secret-a" not in text
assert "secret-b" not in text
def sse_response(text: str = "ok") -> httpx.Response:
body = (
'data: {"choices":[{"delta":{"content":"'
+ text
+ '"},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n'
)
return httpx.Response(
200,
headers={"content-type": "text/event-stream"},
content=body.encode(),
)
def error_response(status: int, retry_after: str | None = None) -> httpx.Response:
headers = {"content-type": "application/json"}
if retry_after is not None:
headers["Retry-After"] = retry_after
return httpx.Response(
status,
headers=headers,
json={"error": {"message": "temporary"}},
)
async def client_with_transport(handler, *, max_retries: int = 2):
config = Config(
provider=ProviderConfig(
base_url="https://provider.example/v1", max_retries=max_retries
)
)
client = OpenAIClient(config, [], profile_id="third-party")
await client._client.aclose()
client._client = httpx.AsyncClient(transport=httpx.MockTransport(handler))
return client
async def stream(client: OpenAIClient, **callbacks):
return await client.stream_chat(
model="model",
messages=[],
session_id="test-session",
**callbacks,
)
@pytest.mark.parametrize("status", [408, 409, 425, 429, 500, 502, 503, 504])
def test_retryable_http_statuses_use_total_attempt_budget(
monkeypatch: pytest.MonkeyPatch, status: int
):
calls = 0
delays: list[float] = []
retries: list[tuple[int, int, float, str]] = []
def handler(request):
nonlocal calls
calls += 1
return error_response(status) if calls == 1 else sse_response()
async def fake_sleep(delay):
delays.append(delay)
monkeypatch.setattr(provider_module.asyncio, "sleep", fake_sleep)
monkeypatch.setattr(provider_module.random, "uniform", lambda low, high: 0.0)
async def scenario():
client = await client_with_transport(handler, max_retries=2)
try:
turn = await stream(client, on_retry=lambda *args: retries.append(args))
assert turn.content == "ok"
finally:
await client.aclose()
run(scenario())
assert calls == 2
assert delays == [1.0]
assert retries == [(1, 2, 1.0, f"HTTP {status}")]
def test_retry_after_seconds_and_http_date(monkeypatch: pytest.MonkeyPatch):
delays: list[float] = []
async def fake_sleep(delay):
delays.append(delay)
monkeypatch.setattr(provider_module.asyncio, "sleep", fake_sleep)
async def seconds_scenario():
calls = 0
def handler(request):
nonlocal calls
calls += 1
return error_response(429, "3") if calls == 1 else sse_response()
client = await client_with_transport(handler)
try:
await stream(client)
finally:
await client.aclose()
run(seconds_scenario())
assert delays == [3.0]
fixed = datetime(2026, 1, 1, tzinfo=timezone.utc)
class FixedDateTime:
@classmethod
def now(cls, tz=None):
return fixed
monkeypatch.setattr(provider_module, "datetime", FixedDateTime)
retry_date = format_datetime(fixed + timedelta(seconds=7), usegmt=True)
async def date_scenario():
calls = 0
def handler(request):
nonlocal calls
calls += 1
return error_response(503, retry_date) if calls == 1 else sse_response()
client = await client_with_transport(handler)
try:
await stream(client)
finally:
await client.aclose()
run(date_scenario())
assert delays == [3.0, 7.0]
def test_connection_retry_and_non_retryable_http_error(monkeypatch: pytest.MonkeyPatch):
calls = 0
delays: list[float] = []
def handler(request):
nonlocal calls
calls += 1
if calls == 1:
raise httpx.ConnectError("offline")
return sse_response()
async def fake_sleep(delay):
delays.append(delay)
monkeypatch.setattr(provider_module.asyncio, "sleep", fake_sleep)
monkeypatch.setattr(provider_module.random, "uniform", lambda low, high: 0.5)
async def scenario():
client = await client_with_transport(handler)
try:
assert (await stream(client)).content == "ok"
finally:
await client.aclose()
run(scenario())
assert calls == 2
assert delays == [1.5]
calls = 0
def bad_request(request):
nonlocal calls
calls += 1
return error_response(400)
async def no_retry_scenario():
client = await client_with_transport(bad_request, max_retries=4)
try:
with pytest.raises(ProviderError) as caught:
await stream(client)
assert caught.value.status == 400
assert caught.value.attempts == 1
finally:
await client.aclose()
run(no_retry_scenario())
assert calls == 1
assert delays == [1.5]
def test_retry_budget_is_total_attempts_and_minimum_one(monkeypatch: pytest.MonkeyPatch):
calls = 0
delays: list[float] = []
def handler(request):
nonlocal calls
calls += 1
return error_response(503)
async def fake_sleep(delay):
delays.append(delay)
monkeypatch.setattr(provider_module.asyncio, "sleep", fake_sleep)
monkeypatch.setattr(provider_module.random, "uniform", lambda low, high: 0.0)
async def scenario():
client = await client_with_transport(handler, max_retries=3)
try:
with pytest.raises(ProviderError) as caught:
await stream(client)
assert caught.value.attempts == 3
assert calls == 3
client.config.provider.max_retries = 0
with pytest.raises(ProviderError) as minimum:
await stream(client)
assert minimum.value.attempts == 1
assert calls == 4
finally:
await client.aclose()
run(scenario())
assert delays == [1.0, 2.0]
def test_no_retry_after_output_was_emitted(monkeypatch: pytest.MonkeyPatch):
calls = 0
delays: list[float] = []
text: list[str] = []
class OutputThenDisconnect(httpx.AsyncByteStream):
async def __aiter__(self):
yield b'data: {"choices":[{"delta":{"content":"partial"}}]}\n\n'
raise httpx.ReadError("disconnected")
def handler(request):
nonlocal calls
calls += 1
return httpx.Response(
200,
headers={"content-type": "text/event-stream"},
stream=OutputThenDisconnect(),
)
async def fake_sleep(delay):
delays.append(delay)
monkeypatch.setattr(provider_module.asyncio, "sleep", fake_sleep)
async def scenario():
client = await client_with_transport(handler, max_retries=5)
try:
with pytest.raises(ProviderError) as caught:
await stream(client, on_text=text.append)
assert caught.value.attempts == 1
finally:
await client.aclose()
run(scenario())
assert calls == 1
assert delays == []
assert text == ["partial"]
def test_401_rotates_tokens_and_third_party_hints_do_not_mention_opencode():
authorizations: list[str | None] = []
def handler(request):
authorizations.append(request.headers.get("Authorization"))
if len(authorizations) == 1:
return error_response(401)
return sse_response()
async def scenario():
config = Config(
provider=ProviderConfig(
base_url="https://third-party.example/v1", max_retries=2
)
)
client = OpenAIClient(
config,
[Token(value="first-secret", source="test"), Token(value="second-secret", source="test")],
profile_id="third-party",
)
await client._client.aclose()
client._client = httpx.AsyncClient(transport=httpx.MockTransport(handler))
try:
assert (await stream(client)).content == "ok"
assert "first-secret" not in repr(client.tokens)
assert "second-secret" not in repr(client.tokens)
finally:
await client.aclose()
failing = await client_with_transport(lambda request: error_response(401), max_retries=1)
try:
with pytest.raises(ProviderError) as caught:
await stream(failing)
assert "OPENCODE_API_KEY" not in caught.value.hint
assert "third-party" in caught.value.hint
finally:
await failing.aclose()
run(scenario())
assert authorizations == ["Bearer first-secret", "Bearer second-secret"]