Skip to content

The Edge of the Cyber World See the latest

Apps

ChatGPT vs Claude vs Gemini API: 13 Steps, 60 Min [2026]

Picking between ChatGPT, Claude and Gemini by reading launch posts is a coin flip with extra steps. This tutorial gives you a repeatable way to settle it with your own data. In 13 steps and about 60 minutes, you will build a small Python harness that sends the same documents to all three vendors, scores every answer against known ground truth, and prints accuracy, latency and cost per document. The ChatGPT vs Claude vs Gemini question stops being an argument and becomes a table you can rerun every time a vendor ships a new model.

The timing matters right now. As of November 2, 2026, Anthropic’s pricing page still centres on the Claude 5.5 family (Opus 5.5, Sonnet 5.5 and Haiku 5.5), OpenAI sells GPT-6.1 Sol and GPT-6.1 Terra through its API, and Google’s Gemini 4 Argon has been generally available since October 13, 2026 at an introductory price that ends on November 30. Model names and prices have moved repeatedly since mid-October, so any chart older than a month is already stale. If you want the chat-window version of this exercise, our earlier hands-on test in the chat apps covers it. This guide goes one level deeper and tests the APIs that your code will actually call.

The task is structured data extraction from invoices. It is boring on purpose. Extraction has one correct answer per field, so you can grade it without a judge model, and it is the kind of work teams run thousands of times a day where a few cents per document add up. The harness you build here is generic, though. Swap the schema and the documents, and you can test contracts, support tickets or log lines the same way.

What This ChatGPT vs Claude vs Gemini Test Measures (and What It Skips)

A fair test starts with a narrow question. Ours is: given a messy invoice as plain text, which model returns the correct eight fields, how fast, and at what price per thousand documents? Every contestant gets the same system prompt, the same user prompt, the same JSON schema and the same 16 documents. Nothing else changes between vendors except the SDK call that delivers them.

That narrowness is the point. The usual head-to-head articles mix coding, essay writing, image generation and web browsing into one verdict, and the verdict ends up as vibes. A single-task harness gives you a number you can defend in a pull request. Four layouts of invoice (US, European, British and a deliberately noisy OCR-style one) keep the task from being trivial, because each layout formats dates, decimals and currency differently. Each document also carries traps: a previous balance that is not the total, a payment due date that is not the invoice date, and a customer order reference that is not the invoice number.

Here is what the test deliberately does not cover. It does not test the consumer apps, where memory, tools, system prompts and rate limits differ from the raw API. It does not measure long-context recall, vision on scanned PDFs, tool use or agentic coding. A model that wins on invoices can lose on your legal contracts. Treat the result as one data point, then extend the harness with your own documents. For broader benchmark context across the three vendors, see our ChatGPT vs Claude vs Gemini benchmark comparison, and for more testing guides browse the AI and machine learning section.

The 13 steps and the 60-minute budget

The table below shows the full path and a realistic time budget for each step. Most of the clock goes to account setup and the first live run, because everything else is code you can paste.

Step What you do Minutes
1 Define the rubric and contestants 4
2 Get three API keys and the model IDs 8
3 Create the project and virtual environment 3
4 Store keys in a .env file 3
5 Write the shared schema and prompt 4
6 Generate invoices with ground truth 6
7 Write the Claude adapter 4
8 Write the OpenAI adapter 4
9 Write the Gemini adapter 4
10 Write scoring and pricing 4
11 Write the runner with retries 5
12 Smoke test, then full run 6
13 Read the report and decide 5

Prerequisites: Tools, Versions and Accounts

You need a laptop with a terminal, a text editor and a stable connection. Nothing in this project needs a GPU, a database or Docker. The whole thing runs on the standard library plus the three vendor SDKs and a dotenv loader.

Requirement Version or detail Why you need it
Python 3.11 or newer (the code was tested on 3.12.3) Dataclasses, f-strings and modern typing
anthropic Latest release from PyPI Claude Messages API client
openai Latest release from PyPI Responses API client for GPT-6.1 models
google-genai Latest release from PyPI Gemini API client for Gemini 4 Argon
python-dotenv Latest release from PyPI Loads keys from a local .env file
Anthropic API key Billing enabled on the Claude Platform Pays for Claude calls
OpenAI API key Billing enabled on the API platform Pays for GPT-6.1 calls
Gemini API key Created in Google AI Studio Pays for Gemini calls
Budget Under $1 for the 16-document run See the cost table later

Pin exact SDK versions once the test works, using the output of pip freeze. We say “latest release” here because SDK version numbers change faster than articles do, and a wrong number would only mislead you. If you have never called the Claude API from Python, skim our Claude API tutorial first. It covers key creation and the Messages API basics that this harness builds on.

One naming point saves confusion. “ChatGPT” is OpenAI’s app. The API exposes the underlying GPT models, so in this harness the ChatGPT contestants are gpt-6.1-sol and gpt-6.1-terra. Likewise “Gemini” in the app and Gemini in the API share a model family but not a configuration, so results from the API will not match what you see in a chat window.

The Contestants as of November 2, 2026

Before writing code, fix the lineup. A fair ChatGPT vs Claude vs Gemini test compares the newest generation from each vendor, and it compares at least two price tiers, because the cheap model is often the one that ends up in production. We use five contestants across the three vendors.

Anthropic’s current lineup is led by Claude Opus 5.5, with Sonnet 5.5 and Haiku 5.5 as the other 5.5-generation models. Anthropic describes Opus 5.5 as its leading model for agentic coding and knowledge work, and says it runs about 40% cheaper than Opus 5 on typical workloads. Haiku 5.5 is the fast, small model for high-volume jobs such as summarization and subagents. We test Opus 5.5 and Haiku 5.5 and leave Sonnet 5.5 as an exercise, since its pricing sits between the two.

OpenAI’s picture is busier. GPT-6.1 Terra began rolling out in the API on October 26, 2026, with the API identifier gpt-6.1-terra. GPT-6.1 Sol uses gpt-6.1-sol, and OpenAI positions it near the top GPT-6 model, GPT-6 Astra, for document understanding at lower cost. GPT-5.5, the model older tutorials still use, was retired from ChatGPT, Work and Codex on October 14, 2026. If a guide tells you to call GPT-5.5, close the tab.

