Skip to main content

How to Save User State in the Microsoft 365 Agents SDK in C#

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

Some things an agent should remember about a person, not a conversation: their name, their settings, their usual order. In the Microsoft 365 Agents SDK that's user state, and it follows the person into every conversation they have with your agent.

Syntax​

C#
turnState.User.SetValue(name, value);

T value = turnState.User.GetValue<T>(name, defaultValueFactory);
  • turnState is the ITurnState every handler receives.
  • User is the user scope: one set of values for each person, kept for whoever sent the activity.
  • name is the value's name in the scope, a string you choose.
  • value is what you store: a string, a number, a list or a class of your own, saved as JSON.
  • T is the type you read the value back as.
  • defaultValueFactory is optional: a function that returns the value to use when the person has none yet. Without it, a missing value comes back as null, or as 0 for a number.

The SDK loads the sender's user state before your handlers run and saves it when the turn ends.

The Example​

The agent for this post greets people, and remembers what they want to be called. call me Sam saves the name; any other message gets a greeting:

GreeterAgent.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 UserStateDemo;

public class GreeterAgent : AgentApplication
{
private static readonly Regex NamePattern = new(@"^call me\s+(.{1,30})$", RegexOptions.IgnoreCase);

public GreeterAgent(AgentApplicationOptions options) : base(options)
{
OnMessage(NamePattern, SaveNameAsync);
OnActivity(ActivityTypes.Message, GreetAsync, rank: RouteRank.Last);
}

private async Task SaveNameAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
string name = NamePattern.Match(turnContext.Activity.Text).Groups[1].Value.Trim();

turnState.User.SetValue("name", name);

await turnContext.SendActivityAsync($"Nice to meet you, {name}. I'll remember that.", cancellationToken: cancellationToken);
}

private async Task GreetAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
string? name = turnState.User.GetValue<string>("name");

string reply = name is null
? "Hello! What should I call you? Send **call me** and your name."
: $"Hello again, {name}!";

await turnContext.SendActivityAsync(reply, cancellationToken: cancellationToken);
}
}

GreeterAgent.cs in a macOS-style editor window: SaveNameAsync stores the name with turnState.User.SetValue, and GreetAsync reads it with turnState.User.GetValue, asking for a name when it is null and greeting the person by name when it isn't

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

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: Save the Value for the Person​

GreeterAgent.cs (SaveNameAsync)
turnState.User.SetValue("name", name);

turnState.User is the state of whoever sent this message. The SDK finds it with the channel and the sender's ID, so you never pass the person yourself.

Step 2: Read It Back​

GreeterAgent.cs (GreetAsync)
string? name = turnState.User.GetValue<string>("name");

There's no default here on purpose: for someone who hasn't said what to call them, GetValue<string> returns null, and the agent asks.

Step 3: Try It​

Run the agent with dotnet run, then start the Agents Playground in a second terminal:

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

Send hello, call me Sam, then hello again:

The Agents Playground chat: hello gets Hello! What should I call you? Send call me and your name., call me Sam gets Nice to meet you, Sam. I'll remember that., and the second hello gets Hello again, Sam!

Step 4: Try Another Conversation and Another Person​

Select Group Chat in the Playground's list on the left. There, the agent only receives messages that mention it: type @, choose Test Bot, and send hello.

Then send hello as a second person. The Playground sends what you type as its made-up user, Alex Wilber, but its custom activity can send a message as someone else, such as its built-in user Megan Bowen, whose ID is user-id-1. Select Mock an Activity, then Custom activity, and change the from lines and the last line of the activity:

The from lines and the last line, changed
"from": {
"id": "user-id-1",
"name": "Megan Bowen"
},
"type": "message",
"text": "hello"

Select Send activity. How to Send a Custom Activity from the Microsoft 365 Agents Playground walks through that dialog in full. The group chat shows:

The Agents Playground group chat: Test Bot hello gets Hello again, Sam!, and the custom activity from Megan Bowen gets Hello! What should I call you? Send call me and your name.

A custom activity doesn't appear in the chat as a message; only the agent's answer does. The two answers show both sides of user state:

  • Alex is still Sam in the group chat. User state follows a person into every conversation with the agent.
  • Megan gets asked for a name. User state belongs to one person, and Megan hasn't given one yet.

Common Mistakes​

MistakeWhat happensDo this instead
Keeping a person's setting in conversation stateEveryone in a group chat shares it, and it's missing in the person's other chatsUse turnState.User
Expecting user state to follow a person to another channelThe same person on another channel is a different userTreat each channel's user state as separate
Reading a number without a default and testing for nullA missing number comes back as 0, not nullCheck turnState.User.HasValue(name) first, or pass a default
Storing more than the agent needs about peoplePersonal data you have to protect and delete on requestKeep only what the agent uses

Troubleshooting​

SymptomLikely causeFix
The agent asks for the name again in another chatThe value was saved in conversation stateUse turnState.User
The name is gone after the agent restartsMemoryStorage keeps state only in the agent's memoryExpected; use durable storage in production
Someone else's name appearsThe value was saved in conversation state, or in a static fieldUser state is kept per sender; save the value there

FAQ​

How does the SDK know who the user is?​

From the activity: the channel's ID and the sender's ID, turnContext.Activity.From.Id. The user state is saved under a key made of both, such as emulator/users/user-id-0 in the Playground.

Does user state follow a person from Teams to a website?​

No. Microsoft's state documentation says it plainly: user state and conversation state are scoped by channel. The same person on two channels has two separate user states.

How do I delete a person's user state?​

Call await turnState.User.DeleteStateAsync(turnContext, cancellationToken) in a turn from that person. It removes their user state from storage. Anything about them in conversation state, such as their name in a shared list, stays where it is.

Conclusion​

User state is the person's own corner of an agent's memory: turnState.User.SetValue(name, value) to keep something about whoever sent the message, and turnState.User.GetValue<T>(name) to read it in any conversation they have with the agent, on the same channel. Everyone else gets their own.

Additional Resources​