Compare Three LLM APIs With One Python Script and a Test You Can Score
When a model returns a plausible-looking answer, it can still fail the contract your application depends on. Imagine a support workflow that expects {"intent":"billing","urgent":false}.
One model returns that object. Another puts it in a Markdown fence. A third returns "false" as a string. They look similar in a chat window, but only one passes a strict parser.
In Python, bool("false") is True. Silently coercing the result can route tickets to the wrong queue.
Here's a small test that separates three questions: did the HTTP request succeed, did the answer match the required shape, and did the model make the right decision? It uses synthetic tickets, a fixed rubric, and nothing outside Python's standard library.
The example uses AIWave, which I operate. You can use the same script with another endpoint that implements OpenAI-style /chat/completions by changing the base URL, credential and model IDs. AI was used to help prepare this article.
1. Define the decision before you run a model
The task is deliberately narrow: classify a support ticket as billing, access, or other. Mark it urgent only if a production service is currently down.
A demo scheduled for tomorrow is not urgent under this rule. A live checkout failure is urgent even if the ticket never says "urgent." If your real queue uses a different policy, change the prompt and the expected labels together.
There are three independent pass criteria:
- Transport: The API returns a response the client can read. A 429 is an availability observation, not a wrong label.
- Format: The message is a JSON object with exactly two keys.
intentmust be one of three strings, andurgentmust be a JSON boolean. Extra prose, extra keys and string booleans fail. - Decision: The two values match a label picked before the request. A well-formed but wrong answer is still wrong for this workflow.
The fixtures below include an explicit urgency cue that should be ignored, a live incident described without an urgency keyword, and a billing case. That catches a few simple shortcuts. It doesn't make three tickets a representative data set. The sample is a smoke test for a contract, not a model leaderboard.
2. Run the same cases against each model
Use Python 3.8 or later. Set LLM_API_KEY in your local environment. Set LLM_BASE_URL to the API base, including /v1 if your provider uses it. Set LLM_MODEL_IDS to a comma-separated list of exact model IDs.
If you're using AIWave, the concrete values and account entry are at the end. Point these variables at a test credential and verify the provider's rates before running; this script sends one request per model per case.
Save this as compare_models.py and run python compare_models.py:
import json
import os
import time
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
CASES = [
("invoice", "My invoice includes two charges for the same order.", {"intent": "billing", "urgent": False}),
("demo_access", "URGENT: I forgot my password for a demo tomorrow.", {"intent": "access", "urgent": False}),
("checkout_down", "Live checkout is down and customers cannot place orders.", {"intent": "other", "urgent": True}),
]
RULES = (
"Classify a support ticket. Intent is billing for invoice or charge questions, "
"access for account login issues, and other otherwise. Set urgent to true "
"only if a production service is currently down. Return only a JSON object "
"with keys intent (string) and urgent (boolean)."
)
def result(status, started, note=None):
row = {"status": status, "elapsed_ms": round((time.perf_counter() - started) * 1000)}
if note is not None:
row["note"] = note
return row
def evaluate(url, key, model, ticket, expected):
body = {
"model": model,
"messages": [
{"role": "system", "content": RULES},
{"role": "user", "content": ticket},
]
}
req = Request(
url,
data=json.dumps(body).encode(),
headers={
"Authorization": f"Bearer {key}",
"Content-Type": "application/json",
},
method="POST"
)
started = time.perf_counter()
try:
with urlopen(req, timeout=30) as response:
data = json.load(response)
content = data["choices"][0]["message"]["content"]
except HTTPError as exc:
return result("http_error", started, exc.code)
except (URLError, TimeoutError):
return result("network_error", started)
except (ValueError, KeyError, IndexError, TypeError):
return result("invalid_api_response", started)
try:
obj = json.loads(content)
except (TypeError, ValueError):
return result("invalid_json", started)
if (
not isinstance(obj, dict)
or set(obj) != {"intent", "urgent"}
or obj["intent"] not in ("billing", "access", "other")
or type(obj["urgent"]) is not bool
):
return result("wrong_shape", started)
if obj != expected:
return result("wrong_label", started, obj)
return result("pass", started)
def main():
url = os.environ["LLM_BASE_URL"].rstrip("/") + "/chat/completions"
key = os.environ["LLM_API_KEY"]
models = [m.strip() for m in os.environ["LLM_MODEL_IDS"].split(",") if m.strip()]
if not models:
raise SystemExit("Set LLM_MODEL_IDS to at least one exact model ID.")
for model in models:
for name, ticket, expected in CASES:
row = evaluate(url, key, model, ticket, expected)
print(json.dumps({"model": model, "case": name, **row}), flush=True)
if __name__ == "__main__":
main()
A run with three models produces nine JSON lines. To keep them for comparison, run python compare_models.py > results.jsonl.
You can count passes in a spreadsheet after importing the lines, or group them by model and status with any JSONL tool. Keep the denominator visible: report something like "2 of 3 cases passed, one HTTP 429," not "2 of 2 answers correct" without explaining where the third request went. These are example counts, not results from the three services below.
3. Diagnose the failure before changing models
Start with HTTP failures. A 401 means the server did not accept this authentication attempt. Check that your base URL and credential belong to the same service. A 429 is usually a rate or quota signal; look at the provider's documentation and space out only the requests you decide to repeat. A 400 can mean that the ID or payload is not accepted; read the provider's error details separately, without pasting credentials or customer data into an issue.
Gateways can use different status codes for the same failure, so use the status as a clue, not proof of a cause. The harness does not retry on its own, so a failed request stays visible and a rate-limited run does not snowball into more traffic.
Treat bad shape and bad decisions differently. If the provider returns text with a JSON fence around it, you have a formatting failure. If it gives you a valid object with the wrong intent, you have a decision failure. Stripping fences or adding a JSON schema can help with formatting; neither proves the answer agrees with your business rules. That distinction matters when deciding whether to adjust the client or change the model.
The script deliberately tests a prompt-only contract and does not send response_format or tools. To compare schema enforcement, create a separate run with a documented structured-output setting. Record whether the provider accepts the option before comparing pass rates. Otherwise you are comparing different API features and calling the result a model difference.
Read timings narrowly. elapsed_ms is the elapsed wall-clock time observed by this client, including network, queueing, generation, transfer, and a small amount of parsing. It's not time to first token, pure inference time, or a provider uptime measurement. Three consecutive runs can put one model at a quieter time than another. If latency matters, interleave the same cases across models, repeat a small number of runs at different times, and keep failures in the report. For a smoke test, comparing the error categories gives a better first signal than ranking nine timings.
4. Make the next run harder, not just bigger
If all three routes pass these fixtures, keep the fixtures as a regression check. Then add cases your application can actually confuse: a billing complaint that also mentions logging in, a customer reporting an outage that already ended, or a valid result with an unexpected key. Agree on which category wins before sending the request.
If two teammates disagree on the expected label, that's a policy gap; it isn't evidence that one model is worse. Rewrite the labeling rule or document the disputed example separately.
Keep the original cases unchanged when you tune the prompt. Create a separate holdout set that you don't use for prompt edits. Put the model ID, run date, endpoint, and prompt version next to each run, especially when a model name points at a route that can change. Record any request setting you vary. This makes it possible to retest a future upgrade without guessing what was different last time. Avoid using customer tickets for your first run; synthetic fixtures let you share failures without exposing user data.
The practical result you want is a decision about your application. If output format is the main source of trouble, spend time on strict validation and a documented repair or fallback path. If labels are wrong despite valid shape, improve the rubric and test with new examples before choosing a model. If HTTP failures dominate, investigate the route and account limits separately before drawing any quality conclusions. The same harness keeps working when you change providers or stop using the examples below.
Example endpoint and temporary model IDs
For AIWave, set LLM_BASE_URL to https://aiwave.live/v1 and use your own AIWave credential. You can sign in or create an AIWave account if you want to use this example provider.
Use this value for LLM_MODEL_IDS:
glm-5.3-free,glm-5.3-flash-free,deepseek-v4.1-flash-1017-free
AIWave's public pricing API listed all three IDs at zero for the Dec 3-9, 2026 offer (UTC+8), checked on Dec 3. The DeepSeek ID includes -1017.
On Dec 10, AIWave plans to remove these trial IDs, not convert them into paid IDs. If you continue after the trial, explicitly select a regular paid ID and check its current rate. A removed ID shouldn't be used as a fallback.
The harness was checked with simulated success and failures, not used to claim live benchmark results or verify real account charges.
Comments
No comments yet. Start the discussion.