Ollama from C# in 2026: IChatClient with OllamaSharp, Without the Deprecated Package
Which NuGet packages to install to call a local Ollama model from .NET 10, how to register IChatClient in a minimal API, stream tokens over SSE and get typed JSON back. Measured on two small models, plus what the deprecated package still does.
TL;DR. To call Ollama from C# today, install OllamaSharp (5.5.2) and Microsoft.Extensions.AI (11.0.1). Do not install Microsoft.Extensions.AI.Ollama: it is deprecated, it never shipped a stable version, and Microsoft’s own docs now build IChatClient from OllamaSharp’s OllamaApiClient. Register it with builder.Services.AddChatClient(new OllamaApiClient(uri, model)), inject IChatClient, and use GetResponseAsync, GetStreamingResponseAsync and GetResponseAsync<T> for typed JSON. The whole working API is about 60 lines, below.
new OllamaChatClient(...) is the line most older .NET samples start from. That class lives in Microsoft.Extensions.AI.Ollama, a package NuGet now marks as deprecated. So I set up a clean .NET 10 minimal API against a current Ollama, built the same thing the old way next to it, and measured both the streaming latency and how often a small local model returns JSON that actually deserializes.
The setup I tested on
Everything ran in containers on a 12-core x86_64 Linux box, CPU only, no GPU:
- Ollama 0.40.18 (the release published the same day I ran this), in its own container.
- .NET SDK 10.0.404 from
mcr.microsoft.com/dotnet/sdk:10.0. OllamaSharp5.5.2,Microsoft.Extensions.AI11.0.1,Microsoft.Extensions.AI.OpenAI11.0.1 (only for the swap test).- Two small models:
qwen2.5:1.5b(986 MB) andllama3.2:3b(2.0 GB).
The box is shared and other jobs were running while I measured. That matters for the latency numbers, and I come back to it below.
Which package to install, and what the old one actually does
The package most tutorials still reference is Microsoft.Extensions.AI.Ollama. Its NuGet page says it plainly: “This package is deprecated and the OllamaSharp package is recommended” and “No further updates, features, or fixes are planned”. Its last version is 9.7.0-preview.1.25356.2, from July 2025.
I wanted to know what actually happens if you follow an old tutorial in a fresh project, so I tried. The first surprise is that it does not even install the normal way:
$ dotnet add package Microsoft.Extensions.AI.Ollama
[...]
error: There are no stable versions available, 9.7.0-preview.1.25356.2 is the best available. Consider adding the --prerelease option
With --prerelease it installs, and then nothing complains. The build reports zero warnings. The only place the deprecation shows up is a command you have to know to run:
$ dotnet list package --deprecated
Project `legacy` has the following deprecated packages
[net10.0]:
Top-level Package Requested Resolved Reason(s) Alternative
> Microsoft.Extensions.AI.Ollama 9.7.0-preview.1.25356.2 9.7.0-preview.1.25356.2 Other OllamaSharp >= 0.0.0
The second surprise is that it still works. With Microsoft.Extensions.AI 11.0.1 next to it, NuGet resolved Microsoft.Extensions.AI.Abstractions to 11.0.1, and this three-liner answered against Ollama 0.40.18:
using Microsoft.Extensions.AI;
// What the old tutorials tell you to write.
IChatClient client = new OllamaChatClient(new Uri("http://post1-ollama:11434"), "qwen2.5:1.5b");
Console.WriteLine(await client.GetResponseAsync("Say hi in three words."));
Hello there.
So the honest version of “the package is deprecated” is not “it is broken”. It is frozen. It still compiles against the 11.x abstractions today, but nobody will fix it when Ollama or the abstractions move, while OllamaSharp keeps shipping: 5.5.2 (5 November) fixed reasoning content being dropped on the IChatClient path, which is exactly the kind of fix a frozen package will never get. I would not start anything new on it, and if dotnet list package --deprecated prints it in an existing project, the migration is a one-line constructor change.
What to install instead:
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.AI" Version="11.0.1" />
<PackageReference Include="OllamaSharp" Version="5.5.2" />
</ItemGroup>
OllamaSharp only depends on Microsoft.Extensions.AI.Abstractions (>= 10.8.0). Microsoft.Extensions.AI is the package with the builder, AddChatClient, logging, caching and function invocation. You want both in an app.
The whole API: one IChatClient, three endpoints
OllamaApiClient implements IChatClient directly, so there is no adapter class to look for. This is the full Program.cs I ran, including the provider switch I use later:
using System.ComponentModel;
using System.Text.Json.Serialization;
using Microsoft.Extensions.AI;
using OllamaSharp;
using OpenAI;
var builder = WebApplication.CreateBuilder(args);
var ollamaUrl = builder.Configuration["Ollama:Url"] ?? "http://post1-ollama:11434";
var model = builder.Configuration["Ollama:Model"] ?? "qwen2.5:1.5b";
// One IChatClient for the whole app. Swap the provider here, nothing else changes.
IChatClient inner = builder.Configuration["Provider"] == "openai"
? new OpenAIClient(
new System.ClientModel.ApiKeyCredential("ollama"),
new OpenAIClientOptions { Endpoint = new Uri($"{ollamaUrl}/v1") })
.GetChatClient(model).AsIChatClient()
: new OllamaApiClient(new Uri(ollamaUrl), model);
builder.Services.AddChatClient(inner).UseLogging();
var app = builder.Build();
app.MapPost("/chat", async (Prompt p, IChatClient chat, CancellationToken ct) =>
{
var res = await chat.GetResponseAsync(p.Text, Options(p), ct);
return Results.Ok(new { res.Text, res.ModelId, res.Usage?.OutputTokenCount });
});
app.MapPost("/stream", (Prompt p, IChatClient chat, CancellationToken ct) =>
TypedResults.ServerSentEvents(Tokens(chat, p, ct)));
static async IAsyncEnumerable<string> Tokens(IChatClient chat, Prompt p,
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken ct)
{
await foreach (var update in chat.GetStreamingResponseAsync(p.Text, Options(p), ct))
if (!string.IsNullOrEmpty(update.Text))
yield return update.Text;
}
app.MapPost("/ticket", async (Prompt p, IChatClient chat, CancellationToken ct) =>
{
var res = await chat.GetResponseAsync<Ticket>(
$"Classify this support message:\n{p.Text}", Options(p), cancellationToken: ct);
return res.TryGetResult(out var ticket)
? Results.Ok(ticket)
: Results.UnprocessableEntity(new { raw = res.Text });
});
app.Run();
static ChatOptions Options(Prompt p) => new() { ModelId = p.Model, Temperature = 0 };
record Prompt(string Text, string? Model = null);
[JsonConverter(typeof(JsonStringEnumConverter<Category>))]
enum Category { Billing, Bug, Account, FeatureRequest }
record Ticket(
Category Category,
[property: Description("1 = low, 3 = urgent")] int Priority,
[property: Description("One sentence, max 15 words")] string Summary);
It built with 0 warnings and 0 errors. A few things in there are easy to get wrong.
AddChatClient returns a builder. .UseLogging() (and .UseDistributedCache(), .UseFunctionInvocation(), .UseOpenTelemetry()) wrap the inner client in a pipeline. Handlers never see OllamaApiClient, only IChatClient, which is the point of the abstraction and what makes the swap later a one-line change.
ModelId per request. The constructor sets the default model, and ChatOptions.ModelId overrides it per call. One registered client served both models in my tests.
Streaming without blocking a thread. GetStreamingResponseAsync returns an IAsyncEnumerable<ChatResponseUpdate>, and .NET 10’s TypedResults.ServerSentEvents takes an IAsyncEnumerable and writes each item as an SSE event as it arrives. No Response.Body plumbing, no manual flush. I pass the request CancellationToken all the way down so a client that disconnects can cancel the enumeration; I did not test that path here, it deserves its own post. I also skip updates with empty Text, since not every update carries text and an empty SSE event is just noise for the browser.
The three endpoints, called with curl against qwen2.5:1.5b:
$ curl -s -d '{"text":"Say hi in three words."}' -H 'Content-Type: application/json' localhost:5101/chat
{"text":"Hello world!","modelId":"qwen2.5:1.5b","outputTokenCount":4}
$ curl -sN -d '{"text":"Count from 1 to 5."}' -H 'Content-Type: application/json' localhost:5101/stream
data: 1
data: ,
data:
data: 2
[...]
$ curl -s -d '{"text":"I was charged twice for my November invoice, please refund one."}' -H 'Content-Type: application/json' localhost:5101/ticket
{"category":"Billing","priority":2,"summary":"Customer is requesting a refund for a billing error."}
What GetResponseAsync<T> sends to Ollama
GetResponseAsync<T> is an extension method in Microsoft.Extensions.AI. It generates a JSON schema from T, puts it in ChatOptions.ResponseFormat, and deserializes the reply. I wanted to see the schema rather than trust it, so I turned the LoggingChatClient up to Trace (Logging__LogLevel__Microsoft.Extensions.AI=Trace) and sent one ticket. Trimmed log:
GetResponseAsync invoked: [ ... "text": "Classify this support message:\nThe export button crashes the app." ... ]. Options: {
"temperature": 0,
"responseFormat": {
"$type": "json",
"schema": {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"category": {
"type": "string",
"enum": [ "Billing", "Bug", "Account", "FeatureRequest" ]
},
"priority": {
"description": "1 = low, 3 = urgent",
"type": "integer"
},
"summary": {
"description": "One sentence, max 15 words",
"type": "string"
}
},
"required": [ "category", "priority", "summary" ]
},
"schemaName": "Ticket"
}
}. Metadata: {
"providerName": "ollama",
[...]
Two details are worth copying. The [JsonConverter(typeof(JsonStringEnumConverter<Category>))] on the enum turns it into a string enum in the schema, so the model is constrained to four exact labels instead of an integer it has to guess. And the [Description] attributes end up in the schema too, which is the only place I had to put the “1 to 3” scale. From there it is OllamaSharp’s job to hand the schema to Ollama’s format parameter, which constrains generation to it. I tried to capture the raw HTTP request to show that step too and could not get a capture working on this box, so for that hop I am relying on the docs and on the results below.
TryGetResult is the part people skip. res.Result throws if the text does not deserialize. TryGetResult lets the endpoint answer 422 with the raw text instead of a 500, which is what you want when a local model has a bad day.
Where structured output still fails
I sent 10 fixed support messages to /ticket with each model, temperature 0, and checked two things: did the JSON deserialize into Ticket, and was the category the one I would have picked.
| Model | Provider | Parsed into Ticket | Category as expected |
|---|---|---|---|
qwen2.5:1.5b | OllamaSharp | 10/10 | 10/10 |
llama3.2:3b | OllamaSharp | 10/10 | 9/10 |
qwen2.5:1.5b | OpenAI client on /v1 | 10/10 | 10/10 |
llama3.2:3b | OpenAI client on /v1 | 10/10 | 9/10 |
Parsing never failed. With the schema enforced by Ollama, I could not get a malformed Ticket out of either model on this set. The one miss was a value, not a shape, and it was the same miss through both providers:
('wrong', 'Billing', {'category': 'Account', 'priority': 2, 'summary': 'VAT Error on Last Receipt'})
The input was “Your VAT is wrong on the last receipt, it should be 22 percent not 20.” That is a billing problem. llama3.2:3b returned a perfectly valid Account. The bigger model was the one that got it wrong, which I did not expect, and 10 inputs is far too few to rank the two models on accuracy. What it does show is the failure mode to design for: the schema guarantees the type, the enum guarantees the label exists, and nothing guarantees the label is right. If a category routes money or people, validate it against something that is not the model. I wrote about that exact trap in the LLM ticket dispatcher post, where the JSON was fine and the meaning was not.
The numbers: time to first token and total latency
The client was a small Python script that posts to /stream and records when the first data: event arrives (time to first token, measured end to end through ASP.NET Core) and when the stream ends. Each run uses a different prompt from a fixed list of seven (“In two sentences, what is a reverse proxy?”, “…a database index?”, and so on), so Ollama cannot reuse a cached prompt between runs. A warm-up request loads the model and is not counted. Seven runs per model, two rounds, medians:
| Path | Model | TTFT median (round 1 / 2) | Total median (round 1 / 2) |
|---|---|---|---|
| API, OllamaSharp | qwen2.5:1.5b | 0.078 s / 0.101 s | 0.862 s / 0.867 s |
| API, OllamaSharp | llama3.2:3b | 0.169 s / 0.158 s | 4.175 s / 4.144 s |
API, OpenAI client on /v1 | qwen2.5:1.5b | 0.093 s | 0.888 s |
API, OpenAI client on /v1 | llama3.2:3b | 0.158 s | 4.402 s |
Ollama /api/chat directly, no .NET | qwen2.5:1.5b | 0.072 s / 0.073 s | 0.800 s / 0.801 s |
Ollama /api/chat directly, no .NET | llama3.2:3b | 0.061 s / 0.069 s | 4.043 s / 5.014 s |
The totals are not a speed comparison between the models. llama3.2:3b simply wrote longer answers to the same prompts: 59 to 78 stream chunks per answer against 16 to 34 for qwen2.5:1.5b.
Loading the model is the cost that dwarfs everything else. The first request after ollama stop took 2.2 to 2.3 s to the first token for llama3.2:3b and 1.2 s for qwen2.5:1.5b, and one cold load of qwen2.5:1.5b, during a busier minute on the box, took 15.3 s. If your API has a cold-start path, that is where the latency is, not in the client library.
For qwen2.5:1.5b the API adds a few tens of milliseconds over calling Ollama directly. For llama3.2:3b the gap in time to first token is closer to 100 ms, consistently, with both the OllamaSharp and the OpenAI client. I did not pin down why. It could be the request shape, or ASP.NET Core competing for CPU with the model on a busy box, and I would not build a conclusion on it without a quieter machine.
The busy box is not a hypothetical. My first round ran while the load average was 18.6 on 12 cores, and qwen2.5:1.5b went from under a second to a median total of 19.3 s, with one run at 67.8 s and a first token at 3.9 s. A later llama3.2:3b run at load 29 had a median total of 28 s. I threw those rounds away for the table, but they are the most useful numbers here if you plan to run CPU inference on the same server as anything else: the model does not degrade gracefully when it shares cores, it falls off a cliff.
Swapping Ollama for an OpenAI-compatible endpoint
The Provider=openai branch in Program.cs builds the IChatClient from the official OpenAI client via Microsoft.Extensions.AI.OpenAI and points it at Ollama’s OpenAI-compatible /v1 endpoint, with a dummy key. No handler changed. All three endpoints worked, GetResponseAsync<T> went through the OpenAI client (which speaks response_format, and Ollama’s docs say /v1 supports it), and the structured output results above were identical.
That is the practical value of the abstraction. When I want to move one route to a hosted model, I change where inner comes from and keep the handlers, the tests and the logging pipeline. I did not test a paid provider here, so I can only say the interface held between two transports to the same server, which is a weaker claim than “it works with any cloud”. It is still the part of the stack I would least like to rewrite later.
What I would not use this for yet
A 1.5B or 3B model on CPU is fine for classification, extraction into a small schema and short answers where a second of latency is acceptable. For anything where the label carries consequences, the 9/10 above is the number to remember, and the fix is not a better prompt but a check outside the model. I also would not put CPU inference on a box that serves other traffic, after watching a sub-second request take 67 s.
If you want to go further with a local model in .NET, the next steps are retrieval and tools. I covered both, still on OllamaSharp, in a local chatbot with tool calling and RAG without a vector database, and the privacy side of keeping everything on your own machine in building a privacy-first local RAG system.
Verdict
Use OllamaSharp behind IChatClient and nothing else. The deprecated Microsoft.Extensions.AI.Ollama still runs today, which is exactly why it is dangerous: it builds without a warning, and you find out it is frozen the day you need a fix. OllamaSharp is the package Microsoft’s own docs use, it implements IChatClient directly, and with AddChatClient plus GetResponseAsync<T> you get DI, streaming and schema-constrained JSON in about 60 lines. The library is not where your latency or your errors will come from. The model load and the model’s judgement are.