Google’s current model is Gemini 4 Argon, generally available since October 13, 2026 under the API identifier gemini-4-argon. Its launch price is $2 per million input tokens and $10 per million output tokens, with cached input discounted 95%, but that price runs only through November 30, 2026. From December 1, Google lists $4 and $20. A newer sibling, Gemini 4 Carbon, was announced on October 28 for trusted testers and selected cyber defenders and is not generally available, so it stays out of this test. Our Carbon vs Opus 5.5 vs Terra analysis covers the high end.

Contestant key Vendor Model Input $/M tokens Output $/M tokens
claude-flagship Anthropic Claude Opus 5.5 $4.00 $20.00
claude-small Anthropic Claude Haiku 5.5 $0.10 $0.50
gpt-6.1-sol OpenAI GPT-6.1 Sol $2.00 $10.00
gpt-6.1-terra OpenAI GPT-6.1 Terra $1.00 $5.00
gemini-4-argon Google Gemini 4 Argon $2.00 until Nov 30 $10.00 until Nov 30

Prices come from each vendor’s own pricing pages as of November 2, 2026, and Haiku 5.5’s rate applies to prompts up to 100,000 tokens, which covers every invoice here. A third-party Gemini API price tracker shows the same two-stage schedule. Every vendor also sells cheaper tiers than the ones above, as the Sonnet 5.5 vs GPT-6 Luna vs Gemini 3.8 comparison shows, and you can add any of them to the list in step 10.

Why test yourself at all? Developers split their usage across all three vendors. In the 2025 Stack Overflow Developer Survey, a large majority of respondents said they had used OpenAI GPT models for development work in the past year, and sizable groups had used Claude Sonnet models and Gemini Flash models. Most teams use more than one. A harness lets you route each task to the model that earns its price.

Steps 1-2: Define the Rubric and Collect Keys

Step 1: Write the rubric before you write code

Decide what counts as a win while you are still neutral. Write these four lines in a README and do not edit them after you see results:

  • Primary metric: field accuracy, meaning correct fields divided by 8 fields times the number of documents.
  • Secondary metric: perfect-document rate, meaning the share of documents where all 8 fields are right.
  • Operational metrics: median and 95th-percentile latency, and cost per 1,000 documents.
  • Decision rule: pick the cheapest contestant within one percentage point of the best field accuracy.

The decision rule is the part people skip, and it is the most useful one. Without it, the most accurate model wins by default and you never learn whether a model at one-twentieth the price was good enough. Anthropic’s Haiku 5.5 lists $0.10 per million input tokens against $4.00 for Opus 5.5, a 40x gap. If the small model lands within a point of the flagship, the choice is easy.

Step 2: Create API keys and copy the exact model IDs

Create one key per vendor in its console: the Claude Platform, the OpenAI API platform and Google AI Studio. Enable billing on each. Keys from consumer subscriptions do not work for the API. A ChatGPT Plus plan, a Claude Pro plan and a Google AI Pro plan are separate products from API credit, so budget a few dollars of prepaid credit per vendor. Our subscription pricing breakdown explains how the app plans differ from API billing.

Then copy the model IDs. OpenAI’s gpt-6.1-sol and gpt-6.1-terra and Google’s gemini-4-argon are documented identifiers, and the code hardcodes them. For Claude, the harness reads the IDs from environment variables, and you paste the exact strings from the models page of the Claude Platform docs. This is deliberate. A marketing name and an API ID can differ in punctuation or date suffix, and a typo returns a 404 that looks like an outage. Reading the ID from your own environment makes that mistake loud and local.

Steps 3-4: Create the Project and Store Secrets

Step 3: Scaffold the project

Create the folder, a virtual environment and the package skeleton. The commands below work on macOS and Linux. On Windows, activate the environment with .venvScriptsactivate instead.

mkdir llm-bakeoff && cd llm-bakeoff
python3 -m venv .venv
source .venv/bin/activate
mkdir bakeoff cases results
touch bakeoff/__init__.py
printf "anthropicnopenaingoogle-genainpython-dotenvn" > requirements.txt
pip install -r requirements.txt

The package layout is small on purpose: one module per concern, so you can swap a single adapter without touching the rest. The final tree looks like this:

llm-bakeoff/
  .env
  .gitignore
  requirements.txt
  bakeoff/
    __init__.py
    schema.py        # JSON schema and prompts shared by all vendors
    make_cases.py    # synthetic invoices with ground truth
    adapters.py      # one function per vendor SDK
    contestants.py   # model IDs and prices
    pricing.py       # cost math and the Gemini price switch
    score.py         # field-level grading
    run.py           # concurrent runner with retries
    report.py        # summary tables
  cases/cases.jsonl
  results/run-*.jsonl

Step 4: Keep keys out of the code

Create a .env file with your three keys and the two Claude IDs, then make sure Git never sees it. A key pushed to a public repository can be scraped quickly, and the bill lands on you.

ANTHROPIC_API_KEY=your-key-here
OPENAI_API_KEY=your-key-here
GEMINI_API_KEY=your-key-here
CLAUDE_FLAGSHIP_MODEL=paste-the-opus-5-5-id-here
CLAUDE_SMALL_MODEL=paste-the-haiku-5-5-id-here
printf ".envn.venv/nresults/n__pycache__/n" > .gitignore

The Anthropic and OpenAI SDKs read their keys from ANTHROPIC_API_KEY and OPENAI_API_KEY automatically. The Google client reads GEMINI_API_KEY or GOOGLE_API_KEY from the environment. The runner calls load_dotenv() before it builds any client, which is the one ordering rule that matters here.

Step 5: Write the Shared Schema and Prompt

Every vendor must see exactly the same task. Put the schema and prompts in one file and import them everywhere. The schema lists eight fields, forbids extras with additionalProperties: false, and marks every field as required. Those three properties also happen to satisfy the strictest of the three vendors’ structured-output modes, so one schema works for all.

