Skip to main content

How to Run Code Before Every Turn in the Microsoft 365 Agents SDK in C#

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

Some checks belong in front of every route: is this person allowed, is the agent switched on, is this the right kind of conversation? Instead of repeating them in each handler, the Microsoft 365 Agents SDK lets you register a before-turn handler that runs before the routes on every turn, and stops the turn when it returns false.

Syntax​

C#
OnBeforeTurn(handler);

private async Task<bool> HandlerName(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
  • OnBeforeTurn is a method of AgentApplication. Call it in your agent's constructor. You can register several handlers, and they run in the order you register them.
  • handler is the method that runs. It gets the same three parameters as a route handler, and returns Task<bool>.
  • Return true to carry on with the turn: the next before-turn handler runs, then the routes.
  • Return false to stop the turn: no route runs, and neither do the after-turn handlers. The SDK still saves the turn's state.

Before-turn handlers run for every activity your agent receives, messages or not, after the SDK loads the turn's state and before it tries the routes.

The Example​

The agent for this post tells people how much leave they have left. That's private, so it should only answer in a one-to-one chat, never in a group chat where everyone can read the answer:

LeaveAgent.cs
using Microsoft.Agents.Builder;
using Microsoft.Agents.Builder.App;
using Microsoft.Agents.Builder.State;
using Microsoft.Agents.Core.Models;

namespace BeforeTurnDemo;

public class LeaveAgent : AgentApplication
{
public LeaveAgent(AgentApplicationOptions options) : base(options)
{
OnBeforeTurn(OnlyInPersonalChatAsync);
OnActivity(ActivityTypes.Message, LeaveBalanceAsync);
}

private async Task<bool> OnlyInPersonalChatAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
if (turnContext.Activity.Conversation.ConversationType == ConversationTypes.Personal)
{
return true;
}

if (turnContext.Activity.Type == ActivityTypes.Message)
{
await turnContext.SendActivityAsync("Leave balances are private, so I only answer in a one-to-one chat with you.", cancellationToken: cancellationToken);
}

return false;
}

private async Task LeaveBalanceAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
await turnContext.SendActivityAsync("You have **12 days** of leave left this year.", cancellationToken: cancellationToken);
}
}

LeaveAgent.cs in a macOS-style editor window: an AgentApplication whose constructor registers OnBeforeTurn with OnlyInPersonalChatAsync and a message route; the before-turn handler returns true for personal conversations, otherwise answers messages with a refusal and returns false

It's one class in an ASP.NET Core project with the Agents SDK, hosted with AddAgent<LeaveAgent>() and listening on port 3978. The leave balance is a fixed sentence, so the check is the only thing to look at.

Prerequisites​

  • The Microsoft 365 Agents Playground, to chat with the agent on your own machine. agentsplayground --version should print 0.2.30; if the command isn't found, install it with npm install -g @microsoft/m365agentsplayground.

Step 1: Register the Before-Turn Handler​

Register it in the constructor, next to the routes:

LeaveAgent.cs (the constructor)
public LeaveAgent(AgentApplicationOptions options) : base(options)
{
OnBeforeTurn(OnlyInPersonalChatAsync);
OnActivity(ActivityTypes.Message, LeaveBalanceAsync);
}

The order of these two lines doesn't matter: before-turn handlers always run before the routes, whatever order you register them in.

Step 2: Check the Conversation and Stop the Turn​

The handler looks at the conversation the activity came from:

LeaveAgent.cs (the before-turn handler)
private async Task<bool> OnlyInPersonalChatAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
if (turnContext.Activity.Conversation.ConversationType == ConversationTypes.Personal)
{
return true;
}

if (turnContext.Activity.Type == ActivityTypes.Message)
{
await turnContext.SendActivityAsync("Leave balances are private, so I only answer in a one-to-one chat with you.", cancellationToken: cancellationToken);
}

return false;
}
  • Conversation.ConversationType is personal for a one-to-one chat, groupChat for a group chat and channel for a channel in a team. The SDK has constants for them in ConversationTypes, in the Microsoft.Agents.Core.Models namespace.
  • A one-to-one chat returns true, so the turn carries on to the message route.
  • Anything else returns false. Only messages get the refusal, because a member joining a group chat isn't waiting for an answer, but every turn there stops.

Step 3: Try It in a One-to-One Chat​

Run the agent with dotnet run, start the Agents Playground in a second terminal, and ask about your leave in Personal Chat, where the Playground opens:

Terminal 2
agentsplayground -e http://localhost:3978/api/messages -c emulator

The Agents Playground chat: How much leave do I have left? gets You have 12 days of leave left this year. from Test Bot, with 12 days in bold

The before-turn handler returned true, and the message route answered.

Step 4: Try It in a Group Chat​

Select Group Chat in the Playground's list of chats. In a group chat, the agent only receives messages that @mention it, as in Microsoft Teams, so type @, choose Test Bot from the list that appears, and ask the same question:

The Playground's group chat: Test Bot How much leave do I have left?, with Test Bot as a mention, gets Leave balances are private, so I only answer in a one-to-one chat with you.

This time the activity's conversationType was groupChat, so the handler answered with the refusal and returned false, and the message route never ran. The leave balance stayed private.

Common Mistakes​

MistakeWhat happensDo this instead
Forgetting return true on the normal pathEvery turn stops, and the agent never answersReturn true unless you mean to stop the turn
Replying to every activity you stopPeople get messages they didn't ask for, such as when someone joins a group chatReply only to messages
Comparing with the string "personal"It works, but a typo fails silentlyUse ConversationTypes.Personal
Putting the check in every routeEasy to forget in the next route you addPut it in one before-turn handler

Troubleshooting​

SymptomLikely causeFix
The agent never answers, even in a one-to-one chatThe handler returns false on every pathCheck that it returns true for the turns that should go on
No answer and no refusal in a group chatThe message didn't @mention the agent, so it never arrivedMention the agent: type @ and choose it
The refusal also appears in one-to-one chatsThe conversation type isn't what you compare it withLog turnContext.Activity.Conversation.ConversationType and check its value

FAQ​

Why doesn't the agent get group chat messages without a mention?​

Microsoft Teams works that way: by default, agents in group chats and channels only receive messages that @mention them. An agent can ask for permission to receive all of them, through resource-specific consent in its app manifest. The Agents Playground behaves the same way, which is why Step 4 mentions the agent.

What happens to the state when a before-turn handler returns false?​

The SDK saves it, as at the end of a normal turn. That lets your agent remember why it stopped a turn, for example to count how many times someone tried.

What else is a before-turn handler good for?​

Anything that should happen before every route: writing each activity to your log, switching the agent off with a setting while you fix something, or checking that a person may use the agent before any route answers.

Do before-turn handlers run for activities that no route handles?​

Yes. They run for every activity the agent receives, such as the conversationUpdate the Playground sends when it connects, before the SDK looks for a route.

Conclusion​

Register a before-turn handler with OnBeforeTurn, and it runs before your routes on every turn. Return true to carry on, or false to stop the turn there, with no route and no after-turn handler. One handler that checks Conversation.ConversationType is enough to keep an agent's private answers out of group chats.

Additional Resources​