AI in .NET
In .NET, the Microsoft.Extensions.AI packages give one small interface for chat (IChatClient) and one for embeddings (IEmbeddingGenerator). Your code talks to the interface, and the model provider is set up once in dependency injection. Around it you add a pipeline of middleware for logging, caching, tool calls and tracing. Ask for typed output instead of parsing text, stream long answers, and test with a fake client. Semantic Kernel and Agent Framework sit on top when you need more.
Author: bezzad
Contents
The problem: the model is everywhere in the code
Our online shop is an ASP.NET Core app. The team added a help assistant that answers customer questions. Three months later:
- The vendor SDK is used in 14 files. Each file builds its own client and reads the API key in its own way.
- The team wants to try a local model for cheap tasks. It means changing all 14 files.
- Nobody knows what was sent. When a customer got a strange answer, there was no log of the prompt.
- The tests call the paid API. They are slow, they cost money, and they fail when the network is down.
These are normal backend problems: a hidden dependency, no abstraction, no logs, no fakes. .NET already has good answers for them.
One interface for every model
The Microsoft.Extensions.AI packages define two small interfaces:
- IChatClient sends messages and gets an answer (or a stream of answer pieces).
- IEmbeddingGenerator turns text into vectors. The embeddings lesson explains what they are for.
Each provider (OpenAI, Azure OpenAI, Ollama for local models, and others) gives an adapter that implements these interfaces. Your code knows only the interface.
Register it once, in Program.cs:
// Packages: Microsoft.Extensions.AI and Microsoft.Extensions.AI.OpenAI
var key = builder.Configuration["OpenAI:Key"]!;
IChatClient inner = new OpenAI.Chat.ChatClient("gpt-4o-mini", key)
.AsIChatClient();
builder.Services.AddChatClient(inner)
.UseLogging()
.UseOpenTelemetry();
Then any class asks for it in its constructor, like any other service:
public sealed class HelpAssistant(IChatClient chat)
{
public async Task<string> AskAsync(string question, CancellationToken ct)
{
ChatResponse answer = await chat.GetResponseAsync(question, cancellationToken: ct);
return answer.Text;
}
}
To try a local model, you change one line in Program.cs. The 14 files do not change.
The middleware pipeline
The builder works like the ASP.NET Core middleware pipeline. Each Use call wraps the client with one more layer:
- UseLogging writes the messages and answers to your normal logs. Be careful: prompts can hold personal data.
- UseOpenTelemetry creates a trace span per call, with the model name and token counts. The tracing lesson shows why this matters.
- UseDistributedCache returns a saved answer when the same messages come again. Good for fixed prompts, dangerous for answers that depend on live data.
- UseFunctionInvocation runs tools: when the model asks for a tool, this layer calls your C# method and sends the result back.
Order matters. The first Use is the outer layer. If the cache is outside the tool layer, it saves the final answer, including live data from tools like “your order is on the way”. The next customer with the same words gets an old status.
Ask for typed output, not text
A common first version asks “Reply with the category” and then compares strings. It works in the demo. In production the model writes “Category: Shipping.” with a dot, and the switch falls to the default case.
public enum Topic { Shipping, Returns, Payment, Other }
public sealed record Triage(Topic Topic, bool NeedsHuman, string Reason);
ChatResponse<Triage> response = await chat.GetResponseAsync<Triage>(
$"Sort this customer message: {message}", cancellationToken: ct);
if (!response.TryGetResult(out Triage? triage))
triage = new Triage(Topic.Other, NeedsHuman: true, "Could not read model output");
- The type is the contract. The library sends a JSON schema made from the record. Many providers can force the answer to follow it.
- Still check it. A model can return a valid shape with a wrong value. Keep your business rules in C#.
- Have a safe fallback. Here, a message we cannot read goes to a person.
Stream long answers
A long answer can take several seconds. Show the first words fast:
app.MapGet("/help/stream", (string q, IChatClient chat, CancellationToken ct) =>
TypedResults.ServerSentEvents(Stream(q, chat, ct)));
static async IAsyncEnumerable<string> Stream(
string q, IChatClient chat, [EnumeratorCancellation] CancellationToken ct)
{
await foreach (var update in chat.GetStreamingResponseAsync(q, cancellationToken: ct))
yield return update.Text;
}
Pass the cancellation token. When the customer closes the page, the request to the model stops too, and you stop paying for tokens nobody reads.
Tools in .NET
A tool is a normal C# method with a description. The model reads the description and decides when to call it.
[Description("Gets the shipping status of one order of the signed-in customer.")]
async Task<string> GetOrderStatus(string orderId) =>
await orders.StatusForCustomerAsync(orderId, currentUser.Id);
var options = new ChatOptions { Tools = [AIFunctionFactory.Create(GetOrderStatus)] };
var answer = await chat.GetResponseAsync(messages, options, ct);
The tool layer (UseFunctionInvocation) must be in the pipeline. The method uses the signed-in user from your code, never a customer id sent by the model. The agents lesson covers limits and human approval.
Test without the real model
Because your code depends on an interface, a test can pass a small fake:
sealed class FakeChat(string reply) : IChatClient
{
public Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages,
ChatOptions? options = null, CancellationToken ct = default) =>
Task.FromResult(new ChatResponse(new ChatMessage(ChatRole.Assistant, reply)));
public IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
IEnumerable<ChatMessage> messages, ChatOptions? options = null,
CancellationToken ct = default) => throw new NotSupportedException();
public object? GetService(Type serviceType, object? key = null) => null;
public void Dispose() { }
}
Unit tests check your code: the fallback, the rules, the tool permissions. The quality of the model’s answers is checked by evals, a different kind of test (see the evals lesson).
Semantic Kernel and Agent Framework
Two bigger Microsoft libraries build on the same interfaces:
- Semantic Kernel has plugins, prompt templates, memory connectors for vector stores, and agent helpers. Many .NET teams already use it.
- Microsoft Agent Framework is the newer library for agents and multi-step workflows. It joins ideas from Semantic Kernel and AutoGen. It was still young when this lesson was written, so check its current status.
Start with IChatClient. Add a bigger library only when you need its features, for example many agents that hand work to each other. Interviewers like to hear why you picked a library, not only its name.
Common mistakes
| Mistake | Result | Right way |
|---|---|---|
| New vendor client in every class | Changing the model touches many files. | One IChatClient in DI. |
| API key in code or in the repo | The key leaks. | User secrets, environment, or a key vault. |
| Parsing free text with string compares | Breaks on a dot or a new word. | Typed output, plus checks and a fallback. |
| Cache outside the tool layer | Old live data in new answers. | Cache only answers that do not depend on live data. |
| No cancellation token | You pay for answers nobody reads. | Pass the request’s token all the way down. |
| Unit tests call the real model | Slow, costly, flaky tests. | A fake client for unit tests, evals for quality. |
Summary in six lines
- IChatClient and IEmbeddingGenerator hide the provider; set the provider once in DI.
- Middleware adds logging, tracing, caching and tool calls; the order of layers matters.
- Ask for a C# type, not text, and keep checks and a fallback in your code.
- Stream long answers and pass the cancellation token.
- Tools are C# methods that use the signed-in user, never ids from the model.
- Fake the client in unit tests; check answer quality with evals.