BrandGhost
Microsoft Agent Framework in C#: Complete Developer Guide

Microsoft Agent Framework in C#: Complete Developer Guide

Microsoft Agent Framework in C#: Complete Developer Guide

The microsoft agent framework c# is Microsoft's focused, first-class library for building AI agents in .NET -- and it fundamentally changes how you integrate large language models into your applications. Rather than manually wiring raw chat completions or reaching for the full weight of Semantic Kernel, the Microsoft Agent Framework (MAF) gives you a lightweight, purpose-built abstraction layer on top of Microsoft.Extensions.AI. You get structured agents, session memory, tool calling, and streaming support -- all in a package designed to work with any IChatClient-compatible provider.

As of this writing, the Microsoft Agent Framework in C# ships as Microsoft.Agents.AI at version 1.0.0-rc1 and is in public preview. The APIs are stabilizing rapidly, but you should expect the possibility of breaking changes before the GA release. This guide walks you through everything you need to understand MAF -- what it is, how it works under the hood, how its core abstractions fit together, and when to reach for it over alternatives like raw IChatClient or Semantic Kernel.

What Is the Microsoft Agent Framework?

Microsoft Agent Framework is a .NET library that provides a thin but powerful orchestration layer on top of Microsoft.Extensions.AI. The core idea is straightforward: give developers a standardized way to build AI agents in C# without having to reinvent conversation management, tool invocation loops, or streaming infrastructure every time.

MAF sits in an interesting spot in the Microsoft AI ecosystem. Microsoft.Extensions.AI defines the base abstractions -- primarily IChatClient -- that let you swap LLM providers without changing your application code. But IChatClient is low-level by design. It's a single interface for sending chat messages and receiving completions. MAF layers on top of IChatClient to provide the agent-level primitives you actually need in production: persistent conversation context, tool/function calling, system prompt management, and a clean streaming API.

Think of the relationship this way: IChatClient is to MAF what HttpClient is to a REST client library. The low-level primitive is there, but the framework gives you structured patterns on top of it.

MAF is not a replacement for Semantic Kernel. Semantic Kernel is a full orchestration framework with memory plugins, planners, vector stores, and a rich plugin system. The Microsoft Agent Framework in C# is intentionally narrower -- it focuses on the agent execution loop and leaves the rest to you. If you need the full SK feature set, use SK. If you need something leaner that builds directly on IChatClient, MAF is the better fit.

Core Abstractions in Microsoft Agent Framework

Understanding the four core building blocks of MAF is the key to using it effectively. Each abstraction serves a distinct purpose in the agent execution model.

IAIAgent

IAIAgent is the central interface in MAF. It represents an AI agent -- an entity that can receive a prompt and produce a response, optionally using tools and maintaining conversation state. The interface defines the two methods you'll use in every MAF application:

  • RunAsync -- runs the agent with a prompt and returns an AgentResponse
  • RunStreamingAsync -- runs the agent with a prompt and streams back StreamingAgentResponse chunks

Both methods accept an optional AgentSession parameter for multi-turn conversation memory and a CancellationToken for cooperative cancellation. The interface keeps things intentionally minimal -- you interact with an agent through prompts and responses, regardless of which LLM is powering it under the hood.

ChatClientAgent

ChatClientAgent is the concrete implementation of IAIAgent that ships with MAF. It wraps any IChatClient and adds agent-level orchestration: processing system instructions, managing the tool invocation loop, and handling conversation history. You typically never instantiate ChatClientAgent directly -- instead, you use the AsAIAgent() extension method on any IChatClient to create one.

ChatClientAgent handles the tool loop automatically. When you register tools and the LLM decides it needs to call one, ChatClientAgent executes the function, appends the result to the conversation, and re-invokes the model -- all without you writing any of that plumbing manually.

AgentSession

AgentSession is MAF's conversation memory container. It stores the message history for a conversation thread and passes that history along on each subsequent RunAsync call. Without a session, each call to RunAsync is stateless -- the agent has no memory of previous exchanges.

AgentSession is the answer to multi-turn conversations in MAF. Create one session per conversation, pass it into RunAsync on every turn, and dispose it when the conversation ends. Sessions are lightweight value objects and can be created freely without significant overhead.

AIFunctionFactory

AIFunctionFactory is the tool registration utility. It converts standard C# methods -- including lambdas, local functions, and static methods -- into AI functions that the LLM can invoke. Unlike Semantic Kernel's [KernelFunction] attribute approach, MAF uses AIFunctionFactory.Create() to wrap any callable delegate. This means zero new attributes required in your codebase.

AIFunctionFactory also handles schema generation automatically. It introspects method parameters and return types and generates the JSON schema that the LLM uses to understand when and how to call each tool.

How MAF Relates to Microsoft.Extensions.AI

