Building an AI Agent in .NET: A Step-by-Step Guide with the Microsoft Agent Framework
Introduction
In the previous articles of this series, we covered the foundations: Microsoft Extensions for AI (MEAI) for unified model interaction, and Microsoft.Extensions.VectorData for semantic search and RAG. Now, we take the next leap—giving your AI the ability to act. This guide walks you through creating your first autonomous AI agent using the Microsoft Agent Framework (version 1.0+). An agent differs from a simple chatbot: it reasons, uses tools, remembers context, and can even collaborate with other agents. By the end, you’ll have a working agent that tells jokes, and you’ll understand how to extend it for real-world tasks.

What You Need
- .NET 9 SDK (or later) installed.
- An Azure OpenAI resource with a deployed model (e.g.,
gpt-5.4-mini). - The following environment variables set:
AZURE_OPENAI_ENDPOINT— your endpoint URL.AZURE_OPENAI_DEPLOYMENT_NAME— your deployment name (default:gpt-5.4-mini).
- NuGet packages to install (see Step 2).
- A console app project.
- Basic familiarity with C# and the MEAI
IChatClient(review Part 1 if needed).
Step-by-Step Instructions
Step 1: Create a .NET Console App
Open your terminal and run:
dotnet new console -n AgentExample
cd AgentExample
This scaffolds a new console project. We’ll keep it simple—no extra folders.
Step 2: Install the Microsoft Agent Framework NuGet Package
The framework builds on MEAI’s IChatClient. Add the agent library:
dotnet add package Microsoft.Agents.AI
This package includes everything needed for single‑agent scenarios. If you later need multi‑agent orchestration, add Microsoft.Agents.Orchestration as well.
Step 3: Set Up Azure OpenAI Credentials
You’ll connect to your Azure OpenAI resource. The easiest way is to read environment variables. Ensure AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_DEPLOYMENT_NAME are set. For local development, you can use a .env file or the system’s environment settings. Example for macOS/Linux:
export AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/
export AZURE_OPENAI_DEPLOYMENT_NAME=gpt-5.4-mini
On Windows (PowerShell):
$env:AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com/"
$env:AZURE_OPENAI_DEPLOYMENT_NAME="gpt-5.4-mini"
We’ll also use DefaultAzureCredential for authentication, which works with Visual Studio, Azure CLI, or managed identities.
Step 4: Write the Agent Code
Open Program.cs and replace its content with the following:
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME")
?? "gpt-5.4-mini";
AIAgent agent = new AzureOpenAIClient(
new Uri(endpoint),
new DefaultAzureCredential())
.GetChatClient(deploymentName)
.AsAIAgent(
instructions: "You are good at telling jokes.",
name: "Joker");
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate."));
Notice the .AsAIAgent() extension method—it transforms your MEAI ChatClient into an agent. The instructions parameter sets the agent’s personality, and name identifies it in logs or conversations.

Step 5: Run Your Agent
Execute the app:
dotnet run
You should see a joke output, like:
Why did the pirate go to school? To improve his arrrrrt!
Congratulations—you’ve built your first autonomous agent! It received a goal, used the model to generate a response, and returned it. In the background, the agent framework handled conversation history, tool invocation (none here), and decision-making.
Step 6: (Optional) Extend with Tools and Multi‑Agent Workflows
Agents shine when they can call external tools. For example, you can add a weather lookup tool:
// Define a tool
var getWeatherTool = AIFunctionFactory.Create(
() => new { Temperature = 72, Condition = "Sunny" },
"get_weather");
// Attach it to the agent
agent.WithTools(getWeatherTool);
Then ask: “What’s the weather like?” The agent will call the tool, evaluate the result, and answer. For multi‑agent scenarios (e.g., a supervisor agent delegating to specialist agents), use the AgentOrchestrator from Microsoft.Agents.Orchestration with a graph-based workflow.
Tips for Success
- Test instructions thoroughly: Small tweaks to the
instructionsstring can dramatically change agent behavior. Iterate until the agent follows your intent reliably. - Use environment variables for secrets: Never hardcode endpoints or keys. The pattern shown above is production‑ready.
- Monitor token usage: Agents with long conversations or many tool calls can consume tokens quickly. Log the number of calls or use Azure’s token consumption metrics.
- Start simple, then add complexity: A single agent with one tool is easier to debug than a multi‑agent mesh. Validate each piece before scaling.
- Leverage the MEAI stack: Because the Agent Framework builds on
IChatClientand integrates withVectorData, you can easily add knowledge retrieval (RAG) by attaching a vector store—just pass theIChatClientwith the vector plugin. - Handle errors gracefully: Wrap the
RunAsynccall in try/catch, and consider implementing retry logic for transient Azure failures. - Explore the official samples: The Microsoft Agent Framework repository on GitHub contains complete examples for single‑agent, tool‑based, and orchestrated workflows.
With these steps, you’ve graduated from basic chat to building an agent that can reason and act. The next frontier? Combine agents, vector databases, and MEAI to create truly intelligent applications. Happy coding!
Related Articles
- Why Your Site Search Drives Users to Google: The Site-Search Paradox Explained
- The Block Protocol: A Universal Standard for Web Content Blocks
- 8 Ways AI Coding Tools Are Overwhelming Code Review (And How to Fix It)
- Breakthrough 'Living Plastic' Disintegrates in Days, Scientists Announce
- How to Prevent Real-Time Teamwork Dashboards from Undermining Collaboration
- Boost Your Python Development with Terminal-Based AI: A Guide to Codex CLI
- Beyond Metrics: How Leaders Can Unlock Hidden Employee Potential by Nurturing Meaning and Belonging
- Top 10 Facts About the May MacBook Pro Deals: M5 Pro and M5 Max at Record Low Prices