Article · AI in .NET · Tool use (function calling)
AI in .NET: Microsoft.Extensions.AI, official SDKs, Semantic Kernel and Agent Framework
A map of the .NET AI ecosystem and practical C# code – the official Anthropic and OpenAI SDKs, the IChatClient and IEmbeddingGenerator abstractions, a middleware pipeline in ASP.NET Core, tools, structured output, Semantic Kernel and Microsoft Agent Framework.
Not long ago, integrating a language model into a .NET application meant hand-written HttpClient calls or tying yourself to a single provider. Today the ecosystem has clear layers: the providers' official SDKs, the shared Microsoft.Extensions.AI abstractions familiar from the rest of Microsoft.Extensions.*, Semantic Kernel for orchestration and Microsoft Agent Framework for agents. This article puts that map in order and shows code you can paste into an ASP.NET Core project.
- 2
- interfaces to remember – IChatClient and IEmbeddingGenerator
- 1
- place in DI – switch providers without touching business logic
- 4
- middleware layers "for free" – logging, OpenTelemetry, caching, tool invocation
The problem: three teams, three integrations
Halina's Pierogi backend is ASP.NET Core. The orders team wrote its own REST calls to one provider, the marketing team used another library to summarize reviews, and the customer service team has a third, with hand-parsed JSON from the model's answers. The consequences:
- nobody knows how many tokens each feature uses – there is no shared telemetry,
- unit tests need an API key or get skipped,
- changing the model in one place means rewriting code, not changing configuration.
It is the same problem .NET once solved for logging (ILogger) and caching (IDistributedCache): a shared abstraction plus interchangeable implementations.
The ecosystem map
| Layer | Packages | What for |
|---|---|---|
| Provider SDK | Anthropic, OpenAI, Azure.AI.OpenAI, OllamaSharp | the provider's full API: prompt caching, effort, batch, files |
| Abstractions | Microsoft.Extensions.AI (+ .Abstractions) | IChatClient, IEmbeddingGenerator, middleware, tools, structured output |
| Vector data | Microsoft.Extensions.VectorData + connectors | a shared model for vector databases (Qdrant, PostgreSQL/pgvector, Azure AI Search, Redis…) |
| Orchestration | Microsoft.SemanticKernel | kernel, plugins, prompt templates, automatic function calling |
| Agents | Microsoft.Agents.AI (Microsoft Agent Framework) | agents on any IChatClient, conversation threads, multi-agent workflows |
| Protocol | ModelContextProtocol (MCP C# SDK) | MCP servers and clients |
nuget: Microsoft.Extensions.AI
nuget: Anthropic
Official SDKs and the IChatClient abstraction
Start with a question: do you need provider-specific features? Prompt caching, the effort level, the Batches API or refusal fallbacks are easiest to handle directly in the SDK. For typical chat, extraction and tools, IChatClient is enough – and the official Anthropic and OpenAI SDKs ship ready-made AsIChatClient() adapters.
Official SDKs, the abstraction and structured output
using Anthropic;
using Anthropic.Models.Messages;
// Official Anthropic SDK: full access to provider-specific features.
AnthropicClient client = new(); // reads ANTHROPIC_API_KEY
var parameters = new MessageCreateParams
{
Model = "claude-opus-5-5",
MaxTokens = 4096,
OutputConfig = new OutputConfig { Effort = Effort.Low }, // provider-specific: effort
System = new List<TextBlockParam>
{
new() { Text = File.ReadAllText("menu.md"), CacheControl = new CacheControlEphemeral() }, // prompt caching
},
Messages = [new UserMessageParam { Content = "Which pierogi are vegetarian?" }],
};
// Stream the answer token by token.
await foreach (RawMessageStreamEvent ev in client.Messages.CreateStreaming(parameters))
{
if (ev.TryPickContentBlockDelta(out var delta) && delta.Delta.TryPickText(out var text))
Console.Write(text.Text);
}using Anthropic;
using Microsoft.Extensions.AI;
using OpenAI;
// One interface, many providers: business code depends only on IChatClient.
IChatClient claude = new AnthropicClient().AsIChatClient("claude-opus-5-5");
IChatClient gpt = new OpenAIClient(Environment.GetEnvironmentVariable("OPENAI_API_KEY"))
.GetChatClient("gpt-5-mini").AsIChatClient();
foreach (IChatClient chat in new[] { claude, gpt })
{
ChatResponse response = await chat.GetResponseAsync(
[
new ChatMessage(ChatRole.System, "You are the support assistant of Halina's Pierogi. Be brief."),
new ChatMessage(ChatRole.User, "Do you deliver on Sundays?"),
]);
Console.WriteLine($"{response.ModelId}: {response.Text}");
Console.WriteLine($"tokens in={response.Usage?.InputTokenCount} out={response.Usage?.OutputTokenCount}");
}using Anthropic;
using Microsoft.Extensions.AI;
IChatClient chat = new AnthropicClient().AsIChatClient("claude-opus-5-5");
// GetResponseAsync<T> requests JSON matching T's schema and deserializes it.
ChatResponse<Complaint> response = await chat.GetResponseAsync<Complaint>(
"Classify: 'The courier was 50 minutes late and the pierogi were cold.'");
if (response.TryGetResult(out Complaint? complaint))
Console.WriteLine($"{complaint.Category}, urgent={complaint.Urgent}: {complaint.Summary}");
public sealed record Complaint(string Category, bool Urgent, string Summary);The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- ASP.NET Core: DI, middleware and tools
- Embeddings, Semantic Kernel and agents
- Step by step: adopting it in an existing project
- Abstraction or the SDK directly?
- Checklist
- Test yourself
- What's next