GyaanStack. Blog

Articles / llmevalsllmops

How to choose an LLM for your project: requirements, a small eval and cost per task

Pick an LLM by measuring it on your own task. Write requirements, build a 15-item eval, run candidates, then work out cost per task from official prices.

By Raghunath · · 19 min read

Leaderboards rank models on someone else's task. Your project has its own inputs, its own idea of a correct answer, a latency budget and a monthly bill. The model that wins on those four is often a small, cheap one, and you only find out by measuring.

This post is a method you can run in an afternoon:

  1. Decide whether the problem needs an LLM at all.
  2. Write the requirements down, and split them into hard limits and things you trade off.
  3. Build a small eval set from real inputs.
  4. Run two or three candidates on it and record accuracy, latency and tokens.
  5. Turn the token counts into cost per task with the providers' own price lists.

The worked example runs two local models through Ollama on a 15-item support-ticket eval, then prices the same workload on six hosted models. Prices and model names come from the Anthropic, OpenAI and Google pricing pages as they stood on 24 November 2026.

  candidates (dozens)
        |
        v
  [1] hard limits: privacy, licence, context, region   --> drops most
        |
        v
  [2] eval set on your own inputs (15 items, then 100+)
        |
        v
  [3] score: accuracy, p50/p95 latency, tokens per task
        |
        v
  [4] cost per task x monthly volume, from official prices
        |
        v
  pick the cheapest model that clears the quality bar

Step 0: check you need an LLM#

Some problems are cheaper and more accurate without one.

If the data is a table of numbers and categories (churn, credit risk, demand), a gradient-boosted tree from XGBoost, LightGBM or scikit-learn trains in minutes, runs in microseconds per row, and gives you feature importances to show a reviewer. An LLM adds cost and removes the explanation.

If the rule can be written down, write it down. Pulling a five-digit order number out of a message is a regular expression. Routing by a dropdown the user already picked is an if statement. Use the LLM for the part that is messy language: free-text complaints, emails, PDFs, questions phrased fifty different ways.

A common split is a cheap model or a rule for the bulk of traffic and a stronger model only for the cases the cheap path is unsure about. Keep that option in mind while you evaluate, because it changes which model you need.

Step 1: write the requirements#

Six questions settle most of the choice. Write the answer to each before opening any model catalogue.

Requirement Question to answer Example answer
Quality What does a correct output look like, and what score is good enough? 95% of tickets get the right queue
Latency What p95 can the user or pipeline tolerate? under 2 s, a human is waiting
Cost What volume, and what budget per month? 300,000 tickets, under $200
Context How long are the inputs, including retrieved documents? 150 tokens, no retrieval
Data privacy Can the data leave your network? Which provider terms apply? customer PII, contract with provider required
Licence For open-weight models, may you use it commercially at your scale? yes, under 700M MAU

Some rows are hard limits. If patient records may not leave your servers, every hosted API is out no matter how good it is, and the question becomes which open-weight model you can host. Read the licence too. Qwen3-4B-Instruct-2507 is Apache 2.0. Llama 3.2 ships under the Llama 3.2 Community License, which requires a separate licence from Meta for products with more than 700 million monthly active users. The open-source LLMs guide covers that side in more depth.

Privacy also depends on the tier, not only the provider. Google's Gemini API pricing page says free-tier content is used to improve its products and paid-tier content is not. Prototype on the free tier with synthetic data, not real customer messages.

The other rows are trade-offs. A model 2 points more accurate at 20 times the price can be the right call for legal review and the wrong one for ticket routing. You can only make that call with numbers, which is what the next steps produce.

Step 2: build a small eval set#

An eval set is a list of real inputs with the answer you expect. For a first cut, 15 to 30 items is enough to separate a model that works from one that does not. Before you commit, grow it to 100 or more so a 3-point gap means something.

Rules that make a small set useful:

  • Take inputs from production logs or real user messages, with personal data removed. Invented examples are cleaner than real ones and flatter every model.
  • Put the hard cases in on purpose: two problems in one message, a number that is not an order ID, an angry message that is about billing.
  • Use answers you can check with code. A label, a number, a JSON field. Exact match is cheap and has no judge bias.
  • Freeze the set and version it. If you edit items between runs, you can't compare runs.

