AI agents can automate several software development activities, including code generation, debugging, testing, repository analysis, and pull request preparation.
As teams adopt these agents, their usage can increase quickly. A developer might use an agent for a small code change, while another runs multiple agents to investigate bugs, generate tests, and review an entire repository.
Although individual tasks may appear inexpensive, the combined usage across a development team can become difficult to predict.
A single agent run may involve several model requests, tool executions, code inspections, and repeated reasoning steps. If the agent encounters an error or receives an unclear instruction, it may repeat operations and consume additional tokens.
Without proper tracking, engineering managers may know that AI tools are being used but have limited visibility into which projects, developers, or tasks generate the highest costs.
Tracking AI agent costs requires more than monitoring API token usage. Teams need to measure complete agent runs, associate usage with development activities, and understand the relationship between cost and engineering output.
This article explains how to build an AI agent cost-tracking system, collect usage data, calculate expenses, monitor team consumption, and identify opportunities to reduce unnecessary spending.
Why AI Agent Costs Are Difficult to Track
A traditional API request usually has a relatively straightforward usage pattern.
An application sends a request to a model, receives a response, and records the token usage.
An AI coding agent works differently.
One development task may involve several operations:
Receive the developer's request.
Inspect repository files.
Search for relevant code.
Send context to a language model.
Generate an implementation plan.
Read additional files.
Modify source code.
Run tests.
Analyze test failures.
Generate a final explanation.
Some of these operations involve model calls, while others involve tools such as terminal commands, file access, or Git operations.
A single agent run can therefore generate multiple model requests and tool executions.
The cost may also differ between model calls because of:
Input token volume.
Output token volume.
Cached input usage.
Model selection.
Reasoning-token accounting.
Provider-specific pricing.
Additional service charges.
A system that records only the final response will miss much of the activity.
Understand the Main Components of Agent Cost
Before building a tracking system, identify which activities generate measurable costs.
Input Tokens
Input tokens represent the information sent to the model.
For a coding agent, this may include:
Developer instructions.
Repository context.
Source-code files.
Git diffs.
Previous conversation messages.
Tool results.
System instructions.
Large repositories can produce substantial input usage when agents repeatedly send similar context.
Output Tokens
Output tokens represent the content generated by the model.
Examples include:
Implementation plans.
Source code.
Explanations.
Tool-call instructions.
Test suggestions.
Review summaries.
Some providers account for reasoning tokens separately or include them within output usage. Follow the provider's actual usage reporting rather than assuming every token category is billed identically.
Cached Tokens
Some model providers support prompt or input caching.
When previously processed input is reused, cached input may have a different price from ordinary input.
For example, a coding agent may repeatedly send the same repository instructions or project documentation across multiple requests.
If the provider reports cached input usage, record it separately.
Tool Execution Costs
An agent may also use external tools.
Examples include:
Cloud-hosted development environments.
Code execution services.
Repository analysis tools.
External search APIs.
Browser automation.
Third-party plugins.
Not every tool call generates a separate bill. Some tools run locally, while others have usage-based pricing.
Track tool execution costs separately when the provider exposes them.
Infrastructure Costs
An agent platform may require additional infrastructure.
For example:
Cloud virtual machines.
Container execution environments.
Temporary storage.
Logging services.
CI/CD runners.
These costs should not be mixed blindly with model token costs.
A useful cost report should distinguish model usage, tool usage, and infrastructure expenses.
Design a Cost-Tracking Architecture
A practical cost-tracking system should collect usage information from every agent execution and connect it with the developer task that generated it.
A simple architecture looks like this:
Developer Request
|
v
AI Agent Orchestrator
|
+------------------+
| |
v v
Model API Calls Tool Executions
| |
v v
Usage Metadata Execution Metadata
| |
+---------+--------+
|
v
Usage Collector
|
v
Cost Calculator
|
v
Usage Database
|
v
Cost Dashboard
|
v
Team and Project ReportsThe agent orchestrator should assign a unique identifier to every run.
Every model request and tool execution should carry that identifier.
This makes it possible to calculate the total cost of a task rather than reporting each API request independently.
Step 1: Assign a Unique ID to Every Agent Run
Start by generating a unique run identifier whenever a developer starts an agent task.
For example:
{
"run_id": "run-2026-1103-001",
"developer_id": "dev-102",
"team_id": "backend-team",
"project_id": "payment-api",
"task_type": "code_generation",
"started_at": "2026-11-03T10:30:00Z"
}The identifier should be included in every related model request, tool call, and usage event.
Without this relationship, it becomes difficult to determine which requests belong to the same task.
For example, a developer might run three agents simultaneously:
One agent investigates a production bug.
Another generates unit tests.
A third reviews a pull request.
All three runs may use the same model and API account.
The run identifier separates their usage.
Recommended Tracking Dimensions
Field | Purpose |
|---|---|
run_id | Identifies the complete agent run |
developer_id | Identifies the responsible developer |
team_id | Groups usage by engineering team |
project_id | Connects usage with a project |
repository | Identifies the source repository |
task_type | Classifies the development activity |
model | Identifies the model used |
provider | Identifies the model provider |
started_at | Records the start time |
completed_at | Records the completion time |
status | Tracks success, failure, or cancellation |
Use stable identifiers rather than storing unnecessary personal information.
Step 2: Capture Token Usage From Model Responses
Most model APIs provide usage metadata in their responses.
For example, a response may contain information similar to:
{
"usage": {
"input_tokens": 12000,
"output_tokens": 2500,
"cached_input_tokens": 4000
}
}The exact response structure depends on the model provider.
Some providers expose additional categories, such as reasoning tokens or cache creation tokens.
Your usage collector should normalize these fields into a common internal format.
For example:
def normalize_usage(response):
usage = response.get("usage", {})
return {
"input_tokens": usage.get("input_tokens", 0),
"output_tokens": usage.get("output_tokens", 0),
"cached_input_tokens": usage.get(
"cached_input_tokens", 0
)
}This is a simplified example. Adapt it to the actual response schema of the selected provider.
Do not estimate usage from the length of the generated text when the provider already supplies authoritative usage metadata.
Also record the model identifier used for each request. Pricing can differ between models and change over time.
Step 3: Calculate the Cost of Each Model Request
Once token usage is available, calculate the cost using the applicable provider pricing.
A basic calculation is:
[
\text{Cost} =
\frac{\text{Input Tokens}}{1,000,000}
\times \text{Input Rate}
+
\frac{\text{Output Tokens}}{1,000,000}
\times \text{Output Rate}
]
If cached input has a separate price, include it as another component.
For example, assume the following illustrative pricing:
Usage type | Example rate per million tokens |
|---|---|
Input | $2.00 |
Cached input | $0.50 |
Output | $8.00 |
Suppose an agent request uses:
12,000 input tokens.
4,000 cached input tokens included within the input total.
2,500 output tokens.
If the 4,000 cached tokens are a subset of the 12,000 input tokens, calculate ordinary and cached input separately:
[
\text{Ordinary Input} = 12,000 - 4,000 = 8,000
]
[
\text{Cost} =
\frac{8,000 \times 2.00}{1,000,000}
+
\frac{4,000 \times 0.50}{1,000,000}
+
\frac{2,500 \times 8.00}{1,000,000}
]
<math block value="\\text{Total Cost} = \\$0.044"/>
This example uses hypothetical rates to demonstrate the calculation.
In production, use the provider's current pricing and the exact billing categories reported by the API. Avoid double-counting cached tokens if the provider already includes them in another usage field.
Implement a Basic Cost Calculator
def calculate_request_cost(
input_tokens,
output_tokens,
cached_input_tokens,
input_rate,
output_rate,
cached_rate
):
ordinary_input = max(
input_tokens - cached_input_tokens,
0
)
input_cost = (
ordinary_input * input_rate
) / 1_000_000
cached_cost = (
cached_input_tokens * cached_rate
) / 1_000_000
output_cost = (
output_tokens * output_rate
) / 1_000_000
return input_cost + cached_cost + output_costThe function expects rates expressed as currency per million tokens.
Store the rates used for every calculation so historical reports remain reproducible when provider pricing changes.
Step 4: Store Usage Events in a Database
A cost-tracking platform should retain individual usage events rather than storing only daily totals.
This makes it possible to investigate expensive runs and recalculate historical costs when pricing information changes.
A relational database can store usage records using a structure like this:

Join the conversation! Your thoughts help the community grow.