Swarms Logo
GuidesEngineering

How to Compare GPT, Claude and Gemini on Your Own Prompts

Public leaderboards rank models on someone else's tasks. This tutorial compares GPT, Claude and Gemini on your prompts: run every prompt on every model in one batched grid request, grade the answers blind with a judge, measure latency and cost per request, and pick a model with numbers. Python on the Swarms API.

Kye Gomez11 min read
How to Compare GPT, Claude and Gemini on Your Own Prompts

Leaderboards tell you which model is best at the leaderboard's tasks. Your product has its own: a support bot that has to follow a refund policy, an extractor that has to return valid JSON, a summarizer that has to keep the numbers right. The model that wins a reasoning benchmark is often not the one that is best, fastest or cheapest on those.

The only reliable way to choose is to run your own prompts on each candidate and grade the results. This tutorial builds that comparison in Python on the Swarms API, which serves models from OpenAI, Anthropic, Google and others behind one key, so trying a model is a matter of changing a string.

By the end you get a table like this for your prompts:

model pass rate mean score median latency cost / 1k requests gpt-5.4 ... ... ... ... claude-sonnet-5 ... ... ... ... gemini-3.5-flash ... ... ... ...

The plan

  1. Collect 20 to 50 real prompts from your logs, each with what a good answer must contain.
  2. Run every prompt on every model in one request to the batched grid workflow endpoint.
  3. Grade the answers blind with a judge that does not know which model wrote what.
  4. Measure latency and cost per model with a small timed sample.
  5. Read the table and pick the cheapest model that is good enough.

Step 1: a test set from real traffic

The test set matters more than any other part. Pull real requests from your logs instead of inventing them, include the hard and weird ones, and write down for each what a correct answer needs. A JSON Lines file works well:

JSON
{"id": "refund-41d", "prompt": "Customer bought 41 days ago and wants a refund. Policy: refunds within 30 days, store credit after. Write the reply.", "criteria": "Declines the refund, offers store credit, polite, under 80 words."}
{"id": "extract-inv-7", "prompt": "Extract vendor, date and total as JSON from: 'Invoice from Lumen Labs, 3 Nov 2026, amount due EUR 1,240.00'", "criteria": "Valid JSON with vendor 'Lumen Labs', date 2026-11-03, total 1240.00 and currency EUR."}
{"id": "summ-q3", "prompt": "Summarize in two sentences: <earnings call excerpt>", "criteria": "Two sentences, keeps revenue and margin figures exact, no invented numbers."}

Twenty prompts is enough to separate models that differ a lot. Fifty gives you a pass rate you can trust to a few percentage points.

Step 2: every prompt on every model, in one request

POST /v1/batched-grid-workflow/completions takes a list of agents and a list of tasks and runs them all concurrently. The agents and tasks are paired by position: agent 1 gets task 1, agent 2 gets task 2, and so on, and the response maps each agent's name to its output. So for a models-by-prompts matrix, you create one agent per cell and name it after the cell:

Python
import json
import os
import requests

BASE = "https://api.swarms.world"
HEADERS = {"x-api-key": os.environ["SWARMS_API_KEY"], "Content-Type": "application/json"}

MODELS = ["gpt-5.4", "claude-sonnet-5", "gemini-3.5-flash"]
SYSTEM_PROMPT = "You are the assistant inside Acme's product. Follow the instructions in each request exactly."

cases = [json.loads(line) for line in open("cases.jsonl")]


def run_grid(models: list[str], cases: list[dict]) -> dict[str, str]:
    agents, tasks = [], []
    for model in models:
        for case in cases:
            agents.append({
                "agent_name": f"{model}|{case['id']}",   # unique name per cell
                "model_name": model,
                "system_prompt": SYSTEM_PROMPT,           # identical for every model
                "max_loops": 1,
                "max_tokens": 1500,
                "temperature": 0.2,
            })
            tasks.append(case["prompt"])

    payload = {
        "name": "model-comparison",
        "description": f"{len(models)} models x {len(cases)} prompts",
        "agent_completions": agents,
        "tasks": tasks,
    }
    resp = requests.post(f"{BASE}/v1/batched-grid-workflow/completions",
                         headers=HEADERS, json=payload, timeout=600)
    resp.raise_for_status()
    data = resp.json()
    print(f"status={data['status']}  cost=${data['usage'].get('total_cost', 0):.4f}")

    cells = data["outputs"][0]   # one loop, so one mapping of agent name to output
    return {name: (out if isinstance(out, str) else f"ERROR: {out.get('error')}")
            for name, out in cells.items()}