FIELDS = [
    "vendor_name", "invoice_number", "invoice_date", "currency",
    "subtotal", "tax", "total", "line_item_count",
]
MONEY_FIELDS = {"subtotal", "tax", "total"}

INVOICE_SCHEMA = {
    "type": "object",
    "properties": {
        "vendor_name": {"type": "string", "description": "Legal name of the seller issuing the invoice"},
        "invoice_number": {"type": "string", "description": "The invoice number, not an order or PO reference"},
        "invoice_date": {"type": "string", "description": "Issue date as ISO 8601, YYYY-MM-DD"},
        "currency": {"type": "string", "description": "ISO 4217 code such as USD, EUR or GBP"},
        "subtotal": {"type": "number", "description": "Sum of line items before tax"},
        "tax": {"type": "number", "description": "Total tax amount"},
        "total": {"type": "number", "description": "Grand total for this invoice, excluding any previous balance"},
        "line_item_count": {"type": "integer", "description": "Number of distinct billed line items"},
    },
    "required": FIELDS,
    "additionalProperties": False,
}

SYSTEM_PROMPT = (
    "You extract structured data from invoice text. "
    "Return only the requested fields. Use null-free values: dates as YYYY-MM-DD, "
    "money as plain numbers with a dot as decimal separator, currency as an ISO 4217 code. "
    "Ignore previous balances, payment due dates and order references."
)

def user_prompt(doc_text: str) -> str:
    return f"Extract the invoice fields from this document:nn{doc_text}"

Read the prompt wording carefully, because it is part of the experiment. It tells the model to ignore previous balances, payment due dates and order references. That sentence helps every contestant equally, but a harder variant of the test removes it and measures which model avoids the traps unaided. Try both runs once your baseline works. The gap between them tells you how much your prompt is carrying the model.

Field descriptions inside the schema do real work as well. The description on total says to exclude any previous balance, and the one on invoice_number says it is not an order or PO reference. Vendors pass these descriptions to the model, so they act as per-field instructions without lengthening the system prompt.

Step 6: Generate Invoices With Known Ground Truth

Real invoices make poor test data for a first harness, because you must label them by hand and you cannot publish them. A seeded generator gives you labelled documents on demand, with exact answers and zero privacy risk. The generator below builds 16 invoices across four layouts, using Decimal for money so that rounding is exact, and writes each document with its truth to cases/cases.jsonl.

"""Generate synthetic invoices with known ground truth."""
import json, random
from datetime import date, timedelta
from decimal import Decimal, ROUND_HALF_UP
from pathlib import Path

VENDORS = ["Northwind Freight Ltd", "Brightline Analytics GmbH", "Harbor & Pine Supply Co.",
           "Kestrel Cloud Services", "Maple Row Printing", "Orchard Lane Catering",
           "Vantage Point Security", "Tidewater Tools Inc."]
ITEMS = [("Pallet wrap (roll)", "18.40"), ("Label printer ribbon", "9.95"), ("Onsite audit day", "640.00"),
         ("Hosting, monthly", "129.00"), ("Courier surcharge", "14.25"), ("Safety goggles", "6.80"),
         ("Consulting hour", "95.00"), ("Toner cartridge", "74.50")]
LAYOUTS = ["us", "eu", "uk", "ocr"]
TAX = {"us": Decimal("0.0825"), "eu": Decimal("0.19"), "uk": Decimal("0.20"), "ocr": Decimal("0.07")}
CUR = {"us": "USD", "eu": "EUR", "uk": "GBP", "ocr": "USD"}
MONTHS = ["January", "February", "March", "April", "May", "June", "July",
          "August", "September", "October", "November", "December"]

def q(x): return x.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)

def money(layout, x):
    s = f"{x:,.2f}"
    if layout == "us": return f"${s}"
    if layout == "uk": return f"£{s}"
    if layout == "eu": return s.replace(",", "X").replace(".", ",").replace("X", ".") + " EUR"
    return f"USD {s}"

def fdate(layout, d):
    if layout == "us": return d.strftime("%m/%d/%Y")
    if layout == "eu": return d.strftime("%d.%m.%Y")
    if layout == "uk": return f"{d.day} {MONTHS[d.month-1]} {d.year}"
    return d.strftime("%Y/%m/%d")

def build(i, rng):
    layout = LAYOUTS[i % 4]
    vendor = rng.choice(VENDORS)
    number = f"{rng.choice(['INV', 'RE', 'SI'])}-{rng.randint(10000, 99999)}"
    issued = date(2026, 1, 5) + timedelta(days=rng.randint(0, 270))
    due = issued + timedelta(days=30)
    lines = []
    for name, price in rng.sample(ITEMS, rng.randint(2, 5)):
        qty = rng.randint(1, 12)
        lines.append((name, qty, Decimal(price), q(Decimal(price) * qty)))
    subtotal = sum(l[3] for l in lines)
    tax = q(subtotal * TAX[layout])
    total = subtotal + tax
    prev = q(Decimal(rng.randint(2000, 90000)) / 100)
    po = f"PO-{rng.randint(100000, 999999)}"
    m = lambda x: money(layout, x)
    rows = "n".join(f"{n:<26}{qty:>3} x {m(p):>14}{m(t):>16}" for n, qty, p, t in lines)
    if layout == "ocr":
        head = f"{vendor.upper()}nlnvoice No: {number}   Order ref: {po}nDate : {fdate(layout, issued)}"
        foot = f"Sub total   {m(subtotal)}nTax (7 %)   {m(tax)}nPrev. balance  {m(prev)}nTOTAL DUE THIS INVOICE  {m(total)}"
    else:
        head = f"{vendor}nInvoice number: {number}nCustomer order: {po}nInvoice date: {fdate(layout, issued)}nPayment due: {fdate(layout, due)}"
        foot = f"Subtotal: {m(subtotal)}nTax: {m(tax)}nPrevious balance: {m(prev)}nTotal: {m(total)}"
    text = f"{head}nn{rows}nn{foot}n"
    truth = {"vendor_name": vendor, "invoice_number": number, "invoice_date": issued.isoformat(),
             "currency": CUR[layout], "subtotal": float(subtotal), "tax": float(tax),
             "total": float(total), "line_item_count": len(lines)}
    return {"id": f"doc{i:02d}", "layout": layout, "text": text, "truth": truth}

