← Back to Articles         
Multi-Turn Conversations with Agent Session

Multi-Turn Conversations with Agent Session

Published on 20 Nov 2026 6 min read Agentic AI (.NET)
Building .NET 10 AI Agent with Microsoft Foundry

Multi-Turn Conversations with Agent Session

The key concept in this lecture is how an AI agent remembers previous turns.

A normal LLM request is stateless. If each request is sent independently, the model does not automatically know what was discussed in previous requests.

For example:

User: Who invented the telephone?
Agent: Alexander Graham Bell.

User: When was he born?

The second request contains only "When was he born?". Without the previous conversation history, the model has no reliable way to know who "he" refers to.

The Problem: Stateless LLM

The basic architecture looks like this:

User Question
     │
     ▼
Azure OpenAI
     │
     ▼
Response
     │
     ▼
Request finished
     │
     X
Conversation forgotten

The LLM itself doesn't maintain application-level conversational state between independent requests.

Therefore, the application has to provide the previous conversation context when making the next request.

Conceptually:

Request 1:
User: Who invented the telephone?

Request 2:
User: When was he born?

        ↓

Application sends:

User: Who invented the telephone?
Agent: Alexander Graham Bell.
User: When was he born?

        ↓

Azure OpenAI

Doing this manually would require the application to maintain the conversation history and repeatedly send it with each request.

Agent Session

Microsoft Agent Framework provides AgentSession to manage this conversation state.

AgentSession session = await agent.CreateSessionAsync();

This creates a session associated with the agent.

Think of it as:

AgentSession
┌──────────────────────────────────────┐
│ Conversation History                 │
│                                      │
│ User: Who invented the telephone?   │
│ Agent: Alexander Graham Bell.       │
│                                      │
│ User: When was he born?             │
│ Agent: March 3, 1847.               │
└──────────────────────────────────────┘

The important point is that the session is separate from the agent itself.

AIAgent
   │
   ├── AgentSession → User A conversation
   │
   ├── AgentSession → User B conversation
   │
   └── AgentSession → User C conversation

This allows an application to maintain separate conversation contexts for different users or conversations.

Step 1: Create the Agent

The agent is created from IChatClient:

IChatClient chatClient = new AzureOpenAIClient(
        new Uri(endpoint),
        new AzureCliCredential())
    .GetChatClient(deploymentName)
    .AsIChatClient();

Then:

AIAgent agent = chatClient.AsAIAgent(
    name: "HistoryBuff",
    instructions: "You are a helpful history teacher. You answer questions and help students make connections between events."
);

Here:

  • IChatClient — Microsoft.Extensions.AI abstraction for interacting with the chat model.
  • AsIChatClient() — converts the Azure OpenAI chat client into IChatClient.
  • AsAIAgent() — creates an AIAgent using the chat client.
  • name — identifies the agent.
  • instructions — defines the agent's behavior/persona.

Step 2: Create the Session

This is the major addition for multi-turn conversation:

AgentSession session = await agent.CreateSessionAsync();

CreateSessionAsync() is an asynchronous method on AIAgent.

It creates a new AgentSession, initially containing no conversation history.

Conceptually:

AIAgent
   │
   │ CreateSessionAsync()
   ▼
AgentSession
   │
   └── Empty conversation history

Step 3: Keep the Application Running

A single request is not enough for a conversational application.

Therefore, the code uses:

while (true)

This keeps accepting user messages until the user enters exit.

while (true)
{
    Console.Write("User: ");
    string? input = Console.ReadLine();

    if (string.IsNullOrWhiteSpace(input) || input.ToLower() == "exit")
        break;

    ...
}

The important architectural difference is:

Single-turn:

Input → Agent → Response → Exit


Multi-turn:

Input
  ↓
Agent
  ↓
Response
  ↓
Input
  ↓
Agent
  ↓
Response
  ↓
Input
  ↓
Agent
  ↓
...

Step 4: Pass the Session to RunAsync

This is the most important line in the entire example:

AgentResponse response = await agent.RunAsync(input, session);

Instead of simply doing:

await agent.RunAsync(input);

the code supplies the session:

agent.RunAsync(input, session)

The second argument tells the Agent Framework which conversation context should be used for this execution.

The conceptual flow becomes:

User Input
    │
    ▼
agent.RunAsync(input, session)
    │
    ▼
AgentSession
    │
    ├── Previous User messages
    ├── Previous Agent responses
    └── Current User message
            │
            ▼
       Azure OpenAI
            │
            ▼
      Agent Response
            │
            ▼
       AgentSession
       updated history