answers = run_grid(MODELS, cases)

Every model gets the same system prompt, the same user prompt and the same token budget, so differences in the answers come from the models. Keep temperature low for a comparison; you are measuring the model, not its sampling noise.

If one model errors on a prompt, the run still completes: status is "partial" and that cell holds an {"error": ...} object, which the code above turns into a string you will see in the report. A run where every cell fails returns a 502 and is not charged.

Step 3: grade blind

Reading 150 answers yourself defeats the point, so a judge model grades them against each prompt's criteria. Two rules keep the grading fair:

  • The judge never sees the model name. The task only contains the prompt, the criteria and the answer.
  • The judge is not one of the contestants, or you use a panel of judges from different providers, because models tend to rate answers that sound like their own more highly.
Python
import re
from concurrent.futures import ThreadPoolExecutor

JUDGE = """You grade one answer against the criteria for its prompt.
Score 1 to 5: 5 meets every criterion, 3 misses one, 1 is wrong or unusable.
Length is not a quality signal. Return only JSON: {"score": <1-5>, "pass": true | false, "reason": "<one sentence>"}
An answer passes with a score of 4 or 5."""


def grade(case: dict, answer: str, judge_model: str = "gpt-5.4-mini") -> dict:
    payload = {
        "agent_config": {"agent_name": "Grader", "model_name": judge_model, "system_prompt": JUDGE,
                         "max_loops": 1, "max_tokens": 300, "temperature": 0},
        "task": f"Prompt:\n{case['prompt']}\n\nCriteria:\n{case['criteria']}\n\nAnswer:\n{answer}",
    }
    r = requests.post(f"{BASE}/v1/agent/completions", headers=HEADERS, json=payload, timeout=120)
    r.raise_for_status()
    reply = [o for o in r.json()["outputs"] if str(o.get("role", "")).lower() not in ("user", "system")][-1]
    match = re.search(r"\{.*\}", str(reply["content"]), re.S)
    return json.loads(match.group(0)) if match else {"score": 1, "pass": False, "reason": "unparseable"}


jobs = [(m, c) for m in MODELS for c in cases]
with ThreadPoolExecutor(max_workers=8) as pool:
    grades = dict(zip(jobs, pool.map(lambda mc: grade(mc[1], answers[f"{mc[0]}|{mc[1]['id']}"]), jobs)))

For a release decision, swap the single grader for the three-judge panel with majority voting from LLM-as-a-Judge: Build an Evaluation Pipeline. It costs three times as much per grade and removes most of the single-judge bias.

Step 4: latency and cost per model

The grid returns one bill for the whole run, and its cells run concurrently, so it cannot tell you how fast or how expensive each model is per request. A small timed sample through POST /v1/agent/completions can: each response carries its own usage with input_tokens, output_tokens and total_cost.

Python
import statistics
import time


def probe(model: str, sample: list[dict]) -> dict:
    latencies, costs = [], []
    for case in sample:
        payload = {
            "agent_config": {"agent_name": "Probe", "model_name": model, "system_prompt": SYSTEM_PROMPT,
                             "max_loops": 1, "max_tokens": 1500, "temperature": 0.2},
            "task": case["prompt"],
        }
        start = time.perf_counter()
        r = requests.post(f"{BASE}/v1/agent/completions", headers=HEADERS, json=payload, timeout=180)
        latencies.append(time.perf_counter() - start)
        r.raise_for_status()
        costs.append(r.json()["usage"]["total_cost"])
    return {"latency": statistics.median(latencies), "cost_per_1k": 1000 * statistics.mean(costs)}


speed = {m: probe(m, cases[:5]) for m in MODELS}

Five prompts per model is enough for a rough latency figure. Latency measured from your machine includes network time and varies with provider load, so compare models in the same run rather than against numbers from another day.

