Skip to main content

How to Get the Token Usage and Cost of a Microsoft Agent Framework Agent Run in C#

· 12 min read
Jagdish Kumawat
Founder @ Dewiride

Every call to a model is paid for by the token, and Microsoft Agent Framework tells you how many each run used: AgentResponse.Usage holds the run's input, cached, output and reasoning tokens. This guide reads them in a small C# agent, turns them into a cost in dollars, and gets the same numbers when the answer is streamed.

Syntax​

Syntax
AgentResponse <response> = await <agent>.RunAsync(<message>);
UsageDetails? <usage> = <response>.Usage;

<usage>?.InputTokenCount
<usage>?.CachedInputTokenCount
<usage>?.OutputTokenCount
<usage>?.ReasoningTokenCount
<usage>?.TotalTokenCount
PartWhat it is
<agent>Your agent, an AIAgent
<message>What you send to the agent
UsageThe run's token counts, a UsageDetails from Microsoft.Extensions.AI, or null when the model service reported none
InputTokenCountThe number of tokens in the input: everything the run sent to the model, including the instructions, the conversation and the descriptions of the tools
CachedInputTokenCountThe number of input tokens that were read from a cache. They're part of the input count, and they cost less
OutputTokenCountThe number of tokens in the output, reasoning tokens included
ReasoningTokenCountThe number of "reasoning" / "thinking" tokens used internally by the model
TotalTokenCountThe total number of tokens used to produce the response: the input and the output together

The descriptions in italics are the reference's own. Each count is a long?, which is empty when the service doesn't report it, so read them with ?..

The Example​

A console app runs an agent that writes very short poems. It asks for a two-line poem about the sea, prints the poem, then prints the run's token counts and what the run cost.

Prerequisites​

  • A model deployment in a Microsoft Foundry project, and the Foundry User role on the Foundry resource for your account. The app calls the model as you.
  • The .NET 10 SDK (dotnet --version prints a version that starts with 10.0) and the Azure CLI, signed in with az login.

Step 1: Create a Console App​

In a terminal, in the folder where you keep your projects, create a console app, move into it and add two packages:

Terminal
dotnet new console -n PoemAgent
cd PoemAgent
dotnet add package Microsoft.Agents.AI.Foundry --version 1.28.0-preview.261106.1
dotnet add package Azure.Identity --version 1.21.0
Output (first command)
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/PoemAgent/PoemAgent.csproj:
Restore succeeded.
PackageWhat it gives the app
Microsoft.Agents.AI.FoundryAsAIAgent, which turns a model in a Foundry project into an agent. It also brings in Microsoft.Extensions.AI, where UsageDetails lives
Azure.IdentityAzureCliCredential, which signs the app in to Foundry with your Azure CLI sign-in

Microsoft Agent Framework 1.28.0 is generally available, but its Foundry package ships only as a preview of the same release, so it needs its exact --version. Open the PoemAgent folder in VS Code, or PoemAgent.csproj in Visual Studio.

Step 2: Read the Usage After a Run​

Replace everything in Program.cs with:

Program.cs
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

AIAgent agent = new AIProjectClient(
new Uri("https://foundry-devblogs-exp.services.ai.azure.com/api/projects/proj-devblogs-exp"),
new AzureCliCredential())
.AsAIAgent(
model: "gpt-5.6-luna",
instructions: "You write very short poems.");

AgentResponse response = await agent.RunAsync("Write a two-line poem about the sea.");
Console.WriteLine(response.Text);
Console.WriteLine();

// The tokens the run used, as the model service reported them.
UsageDetails? usage = response.Usage;
Console.WriteLine($"Input tokens: {usage?.InputTokenCount} ({usage?.CachedInputTokenCount} read from the cache)");
Console.WriteLine($"Output tokens: {usage?.OutputTokenCount} ({usage?.ReasoningTokenCount} for reasoning)");
Console.WriteLine($"Total tokens: {usage?.TotalTokenCount}");
  • The AIProjectClient URI and gpt-5.6-luna are my Foundry project's endpoint and model deployment. Use your own; How to Create a Microsoft Foundry Resource and Deploy a Model shows where to find them.
  • RunAsync runs the agent and returns an AgentResponse once the whole answer is there.
  • response.Usage is the run's token counts. The three lines after it print them, with the cached part of the input and the reasoning part of the output in brackets.

