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.
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
1session = agent.create_session()23await 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 ✅
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 sessionstate
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.
1class CustomerProfileProvider(ContextProvider):2 def __init__(self) -> None:3 super().__init__(source_id="customer_profile")45 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}")89 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]1314agent = Agent(client=client, instructions="...", context_providers=[CustomerProfileProvider()])
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
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.
1saved = session.to_dict() # {'type', 'session_id', 'service_session_id', 'state'}2db.save(user_id, saved)34restored = AgentSession.from_dict(db.load(user_id))5await agent.run("One-line summary of our chat?", session=restored)
Key takeaways
No session = no memory. Pass session=… on every turn.
ContextProvider.before_run injects; after_run learns.
Session state is a dict you control — and it serialises with to_dict().
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
- 1Playground: turn Session memory OFF. Tell it your budget, then ask “what's my budget?” — it forgets.
- 2Turn Session memory ON and repeat. Watch the message count grow in the Session State panel.
- 3Add a ‘customer profile’ to the Context Provider box and ask a question that needs it.
- 4Code Lab → Exercise 4: implement before_run in CustomerProfileProvider.
Reference solution — labs/ex4_sessions_memory.py (verified on agent-framework-core 1.26)
1"""Exercise 4 — Multi-turn sessions, context providers and memory (Module 4)."""23import asyncio4import json5from typing import Any67from agent_framework import Agent, AgentSession, ContextProvider, SessionContext, SupportsAgentRun8from common import make_client91011class CustomerProfileProvider(ContextProvider):12 """Injects long-lived facts before every run and learns new ones afterwards."""1314 def __init__(self) -> None:15 super().__init__(source_id="customer_profile")1617 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)}")2223 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 one27 for message in context.get_messages():28 text = message.text or ""29 if "budget" in text.lower():30 state["profile"]["budget_note"] = text[:120]313233async 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 )4041 # A session holds conversation state across turns42 session = agent.create_session()4344 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 memory48 ]49 for turn in turns:50 reply = await agent.run(turn, session=session)51 print(f"\nUSER: {turn}\nAGENT: {reply.text}")5253 # Sessions are serialisable -> store in Redis/Cosmos/DB and resume later54 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)596061if __name__ == "__main__":62 asyncio.run(main())
Check your understanding
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?