
Series - AI chat applications with .NET: Part 1: A Console Chat with IChatClient. The following parts build on this chat step by step.
A console chat is a useful starting point for an AI application because there is little between the application and the model. A loop reads a question, sends it to the model and prints the answer. Conversation history, streaming and cancellation remain visible in the code, as does the growing token usage of a longer conversation.
IChatClient from Microsoft.Extensions.AI provides a common interface for that loop. In this article, it connects to llama3.2 running locally in Ollama and to a gpt-4.1-mini deployment in Microsoft Foundry. The client is created differently for each provider, while the application uses the same message types and streaming API afterwards. Provider capabilities and operational details still differ, particularly around context limits, authentication and usage reporting.
Versions: The samples use .NET 10, Microsoft.Extensions.AI 10.11.0, Microsoft.Extensions.AI.OpenAI 10.11.0 and OllamaSharp 5.5.0. The console output below was captured with
llama3.2in a local Ollama instance.
The building blocks
| Building block | Technology |
|---|---|
| Application | .NET 10 console app |
| Chat abstraction | IChatClient from Microsoft.Extensions.AI |
| Ollama | OllamaSharp - OllamaApiClient implements IChatClient directly |
| Microsoft Foundry | OpenAI SDK plus Microsoft.Extensions.AI.OpenAI for AsIChatClient() |
| Settings | Microsoft.Extensions.Configuration: JSON, user secrets, environment variables, command line |
1dotnet add package Microsoft.Extensions.AI
2dotnet add package OllamaSharp # Ollama
3dotnet add package Microsoft.Extensions.AI.OpenAI # Microsoft FoundryThe configuration packages (Json, Binder, UserSecrets, EnvironmentVariables, CommandLine) come on top. Nothing else is required.
One switch decides the provider
The provider is a setting. Both factory methods return an IChatClient, and that is the only type the rest of the application knows:
1IChatClient chatClient = chat.Provider switch
2{
3 "Ollama" => await OllamaChat.CreateAsync(ollamaSettings),
4 "Foundry" => await FoundryChat.CreateAsync(foundrySettings),
5 _ => throw new InvalidOperationException($"Unknown provider '{chat.Provider}'.")
6};The matching appsettings.json:
1{
2 "Chat": {
3 "Provider": "Ollama",
4 "SystemPrompt": "You are a concise assistant for software developers. Answer in one or two sentences."
5 },
6 "Ollama": {
7 "Endpoint": "http://localhost:11434",
8 "Model": "llama3.2"
9 },
10 "Foundry": {
11 "Endpoint": "https://<resource>.openai.azure.com/",
12 "Model": "gpt-4.1-mini"
13 }
14}Switching to the cloud is a command-line argument: dotnet run -- --Chat:Provider=Foundry.
The API key does not belong in this file. User secrets are the right place during development, but a console app does not load them on its own. The ASP.NET Core host does that automatically; a plain ConfigurationBuilder has to be told:
1IConfigurationRoot configuration = new ConfigurationBuilder()
2 .SetBasePath(AppContext.BaseDirectory)
3 .AddJsonFile("appsettings.json", optional: false)
4 .AddUserSecrets<Program>(optional: true)
5 .AddEnvironmentVariables()
6 .AddCommandLine(args)
7 .Build();AddUserSecrets<Program>() needs a UserSecretsId in the project file, which dotnet user-secrets init creates. After that, dotnet user-secrets set "Foundry:ApiKey" "<key>" stores the key in the user profile, outside the repository. Also make sure appsettings.json is copied to the output directory, because SetBasePath(AppContext.BaseDirectory) reads it from there.
Ollama: the model runs locally
Ollama is installed with winget install Ollama.Ollama on Windows, or from ollama.com
on other platforms, and listens on http://localhost:11434.
The client itself is one line, because OllamaSharp implements IChatClient without an adapter:
1OllamaApiClient ollama = new(new Uri(settings.Endpoint), settings.Model);
2IChatClient chatClient = ollama;The same client can also prepare the local model before the chat starts. Checking availability, downloading a missing model and warming it up moves predictable startup failures out of the first conversation turn.
The model check needs to account for Ollama’s default tag: a request for llama3.2 can match the local name llama3.2:latest. If neither name is present, the application downloads it and reports progress:
1IEnumerable<Model> localModels = await ollama.ListLocalModelsAsync();
2bool isPresent = localModels.Any(m => m.Name == model || m.Name == $"{model}:latest");
3
4if (!isPresent)
5{
6 await foreach (PullModelResponse? progress in ollama.PullModelAsync(model))
7 {
8 Console.Write($"\r{progress?.Status} {progress?.Percent:0}%".PadRight(70));
9 }
10}A model consists of several layers, and the progress is reported per layer. llama3.2 is about 2 GB.
Before that, ollama.IsRunningAsync() answers whether Ollama is reachable at all. A startup check should treat an HttpRequestException as “not running” as well, so that a stopped Ollama produces a helpful message instead of a stack trace.
Once available, the model can be loaded into memory with an empty generate request. Without this warm-up, loading adds several seconds to the first question on some machines:
1// A generate request without a prompt loads the model and generates nothing.
2await foreach (GenerateResponseStream? _ in ollama.GenerateAsync(new GenerateRequest { Model = model }))
3{
4}The running-model information then reports the context allocated to this loaded instance:
1RunningModel? running = (await ollama.ListRunningModelsAsync())
2 .FirstOrDefault(m => m.Name == model || m.Name == $"{model}:latest");
3
4long? contextLength = running?.ContextLength;In the setup used for this article, Ollama loaded llama3.2 with a context window of 4,096 tokens. A growing conversation can exceed that allocation, and the tested backend truncated input without returning a request error. The application therefore needs an explicit context budget rather than relying on successful HTTP responses.
Switching to another local model at runtime is a property: ollama.SelectedModel = "qwen2.5:7b";. The history stays where it is - in the application.
Microsoft Foundry: the model runs in Azure
Azure OpenAI deployments in Microsoft Foundry expose an OpenAI-compatible v1 API at https://<resource>.openai.azure.com/openai/v1/. That means the regular OpenAI SDK works: no Azure-specific client and no api-version parameter.
A gpt-4.1-mini deployment is created in the Foundry portal
under the model catalog, or via Bicep
. The client:
1OpenAIClient openAi = new(
2 new ApiKeyCredential(settings.ApiKey),
3 new OpenAIClientOptions { Endpoint = settings.OpenAiEndpoint });
4
5IChatClient chatClient = openAi.GetChatClient(settings.Model).AsIChatClient();AsIChatClient() from Microsoft.Extensions.AI.OpenAI turns the OpenAI ChatClient into an IChatClient. From here on, nothing in the code knows about OpenAI, Azure or Foundry.
The settings need some care around endpoint and deployment names. The portal shows host names such as …openai.azure.com or …services.ai.azure.com, sometimes with a path. For the direct Azure endpoints used here, the settings class constructs the v1 path from the host:
1public Uri OpenAiEndpoint =>
2 new(new Uri(Endpoint).GetLeftPart(UriPartial.Authority) + "/openai/v1/");The configured model value is the deployment name in Azure. GetChatClient("gpt-4.1-mini") addresses a deployment, which may have a different name from its model. ChatResponse.ModelId exposes the model identifier returned by the provider; its detail depends on the response.
A startup probe can detect an incorrect key, endpoint or deployment before the conversation begins. For the gpt-4.1-mini deployment used here, a one-token response is enough to exercise the request path and inspect the returned model identifier:
1ChatResponse probe = await chatClient.GetResponseAsync(
2 "Hello",
3 new ChatOptions { MaxOutputTokens = 1 });
4
5Console.WriteLine($"Deployment {settings.Model} runs {probe.ModelId}.");
6// Deployment gpt-4.1-mini runs gpt-4.1-mini-2025-04-14.Errors from the OpenAI SDK are ClientResultExceptions with an HTTP status. Network failures are retried automatically; once the retries are exhausted, the exceptions arrive bundled in an AggregateException. A small mapping turns both into messages a human can act on:
1public static string Describe(Exception ex, string deployment)
2{
3 return ex switch
4 {
5 AggregateException aggregate => Describe(aggregate.InnerExceptions[^1], deployment),
6 ClientResultException { Status: 401 or 403 } => "Authentication or access was denied (401/403). Check credentials and permissions.",
7 ClientResultException { Status: 404 } => $"Deployment '{deployment}' was not found (404).",
8 ClientResultException { Status: 429 } => "The rate limit of the deployment was reached (429).",
9 ClientResultException { Status: > 0 } result => $"Foundry returned {result.Status}: {result.Message}",
10 _ => $"Foundry is not reachable: {ex.Message}",
11 };
12}An API key is fine for a local experiment. Anything beyond that should use Microsoft Entra ID, and with the v1 API this only changes the constructor:
1#pragma warning disable OPENAI001
2
3BearerTokenPolicy tokenPolicy = new(new DefaultAzureCredential(), "https://ai.azure.com/.default");
4
5OpenAIClient openAi = new(tokenPolicy, new OpenAIClientOptions { Endpoint = settings.OpenAiEndpoint });The identity needs the Cognitive Services OpenAI User role. Managed Identity in .NET: Stop Using Connection Strings
covers why DefaultAzureCredential belongs to local development and an explicit credential to production.
The chat loop
This is the part both providers share. Stripped to its core, it is short:
1List<ChatMessage> history = [new(ChatRole.System, chat.SystemPrompt)];
2
3while (Console.ReadLine() is { } input)
4{
5 history.Add(new ChatMessage(ChatRole.User, input));
6
7 List<ChatResponseUpdate> updates = [];
8 await foreach (ChatResponseUpdate update in chatClient.GetStreamingResponseAsync(history))
9 {
10 Console.Write(update.Text);
11 updates.Add(update);
12 }
13
14 history.AddMessages(updates);
15}The history list connects the turns. In this chat, the application sends the system prompt, earlier questions and earlier answers with each request; the model has no separate conversation memory behind that list. Streaming delivers ChatResponseUpdate objects as the response becomes available. AddMessages combines those updates into the assistant messages that subsequent requests need.
The loop also handles the end of input through Console.ReadLine(): it returns null for Ctrl+Z followed by Enter on Windows, Ctrl+D on Linux and macOS, or the end of redirected input. That allows a session to be driven from a file, for example with Get-Content questions.txt | dotnet run. The source encoding and Console.InputEncoding need to agree when the redirected text contains non-ASCII characters.
Starting a new conversation means clearing everything except the system prompt:
history.RemoveRange(1, history.Count - 1);Ctrl+C cancels the answer, not the application
A long answer that goes in the wrong direction should be stoppable without losing the conversation. Console.CancelKeyPress makes that possible:
1CancellationTokenSource? answerCancellation = null;
2
3Console.CancelKeyPress += (_, e) =>
4{
5 if (answerCancellation is { } cts)
6 {
7 e.Cancel = true; // keep the process alive
8 cts.Cancel(); // stop only the current answer
9 }
10};The loop creates a new CancellationTokenSource before each request, passes its token to GetStreamingResponseAsync, catches the OperationCanceledException and resets the field in finally. While the chat waits for input, the field is null and Ctrl+C ends the application as usual.
AddMessages runs after the try block, so a cancelled partial answer still lands in the history. The model knows what it already said. If the answer is cancelled before the first token, the history ends with a question that has no answer - something to keep in mind when trimming the history later.
What the model remembers
A short session with llama3.2:
1Model llama3.2 loaded, context window 4,096 tokens.
2You: Which port does PostgreSQL listen on by default?
3AI: PostgreSQL listens on port 5432 by default.
4 [50 in · 12 out · 135.3 tok/s · first token 79 ms · 168 ms]
5
6You: And SQL Server?
7AI: SQL Server listens on port 1433 by default, but can be configured to listen on other ports, such as 1434 for named pipes.
8 [75 in · 31 out · 131.9 tok/s · first token 20 ms · 255 ms]
9
10You: /new
11History cleared.
12You: And SQL Server?
13AI: I'm familiar with SQL Server, a popular relational database management system developed by Microsoft. SQL Server supports various features like T-SQL, CLR integration, and high-performance data storage.
14 [45 in · 37 out · 140.3 tok/s · first token 23 ms · 287 ms]The follow-up “And SQL Server?” relies on the earlier question about ports. That context accounts for the larger input of the second request. After /new, the same words produce a general description because the application no longer sends the earlier exchange.
The second answer also contains a useful warning about model output. TCP port 1433 is the default for a default SQL Server instance, while UDP port 1434 belongs to SQL Server Browser; it is unrelated to named pipes. The example preserves the model’s error because it illustrates how an incorrect detail can appear in otherwise plausible prose.
Time to first token
For the user, the time before the first token is the time in which nothing seems to happen. It is worth measuring:
1Stopwatch stopwatch = Stopwatch.StartNew();
2TimeSpan? timeToFirstToken = null;
3
4await foreach (ChatResponseUpdate update in chatClient.GetStreamingResponseAsync(history, cancellationToken: token))
5{
6 if (timeToFirstToken is null && !string.IsNullOrEmpty(update.Text))
7 {
8 timeToFirstToken = stopwatch.Elapsed;
9 }
10
11 // ...
12}A spinner can cover the initial wait. Manually enumerating the stream makes the first MoveNextAsync call available to Spectre.Console
. This example stops the spinner at the first update, which can contain metadata before any visible text:
1await using IAsyncEnumerator<ChatResponseUpdate> stream = chatClient
2 .GetStreamingResponseAsync(history, cancellationToken: token)
3 .GetAsyncEnumerator();
4
5bool hasNext = await AnsiConsole.Status()
6 .Spinner(Spinner.Known.Dots)
7 .StartAsync("thinking …", _ => stream.MoveNextAsync().AsTask());
8
9while (hasNext)
10{
11 Console.Write(stream.Current.Text);
12 updates.Add(stream.Current);
13 hasNext = await stream.MoveNextAsync();
14}Token usage without provider-specific code
When usage is available, these adapters expose it as UsageContent, typically near the end of the stream. Reading it does not depend on the provider:
1UsageDetails? usage = updates
2 .SelectMany(u => u.Contents)
3 .OfType<UsageContent>()
4 .LastOrDefault()?.Details;
5
6long inputTokens = usage?.InputTokenCount ?? 0;
7long outputTokens = usage?.OutputTokenCount ?? 0;A cancelled answer usually has no usage at all, so null has to be expected.
Beyond that, the providers differ. Ollama adds server-side timings to the AdditionalProperties of the final update: prompt_eval_duration for reading the input, eval_duration for generating the output and load_duration for loading the model. They make the generation speed exact:
1AdditionalPropertiesDictionary? properties = updates
2 .LastOrDefault(u => u.AdditionalProperties is { Count: > 0 })?.AdditionalProperties;
3
4if (properties?.TryGetValue("eval_duration", out object? value) == true && value is TimeSpan generation)
5{
6 double tokensPerSecond = outputTokens / generation.TotalSeconds;
7}A noticeable load_duration in the middle of a conversation means that Ollama had evicted the model, for example because another model needed the GPU memory.
For Microsoft Foundry, this example measures elapsed time on the client, including network latency. Streaming behavior also depends on the content filtering configuration: buffered filtering can release text in blocks, while asynchronous filtering changes when text and filter annotations arrive. A short answer may arrive in one update. Client-side throughput therefore describes the observed request rather than the model’s generation speed in isolation.
What a conversation costs
Ollama costs hardware and electricity. Foundry bills per token, with input and output priced separately and output usually several times more expensive. With the prices of the deployment in the settings, the cost of each request is a single calculation:
1public sealed record Pricing(decimal InputPerMillionTokens, decimal OutputPerMillionTokens)
2{
3 public decimal Cost(long inputTokens, long outputTokens)
4 {
5 return (inputTokens * InputPerMillionTokens + outputTokens * OutputPerMillionTokens) / 1_000_000m;
6 }
7}The price calculation uses decimal to avoid binary floating-point rounding in monetary arithmetic; The Big Decimal Bugfix with .NET 11
shows what happens otherwise. Prices such as 0.40 (input) and 1.60 (output) US dollars per million tokens for gpt-4.1-mini are examples; the Azure pricing page
and the applicable contract determine the actual rates.
The interesting part is not the price per token but the growth. Because the whole history is sent with every request, the input is paid again on every request. An illustrative calculation: if every question and answer together add 150 tokens, request number 20 carries roughly 3,000 input tokens. Across all 20 requests, the model reads about 150 × (1 + 2 + … + 20) = 31,500 input tokens - for a conversation that is only 3,000 tokens long.
With a roughly constant amount of new text per turn and the complete history resent each time, cumulative input token usage grows quadratically with the number of turns. For gpt-4.1-mini, 31,500 input tokens are about one cent. With a larger model, a long system prompt or several thousand tokens of retrieved context per request, the same pattern dominates the bill.
Prompt caching reduces the price of a repeated input prefix once it is long enough. The calculation above ignores it, so it illustrates uncached input cost rather than predicting an invoice.
Ollama or Foundry?
| Ollama | Microsoft Foundry | |
|---|---|---|
| Where the model runs | Local machine, downloaded and loaded into memory | Azure, as a deployment |
| Access | None | Endpoint plus API key or Microsoft Entra ID |
| Cost | Own hardware | Per token, input and output billed separately |
| Context window | Set by Ollama when loading (4,096 tokens in this setup) | About 1 million tokens for gpt-4.1-mini |
| Timings | Server-side: load, prompt evaluation, generation | Client-side only, including network |
| Data | Never leaves the machine | Processed in Azure, location depends on the deployment type |
| Answer quality | Limited by local hardware; small models make more factual mistakes | Larger models, fewer mistakes |
Ollama is the better start for learning, offline work and data that must not leave the machine. Foundry is the better start for answer quality, large contexts and anything that will eventually run in production. With IChatClient, the decision does not have to be final.
Where to go from here
Two knobs are worth adding to any chat right after it works.
Model parameters are passed through ChatOptions. A lower temperature reduces sampling variation without guaranteeing deterministic or correct output; leaving it null uses the provider’s default:
1ChatOptions chatOptions = new() { Temperature = 0.2f };
2
3await foreach (ChatResponseUpdate update in chatClient.GetStreamingResponseAsync(history, chatOptions, token))
4{
5 // ...
6}Bounding the history limits both input size and cost. For this text-only loop, old messages can be removed while retaining the system prompt and beginning with a user question:
1// Index 0 is the system prompt and always stays.
2while (history.Count > 1
3 && (history.Count - 1 > maxHistoryMessages || history[1].Role != ChatRole.User))
4{
5 history.RemoveAt(1);
6}Removed messages are no longer available to the model. Summarizing them can retain some context, but introduces another generated representation to verify. Once tools are added, trimming also has to preserve complete call/result pairs and pending approval state; the simple loop above is intended for text messages only.
Everything else builds on the same interface. IChatClient composes like ASP.NET Core middleware, so tool calling and telemetry are layers around the existing client, not changes to the loop:
1IChatClient chatClient = innerClient
2 .AsBuilder()
3 .UseFunctionInvocation()
4 .UseOpenTelemetry()
5 .Build();The part that stays
The common interface makes it possible to keep history management, cancellation and streaming in one place while changing the provider at startup. It does not remove the need to understand the backend: local context limits, Azure credentials and usage reporting still shape the application.
The console is useful precisely because those responsibilities remain visible. Each request shows what the application sent, how long the response took and how much history it carried. Later parts build on that same loop when local data and tools become part of the conversation.
Further reading
Related articles

- 10 min read
Migrating Semantic Kernel Agents to Microsoft Agent Framework
Microsoft Agent Framework is the successor to the agent capabilities in Semantic Kernel and AutoGen. That statement is easy to misread as …

- 22 min read
Building Production MCP Servers with ASP.NET Core
An MCP server can look deceptively small. A package is installed, a method receives an attribute and ASP.NET Core maps an endpoint. That is …

- 11 min read
MCP C# SDK 2.0: Stateless HTTP, Interactive Tools and a Practical Migration Path
The 2.0 release of the official Model Context Protocol (MCP) C# SDK is more than a version increment. It implements the 2026-07-28 MCP …
Let's Work Together
Looking for an experienced Platform Architect or Engineer for your next project? Whether it's cloud migration, platform modernization or building new solutions from scratch - I'm here to help you succeed.