Run the app:

In the terminal, in the PoemAgent folder, run:

Terminal
dotnet run
Output
The sea hums softly under skies of blue,
Its waves carry dreams to the far-off view.

Input tokens: 25 (0 read from the cache)
Output tokens: 25 (0 for reasoning)
Total tokens: 50

The run sent 25 tokens, the instructions and the question, and got 25 back: the poem. The total is the two together. Nothing came from the cache, because a prompt this short is never cached, as the FAQ explains.

Step 3: Turn the Tokens into a Cost​

Add these lines to the end of Program.cs:

Program.cs (add at the end)
// gpt-5.6-luna on a Global Standard deployment, in US dollars per million tokens.
const decimal InputPrice = 0.20m;
const decimal CachedInputPrice = 0.02m;
const decimal OutputPrice = 1.20m;

long input = usage?.InputTokenCount ?? 0;
long cached = usage?.CachedInputTokenCount ?? 0;
long output = usage?.OutputTokenCount ?? 0;
decimal cost = ((input - cached) * InputPrice + cached * CachedInputPrice + output * OutputPrice) / 1_000_000m;
Console.WriteLine($"Cost: ${cost:0.000000}");
  • The three prices are what gpt-5.6-luna costs on a Global Standard deployment: $0.20 per million input tokens, $0.02 per million input tokens read from the cache, and $1.20 per million output tokens. How to Look Up Azure OpenAI Model Prices with the Azure Retail Prices API shows where they come from. Put in your own model's prices.
  • input - cached is the input that didn't come from the cache, at the full input price. The cached tokens get the cache price.
  • ?? 0 turns a count the service didn't report into zero.
  • Reasoning tokens need no line of their own. They're already inside the output count, and Microsoft's guide to reasoning models says they are billed as output tokens.

Run the app again:

Output
The sea hums blue beneath the sun,
Its waves chase where the clouds have run.

Input tokens: 25 (0 read from the cache)
Output tokens: 38 (13 for reasoning)
Total tokens: 63
Cost: $0.000051

macOS-style terminal window titled Terminal — PoemAgent showing dotnet run printing a two-line poem about the sea, then Input tokens: 25 (0 read from the cache), Output tokens: 38 (13 for reasoning), Total tokens: 63 and Cost: $0.000051

This time the model reasoned before it wrote: 13 of the 38 output tokens never appear in the poem, and they're paid for all the same. 25 input tokens at $0.20 and 38 output tokens at $1.20, per million, come to $0.0000506, which the format rounds to $0.000051.

Cache writes aren't in the count

On GPT-5.6 models, writing to the prompt cache can cost extra, and UsageDetails has no count for it: its AdditionalCounts were empty in every run I made. The formula covers everything Usage reports. For the complete bill, check the costs in Azure Cost Management.

Step 4: Get the Usage from a Streamed Run​

With RunStreamingAsync, the answer arrives in pieces, as AgentResponseUpdate objects, and an update has no Usage property. Keep the updates, and combine them into one response at the end. Replace these three lines:

Program.cs (replace)
AgentResponse response = await agent.RunAsync("Write a two-line poem about the sea.");
Console.WriteLine(response.Text);
Console.WriteLine();

with:

Program.cs (new)
// Stream the answer, keep every update, and combine them into one response at the end.
List<AgentResponseUpdate> updates = [];
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync("Write a two-line poem about the sea."))
{
Console.Write(update.Text);
updates.Add(update);
}
Console.WriteLine();
Console.WriteLine();

AgentResponse response = updates.ToAgentResponse();
  • Console.Write(update.Text) prints each piece of the poem as it arrives.
  • ToAgentResponse() combines the updates into one AgentResponse, with Usage filled in, so the rest of the file works unchanged. The counts travel inside the updates as UsageContent items, one for each call to the model, and ToAgentResponse() adds them up.

Run the app again:

Output
Moonlit waves softly gleam,
The sea hums an endless dream.

Input tokens: 25 (0 read from the cache)
Output tokens: 20 (0 for reasoning)
Total tokens: 45
Cost: $0.000029

The counts came out of the combined response, exactly as they did from RunAsync.

