Skip to content

Evaluation and modelsMethodology

What does one AI coding agent task cost? A per-task method

A coding agent bill is a monthly total, not a unit cost. This method tags every agent loop with a task id, prices tokens by class, counts retries as their own line, and divides all spend, failed attempts included, by merged pull requests.

By INFRO Editorial

Published

9 min read

A single amber path on a dark ground forking into two glass branches of slightly different brightness

In short

Cost per task is the priced token spend of every request that shares a task id, retries and abandoned attempts included. Cost per merged pull request is that total divided by accepted outcomes only. Tag the task, price four token classes, record the outcome, then report median and p90.

Key takeaways

  • A task is the unit: give every agent launch a task id and send it on every model request so spend can be grouped by task, not by day or seat.
  • Price four token classes separately (uncached input, cache write, cache read, output); in a long agent loop cache reads dominate the token count but not always the dollars.
  • Count retries as their own lines (provider retry, agent self-retry, CI-fix loop, human re-prompt) so you can see which kind inflates cost.
  • Cost per merged pull request divides all spend, abandoned attempts included, by accepted outcomes only; it is always above the mean cost per task.
  • Report median and 90th percentile per task, and flag runs whose cost is partial or unpriced instead of averaging them in.

Why the monthly bill cannot answer this

A provider invoice or a seat report says how much the team spent. It cannot say what a merged pull request cost, because the unit that matters (one task, from ticket to merge or abandonment) is not a column in any billing export. Two engineers can spend the same amount in a week, one landing nine small PRs and the other landing one after four abandoned attempts.

This method builds the missing column. It has four parts: give every agent launch a task id, meter the requests under that id, price them at your own rates, and divide by accepted outcomes. The team-level view is in coding agent costs for teams, and the general metric is in cost per successful task. This post covers what those do not: the loop inside one agent task, where a single prompt becomes dozens of model calls.

Define the task and the accepted outcome first

Decide two things before you measure anything, because changing them later makes old numbers incomparable.

  • Task: one unit of work handed to an agent, usually one ticket or one prompt that is expected to produce one branch. A human re-prompt after a failure is inside the same task; a new ticket is a new task.
  • Accepted outcome: the event that makes the spend worth it. For a coding agent this is typically "pull request merged, CI green, not reverted within N days". Pick N once (seven is common) and write it down.

Everything else is bookkeeping around those two definitions. A task that ends without an accepted outcome is not excluded; its cost stays in the numerator. That is the whole point of the metric.

What to meter per task

An agent loop reads files, calls tools, runs tests, reads the output and calls the model again. Each model call re-sends a growing context. Record these per task:

MeasureWhy it mattersWhere it comes from
Uncached input tokensBilled at the full input rateProvider usage on each request
Cache write tokensBilled above the input rateProvider usage
Cache read tokensMost of a long loop's volume, at a small fraction of the input rateProvider usage
Output tokens (including reasoning)Highest rate per tokenProvider usage
Model callsLoop length; the multiplier on context re-sendsCount of requests under the task id
Tool callsTime and, for server-side tools, separate chargesAgent logs or an MCP/tool gateway log
Retries, by kindSpend that bought nothingSee the next section
Model used per callRates differ by model and by prompt sizeRequest record
OutcomeThe divisorYour VCS and CI

Token classes must be kept apart. Anthropic's published API rates show why: for Sonnet 5.5 the listed rates are $2 per million input tokens, $2.50 to write cache, $0.10 to read cache and $10 for output1. A task that re-reads a large cached context forty times is mostly cache reads by volume, but a single uncached rewrite of that context costs far more than all the reads that follow it.

Two rate quirks matter in loops. Haiku 5.5 is listed at a higher input and output rate for prompts above 100K tokens than at or below it1, and context grows as a loop proceeds, so a task can cross that line mid-run. Fast mode for Opus 5.5 and Fable 5.2 is listed at 2x standard pricing, and US-only inference at 1.1x1. Record the mode per request, or your price table will quietly be wrong.

