Microsoft Agent Framework for .NET
Overview
Microsoft Agent Framework is a framework for building, orchestrating, and deploying AI agents and multi-agent workflows. It provides graph-based workflows with streaming, checkpointing, human-in-the-loop, and time-travel capabilities.
Installation
bash1# Core AI package 2dotnet add package Microsoft.Agents.AI 3 4# OpenAI/Azure OpenAI support 5dotnet add package Microsoft.Agents.AI.OpenAI --prerelease 6 7# Google Gemini support (via Microsoft.Extensions.AI) 8dotnet add package Mscc.GenerativeAI.Microsoft 9 10# Azure identity for authentication 11dotnet add package Azure.Identity
Quick Start
Basic Agent with OpenAI
csharp1using Microsoft.Agents.AI; 2using OpenAI; 3 4var agent = new OpenAIClient("<api-key>") 5 .GetOpenAIResponseClient("gpt-4o-mini") 6 .CreateAIAgent( 7 name: "Assistant", 8 instructions: "You are a helpful assistant." 9 ); 10 11Console.WriteLine(await agent.RunAsync("Hello!"));
Azure OpenAI with Azure CLI Auth
csharp1using Azure.AI.OpenAI; 2using Azure.Identity; 3using Microsoft.Agents.AI; 4 5var agent = new AzureOpenAIClient( 6 new Uri("https://<resource>.openai.azure.com/"), 7 new AzureCliCredential()) 8 .GetChatClient("gpt-4o-mini") 9 .CreateAIAgent(instructions: "You are helpful."); 10 11Console.WriteLine(await agent.RunAsync("Tell me a joke."));
Azure OpenAI with Bearer Token
csharp1var agent = new OpenAIClient( 2 new BearerTokenPolicy( 3 new AzureCliCredential(), 4 "https://ai.azure.com/.default"), 5 new OpenAIClientOptions 6 { 7 Endpoint = new Uri("https://<resource>.openai.azure.com/openai/v1") 8 }) 9 .GetOpenAIResponseClient("gpt-4o-mini") 10 .CreateAIAgent(name: "Bot", instructions: "You are helpful.");
Google Gemini
csharp1using Mscc.GenerativeAI; 2using Mscc.GenerativeAI.Microsoft; 3using Microsoft.Agents.AI; 4 5var googleAI = new GoogleAI("<gemini-api-key>"); 6var geminiModel = googleAI.GenerativeModel("gemini-2.0-flash"); 7IChatClient chatClient = geminiModel.AsIChatClient(); 8 9var agent = chatClient.CreateAIAgent( 10 name: "Assistant", 11 instructions: "You are a helpful assistant." 12); 13 14Console.WriteLine(await agent.RunAsync("Hello!"));
Function Tools
Define tools using attributes:
csharp1public class WeatherTools 2{ 3 [Description("Gets current weather for a location")] 4 public static string GetWeather( 5 [Description("City name")] string city) 6 { 7 return $"Weather in {city}: Sunny, 72F"; 8 } 9} 10 11// Register tools with agent 12var agent = client.GetChatClient("gpt-4o-mini") 13 .CreateAIAgent( 14 instructions: "Help users check weather.", 15 tools: [typeof(WeatherTools)]); 16 17await agent.RunAsync("What's the weather in Seattle?");
Function Tools with Approval
For human-in-the-loop approval:
csharp1agent.OnToolCall += (sender, args) => 2{ 3 Console.WriteLine($"Tool: {args.ToolName}"); 4 Console.Write("Approve? (y/n): "); 5 args.Approved = Console.ReadLine()?.ToLower() == "y"; 6};
Structured Output
Return strongly-typed responses:
csharp1public class MovieRecommendation 2{ 3 public string Title { get; set; } 4 public string Genre { get; set; } 5 public int Year { get; set; } 6 public string Reason { get; set; } 7} 8 9var result = await agent.RunAsync<MovieRecommendation>( 10 "Recommend a sci-fi movie from the 2020s"); 11 12Console.WriteLine($"{result.Title} ({result.Year}) - {result.Reason}");
Multi-Turn Conversations
csharp1var agent = client.GetChatClient("gpt-4o-mini") 2 .CreateAIAgent(instructions: "You are a helpful assistant."); 3 4// First turn 5var response1 = await agent.RunAsync("My name is Alice."); 6 7// Continues context 8var response2 = await agent.RunAsync("What's my name?");
Persisted Conversations
Save and restore conversation state:
csharp1// Save state 2var state = agent.GetConversationState(); 3await File.WriteAllTextAsync("state.json", state.ToJson()); 4 5// Restore later 6var savedState = ConversationState.FromJson( 7 await File.ReadAllTextAsync("state.json")); 8agent.LoadConversationState(savedState);
Middleware
Add custom processing pipelines:
csharp1agent.UseMiddleware(async (context, next) => 2{ 3 Console.WriteLine($"Request: {context.Input}"); 4 var start = DateTime.UtcNow; 5 6 await next(); 7 8 var duration = DateTime.UtcNow - start; 9 Console.WriteLine($"Response time: {duration.TotalMilliseconds}ms"); 10});
Multi-Modal (Images)
csharp1var result = await agent.RunAsync( 2 "Describe this image", 3 images: [File.ReadAllBytes("photo.jpg")]);
Observability with OpenTelemetry
csharp1using var tracerProvider = Sdk.CreateTracerProviderBuilder() 2 .AddSource("Microsoft.Agents") 3 .AddConsoleExporter() 4 .Build(); 5 6// Agent calls are now traced 7await agent.RunAsync("Hello!");
Dependency Injection
csharp1services.AddSingleton<AIAgent>(sp => 2{ 3 var client = sp.GetRequiredService<OpenAIClient>(); 4 return client.GetChatClient("gpt-4o-mini") 5 .CreateAIAgent(instructions: "You are helpful."); 6});
Agent as MCP Tool
Expose agent as Model Context Protocol tool:
csharp1var mcpTool = agent.AsMcpTool( 2 name: "research_assistant", 3 description: "Researches topics and provides summaries");
Agent as Function Tool
Compose agents by exposing one as a tool for another:
csharp1var researchAgent = client.GetChatClient("gpt-4o") 2 .CreateAIAgent(instructions: "You do deep research."); 3 4var mainAgent = client.GetChatClient("gpt-4o-mini") 5 .CreateAIAgent( 6 instructions: "Answer questions, use research tool for complex topics.", 7 tools: [researchAgent.AsFunctionTool("research", "Deep research")]);
Workflows
For complex multi-agent orchestration, see references/workflows.md.
Key workflow patterns:
- Executors and Edges: Basic workflow building blocks
- Streaming: Real-time event streaming
- Fan-Out/Fan-In: Parallel processing
- Checkpointing: Save and resume workflow state
- Human-in-the-Loop: Pause for user input
- Writer-Critic: Iterative refinement loops
Best Practices
- Use Azure CLI credentials for local development
- Add OpenTelemetry for production observability
- Implement middleware for logging, error handling, rate limiting
- Use structured outputs when you need typed responses
- Persist conversation state for stateless services
- Use checkpointing in workflows for reliability
- Implement human-in-the-loop for sensitive operations