The Complete File​

Program.cs
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

AIAgent agent = new AIProjectClient(
new Uri("https://foundry-devblogs-exp.services.ai.azure.com/api/projects/proj-devblogs-exp"),
new AzureCliCredential())
.AsAIAgent(
model: "gpt-5.6-luna",
instructions: "You write very short poems.");

// Stream the answer, keep every update, and combine them into one response at the end.
List<AgentResponseUpdate> updates = [];
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync("Write a two-line poem about the sea."))
{
Console.Write(update.Text);
updates.Add(update);
}
Console.WriteLine();
Console.WriteLine();

AgentResponse response = updates.ToAgentResponse();

// The tokens the run used, as the model service reported them.
UsageDetails? usage = response.Usage;
Console.WriteLine($"Input tokens: {usage?.InputTokenCount} ({usage?.CachedInputTokenCount} read from the cache)");
Console.WriteLine($"Output tokens: {usage?.OutputTokenCount} ({usage?.ReasoningTokenCount} for reasoning)");
Console.WriteLine($"Total tokens: {usage?.TotalTokenCount}");

// gpt-5.6-luna on a Global Standard deployment, in US dollars per million tokens.
const decimal InputPrice = 0.20m;
const decimal CachedInputPrice = 0.02m;
const decimal OutputPrice = 1.20m;

long input = usage?.InputTokenCount ?? 0;
long cached = usage?.CachedInputTokenCount ?? 0;
long output = usage?.OutputTokenCount ?? 0;
decimal cost = ((input - cached) * InputPrice + cached * CachedInputPrice + output * OutputPrice) / 1_000_000m;
Console.WriteLine($"Cost: ${cost:0.000000}");

macOS-style code window titled Program.cs — PoemAgent showing a C# agent that streams a poem with RunStreamingAsync, combines the updates with ToAgentResponse, prints InputTokenCount, CachedInputTokenCount, OutputTokenCount, ReasoningTokenCount and TotalTokenCount from response.Usage, and computes the cost from three prices per million tokens

Common Mistakes​

MistakeWhat happensDo this instead
Reading the counts without ?.A NullReferenceException when a service reports no usageRead them as usage?.InputTokenCount ?? 0
Pricing every input token at the full priceThe cost comes out too high once prompts are cachedPrice the cached tokens at the cache price, and only the rest at the input price
Adding ReasoningTokenCount to the outputReasoning is counted twiceIt's already part of OutputTokenCount
Looking for usage on a streamed updateAgentResponseUpdate has no Usage propertyKeep the updates and call ToAgentResponse()

Troubleshooting​

SymptomLikely causeFix
CachedInputTokenCount stays at 0The prompt is shorter than 1,024 tokens, or its start changedKeep long, repeated text, such as instructions, at the start of the prompt and unchanged
The bill is higher than your calculationCache writes on GPT-5.6 models, which Usage doesn't countCompare with the costs in Azure Cost Management

FAQ​

Does Usage include the tool calls?​

Yes. When the model calls a tool, one run makes several calls to the model, and Usage adds them all up. I checked with a dice-rolling agent and a small piece of middleware that printed the usage of each call to the model: the two calls used 82 and 113 input tokens and 19 and 10 output tokens, and the run's Usage said 195 and 29.

When does input come from the cache?​

Microsoft's prompt caching guide names two conditions: the request must be a minimum of 1,024 tokens in length, and the first 1,024 tokens in the prompt must be identical. To see it, I gave an agent about 2,000 tokens of instructions and asked the same question three times. The first run reported 2,005 input tokens and none cached; the second and third each reported 2,002 of their 2,005 input tokens as cached.

Why isn't the total bigger than input plus output?​

Because the reasoning tokens are already inside the output count. In Step 3, 25 input and 38 output tokens make the total of 63, and the 13 reasoning tokens are part of the 38.

Conclusion​

AgentResponse.Usage tells you what a run cost in tokens: input, the part of it read from the cache, output, and the part of that spent on reasoning. Multiply the uncached input, the cached input and the output by your model's prices to get the cost in dollars. When you stream, combine the updates with ToAgentResponse() first. On GPT-5.6 models, cache writes are the one charge the counts don't cover.

Additional Resources​