LLM basics for a .NET developer: tokens and tokenisation, the context window, temperature and sampling, the chat completions message model (system, user, assistant), statelessness, and how tokens drive cost and latency.
An LLM reads and writes tokens, sub-word pieces of about four characters of English. Every limit and every price is in tokens. The context window is the most tokens one call can handle, input and output together. A chat completion sends a list of messages with roles (system, user, assistant, tool) and gets the next assistant message back; the model is stateless, so your app resends the conversation every time. Temperature controls how random the sampling of the next token is: low for extraction and classification, higher for drafting.
Cost is input tokens plus output tokens, each at its own per-million price, with output usually dearer. Latency grows with output length because tokens are generated one by one. The trade-off: more context gives better answers but costs more and responds slower.
"An LLM doesn't see characters or words, it sees tokens: pieces of words from a fixed vocabulary, roughly four characters or three-quarters of a word in English, and code and non-English text usually take more. Everything is counted in tokens: the context window, the price and the rate limits on my Azure OpenAI deployment, which are expressed as tokens per minute.
A chat completion call is just a list of messages with roles. The system message sets behaviour, user messages are the input, assistant messages are earlier replies and tool messages carry results of function calls. The model is stateless: it remembers nothing between calls, so if I want a conversation I resend the history, and that history costs tokens every turn. The context window is the hard limit on input plus output for one call. Temperature changes how the next token is sampled: near zero it almost always picks the most likely token, which I want for extraction or classification; higher values make it more varied. Newer reasoning models often fix temperature and spend extra hidden reasoning tokens instead, which I'm billed for.
In .NET I call it through
IChatClientfrom Microsoft.Extensions.AI, setMaxOutputTokensso one request can't run away, and readresponse.Usageto log input and output tokens. The mistake I see is people pasting whole documents or long chat histories into every call and being surprised by the bill and the latency. Tokens are the unit of cost, latency and quality, so I budget them like memory."
| Term | What it is | Why you care |
|---|---|---|
| Token | Sub-word unit from the model's vocabulary | Limits, price and rate limits are all in tokens |
| Context window | Max input + output tokens in one call | Long histories and documents must fit, or be trimmed or retrieved |
| Chat completion | Messages with roles in, one assistant message out | Stateless: your app owns the history |
| System message | Instructions that frame the model's behaviour | Not a security boundary; users can still try to override it |
| Temperature / top-p | Sampling randomness | Low for deterministic tasks; still not perfectly repeatable |
| Max output tokens | Cap on the reply length | Bounds cost and latency per request |
| Usage | Token counts returned with the response | The basis for cost dashboards and budgets |
| Driver | Effect |
|---|---|
| Input tokens (system prompt, history, documents) | Linear cost; some time before the first token |
| Output tokens | Usually several times dearer per token than input; generated one at a time, so they dominate latency |
| Reasoning tokens (reasoning models) | Hidden but billed as output; better answers on hard tasks, slower |
| Model choice | Smaller "mini" models are much cheaper and faster for simple tasks |
| Prompt caching | Repeated identical prompt prefixes can be billed at a discount |
On [a support-ticket summariser], each call resent a [3,000-token] system prompt plus the full thread. Trimming history to the last [6] messages, moving to a mini model for classification and capping MaxOutputTokens at [300] cut average cost per ticket by [about 60%] and p95 latency from [9 s] to [3 s], with no drop on our evaluation set.
Checks that the candidate understands the basic mechanics that drive the cost, latency and behaviour of every LLM feature.
Green flags
Red flags
Models use a byte-pair-encoding style tokeniser: frequent character sequences become single tokens, rare ones are split. " the" is one token; an unusual identifier like CustomerOrderReconciliationService may be five or six. That is why code, JSON and languages other than English cost more per character.
"Hello, world!" → ["Hello", ",", " world", "!"] 4 tokens
In .NET the Microsoft.ML.Tokenizers package provides the same tokenisers (for example TiktokenTokenizer) so you can count tokens before sending.
prompt tokens ─► model ─► probability for every token in vocab ─► sample one ─► append ─┐
▲ │
└──────────────────────────── until stop token or MaxOutputTokens ─────────────────┘
Each output token needs a forward pass, so 1,000 output tokens take roughly ten times as long as 100. Input tokens are processed in parallel, which is why long prompts cost money but add less latency than long answers.
The model produces scores (logits) for every token. Temperature divides them before the softmax: below 1 sharpens the distribution (the likely token wins more often), above 1 flattens it. Top-p keeps only the smallest set of tokens whose probability adds up to p. Even at temperature 0 results can vary slightly between calls because of batching and floating-point effects, so never rely on byte-identical output.
[system] You classify support tickets into Billing, Technical or Other.
[user] My invoice is wrong.
[assistant] Billing
[user] The app crashes on login.
─► model returns the next assistant message
The model does not store this. Your app (or a framework) keeps the history, decides what to trim and resends it. Long conversations therefore get more expensive every turn unless you summarise or truncate.
Modern models accept very large contexts (hundreds of thousands of tokens as of late 2026), but bigger is not free: cost scales with input, and quality drops when the relevant fact is buried in the middle of a huge prompt ("lost in the middle"). Retrieval (RAG) usually beats stuffing everything in.
Azure OpenAI deployments have a tokens-per-minute (TPM) and requests-per-minute quota. Exceeding it returns HTTP 429 with a retry-after hint. Plan capacity in tokens, not requests. Deployment type also matters in Australia: a Standard (regional) deployment in Australia East keeps processing in-region, while Global deployments can process anywhere.
Microsoft.ML.Tokenizers to count tokens for an English sentence, a JSON payload and a C# class. Compare tokens per character.response.Usage for a call, then double the system prompt and compare input tokens and latency.MaxOutputTokens = 20 on a long-answer prompt and look at FinishReason.A minimal call with IChatClient that sets the knobs from this question and logs token usage.
// Program.cs (.NET 10 console). Packages: Microsoft.Extensions.AI.OpenAI, Azure.AI.OpenAI, Azure.Identity
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Extensions.AI;
var endpoint = new Uri(Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
?? throw new InvalidOperationException("Set AZURE_OPENAI_ENDPOINT"));
// Keyless: DefaultAzureCredential uses your az login locally and managed identity in Azure.
IChatClient client = new AzureOpenAIClient(endpoint, new DefaultAzureCredential())
.GetChatClient("gpt-4.1-mini") // the deployment name
.AsIChatClient();
List<ChatMessage> history =
[
new(ChatRole.System, "Classify the ticket as Billing, Technical or Other. Reply with one word."),
new(ChatRole.User, "I was charged twice this month.")
];
var options = new ChatOptions
{
Temperature = 0f, // classification: we want the most likely label
MaxOutputTokens = 5 // bounds cost and latency
};
ChatResponse response = await client.GetResponseAsync(history, options);
Console.WriteLine($"Label: {response.Text}");
Console.WriteLine($"Tokens in/out: {response.Usage?.InputTokenCount}/{response.Usage?.OutputTokenCount}");
Console.WriteLine($"Finish reason: {response.FinishReason}");
// Stateless model: to continue the conversation, append the reply and resend everything.
history.AddMessages(response);
Counting tokens before you send, to keep within a budget:
using Microsoft.ML.Tokenizers;
var tokenizer = TiktokenTokenizer.CreateForModel("gpt-4o");
int count = tokenizer.CountTokens("public sealed record Order(Guid Id, decimal Total);");
Console.WriteLine($"{count} tokens");
Microsoft.ML.Tokenizers and log Usage.MaxOutputTokens. Why it is wrong: a rambling answer costs the most per token and takes the longest. Instead: cap output for each use case and ask for a concise format in the prompt.Treat tokens as a resource budget, like memory or database round trips. Every AI feature should have a known tokens-per-request profile, a cap, and a dashboard. The cheapest optimisation is usually not a cleverer prompt but sending less: shorter, precise system prompts, summarised history, retrieval instead of stuffing, and a smaller model for the easy steps.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Small "mini" model | Classification, extraction, routing | Lowest per token, fastest | Multi-step reasoning, nuanced writing |
| Large general model | Drafting, complex answers | Higher | High-volume simple tasks |
| Reasoning model | Hard logic, planning, code | Highest: hidden reasoning tokens, slow | Latency-sensitive chat, simple lookups |
Measure before choosing: run the same evaluation set against two models and compare quality, p95 latency and cost per 1,000 requests. Then close the loop in production: chart tokens per request, cost per feature and user feedback (thumbs up/down) over time, and revisit prompts, history limits and model choice when the numbers drift.
Measure first: log input and output tokens per request from ChatResponse.Usage and chart cost per feature and per tenant; set Azure Cost Management budgets and alerts on the Azure OpenAI / Foundry resource so spend never surprises you. Then reduce:
ChatOptions.MaxOutputTokens, and cache repeated answers with Microsoft.Extensions.AI's UseDistributedCache() on the ChatClientBuilder (it wraps an ASP.NET Core IDistributedCache such as Redis; exact-match only, so it helps for identical prompts).Re-run your evaluation set after each change, because a cost cut that silently lowers quality is a false saving.
An LLM predicts likely tokens, not true ones. When its training data lacks the fact or the prompt is ambiguous, it still produces fluent text, and lowering temperature reduces randomness but not ignorance. In .NET I reduce it in layers:
IChatClient.GetResponseAsync<T>() in Microsoft.Extensions.AI) and validate the object with FluentValidation or data annotations.UseOpenTelemetry() and score groundedness with GroundednessEvaluator from Microsoft.Extensions.AI.Evaluation in CI.The trade-off is that grounding and checking add tokens and latency, so you size them to the cost of a wrong answer.
Last updated 23 Nov 2026.