To estimate before running anything, GET /v1/models/pricing?model_name=gpt-5.4 returns a model's input_cost_per_1m and output_cost_per_1m, service fee included.

Step 5: the report

Python
print(f"{'model':<20}{'pass rate':>10}{'mean score':>12}{'median latency':>16}{'cost / 1k':>12}")
for m in MODELS:
    g = [grades[(m, c)] for c in cases]
    pass_rate = sum(bool(x.get("pass")) for x in g) / len(g)
    mean_score = statistics.mean(x.get("score", 1) for x in g)
    print(f"{m:<20}{pass_rate:>10.0%}{mean_score:>12.2f}{speed[m]['latency']:>15.1f}s{speed[m]['cost_per_1k']:>11.2f}$")

# The failures are where the decision gets made: read them.
for (m, c), g in grades.items():
    if not g.get("pass"):
        print(f"[{m}] {c['id']}: {g.get('reason')}")

Reading the results

A few patterns come up again and again:

  • The cheapest model that passes is usually the right default. If two models are within a few points of each other on pass rate, the one at a fraction of the cost and latency wins, and you can route the hard cases to the stronger one.
  • Failures cluster. One model may fail every JSON extraction case while doing well on writing. That points to splitting traffic by task type instead of picking one model for everything.
  • Read the reasons, not just the scores. A judge reason like "invented a revenue figure" is worth more than a 0.2 difference in mean score.

Once you have picked, make the choice resilient: set model_name to the winner and add the runner-up in fallback_models, so a provider outage switches models instead of failing requests.

Testing frontier models

The models above are available on every plan. GPT-5.6, Claude Opus 5 and Gemini 3.1 Pro are premium models, and the batched grid endpoint is part of the Pro and Premium plans. On a Pro key, add them to MODELS and rerun the same script to see whether the frontier tier earns its price on your prompts. On the Free plan, run the comparison with the probe loop from step 4, which uses only the agent endpoint.

Get started

Create an API key at cloud.swarms.world, export 20 prompts from your logs and write a line of criteria for each. If you want to try it before writing code, Grid on Swarms Cloud runs a task list against an agent list from the browser, and Compare runs one task through up to six agent configurations side by side (how Compare works). The pricing page lists what each plan includes, and you can upgrade on Swarms Cloud when you need the grid and premium models.

More from the blog

Swarms v18 'Collective': Self-Organizing Swarms, A2A, Native Async Agents, Structured Output, and Token Usage on Every Structure
Engineering

Swarms v18 'Collective': Self-Organizing Swarms, A2A, Native Async Agents, Structured Output, and Token Usage on Every Structure

The complete technical changelog for Swarms v18, code-named Collective. SelfOrganizingSwarm runs a leaderless team that coordinates by message, MessageBoard gives agents a forum they work through tools, A2AServer and A2AClient put any agent on the A2A protocol, Agent.arun runs natively on the event loop, output_schema returns a validated Pydantic object, every multi-agent structure reports its token usage, seven structures force the tool call they depend on, images actually reach the model, telemetry is off by default, and importing swarms and building the first Agent takes half the time. Every new feature, improvement, bug fix and removal from November 2 to December 1, 2026, day by day.

Deploy AI Agents Without Servers: Scheduled and Event-Driven Agents With One API Call
Guides

Deploy AI Agents Without Servers: Scheduled and Event-Driven Agents With One API Call

Run AI agents on a schedule or in response to webhooks from Vercel Cron, AWS Lambda or Cloudflare Workers, with no Python runtime, worker process or queue to maintain. Each agent run is one HTTPS request to the Swarms API. TypeScript code for all three platforms.

The OpenAI Assistants API Has Shut Down: How to Migrate Your Agents to the Swarms API
Guides

The OpenAI Assistants API Has Shut Down: How to Migrate Your Agents to the Swarms API

OpenAI sunset the Assistants API on August 26, 2026. This guide maps assistants, threads, runs, function tools and file search to the Swarms API, with before-and-after Python code, a thread store you own, MCP in place of function calling, and a one-line route for code that already uses the OpenAI SDK.