When the output is free text, such as a summary or an email draft, exact match stops working. Then you need a rubric and a grader, and the LLM-as-a-judge post shows how to build one and check it against human labels.

The example task: triage a support message into one of four queues (billing, shipping, bug, feature_request) and extract the order ID if there is one, as JSON. Three of the fifteen items are traps. Item 9 asks to swap a wrong size (shipping, even though it mentions refunds). Item 10 mentions two rupee amounts that are not order IDs. Item 14 has a refund problem and an app problem in the same message.

{"id": 9, "text": "I got the wrong size in order 61834 and want to swap it, not a refund.", "label": "shipping", "order_id": "61834"}
{"id": 10, "text": "Why did my subscription price go up from 499 to 599 rupees without notice?", "label": "billing", "order_id": null}
{"id": 14, "text": "Refund for order 22981 still not in my account after 10 days. The app also logged me out twice.", "label": "billing", "order_id": "22981"}

Step 3: run the candidates#

The runner below puts every model behind one small interface, complete(system, user), that returns the text, input and output token counts, and compute time. The Ollama class calls a local model with no API key. The hosted class is a stub: replace its body with the provider SDK call and read the token counts from the response's usage field. The scoring and reporting code does not change when you swap providers.

"""Run one eval set against several models and report accuracy, latency and tokens."""
import json, statistics, sys, urllib.request
from typing import Protocol

LABELS = ["billing", "shipping", "bug", "feature_request"]
SYSTEM = (
    "You triage customer support messages. Reply with JSON only: "
    '{"label": one of ' + json.dumps(LABELS) + ', "order_id": the 5-digit order number as a string, or null}. '
    "If a message mentions several problems, pick the one about money or the order first."
)


class Model(Protocol):
    name: str
    def complete(self, system: str, user: str) -> dict: ...
    # must return {"text": str, "in_tokens": int, "out_tokens": int, "model_ms": float}


class OllamaModel:
    """Local model through Ollama's /api/chat endpoint (no API key)."""
    def __init__(self, name: str, host: str = "http://localhost:11434"):
        self.name, self.host = name, host

    def complete(self, system, user):
        body = {
            "model": self.name, "stream": False, "format": "json", "think": False,
            "options": {"temperature": 0, "num_ctx": 2048, "num_predict": 64},
            "messages": [{"role": "system", "content": system}, {"role": "user", "content": user}],
        }
        req = urllib.request.Request(f"{self.host}/api/chat", json.dumps(body).encode(),
                                     {"Content-Type": "application/json"})
        with urllib.request.urlopen(req, timeout=1800) as r:
            out = json.load(r)
        return {"text": out["message"]["content"],
                "in_tokens": out.get("prompt_eval_count", 0), "out_tokens": out.get("eval_count", 0),
                # compute time only (nanoseconds -> ms), so queueing behind other jobs is excluded
                "model_ms": (out.get("prompt_eval_duration", 0) + out.get("eval_duration", 0)) / 1e6}


class HostedModelStub:
    """Placeholder for a hosted API. Replace complete() with the provider SDK call,
    e.g. client.messages.create(...) or client.responses.create(...), and read the
    token counts from the response's usage field."""
    def __init__(self, name: str):
        self.name = name

    def complete(self, system, user):
        raise NotImplementedError("wire up the provider SDK here")


def score(item, text):
    try:
        got = json.loads(text)
    except json.JSONDecodeError:
        return False, False, "bad_json"
    label_ok = got.get("label") == item["label"]
    oid = got.get("order_id")
    oid = str(oid) if oid not in (None, "", "null") else None
    return label_ok, oid == item["order_id"], None


def run(model: Model, items):
    model.complete(SYSTEM, "warm-up")  # load weights before timing
    rows = []
    for it in items:
        r = model.complete(SYSTEM, it["text"])
        ms = r["model_ms"]
        label_ok, oid_ok, err = score(it, r["text"])
        rows.append({"id": it["id"], "label_ok": label_ok, "oid_ok": oid_ok, "both": label_ok and oid_ok,
                     "err": err, "ms": ms, "in": r["in_tokens"], "out": r["out_tokens"], "raw": r["text"]})
    return rows


