Preloader
Others
  • Estimated reading time: 4 Minutes

Building a Model-Agnostic LLM Client in Python: Config, Fallbacks, and Cost Logging

Building a Model-Agnostic LLM Client in Python: Config, Fallbacks, and Cost Logging

If you've shipped anything that calls a large language model, you've probably hard-coded a model name somewhere and later regretted it. Models get deprecated, prices change, a newer model turns out to be better at your task, or the provider has a bad afternoon and your app goes down with it.

This tutorial walks through a small, practical pattern for keeping your code model-agnostic: one client, models chosen by configuration, a fallback chain for failures, and per-request usage logging. The examples use Python and the openai SDK, because the OpenAI-compatible Chat Completions format is now supported by many providers, gateways, and local servers.

Step 1: Move everything model-specific into config

The first rule is that your application code shouldn't know which model it's talking to. Put the endpoint, key, and model names in environment variables or a config file.

# config.py
import os

BASE_URL = os.environ["LLM_BASE_URL"]          # any OpenAI-compatible endpoint
API_KEY = os.environ["LLM_API_KEY"]

# Map tasks to an ordered list of models (first = preferred)
MODEL_ROUTES = {
    "summarize": os.environ.get("LLM_SUMMARIZE", "small-fast-model,medium-model").split(","),
    "code_review": os.environ.get("LLM_CODE_REVIEW", "large-model,medium-model").split(","),
}

Notice the routes are keyed by task, not by model. Your code asks for "summarize," and configuration decides what that means today.

Step 2: A thin client wrapper

Next, wrap the SDK so the rest of your code never touches it directly.

# llm.py
import time
import logging
from openai import OpenAI, APIError, APITimeoutError, RateLimitError
from config import BASE_URL, API_KEY, MODEL_ROUTES

client = OpenAI(base_url=BASE_URL, api_key=API_KEY, timeout=60)
log = logging.getLogger("llm")

RETRYABLE = (APITimeoutError, RateLimitError, APIError)

def complete(task: str, messages: list[dict], **kwargs) -> str:
    last_error = None
    for model in MODEL_ROUTES[task]:
        start = time.monotonic()
        try:
            resp = client.chat.completions.create(
                model=model, messages=messages, **kwargs
            )
        except RETRYABLE as e:
            last_error = e
            log.warning("model=%s task=%s failed: %s", model, task, e)
            continue
        elapsed = time.monotonic() - start
        usage = resp.usage
        log.info(
            "model=%s task=%s in=%d out=%d secs=%.2f",
            model, task, usage.prompt_tokens, usage.completion_tokens, elapsed,
        )
        return resp.choices[0].message.content
    raise RuntimeError(f"All models failed for task {task}") from last_error

A few deliberate choices here:

  • Fallback, not blind retry. If the preferred model times out or is rate-limited, we try the next model in the route instead of hammering the same one.
  • Usage logging on every call. Token counts per task and per model are the raw material for cost analysis later.
  • A single exit for failure. Callers get one clear exception when everything fails, which is easier to handle than a dozen provider-specific errors.

Step 3: Use it from application code

from llm import complete

summary = complete(
    "summarize",
    [
        {"role": "system", "content": "Summarize the text in three bullet points."},
        {"role": "user", "content": article_text},
    ],
    max_tokens=300,
)

Your feature code now has no idea which model produced the summary, and that's exactly the point. Switching from one model to another is an environment variable change and a redeploy, not a refactor.

Step 4: Turn logs into cost numbers

Once you're logging in and out tokens per model, you can estimate spend with a small lookup table of per-token rates. Keep that table in config too, and update it when your provider's prices change.

RATES_PER_MILLION = {  # fill in from your provider's current price list
    "small-fast-model": {"in": 0.0, "out": 0.0},
    "large-model": {"in": 0.0, "out": 0.0},
}

def estimate_cost(model: str, tokens_in: int, tokens_out: int) -> float:
    r = RATES_PER_MILLION[model]
    return (tokens_in * r["in"] + tokens_out * r["out"]) / 1_000_000

Aggregate by task each week and you'll quickly see which features are expensive and whether a cheaper model would do. If you route through a gateway, check whether it already reports this: some, like OpenLux, publish per-model rates and show the model, tokens, and cost for each request in the console, which saves you maintaining the rate table yourself.

Step 5: Test with a fake endpoint

Because everything goes through LLM_BASE_URL, you can point tests at a local mock server that implements the same API shape and returns canned responses. That keeps your test suite fast, free, and deterministic.

Things to watch out for

  • Not every provider supports every parameter. Features like tool calling, JSON mode, or vision inputs vary. Keep per-model capability flags in config if you rely on them.
  • Prompts aren't perfectly portable. A prompt tuned for one model may behave differently on another. Keep a small evaluation set and run it whenever you change a route.
  • Streaming adds complexity. If you stream responses, your fallback logic needs to handle failures mid-stream, typically by only falling back before the first token arrives.
  • Anthropic-format clients. Some tools, like Claude Code, speak the Anthropic Messages API instead. If you use both, keep two thin wrappers behind the same task interface.

Wrapping up

Model-agnostic code doesn't require a framework. A config-driven route table, a thin wrapper with fallbacks, and honest usage logging will cover most production needs. The payoff is flexibility: when the next model comes out, or the current one has a bad day, you change a line of configuration instead of your codebase.

Related articles
Best Online Converters Every Software Developer Needs
6 Dec, 2026
  • Estimated reading time: 6 Minutes
What Is Missed Call Text Back and How Does It Work?
6 Dec, 2026
  • Estimated reading time: 6 Minutes
How Blue30 order fulfilment works when a promotion takes off
6 Dec, 2026
  • Estimated reading time: 3 Minutes
Best Facebook Video Downloaders for Linux Users in 2027
6 Dec, 2026
  • Estimated reading time: 6 Minutes
Weekly trending
Best Online Converters Every Software Developer Needs
6 Dec, 2026
  • Estimated reading time: 6 Minutes
What Is Missed Call Text Back and How Does It Work?
6 Dec, 2026
  • Estimated reading time: 6 Minutes
How Blue30 order fulfilment works when a promotion takes off
6 Dec, 2026
  • Estimated reading time: 3 Minutes
Our Sponsors

Our blog is proudly supported by industry-leading sponsors.