In the Microsoft Agent Framework .NET SDK, AIAgent is the foundational abstraction for creating AI-powered agents. Agents encapsulate an AI model, instructions, tools, and conversation management capabilities.
Use the AsAIAgent() extension method on any IChatClient to create an agent:
using Azure.AI.OpenAI;using Azure.Identity;using Microsoft.Agents.AI;using OpenAI.Chat;var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT");var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";// Create an agent using Azure OpenAIAIAgent agent = new AzureOpenAIClient( new Uri(endpoint), new DefaultAzureCredential()) .GetChatClient(deploymentName) .AsAIAgent( instructions: "You are a helpful assistant.", name: "Assistant");// Run the agentAgentResponse response = await agent.RunAsync("What is the capital of France?");Console.WriteLine(response.Text);
DefaultAzureCredential is convenient for development but requires careful consideration in production. Consider using a specific credential (e.g., ManagedIdentityCredential) to avoid latency issues and potential security risks.
using Microsoft.Extensions.AI;AIAgent agent = chatClient.AsAIAgent(new ChatClientAgentOptions(){ Name = "ResearchAssistant", Description = "An agent that helps with research tasks", ChatOptions = new ChatOptions() { Instructions = "You are an expert research assistant.", Temperature = 0.7f, MaxOutputTokens = 2000 }});
// Stream responses for real-time outputawait foreach (var update in agent.RunStreamingAsync("Write a short story about AI.")){ Console.Write(update.Text);}
Use AgentSession to maintain conversation context across multiple turns:
// Create a session for the conversationAgentSession session = await agent.CreateSessionAsync();// First turnvar response1 = await agent.RunAsync("Tell me a joke about pirates.", session);Console.WriteLine(response1.Text);// Second turn - agent remembers previous contextvar response2 = await agent.RunAsync( "Now tell it in the voice of a pirate's parrot.", session);Console.WriteLine(response2.Text);
AgentSession session = await agent.CreateSessionAsync();await foreach (var update in agent.RunStreamingAsync("Tell me a joke.", session)){ Console.Write(update.Text);}await foreach (var update in agent.RunStreamingAsync("Make it funnier.", session)){ Console.Write(update.Text);}
Request structured JSON output matching a specific schema:
using System.ComponentModel;using System.Text.Json.Serialization;[Description("Information about a city")]public class CityInfo{ [JsonPropertyName("name")] public string? Name { get; set; } [JsonPropertyName("population")] public int? Population { get; set; } [JsonPropertyName("country")] public string? Country { get; set; }}AIAgent agent = chatClient.AsAIAgent(new ChatClientAgentOptions(){ Name = "CityExpert", ChatOptions = new ChatOptions() { Instructions = "You provide information about cities.", ResponseFormat = ChatResponseFormat.ForJsonSchema<CityInfo>() }});AgentResponse response = await agent.RunAsync( "Tell me about Paris, France.");// Deserialize the structured outputCityInfo city = JsonSerializer.Deserialize<CityInfo>(response.Text);Console.WriteLine($"City: {city.Name}, Population: {city.Population}");
// Directly get typed resultAgentResponse<CityInfo> response = await agent.RunAsync<CityInfo>( "Tell me about Tokyo, Japan.");CityInfo city = response.Result;Console.WriteLine($"City: {city.Name}");
Agents can be converted to AIFunction instances and used as tools by other agents:
// Create a specialized agentAIAgent weatherAgent = weatherChatClient.AsAIAgent( name: "WeatherAgent", instructions: "You provide weather information for cities.");// Convert agent to a function toolAIFunction weatherTool = weatherAgent.AsAIFunction();// Use it as a tool in another agentAIAgent mainAgent = chatClient.AsAIAgent( instructions: "You are a travel assistant.", tools: [weatherTool]);var response = await mainAgent.RunAsync( "What's the weather like in Paris?");