Skip to main content

How to Let More Than One Route Handle a Message in the Microsoft 365 Agents SDK in C#

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

In the Microsoft 365 Agents SDK, one activity normally means one route: the first route that matches handles it, and the rest are never asked. Sometimes you want two, such as a warning and the normal answer. Mark the first route non-terminal, and the SDK keeps going.

Syntax​

C#
AddRoute(MessageRouteBuilder.Create()
.WithText(textOrPattern)
.WithHandler(handler)
.WithOrderRank(rank)
.AsNonTerminal()
.Build());
  • MessageRouteBuilder.Create() starts a route for message activities. The SDK has a builder for each kind of route, such as TypeRouteBuilder and EventRouteBuilder, and all of them have AsNonTerminal().
  • .WithText(textOrPattern) sets what the message must say: a string, for the whole text ignoring case, or a Regex. Use .WithSelector(...) instead to decide with your own function.
  • .WithHandler(handler) names the method that runs, with the signature Task Name(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken).
  • .WithOrderRank(rank) sets the route's rank. A non-terminal route only helps the routes tried after it, so it usually gets RouteRank.First.
  • .AsNonTerminal() is the key: after this route's handler runs, the SDK goes on trying the routes after it.
  • .Build() returns the route, and AddRoute, a method of AgentApplication, registers it. Do this in your agent's constructor.

The Example​

The agent for this post answers every message with a thank-you. When a message mentions a password, it warns first, then still answers:

SafetyAgent.cs
using System.Text.RegularExpressions;
using Microsoft.Agents.Builder;
using Microsoft.Agents.Builder.App;
using Microsoft.Agents.Builder.State;
using Microsoft.Agents.Core.Models;

namespace NonTerminalDemo;

public class SafetyAgent : AgentApplication
{
public SafetyAgent(AgentApplicationOptions options) : base(options)
{
// Any message with the word "password": tried first, and the routes after it still run.
AddRoute(MessageRouteBuilder.Create()
.WithText(new Regex(@"\bpassword\b", RegexOptions.IgnoreCase))
.WithHandler(WarnAsync)
.WithOrderRank(RouteRank.First)
.AsNonTerminal()
.Build());

OnActivity(ActivityTypes.Message, AnswerAsync, rank: RouteRank.Last);
}

private async Task WarnAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
await turnContext.SendActivityAsync("Never share a password in chat, not even with me.", cancellationToken: cancellationToken);
}

private async Task AnswerAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
await turnContext.SendActivityAsync("Thanks! I've passed your message to the help desk.", cancellationToken: cancellationToken);
}
}

SafetyAgent.cs in a macOS-style editor window: a constructor that adds a route built with MessageRouteBuilder, matching the word password with a case-insensitive Regex, handled by WarnAsync, ranked RouteRank.First and marked AsNonTerminal, then a catch-all OnActivity for messages with RouteRank.Last handled by AnswerAsync

It's one class in an ASP.NET Core project with the Agents SDK, hosted with AddAgent<SafetyAgent>() and listening on port 3978.

Prerequisites​

  • The Microsoft 365 Agents Playground, to send the agent messages 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: Build the Non-Terminal Route​

The On... shortcuts, such as OnMessage, can't mark a route non-terminal, so build the route yourself:

SafetyAgent.cs (the warning route)
// Any message with the word "password": tried first, and the routes after it still run.
AddRoute(MessageRouteBuilder.Create()
.WithText(new Regex(@"\bpassword\b", RegexOptions.IgnoreCase))
.WithHandler(WarnAsync)
.WithOrderRank(RouteRank.First)
.AsNonTerminal()
.Build());
  • \bpassword\b matches password as a whole word anywhere in the message, \b being a word boundary, and RegexOptions.IgnoreCase accepts Password too.
  • RouteRank.First makes it the first route tried, so the warning comes before any answer.
  • .AsNonTerminal() lets the routes after it run.

Step 2: Add the Route That Answers​

The normal answer is a catch-all for every message, tried last:

SafetyAgent.cs (the answer route)
OnActivity(ActivityTypes.Message, AnswerAsync, rank: RouteRank.Last);

For a message that mentions a password, the SDK runs the warning route, carries on because it's non-terminal, and reaches this route. For any other message, the warning route doesn't match, and this one answers alone.

Step 3: Try It​

Run the agent with dotnet run, start the Agents Playground in a second terminal, and send My printer is jammed, then I forgot my Password:

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

The Agents Playground chat: My printer is jammed gets Thanks! I've passed your message to the help desk.; I forgot my Password gets two replies, Never share a password in chat, not even with me., then Thanks! I've passed your message to the help desk.

The printer message got one answer. The password message got two, in rank order: the warning, then the answer.

Step 4: See What Happens Without AsNonTerminal​

Remove the .AsNonTerminal() line, restart the agent, and send I forgot my Password again:

The Playground chat: I forgot my Password now gets only one reply, Never share a password in chat, not even with me.

Only the warning comes back. The warning route matched first and, being an ordinary route, ended routing for the message, so the answer route was never asked. Put the line back to get both answers again.

Common Mistakes​

MistakeWhat happensDo this instead
Forgetting .AsNonTerminal()The non-terminal route's answer is the only oneCall .AsNonTerminal() on the builder
Giving the non-terminal route a later rank than the route that answersThe answering route runs first and ends routing, so the non-terminal route never runsRank it before the routes it should precede, usually RouteRank.First
Marking the answering route non-terminal tooThe SDK keeps trying the routes after it as wellMark only the routes that should let others run
Looking for AsNonTerminal on OnMessageThe shortcuts have no such optionBuild the route with a route builder

Troubleshooting​

SymptomLikely causeFix
Only the warning appearsThe route isn't non-terminalAdd .AsNonTerminal()
Only the answer appearsThe warning route didn't match, or it's ranked after the answerCheck its pattern, and give it RouteRank.First
The answers come in the wrong orderThe ranks put them in that orderLower ranks run first; adjust them

FAQ​

Does the route after a non-terminal route have to match?​

Yes. The SDK goes on asking the remaining routes in order, and the next one whose selector says yes runs. If none does, the non-terminal route's handler was the only one.

Can more than one route be non-terminal?​

Yes. Each non-terminal route lets the search continue after it, so several can run for one activity, followed by one ordinary route that ends it.

How is this different from running code before every turn?​

A non-terminal route runs only when its selector matches, and it runs in its place in the route order. Code that should run for every activity, whatever it is, belongs in a before-turn handler: How to Run Code Before Every Turn in the Microsoft 365 Agents SDK in C# shows one.

Conclusion​

To let more than one route handle a message, build the earlier route with a route builder, give it a rank that puts it first, and call .AsNonTerminal(). Its handler runs, and the SDK goes on to the next matching route, which answers as usual.

Additional Resources​