Skip to main content
Pre-built agent implementations and specialized components for common use cases.

AI Agents

Base class for agents using Microsoft.Extensions.AI for chat completion.
using Microsoft.AutoGen.Agents;
using Microsoft.AutoGen.Contracts;
using Microsoft.AutoGen.Core;
using Microsoft.Extensions.AI;

public class MyAIAgent : InferenceAgent<MyMessage>
{
    public MyAIAgent(
        AgentId id,
        IAgentRuntime runtime,
        string name,
        ILogger<InferenceAgent<MyMessage>>? logger,
        IChatClient client)
        : base(id, runtime, name, logger, client)
    {
    }

    public async Task<ChatResponse> GenerateResponseAsync(
        IList<ChatMessage> messages,
        ChatOptions? options = null)
    {
        return await ChatClient.GetResponseAsync(messages, options);
    }
}
T
type parameter
required
Message type (must implement IMessage)
id
AgentId
required
Agent identifier
runtime
IAgentRuntime
required
Runtime environment
name
string
required
Agent name
logger
ILogger?
Optional logger
client
IChatClient
required
Chat client from Microsoft.Extensions.AI

Properties

ChatClient
IChatClient
Gets the chat client for inference

Methods

CompleteAsync
Task<ChatResponse>
Generate a chat completion
var response = await CompleteAsync(
    chatMessages: messages,
    options: new ChatOptions
    {
        Temperature = 0.7f,
        MaxTokens = 1000
    }
);
chatMessages
IList<ChatMessage>
required
Conversation messages
options
ChatOptions?
Generation options
cancellationToken
CancellationToken
Cancellation token
CompleteStreamingAsync
IAsyncEnumerable<ChatResponseUpdate>
Stream chat completion chunks
await foreach (var update in CompleteStreamingAsync(messages))
{
    Console.Write(update.Content);
}

I/O Agents

Interface for process I/O operations.
using Microsoft.AutoGen.Agents;

public interface IProcessIO
{
    Task WriteAsync(string content);
    Task<string> ReadAsync();
}
WriteAsync
Task
Write content to output
content
string
required
Content to write
ReadAsync
Task<string>
Read input from user or process
Interface for console interaction agents.
using Microsoft.AutoGen.Agents;

public class ConsoleAgent : BaseAgent, IHandleConsole
{
    public async ValueTask HandleConsoleInputAsync(
        string input,
        MessageContext context)
    {
        // Process console input
        await WriteToConsoleAsync($"Received: {input}");
    }

    public async Task WriteToConsoleAsync(string message)
    {
        Console.WriteLine(message);
    }
}
Interface for file I/O operations.
using Microsoft.AutoGen.Agents;

public class FileAgent : BaseAgent, IHandleFileIO
{
    public async ValueTask<string> ReadFileAsync(
        string filePath,
        MessageContext context)
    {
        return await File.ReadAllTextAsync(filePath);
    }

    public async ValueTask WriteFileAsync(
        string filePath,
        string content,
        MessageContext context)
    {
        await File.WriteAllTextAsync(filePath, content);
    }
}
ReadFileAsync
ValueTask<string>
Read file contents
filePath
string
required
Path to file
WriteFileAsync
ValueTask
Write content to file
filePath
string
required
Path to file
content
string
required
Content to write

Agent Chat (Teams)

State management for agent teams.
using Microsoft.AutoGen.AgentChat;

public class TeamState
{
    public List<Message> History { get; set; } = new();
    public Dictionary<string, object> SharedContext { get; set; } = new();
    public string CurrentSpeaker { get; set; } = string.Empty;
}
History
List<Message>
Conversation history
SharedContext
Dictionary<string, object>
Shared context between agents
CurrentSpeaker
string
Current active agent

Termination Conditions

Terminate after maximum messages.
using Microsoft.AutoGen.AgentChat.Terminations;

var termination = new MaxMessageTermination(maxMessages: 20);
maxMessages
int
required
Maximum number of messages
Terminate on specific text pattern.
var termination = new TextMessageTermination("TERMINATE");
pattern
string
required
Text pattern to match
Terminate when text mentions specific content.
var termination = new TextMentionTermination("@done");
Terminate after time limit.
var termination = new TimeoutTermination(
    timeout: TimeSpan.FromMinutes(5)
);
timeout
TimeSpan
required
Maximum execution time
Terminate after token budget.
var termination = new TokenUsageTermination(maxTokens: 10000);
maxTokens
int
required
Maximum tokens to consume
Terminate on stop message.
var termination = new StopMessageTermination();
Terminate when message source matches.
var termination = new SourceMatchTermination("supervisor");
Terminate on agent handoff.
var termination = new HandoffTermination();
Terminate on specific function call.
var termination = new FunctionCallTermination("complete_task");
Terminate based on external signal.
var cts = new CancellationTokenSource();
var termination = new ExternalTermination(cts.Token);

// Trigger termination
cts.Cancel();

Agent Host

Application host for running agent systems.
using Microsoft.AutoGen.AgentHost;

public class Program
{
    public static async Task Main(string[] args)
    {
        var builder = Host.CreateApplicationBuilder(args);

        // Configure services
        builder.Services.AddSingleton<IAgentRuntime, InProcessRuntime>();
        builder.Services.AddTransient<WorkerAgent>();

        var host = builder.Build();
        await host.RunAsync();
    }
}

Example: Complete AI Agent

using Microsoft.AutoGen.Agents;
using Microsoft.AutoGen.Contracts;
using Microsoft.AutoGen.Core;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
using Google.Protobuf;

public class TaskMessage : IMessage
{
    public string Content { get; set; } = string.Empty;
    // IMessage implementation...
}

public class AssistantAgent : InferenceAgent<TaskMessage>
{
    public AssistantAgent(
        AgentId id,
        IAgentRuntime runtime,
        IChatClient chatClient,
        ILogger<InferenceAgent<TaskMessage>> logger)
        : base(id, runtime, "Assistant", logger, chatClient)
    {
    }

    public async ValueTask<object?> HandleAsync(
        TaskMessage message,
        MessageContext context)
    {
        var messages = new List<ChatMessage>
        {
            new ChatMessage(ChatRole.System, "You are a helpful assistant."),
            new ChatMessage(ChatRole.User, message.Content)
        };

        var response = await ChatClient.GetResponseAsync(
            messages,
            new ChatOptions
            {
                Temperature = 0.7f,
                MaxTokens = 1000
            });

        return new TaskMessage { Content = response.Content };
    }
}

// Usage
var runtime = new InProcessRuntime();

await runtime.RegisterAgentFactoryAsync(
    new AgentType("assistant"),
    async (id, rt) => new AssistantAgent(
        id,
        rt,
        chatClient,
        logger)
);

var response = await runtime.SendMessageAsync(
    new TaskMessage { Content = "Write a poem" },
    new AgentId("assistant", "default")
);

See Also

Build docs developers (and LLMs) love