MAF AcademyLearnCapstoneSandbox
MAF Academy · Microsoft Agent Framework hands-on workshop · labs verified on agent-framework-core 1.26
← All modules
MODULE 4 OF 8 10 minutes

Agent Conversations, Context and Memory

LLMs are stateless. Sessions and context providers make agents remember.

1.Understanding multi-turn agent conversations
2.Managing conversation sessions
3.Maintaining contextual information across interactions
4.Introduction to agent memory and context providers
5.Managing session state
6.Understanding persistent context and memory management

On this page

Every model call starts from zeroInject knowledge before — learn afterThree kinds of memorySerialise, store, resumeKey takeawaysHands-on activityQuiz
1The problem

Every model call starts from zero

A model only knows what's in the current request. “Which plan fits us?” is meaningless unless the earlier turns are sent again. An AgentSession carries that history for you: each turn appends user + assistant messages, so context grows 2 → 4 → 6 → 8 messages.

Turn 1: “Budget is $40k.”2 msgs
Turn 2: “Which plan fits us?”4 msgs
Turn 3: “What budget did I mention?”6 msgs
Turn 4: “Summarise our chat (resumed)”8 msgs
user assistant

Per-run pipeline

AgentSession

session_id + state dict

before_run()

history + profile injected

Model call

sees the full context

after_run()

new messages & memories saved to state

Measured in the lab: messages sent to the model per turn when the same session is reused.
multi-turn with a session
1session = agent.create_session()
2
3await agent.run("We want AI Copilot for support. Budget is $40k.", session=session)
4await agent.run("Which plan fits us?", session=session)
5reply = await agent.run("What budget did I mention?", session=session) # remembers ✅
2Context providers

Inject knowledge before — learn after

A ContextProvider hooks into every run:

  • before_run → add instructions, messages or tools (profile, retrieved docs, policies)
  • after_run → inspect the exchange and store memories in session state

When you pass a session and no history provider, MAF auto-adds an InMemoryHistoryProvider. Swap in File, Redis, Mem0 or vector-store providers for durability and semantic recall.

ex4_sessions_memory.py
1class CustomerProfileProvider(ContextProvider):
2 def __init__(self) -> None:
3 super().__init__(source_id="customer_profile")
4
5 async def before_run(self, *, agent, session, context, state) -> None:
6 profile = state.setdefault("profile", {"company": "Contoso Retail", "tier": "Gold"})
7 context.extend_instructions(self.source_id, f"Known customer profile: {profile}")
8
9 async def after_run(self, *, agent, session, context, state) -> None:
10 for m in context.get_messages():
11 if "budget" in (m.text or "").lower():
12 state["profile"]["budget_note"] = m.text[:120]
13
14agent = Agent(client=client, instructions="...", context_providers=[CustomerProfileProvider()])
3Taxonomy

Three kinds of memory

Design memory deliberately — more context is not always better (cost, latency, distraction). Compaction strategies (sliding window, summarisation, token budgets) keep long sessions in check.

Short-term

Conversation history

AgentSession + InMemory / File / Redis history provider

Lifetime

This conversation

Long-term

Facts & knowledge

ContextProvider, Mem0, vector stores (VectorCollectionContextProvider)

Lifetime

Across sessions

Working state

Task variables

session state dict, workflow state & checkpoints

Lifetime

Until the task completes

4Persistence

Serialise, store, resume

Sessions are plain data. Persist them per user/conversation in Redis, Cosmos DB or SQL and resume hours later — the agent picks up where it left off.

persist & resume
1saved = session.to_dict() # {'type', 'session_id', 'service_session_id', 'state'}
2db.save(user_id, saved)
3
4restored = AgentSession.from_dict(db.load(user_id))
5await agent.run("One-line summary of our chat?", session=restored)

Key takeaways

01

No session = no memory. Pass session=… on every turn.

02

ContextProvider.before_run injects; after_run learns.

03

Session state is a dict you control — and it serialises with to_dict().

04

Short-term (history), long-term (facts/vectors) and working state are different tools.

Hands-on activity

Extend the agent to maintain context and answer follow-up questions

  1. 1Playground: turn Session memory OFF. Tell it your budget, then ask “what's my budget?” — it forgets.
  2. 2Turn Session memory ON and repeat. Watch the message count grow in the Session State panel.
  3. 3Add a ‘customer profile’ to the Context Provider box and ask a question that needs it.
  4. 4Code Lab → Exercise 4: implement before_run in CustomerProfileProvider.
Open Agent Playground Exercise 4 in Code Lab

Reference solution — labs/ex4_sessions_memory.py (verified on agent-framework-core 1.26)

ex4_sessions_memory.py
1"""Exercise 4 — Multi-turn sessions, context providers and memory (Module 4)."""
2
3import asyncio
4import json
5from typing import Any
6
7from agent_framework import Agent, AgentSession, ContextProvider, SessionContext, SupportsAgentRun
8from common import make_client
9
10
11class CustomerProfileProvider(ContextProvider):
12 """Injects long-lived facts before every run and learns new ones afterwards."""
13
14 def __init__(self) -> None:
15 super().__init__(source_id="customer_profile")
16
17 async def before_run(
18 self, *, agent: SupportsAgentRun, session: AgentSession, context: SessionContext, state: dict[str, Any]
19 ) -> None:
20 profile = state.setdefault("profile", {"company": "Contoso Retail", "tier": "Gold"})
21 context.extend_instructions(self.source_id, f"Known customer profile: {json.dumps(profile)}")
22
23 async def after_run(
24 self, *, agent: SupportsAgentRun, session: AgentSession, context: SessionContext, state: dict[str, Any]
25 ) -> None:
26 # Toy "memory extraction": remember the budget if the user mentions one
27 for message in context.get_messages():
28 text = message.text or ""
29 if "budget" in text.lower():
30 state["profile"]["budget_note"] = text[:120]
31
32
33async def main() -> None:
34 agent = Agent(
35 client=make_client(),
36 name="AccountManager",
37 instructions="You are a helpful account manager. Use the customer profile when relevant.",
38 context_providers=[CustomerProfileProvider()],
39 )
40
41 # A session holds conversation state across turns
42 session = agent.create_session()
43
44 turns = [
45 "Hi! We want to roll out AI Copilot to our support team. Our budget is $40k.",
46 "Which plan fits us?",
47 "Remind me — what budget did I mention, and what tier are we?", # follow-up needs memory
48 ]
49 for turn in turns:
50 reply = await agent.run(turn, session=session)
51 print(f"\nUSER: {turn}\nAGENT: {reply.text}")
52
53 # Sessions are serialisable -> store in Redis/Cosmos/DB and resume later
54 saved = session.to_dict()
55 print("\nSession keys:", list(saved.keys()))
56 restored = AgentSession.from_dict(saved)
57 reply = await agent.run("One-line summary of our chat?", session=restored)
58 print("\nRESUMED:", reply.text)
59
60
61if __name__ == "__main__":
62 asyncio.run(main())

Check your understanding

0/3

Q1.What makes a follow-up like “which plan fits us?” work?

Q2.Which hook should retrieve a customer's profile and add it to the prompt?

Q3.How do you resume a conversation after a server restart?

M3 · ToolsM5 · Multi-Agent