Session
AgentSession is the conversation state container used across agent runs. It holds the state needed to continue a multi-turn conversation and can be serialised to any durable medium so that conversations survive application restarts.
What AgentSession Contains
| Property | Description |
|---|---|
StateBag | Arbitrary state container for this session. Used by the agent and providers to store per-session data. |
The C# AgentSession is an abstract base class. Concrete implementations (created via CreateSessionAsync()) may add additional state - for example, an id for remote chat history storage when service-managed history is used.
Built-in Usage Pattern
Create a session with CreateSessionAsync() and pass it to every RunAsync() call. The agent automatically loads and updates conversation history across turns using the session's state bag.
Because the same session object is passed on both calls, the second message includes the full conversation history, so the agent remembers the name from the first turn.
Creating a Session from an Existing Service Conversation ID
When a conversation already exists on a remote service, you can attach a session to it by passing the existing conversation ID to CreateSessionAsync(). The exact overload depends on the agent type.
Using ChatClientAgent
Using an A2AAgent
After attaching, all subsequent RunAsync() calls continue the existing conversation on the service side rather than starting a new one.
Serialization and Restoration
An AgentSession can be serialised to a JsonElement so it survives application restarts. Store the JSON in a file, database, or blob storage and deserialise it later to resume the conversation exactly where it left off.
Important: Sessions are agent/service-specific. Reusing a session with a different agent configuration or provider can lead to invalid context.
Summary
| Concept | API | Description |
|---|---|---|
| Create session | agent.CreateSessionAsync() | Creates a new, empty conversation session |
| Attach to existing conversation | agent.CreateSessionAsync(conversationId) | Attaches to an existing service-side conversation by ID |
| Run a turn | agent.RunAsync(message, session) | Sends a message and updates the session with the full exchange |
| Serialise session | agent.SerializeSessionAsync(session) | Returns a JsonElement snapshot of the full session state |
| Restore session | agent.DeserializeSessionAsync(element) | Restores an AgentSession from a snapshot |
Required Packages
| Package | Purpose |
|---|---|
Microsoft.Agents.AI | AIAgent, AgentSession, serialization |
Microsoft.Extensions.AI.OpenAI | AsIChatClient() and OpenAI integration |