Share via

Estimate/Retrieve the token usage and costs (prompt, completion, total) in C# with Azure OpenAI.

Alberto Valenti 25 Reputation points
2025-09-22T10:46:45.15+00:00

I would like to know if this is the best way to know how many tokens were consumed and can calculate costs.

I am not sure about costs, are those costs correct?

double costPer1KInput = 0.0015; // example for GPT-4o-mini input

double costPer1KOutput = 0.002; // example for GPT-4o-mini output

using Azure;

using Azure.AI.OpenAI;

var client = new OpenAIClient(

new Uri("https://YOUR-RESOURCE-NAME.openai.azure.com/"),

new AzureKeyCredential("YOUR-API-KEY"));

var options = new ChatCompletionsOptions()

{

DeploymentName = "gpt-4o-mini", // your deployment

Messages =

{

    new ChatRequestSystemMessage("You are a helpful assistant."),

    new ChatRequestUserMessage("Write a haiku about autumn.")

}

};

Response<ChatCompletions> response = await client.GetChatCompletionsAsync(options);

ChatCompletions completions = response.Value;

// Access token usage info

Console.WriteLine($"Prompt tokens: {completions.Usage.PromptTokens}");

Console.WriteLine($"Completion tokens: {completions.Usage.CompletionTokens}");

Console.WriteLine($"Total tokens: {completions.Usage.TotalTokens}");

Then I found this to evaluate costs:

double costPer1KInput = 0.0015; // example for GPT-4o-mini input

double costPer1KOutput = 0.002; // example for GPT-4o-mini output

double inputCost = completions.Usage.PromptTokens / 1000.0 * costPer1KInput;

double outputCost = completions.Usage.CompletionTokens / 1000.0 * costPer1KOutput;

double totalCost = inputCost + outputCost;

Console.WriteLine($"Estimated cost: ${totalCost:F4}");

Foundry Tools
Foundry Tools

Formerly known as Azure AI Services or Azure Cognitive Services is a unified collection of prebuilt AI capabilities within the Microsoft Foundry platform

0 comments No comments

Answer accepted by question author

  1. Moritz Goeke 395 Reputation points MVP
    2025-09-22T11:01:24.42+00:00

    Hi,

    Your method is correct, I usually do it in a similar way.
    For the cost values, you can look it up at https://azure.microsoft.com/en-us/pricing/details/cognitive-services/openai-service/ based on your configuration (deployment region, type, model).
    Alternativey, you can calculate using https://azure.microsoft.com/en-us/pricing/calculator/.

    Best regards! :)

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.