Skip to main content

Overview

This quickstart will guide you through creating your first AI agent using the Microsoft Agent Framework .NET SDK. You’ll learn the core concepts and patterns used throughout the framework.
Make sure you’ve completed the Installation guide before proceeding.

Core Concepts

Before diving into code, let’s understand the key components:

AIAgent

The main abstraction for interacting with AI models. Created from a chat client with instructions and optional tools.

ChatClient

The underlying client that communicates with AI providers (Azure OpenAI, OpenAI, etc.).

AgentSession

Manages conversation state and history for multi-turn interactions.

Tools

Functions that agents can call to perform actions or retrieve information.

Your First Agent

Let’s create a simple agent that can respond to questions:
1

Import required namespaces

using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using OpenAI.Chat;
2

Configure the connection

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-4o-mini";
3

Create the agent

AIAgent agent = new AzureOpenAIClient(
    new Uri(endpoint),
    new DefaultAzureCredential())
    .GetChatClient(deploymentName)
    .AsAIAgent(
        instructions: "You are a helpful assistant that provides clear, concise answers.",
        name: "Assistant");
4

Run the agent

string response = await agent.RunAsync("What is the Microsoft Agent Framework?");
Console.WriteLine(response);

Complete Example

Here’s the complete working example:
Program.cs
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using OpenAI.Chat;

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-4o-mini";

AIAgent agent = new AzureOpenAIClient(
    new Uri(endpoint),
    new DefaultAzureCredential())
    .GetChatClient(deploymentName)
    .AsAIAgent(
        instructions: "You are a helpful assistant that provides clear, concise answers.",
        name: "Assistant");

string response = await agent.RunAsync("What is the Microsoft Agent Framework?");
Console.WriteLine(response);

Streaming Responses

For real-time feedback, use streaming to receive responses as they’re generated:
await foreach (var update in agent.RunStreamingAsync("Tell me about AI agents."))
{
    Console.Write(update);
}
Console.WriteLine();
Streaming is ideal for user-facing applications where you want to show progress in real-time.

Multi-Turn Conversations

Use AgentSession to maintain conversation context across multiple interactions:
// Create a session to preserve conversation history
AgentSession session = await agent.CreateSessionAsync();

// First turn
Console.WriteLine(await agent.RunAsync("My name is Alice.", session));

// Second turn - the agent remembers the context
Console.WriteLine(await agent.RunAsync("What's my name?", session));

How It Works

  1. CreateSessionAsync() initializes a new conversation session
  2. Pass the session object to subsequent RunAsync() calls
  3. The session automatically maintains the conversation history
  4. The agent has full context from previous messages

Adding Tools (Functions)

Agents become more powerful when they can call functions:
1

Define a function with Description attributes

using System.ComponentModel;

[Description("Get the current weather for a location.")]
static string GetWeather(
    [Description("The city name")] string location)
{
    return $"The weather in {location} is sunny with a high of 22°C.";
}
2

Create an agent with tools

using Microsoft.Extensions.AI;

AIAgent agent = new AzureOpenAIClient(
    new Uri(endpoint),
    new DefaultAzureCredential())
    .GetChatClient(deploymentName)
    .AsAIAgent(
        instructions: "You are a helpful weather assistant.",
        tools: [AIFunctionFactory.Create(GetWeather)]);
3

Run the agent

Console.WriteLine(await agent.RunAsync("What's the weather in Seattle?"));
The agent will automatically call your GetWeather function and incorporate the result into its response.

Complete Tool Example

Program.cs
using System.ComponentModel;
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using OpenAI.Chat;

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-4o-mini";

[Description("Get the weather for a given location.")]
static string GetWeather([Description("The location to get the weather for.")] string location)
    => $"The weather in {location} is cloudy with a high of 15°C.";

AIAgent agent = new AzureOpenAIClient(
    new Uri(endpoint),
    new DefaultAzureCredential())
    .GetChatClient(deploymentName)
    .AsAIAgent(
        instructions: "You are a helpful assistant",
        tools: [AIFunctionFactory.Create(GetWeather)]);

Console.WriteLine(await agent.RunAsync("What is the weather like in Amsterdam?"));

Key Patterns

Async/Await

All agent interactions are asynchronous:
// Single response
string response = await agent.RunAsync("Hello");

// Streaming
await foreach (var chunk in agent.RunStreamingAsync("Hello"))
{
    Console.Write(chunk);
}

// Create session
AgentSession session = await agent.CreateSessionAsync();

Extension Methods

The SDK uses extension methods for clean API design:
// .AsAIAgent() converts IChatClient to AIAgent
AIAgent agent = chatClient.AsAIAgent(
    instructions: "You are helpful.",
    name: "MyAgent",
    tools: [...]);

Dependency Injection

The framework integrates with Microsoft.Extensions.DependencyInjection:
services.AddSingleton<AIAgent>(sp =>
{
    var chatClient = new AzureOpenAIClient(
        new Uri(endpoint),
        new DefaultAzureCredential())
        .GetChatClient(deploymentName);
    
    return chatClient.AsAIAgent(
        instructions: "You are helpful.",
        name: "MyAgent");
});

Common Patterns

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-4o-mini";
try
{
    var response = await agent.RunAsync("Hello");
    Console.WriteLine(response);
}
catch (InvalidOperationException ex)
{
    Console.WriteLine($"Configuration error: {ex.Message}");
}
catch (Exception ex)
{
    Console.WriteLine($"Error: {ex.Message}");
}
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));

var response = await agent.RunAsync(
    "Write a long story",
    cancellationToken: cts.Token);

Example Use Cases

Customer Support Bot

Build agents that answer customer questions and route to human agents when needed.

Data Analysis Assistant

Create agents that query databases and generate insights from data.

Code Assistant

Develop agents that help with coding tasks, explain code, and suggest improvements.

Workflow Automation

Orchestrate complex multi-step workflows with agent coordination.

Next Steps

Now that you understand the basics:

Create Your First Agent

Build a complete agent with advanced features

Working with Tools

Learn how to create and use agent tools

Agent Sessions

Master multi-turn conversations and context management

Browse Examples

Explore sample code and patterns

Best Practices

Security: Never hardcode API keys or secrets. Always use environment variables or Azure Key Vault.
Production Credentials: Use ManagedIdentityCredential instead of DefaultAzureCredential in production to avoid latency from credential probing.
Async All The Way: Always use async/await patterns. Never use .Result or .Wait() as it can cause deadlocks.
Dispose Sessions: If you create many sessions, consider disposing them when done to free resources.

Build docs developers (and LLMs) love