def main(n=16, seed=2026, out="cases/cases.jsonl"):
    rng = random.Random(seed)
    path = Path(out); path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w") as f:
        for i in range(n):
            f.write(json.dumps(build(i, rng), ensure_ascii=False) + "n")
    print(f"wrote {n} cases to {path}")

if __name__ == "__main__":
    import sys
    main(n=int(sys.argv[1]) if len(sys.argv) > 1 else 16)

The fixed seed (2026) makes the set identical on every machine, which matters when two teammates compare numbers. Run it and inspect the first few cases yourself before spending a cent on API calls:

python3 -m bakeoff.make_cases

You should see this line, and then the file in cases/:

wrote 16 cases to cases/cases.jsonl

Here is the first generated document, a US-layout invoice, exactly as the models will see it. Note the distractors: a previous balance of $571.30 that is not the total, and a due date a month after the invoice date.

Brightline Analytics GmbH
Invoice number: RE-75865
Customer order: PO-921426
Invoice date: 09/24/2026
Payment due: 10/24/2026

Hosting, monthly           10 x        $129.00       $1,290.00
Courier surcharge           9 x         $14.25         $128.25

Subtotal: $1,418.25
Tax: $117.01
Previous balance: $571.30
Total: $1,535.26

The matching ground truth covers invoice_date, currency (USD), subtotal, tax, total and line_item_count (2). The European layout writes dates with dots, day first, and amounts like 86,55 EUR, which is where many extraction pipelines quietly break: is such a date the seventh of May or the fifth of July? The British layout spells months out, and the OCR layout misspells “Invoice” as “lnvoice” with a lowercase L.

If you want to stress the models harder, raise the count to 100 documents with python3 -m bakeoff.make_cases 100. Sixteen is enough for a first read and costs pennies. A hundred gives you tighter error bars. The same cost-per-task thinking drives our Grok vs Claude API cost test, which is worth reading if you plan to add xAI as a fourth contestant.

Steps 7-9: Write One Adapter per Vendor

Each adapter takes a contestant and a document, makes one API call and returns a Reply with the raw text and token counts. The runner never touches vendor details, which keeps the comparison honest. All five adapters live in one file, and the imports for each SDK happen lazily so that the mock mode works without any SDK installed.

import hashlib, json, random
from dataclasses import dataclass
from .schema import INVOICE_SCHEMA, SYSTEM_PROMPT, user_prompt

@dataclass
class Reply:
    text: str
    input_tokens: int
    output_tokens: int

_clients = {}

def _client(name):
    if name not in _clients:
        if name == "anthropic":
            import anthropic
            _clients[name] = anthropic.Anthropic()
        elif name == "openai":
            import openai
            _clients[name] = openai.OpenAI()
        elif name == "google":
            from google import genai
            _clients[name] = genai.Client()
    return _clients[name]

def call_anthropic(c, doc_text):
    resp = _client("anthropic").messages.create(
        model=c.model, max_tokens=1024, system=SYSTEM_PROMPT,
        tools=[{"name": "record_invoice", "description": "Record the extracted invoice fields",
                "input_schema": INVOICE_SCHEMA}],
        tool_choice={"type": "tool", "name": "record_invoice"},
        messages=[{"role": "user", "content": user_prompt(doc_text)}],
    )
    block = next(b for b in resp.content if b.type == "tool_use")
    return Reply(json.dumps(block.input), resp.usage.input_tokens, resp.usage.output_tokens)

def call_openai(c, doc_text):
    resp = _client("openai").responses.create(
        model=c.model, instructions=SYSTEM_PROMPT, input=user_prompt(doc_text),
        text={"format": {"type": "json_schema", "name": "invoice",
                         "schema": INVOICE_SCHEMA, "strict": True}},
    )
    return Reply(resp.output_text, resp.usage.input_tokens, resp.usage.output_tokens)

def call_google(c, doc_text):
    from google.genai import types
    resp = _client("google").models.generate_content(
        model=c.model, contents=user_prompt(doc_text),
        config=types.GenerateContentConfig(
            system_instruction=SYSTEM_PROMPT,
            response_mime_type="application/json",
            response_json_schema=INVOICE_SCHEMA),
    )
    u = resp.usage_metadata
    out = (u.candidates_token_count or 0) + (getattr(u, "thoughts_token_count", 0) or 0)
    return Reply(resp.text, u.prompt_token_count or 0, out)