Example

Turn 1

User: Who invented the telephone?

The agent responds:

Alexander Graham Bell.

The session now contains:

User: Who invented the telephone?
Agent: Alexander Graham Bell.

Turn 2

User: When was he born?

The application does not need to manually add:

When was Alexander Graham Bell born?

The session provides the previous context.

Conceptually, the model receives:

User: Who invented the telephone?
Agent: Alexander Graham Bell.
User: When was he born?

Therefore:

"he"
 ↓
Alexander Graham Bell

and the agent can answer:

Alexander Graham Bell was born on March 3, 1847.

Session vs Agent

This distinction is important.

AIAgent defines the agent:

Who is the agent?
What instructions does it follow?
Which model does it use?

AgentSession represents a particular conversation:

What has this user and this agent discussed?

Think of it as:

              AIAgent
                 │
       ┌─────────┼─────────┐
       ▼         ▼         ▼
   Session A  Session B  Session C
       │         │         │
     User A    User B    User C

The same agent can therefore participate in many independent conversations.

Why This Is Important for Enterprise Applications

This pattern is fundamental for applications such as:

  • Customer-support assistants
  • AI tutors
  • Coding/debugging assistants
  • Report-generation agents
  • Scheduling assistants
  • Enterprise knowledge assistants
  • Multi-step business workflows

For example:

User
 │
 ├── Turn 1: "Analyze this sales report."
 │
 ├── Turn 2: "What was the weakest region?"
 │
 ├── Turn 3: "Why did it perform poorly?"
 │
 └── Turn 4: "Give me three recommendations."

The agent can progressively build on the conversation rather than treating each question as an unrelated request.

Important Point About Session Persistence

The AgentSession in this example is created in the application's memory:

AgentSession session = await agent.CreateSessionAsync();

So this example demonstrates multi-turn conversation within the lifetime of the application.

Do not automatically assume that this session survives application termination or is automatically stored in SQL Server/Cosmos DB. Persistent conversation storage requires an appropriate persistence mechanism and session serialization/restoration support.

Therefore:

Current application
       │
       ▼
AgentSession
       │
       ▼
Conversation history
       │
       ▼
Application continues running

If the application is terminated, the in-memory state should not be assumed to remain available.

Complete Code

using Azure.Identity;
using Azure.AI.OpenAI;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

// 1. Define the variables extracted from Microsoft Foundry
var endpoint =
    Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
    ?? throw new InvalidOperationException(
        "AZURE_OPENAI_ENDPOINT is not set.");

var deploymentName =
    Environment.GetEnvironmentVariable(
        "AZURE_OPENAI_DEPLOYMENT_NAME")
    ?? "gpt-5-mini";

// Create the IChatClient
IChatClient chatClient = new AzureOpenAIClient(
        new Uri(endpoint),
        new AzureCliCredential())
    .GetChatClient(deploymentName)
    .AsIChatClient();

// 2. Create the Agent
AIAgent agent = chatClient.AsAIAgent(
    name: "HistoryBuff",
    instructions:
        "You are a helpful history teacher. " +
        "You answer questions and help students make connections between events."
);

// 3. Create the Agent Session
// The session maintains the conversation history.
AgentSession session = await agent.CreateSessionAsync();

Console.WriteLine(
    "History Teacher is online. Type 'exit' to quit.\n");

// 4. Conversation Loop
while (true)
{
    Console.Write("User: ");

    string? input = Console.ReadLine();

    // Exit when the user enters an empty input or "exit"
    if (string.IsNullOrWhiteSpace(input) ||
        input.Equals("exit", StringComparison.OrdinalIgnoreCase))
    {
        break;
    }

    // Pass the AgentSession to RunAsync.
    // The framework uses the session to maintain
    // the conversation context between turns.
    AgentResponse response =
        await agent.RunAsync(input, session);

    Console.WriteLine($"Agent: {response.Text}\n");
}

Key Takeaway

The fundamental change from single-turn to multi-turn is the introduction of an AgentSession:

AgentSession session = await agent.CreateSessionAsync();

and passing that session into every execution:

await agent.RunAsync(input, session);

So the architecture changes from:

User → Agent → Response

to:

User
  ↓
Agent
  ↓
AgentSession
  ↓
Response
  ↓
User
  ↓
Agent + Same Session
  ↓
Response

AIAgent provides the intelligence and behavior; AgentSession provides the conversation context across turns.

← Back to Articles