Configure Provider Clients
One Place That Creates the Client
Once a platform is chosen (Lesson 165), the application still has to create the right client, with the right settings, wherever it needs one. In a small script, that is one line. In a larger application, the same client is created in several modules, and each copy of the setup is another place where a setting can drift: one module uses a timeout of sixty seconds, another uses the default, and a third forgot the region entirely.
The remedy is a single factory. Configuration is read once, validated once, and a client is produced from it wherever the application needs one. This lesson builds that factory, explains why the configuration is kept separate from the client, and shows how the same code can serve the direct API and each cloud. The factory is also where the settings from earlier lessons, such as timeouts and retry counts (Lessons 143 and 144), are applied consistently.
Configuration Separate From Creation
The factory has two steps, and keeping them apart makes both easier to test. The first step turns a configuration into a set of constructor arguments, which is pure data and can be checked without any network or SDK. The second step passes those arguments to the client class, which is the only part that touches the SDK. Tests exercise the first step thoroughly, and the second only needs a few checks.
configuration ──► constructor arguments ──► client
(data, checked) (data, checked) (the SDK)
Every platform-specific rule lives in the first step. The second step is a single line per provider, which means the rules cannot be bypassed by creating a client directly somewhere else.
The Settings Every Client Shares
Some settings apply to every provider: the timeout, which bounds each request (Lesson 144), and the retry count, which decides how many automatic retries the SDK makes (Lesson 143). Setting them in one place keeps the whole application consistent. A team that changes its timeout changes one value, and every client follows.
The provider-specific settings differ: a region for Bedrock, a project and region for Vertex, and a resource name for Foundry. The configuration holds those values too, and the constructor step requires the ones each provider needs.
The Factory
The factory below reads a configuration, builds the constructor arguments, and creates the client. The SDK classes are imported inside the function that needs them, so the configuration logic can be tested on a machine that has only some of the cloud extras installed:
"""provider_clients.py: one factory for every integration, with validation before creation."""
from dataclasses import dataclass
@dataclass(frozen=True)
class ProviderConfig:
provider: str
region: str | None = None
project_id: str | None = None
resource: str | None = None
timeout: float = 60.0
max_retries: int = 2
def constructor_kwargs(config: ProviderConfig) -> dict:
kwargs = {"timeout": config.timeout, "max_retries": config.max_retries}
if config.provider == "bedrock":
if not config.region:
raise ValueError("bedrock needs a region")
kwargs["aws_region"] = config.region
elif config.provider == "vertex":
if not config.project_id or not config.region:
raise ValueError("vertex needs project_id and region")
kwargs.update(project_id=config.project_id, region=config.region)
elif config.provider == "foundry":
if not config.resource:
raise ValueError("foundry needs a resource name")
kwargs["resource"] = config.resource
elif config.provider != "direct":
raise ValueError(f"unknown provider {config.provider}")
return kwargs
def make_client(config: ProviderConfig):
kwargs = constructor_kwargs(config)
if config.provider == "direct":
from anthropic import Anthropic
return Anthropic(**kwargs)
if config.provider == "bedrock":
from anthropic import AnthropicBedrock
return AnthropicBedrock(**kwargs)
if config.provider == "vertex":
from anthropic import AnthropicVertex
return AnthropicVertex(**kwargs)
from anthropic import AnthropicFoundry
return AnthropicFoundry(**kwargs)
if __name__ == "__main__":
configs = [
ProviderConfig("direct"),
ProviderConfig("bedrock", region="us-east-1"),
ProviderConfig("vertex", project_id="my-project-id", region="global"),
ProviderConfig("foundry", resource="acme-claude"),
ProviderConfig("bedrock"),
]
for config in configs:
try:
print(f"{config.provider}: {constructor_kwargs(config)}")
except ValueError as error:
print(f"{config.provider}: error: {error}")
Output:
direct: {'timeout': 60.0, 'max_retries': 2}
bedrock: {'timeout': 60.0, 'max_retries': 2, 'aws_region': 'us-east-1'}
vertex: {'timeout': 60.0, 'max_retries': 2, 'project_id': 'my-project-id', 'region': 'global'}
foundry: {'timeout': 60.0, 'max_retries': 2, 'resource': 'acme-claude'}
bedrock: error: bedrock needs a region
How It Works
- The configuration is immutable. The frozen dataclass cannot be changed after it is created, so a setting cannot drift while the application runs.
constructor_kwargs()holds the platform rules. Each provider's required values are checked, and a missing value raises an error that names the problem. The fifth configuration, a Bedrock client with no region, is rejected here, before any client exists.- The shared settings come first in the arguments, so every provider receives the same timeout and retry count unless the configuration says otherwise.
make_client()imports the SDK class only when it is needed. A machine without the Vertex extra can still run the configuration logic and its tests, because the Vertex import happens only on the Vertex path.- Errors are raised as
ValueError, which the caller can catch at startup and report, so a misconfiguration stops the program before it serves a request.
Creating Clients Once
A client holds connections and configuration, and creating one per request wastes effort. The factory's output should normally be created once when the application starts, and shared by the code that needs it. Lesson 79 covered closing clients, and the same care applies here: a shared client is closed when the application shuts down, not after each use.
Testing the Factory
The configuration step is pure, so it can be tested directly: each provider with valid settings returns the expected arguments, and each missing value raises the expected error. The client creation step needs only a smoke test per provider, which confirms that the class is constructed with the arguments the factory produced. Separating the two keeps most of the testing fast and free of credentials.
Summary
A single factory keeps client creation consistent across an application. Configuration is validated and turned into constructor arguments, which is data that tests can check without any SDK. The shared timeout and retry settings apply to every provider, and each provider's required values are enforced in one place. Clients are created once and shared. The next lesson covers the errors that cloud integrations return, which need their own handling on top of the shared classes.