def call_mock(c, doc_text, case):
    """Offline stand-in: truth with deterministic, model-specific damage."""
    seed = int(hashlib.sha256(f"{c.key}:{case['id']}".encode()).hexdigest(), 16)
    rng = random.Random(seed)
    out = dict(case["truth"])
    error_rate = {"mock-a": 0.03, "mock-b": 0.12, "mock-c": 0.07}[c.key]
    for field in list(out):
        if rng.random() < error_rate:
            v = out[field]
            out[field] = round(v + 1, 2) if isinstance(v, float) else (v + 1 if isinstance(v, int) else v + "x")
    if rng.random() < error_rate / 3:
        return Reply("Sure! Here is the JSON: " + json.dumps(out), len(doc_text) // 4 + 150, 90)
    return Reply(json.dumps(out), len(doc_text) // 4 + 150, 90)

DISPATCH = {"anthropic": call_anthropic, "openai": call_openai, "google": call_google}

Step 7: Claude, with a forced tool call

The Claude adapter skips a dedicated JSON mode. Instead, it declares a tool named record_invoice whose input_schema is our shared schema, then sets tool_choice so the model must call it. The structured result arrives as the input of a tool_use block, and the adapter serialises it back to a JSON string so that parsing and scoring stay identical across vendors. Token counts come from resp.usage.input_tokens and resp.usage.output_tokens. Do not enable extended thinking on this call, because a forced tool choice and thinking do not combine.

Step 8: OpenAI, with strict JSON schema

The OpenAI adapter uses the Responses API. The text.format block asks for a json_schema output named invoice with strict set to true, which makes the API reject schemas that are not fully specified (hence the all-required, no-extras schema from step 5). The answer is in resp.output_text, and usage is in resp.usage. The adapter passes no temperature on purpose. Newer reasoning-style models can reject sampling parameters, and a test that crashes on a rejected knob tells you nothing about extraction quality.

Step 9: Gemini, with a JSON response schema

The Gemini adapter uses the google-genai client. It sets response_mime_type to application/json and passes the schema through response_json_schema. Token accounting needs care here. Gemini reports thinking tokens separately from visible output tokens, and Google bills them as output. The adapter therefore adds thoughts_token_count to candidates_token_count. Skip that line and Argon will look cheaper than it is.

At this point you have three vendors behind one interface. The mock function at the bottom of the file lets you exercise everything that follows without spending money, and it is the reason this tutorial can show real terminal output below.

Step 10: Score Answers and Price Every Call

Grading must be strict where precision matters and forgiving where formatting varies. The scorer compares money to the cent, compares the line-item count as an integer, and compares text after lowercasing and collapsing whitespace. A missing field, a wrong type or unparsable JSON counts as wrong for every field of that document.

import json
from .schema import FIELDS, MONEY_FIELDS

def _norm(s): return " ".join(str(s).casefold().split())

def field_ok(field, pred, truth):
    if pred is None: return False
    try:
        if field in MONEY_FIELDS: return abs(float(pred) - float(truth)) < 0.005
        if field == "line_item_count": return int(pred) == int(truth)
    except (TypeError, ValueError):
        return False
    return _norm(pred) == _norm(truth)

def parse(text):
    try:
        obj = json.loads(text)
    except json.JSONDecodeError:
        return None
    return obj if isinstance(obj, dict) else None

def score(pred, truth):
    if pred is None:
        return {f: False for f in FIELDS}
    return {f: field_ok(f, pred.get(f), truth[f]) for f in FIELDS}

Cost math lives in its own module, because it has to change on a known date. Google’s Argon price rises from $2 and $10 to $4 and $20 per million tokens on December 1, 2026. The function below reads today’s date and switches automatically, so a test run on November 30 and one on December 1 use different rates without a code edit. This is the sort of detail covered in more depth in our API cache pricing comparison.

from datetime import date

GEMINI_INTRO_ENDS = date(2026, 11, 30)

def gemini_argon_prices(today=None):
    """Per-million-token (input, output) USD. Intro price ends Nov 30, 2026."""
    today = today or date.today()
    return (2.00, 10.00) if today <= GEMINI_INTRO_ENDS else (4.00, 20.00)

def cost_usd(in_tokens, out_tokens, in_price, out_price):
    return (in_tokens * in_price + out_tokens * out_price) / 1_000_000

Finally, contestants.py defines the lineup. The mock flag swaps in three fake contestants so you can test the pipeline offline.

import os
from dataclasses import dataclass
from .pricing import gemini_argon_prices

@dataclass(frozen=True)
class Contestant:
    key: str
    vendor: str      # anthropic | openai | google | mock
    model: str
    in_price: float  # USD per million input tokens
    out_price: float # USD per million output tokens

def build(mock=False):
    if mock:
        return [Contestant("mock-a", "mock", "mock-a", 4.00, 20.00),
                Contestant("mock-b", "mock", "mock-b", 1.00, 5.00),
                Contestant("mock-c", "mock", "mock-c", 2.00, 10.00)]
    g_in, g_out = gemini_argon_prices()
    return [
        Contestant("claude-flagship", "anthropic", os.environ["CLAUDE_FLAGSHIP_MODEL"], 4.00, 20.00),
        Contestant("claude-small", "anthropic", os.environ["CLAUDE_SMALL_MODEL"], 0.10, 0.50),
        Contestant("gpt-6.1-sol", "openai", "gpt-6.1-sol", 2.00, 10.00),
        Contestant("gpt-6.1-terra", "openai", "gpt-6.1-terra", 1.00, 5.00),
        Contestant("gemini-4-argon", "google", "gemini-4-argon", g_in, g_out),
    ]

A worked example shows why the price table matters. Assume a typical call uses 700 input tokens and 120 output tokens (your real numbers will differ, so replace these with the averages from your first run). Cost per 1,000 documents then works out as follows:

Contestant Input cost Output cost Per document Per 1,000 documents
Claude Opus 5.5 Not listed Not listed Not listed Not listed
Claude Haiku 5.5 $0.00007 $0.00006 $0.00013 Not listed
GPT-6.1 Sol Not listed $0.0012 Not listed Not listed
GPT-6.1 Terra Not listed $0.0006 Not listed Not listed
Gemini 4 Argon (to Nov 30) Not listed $0.0012 Not listed Not listed
Gemini 4 Argon (from Dec 1) Not listed Not listed Not listed Not listed

Those figures are arithmetic on listed prices, not measurements, and they ignore thinking tokens, which can push real output counts well above 120. They do show the shape of the decision. At these volumes the entire 16-document run costs a few cents, and the gap between the cheapest and the dearest contestant is a factor of 40. Whether the dearer models earn that factor is exactly what the accuracy column will tell you.

Step 11: Build the Runner With Retries and Concurrency

The runner expands contestants, documents and repeats into a job list, runs the jobs on a small thread pool, retries transient failures with exponential backoff and writes every result to a JSONL file as it arrives. A crash at document 70 of 80 then costs you nothing but a rerun of the tail.

import argparse, json, time, sys
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime
from pathlib import Path
from . import adapters, contestants
from .pricing import cost_usd
from .score import parse, score
from .report import summarize

def load_cases(path, limit=None):
    cases = [json.loads(l) for l in Path(path).read_text().splitlines() if l.strip()]
    return cases[:limit] if limit else cases

def one_call(c, case, retries=4):
    delay = 2.0
    for attempt in range(retries + 1):
        t0 = time.perf_counter()
        try:
            if c.vendor == "mock":
                reply = adapters.call_mock(c, case["text"], case)
            else:
                reply = adapters.DISPATCH[c.vendor](c, case["text"])
            latency = time.perf_counter() - t0
            pred = parse(reply.text)
            s = score(pred, case["truth"])
            return {"contestant": c.key, "model": c.model, "case": case["id"], "layout": case["layout"],
                    "latency_s": round(latency, 3), "input_tokens": reply.input_tokens,
                    "output_tokens": reply.output_tokens,
                    "cost_usd": cost_usd(reply.input_tokens, reply.output_tokens, c.in_price, c.out_price),
                    "valid_json": pred is not None, "fields": s, "pred": pred, "error": None}
        except Exception as exc:
            if attempt == retries:
                return {"contestant": c.key, "model": c.model, "case": case["id"], "layout": case["layout"],
                        "latency_s": None, "input_tokens": 0, "output_tokens": 0, "cost_usd": 0.0,
                        "valid_json": False, "fields": score(None, case["truth"]), "pred": None,
                        "error": f"{type(exc).__name__}: {exc}"[:300]}
            time.sleep(delay); delay *= 2

def main(argv=None):
    ap = argparse.ArgumentParser()
    ap.add_argument("--cases", default="cases/cases.jsonl")
    ap.add_argument("--limit", type=int)
    ap.add_argument("--repeats", type=int, default=1)
    ap.add_argument("--only", help="comma-separated contestant keys")
    ap.add_argument("--workers", type=int, default=4)
    ap.add_argument("--mock", action="store_true")
    a = ap.parse_args(argv)

    if not a.mock:
        from dotenv import load_dotenv
        load_dotenv()
    cs = contestants.build(mock=a.mock)
    if a.only:
        keep = set(a.only.split(","))
        cs = [c for c in cs if c.key in keep]
    cases = load_cases(a.cases, a.limit)
    jobs = [(c, case) for c in cs for case in cases for _ in range(a.repeats)]
    out = Path("results"); out.mkdir(exist_ok=True)
    path = out / f"run-{datetime.now():%Y%m%d-%H%M%S}.jsonl"
    records = []
    with ThreadPoolExecutor(max_workers=a.workers) as pool, path.open("w") as f:
        futs = [pool.submit(one_call, c, case) for c, case in jobs]
        for i, fut in enumerate(as_completed(futs), 1):
            r = fut.result(); records.append(r)
            f.write(json.dumps(r) + "n")
            print(f"[{i}/{len(jobs)}] {r['contestant']:<16}{r['case']} {'ERR ' + r['error'] if r['error'] else 'ok'}", file=sys.stderr)
    print(f"nsaved {path}n")
    print(summarize(records))

if __name__ == "__main__":
    main()

Three design choices deserve a note. First, latency is measured around the SDK call only, using time.perf_counter(), so scoring and JSON parsing never pollute it. Second, a call that still fails after four retries is recorded as an error with every field marked wrong, rather than being dropped. Dropping failures would reward the vendor with the worst reliability. Third, the default of four workers keeps you under most new-account rate limits. Raise it only after the first clean run.

The report module turns the JSONL records into two tables: overall metrics per contestant and field accuracy broken out by invoice layout.

import json, statistics, sys
from collections import defaultdict
from pathlib import Path
from .schema import FIELDS

def pct(n, d): return f"{100 * n / d:.1f}%" if d else "n/a"

def p95(xs):
    xs = sorted(xs)
    return xs[min(len(xs) - 1, int(round(0.95 * (len(xs) - 1))))] if xs else float("nan")

def summarize(records):
    by = defaultdict(list)
    for r in records: by[r["contestant"]].append(r)
    rows = []
    for key, rs in by.items():
        n = len(rs)
        ok_fields = sum(sum(r["fields"].values()) for r in rs)
        perfect = sum(all(r["fields"].values()) for r in rs)
        lat = [r["latency_s"] for r in rs if r["latency_s"] is not None]
        cost = sum(r["cost_usd"] for r in rs)
        rows.append((key, n, pct(ok_fields, n * len(FIELDS)), pct(perfect, n),
                     sum(not r["valid_json"] for r in rs), sum(1 for r in rs if r["error"]),
                     f"{statistics.median(lat):.2f}" if lat else "n/a",
                     f"{p95(lat):.2f}" if lat else "n/a",
                     f"${1000 * cost / n:.2f}", f"${cost / perfect:.4f}" if perfect else "n/a"))
    head = ("model", "docs", "field acc", "perfect", "bad json", "errors", "p50 s", "p95 s", "$/1k docs", "$/perfect doc")
    rows.sort(key=lambda r: -float(r[2].rstrip("%")) if r[2] != "n/a" else 0)
    widths = [max(len(str(x)) for x in col) for col in zip(head, *rows)]
    line = lambda r: "| " + " | ".join(str(x).ljust(w) for x, w in zip(r, widths)) + " |"
    out = [line(head), "|" + "|".join("-" * (w + 2) for w in widths) + "|"] + [line(r) for r in rows]
    lay = defaultdict(lambda: defaultdict(lambda: [0, 0]))
    for r in records:
        c = lay[r["contestant"]][r["layout"]]
        c[0] += sum(r["fields"].values()); c[1] += len(FIELDS)
    layouts = sorted({r["layout"] for r in records})
    return "n".join(out) + "nn" + layout_table(lay, layouts)

def layout_table(lay, layouts):
    head = ["model"] + layouts
    rows = [[k] + [pct(*lay[k][l]) for l in layouts] for k in lay]
    widths = [max(len(str(x)) for x in col) for col in zip(head, *rows)]
    line = lambda r: "| " + " | ".join(str(x).ljust(w) for x, w in zip(r, widths)) + " |"
    return "n".join(["Field accuracy by layout", line(head), "|" + "|".join("-" * (w + 2) for w in widths) + "|"] + [line(r) for r in rows])

def main():
    path = Path(sys.argv[1])
    recs = [json.loads(l) for l in path.read_text().splitlines() if l.strip()]
    print(summarize(recs))
    if "--misses" in sys.argv:
        print(); misses(recs)


def misses(records, limit=10):
    """List the first failing fields so you can read what the model actually returned."""
    shown = 0
    for r in sorted(records, key=lambda r: (r["contestant"], r["case"])):
        bad = [f for f, ok in r["fields"].items() if not ok]
        if bad and shown < limit:
            print(r["contestant"], r["case"], r["layout"], "missed:", ", ".join(bad), "| error:", r["error"])
            shown += 1

if __name__ == "__main__":
    main()

Steps 12-13: Run the Test and Read the Results

Step 12: Smoke test first, then the full run

Start offline. The mock run proves the plumbing before any money moves:

python3 -m bakeoff.run --mock

The runner prints one progress line per call to stderr and the summary to stdout. This is real output from a mock run on the 16 generated documents:

[47/48] mock-c          doc14 ok
[48/48] mock-c          doc15 ok

saved results/run-20261102-195302.jsonl

| model  | docs | field acc | perfect | bad json | errors | p50 s | p95 s | $/1k docs | $/perfect doc |
|--------|------|-----------|---------|----------|--------|-------|-------|-----------|---------------|
| mock-a | 16   | 98.4%     | 87.5%   | 0        | 0      | 0.00  | 0.00  | $2.84     | $0.0032       |
| mock-c | 16   | 90.6%     | 31.2%   | 0        | 0      | 0.00  | 0.00  | $1.42     | $0.0045       |
| mock-b | 16   | 89.1%     | 37.5%   | 0        | 0      | 0.00  | 0.00  | $0.71     | $0.0019       |

Field accuracy by layout
| model  | eu    | ocr    | uk    | us     |
|--------|-------|--------|-------|--------|
| mock-a | 96.9% | 100.0% | 96.9% | 100.0% |
| mock-b | 90.6% | 84.4%  | 87.5% | 93.8%  |
| mock-c | 84.4% | 93.8%  | 90.6% | 93.8%  |

Those numbers describe three fake contestants with deliberately injected errors. They say nothing about Claude, ChatGPT or Gemini. They do confirm that the generator, scorer, cost math and report all work. Notice how the perfect column punishes small error rates: mock-c has a respectable field accuracy but only a small share of perfect documents, because one wrong field spoils a whole record. If a downstream system needs clean records, the perfect-document rate is the number to watch.

Now spend a few cents. Run the three cheapest-to-debug contestants on four documents to catch authentication and model-ID mistakes early:

python3 -m bakeoff.run --limit 4 --only claude-small,gpt-6.1-terra,gemini-4-argon

If all twelve progress lines end in ok, run everything with three repeats, which smooths out run-to-run variation:

python3 -m bakeoff.run --repeats 3 --workers 4

That is one call per contestant, document and repeat. It finishes in a few minutes at four workers and should cost little at current vendor prices.

Step 13: Read the report like a skeptic

Open the summary and work through it in this order. First check the errors and bad json columns. Any nonzero value means a reliability problem or a harness bug, and you should fix or explain it before comparing accuracy. Second, read the layout table. A contestant that scores 100% on US invoices and 85% on European ones has a locale weakness, and the average hides it. Third, apply the rule from step 1: find the best field accuracy, then pick the cheapest contestant within one point of it.

Then read the actual misses. This command prints the first ten failing fields from any results file:

python3 -m bakeoff.report results/run-20261102-195302.jsonl --misses

Real failures usually fall into two buckets. Some are genuine model errors, such as picking the previous balance as the total. Others are harness issues, such as a date in the wrong order or a grader that is too strict. Sorting misses into those two buckets is the most valuable ten minutes of the whole exercise, because it shows whether you are measuring the models or your own grader.

If you want to publish or share your findings, record the date, the exact model IDs, the SDK versions and the Gemini price regime alongside the table. Model behaviour and prices change, and a result without a date is a rumor.

Common Pitfalls That Skew a Three-Way Test

Most bad AI comparisons fail in the setup rather than in the models. These are the traps that catch careful people.

  1. Comparing apps with APIs. The ChatGPT app, the Claude app and the Gemini app all add hidden system prompts, memory and tools. Results from them do not transfer to your code. Use the API for anything you will ship.
  2. Using retired or stale model names. OpenAI retired GPT-5.5 from ChatGPT, Work and Codex on October 14, 2026, and plenty of tutorials still reference it. Check each vendor’s current model list the day you test and write the date down.
  3. Forgetting thinking tokens. Reasoning output is billed as output. A model that thinks for 2,000 tokens before a 100-token answer costs far more than the visible text suggests. Log the vendor’s real usage fields, as the Gemini adapter does.
  4. Ignoring the November 30 price switch. Argon’s introductory $2 and $10 end that day, and December 1 brings $4 and $20. A cost model built in November and reused in December will be off by half.
  5. Letting prompts drift apart. If you tweak the Gemini prompt to fix one failure and leave the others alone, you are no longer comparing models. Change the shared prompt only, then rerun everybody.
  6. Trusting one run. Language models vary between calls. A two-point gap on 16 documents and one repeat is noise. Use repeats, more documents, or both before drawing a conclusion.
  7. Grading too loosely or too strictly. Exact string matching on free text punishes harmless formatting. Fuzzy matching hides real errors. Normalise what is cosmetic (case, whitespace, trailing zeros) and match exactly on everything else.
  8. Overfitting to synthetic data. A generator produces tidy variety. Real scans bring skew, stamps and handwriting. Treat the synthetic score as a check on your plumbing, then validate on a small set of real, redacted documents.

A related trap sits in the price list. Small models are tempting, and the gap is large, as the small-model price comparison with Haiku 5.5 shows. But a cheap model that fails 10% of documents creates review work that can cost more than the savings. The cost per perfect document column exists to expose exactly that trade.

Troubleshooting: 10 Errors and Their Fixes

Expect at least one of these on the first live run. Each row starts from the symptom you will see in the terminal.

Symptom Likely cause Fix
KeyError: 'CLAUDE_FLAGSHIP_MODEL' Env variable missing, or .env not loaded Add both Claude IDs to .env and run from the project root
Anthropic not_found_error on the model Wrong or truncated Claude ID Copy the ID verbatim from the Claude Platform models page
OpenAI 400 about the schema Strict mode needs every property in required and additionalProperties false Keep the schema from step 5 unchanged
OpenAI 400 unsupported parameter A sampling parameter such as temperature on a reasoning-style model Remove the parameter from the call
Gemini unexpected keyword or schema error Old google-genai release without response_json_schema Run pip install -U google-genai
Gemini returns empty text Output cap hit while thinking, or a safety block Print finish_reason and raise the output limit
Many 429 or rate-limit errors Too many parallel workers for a new account Use --workers 2 and keep the backoff
Valid JSON but every field wrong Date or decimal format mismatch in the grader Run --misses and read raw predictions in the JSONL
Cost shows $0.00 Usage fields empty or renamed in the SDK Print resp.usage once and map the new field names
Scores change on every run Normal sampling variation Use --repeats 3 or more and compare averages

Two of these deserve a longer note. When a model returns valid JSON but the grader marks everything wrong, resist the urge to blame the model. Open the JSONL, find one record and compare pred against the case truth by eye. A type mismatch (a string where a number belongs) or an ISO date with the day and month swapped usually explains it. The grader should fail loudly, and the --misses flag is there to show you why.

The second note concerns latency. The first call to any vendor includes connection setup, so a single slow outlier is normal. That is why the report shows both p50 and p95. If p95 is ten times the median for one vendor, you have found a tail-latency problem worth knowing about before it hits a user.

Advanced Tips: Take the Harness Further

Once the baseline works, these upgrades give the most value for the least effort.

Add statistical honesty

Report a confidence interval, not just a percentage. For a pass rate, the Wilson interval is a good default and fits in a dozen lines of standard-library Python:

from math import sqrt

def wilson(successes, n, z=1.96):
    if n == 0:
        return (0.0, 0.0)
    p = successes / n
    denom = 1 + z * z / n
    centre = (p + z * z / (2 * n)) / denom
    half = z * sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denom
    return (centre - half, centre + half)

print(wilson(125, 128))   # field-level pass rate for one contestant

If two contestants’ intervals overlap heavily, the honest conclusion is no detectable difference at this sample size. That is a legitimate and useful result.

Use caching and batch pricing

Your system prompt and schema repeat on every call, which makes them ideal for prompt caching. Google says cached input for Argon costs 95% less than the standard input price, and Anthropic lists cache reads for Opus 5.5 at $0.20 per million tokens against $4 for fresh input. For large nightly jobs, Anthropic also advertises a 50% saving with batch processing. Rerun the harness with caching on and compare cost per thousand documents. The saving can be larger than the gap between two vendors.

Test the ceiling and the floor

Add GPT-6 Astra, which OpenAI lists at $10 per million input tokens and $50 per million output tokens, as a ceiling run to see what the most capable GPT-6 model buys on your task. Add the small models from every vendor as the floor. A ceiling that barely beats your pick tells you to stop paying for more. Leave Gemini 4 Carbon out until it ships generally, since Google limited it to trusted testers and selected cyber defenders when it announced the model on October 28.

Move from text to real PDFs

Invoice text is the easy mode. To test real documents, send the PDF or page images through each vendor’s file or image input. Anthropic describes Opus 5.5 as able to read dense documents, charts, screenshots and diagrams, and the other two vendors market similar abilities. Document handling is where vendors differ most in API shape, so keep the adapter boundary and change only the call inside it. Measure token counts again, because images and PDFs inflate input tokens sharply.

Run it on a schedule

Put the harness in a weekly CI job that runs on a fixed document set and writes results to a dated file. When a vendor ships a new model, you add one line to contestants.py and see within minutes how it compares with last month’s winner. Keep the documents, the seed and the prompt frozen so only the model changes. This turns the one-time tutorial into a regression test for your AI vendor choices.

Frequently Asked Questions

Is this a fair ChatGPT vs Claude vs Gemini comparison?

It is fair for one task. All contestants get the same prompt, schema and documents, and the grader never sees which model produced an answer. It is not a general ranking, because extraction accuracy says little about coding, writing or reasoning quality.

Why does the test use the API instead of the ChatGPT, Claude and Gemini apps?

The apps add system prompts, memory and tools that you cannot control or reproduce. The API gives you fixed inputs, exact token counts and prices, which are the things a production decision needs. App plans such as ChatGPT Plus, Claude Pro and Google AI Pro are billed separately from API usage. You can check the consumer tiers on ChatGPT’s pricing page.

How much does the full test cost?

The run makes one call per contestant, document and repeat. With the assumed 700 input and 120 output tokens per call, the cost per document stays small even for Claude Opus 5.5, but check each vendor’s current price page before relying on it. Your real token counts will vary, and thinking tokens add to output cost.

Which models should I test right now?

Test the newest generation from each vendor: Claude Opus 5.5 and Haiku 5.5, GPT-6.1 Sol and Terra, and Gemini 4 Argon. As of November 2, 2026, Gemini 4 Carbon is limited to trusted testers and is not generally available. Recheck the vendors’ model pages before each run, because lineups are changing fast.

What happens to Gemini costs on December 1, 2026?

Google lists Argon at $2 per million input tokens and $10 per million output tokens through November 30, 2026, then $4 and $20 from December 1. The pricing.py module in this project switches rates by date automatically, so rerun your cost table after the change.

Can I use my own documents instead of synthetic invoices?

Yes, and you should once the plumbing works. Redact personal data, label 30 to 50 documents by hand into the same JSONL format with a truth object, and point the runner at that file with --cases. Keep the synthetic set as a regression check for the harness itself.

How many documents do I need before trusting the result?

For a first read, 16 documents with 3 repeats is enough to catch big gaps and broken setups. For a purchasing decision, aim for at least 100 documents and report confidence intervals. If the intervals overlap, treat the models as tied on accuracy and decide on price and latency.

Does this harness work for other tasks?

It does. Replace the schema, the prompt and the case generator, and keep everything else. Classification, entity extraction and routing tasks all fit the same pattern, since each has a checkable answer.

Source: Tech Insider