Sub topic 6
Choosing a provider from configuration
This chapter covers how to pick a provider at startup from configuration, so that changing providers never touches call sites. It assumes you have read the earlier chapters on provider-neutral types, the ChatProvider interface, and adapters. You should be comfortable with Python dataclasses, Protocol, environment variables, and basic dictionaries of callables.
The goal: one change point
Application code should depend only on ChatProvider. Something else must decide which concrete class sits behind that name. That something is a small piece of wiring code, placed at the edge of the program, that reads configuration and returns a provider.
If the choice is spread across the code base, with if provider == "openai" checks in several places, you have rebuilt the coupling the interface was meant to remove. The aim is to have exactly one place that knows provider names.
A registry keyed by name
A registry is a dictionary that maps a configuration value to a function that builds a provider. The functions are factories: they are not called until the provider is requested. This matters because building a real adapter often needs an API key or an SDK import, and you do not want that to happen for providers you are not using.
import os
class ProviderError(Exception):
def __init__(self, message: str, retryable: bool):
super().__init__(message)
self.retryable = retryable
REGISTRY = {
"fake": lambda: FakeProvider(),
# "openai": lambda: OpenAIAdapter(),
# "anthropic": lambda: AnthropicAdapter(),
}
def get_provider() -> ChatProvider:
name = os.environ.get("LLM_PROVIDER", "fake")
try:
return REGISTRY[name]()
except KeyError:
raise ValueError(f"Unknown provider: {name}")This code relies on FakeProvider and ChatProvider from the earlier chapters. Run on its own, it needs those definitions in scope.
Three details are worth noting.
- The lambdas delay construction.
REGISTRY["openai"]is only a recipe until you call it. - The default is
"fake". A missing variable then yields a harmless provider, not a silent call to a paid API. Whether that default is right for production is a decision for your team. Some teams prefer to fail loudly when the variable is missing. ProviderErroris defined here because adapters raise it. The retry and fallback chapters use itsretryableflag.
Switching without changing call sites
Application code receives the provider and never asks which one it is.
def run() -> None:
provider = get_provider()
print(summarize(provider, "A long article about tides."))With LLM_PROVIDER=fake this prints the fake's reply. With LLM_PROVIDER=openai and the adapter registered, the same summarize function runs against that provider. Neither run nor summarize changed.
The model string in ChatRequest is a related problem. Model names are provider-specific, so "gpt-4o" means nothing to another vendor. Configuration should therefore carry the model name too, not only the provider name. The next section shows one way to do that.
Configuration beyond the provider name
A provider name alone is rarely enough. You usually also need a model, an API key, and sometimes a base URL or timeout. Put these in a small settings object so they travel together.
import os
from dataclasses import dataclass
@dataclass
class LLMSettings:
provider: str
model: str
api_key: str | None = None
timeout_s: float = 30.0
def load_settings() -> LLMSettings:
return LLMSettings(
provider=os.environ.get("LLM_PROVIDER", "fake"),
model=os.environ.get("LLM_MODEL", "any"),
api_key=os.environ.get("LLM_API_KEY"),
timeout_s=float(os.environ.get("LLM_TIMEOUT_S", "30")),
)Then let each registry entry accept the settings. This changes the registry from zero-argument lambdas to functions of LLMSettings.
SETTINGS_REGISTRY = {
"fake": lambda s: FakeProvider(),
# "openai": lambda s: OpenAIAdapter(api_key=s.api_key, timeout=s.timeout_s),
# "anthropic": lambda s: AnthropicAdapter(api_key=s.api_key, timeout=s.timeout_s),
}
def build_provider(settings: LLMSettings) -> ChatProvider:
try:
factory = SETTINGS_REGISTRY[settings.provider]
except KeyError:
known = ", ".join(sorted(SETTINGS_REGISTRY))
raise ValueError(
f"Unknown provider: {settings.provider!r}. Known: {known}"
) from None
return factory(settings)Listing the known names in the error message saves a trip to the source when someone mistypes a value. The from None removes the confusing KeyError from the traceback.
Where the model name goes
Call sites currently build ChatRequest(model="any", ...). A hard-coded model name defeats the point of configuration. Pass the model from settings into the code that builds requests.
def summarize_configured(
provider: ChatProvider, settings: LLMSettings, text: str
) -> str:
request = ChatRequest(
model=settings.model,
messages=[Message("user", f"Summarize: {text}")],
)
return provider.complete(request).textNow switching from one vendor to another means changing two environment variables, LLM_PROVIDER and LLM_MODEL. Keep them consistent. A provider name paired with another vendor's model name is a common mistake, and it produces an error from the provider at request time.
Validate at startup
A typo in configuration should fail when the program starts, not on the first user request. Two cheap checks help.
- Look up the provider name in the registry during startup, which
build_provideralready does. - Check that required values, such as an API key for a real provider, are present before building the adapter.
def build_validated(settings: LLMSettings) -> ChatProvider:
if settings.provider != "fake" and not settings.api_key:
raise ValueError(
f"LLM_API_KEY is required for provider {settings.provider!r}"
)
return build_provider(settings)You can hide the key from repr like this:
from dataclasses import dataclass, field
@dataclass
class SafeSettings:
provider: str
model: str
api_key: str | None = field(default=None, repr=False)Choosing between a registry and alternatives
The registry is not the only way to select a provider. The table compares common options.
| Approach | Strength | Weakness |
|---|---|---|
| `if/elif` chain in the factory | Simple for two providers | Grows messy, easy to duplicate elsewhere |
| Registry dictionary | One place to add a provider, easy to test | Names are strings, so typos appear at runtime |
| Plugin discovery (entry points) | Third parties add providers without editing your code | More machinery, harder to debug |
| Dependency injection container | Fits large applications | Heavy for a small tool |
For most applications, the registry is the right size. Move to entry points only if outside packages need to register providers.
Edge cases and common errors
- Lazy imports. If an adapter module imports a vendor SDK at the top, importing the registry module imports every SDK. Import inside the factory function instead, so an uninstalled SDK only fails when that provider is chosen.
- Reading configuration too late. Calling
os.environ.getdeep inside call sites scatters the choice again. Read configuration once and pass the result down. - Caching.
get_provider()builds a new object each call. For adapters that hold an HTTP client, build one at startup and reuse it, because creating a client per request wastes connections. - Case and whitespace.
"OpenAI"and"openai "will not match a registry key. Normalize with.strip().lower()when you read the value. - Mismatched model. The registry cannot know whether
LLM_MODELis valid for the chosen provider. Treat a bad model name as a provider error and surface it clearly.
A lazy import inside a factory looks like this:
def make_openai(settings: LLMSettings) -> ChatProvider:
from my_app.adapters.openai_adapter import OpenAIAdapter # imported on use
return OpenAIAdapter(api_key=settings.api_key, timeout=settings.timeout_s)
# SETTINGS_REGISTRY["openai"] = make_openaiThe module path my_app.adapters.openai_adapter is a placeholder for wherever your adapter lives.
Testing the selection logic
Selection is plain code, so test it directly. Setting the environment in a test avoids touching real services.
import os
def test_unknown_provider_is_rejected():
settings = LLMSettings(provider="nope", model="x")
try:
build_provider(settings)
except ValueError as err:
assert "nope" in str(err)
else:
raise AssertionError("expected ValueError")
def test_default_is_fake():
os.environ.pop("LLM_PROVIDER", None)
assert isinstance(get_provider(), FakeProvider)The second test shows why a fake registered under a known name is useful. Tests can select it through the same configuration path that production uses.
Exercise
Your service reads LLMPROVIDER=anthropic but LLMMODEL is still set to a model name from another vendor. The factory builds the adapter without error. Where does the problem show up, and what is one way to catch it sooner?
Show answer
It shows up at request time, when the provider rejects the unknown model, because the registry only checks the provider name. To catch it sooner, keep a per-provider list of allowed model names (or a name prefix check) and validate settings.model at startup, or send a cheap test request during startup.
Exercise
Why do the registry values in this chapter use lambdas or functions instead of storing provider instances directly?
Show answer
Instances would be built at import time for every provider, which needs API keys and installed SDKs even for providers that are not selected. Factories delay construction until a provider is chosen.