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
d9e3051460
commit
63a612c0d6
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
|
||||
Reference in new issue
Block a user