Lesson 15 of 39 · Sessions, Memory and Context
Context Providers and Long-Term Memory
Write Agent Framework context providers that add instructions, messages and tools to each run, and give agents long-term memory with Mem0, Redis or Foundry.
- 12 min read
- Intermediate
- Reviewed
- Explain what a context provider is and when its before_run and after_run steps run
- Write a provider that adds instructions, messages and tools to a run
- Keep facts for one session in provider state, and long-term facts outside the session
- Use the built-in memory providers for Mem0, Redis, Foundry and Content Understanding
- Avoid the deprecated memory classes and the most common provider bugs
What the model gets to see
A model knows only what's in its request. Deciding what goes in, such as instructions, earlier messages, facts about the user or the right tools, is called context engineering. In Agent Framework, much of it is done by small plugins called context providers.
You've already met two: the history provider that loads and saves the conversation, and CompactionProvider. You attach providers with context_providers=[...], and every run passes through them.
The order they run in
Providers wrap the model call like the layers of an onion. Their before_run steps run in list order, and their after_run steps run in reverse:
# Context providers run like layers of an onion around the model call.
class Provider:
def __init__(self, name):
self.name = name
def before_run(self):
print(f"{self.name}: before_run")
def after_run(self):
print(f"{self.name}: after_run")
providers = [Provider("history"), Provider("customer memory"), Provider("compaction")]
for provider in providers: # in list order
provider.before_run()
print(" ... model call (and any tool calls) ...")
for provider in reversed(providers): # in reverse order
provider.after_run()That's why the history provider usually comes first: it loads the conversation before anything else needs it, and it saves the turn last, after the others have finished.
Your first provider
Subclass ContextProvider and override before_run, after_run, or both. This one remembers the customer's name and bike for the rest of the session:
import asyncio
import re
from agent_framework import Agent, ContextProvider, SessionContext
from agent_framework.openai import OpenAIChatClient
class CustomerProfile(ContextProvider):
"""Remembers the customer's name and bike for the rest of the session."""
def __init__(self):
super().__init__(source_id="customer_profile") # also the key of this provider's state
async def before_run(self, *, agent, session, context: SessionContext, state: dict) -> None:
if state: # facts saved on earlier turns
facts = ", ".join(f"{key}: {value}" for key, value in state.items())
context.extend_instructions(self.source_id, f"Known facts about the customer: {facts}.")
async def after_run(self, *, agent, session, context: SessionContext, state: dict) -> None:
for message in context.input_messages: # what the customer said this turn
if found := re.search(r"my name is (\w+)", message.text, re.IGNORECASE):
state["name"] = found.group(1)
if found := re.search(r"I ride an? ([\w ]+?)[.!]", message.text, re.IGNORECASE):
state["bike"] = found.group(1)
async def main():
agent = Agent(
client=OpenAIChatClient(),
instructions="You are the assistant of a bike shop.",
context_providers=[CustomerProfile()],
)
session = agent.create_session()
await agent.run("Hi, my name is Priya. I ride a Trek FX 2.", session=session)
await agent.run("How often should it be serviced?", session=session) # now with the facts
print(session.state["customer_profile"])
asyncio.run(main()){'name': 'Priya', 'bike': 'Trek FX 2'}How it works:
super().__init__(source_id="customer_profile")names the provider. The name must be unique among the agent's providers, because it's also where the provider's data is kept.stateis a dictionary only this provider uses. It's stored in the session (session.state["customer_profile"]), so it lasts as long as the session, and it's saved whenever the session is saved.after_runreadscontext.input_messages, the messages the customer sent this run, and stores what it finds.before_runadds a line withcontext.extend_instructions(...). On the second run the model's instructions were: "You are the assistant of a bike shop." followed by "Known facts about the customer: name: Priya, bike: Trek FX 2."
Patterns like these are fragile. Real memory systems ask a model to pick out the facts, which is what the built-in providers below do. The plumbing stays the same.
What a provider can read and change
Both methods receive a SessionContext describing this run:
| Member | Use it to |
|---|---|
input_messages | Read the new messages of this run |
extend_instructions(source_id, text) | Add instructions for this run |
extend_messages(source_id, messages) | Add messages, such as notes or documents, before the new input |
extend_tools(source_id, tools) | Give the model extra tools for this run only |
extend_middleware(source_id, middleware) | Add chat or function middleware for this run |
get_messages(sources=..., include_input=..., include_response=...) | Read the messages that providers have added |
response | In after_run: the agent's full response |
metadata | A dictionary all providers share during one run |
session_id, service_session_id, options | Which session this is, and the run's options (read-only) |
This provider adds a customer's open repair tickets and a booking tool, but only when the question is about a repair:
import asyncio
from agent_framework import Agent, ContextProvider, Message, SessionContext, tool
from agent_framework.openai import OpenAIChatClient
OPEN_TICKETS = {"priya": ["R-102: gears slipping, ready on Friday"]} # stands in for the repair system
@tool
def book_repair(day: str) -> str:
"""Book a repair slot on the given day."""
return f"Repair booked for {day}."
class RepairDesk(ContextProvider):
"""For repair questions only: adds the customer's open tickets and the booking tool."""
def __init__(self, customer_id: str):
super().__init__(source_id="repair_desk")
self.customer_id = customer_id
async def before_run(self, *, agent, session, context: SessionContext, state: dict) -> None:
question = " ".join(message.text for message in context.input_messages).lower()
if "repair" not in question:
return # nothing to add to other questions
tickets = OPEN_TICKETS.get(self.customer_id, [])
if tickets:
context.extend_messages(self.source_id, [Message("user", ["Open repair tickets: " + "; ".join(tickets)])])
context.extend_tools(self.source_id, [book_repair])
async def main():
agent = Agent(
client=OpenAIChatClient(),
instructions="You are the assistant of a bike shop.",
context_providers=[RepairDesk(customer_id="priya")],
)
session = agent.create_session()
await agent.run("Do you sell helmets?", session=session) # no tickets, no tool
await agent.run("Is my repair done? If not, book one for Monday.", session=session)
asyncio.run(main())For the helmet question the model got nothing extra. For the repair question it received the message "Open repair tickets: R-102: gears slipping, ready on Friday", placed before the question, and the book_repair tool. Adding tools only when they're relevant keeps the model's choices small, and a tool it never sees is a tool it can't misuse.
Long-term memory
Provider state ends with the session. To remember a customer next week, store the facts outside the session, under an ID that tells you who the customer is:
import asyncio
import re
from agent_framework import Agent, ContextProvider, SessionContext
from agent_framework.openai import OpenAIChatClient
class CustomerMemory(ContextProvider):
"""Long-term memory: facts about one customer, stored outside the session."""
def __init__(self, customer_id: str, database: dict):
super().__init__(source_id="customer_memory")
self.customer_id = customer_id
self.database = database # stands in for a real database table
async def before_run(self, *, agent, session, context: SessionContext, state: dict) -> None:
facts = self.database.get(self.customer_id)
if facts:
known = "; ".join(f"{key}: {value}" for key, value in facts.items())
context.extend_instructions(self.source_id, f"From earlier visits: {known}.")
async def after_run(self, *, agent, session, context: SessionContext, state: dict) -> None:
facts = self.database.setdefault(self.customer_id, {})
for message in context.input_messages:
if found := re.search(r"I ride an? ([\w ]+?)[.!]", message.text, re.IGNORECASE):
facts["bike"] = found.group(1)
async def main():
database = {}
def agent_for(customer_id):
return Agent(
client=OpenAIChatClient(),
instructions="You are the assistant of a bike shop.",
context_providers=[CustomerMemory(customer_id, database)],
)
priya = agent_for("priya")
await priya.run("Hello! I ride a Trek FX 2.", session=priya.create_session()) # Monday
await priya.run("Which tyres fit my bike?", session=priya.create_session()) # Friday: a new session
sam = agent_for("sam")
await sam.run("Which tyres fit my bike?", session=sam.create_session()) # knows nothing about Sam
print(database)
asyncio.run(main()){'priya': {'bike': 'Trek FX 2'}, 'sam': {}}On Friday, Priya's brand-new session started with "From earlier visits: bike: Trek FX 2." in its instructions. Sam's run got nothing, because memory is looked up by customer ID. In a real app, database would be a table, and the customer ID would come from your login system, never from the chat itself.
Built-in memory providers
You rarely need to write the long-term part yourself:
| Provider | Import from | What it does | What you need |
|---|---|---|---|
Mem0ContextProvider | agent_framework.mem0 | Before each run, searches Mem0 for memories related to the new message. After it, sends the turn to Mem0, which picks out what to remember | A Mem0 Platform API key (MEM0_API_KEY), or your own Mem0 passed as mem0_client |
RedisContextProvider | agent_framework.redis | Saves each turn in Redis and searches it before each run, by full text or, with a vectorizer, by meaning as well | A Redis server with search (Redis 8, or Redis Stack). Free to run yourself |
FoundryMemoryProvider | agent_framework.foundry | Uses an Azure AI Foundry memory store: loads the user's profile memories once per session, searches related memories every run, and updates them in the background | An Azure AI Foundry project (paid) |
ContentUnderstandingContextProvider | agent_framework.foundry | Analyses files attached to a message (documents, images, audio, video) and adds the extracted text and fields | Azure Content Understanding (paid) |
MemoryContextProvider with a MemoryStore | agent_framework | An older memory system with a MEMORY.md index and memory tools | Deprecated, removed after 31 December 2026. Use FileMemoryProvider (the Harness Agents lesson) |
Creating them:
from agent_framework.foundry import ContentUnderstandingContextProvider, FoundryMemoryProvider
from agent_framework.mem0 import Mem0ContextProvider
from agent_framework.redis import RedisContextProvider
from azure.identity.aio import AzureCliCredential
def mem0_memory(customer_id: str): # needs a Mem0 account: set MEM0_API_KEY
return Mem0ContextProvider(
user_id=customer_id, # memories saved after each run belong to this customer
search_user_id=customer_id, # memories searched before each run come only from them
)
def redis_memory(customer_id: str): # free to run yourself: Redis 8, or Redis Stack
return RedisContextProvider(
redis_url="redis://localhost:6379",
index_name="bike_shop_memory",
user_id=customer_id, # every read and write is filtered by this ID
)
def foundry_memory(customer_id: str): # needs an Azure AI Foundry project (paid)
return FoundryMemoryProvider(
project_endpoint="https://your-resource.services.ai.azure.com/api/projects/your-project",
credential=AzureCliCredential(),
memory_store_name="bike-shop-memory",
scope=customer_id, # memories are grouped and isolated by scope
)
def document_reader(): # Azure Content Understanding (paid)
return ContentUnderstandingContextProvider(
endpoint="https://your-resource.services.ai.azure.com/",
credential=AzureCliCredential(),
output_sections=["markdown", "fields"], # what to pass to the model from each analysed file
)Attach any of them like your own: Agent(client=..., context_providers=[redis_memory("priya")]). Details that matter:
- Mem0 keeps two scopes.
user_id,agent_idandapplication_idsay where new memories are stored;search_user_id,search_agent_idandsearch_application_idsay where they're read from. Without asearch_*value nothing is retrieved, and the provider logs: "Mem0ContextProvider has no retrieval scope configured, so no memories will be retrieved." Keeping them separate stops one customer's memories leaking into another's chat. - Redis filters everything by
application_id,agent_idanduser_id; at least one must be set. - Foundry needs a
scope, usually the user's ID. New memories are processed afterupdate_delayseconds (300 by default; 0 for right away). The endpoint can also come from theFOUNDRY_PROJECT_ENDPOINTvariable. - Content Understanding waits up to
max_waitseconds (5 by default) for a file, then keeps analysing it in the background. Each file'sDocumentStatusis analyzing, uploading, ready or failed, andoutput_sectionschooses what reaches the model: theAnalysisSectionvalues"markdown","fields"or both.
Common mistakes
Write the after_run part of a memory provider in plain Python: pull facts out of what the customer said, keeping the newest value of each fact.
import re
messages = ["Hi there!", "My name is Ana and I live in Porto.", "Actually, I live in Braga now."]
facts = {}
# For each message, save the word after "my name is" as facts["name"] and the word
# after "I live in" as facts["city"] (ignore upper and lower case). Later messages win.
# Then print exactly: Known facts: name=Ana, city=Braga
A provider saves the customer's bike in its state argument. Next week the customer starts a new session. What happens?
Summary
- A context provider runs
before_runbefore the model call andafter_runafter it, in list order and then in reverse. SessionContextlets a provider add instructions, messages, tools and middleware for one run, and read the input and the response.- Provider
statelives in the session; long-term memory is stored outside it, keyed by a trusted user ID. - Mem0, Redis, Foundry Memory and Content Understanding providers are ready to use; the older
MemoryContextProviderandMemoryStoreare deprecated. - Give each provider a unique
source_id, and keep its state JSON-friendly.
Next: Embeddings, Vector Stores and RAG.
Finished reading? Tick it off to track your progress.