Skip to content

Commit 47c8e29

Browse files
authored
Python: Add FileMemoryProvider context provider sample (#7428)
* Add FileMemoryProvider sample * Address PR comments
1 parent 51615d5 commit 47c8e29

2 files changed

Lines changed: 151 additions & 0 deletions

File tree

‎python/samples/02-agents/context_providers/README.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ These samples demonstrate how to use context providers to enrich agent conversat
1111
| [`agent_mode_provider.py`](agent_mode_provider.py) | Use the built-in `AgentModeProvider` to track and switch an agent's operating mode at runtime. An interactive loop with a `/mode` slash command demonstrating the built-in `plan`/`execute` modes and custom modes. |
1212
| [`cross_session_observer.py`](cross_session_observer.py) | Detect injected context messages whose origins differ from the current session, via the `Message.additional_properties["_attribution"]["origin_session_ids"]` field. Self-contained — no LLM credentials required. |
1313
| [`azure_ai_foundry_memory.py`](azure_ai_foundry_memory.py) | Use `FoundryMemoryProvider` to add semantic memory — automatically retrieves, searches, and stores memories via Microsoft Foundry. |
14+
| [`file_memory_provider.py`](file_memory_provider.py) | Use the built-in `FileMemoryProvider` with `FileSystemAgentFileStore` to give an agent tools for storing and recalling memories as files, and configure the `scope` so memories persist and are recalled across separate sessions. |
1415
| [`file_access_data_processing/`](file_access_data_processing/) | Use `FileAccessProvider` with `FileSystemAgentFileStore` to give an agent read/write/search access to a folder of CSV data files. See its own [README](file_access_data_processing/README.md). |
1516
| [`azure_ai_search/`](azure_ai_search/) | Retrieval Augmented Generation (RAG) with Azure AI Search in semantic and agentic modes. See its own [README](azure_ai_search/README.md). |
1617
| [`azure_content_understanding/`](azure_content_understanding/) | Analyze documents, images, audio, and video with Azure Content Understanding and inject the extracted content into agent context. |
@@ -45,6 +46,11 @@ These samples demonstrate how to use context providers to enrich agent conversat
4546
- `AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME`: Embedding model deployment name (e.g., `text-embedding-ada-002`)
4647
- Azure CLI authentication (`az login`)
4748

49+
**For `file_memory_provider.py`:**
50+
- `FOUNDRY_PROJECT_ENDPOINT`: Your Microsoft Foundry project endpoint
51+
- `FOUNDRY_MODEL`: Chat model deployment name
52+
- Azure CLI authentication (`az login`)
53+
4854
**For `file_access_data_processing/`:**
4955
- `FOUNDRY_PROJECT_ENDPOINT`: Your Microsoft Foundry project endpoint
5056
- `FOUNDRY_MODEL`: Chat model deployment name
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
# Copyright (c) Microsoft. All rights reserved.
2+
3+
import asyncio
4+
import os
5+
from pathlib import Path
6+
7+
from agent_framework import Agent, AgentSession, FileMemoryProvider, FileSystemAgentFileStore
8+
from agent_framework.foundry import FoundryChatClient
9+
from azure.identity import AzureCliCredential
10+
from dotenv import load_dotenv
11+
12+
# Load python/.env (python-dotenv walks up from this file by default). Pass
13+
# override=True so values from .env take precedence over any pre-existing OS
14+
# environment variables — without this, OS-level values silently win.
15+
load_dotenv(override=True)
16+
17+
"""
18+
Sample: give an agent file-based memory with ``FileMemoryProvider``.
19+
20+
This sample shows how to attach :class:`FileMemoryProvider` directly to a plain
21+
``Agent`` via ``context_providers``, and how to control the *scope* of the
22+
memories so they persist and can be recalled across separate sessions.
23+
24+
``FileMemoryProvider`` is a :class:`~agent_framework.ContextProvider` that
25+
exposes a set of ``file_memory_*`` tools (write, read, delete, ls, grep,
26+
replace, replace_lines) to the agent, letting the model decide what to remember
27+
and when to recall it. Each memory is stored as an individual file in an
28+
:class:`~agent_framework.AgentFileStore`; here we use a
29+
:class:`~agent_framework.FileSystemAgentFileStore` so the memories are written
30+
to real files on disk. Because the files live outside the conversation, the
31+
agent can recall them in a later session, even after the original chat history
32+
is gone.
33+
34+
Controlling scope:
35+
The provider isolates memories per session by default (the working folder is
36+
derived from the session id). Passing an explicit ``scope`` (for example a
37+
user id) instead groups memories under a stable working folder that every
38+
session for that user shares — which is what lets the second conversation
39+
below recall what the user said in the first.
40+
41+
Prerequisites:
42+
- ``FOUNDRY_PROJECT_ENDPOINT``: Your Microsoft Foundry project endpoint.
43+
- ``FOUNDRY_MODEL``: Chat model deployment name.
44+
- Run ``az login`` before executing the sample.
45+
"""
46+
47+
# The id of the user we are storing memories for. It is used below as the
48+
# provider's scope so that each user gets their own memory folder.
49+
USER_ID = "UID1"
50+
51+
52+
async def main() -> None:
53+
client = FoundryChatClient(
54+
project_endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
55+
model=os.environ["FOUNDRY_MODEL"],
56+
credential=AzureCliCredential(),
57+
)
58+
59+
# <create_file_memory_provider>
60+
# 1. Create the file store the provider will use to persist memory files.
61+
# Here we use a file-system backed store rooted at a local
62+
# ``agent-file-memory`` folder, but any AgentFileStore implementation can
63+
# be used, e.g. InMemoryAgentFileStore or a custom blob-backed store.
64+
memory_root = Path(__file__).parent / "agent-file-memory"
65+
store = FileSystemAgentFileStore(memory_root)
66+
67+
# 2. Create the FileMemoryProvider over that store.
68+
# The ``scope`` determines the scope and lifetime of the memories:
69+
# - A stable scope, like the per-user one below, gives durable memories
70+
# shared by every session for that user. That is what allows the second
71+
# conversation further down to recall what the user said in the first.
72+
# - Omitting ``scope`` (the default) isolates memories to a single session
73+
# (the working folder is derived from the session id).
74+
file_memory_provider = FileMemoryProvider(store, scope=f"users/{USER_ID}")
75+
76+
# 3. Attach the provider to the agent so it gets the file_memory_* tools.
77+
agent = Agent(
78+
client=client,
79+
name="TravelAssistant",
80+
instructions=(
81+
"You are a helpful travel assistant. Remember what the user tells you about "
82+
"themselves so that you can give better recommendations later."
83+
),
84+
context_providers=[file_memory_provider],
85+
)
86+
# </create_file_memory_provider>
87+
88+
working_folder = memory_root / "users" / USER_ID
89+
print(f"Memory files will be written to: {working_folder}\n")
90+
91+
# 4. First conversation: tell the agent something worth remembering. The
92+
# agent should call file_memory_write to store it as a file in the scope.
93+
first_session: AgentSession = agent.create_session()
94+
print("=== First conversation ===")
95+
print(
96+
await agent.run(
97+
"I'm vegetarian and I always travel with my dog. Please remember this for future trips.",
98+
session=first_session,
99+
)
100+
)
101+
print()
102+
103+
# 5. Show the memory files the agent created on disk.
104+
print("=== Memory files on disk ===")
105+
if working_folder.exists():
106+
for file in sorted(working_folder.iterdir()):
107+
if file.is_file():
108+
print(file.name)
109+
print()
110+
111+
# 6. Second conversation: a brand new session with no chat history from the
112+
# first. The provider injects the memory index (memories.md) into the
113+
# agent's context, and the agent calls file_memory_read to recall the
114+
# user's preferences with no shared chat history.
115+
second_session: AgentSession = agent.create_session()
116+
print("=== Second conversation (new session) ===")
117+
print(
118+
await agent.run(
119+
"Suggest a hotel and a restaurant for my trip to Paris next week.",
120+
session=second_session,
121+
)
122+
)
123+
124+
125+
if __name__ == "__main__":
126+
asyncio.run(main())
127+
128+
129+
"""
130+
Sample output (abridged; exact text varies by model):
131+
132+
Memory files will be written to: .../context_providers/agent-file-memory/users/UID1
133+
134+
=== First conversation ===
135+
Got it — I'll remember that you're vegetarian and always travel with your dog. I've saved
136+
this so I can tailor future recommendations for you.
137+
138+
=== Memory files on disk ===
139+
userpreferences.md
140+
141+
=== Second conversation (new session) ===
142+
Since you're vegetarian and travel with your dog, here are some dog-friendly options in Paris:
143+
- Hotel: ... (pet-friendly, central) ...
144+
- Restaurant: ... (excellent vegetarian menu, welcomes dogs) ...
145+
"""

0 commit comments

Comments
 (0)