Memory

A session remembers within one conversation. A ContextProvider remembers across all of them — durable facts injected into every run.

Part 4 of 72 Microsoft Agent Framework Python — Every Lesson

What this lesson demonstrates

The last lesson gave an agent memory within one conversation via a session. But real assistants remember across conversations — “you told me last week you bank with HDFC.” That durable knowledge lives in a ContextProvider, an object the agent consults on every run regardless of which session. Because the provider instance persists between runs, what it injects survives even a brand-new session.

The code

Subclass ContextProvider and use its two keyword-only hooks. before_run slips facts into this run’s system prompt; after_run is where you’d learn new ones:

class ProfileMemory(ContextProvider):
    def __init__(self) -> None:
        super().__init__(source_id="profile_memory")  # source_id is required
        self.facts: list[str] = []

    async def before_run(self, *, agent, session, context, state) -> None:
        if self.facts:
            note = "Known facts about the user: " + "; ".join(self.facts) + "."
            context.extend_instructions(self.source_id, note)

Attach it with context_providers=[memory], then two different sessions both know the user.

What to notice

How it maps to Azure AI Foundry

Nothing Foundry-specific here — the provider runs client-side, extending the instructions sent to the Foundry Responses API on each request. A production after_run would extract facts with an LLM call or tool; the lesson keeps it deterministic and offline. Same FoundryChatClient + AzureCliCredential.

Run it

uv run tutorial/01-get-started/04_memory.py

Expected: session two still knows the user because the facts live in the provider. Needs Foundry creds and az login.


Next: Functional Workflow With Agents

Sources & References

The Python SDK this lesson exercises
Cross-conversation memory with context providers