DEV Community

Cover image for How to Build a Reliable Multi-Model API Client in Python
4sapi
4sapi

Posted on

How to Build a Reliable Multi-Model API Client in Python

1. Why Multi-Model Applications Need a Separate API Layer

A common mistake in AI application development is treating model access as a collection of isolated API calls.

A prototype may start with one model. A few weeks later, the development team wants to test another provider, compare reasoning performance, or introduce a cheaper model for routine requests.

Suddenly, model configuration is scattered throughout the codebase.

One module contains a provider URL. Another contains a model identifier. A third implements its own timeout and retry logic.

This architecture becomes difficult to maintain.

A more scalable approach is to create a model-access layer that separates application logic from provider configuration.

2. Separate Model Configuration from Business Logic

Consider this configuration:

import os

MODELS = {
    "reasoning": {
        "base_url": os.getenv("REASONING_BASE_URL"),
        "api_key": os.getenv("REASONING_API_KEY"),
        "model": os.getenv("REASONING_MODEL")
    },
    "fast": {
        "base_url": os.getenv("FAST_BASE_URL"),
        "api_key": os.getenv("FAST_API_KEY"),
        "model": os.getenv("FAST_MODEL")
    }
}
Enter fullscreen mode Exit fullscreen mode

This configuration allows the application to choose a model by role.

For example:

  • Reasoning tasks can use a model configured for complex analysis.
  • Classification can use a faster model.
  • Summarization can use a model with an appropriate cost and latency profile.

Application code should not need to know every provider's configuration.

3. Create a Reusable API Client

For providers supporting the OpenAI-compatible Chat Completions format, a common request structure can reduce integration work.

Install the SDK:

pip install openai python-dotenv
Enter fullscreen mode Exit fullscreen mode

Implement a reusable client:

from openai import OpenAI

class ModelClient:

    def __init__(self, config):
        self.client = OpenAI(
            api_key=config["api_key"],
            base_url=config["base_url"],
            timeout=30,
            max_retries=0
        )

        self.model = config["model"]

    def generate(self, prompt):

        response = self.client.chat.completions.create(
            model=self.model,
            messages=[
                {
                    "role": "user",
                    "content": prompt
                }
            ],
            temperature=0.3
        )

        return response.choices[0].message.content
Enter fullscreen mode Exit fullscreen mode

The application now has a reusable interface.

reasoning_client = ModelClient(
    MODELS["reasoning"]
)

answer = reasoning_client.generate(
    "Explain how vector databases support RAG."
)

print(answer)
Enter fullscreen mode Exit fullscreen mode

This example assumes the selected endpoint supports the Chat Completions request format and parameters. Compatibility should be verified rather than inferred from the SDK alone.

4. Implement Explicit Retry Handling

An API request can fail because of:

  • Temporary network problems.
  • Request timeouts.
  • Rate limits.
  • Provider capacity restrictions.
  • Authentication errors.
  • Invalid request parameters.

Not every error should be retried.

A 401 authentication error, for example, is unlikely to be resolved by sending the same request again.

A basic retry function:

import time
import random

def retry_request(request_fn, max_attempts=4):

    for attempt in range(max_attempts):

        try:
            return request_fn()

        except Exception as error:

            if attempt == max_attempts - 1:
                raise

            delay = min(
                2 ** attempt + random.random(),
                20
            )

            print(
                f"Retrying in {delay:.2f}s: {error}"
            )

            time.sleep(delay)
Enter fullscreen mode Exit fullscreen mode

For production use, classify exceptions before retrying. Retry transient connection failures, timeouts, and eligible rate-limit or server errors. Respect Retry-After when provided.

Also consider retrying only idempotent operations or requests protected by an appropriate idempotency strategy.

5. Introduce Model Fallback

What happens when the primary model is unavailable?

A fallback mechanism can improve application resilience, provided the alternative model supports the task.

def generate_with_fallback(
    prompt,
    primary,
    fallback
):

    try:
        return primary.generate(prompt)

    except Exception as primary_error:

        print(
            "Primary model failed:",
            primary_error
        )

        return fallback.generate(prompt)
Enter fullscreen mode Exit fullscreen mode

However, model fallback introduces a subtle problem: different models may interpret the same prompt differently.

One model may support a specific tool-calling format while another expects different parameter names.

A fallback strategy should therefore include compatibility checks, not just an alternate API key.

6. Build a Model Router

A simple router can choose a model based on task type.

def route_task(task_type):

    routing_table = {
        "reasoning": "reasoning",
        "classification": "fast",
        "summarization": "fast",
        "coding": "reasoning"
    }

    return routing_table.get(
        task_type,
        "reasoning"
    )
Enter fullscreen mode Exit fullscreen mode

Then:

task = "classification"

model_name = route_task(task)

client = ModelClient(
    MODELS[model_name]
)
Enter fullscreen mode Exit fullscreen mode

A more advanced router could evaluate:

  • Maximum context length.
  • Tool-calling compatibility.
  • Structured output support.
  • Latency requirements.
  • Token budget.
  • Provider availability.

7. Monitor Model Performance

A router without observability is difficult to improve.

At minimum, record:

import time

def measured_call(client, prompt):

    start = time.perf_counter()

    try:
        result = client.generate(prompt)

        elapsed = time.perf_counter() - start

        return {
            "success": True,
            "latency": elapsed,
            "result": result
        }

    except Exception as error:

        elapsed = time.perf_counter() - start

        return {
            "success": False,
            "latency": elapsed,
            "error": str(error)
        }
Enter fullscreen mode Exit fullscreen mode

In production, collect:

  • Request latency.
  • Error rate.
  • Token usage.
  • Model selection.
  • Retry count.
  • Fallback frequency.
  • Request identifiers.

Avoid logging API keys or sensitive prompts.

8. A Practical Multi-Model Architecture

A maintainable implementation should have four separate layers:

  1. Application logic.
  2. Model routing.
  3. Provider adapter.
  4. API access infrastructure.

For development teams testing multiple model families, 4SAPI can simplify the management of supported model access through a common API gateway.

The application still decides which model is appropriate. The gateway handles the configured access layer.

Conclusion

Multi-model applications become easier to maintain when model configuration, routing, and provider-specific behavior are separated from business logic.

The important step is not simply adding more API keys. It is designing an architecture that can handle model changes, temporary failures, and different request capabilities without requiring modifications throughout the application.

References

Top comments (0)