Skip to main content

How to Save and Restore a Microsoft Agent Framework Session in C#

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

An AgentSession lives in memory, so a conversation ends when the app does. To pick it up later, save the session as JSON with SerializeSessionAsync, and turn the JSON back into a session with DeserializeSessionAsync when the app starts again.

Syntax​

Syntax
// Save
JsonElement <state> = await <agent>.SerializeSessionAsync(<session>);
await File.WriteAllTextAsync("<file>", <state>.GetRawText());

// Restore
JsonElement <saved> = JsonSerializer.Deserialize<JsonElement>(await File.ReadAllTextAsync("<file>"));
AgentSession <session> = await <agent>.DeserializeSessionAsync(<saved>);
PartWhat it is
SerializeSessionAsync(<session>)Returns the session as a JsonElement. Microsoft's reference: it enables saving conversation sessions to persistent storage, allowing conversations to resume across application restarts
GetRawText()The JSON as text, ready to write to a file or a database
JsonSerializer.Deserialize<JsonElement>(…)Reads the saved text back into a JsonElement
DeserializeSessionAsync(<saved>)Returns a session of this agent with the saved state
<agent>The same agent, with the same settings, that created the session

The Example​

A small agent helps people learn languages. The first time the app starts, you tell it which Spanish word you learned today, and the app saves the conversation to conversation.json. The next time it starts, it restores the conversation and asks which word that was.

Prerequisites​

  • A model deployment in a Microsoft Foundry project, and the Foundry User role on the Foundry resource for your account. The app calls the model as you.
  • The .NET 10 SDK (dotnet --version prints a version that starts with 10.0) and the Azure CLI, signed in with az login.

Step 1: Create a Console App​

Terminal
dotnet new console -n StudyBuddy
cd StudyBuddy
dotnet add package Microsoft.Agents.AI.Foundry --version 1.28.0-preview.261106.1
dotnet add package Azure.Identity --version 1.21.0

Microsoft.Agents.AI.Foundry turns a model in a Foundry project into an agent, and brings in Agent Framework. Azure.Identity signs the app in with your Azure CLI sign-in. Open the folder in VS Code, or StudyBuddy.csproj in Visual Studio.

Step 2: Restore or Start, Then Save​

Replace everything in Program.cs:

Program.cs
using System.Text.Json;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;

AIAgent agent = new AIProjectClient(
new Uri("https://foundry-devblogs-exp.services.ai.azure.com/api/projects/proj-devblogs-exp"),
new AzureCliCredential())
.AsAIAgent(
model: "gpt-5.6-luna",
instructions: "You help people learn languages. Answer in one sentence.",
name: "StudyBuddy");

const string SavedConversation = "conversation.json";
AgentSession session;
string message;

if (File.Exists(SavedConversation))
{
// Restore: read the saved JSON, and turn it back into a session of this agent.
JsonElement saved = JsonSerializer.Deserialize<JsonElement>(await File.ReadAllTextAsync(SavedConversation));
session = await agent.DeserializeSessionAsync(saved);
message = "Which Spanish word did I learn today?";
}
else
{
session = await agent.CreateSessionAsync();
message = "I'm learning Spanish. Today I learned the word 'gato'.";
}

AgentResponse response = await agent.RunAsync(message, session);
Console.WriteLine($"> {message}");
Console.WriteLine(response.Text);

// Save: turn the session into JSON, and write it to a file.
JsonElement state = await agent.SerializeSessionAsync(session);
await File.WriteAllTextAsync(SavedConversation, state.GetRawText());
Console.WriteLine($"(saved to {SavedConversation})");
  • File.Exists decides which run this is. With a saved conversation, the app restores it and asks about the earlier message; without one, it creates a new session.
  • DeserializeSessionAsync(saved) gives back a session of this agent, with the state from the file.
  • SerializeSessionAsync(session) at the end saves the session as it is after this run, so the next start continues from here.

Use your own Foundry project endpoint and model deployment.

Step 3: Run It Twice​

Run dotnet run twice in VS Code's terminal, or press Ctrl+F5 twice in Visual Studio:

Output
$ dotnet run
> I'm learning Spanish. Today I learned the word 'gato'.
“Gato” means “cat” in English.
(saved to conversation.json)

$ dotnet run
> Which Spanish word did I learn today?
You learned the Spanish word “gato.”
(saved to conversation.json)

macOS-style terminal window titled Terminal — StudyBuddy showing two runs. In the first, I'm learning Spanish. Today I learned the word 'gato'. gets the answer Gato means cat in English, and the conversation is saved to conversation.json. In the second, Which Spanish word did I learn today? gets the answer You learned the Spanish word gato.

The second start is a new process, and it still knew the word: it restored the conversation from the file. conversation.json is small. With an agent on Microsoft Foundry, it holds the ID of the conversation's newest response, and Foundry keeps the messages:

conversation.json (the ID shortened)
{"conversationId":"resp_…","stateBag":{"InMemoryChatHistoryProvider":{"messages":[]}}}

The Complete File​

macOS-style code window titled Program.cs showing the StudyBuddy app: if conversation.json exists, it restores the session with DeserializeSessionAsync and asks which Spanish word was learned; otherwise it creates a session with CreateSessionAsync and tells the agent about the word gato. After the run, it saves the session with SerializeSessionAsync to conversation.json

Program.cs from Step 2 is the whole program.

Common Mistakes​

MistakeWhat happensDo this instead
Saving the session before the runThe file holds the state from before the runSave after RunAsync
Restoring with a different agentMicrosoft's documentation: Reusing a session with a different agent configuration or provider can lead to invalid contextRestore with the agent that created the session
Treating the file as harmlessThe reference warns that saved sessions may contain conversation content, session identifiers, and other potentially sensitive data including PIIStore it like other private data

FAQ​

Where should a real app keep the saved sessions?​

Where it keeps other private data for that user, such as a database, and only restore a session for the person it belongs to. The reference: Treat restoring a session from an untrusted source as equivalent to accepting untrusted input.

How do I start a new conversation?​

Delete the saved JSON, or don't restore it: CreateSessionAsync starts an empty session.

Conclusion​

To keep a conversation across restarts, save the session after each run with SerializeSessionAsync and GetRawText, and restore it at the next start with JsonSerializer.Deserialize<JsonElement> and DeserializeSessionAsync, using the same agent. With Microsoft Foundry, the saved JSON only holds the conversation's ID; the conversation itself stays in Foundry.

Additional Resources​