AI Engineer Portal
Your personal operating system for career transition.
Exercise
Build a type-safe provider abstraction layer
Build a Type-Safe Provider Abstraction Layer
Application code that calls OpenAI directly becomes brittle when you add Anthropic as a fallback, switch to a local model for development, or need to mock provider calls in tests. An abstraction layer with a shared interface and typed contracts solves all three.
What to build
Design a provider abstraction that:
- Defines a
GenerateRequestmodel —prompt: str,model: str,max_tokens: int,temperature: float,request_id: str. - Defines a
GenerateResponsemodel —request_id: str,text: str,model: str,input_tokens: int,output_tokens: int,latency_ms: int. - Defines an abstract
LLMProviderbase class — with an abstractasync def generate(self, request: GenerateRequest) -> GenerateResponsemethod and aprovider_name: strproperty. - Implements
MockProvider— returns a deterministic fake response based on the prompt hash. Useful for tests. - Implements
FallbackProvider— wraps aprimaryandfallbackprovider. Tries primary first; on any exception, logs the failure and retries with fallback. - Writes a
ProviderRegistry— maps provider names to instances.get(name) -> LLMProviderraises a clear error if the provider is not registered.
Why this matters
This pattern isolates all vendor-specific code behind a stable interface. Tests use MockProvider. Development can use a local model. Production uses a hosted API. The FallbackProvider adds resilience without touching application code.
Constraints
LLMProvidermust be an abstract base class (abc.ABC).FallbackProvidermust log a warning when it falls back, including which provider failed and the error.MockProvidermust be deterministic: the same prompt always returns the same text.
Python Ai / medium / Step 4 of 6
General drill
Keep the solution explicit and reviewable.
Make the solution explicit, debuggable, and easy to explain.
Review where the boundary is, what gets validated, and what would be hard to debug later.
Practice
Generate a variation
Generate a new exercise variation to deepen understanding or practice a related concept.
Attempt history
Recent submissions
Before you submit, decide what a strong answer should make obvious to the reviewer.
No attempts yet.