Velamuvi AIAcademy

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
In this lesson you will learn
  • 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:

Try it yourselfPython
# 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())
Output
{'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.
  • state is 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_run reads context.input_messages, the messages the customer sent this run, and stores what it finds.
  • before_run adds a line with context.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:

MemberUse it to
input_messagesRead 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
responseIn after_run: the agent's full response
metadataA dictionary all providers share during one run
session_id, service_session_id, optionsWhich 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())
Output
{'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:

ProviderImport fromWhat it doesWhat you need
Mem0ContextProvideragent_framework.mem0Before each run, searches Mem0 for memories related to the new message. After it, sends the turn to Mem0, which picks out what to rememberA Mem0 Platform API key (MEM0_API_KEY), or your own Mem0 passed as mem0_client
RedisContextProvideragent_framework.redisSaves each turn in Redis and searches it before each run, by full text or, with a vectorizer, by meaning as wellA Redis server with search (Redis 8, or Redis Stack). Free to run yourself
FoundryMemoryProvideragent_framework.foundryUses 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 backgroundAn Azure AI Foundry project (paid)
ContentUnderstandingContextProvideragent_framework.foundryAnalyses files attached to a message (documents, images, audio, video) and adds the extracted text and fieldsAzure Content Understanding (paid)
MemoryContextProvider with a MemoryStoreagent_frameworkAn older memory system with a MEMORY.md index and memory toolsDeprecated, 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_id and application_id say where new memories are stored; search_user_id, search_agent_id and search_application_id say where they're read from. Without a search_* 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_id and user_id; at least one must be set.
  • Foundry needs a scope, usually the user's ID. New memories are processed after update_delay seconds (300 by default; 0 for right away). The endpoint can also come from the FOUNDRY_PROJECT_ENDPOINT variable.
  • Content Understanding waits up to max_wait seconds (5 by default) for a file, then keeps analysing it in the background. Each file's DocumentStatus is analyzing, uploading, ready or failed, and output_sections chooses what reaches the model: the AnalysisSection values "markdown", "fields" or both.

Common mistakes

Practice exercise

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.

Your solutionPython
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
Knowledge check

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_run before the model call and after_run after it, in list order and then in reverse.
  • SessionContext lets a provider add instructions, messages, tools and middleware for one run, and read the input and the response.
  • Provider state lives 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 MemoryContextProvider and MemoryStore are 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.