📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

You're a .NET developer about to call an LLM for the first time. What are tokens, the context window, temperature and a chat completion, and how do they drive cost and latency?

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.

Beginner Theory Beginner ai azure-openai cost llm microsoft-extensions-ai tokens

🎯 Key points

  • A token is a sub-word piece, roughly 4 characters or 0.75 of an English word; billing and limits are in tokens
  • Context window = input + output tokens one call can handle (from about 128k to over 1M tokens depending on the model, as of late 2026); overflow fails or is truncated
  • Chat completion = list of messages with roles (system, user, assistant, tool); the model is stateless, you resend history every call
  • Temperature controls sampling randomness: low (0–0.3) for extraction and classification; reasoning models may ignore or reject it
  • Cost = input tokens x input price + output tokens x output price; on most current models output costs several times more per token, but check the price sheet for the model and deployment type
  • Latency is dominated by output tokens (generated one at a time); time to first token matters for UX, so stream
  • Read ChatResponse.Usage, set MaxOutputTokens, and keep prompts short (concise instructions, summarised history) to bound cost per request

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 IChatClient from Microsoft.Extensions.AI, set MaxOutputTokens so one request can't run away, and read response.Usage to 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."


The terms

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

Where cost and latency come from

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate understands the basic mechanics that drive the cost, latency and behaviour of every LLM feature.

Green flags

  • Defines a token correctly and knows billing is per token, with output dearer
  • Knows the model is stateless and the app resends history
  • Explains temperature as sampling randomness and when to lower it
  • Mentions capping output and logging usage
  • Links latency to output length and suggests streaming

Red flags

  • "The model remembers the previous conversation"
  • No idea what a context window is or what happens when it overflows
  • Thinks temperature 0 makes output fully deterministic and correct
  • No sense of what an LLM call costs

📚 Learn in depth

1. Tokenisation

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.

2. Generation is a loop

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.

3. Temperature and sampling

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.

4. The chat message model

[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.

5. Context window limits

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.

6. Rate limits and quotas

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.

Try it yourself

  1. Use Microsoft.ML.Tokenizers to count tokens for an English sentence, a JSON payload and a C# class. Compare tokens per character.
  2. Call a chat model with the same classification prompt ten times at temperature 0 and 1; count distinct answers.
  3. Log response.Usage for a call, then double the system prompt and compare input tokens and latency.
  4. Set MaxOutputTokens = 20 on a long-answer prompt and look at FinishReason.
  5. Build a five-turn chat and chart input tokens per turn to see history growth.

💻 Code

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");

⚠ Common mistakes

  • Mistake: Thinking in words or characters. Why it is wrong: limits and prices are in tokens, and code or JSON uses more tokens per character than prose. Instead: count tokens with Microsoft.ML.Tokenizers and log Usage.
  • Mistake: Assuming the model remembers the conversation. Why it is wrong: chat completions are stateless. Instead: keep history in your app and trim or summarise it.
  • Mistake: Resending a full history and large documents on every call. Why it is wrong: input cost grows each turn and latency rises. Instead: trim, summarise older turns into a short recap, or retrieve only relevant chunks.
  • Mistake: No 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.
  • Mistake: Expecting temperature 0 to give identical output every time. Why it is wrong: temperature 0 picks the most likely token at each step, but batching on the provider's GPUs, floating-point non-determinism and silent model updates behind a deployment can still change the output. Instead: validate output structurally, pin model versions, and test with evaluation sets.
  • Mistake: Treating the system prompt as a security control. Why it is wrong: user input can try to override it (prompt injection). Instead: enforce rules in code.
  • Mistake: Using the biggest model for everything. Why it is wrong: simple tasks cost many times more for no quality gain. Instead: start with a smaller model and move up only if evaluation shows it is needed.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions tokens being billed Why: Checks whether they can turn token knowledge into cost controls
    How to answer

    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:

    • Use a smaller model for simple steps (routing, classification, extraction), trim history and system prompts, and use retrieval instead of stuffing whole documents.
    • Cap 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).
    • Enforce budgets per user or tenant with rate limiting.

    Re-run your evaluation set after each change, because a cost cut that silently lowers quality is a false saving.

  2. When: Candidate mentions temperature or sampling Why: Checks understanding that generation is probabilistic, not fact lookup
    How to answer

    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:

    • Ground the model with RAG (retrieved chunks in the prompt) and tell it to answer only from them and say "I don't know" otherwise.
    • Ask for citations as chunk ids and check in code that each id was actually retrieved.
    • Use structured output (IChatClient.GetResponseAsync<T>() in Microsoft.Extensions.AI) and validate the object with FluentValidation or data annotations.
    • Measure: trace calls with 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.

More in .NET and AI

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me