Skip to main content

How to Use Temp State in the Microsoft 365 Agents SDK in C#

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

Sometimes a value only matters while one turn runs: something a before-turn handler works out once, for the route and the after-turn handler to use. In the Microsoft 365 Agents SDK that value goes in temp state, which every handler of the turn can reach and nothing ever saves.

Syntax​

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

T value = turnState.Temp.GetValue<T>(name, defaultValueFactory);
  • turnState is the ITurnState every handler receives: before-turn handlers, routes and after-turn handlers all get the same one during a turn.
  • Temp is the temp scope. It starts empty in every turn and is thrown away when the turn ends. It's never loaded from storage or saved to it.
  • name is the value's name, a string you choose.
  • value is any object: unlike the other scopes, temp state is never turned into JSON, so it can hold anything.
  • defaultValueFactory is optional: a function that returns the value to use when there isn't one yet.

The Example​

The agent for this post takes problem reports. A before-turn handler gives every turn a reference number; the route quotes it in its answer, and an after-turn handler writes it to the log, so a person's reference leads straight to the log lines of their turn:

ReportAgent.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 TempStateDemo;

public class ReportAgent : AgentApplication
{
private const string ReferenceKey = "reference";

private static readonly Regex ReportPattern = new(@"^report\s+(.{1,200})$", RegexOptions.IgnoreCase);

private readonly ILogger<ReportAgent> _logger;

public ReportAgent(AgentApplicationOptions options, ILogger<ReportAgent> logger) : base(options)
{
_logger = logger;

OnBeforeTurn(CreateReferenceAsync);
OnAfterTurn(LogReferenceAsync);

OnMessage(ReportPattern, ReportAsync);
OnActivity(ActivityTypes.Message, HelpAsync, rank: RouteRank.Last);
}

private Task<bool> CreateReferenceAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
string reference = "REF-" + Guid.NewGuid().ToString("N")[..8].ToUpperInvariant();

turnState.Temp.SetValue(ReferenceKey, reference);
return Task.FromResult(true);
}

private async Task ReportAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
string reference = turnState.Temp.GetValue<string>(ReferenceKey);

await turnContext.SendActivityAsync($"Thanks. Your report is logged as **{reference}**.", cancellationToken: cancellationToken);
}

private async Task HelpAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
await turnContext.SendActivityAsync("Send **report** and what went wrong, such as **report the printer is jammed**.", cancellationToken: cancellationToken);
}

private Task<bool> LogReferenceAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
string reference = turnState.Temp.GetValue<string>(ReferenceKey);

_logger.LogInformation("Turn {Reference} finished: {ActivityType}", reference, turnContext.Activity.Type);
return Task.FromResult(true);
}
}

ReportAgent.cs in a macOS-style editor window: the before-turn handler CreateReferenceAsync stores a reference such as REF- and eight characters with turnState.Temp.SetValue, ReportAsync puts it in the answer, and the after-turn handler LogReferenceAsync logs it, both reading it with turnState.Temp.GetValue

It's one class in an ASP.NET Core project with the Agents SDK, hosted with AddAgent<ReportAgent>() 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: Set the Value Before the Routes Run​

ReportAgent.cs (CreateReferenceAsync)
string reference = "REF-" + Guid.NewGuid().ToString("N")[..8].ToUpperInvariant();

turnState.Temp.SetValue(ReferenceKey, reference);
return Task.FromResult(true);

OnBeforeTurn runs this handler at the start of every turn, before any route. Guid.NewGuid().ToString("N") gives 32 random hexadecimal characters, and [..8] keeps the first eight, which is plenty to tell turns apart in a log. return Task.FromResult(true) lets the turn carry on.

Step 2: Read It in the Route and After the Turn​

ReportAsync and LogReferenceAsync both read it the same way:

ReportAgent.cs (ReportAsync and LogReferenceAsync)
string reference = turnState.Temp.GetValue<string>(ReferenceKey);

There's no default here: the before-turn handler always sets the value first. ReferenceKey is a constant, so all three handlers use the same name.

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 two reports, such as report the printer on floor 2 is jammed and report the meeting room screen is blank:

The Agents Playground chat: report the printer on floor 2 is jammed gets Thanks. Your report is logged as REF-EE0FBDBC., and report the meeting room screen is blank gets Thanks. Your report is logged as REF-F40DD6E5.

The agent's terminal logs the same references, one per turn:

Terminal (the agent's own log lines)
info: TempStateDemo.ReportAgent[0]
Turn REF-AF4548B0 finished: conversationUpdate
info: TempStateDemo.ReportAgent[0]
Turn REF-EE0FBDBC finished: message
info: TempStateDemo.ReportAgent[0]
Turn REF-F40DD6E5 finished: message

The first line is the conversationUpdate the Playground sends when it connects: every turn gets a reference, even one no route answers. Each value lived for exactly one turn, from the before-turn handler to the after-turn handler, and the next turn started with an empty temp state and made its own.

Common Mistakes​

MistakeWhat happensDo this instead
Expecting temp state in the next turnIt's empty at the start of every turnKeep values for later turns in conversation or user state
turnState.SetValue("count", 1) meant for conversation stateA name without a scope goes to temp state, so the value disappears after the turnUse turnState.Conversation, or the path "conversation.count"

Troubleshooting​

SymptomLikely causeFix
The route reads nullThe before-turn handler didn't run or didn't set the valueRegister it with OnBeforeTurn, and check the name
The after-turn handler doesn't logA before-turn handler returned false, or the turn threwThose turns skip the after-turn handlers
A value from the previous message is missingTemp state is per turnMove it to conversation or user state

FAQ​

What does the SDK keep in temp state?​

Files that people attach to a message, when the agent is set up with file downloaders: the SDK downloads the files before your before-turn handlers and routes run, and adds them to turnState.Temp.InputFiles. That's the same idea as this post: something prepared once at the start of the turn, for the handlers to use.

Is temp state saved anywhere?​

No. It's never loaded from storage and never saved to it, so it can hold objects that couldn't be turned into JSON, and nothing in it survives the turn.

Why not just use a field of the agent class?​

Within one turn a field works too, because the SDK creates a new agent instance for every activity. Temp state is the SDK's own place for per-turn values: any code you pass the turnState to can read them, and the SDK keeps its per-turn data there as well.

Conclusion​

Temp state is the turn's scratch pad: turnState.Temp.SetValue(name, value) in one handler, turnState.Temp.GetValue<T>(name) in the next, and nothing left over when the turn ends. Use it for values that a before-turn handler prepares for the rest of the turn, such as a reference number that ties a reply to its log lines.

Additional Resources​