def summary(name, rows):
    n = len(rows)
    ms = sorted(r["ms"] for r in rows)
    p95 = ms[min(n - 1, round(0.95 * (n - 1)))]
    return {"model": name,
            "label_acc": sum(r["label_ok"] for r in rows) / n,
            "order_id_acc": sum(r["oid_ok"] for r in rows) / n,
            "both_acc": sum(r["both"] for r in rows) / n,
            "bad_json": sum(r["err"] == "bad_json" for r in rows),
            "p50_ms": statistics.median(ms), "p95_ms": p95,
            "avg_in": statistics.mean(r["in"] for r in rows),
            "avg_out": statistics.mean(r["out"] for r in rows)}


if __name__ == "__main__":
    import os
    host = os.environ.get("OLLAMA_HOST_URL", "http://localhost:11434")
    items = [json.loads(l) for l in open("eval_set.jsonl")]
    results = {}
    for name in sys.argv[1:]:
        rows = run(OllamaModel(name, host), items)
        results[name] = rows
        json.dump(results, open("results.json", "w"), indent=1)  # save after each model
        s = summary(name, rows)
        print(f"{s['model']:<14} label {s['label_acc']:.0%}  order_id {s['order_id_acc']:.0%}  "
              f"both {s['both_acc']:.0%}  bad_json {s['bad_json']}  p50 {s['p50_ms']:.0f} ms  "
              f"p95 {s['p95_ms']:.0f} ms  avg tokens in/out {s['avg_in']:.0f}/{s['avg_out']:.0f}")
        for r in rows:
            if not r["both"]:
                print(f"    miss id={r['id']}: {r['raw']}")

A few details matter for a fair comparison. Temperature is 0, so reruns give the same answer. format: "json" asks Ollama for structured output, the same way you would ask a hosted API for JSON mode. think: False turns off thinking for models that support it. One warm-up call loads the weights so the first item is not charged the load time.

Latency is read from Ollama's own prompt_eval_duration and eval_duration fields (usage docs) instead of a wall clock. The GPU on this machine was shared with other jobs, and a wall clock would have measured time spent waiting in the queue. For a hosted API, measure wall-clock time from your own server instead, because network and provider queueing are part of what your users feel.

Step 4: read the results#

The run below is real output from a MacBook whose GPU was shared with other jobs at the time. Three very long lines are cut with ... where the 64-token cap stopped them.

$ python3 choose.py qwen3:4b-instruct llama3.2:1b
qwen3:4b-instruct label 93%  order_id 100%  both 93%  bad_json 0  p50 1878 ms  p95 2295 ms  avg tokens in/out 96/16
    miss id=7: {"label": "feature_request", "order_id": null}