Microsoft.Extensions.AI is a set of core .NET abstractions for AI services. The star of that package is IChatClient -- a provider-agnostic interface for sending chat messages to any LLM. OpenAI, Azure OpenAI, Ollama, and other providers all have IChatClient implementations. Once your code targets IChatClient, swapping providers is a configuration change, not a code change.

MAF builds directly on that ecosystem. Every agent you create starts with an IChatClient. The AsAIAgent() extension method accepts any IChatClient and wraps it with agent behavior. This means you don't need to change your provider setup to use MAF -- if you're already using Microsoft.Extensions.AI, you're already most of the way there.

Here's how they relate in practice:

using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

// Create an IChatClient from any provider
IChatClient chatClient = new OpenAIClient(new ApiKeyCredential(apiKey))
    .GetChatClient("gpt-4o-mini")
    .AsIChatClient();

// Wrap it with MAF to get an IAIAgent
var agent = chatClient.AsAIAgent(
    instructions: "You are a helpful C# coding assistant.");

The AsAIAgent() extension method is the bridge. Everything below it is standard Microsoft.Extensions.AI. Everything above it is MAF. This separation is deliberate -- it means middleware and pipeline components you've already built for IChatClient (logging, rate limiting, caching) continue working unchanged underneath your agents.

Installing Microsoft Agent Framework

Add the following NuGet packages to your project:

<PackageReference Include="Microsoft.Agents.AI" Version="1.0.0-rc1" />
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" Version="9.5.0-preview.*" />
<PackageReference Include="OpenAI" Version="2.*" />

For Azure OpenAI, swap OpenAI for Azure.AI.OpenAI and adjust the client setup accordingly. The rest of the MAF code is identical regardless of provider -- that's the whole point of the IChatClient abstraction.

Once the packages are installed, you'll need an API key or Azure endpoint. A standard pattern is to load provider configuration from appsettings.json:

{
  "AIProvider": {
    "Type": "openai",
    "ModelId": "gpt-4o-mini",
    "ApiKey": "",
    "Endpoint": ""
  }
}

You can wire this up through standard IConfiguration and dependency injection to keep your agent setup clean and testable.

Your First Agent in C#

With the packages installed and an API key ready, here's a minimal end-to-end example:

using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;

IChatClient chatClient = new OpenAIClient(new ApiKeyCredential(apiKey))
    .GetChatClient("gpt-4o-mini")
    .AsIChatClient();

var agent = chatClient.AsAIAgent(
    instructions: "You are a helpful C# coding assistant. Be concise and precise.");

// Single-turn -- no session, stateless
AgentResponse response = await agent.RunAsync("What is the difference between ref and out in C#?");
Console.WriteLine(response.Text);

// Streaming -- ideal for long responses or interactive UIs
Console.WriteLine("\n--- Streaming Response ---");
await foreach (StreamingAgentResponse chunk in agent.RunStreamingAsync("Show me a simple stack implementation in C#"))
{
    Console.Write(chunk.Text);
}

This is a fully functional agent. No boilerplate conversation loop, no message list management, no tool loop wiring -- MAF handles all of that internally.

Architecture Overview: Agents, Tools, Sessions, and Middleware

MAF's architecture follows a layered model. At the bottom is your IChatClient provider. Above it sits ChatClientAgent, which manages system instructions and the tool invocation loop. Above that, you have AgentSession for conversation state.

Agents are the entry point for all LLM interactions. They encapsulate instructions (the system prompt) and the set of registered tools. An agent is created once and reused across many conversations.

Tools are AIFunction instances created via AIFunctionFactory.Create(). You register tools at agent creation time by passing them to AsAIAgent(). The agent automatically invokes tools during the tool-calling loop when the LLM requests them.

Sessions carry conversation context. A session is a lightweight object that accumulates message history. You create one session per conversation thread and dispose it when done. Sessions are independent -- you can have thousands of concurrent sessions without cross-contamination.

Middleware on the IChatClient level still applies. Since ChatClientAgent ultimately calls through to an IChatClient, any middleware you've added to the IChatClient pipeline (logging, retry, rate limiting) operates transparently. MAF layers on top without disrupting it. This is similar to how decorator patterns layer behavior on top of existing implementations without modifying them.

This clean separation mirrors plugin-style architecture where each layer has a single responsibility.

When to Use MAF vs Raw IChatClient vs Semantic Kernel

Choosing the right abstraction level is important. Here's a practical breakdown:

Use raw IChatClient when:

  • You're building something very simple -- a single-turn Q&A with no tools
  • You want maximum control over the message list and completion options
  • You're building a custom agent framework yourself

