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>
This commit is contained in:
1 parent
140014f8bb
commit
65f0714a3b
5 files changed
+247
No files matched your search
@@ -0,0 +1 @@
|
|||||||
|
"""LLM adapters: configuration, provider interface and profile router."""
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
"""Configuration of providers and profile-to-model mapping."""
|
||||||
|
|
||||||
|
from typing import Annotated, Literal, Self
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||||
|
|
||||||
|
from chemenu.domain.step_profile import StepProfile
|
||||||
|
|
||||||
|
_STRICT = ConfigDict(strict=True, extra="forbid", frozen=True)
|
||||||
|
|
||||||
|
|
||||||
|
class ModelTarget(BaseModel):
|
||||||
|
"""Provider and model a profile resolves to."""
|
||||||
|
|
||||||
|
model_config = _STRICT
|
||||||
|
|
||||||
|
provider: str
|
||||||
|
model: str
|
||||||
|
effort: Literal["low", "medium", "high", "xhigh", "max"]
|
||||||
|
max_tokens: int = Field(gt=0)
|
||||||
|
timeout_seconds: int = Field(gt=0) # no default on purpose
|
||||||
|
|
||||||
|
|
||||||
|
class AnthropicConfig(BaseModel):
|
||||||
|
"""Anthropic API; holds the name of the key variable, never the key."""
|
||||||
|
|
||||||
|
model_config = _STRICT
|
||||||
|
|
||||||
|
kind: Literal["anthropic"]
|
||||||
|
api_key_env: str
|
||||||
|
|
||||||
|
|
||||||
|
class RecordedConfig(BaseModel):
|
||||||
|
"""Replay of recorded answers."""
|
||||||
|
|
||||||
|
model_config = _STRICT
|
||||||
|
|
||||||
|
kind: Literal["recorded"]
|
||||||
|
directory: str
|
||||||
|
|
||||||
|
|
||||||
|
ProviderConfig = Annotated[AnthropicConfig | RecordedConfig, Field(discriminator="kind")]
|
||||||
|
|
||||||
|
|
||||||
|
class LlmConfig(BaseModel):
|
||||||
|
"""All providers and the model each profile uses."""
|
||||||
|
|
||||||
|
model_config = _STRICT
|
||||||
|
|
||||||
|
providers: dict[str, ProviderConfig]
|
||||||
|
# keys arrive as strings (YAML), so the enum is not checked strictly
|
||||||
|
profiles: dict[Annotated[StepProfile, Field(strict=False)], ModelTarget]
|
||||||
|
|
||||||
|
@model_validator(mode="after")
|
||||||
|
def _providers_exist(self) -> Self:
|
||||||
|
for profile, target in self.profiles.items():
|
||||||
|
if target.provider not in self.providers:
|
||||||
|
raise ValueError(
|
||||||
|
f"profile {profile.value!r} names unknown provider {target.provider!r}"
|
||||||
|
)
|
||||||
|
return self
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
"""Interface of one provider behind the router."""
|
||||||
|
|
||||||
|
from typing import Protocol
|
||||||
|
|
||||||
|
from chemenu.adapters.llm.config import ModelTarget
|
||||||
|
from chemenu.ports.llm import LlmRequest, LlmResponse
|
||||||
|
|
||||||
|
|
||||||
|
class Provider(Protocol):
|
||||||
|
"""Calls the model in `target`; keeps no per-call state (used from several threads)."""
|
||||||
|
|
||||||
|
def complete(self, request: LlmRequest, target: ModelTarget) -> LlmResponse: ...
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""Router: one profile leads to exactly one provider and model."""
|
||||||
|
|
||||||
|
from collections.abc import Mapping
|
||||||
|
|
||||||
|
from chemenu.adapters.llm.config import LlmConfig
|
||||||
|
from chemenu.adapters.llm.provider import Provider
|
||||||
|
from chemenu.ports.llm import (
|
||||||
|
LlmRequest,
|
||||||
|
LlmResponse,
|
||||||
|
ModelMismatchError,
|
||||||
|
ProfileNotConfiguredError,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ProfileRouter:
|
||||||
|
"""Implements `LlmPort`; holds no mutable state."""
|
||||||
|
|
||||||
|
def __init__(self, config: LlmConfig, providers: Mapping[str, Provider]) -> None:
|
||||||
|
used = {target.provider for target in config.profiles.values()}
|
||||||
|
missing = sorted(used - providers.keys())
|
||||||
|
if missing:
|
||||||
|
raise ValueError(f"providers not supplied: {', '.join(repr(m) for m in missing)}")
|
||||||
|
self._config = config
|
||||||
|
self._providers = dict(providers)
|
||||||
|
|
||||||
|
def complete(self, request: LlmRequest) -> LlmResponse:
|
||||||
|
target = self._config.profiles.get(request.profile)
|
||||||
|
if target is None:
|
||||||
|
raise ProfileNotConfiguredError(
|
||||||
|
f"no model configured for profile {request.profile.value!r}"
|
||||||
|
)
|
||||||
|
response = self._providers[target.provider].complete(request, target)
|
||||||
|
if response.model != target.model:
|
||||||
|
raise ModelMismatchError(
|
||||||
|
f"expected model {target.model!r}, got {response.model!r}",
|
||||||
|
response.usage,
|
||||||
|
)
|
||||||
|
return response
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
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()})
|
||||||
Reference in new issue
Block a user