Files
chemenu-ng/tests/adapters/test_llm_router.py
T
torbenandClaude Sonnet 5.5 65f0714a3b Add LLM profile router with provider configuration
A profile resolves to exactly one provider and model; unmapped profiles,
unknown providers and model mismatches fail loudly.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-04 22:06:58 +01:00

136 lines
4.3 KiB
Python

from typing import Any
import pytest
from pydantic import BaseModel, ValidationError
from chemenu.adapters.llm.config import LlmConfig, ModelTarget
from chemenu.adapters.llm.router import ProfileRouter
from chemenu.domain.step_profile import StepProfile
from chemenu.ports.llm import (
LlmRequest,
LlmResponse,
ModelMismatchError,
ProfileNotConfiguredError,
Usage,
)
_USAGE = Usage(input_tokens=3, output_tokens=4)
class _Out(BaseModel):
x: int
class _FakeProvider:
def __init__(self, reported_model: str | None = None) -> None:
self.reported_model = reported_model
self.calls: list[tuple[LlmRequest, ModelTarget]] = []
def complete(self, request: LlmRequest, target: ModelTarget) -> LlmResponse:
self.calls.append((request, target))
return LlmResponse(text="raw", model=self.reported_model or target.model, usage=_USAGE)
def _target(provider: str, model: str) -> dict[str, Any]:
return {
"provider": provider,
"model": model,
"effort": "high",
"max_tokens": 1000,
"timeout_seconds": 60,
}
def _raw_config() -> dict[str, Any]:
return {
"providers": {
"a": {"kind": "anthropic", "api_key_env": "KEY"},
"r": {"kind": "recorded", "directory": "rec"},
},
"profiles": {
"analyse": _target("a", "model-a"),
"write": _target("r", "model-w"),
},
}
def _request(profile: StepProfile) -> LlmRequest:
return LlmRequest(step="s", profile=profile, prompt="SECRET", output_model=_Out)
def test_profile_selects_provider_and_model() -> None:
config = LlmConfig.model_validate(_raw_config())
pa, pr = _FakeProvider(), _FakeProvider()
router = ProfileRouter(config, {"a": pa, "r": pr})
response = router.complete(_request(StepProfile.WRITE))
assert response == LlmResponse(text="raw", model="model-w", usage=_USAGE)
assert pa.calls == []
assert len(pr.calls) == 1
assert pr.calls[0][1].model == "model-w"
def test_unmapped_profile_raises() -> None:
config = LlmConfig.model_validate(_raw_config())
pa, pr = _FakeProvider(), _FakeProvider()
router = ProfileRouter(config, {"a": pa, "r": pr})
with pytest.raises(ProfileNotConfiguredError, match="classify") as info:
router.complete(_request(StepProfile.CLASSIFY))
assert "SECRET" not in str(info.value)
assert pa.calls == []
assert pr.calls == []
def test_unknown_provider_is_rejected() -> None:
raw = _raw_config()
raw["profiles"]["write"] = _target("nope", "m")
with pytest.raises(ValidationError, match=r"write.*nope|nope.*write"):
LlmConfig.model_validate(raw)
def test_timeout_is_required() -> None:
raw = _raw_config()
del raw["profiles"]["write"]["timeout_seconds"]
with pytest.raises(ValidationError, match="timeout_seconds"):
LlmConfig.model_validate(raw)
def test_profile_keys_load_from_strings() -> None:
config = LlmConfig.model_validate(_raw_config())
assert set(config.profiles) == {StepProfile.ANALYSE, StepProfile.WRITE}
raw = _raw_config()
raw["profiles"]["bogus"] = _target("a", "m")
with pytest.raises(ValidationError):
LlmConfig.model_validate(raw)
raw = _raw_config()
raw["profiles"]["write"]["max_tokens"] = "32000"
with pytest.raises(ValidationError):
LlmConfig.model_validate(raw)
raw = _raw_config()
raw["profiles"]["write"]["extra"] = 1
with pytest.raises(ValidationError):
LlmConfig.model_validate(raw)
for field in ("max_tokens", "timeout_seconds"):
raw = _raw_config()
raw["profiles"]["write"][field] = 0
with pytest.raises(ValidationError):
LlmConfig.model_validate(raw)
def test_model_mismatch_raises_with_usage() -> None:
config = LlmConfig.model_validate(_raw_config())
router = ProfileRouter(config, {"a": _FakeProvider("other-model"), "r": _FakeProvider()})
with pytest.raises(ModelMismatchError, match=r"model-a.*other-model") as info:
router.complete(_request(StepProfile.ANALYSE))
assert info.value.usage == _USAGE
assert "SECRET" not in str(info.value)
def test_missing_provider_fails_in_constructor() -> None:
config = LlmConfig.model_validate(_raw_config())
with pytest.raises(ValueError, match="'r'"):
ProfileRouter(config, {"a": _FakeProvider()})