llama3.2:1b    label 40%  order_id 53%  both 27%  bad_json 3  p50 1156 ms  p95 2805 ms  avg tokens in/out 106/26
    miss id=2: {"label": "bug", "order_id": "1234567890"}
    miss id=3: {"label": "billing", "order_id": "77120"}
    miss id=4: {"label": "dark_mode", "order_id": null}
    miss id=6: {"label": "billing", "order_id": "55102", "label": "created", "order_id": "55102", "label": "created", ...
    miss id=7: {"label": "bug", "order_id": "12345", "date_filter": null}
    miss id=8: {"label": "billing", "order_id": "123456789", "email_addresses": ["billing@example.com", "support@example.com"]}
    miss id=9: {"label": "billing", "order_id": "61834"}
    miss id=10: {"label": "billing", "order_id": "12345", "label": "bug", "order_id": "67890", "label": "feature_request", ...
    miss id=11: {"label": "billing", "order_id": "12345678", "label": "bug", "order_id": "12345678", "label": "shipping", ...
    miss id=12: {"label": "tax_rate", "order_id": "1234567890"}
    miss id=13: {"label": "billing", "order_id": "30457"}
Model Label Order ID Both right Bad JSON p50 p95 Tokens in/out
qwen3:4b-instruct 93% 100% 93% (14/15) 0 1,878 ms 2,295 ms 96 / 16
llama3.2:1b 40% 53% 27% (4/15) 3 1,156 ms 2,805 ms 106 / 26

Qwen3-4B got all three trap items right. Its one miss is item 7, an export that writes an empty file, which it filed as a feature request. That is a bug, and the system prompt never says what separates the two, so the fix is one sentence in the prompt.

Llama 3.2 1B failed in four different ways, and each one is a different production problem:

  • It invents order IDs when there are none (1234567890 on item 2, 12345 on item 7). A downstream system would look up an order that does not exist.
  • It invents labels outside the list (dark_mode, tax_rate). Code that routes on the label breaks on these.
  • It adds fields nobody asked for (date_filter, email_addresses with made-up addresses).
  • On items 6, 10 and 11 it repeated the same keys until it hit num_predict, which left truncated JSON. Without that cap, a looping model keeps generating until the context fills, and each such call costs seconds. Always set an output cap.

The 1B model has the lower p50, but its p95 is worse because the looping calls ran to the cap. Neither latency would pass a strict sub-second budget on this machine, so latency on your own serving hardware is a separate test.

The verdict for this task: drop the 1B model, it is not close. Qwen3-4B is at 93% against a 95% bar, which on 15 items means one answer. Fix the bug-versus-feature wording, grow the set to 100 items, and rerun before deciding. In the same pass, run one or two cheap hosted models through HostedModelStub so the comparison covers both options.

Step 5: cost per task#

Cost per task is two multiplications:

cost per task = input_tokens  x input_price  / 1,000,000
              + output_tokens x output_price / 1,000,000

Multiply by monthly volume and compare against the budget from step 1. The script below holds the list prices (standard tier, no caching, no batch discount) copied from the Anthropic, OpenAI and Google pricing pages on 24 November 2026.

"""Cost per task and per month from token counts and list prices (USD per 1M tokens).
Prices copied from the official pricing pages on 2026-11-24, standard tier, no caching or batch."""

PRICES = {  # model: (input $/MTok, output $/MTok)
    "claude-haiku-5.5":              (0.10, 0.50),   # prompts up to 100k tokens
    "claude-sonnet-5.5":             (2.00, 10.00),
    "gpt-6-luna":                    (0.10, 0.50),
    "gpt-6.2-sol":                   (2.00, 10.00),
    "gemini-3.5-flash-lite":         (0.30, 2.50),
    "gemini-3.8-flash (to 31 Dec)":  (0.75, 3.75),
    "gemini-3.8-flash (from 1 Jan)": (1.50, 7.50),
}

def cost_per_task(in_tok, out_tok, price_in, price_out):
    return (in_tok * price_in + out_tok * price_out) / 1_000_000

if __name__ == "__main__":
    # token counts measured on the 15-item eval (qwen3:4b-instruct); hosted tokenizers differ a little
    IN_TOK, OUT_TOK, TASKS_PER_MONTH = 96, 16, 300_000
    THINKING = 300  # extra output tokens if reasoning is left on (billed as output)
    print(f"{IN_TOK} input + {OUT_TOK} output tokens per ticket, {TASKS_PER_MONTH:,} tickets/month\n")
    print(f"{'model':<30}{'$/1k tickets':>13}{'$/month':>10}{'$/month +300 thinking':>23}")
    for name, (pi, po) in PRICES.items():
        c = cost_per_task(IN_TOK, OUT_TOK, pi, po)
        t = cost_per_task(IN_TOK, OUT_TOK + THINKING, pi, po)
        print(f"{name:<30}{c * 1000:>13.4f}{c * TASKS_PER_MONTH:>10.2f}{t * TASKS_PER_MONTH:>23.2f}")
96 input + 16 output tokens per ticket, 300,000 tickets/month

model                          $/1k tickets   $/month  $/month +300 thinking
claude-haiku-5.5                     0.0176      5.28                  50.28
claude-sonnet-5.5                    0.3520    105.60                1005.60
gpt-6-luna                           0.0176      5.28                  50.28
gpt-6.2-sol                          0.3520    105.60                1005.60
gemini-3.5-flash-lite                0.0688     20.64                 245.64
gemini-3.8-flash (to 31 Dec)         0.1320     39.60                 377.10
gemini-3.8-flash (from 1 Jan)        0.2640     79.20                 754.20

At about 100 input and 16 output tokens per ticket, every hosted option is cheap. The two small models cost $5.28 a month for 300,000 tickets, and the two large ones cost $105.60. For a short classification task the monthly bill rarely decides it; quality, privacy and latency do. Self-hosting the 4B model only beats $5.28 a month if you already run the GPU for something else, or if the data may not leave your network.

The numbers change fast once any of these apply:

  • Reasoning tokens. Thinking tokens are billed as output. Google's page says so in its price labels ("output price including thinking tokens"). An extra 300 thinking tokens per ticket takes the large models from $105.60 to $1,005.60 a month. For classification, turn reasoning off or set it to the lowest level the model allows, and rerun the eval with it off to confirm accuracy holds.
  • Scheduled price changes. Gemini 3.8 Flash costs $0.75 input and $3.75 output until 31 December 2026, then $1.50 and $7.50 from 1 January 2027. Gemini 4 Carbon doubles on 1 December 2026. A cost model built this week is wrong in five weeks unless you date it.
  • Price tiers by prompt length. Claude Haiku 5.5's $0.10 / $0.50 applies to prompts up to 100,000 tokens. Above that it is $0.50 / $2.50. If you plan to paste long documents, use the long-context row.
  • Tokenizers. 96 tokens is Qwen's count for these prompts. Claude, GPT and Gemini tokenize differently, so take the real counts from each API's usage field on your eval run and put those into the script.
  • Batch and caching. Anthropic, OpenAI and Google all list a Batch API at half the standard price, which fits overnight jobs. Prompt caching cuts the price of a repeated prefix, which matters when the system prompt is long and the user message is short.

Failure modes that skew the choice#

A test set that is too easy. If every candidate scores 100%, the set has no signal and you will pick on price alone, then find the gap in production. Add the hard cases until at least one model fails some of them.

Tuning the prompt on the test set. Each time you edit the prompt after reading failures, you fit the prompt to those 15 items. Keep a second set the prompt never saw and report the final number on it.

Comparing one model's best prompt against another's first try. Give each finalist an hour of prompt work, or none.

Ignoring output format failures. A model that returns invalid JSON 1 time in 50 needs a retry path, and the retry doubles cost and latency for those calls. Count bad_json separately from wrong answers, as the runner does.

Pricing from memory. Prices move, sometimes on a set date. Re-read the pricing pages on the day you decide, and record the date next to the numbers.

Measuring latency on an idle machine. The p95 under real concurrency can be several times the p50 on a quiet box. Before launch, run the eval at your expected request rate, and keep tracking it in production. The cost and latency tracker post logs tokens, latency and cost for every call to SQLite.

Agents change the arithmetic#

An agent calls the model in a loop, once per step, and each step resends the conversation so far. A ticket that costs one call in a classifier can cost 10 to 30 calls in an agent, with input tokens growing every step. Two consequences follow. Price the whole task, not one call: run the agent on your eval items and add up the usage from every step. And prompt caching matters far more, because most of each step's input is the same prefix as the step before. On Anthropic's price list a cache hit costs a fraction of base input (0.1x on most models, 0.05x on Claude Sonnet 5.5), so an agent with caching on can cost a fraction of the uncached figure.

It also opens a cheaper design: a strong model plans and a small model does the many narrow steps. The LLM tech stack post covers where routing and gateways fit when you run more than one model.

A one-page decision record#

When the eval is done, write the decision down so the next person can rerun it:

Task:            support ticket triage, JSON {label, order_id}
Eval set:        eval_set.jsonl v1, 15 items (grow to 100 before launch)
Hard limits:     PII -> provider with data-processing terms, or self-hosted
Candidates:      qwen3:4b-instruct, llama3.2:1b (local); haiku-5.5, gpt-6-luna,
                 gemini-3.5-flash-lite (hosted, next run)
Scores:          label %, order_id %, both %, bad_json, p50/p95 ms, tokens in/out
Prices (date):   from official pages, 2026-11-24
Decision:        cheapest model that cleared 95% on "both"
Re-run when:     new model release, price change, or prompt change

Rerun the same eval set whenever a provider ships a new model or changes a price. With the runner and the set already written, that takes minutes, and the decision stays based on your task instead of a leaderboard.

Sources#

Found this useful? You can buy me a coffee or support with any amount. It pays for hosting and keeps new articles coming.