For span-level instrumentation, OpenTelemetry has GenAI semantic conventions for model and agent spans, but its site now says they have moved to a separate repository and are no longer maintained on that page2. Check the current attribute names there rather than copying them from an older blog post, and add your own task id attribute alongside them.

Separate the four kinds of retry

"Retries" hides four different costs with four different fixes. Tag each one so the task record can show which dominates.

  1. Transport retry or failover: a request that failed before any answer and was re-sent. Usually cheap, since a failed request often bills little or nothing, but check your provider's rules for partial streams.
  2. Agent self-retry: the agent runs the tests, they fail, it edits and runs again. This is the normal loop and the largest controllable cost.
  3. CI-fix loop: the PR is opened, CI fails, the agent is relaunched to repair it. Same task id, new loop.
  4. Human re-prompt: a reviewer rejects the diff and asks again. Count it in the task; it often doubles the context.

A practical rule: if the second, third and fourth kinds do not share a task id with the first attempt, your cost per merged PR will be understated by exactly the rework you wanted to see.

Price it: the formula and a worked example

Cost per task is a sum over requests, using the rates your own provider account bills. List rates are a starting point; if you hold a negotiated rate, use it instead.

Text
task_cost = Σ over requests r in task:
    uncached_input(r) × input_rate(model(r), size(r))
  + cache_write(r)    × write_rate(model(r), size(r))
  + cache_read(r)     × read_rate(model(r), size(r))
  + output(r)         × output_rate(model(r), size(r))

cost_per_merged_pr = Σ task_cost over ALL tasks in the window
                     ÷ count(tasks with an accepted outcome)

Notice that output tokens are 4% of the token volume in this example but a third of the cost. That is the usual shape, and it is why a rule such as "cheap model for exploration, strong model for the final edit" can be tested per task rather than argued about.

Tag the task at the source

The measuring is only as good as the task id. The simplest reliable place to set it is the harness that launches the agent, not the agent itself, because the harness knows the ticket and later learns the outcome.

With a gateway in the path, the id rides as a header on every request the agent makes. INFRO groups requests that share a trace id into one run per workflow, and accepts the id as metadata.trace_id or the X-INFRO-Trace-Id header, alongside metadata.workflow3. Claude Code can be pointed at INFRO by changing the base URL and key, and extra headers can be set through ANTHROPIC_CUSTOM_HEADERS4. Because that variable is per process, a wrapper can give each task its own value:

run_task.py
import os, subprocess, uuid, requests

BASE = "https://api.infro.io"
KEY = os.environ["INFRO_API_KEY"]  # a gateway key with its own spend limit

def run_task(ticket_id: str, prompt: str) -> str:
    trace_id = f"task_{ticket_id}_{uuid.uuid4().hex[:8]}"
    env = dict(
        os.environ,
        ANTHROPIC_BASE_URL=BASE,
        ANTHROPIC_AUTH_TOKEN=KEY,
        ANTHROPIC_CUSTOM_HEADERS=(
            f"X-INFRO-Trace-Id: {trace_id}\n"
            "X-INFRO-Workflow: coding-agent"
        ),
    )
    subprocess.run(["claude", "-p", prompt], env=env, check=False)
    return trace_id  # store it on the ticket for the CI-fix and re-prompt loops

def record_outcome(trace_id: str, merged: bool) -> None:
    requests.post(
        f"{BASE}/v1/scores",
        headers={"Authorization": f"Bearer {KEY}"},
        json={"scores": [
            {"trace_id": trace_id, "name": "merged", "value": merged},
            {"trace_id": trace_id, "name": "accepted", "value": 1 if merged else 0},
        ]},
    )

Reuse the same trace_id when the CI-fix loop or a human re-prompt relaunches the agent on that ticket. Other clients and other gateways can do the same with their own header; the requirement is only that every model request carries one stable id.

Join cost to outcome and read the distribution

Once requests share an id and the outcome is a score on that id, the join is a query. INFRO's runs list returns one row per run with request count, error count, duration, models and estimated provider cost, and can be sorted by cost or filtered by minimum cost and by errors3. Scores can be posted on a run from your code, as a number, a boolean or a category5.

