Share via


Building Agents

Learn more about how and what happens when you build an agent with the Microsoft 365 Agents SDK.

In the Agents SDK, an agent is built using AgentApplication and AgentApplicationOptions

AgentApplicationOptions allows for different configuration options including authentication. It's a parameter in the constructor of AgentApplication

builder.AddAgentApplicationOptions();

builder.AddAgent(sp =>
{
    // Setup the Agent. 
    var agent = new AgentApplication(sp.GetRequiredService<AgentApplicationOptions>());

    // Respond to message events. 
    agent.OnActivity(ActivityTypes.Message, async (turnContext, turnState, cancellationToken) =>
    {
        var text = turnContext.Activity.Text;
        await turnContext.SendActivityAsync(MessageFactory.Text($"Echo: {text}"), cancellationToken);
    });
    return agent;
});

The endpoint of your application needs to be configured to handle incoming requests and is designed to specifically process messages to your agent, using an adapter IAgentHttpAdapter and IAgent. This configuration converts the HTTP request and response into understandable formats between the web server and the agent.

app.MapPost("/api/messages", async (HttpRequest request, HttpResponse response, IAgentHttpAdapter adapter, IAgent agent, CancellationToken cancellationToken) =>
{
    await adapter.ProcessAsync(request, response, agent, cancellationToken);
});

Now that the agent is created, you can register to listen for events, add your AI services and custom logic.

In the starter samples on the Agents SDK GitHub repo, you will see that the agent is registered automatically for the generic OnActivity event.

    agent.OnActivity(ActivityTypes.Message, async (turnContext, turnState, cancellationToken) =>
    {
        var text = turnContext.Activity.Text;
        await turnContext.SendActivityAsync(MessageFactory.Text($"Echo: {text}"), cancellationToken);
    });