AI agents are changing how enterprise applications perform work. Instead of a user manually completing every step, an agent can reason over information, call tools, execute workflows, retrieve documents, and interact with multiple services.
This creates a new challenge for engineering and finance teams: How much does each AI agent actually cost?
A single user request may involve several model calls, tool executions, retrieval operations, background tasks, and retries. If all of these costs are reported as one shared AI bill, it becomes difficult to understand which project, team, tenant, or workflow is responsible for the spending.
Cost attribution solves this problem by connecting AI usage to a meaningful business or engineering dimension.
This article explains how to build a practical AI agent cost attribution system for enterprise projects using .NET, usage telemetry, token measurements, model pricing metadata, and project-level reporting.
Introduction
Consider an enterprise AI platform hosting three projects:
Project A
Customer Support Agent
Project B
Document Analysis Agent
Project C
Developer Coding Agent
All three projects may use the same AI infrastructure.
At the platform level, the organization might see:
Total AI Spend = $18,000
But that number does not answer important questions:
Which project consumed the most tokens?
Which agent has the highest cost per task?
Which model generates the highest spend?
How much of the cost comes from retries?
Which tenants are generating the most usage?
What is the average cost of a successful task?
Which workflows have poor cost efficiency?
A useful attribution architecture turns one aggregate bill into a detailed cost model.
AI Platform Spend
|
v
Usage Telemetry
|
v
Cost Calculation
|
v
Attribution
|
+---- Project
+---- Team
+---- Agent
+---- Tenant
+---- Workflow
|
v
Cost Dashboard
What Is AI Cost Attribution?
AI cost attribution is the process of assigning AI-related consumption to a defined owner or business dimension.
A simple attribution record might contain:
Project
Agent
Model
Operation
Input Tokens
Output Tokens
Tool Calls
Duration
Estimated Cost
For example:
| Project | Agent | Model | Input Tokens | Output Tokens | Estimated Cost |
|---|---|---|---|---|---|
| Support | Support Agent | Model A | 8,000 | 2,000 | Calculated |
| Finance | Report Agent | Model B | 12,000 | 3,500 | Calculated |
| Engineering | Coding Agent | Model A | 20,000 | 6,000 | Calculated |
The important part is that every measurable usage event has enough metadata to determine who or what caused the consumption.
Why Agent Cost Is Difficult to Measure
Traditional application cost attribution is relatively straightforward.
For example:
Application
|
+-- VM
+-- Database
+-- Storage
AI agents introduce multiple dynamic cost sources.
Agent Request
|
+-- LLM Call
|
+-- LLM Call
|
+-- Retrieval
|
+-- Tool Call
|
+-- LLM Call
|
+-- Retry
|
+-- LLM Call
One user action can therefore produce many billable operations.
The cost model needs to capture the entire execution graph.
Define the Attribution Hierarchy
Before collecting telemetry, define what cost ownership means.
A useful hierarchy is:
Organization
|
+-- Business Unit
|
+-- Project
|
+-- Application
|
+-- Agent
|
+-- Workflow
|
+-- Task
For a multi-tenant system, tenant can be another dimension:
Organization
|
+-- Project
|
+-- Tenant
|
+-- Agent
|
+-- Task
The hierarchy should match how the organization makes financial and operational decisions.
Use a Correlation ID
Every agent execution should receive a unique identifier.
public sealed record AgentExecutionContext(
string ExecutionId,
string ProjectId,
string AgentId,
string? TenantId);
For example:
var context = new AgentExecutionContext(
Guid.NewGuid().ToString("N"),
projectId,
agentId,
tenantId);
Every downstream operation should carry this context.
Agent Execution
|
+-- Model Call
|
+-- Retrieval
|
+-- Tool Call
|
+-- Model Call
|
+-- Final Response
This allows the individual operations to be grouped into one logical execution.
Track Every Model Call
Do not record only the final agent request.
An agent may make multiple model calls.
For example:
public sealed record ModelUsage(
string ExecutionId,
string Model,
long InputTokens,
long OutputTokens,
DateTimeOffset Timestamp);
Record an event after each model operation.
var usage = new ModelUsage(
context.ExecutionId,
modelName,
inputTokens,
outputTokens,
DateTimeOffset.UtcNow);
The cost calculator can then aggregate all calls belonging to the same execution.
Token-Based Cost Calculation
Many AI APIs use input and output token consumption as an important usage metric.
Conceptually:
Input Cost =
Input Tokens × Input Price
Output Cost =
Output Tokens × Output Price
Then:
Total Model Cost =
Input Cost + Output Cost
The actual pricing model varies by provider, model, and billing arrangement, so pricing should be treated as configuration rather than hard-coded business logic.
Keep Pricing Separate From Usage
Do not embed pricing directly into your agent implementation.
Instead, define a pricing abstraction.
public sealed record ModelPricing(
string Model,
decimal InputCostPerToken,
decimal OutputCostPerToken);
Then:
public decimal CalculateCost(
ModelPricing pricing,
long inputTokens,
long outputTokens)
{
return
inputTokens * pricing.InputCostPerToken +
outputTokens * pricing.OutputCostPerToken;
}
A centralized pricing table makes model changes easier to manage.
Model
Input Rate
Output Rate
Effective Date
Currency
If pricing changes, historical records should continue to use the correct rate applicable to the original usage period.
Store Usage and Cost Separately
It is useful to distinguish raw usage from calculated cost.
For example:
Usage Event
----------------
ExecutionId
Model
InputTokens
OutputTokens
Timestamp
Cost Record
----------------
ExecutionId
PricingVersion
CalculatedCost
Currency
CalculatedAt
This allows the organization to recalculate costs when pricing metadata or accounting rules change.
Cost Attribution Data Model
A practical relational model might look like this:
AgentExecutions
---------------------------
ExecutionId
ProjectId
AgentId
TenantId
WorkflowId
StartedAt
CompletedAt
Status
ModelUsage
---------------------------
UsageId
ExecutionId
Model
InputTokens
OutputTokens
LatencyMs
ToolUsage
---------------------------
ToolUsageId
ExecutionId
ToolName
DurationMs
Status
CostRecords
---------------------------
CostId
ExecutionId
UsageId
CostType
Amount
Currency
PricingVersion
This structure separates the execution from the individual usage events.
Example Entity Models
public sealed class AgentExecution
{
public required string ExecutionId { get; init; }
public required string ProjectId { get; init; }
public required string AgentId { get; init; }
public string? TenantId { get; init; }
public DateTimeOffset StartedAt { get; init; }
public DateTimeOffset? CompletedAt { get; set; }
public string Status { get; set; } = "Running";
}
Usage can be represented separately:
public sealed class ModelUsageRecord
{
public required string ExecutionId { get; init; }
public required string Model { get; init; }
public long InputTokens { get; init; }
public long OutputTokens { get; init; }
public long LatencyMs { get; init; }
}
Include Tool Costs
Not every agent cost comes from model tokens.
An agent might call:
Search API
Document Processing
Database
Code Execution
Browser Automation
External API
Some of these operations may have their own infrastructure or usage costs.
Represent tool usage independently:
public sealed record ToolUsage(
string ExecutionId,
string ToolName,
decimal EstimatedCost,
long DurationMs);
The final execution cost becomes:
Total Agent Cost
=
Model Costs
+
Tool Costs
+
Retrieval Costs
+
Execution Infrastructure Costs
Not every organization needs every component, but the model should support additional cost categories.
Infrastructure Cost Allocation
Infrastructure costs can be more difficult to attribute.
Suppose ten agents share one compute cluster.
The cluster might cost:
$5,000/month
You cannot simply assign the entire amount to the agent with the most requests.
Instead, define an allocation model.
Possible dimensions include:
CPU Time
Memory Usage
Execution Duration
Request Count
Resource Reservations
For example:
Project Allocation =
Project CPU Seconds
-------------------
Total CPU Seconds
Then:
Allocated Infrastructure Cost =
Allocation Percentage × Shared Infrastructure Cost
This is an allocation estimate, not necessarily an exact invoice amount.
The distinction should be clearly documented.
Direct Cost vs Allocated Cost
Maintain two categories:
Direct Cost
Costs directly associated with a project or execution.
Examples:
Model usage
Dedicated service
Project-specific API
Dedicated storage
Allocated Cost
Shared infrastructure distributed according to an allocation rule.
Examples:
Shared compute
Shared observability platform
Shared gateway
Shared database
This distinction prevents financial reports from presenting estimated allocations as exact provider charges.
Cost Per Agent Run
One of the most useful metrics is cost per successful execution.
Cost Per Run =
Total Successful Execution Cost
--------------------------------
Number of Successful Runs
For example:
Project A
Total Cost: $1,000
Successful Runs: 5,000
Cost Per Run = $0.20
Track this over time.
A sudden increase can indicate:
Larger prompts
Larger context
More tool calls
More retries
Model changes
Inefficient agent loops
Cost Per Successful Task
Cost per run is not always enough.
An agent can make ten attempts before completing one useful task.
A better business metric can be:
Cost Per Successful Task =
Total Cost
-------------------------
Successful Tasks
This includes failed and partially completed attempts when appropriate.
For production optimization, this metric is often more meaningful than raw token consumption.
Detect Costly Agent Loops
Consider an agent that repeatedly calls a model:
User Request
|
+-- Model Call
+-- Tool Call
+-- Model Call
+-- Tool Call
+-- Model Call
+-- Tool Call
+-- Model Call
A workflow that normally requires three model calls might suddenly require fifteen.
Record:
Model Calls Per Execution
Tool Calls Per Execution
Total Tokens
Execution Duration
Then define an alert threshold.
if (modelCallCount > 10)
{
logger.LogWarning(
"High model call count for execution {ExecutionId}",
executionId);
}
This can identify runaway agent behavior before it becomes a major cost problem.
Cost Attribution by Project
Suppose the organization has:
Project A = Customer Support
Project B = Finance
Project C = Engineering
Aggregate costs:
Project A
---------
Model: $800
Tools: $200
Infrastructure: $100
Total: $1,100
Project B
---------
Model: $500
Tools: $150
Infrastructure: $75
Total: $725
Project C
---------
Model: $1,400
Tools: $350
Infrastructure: $125
Total: $1,875
Now the organization can see where AI spending is concentrated.
Cost Attribution by Tenant
For multi-tenant applications:
Tenant A
|
+-- Agent 1
+-- Agent 2
Tenant B
|
+-- Agent 1
+-- Agent 3
Every execution should carry tenant identity from authenticated application context.
Do not allow the model to determine the tenant identifier.
The application should establish it before the agent starts.
Cost Attribution by Workflow
An agent may support multiple workflows.
For example:
Support Agent
|
+-- Ticket Summary
+-- Response Drafting
+-- Knowledge Search
+-- Escalation Analysis
Track workflow IDs:
public sealed record WorkflowContext(
string ExecutionId,
string ProjectId,
string WorkflowId);
This enables much more useful optimization.
Perhaps ticket summarization costs $0.03 per task while escalation analysis costs $0.45.
That information can guide engineering priorities.
Observability Events
Cost telemetry should be integrated with normal application observability.
A useful event might contain:
{
"executionId": "abc123",
"projectId": "support",
"agentId": "ticket-agent",
"workflowId": "summarization",
"model": "model-a",
"inputTokens": 4200,
"outputTokens": 850,
"toolCalls": 2,
"durationMs": 1850,
"estimatedCost": 0.07,
"status": "Succeeded"
}
Avoid placing sensitive prompts, documents, or credentials into telemetry unless there is a clear and controlled requirement.
Building a Cost Collector
A simple .NET service can accept usage events.
public interface ICostTelemetry
{
Task RecordModelUsageAsync(
ModelUsageRecord usage,
CancellationToken cancellationToken);
Task RecordToolUsageAsync(
ToolUsage usage,
CancellationToken cancellationToken);
}
The agent orchestration layer can use this abstraction without knowing how the data is stored.
await costTelemetry.RecordModelUsageAsync(
usage,
cancellationToken);
This keeps cost tracking separate from business logic.
Aggregating Daily Costs
A reporting query can group usage by project.
Conceptually:
SELECT
ProjectId,
CAST(StartedAt AS date) AS UsageDate,
SUM(Cost) AS TotalCost
FROM CostRecords
GROUP BY
ProjectId,
CAST(StartedAt AS date);
The result can power a dashboard showing:
Daily AI Spend
Project Spend
Agent Spend
Tenant Spend
Cost Per Task
Token Consumption
Cost Budgets
Once usage is measurable, budgets become possible.
For example:
Project Monthly Budget
|
v
Current Usage
|
+-- 70% Warning
+-- 85% Warning
+-- 100% Critical
A simple policy could be:
if (currentSpend >= budget * 0.85m)
{
await alertService.SendAsync(
"Project has reached 85% of AI budget.");
}
Budgets should generally trigger investigation or policy changes rather than abruptly breaking production workflows unless that behavior is explicitly required.
Cost Controls
When a project becomes expensive, several controls can help.
Limit Context Size
Large prompts increase input token consumption.
Reduce Unnecessary Tool Calls
Avoid tools that do not materially improve task completion.
Route Simple Tasks to Lower-Cost Models
Not every operation requires the most capable model.
Cache Reusable Results
Repeated retrieval or computation can sometimes be cached.
Detect Loops
Set reasonable limits on model and tool iterations.
Track Failed Executions
Failures still consume resources.
Comparing Cost Efficiency
Consider two agent implementations.
| Metric | Agent A | Agent B |
|---|---|---|
| Average Model Calls | 3 | 8 |
| Input Tokens | 5,000 | 12,000 |
| Output Tokens | 1,000 | 2,500 |
| Success Rate | 96% | 98% |
| Cost Per Run | Lower | Higher |
| Cost Per Successful Task | Lower | Higher |
Agent B has a higher success rate, but the organization should determine whether the additional cost is justified.
This is why cost should be evaluated alongside quality and reliability.
Cost Attribution and Model Routing
Cost telemetry becomes especially valuable when an application supports multiple models.
For example:
Simple Query
|
v
Lower-Cost Model
Complex Query
|
v
Higher-Capability Model
Track:
Model
Task Type
Success Rate
Latency
Cost
Then calculate whether routing actually improves the business outcome.
A lower-cost model is not necessarily better if it creates additional retries or lower-quality responses.
Common Mistakes
Tracking Only Total Tokens
Tokens do not explain which project consumed them.
Recording Only Final Agent Cost
This hides the individual model and tool operations.
Hard-Coding Pricing
Pricing changes and historical calculations need versioned metadata.
Ignoring Failed Runs
Failed executions still consume resources.
Ignoring Retries
Retries can substantially increase cost.
Mixing Actual and Allocated Costs
Estimated infrastructure allocation should be clearly distinguished from direct provider charges.
Letting Users Supply Attribution Fields
Tenant and project identity should come from trusted application context.
Logging Sensitive Prompts
Cost telemetry should not become a data-leak channel.
Advantages
A structured AI cost attribution system provides several benefits:
Clear project-level AI spending
Better financial accountability
Visibility into expensive workflows
Easier budget management
Better model-selection decisions
Detection of inefficient agent loops
Improved tenant-level billing
More informed architecture decisions
Disadvantages
There are also tradeoffs:
Additional telemetry infrastructure
More data storage
Pricing metadata maintenance
Allocation complexity for shared infrastructure
Potential privacy concerns
Small observability overhead
More engineering work to instrument every agent operation
The system should therefore capture useful financial dimensions without collecting unnecessary application data.
Best Practices
Generate a unique execution ID for every agent run.
Propagate that ID through model and tool calls.
Attribute every execution to a trusted project and tenant context.
Record input and output token usage.
Track every model call rather than only the final request.
Track tool and retrieval operations separately.
Keep pricing metadata separate from usage telemetry.
Version pricing information for historical reporting.
Distinguish direct costs from allocated shared costs.
Measure cost per successful task.
Monitor model-call and tool-call counts.
Detect abnormal agent loops.
Add project and workflow budgets.
Avoid logging sensitive prompts and credentials.
Combine cost metrics with quality, latency, and success rate.
Frequently Asked Questions
What is the most important metric for AI agent cost?
Cost per successful task is often more useful than total token consumption because it connects spending to completed business outcomes.
Should tool costs be included?
Yes, when tools generate meaningful infrastructure or external-service costs. Model usage is only one component of an agent's total cost.
How do I attribute shared infrastructure?
Use a documented allocation model based on measurable consumption such as CPU time, memory usage, execution duration, or request volume.
Should failed agent executions count toward project cost?
Yes. Failed executions still consume model, infrastructure, and tool resources. They should remain visible in cost reporting.
Can cost attribution be used for multi-tenant billing?
Yes. If every execution has a trusted tenant identifier and measurable usage records, costs can be aggregated per tenant. Billing calculations should clearly distinguish estimated usage-based costs from actual provider charges.
How frequently should costs be calculated?
Raw usage can be recorded per operation, while aggregated reporting can run hourly, daily, or monthly depending on operational requirements.
Should token counts be stored permanently?
That depends on the organization's retention and privacy requirements. Store only the data needed for cost analysis, auditing, and reporting.
Conclusion
AI agent cost management starts with observability.
Without execution-level telemetry, an enterprise sees only an aggregate AI bill. With proper attribution, that same spend can be connected to projects, agents, workflows, tenants, models, tools, and successful business outcomes.
The most effective design is to create a correlation ID for every agent execution, record each model and tool operation, calculate cost using versioned pricing metadata, and aggregate the results across the dimensions the organization actually manages.
The goal is not simply to reduce AI spending.
The goal is to understand what the organization is paying for, why it is paying for it, and whether that spending produces the expected result.
Once cost becomes a measurable engineering metric alongside latency, reliability, and quality, AI agents become much easier to operate responsibly at enterprise scale.
Join the conversation! Your thoughts help the community grow.