Shell
# Costliest coding-agent runs in the window, with their scores
curl "https://api.infro.io/v1/runs?workflow=coding-agent&sort=costliest&limit=100" \
  -H "Authorization: Bearer $INFRO_API_KEY"

# Runs whose mean numeric score is below 1: tasks that were not accepted
curl "https://api.infro.io/v1/runs?workflow=coding-agent&score_below=1" \
  -H "Authorization: Bearer $INFRO_API_KEY"

The score_below filter works on numeric scores only and leaves out runs with none3, which is why the example above posts a 1 or 0 accepted score next to the boolean. A single run window is limited to 31 days3, so export weekly into your own warehouse if you want quarter-on-quarter trends.

From the joined table, report five figures per period and per model:

  • Median cost per task and 90th-percentile cost per task.
  • Acceptance rate (accepted tasks ÷ all tasks).
  • Cost per merged PR (all spend ÷ accepted tasks).
  • Waste ratio: spend on non-accepted tasks ÷ total spend.
  • Model calls per task, median and 90th percentile.

Cost is skewed. A mean hides the handful of runaway loops; the 90th percentile exposes them, and the costliest-first list tells you which tasks to read.

Traps that distort the number

  • Partial pricing. A run that includes a request with no known rate is understated. INFRO's run rows carry cost_is_partial and unpriced_requests fields3; exclude or flag those runs rather than averaging them in.
  • Estimate versus invoice. A per-request cost computed from usage and a rate table is an estimate. Compare it with what the provider actually billed on a schedule, and apply your contract rates where they differ from list. A persistent gap means the rate table is wrong, not that the method is.
  • Seat usage is not metered per task. Plan seats carry usage limits rather than a per-token bill1. Use API-key or gateway traffic to get task figures, or run a fixed task set through an API key as a proxy.
  • Survivorship. If only merged tasks get a task id and abandoned ones are untagged, the metric looks excellent and means nothing. Assign the id at launch.
  • Task mix. A one-line fix and a cross-module refactor are not the same unit. Segment by size label or repository before comparing models or teams.
  • Idle loops. Cost can accrue after a task is effectively dead. Bound steps, time and spend per task; see bounding agent loops.

Where a gateway helps, and where it does not

Everything above can be built from provider usage exports plus your own harness. A gateway shortens the join: with INFRO, requests from Claude Code or Codex pass through your own provider connections, each is logged with its model, token counts and estimated provider cost, and a run groups them by trace id6. A gateway key can carry its own spend limit, so a runaway task is refused before the provider is called4. Your provider still invoices you directly at your own rates, and INFRO's figure is an estimate that daily reconciliation compares against the provider's reported cost. INFRO sees request metadata, not whether a diff was any good; the merged-or-not outcome has to come from your VCS and CI, as in the code above.

For tracing the steps inside a task, see tracing an agent run.

A one-week rollout

  • Write the task and accepted-outcome definitions, including the revert window.
  • Wrap agent launches so every task gets an id at launch, not at merge.
  • Reuse the id for CI-fix loops and human re-prompts on the same ticket.
  • Load your contracted rates, falling back to list rates only where you have none.
  • Post the outcome as a score or column when the PR merges, closes or ages out.
  • Publish median, p90, acceptance rate, cost per merged PR and waste ratio, by model and repo.
  • Read the ten costliest tasks each week before changing any model or limit.

Questions readers ask

Does a Claude Code or Codex seat price tell me the cost per task?
No. A seat is a flat monthly charge with usage limits, so it carries no per-task meter. Anthropic's Enterprise plan is listed as a seat price plus usage at API rates 1; that usage part is what you can price per task. For seat-only users, estimate by running the same task set through an API key and use that as a proxy.
How many tasks do I need before the number is stable?
There is no fixed threshold. Watch the median and the 90th percentile as the sample grows and stop when a week of added tasks no longer moves them. Task cost is skewed, so the 90th percentile settles slowest; a handful of runaway loops can dominate a small sample.
Should reviewer time count toward the cost of a merged pull request?
Keep it as a separate column. Token spend is a provider-billed cost you can meter exactly; reviewer and rework time is a salary estimate. Adding them into one figure hides which lever (model choice, loop bounds, prompt quality) moved.

