方寸 Portal

AI Engineer Portal

Your personal operating system for career transition.

Private mode

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:

  1. Defines a GenerateRequest modelprompt: str, model: str, max_tokens: int, temperature: float, request_id: str.
  2. Defines a GenerateResponse modelrequest_id: str, text: str, model: str, input_tokens: int, output_tokens: int, latency_ms: int.
  3. Defines an abstract LLMProvider base class — with an abstract async def generate(self, request: GenerateRequest) -> GenerateResponse method and a provider_name: str property.
  4. Implements MockProvider — returns a deterministic fake response based on the prompt hash. Useful for tests.
  5. Implements FallbackProvider — wraps a primary and fallback provider. Tries primary first; on any exception, logs the failure and retries with fallback.
  6. Writes a ProviderRegistry — maps provider names to instances. get(name) -> LLMProvider raises 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

  • LLMProvider must be an abstract base class (abc.ABC).
  • FallbackProvider must log a warning when it falls back, including which provider failed and the error.
  • MockProvider must be deterministic: the same prompt always returns the same text.

Python Ai / medium / Step 4 of 6

Practice stage

General drill

Hint

Keep the solution explicit and reviewable.

Success criteria

Make the solution explicit, debuggable, and easy to explain.

Review checklist

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.