microsoft-agent-framework
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
# Core AI package
dotnet add package Microsoft.Agents.AI
# OpenAI/Azure OpenAI support
dotnet add package Microsoft.Agents.AI.OpenAI --prerelease
# Google Gemini support (via Microsoft.Extensions.AI)
dotnet add package Mscc.GenerativeAI.Microsoft
# Azure identity for authentication
dotnet add package Azure.Identity
Quick Start
Basic Agent with OpenAI
using Microsoft.Agents.AI;
using OpenAI;
var agent = new OpenAIClient("<api-key>")
.GetOpenAIResponseClient("gpt-4o-mini")
.CreateAIAgent(
name: "Assistant",
instructions: "You are a helpful assistant."
);
Console.WriteLine(await agent.RunAsync("Hello!"));
Azure OpenAI with Azure CLI Auth
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
var agent = new AzureOpenAIClient(
new Uri("https://<resource>.openai.azure.com/"),
new AzureCliCredential())
.GetChatClient("gpt-4o-mini")
.CreateAIAgent(instructions: "You are helpful.");
Console.WriteLine(await agent.RunAsync("Tell me a joke."));
Azure OpenAI with Bearer Token
var agent = new OpenAIClient(
new BearerTokenPolicy(
new AzureCliCredential(),
"https://ai.azure.com/.default"),
new OpenAIClientOptions
{
Endpoint = new Uri("https://<resource>.openai.azure.com/openai/v1")
})
.GetOpenAIResponseClient("gpt-4o-mini")
.CreateAIAgent(name: "Bot", instructions: "You are helpful.");
Google Gemini
using Mscc.GenerativeAI;
using Mscc.GenerativeAI.Microsoft;
using Microsoft.Agents.AI;
var googleAI = new GoogleAI("<gemini-api-key>");
var geminiModel = googleAI.GenerativeModel("gemini-2.0-flash");
IChatClient chatClient = geminiModel.AsIChatClient();
var agent = chatClient.CreateAIAgent(
name: "Assistant",
instructions: "You are a helpful assistant."
);
Console.WriteLine(await agent.RunAsync("Hello!"));
Function Tools
Define tools using attributes:
public class WeatherTools
{
[Description("Gets current weather for a location")]
public static string GetWeather(
[Description("City name")] string city)
{
return $"Weather in {city}: Sunny, 72F";
}
}
// Register tools with agent
var agent = client.GetChatClient("gpt-4o-mini")
.CreateAIAgent(
instructions: "Help users check weather.",
tools: [typeof(WeatherTools)]);
await agent.RunAsync("What's the weather in Seattle?");
Function Tools with Approval
For human-in-the-loop approval:
agent.OnToolCall += (sender, args) =>
{
Console.WriteLine($"Tool: {args.ToolName}");
Console.Write("Approve? (y/n): ");
args.Approved = Console.ReadLine()?.ToLower() == "y";
};
Structured Output
Return strongly-typed responses:
public class MovieRecommendation
{
public string Title { get; set; }
public string Genre { get; set; }
public int Year { get; set; }
public string Reason { get; set; }
}
var result = await agent.RunAsync<MovieRecommendation>(
"Recommend a sci-fi movie from the 2020s");
Console.WriteLine($"{result.Title} ({result.Year}) - {result.Reason}");
Multi-Turn Conversations
var agent = client.GetChatClient("gpt-4o-mini")
.CreateAIAgent(instructions: "You are a helpful assistant.");
// First turn
var response1 = await agent.RunAsync("My name is Alice.");
// Continues context
var response2 = await agent.RunAsync("What's my name?");
Persisted Conversations
Save and restore conversation state:
// Save state
var state = agent.GetConversationState();
await File.WriteAllTextAsync("state.json", state.ToJson());
// Restore later
var savedState = ConversationState.FromJson(
await File.ReadAllTextAsync("state.json"));
agent.LoadConversationState(savedState);
Middleware
Add custom processing pipelines:
agent.UseMiddleware(async (context, next) =>
{
Console.WriteLine($"Request: {context.Input}");
var start = DateTime.UtcNow;
await next();
var duration = DateTime.UtcNow - start;
Console.WriteLine($"Response time: {duration.TotalMilliseconds}ms");
});
Multi-Modal (Images)
var result = await agent.RunAsync(
"Describe this image",
images: [File.ReadAllBytes("photo.jpg")]);
Observability with OpenTelemetry
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddSource("Microsoft.Agents")
.AddConsoleExporter()
.Build();
// Agent calls are now traced
await agent.RunAsync("Hello!");
Dependency Injection
services.AddSingleton<AIAgent>(sp =>
{
var client = sp.GetRequiredService<OpenAIClient>();
return client.GetChatClient("gpt-4o-mini")
.CreateAIAgent(instructions: "You are helpful.");
});
Agent as MCP Tool
Expose agent as Model Context Protocol tool:
var mcpTool = agent.AsMcpTool(
name: "research_assistant",
description: "Researches topics and provides summaries");
Agent as Function Tool
Compose agents by exposing one as a tool for another:
var researchAgent = client.GetChatClient("gpt-4o")
.CreateAIAgent(instructions: "You do deep research.");
var mainAgent = client.GetChatClient("gpt-4o-mini")
.CreateAIAgent(
instructions: "Answer questions, use research tool for complex topics.",
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
Resources
More from salmanferozkhan/cloud-and-fast-api
chainlit
Expert guidance for building conversational AI applications with Chainlit framework in Python. Use when (1) creating chat interfaces for LLM applications, (2) building apps with OpenAI, LangChain, LlamaIndex, or Mistral AI, (3) implementing streaming responses, (4) adding UI elements like images, files, charts, (5) handling user file uploads, (6) implementing authentication (OAuth, password), (7) creating multi-step workflows with visible steps, (8) building RAG applications with document upload, or (9) deploying chat apps to web, Slack, Discord, or Teams.
87sqlmodel
Expert guidance for SQLModel - the Python library combining SQLAlchemy and Pydantic for database models. Use when (1) creating database models that work as both SQLAlchemy ORM and Pydantic schemas, (2) building FastAPI apps with database integration, (3) defining model relationships (one-to-many, many-to-many), (4) performing CRUD operations with type safety, (5) setting up async database sessions, (6) integrating with Alembic migrations, (7) handling model inheritance and mixins, or (8) converting between database models and API schemas.
17fastapi
Expert guidance for building REST APIs with FastAPI framework in Python. Use when (1) creating new FastAPI projects from scratch, (2) implementing API endpoints with routing, (3) working with Pydantic models for validation, (4) setting up dependency injection, (5) implementing authentication (OAuth2, JWT, API keys), (6) integrating databases (SQLAlchemy sync/async), (7) writing tests for FastAPI apps, (8) deploying FastAPI to production (Docker, Gunicorn), or (9) implementing advanced features like WebSockets, middleware, background tasks.
5docx
Comprehensive document creation, editing, and analysis with support for tracked changes, comments, formatting preservation, and text extraction. When Claude needs to work with professional documents (.docx files) for: (1) Creating new documents, (2) Modifying or editing content, (3) Working with tracked changes, (4) Adding comments, or any other document tasks
3xlsx
Comprehensive spreadsheet creation, editing, and analysis with support for formulas, formatting, data analysis, and visualization. When Claude needs to work with spreadsheets (.xlsx, .xlsm, .csv, .tsv, etc) for: (1) Creating new spreadsheets with formulas and formatting, (2) Reading or analyzing data, (3) Modify existing spreadsheets while preserving formulas, (4) Data analysis and visualization in spreadsheets, or (5) Recalculating formulas
3skill-validator
|
3