From the team that builds it

Where this shows up in INFRO

INFRO is a control plane in front of the provider accounts you already hold. The capabilities below are the parts of it this article touches, each with the documentation that defines its behaviour.

  • Runs

    Available with a plan

    Requests that share a trace id listed as one run each: requests, errors, duration, models, estimated provider cost, scores and prompt versions, filtered and sorted over a window of up to 31 days. In the API, the console, the management API and MCP, on every plan.

  • Scores and end-user feedback

    Available with a plan

    Scores on a request or a run from your code, from eval monitors and from members in the console, and feedback from the people reading your answers: each response carries a signed token a browser can send with a thumbs up or down, without an API key. Scores do not count against the request allowance. On every plan.

  • Claude Code and Codex through INFRO

    Available with a plan

    Point Claude Code, the Claude Agent SDK, Codex or the OpenAI Agents SDK at INFRO by changing the base URL and the key. Anthropic's Messages API and OpenAI's Responses API, with routing, budgets refused before the call, guardrails and the request log applied as on every other request.

  • Coding agent sessions and spend per person

    Available with a plan

    Claude Code, Codex and OpenCode recognized from their own headers, with each session and the subagents it starts grouped in the request log; session, tag and agent headers and W3C baggage for any other client; labels on a gateway key added to every request it makes; estimated provider spend per person and per agent.

  • Usage and cost per request

    Available with a plan

    Every request records its model, latency, token or unit counts, and estimated provider cost, queryable by project and key.

    Read the documentation for Usage and cost per request
  • Negotiated provider rates

    Available with a plan

    Enter the rates your contracts actually carry, per model and optionally per provider, so estimated cost uses them before the vendor's list rate. Included on every plan.

    Read the documentation for Negotiated provider rates
  • Provider cost reconciliation

    Available with a plan

    Daily comparison of estimated spend against the cost reported by OpenAI's and Anthropic's own cost APIs, using a separate admin credential, with the likely cause of a persistent gap and a suggested rate you can apply. Included on every plan.

    Read the documentation for Provider cost reconciliation
  • Usage, request and FOCUS exports

    Available with a plan

    GET /v1/usage and GET /v1/requests on any gateway key, the request log and usage series as CSV, plus a FOCUS v1.4 Cost and Usage dataset as JSON or CSV, so AI spend lands in your FinOps platform beside the rest of your cloud cost.

    Read the documentation for Usage, request and FOCUS exports

INFRO accounts are self-serve. Provider usage is billed to you by your providers; INFRO charges a software subscription and takes 0% of model spend. See plans.

Sources

Numbered in order of first citation. Each was opened and checked against the claim on the date shown.

  1. 1.Plans & pricing (API rates, prompt caching, fast mode, US-only inference) (opens in a new tab) — Anthropic. Accessed Nov 30, 2026.
  2. 2.Generative AI semantic conventions (moved notice) (opens in a new tab) — OpenTelemetry. Accessed Nov 30, 2026.
  3. 3.Runs (opens in a new tab) — INFRO Docs. Accessed Nov 30, 2026.
  4. 4.Claude Code & Codex (opens in a new tab) — INFRO Docs. Accessed Nov 30, 2026.
  5. 5.Scores and feedback (opens in a new tab) — INFRO Docs. Accessed Nov 30, 2026.
  6. 6.INFRO documentation overview (opens in a new tab) — INFRO Docs. Accessed Nov 30, 2026.

About this article

Read on 30 Nov 2026: Anthropic's pricing page (API rates, caching, fast mode), INFRO's docs overview, Claude Code & Codex, Runs and Scores pages, and OpenTelemetry's GenAI conventions page, which now points to a separate repository. OpenAI's pricing page showed ChatGPT seat plans rather than per-token API rates, so no OpenAI rates are quoted; all dollar figures in worked examples are illustrative.

Last checked against its sources on . The next review is due by . No separate named reviewer is recorded for this article.

How articles are written, sourced and corrected is set out in the editorial standards.