Sub topic 6
Choosing a provider from configuration
This chapter assumes you have the neutral types (ChatRequest, ChatResponse), the ChatProvider protocol, and FakeProvider from the earlier chapters in the same module. It also assumes you can read environment variables in Python.
The working model
Application code should never name a provider. It asks for "the configured provider" and gets an object that satisfies ChatProvider. One function owns the decision, and it runs once at startup.
Three pieces make this work: a settings object, a registry that maps names to factories, and a single get_provider function.
Settings and registry
Read configuration into a frozen dataclass in one place. The rest of the program receives the object and never touches os.environ.
import os
from collections.abc import Callable, Mapping
from dataclasses import dataclass
@dataclass(frozen=True)
class Settings:
provider: str
model: str
api_key: str | None
def load_settings(env: Mapping[str, str] = os.environ) -> Settings:
return Settings(
provider=env.get("LLM_PROVIDER", "fake"),
model=env.get("LLM_MODEL", "any"),
api_key=env.get("LLM_API_KEY"),
)
def _make_fake(settings: Settings) -> ChatProvider:
return FakeProvider()
REGISTRY: dict[str, Callable[[Settings], ChatProvider]] = {
"fake": _make_fake,
# "openai": _make_openai,
# "anthropic": _make_anthropic,
}
def get_provider(settings: Settings) -> ChatProvider:
try:
factory = REGISTRY[settings.provider]
except KeyError:
known = ", ".join(sorted(REGISTRY))
raise ValueError(
f"Unknown provider {settings.provider!r}. Known: {known}"
) from None
return factory(settings)Each factory takes Settings and returns a ready adapter. A real factory would check that api_key is present and construct the SDK client. Because factories are plain functions, adding a provider means writing an adapter and adding one registry line.
Call it at startup:
settings = load_settings({"LLM_PROVIDER": "fake", "LLM_MODEL": "any"})
provider = get_provider(settings)Passing a dictionary instead of os.environ makes load_settings easy to test.
Keep the model name in configuration
A model name belongs to a provider. "gpt-4o" means nothing to Anthropic. If call sites hard-code a model, switching providers breaks them even though the interface is the same. Build the ChatRequest with settings.model, or let the adapter apply a default when the request leaves the model empty. Pick one rule and apply it everywhere.
Common errors
- Importing every SDK at module load. If the registry imports
openaiandanthropicat the top of the file, a deployment that uses only one still needs both installed. Import the SDK inside the factory function instead. - Silent defaults for real providers. Defaulting to
"fake"is acceptable in development. In production it hides a missing variable and returns canned answers. Fail fast: ifLLM_ENV=productionand the provider isfake, raise at startup. - Failing at the first request. A missing API key should raise inside the factory, at startup, not on the first user request.
- Reading the environment at call time. Scattered
os.environ.getcalls make behavior hard to trace and hard to test. Read once, passSettingsdown. - Logging secrets. Log the provider name and model. Never log
api_key. You can setfield(repr=False)on that attribute so printingSettingsstays safe.
Selecting more than one provider
Fallback, covered in a later chapter, needs an ordered list. The same registry supports it:
def get_providers(names: str) -> list[ChatProvider]:
settings = load_settings()
return [
get_provider(Settings(n.strip(), settings.model, settings.api_key))
for n in names.split(",")
if n.strip()
]With LLM_PROVIDERS="openai,anthropic", the first entry is the primary and the rest are backups. A single shared api_key and model is a simplification. Real deployments usually need per-provider keys and models, such as OPENAI_API_KEY and OPENAI_MODEL, read inside each factory.
Exercise
Your app crashes with a 401 error on the first user request after deploying with LLM_PROVIDER=openai, because LLM_API_KEY was not set. Which change in this chapter's design moves the failure to startup, and where does it go?
Show answer
Check for the key inside the openai factory and raise an error if settings.api_key is None. Because get_provider runs once at startup, a missing key stops the deployment before any user request arrives.