方寸 Portal

AI Engineer Portal

Your personal operating system for career transition.

Private mode

Exercise

Build a multi-provider failover chain

Implement a ProviderFailoverChain that:

  1. Takes a list of provider callables (async functions with signature async (messages: list[dict]) -> str)
  2. complete(messages: list[dict]) -> tuple[str, int] — tries providers in order, returns (response, provider_index) for the first one that succeeds
  3. Skips providers whose circuit breaker is open (use a simple in-memory circuit breaker: open after 3 consecutive failures, auto-reset after 60 seconds)
  4. Raises RuntimeError("all providers exhausted") if every provider fails or has an open circuit
  5. Tracks which provider was last used and how many times each provider has been called

Demonstrate with a test where provider 0 always raises an exception, provider 1 succeeds.

import asyncio
import time

async def provider_always_fails(messages):
    raise ConnectionError("Provider 0 is down")

async def provider_always_succeeds(messages):
    return "Hello from provider 1"

Deployment / medium / Step 5 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.