Use Microsoft Agent Framework when:

  • You need multi-turn conversations with session memory
  • You need tool/function calling without building the invocation loop yourself
  • You want a lean, focused agent library with minimal dependencies
  • You're already in the Microsoft.Extensions.AI ecosystem and want a natural upgrade

Use Semantic Kernel when:

  • You need advanced planning and orchestration
  • You need vector memory stores and retrieval-augmented generation
  • You need SK's full plugin ecosystem
  • Your use case requires multi-agent coordination at scale

The right choice depends on complexity. MAF is specifically designed for teams that find raw IChatClient too low-level but don't need Semantic Kernel's full surface area. It is the "just right" middle ground for a large class of agent use cases.

MAF also plays well with ASP.NET Core and DI -- you can register your IChatClient and agent in the service container and inject IAIAgent wherever you need it, just as you would with any other service. This fits naturally with patterns like the abstract factory for creating provider-specific agents at runtime.

Building with MAF: What This Guide Covers

This guide is the entry point to a complete series on the microsoft agent framework c#. Here is what each topic covers:

Getting started -- full project setup, package installation, provider configuration, and your first streaming agent. This covers appsettings.json-driven provider switching and AI coding tool integration to accelerate your development.

IAIAgent and ChatClientAgent -- a deep dive into the two core abstractions. Understand the interface contract, what AsAIAgent() does internally, how instructions drive agent behavior, and when raw IChatClient is the better choice.

AgentSession and multi-turn conversations -- everything about session management. How to build stateful conversations, manage session lifecycle, handle concurrent sessions, and build a proper multi-turn Q&A loop.

AIFunctionFactory and tool calling -- how to register tools, guide the LLM with parameter descriptions, handle sync and async tools, deal with errors, and compare the MAF approach to Semantic Kernel's [KernelFunction] pattern.

Each topic builds on this foundation. If you're new to MAF, work through them in order. If you have a specific need, jump to the topic that addresses it.

FAQ

What is the Microsoft Agent Framework in C#?

The Microsoft Agent Framework (MAF) is a .NET library (Microsoft.Agents.AI) that provides a high-level abstraction for building AI agents on top of Microsoft.Extensions.AI. It adds agent identity, session memory, tool calling, and streaming on top of the standard IChatClient interface, giving you structured agent behavior without building the orchestration loop yourself.

Is the Microsoft Agent Framework production-ready?

MAF is in public preview at version 1.0.0-rc1. It is not yet at GA. Microsoft is actively developing it and the API surface is stabilizing, but breaking changes are possible before the final release. It is suitable for development and pilot projects, but you should plan for updates before going to production.

How does Microsoft Agent Framework differ from Semantic Kernel?

Semantic Kernel is a full orchestration framework with planners, vector memory, a rich plugin system, and multi-agent support. MAF is intentionally narrower -- it focuses on the core agent execution loop (single-turn, multi-turn, tool calling, streaming) and builds directly on IChatClient. If you need SK's advanced features, use SK. If you need a lean agent abstraction, use MAF.

Can I use Microsoft Agent Framework with Azure OpenAI?

Yes. MAF works with any IChatClient implementation, including Azure.AI.OpenAI. Create your AzureOpenAIClient, get a chat client for your deployment, call AsIChatClient(), and then call AsAIAgent(). The MAF code is identical regardless of which provider powers it.

What NuGet package do I install for Microsoft Agent Framework?

Install Microsoft.Agents.AI from NuGet. You will also need an IChatClient provider package such as Microsoft.Extensions.AI.OpenAI for OpenAI or Azure OpenAI support. As of this writing, the current version is 1.0.0-rc1.

Does Microsoft Agent Framework support streaming responses?

Yes. The RunStreamingAsync method on IAIAgent returns IAsyncEnumerable<StreamingAgentResponse>. Each chunk contains a Text property with the incremental content. This is suitable for interactive UIs, console streaming, and server-sent events in ASP.NET Core.

How does Microsoft Agent Framework handle tool calling?

Tool calling is managed automatically by ChatClientAgent. You register AIFunction instances (created via AIFunctionFactory.Create()) when building your agent. When the LLM decides to call a tool, ChatClientAgent executes the function, appends the result to the conversation, and re-invokes the model -- all in a loop until the LLM produces a final text response. You do not write any of this loop yourself.

Microsoft: Welcome to Your New Future!

2020 involved a career change that wasn't something I was planning. At the end of August, I started my adventure with Microsoft.

Entity Framework Core in Blazor - Dev Leader Weekly 30

Welcome to another issue of Dev Leader Weekly! In this issue, I dive into how we can use entity framework core in our Blazor application!

These AI Agents Ain't It - Dev Leader Weekly 94

Welcome to another issue of Dev Leader Weekly! In this issue, I discuss my experience using AI agents to refactor code.

An error has occurred. This application may no longer respond until reloaded. Reload x