Sub topic 15
Design so the model can be swapped
This chapter assumes you can call an HTTP API or SDK, read basic Python, and know what a prompt, token, and context window are. It also assumes you have read the earlier chapters on hosted APIs, open-weight models, and evaluation. Here you will design an application so that changing the model is a configuration change and a test run, not a rewrite.
Why swappability matters
The model you pick today will not be the model you run in a year. Hosted providers retire model versions, change prices, and release better options. Open-weight releases arrive every few months. Your requirements also change: traffic grows, a customer demands that data stay in their region, or a smaller model turns out to be good enough.
If model names, endpoints, and provider-specific details are scattered through your code, each of these changes becomes a project. If they live in one place, each becomes a small edit. This is the "portability" benefit named in the earlier trade-off chapters, and it works for both hosted and self-hosted setups.
Where lock-in hides
Lock-in is rarely one big dependency. It is a pile of small ones. Check for these:
| Source of lock-in | Example | How to reduce it |
|---|---|---|
| Hard-coded model name | `model="some-model-v1"` in ten files | Read it from configuration |
| Hard-coded endpoint | A provider URL inside business logic | Read the base URL from configuration |
| Provider-specific SDK types | Passing vendor response objects through your app | Return plain strings or your own types |
| Prompts tuned to one model | Phrasing that only one model follows | Keep prompts in one place and re-test them on change |
| Provider-only features | Special tool-call formats or caching options | Wrap them and list them as known dependencies |
| Context window assumptions | Prompts sized for a 128k window | Store the limit per model and check it |
| Tokenizer differences | Cost estimates based on one tokenizer | Treat token counts as approximate for other models |
The prompt row is the one that surprises people most. A prompt is part of the interface to the model. A different model can respond to the same text in a different format or with different quirks, so a swap needs a test run, not just a changed string.
The thin interface pattern
The simplest design is a single function that the rest of your application calls. All provider details stay behind it. This chapter's third code example does this with an OpenAI-compatible client, because many hosted providers and local servers such as Ollama and vLLM expose that same style of endpoint.
import os
from openai import OpenAI
# The same client code can target a hosted API or a self-hosted server that
# exposes an OpenAI-compatible endpoint (for example Ollama or vLLM).
client = OpenAI(
base_url=os.environ["LLM_BASE_URL"],
api_key=os.environ.get("LLM_API_KEY", "not-needed-for-local"),
)
MODEL = os.environ["LLM_MODEL"]
def ask(prompt: str) -> str:
response = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": prompt}],
temperature=0,
)
return response.choices[0].message.contentThree decisions make this swappable:
- The endpoint, key, and model name come from environment variables, so switching from a hosted API to a local server changes the environment, not the code.
- The function takes a string and returns a string. Callers never see a vendor object.
- The call sits in one function, so there is exactly one place to change if you adopt a different SDK.
A swap then looks like this:
# Hosted provider (example values)
# LLM_BASE_URL=https://api.example-provider.com/v1
# LLM_API_KEY=...your key...
# LLM_MODEL=provider-large
# Local server (example values)
# LLM_BASE_URL=http://localhost:11434/v1
# LLM_MODEL=a-7b-instruct-modelThe values above are placeholders. Use the base URL and model identifier that your provider or server documents.
Compatible does not mean identical
An OpenAI-compatible endpoint accepts the same request shape. It does not guarantee the same behavior. Expect differences in these areas:
- Supported parameters. Some servers ignore or reject options such as
temperature, stop sequences, or log probabilities. - Structured output and tool calls. Support for JSON modes and function calling varies by model and server. A model that was never trained for tool calls can accept the request and still return unusable output.
- Error codes and rate limits. A hosted API returns rate-limit errors. A local server may simply slow down or run out of memory.
- Token counting. Different model families split text into tokens differently. The same prompt can be a different number of tokens, which changes both cost and how much fits in the context window.
- Determinism. Even with
temperature=0, outputs can differ between runs on some serving stacks.
Treat compatibility as a way to avoid rewriting client code. Treat your evaluation set as the way to learn whether behavior still holds.
Keep model facts in configuration
A single environment variable for the model name is a start. A model also has properties that your application may depend on. Put them in a small configuration structure rather than scattering constants.
from dataclasses import dataclass
@dataclass(frozen=True)
class ModelConfig:
name: str
base_url: str
context_window: int # tokens
max_output_tokens: int
price_in_per_million: float # 0.0 for self-hosted
price_out_per_million: float
MODELS = {
"large": ModelConfig("provider-large", "https://api.example-provider.com/v1",
128_000, 4_096, 1.00, 4.00),
"small": ModelConfig("a-7b-instruct-model", "http://localhost:11434/v1",
32_000, 2_048, 0.0, 0.0),
}
def fits(config: ModelConfig, prompt_tokens: int, reserved_output: int) -> bool:
return prompt_tokens + reserved_output <= config.context_window
print(fits(MODELS["small"], 30_000, 2_048)) # True
print(fits(MODELS["small"], 31_000, 2_048)) # FalseThe prices and sizes are made up for illustration. With this structure, the cost estimate from the earlier chapter and the context check both read from the same record. Adding a candidate means adding one entry.
Use your evaluation set as the swap gate
Portability in code is only half the work. The other half is knowing that the new model is acceptable. The pass-rate check from the evaluation chapter doubles as a regression test.
cases = [
{"prompt": "Extract the invoice number: 'Invoice INV-2041, due May 3'", "expected": "INV-2041"},
{"prompt": "Extract the invoice number: 'Ref: INV-17, total $90'", "expected": "INV-17"},
]
def pass_rate(ask_fn, cases) -> float:
passed = sum(1 for c in cases if c["expected"] in ask_fn(c["prompt"]))
return passed / len(cases)
# Run the same cases against each candidate and compare, e.g.:
# print(pass_rate(ask_small, cases), pass_rate(ask_large, cases))A workable swap procedure:
- Add the candidate to your configuration.
- Run the evaluation set against the current model and the candidate.
- Compare pass rates, and also compare latency and estimated cost.
- If the candidate meets your thresholds, release it to a small share of traffic first.
- Keep the old configuration so you can roll back by changing a setting.
Two cases are too few for a real decision. Use enough examples to cover your typical inputs and your known hard ones. Re-run the set whenever a hosted provider announces a model update, because a version alias can start pointing at different weights.
Pin versions and plan for deprecation
Many hosted providers offer a floating alias such as "latest" and also dated, fixed versions. A floating alias can change behavior without any change on your side. For production, prefer a pinned version, and record it in configuration and in your logs. Then a change in output quality can be traced to a change in model.
Providers also retire old versions on a published schedule. Add the retirement date to your tracking so that the swap happens on your timeline and not during an outage. For self-hosted models, the equivalent is to record the exact weights file or checkpoint and its quantization level, since a 4-bit version of a model can behave differently from the 16-bit one.
Fallbacks use the same seam
Once the model is behind one function, a fallback is a short addition. If the primary call fails with a timeout or rate-limit error, try a second configured model.
def ask_with_fallback(prompt: str, primary, secondary) -> str:
try:
return primary(prompt)
except Exception:
return secondary(prompt)In real code, catch the specific exceptions your SDK raises instead of Exception, and log each fallback so you can see how often it happens. A fallback model needs to pass your evaluation set too, or it will fail quietly when it is needed. The next chapter covers routing between small and large models, which builds on this same interface.
What not to abstract
Swappability has a cost. A large abstraction layer that supports every provider adds code to maintain and can hide features you want. Keep the seam thin: one function, one configuration record, one evaluation set. Do not build support for providers you have no plan to use. If you do need to use a provider-specific feature, such as a caching option that cuts cost, use it, wrap it in your interface, and note it as a dependency so you know what a swap will cost.
Summary of the design
- Read endpoint, key, and model name from configuration.
- Expose one function that takes and returns plain types.
- Store per-model facts such as context window and prices in one record.
- Gate every change with your own evaluation set.
- Pin model versions and track deprecation dates.
- Keep the abstraction thin.
Exercise
Your team switches from a hosted model to a self-hosted model that exposes an OpenAI-compatible endpoint. You change only the environment variables, and the application starts without errors. List three things you should still check before sending real traffic to it, and say why.
Show answer
Any three of the following. (1) Run your evaluation set, because the prompts were tuned to the old model and output quality can differ even when requests succeed. (2) Check structured output and tool-call behavior, because support varies by model and server and a request can succeed while returning unusable output. (3) Re-check context limits and token counts, because a different tokenizer and context window change how much fits and what a request costs. (4) Check latency and error behavior under load, because a local server can slow down or run out of memory instead of returning rate-limit errors. (5) Confirm which parameters the server honors, such as temperature and stop sequences.
Exercise
A provider's "latest" alias is used in production, and output quality drops one week with no code change on your side. What likely happened, and what two practices would have made this easier to diagnose or prevent?
Show answer
The alias probably began pointing at a newer model version with different behavior. Pinning a dated model version in configuration prevents the silent change. Logging the exact model version with each request, and re-running your evaluation set when a provider announces an update, lets you trace and catch the change.