Skip to content

Commit 73f48d2

Browse files
authored
.NET: Add FileMemoryProvider sample to 02-agents/AgentWithMemory (#7401)
* Add FileMemoryProvider sample * Address PR comments
1 parent 28389df commit 73f48d2

8 files changed

Lines changed: 215 additions & 4 deletions

File tree

‎dotnet/agent-framework-dotnet.slnx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,7 @@
205205
<Project Path="samples/02-agents/AgentWithMemory/AgentWithMemory_Step04_MemoryUsingFoundry/AgentWithMemory_Step04_MemoryUsingFoundry.csproj" />
206206
<Project Path="samples/02-agents/AgentWithMemory/AgentWithMemory_Step05_BoundedChatHistory/AgentWithMemory_Step05_BoundedChatHistory.csproj" />
207207
<Project Path="samples/02-agents/AgentWithMemory/AgentWithMemory_Step06_MemoryUsingAgentMemory/AgentWithMemory_Step06_MemoryUsingAgentMemory.csproj" />
208+
<Project Path="samples/02-agents/AgentWithMemory/AgentWithMemory_Step07_FileMemoryProvider/AgentWithMemory_Step07_FileMemoryProvider.csproj" />
208209
</Folder>
209210
<Folder Name="/Samples/02-agents/AgentProviders/openai/">
210211
<File Path="samples/02-agents/AgentProviders/openai/README.md" />

‎dotnet/eng/verify-samples/AgentsSamples.cs‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -510,6 +510,28 @@ internal static class AgentsSamples
510510
SkipReason = "Requires a running Neo4j instance; standalone sample outside the repo's CPM build.",
511511
},
512512

513+
new SampleDefinition
514+
{
515+
Name = "AgentWithMemory_Step07_FileMemoryProvider",
516+
ProjectPath = "samples/02-agents/AgentWithMemory/AgentWithMemory_Step07_FileMemoryProvider",
517+
RequiredEnvironmentVariables = ["FOUNDRY_PROJECT_ENDPOINT"],
518+
OptionalEnvironmentVariables = ["FOUNDRY_MODEL"],
519+
MustContain =
520+
[
521+
"Memory files will be written to:",
522+
"=== First conversation ===",
523+
"=== Memory files on disk ===",
524+
"=== Second conversation (new session) ===",
525+
],
526+
ExpectedOutputDescription =
527+
[
528+
"The output should acknowledge that the user is vegetarian and travels with a dog, indicating the agent stored these preferences.",
529+
"The memory files section should list at least one memory file written by the agent, such as a file about the user's preferences.",
530+
"The second conversation should recommend a hotel and a restaurant in Paris that are consistent with the remembered preferences, for example a pet-friendly hotel and a restaurant with vegetarian options, even though it is a new session.",
531+
"The output should not contain error messages or stack traces.",
532+
],
533+
},
534+
513535
// ── AgentWithRAG ────────────────────────────────────────────────────
514536

515537
new SampleDefinition
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFrameworks>net10.0</TargetFrameworks>
6+
7+
<Nullable>enable</Nullable>
8+
<ImplicitUsings>enable</ImplicitUsings>
9+
</PropertyGroup>
10+
11+
<ItemGroup>
12+
<PackageReference Include="Azure.Identity" />
13+
</ItemGroup>
14+
15+
<ItemGroup>
16+
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Foundry\Microsoft.Agents.AI.Foundry.csproj" />
17+
</ItemGroup>
18+
19+
</Project>
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
// Copyright (c) Microsoft. All rights reserved.
2+
3+
// This sample shows how to give an agent file-based memory using the FileMemoryProvider.
4+
// The FileMemoryProvider exposes a set of tools to the agent (write, read, delete, list, grep and replace)
5+
// that allow it to store memories as individual files in an AgentFileStore.
6+
// Because the files are stored outside of the conversation, the agent can recall them
7+
// in later conversations, even after the original chat history is gone.
8+
//
9+
// The sample also shows how to control the folder that memory files are written to,
10+
// by supplying a state initializer callback that sets the working folder for each session.
11+
12+
#pragma warning disable MAAI001 // AgentFileStore and its implementations are experimental.
13+
14+
using Azure.AI.Projects;
15+
using Azure.Identity;
16+
using Microsoft.Agents.AI;
17+
18+
var endpoint = Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("FOUNDRY_PROJECT_ENDPOINT is not set.");
19+
var deploymentName = Environment.GetEnvironmentVariable("FOUNDRY_MODEL") ?? "gpt-5.4-mini";
20+
21+
// The id of the user that we are storing memories for.
22+
// It is used below to give each user their own memory folder.
23+
const string UserId = "UID1";
24+
25+
// Create the file store that the FileMemoryProvider will use to persist memory files.
26+
// Here we use a file system backed store rooted at a local folder called "agent-memory",
27+
// but any AgentFileStore implementation can be used, e.g. InMemoryAgentFileStore or a custom
28+
// implementation backed by blob storage.
29+
var memoryRoot = Path.Combine(AppContext.BaseDirectory, "agent-memory");
30+
var fileStore = new FileSystemAgentFileStore(memoryRoot);
31+
32+
// The working folder that memories for this user will be written to, relative to the store root.
33+
// The folder you choose determines the scope and lifetime of the memories:
34+
// - A stable folder, like the per-user one below, gives you durable memories that are shared by
35+
// every session for that user. That is what allows the second conversation further down to
36+
// recall what the user said in the first.
37+
// - A unique folder per session gives you memories that are isolated to a single session, e.g.
38+
// generate one in the state initializer callback below:
39+
// _ => new FileMemoryState { WorkingFolder = Guid.NewGuid().ToString() }
40+
var workingFolder = $"users/{UserId}";
41+
42+
Console.WriteLine($"Memory files will be written to: {Path.Combine(memoryRoot, workingFolder)}");
43+
Console.WriteLine();
44+
45+
// Create the file memory provider.
46+
// The second parameter is a state initializer callback that is invoked whenever the provider
47+
// cannot find existing state in a session, i.e. typically the first time it is used with a new session.
48+
// It allows us to configure the folder that memory files for that session are written to.
49+
// If no callback is supplied, the working folder defaults to the root of the store,
50+
// which means all sessions share a single, flat set of memory files.
51+
using var fileMemoryProvider = new FileMemoryProvider(
52+
fileStore,
53+
_ => new FileMemoryState { WorkingFolder = workingFolder });
54+
55+
// Create the agent and attach the FileMemoryProvider so that the agent gets the file memory tools.
56+
AIAgent agent = new AIProjectClient(
57+
new Uri(endpoint),
58+
// WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production.
59+
// In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid
60+
// latency issues, unintended credential probing, and potential security risks from fallback mechanisms.
61+
new DefaultAzureCredential())
62+
.AsAIAgent(new ChatClientAgentOptions
63+
{
64+
ChatOptions = new()
65+
{
66+
ModelId = deploymentName,
67+
Instructions = "You are a helpful travel assistant. Remember what the user tells you about themselves so that you can give better recommendations later."
68+
},
69+
Name = "TravelAssistant",
70+
AIContextProviders = [fileMemoryProvider],
71+
});
72+
73+
// First conversation: tell the agent something worth remembering.
74+
// The agent should use the file_memory_write tool to store it as a file in the working folder.
75+
AgentSession firstSession = await agent.CreateSessionAsync();
76+
Console.WriteLine("=== First conversation ===");
77+
Console.WriteLine(await agent.RunAsync(
78+
"I'm vegetarian and I always travel with my dog. Please remember this for future trips.",
79+
firstSession));
80+
Console.WriteLine();
81+
82+
// Show the memory files that the agent created on disk.
83+
Console.WriteLine("=== Memory files on disk ===");
84+
foreach (var file in Directory.EnumerateFiles(Path.Combine(memoryRoot, workingFolder)))
85+
{
86+
Console.WriteLine(Path.GetFileName(file));
87+
}
88+
89+
Console.WriteLine();
90+
91+
// Second conversation: a brand new session with no chat history from the first conversation.
92+
// The provider surfaces the memory index to the agent, and the agent can read the memory files
93+
// using the file_memory_read tool, so it can still recall the user's preferences.
94+
AgentSession secondSession = await agent.CreateSessionAsync();
95+
Console.WriteLine("=== Second conversation (new session) ===");
96+
Console.WriteLine(await agent.RunAsync(
97+
"Suggest a hotel and a restaurant for my trip to Paris next week.",
98+
secondSession));
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# File Based Memory with FileMemoryProvider
2+
3+
This sample demonstrates how to give an agent file-based memory using the `FileMemoryProvider`.
4+
5+
The `FileMemoryProvider` is an `AIContextProvider` that exposes a set of memory tools to the agent, allowing the agent to decide what to remember and when to recall it. Each memory is stored as an individual file in an `AgentFileStore`, so memories survive beyond the lifetime of a single conversation.
6+
7+
## Concepts
8+
9+
- **`FileMemoryProvider`**: An `AIContextProvider` that adds the following tools to the agent:
10+
11+
| Tool | Description |
12+
|---|---|
13+
| `file_memory_write` | Write a memory file with a name, content and optional description. |
14+
| `file_memory_read` | Read the content of a memory file by name. |
15+
| `file_memory_delete` | Delete a memory file by name. |
16+
| `file_memory_ls` | List all memory files with their descriptions. |
17+
| `file_memory_grep` | Search memory file contents using a regular expression. |
18+
| `file_memory_replace` | Replace occurrences of a substring within a memory file. |
19+
| `file_memory_replace_lines` | Replace whole lines within a memory file. |
20+
21+
The provider also maintains a `memories.md` index file, which it injects into the conversation so the agent knows which memories are available without having to list them first.
22+
23+
- **`AgentFileStore`**: The pluggable storage abstraction used by the provider. This sample uses `FileSystemAgentFileStore` to store memories on the local disk, but `InMemoryAgentFileStore` or a custom implementation (e.g. backed by blob storage) can be used instead.
24+
25+
- **`FileMemoryState`**: The per-session state of the provider. Its `WorkingFolder` property determines the folder, relative to the store root, that memory files are written to.
26+
27+
## Configuring the memory folder
28+
29+
By default, all sessions share the root folder of the store, which means every session reads and writes the same flat set of memory files.
30+
31+
To scope memories, e.g. per user, per tenant or per session, pass a state initializer callback to the `FileMemoryProvider` constructor. The callback receives the `AgentSession` and is invoked whenever the provider cannot find existing state in that session, i.e. typically the first time the provider is used with a new session:
32+
33+
```csharp
34+
using var fileMemoryProvider = new FileMemoryProvider(
35+
fileStore,
36+
session => new FileMemoryState { WorkingFolder = $"users/{userId}" });
37+
```
38+
39+
In this sample, memories are written to `agent-memory/users/UID1` under the application's base directory. Because the folder is derived from a fixed user id rather than the session, a new session for the same user picks up the memories written by earlier sessions.
40+
41+
## Prerequisites
42+
43+
- [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0)
44+
- A Microsoft Foundry project with a chat model deployment
45+
- Run `az login` to authenticate with `DefaultAzureCredential`
46+
47+
## Configuration
48+
49+
Set the following environment variables:
50+
51+
| Variable | Description | Default |
52+
|---|---|---|
53+
| `FOUNDRY_PROJECT_ENDPOINT` | Your Foundry project endpoint | *(required)* |
54+
| `FOUNDRY_MODEL` | Chat model deployment name | `gpt-5.4-mini` |
55+
56+
## Running the Sample
57+
58+
```bash
59+
dotnet run
60+
```
61+
62+
## How it Works
63+
64+
1. A `FileSystemAgentFileStore` is created, rooted at a local `agent-memory` folder.
65+
2. A `FileMemoryProvider` is created over that store, with a state initializer that puts the memories for the current user in their own working folder.
66+
3. The provider is attached to the agent via `ChatClientAgentOptions.AIContextProviders`, which gives the agent the `file_memory_*` tools and instructions for using them.
67+
4. In the first conversation, the user shares some preferences and the agent calls `file_memory_write` to store them as a file in the working folder. The sample then lists the files that were created on disk.
68+
5. In the second conversation, a brand new session is created with no chat history from the first conversation. The provider injects the memory index into the conversation, and the agent calls `file_memory_read` to recall the stored preferences when making its recommendations.

‎dotnet/samples/02-agents/AgentWithMemory/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ These samples show how to create an agent with the Agent Framework that uses Mem
1010
|[Memory with Microsoft Foundry](./AgentWithMemory_Step04_MemoryUsingFoundry/)|This sample demonstrates how to create and run an agent that uses Microsoft Foundry's managed memory service to extract and retrieve individual memories.|
1111
|[Bounded Chat History with Overflow](./AgentWithMemory_Step05_BoundedChatHistory/)|This sample demonstrates how to create a bounded chat history provider that overflows older messages to a vector store and recalls them as memories.|
1212
|[Memory Using AgentMemory](./AgentWithMemory_Step06_MemoryUsingAgentMemory/)|This sample demonstrates a retail shopping assistant built with [`AgentMemory`](https://www.nuget.org/packages/AgentMemory), an unofficial .NET port of the Neo4j Labs graph-memory provider, to learn customer preferences and recommend products via graph traversal.|
13+
|[File Based Memory](./AgentWithMemory_Step07_FileMemoryProvider/)|This sample demonstrates how to use the `FileMemoryProvider` to give an agent tools for storing and recalling memories as files, and how to configure the folder that those memory files are written to.|
1314

1415
> **See also**: [Memory Search with Foundry Agents](../AgentProviders/foundry/Agent_Step22_MemorySearch/) - demonstrates using the built-in Memory Search tool with Microsoft Foundry agents.
1516

‎dotnet/src/Microsoft.Agents.AI/Harness/FileAccess/FileAccessProvider.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ namespace Microsoft.Agents.AI;
2222
/// <para>
2323
/// The <see cref="FileAccessProvider"/> gives agents the ability to work with files
2424
/// in a folder that the user has granted access to. Unlike <see cref="FileMemoryProvider"/>,
25-
/// which provides session-scoped memory that may be isolated per session, <see cref="FileAccessProvider"/>
25+
/// which provides agent-managed memory files whose scope is determined by the working folder it is
26+
/// configured with, <see cref="FileAccessProvider"/>
2627
/// operates on a shared, persistent folder whose contents are visible across sessions and agents.
2728
/// This makes it suitable for reading input data, writing output artifacts, and working with
2829
/// files that have a lifetime beyond any single agent session.

‎dotnet/src/Microsoft.Agents.AI/Harness/FileMemory/FileMemoryProvider.cs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,9 @@ public sealed class FileMemoryProvider : AIContextProvider, IDisposable
6969
private const string DefaultInstructions =
7070
"""
7171
## File Based Memory
72-
You have access to a session-scoped, file-based memory system via the `file_memory_*` tools for storing and retrieving information across interactions.
73-
These files act as your working memory for the current session and are isolated from other sessions.
72+
You have access to a file-based memory system via the `file_memory_*` tools for storing and retrieving information across interactions.
73+
These files act as your working memory and persist beyond the current conversation, so they may already contain memories written earlier,
74+
and anything you write now may remain available later.
7475
Use these tools to store plans, memories, processing results, or downloaded data.
7576
7677
- Use descriptive file names (e.g., "projectarchitecture.md", "userpreferences.md").
@@ -507,7 +508,7 @@ private static bool IsInternalFile(string fileName) =>
507508

508509
/// <summary>
509510
/// Returns <see langword="true"/> if the normalized file name points into a subdirectory.
510-
/// File memory is a flat, session-scoped space, so nested names are rejected up front.
511+
/// File memory is a flat namespace within the working folder, so nested names are rejected up front.
511512
/// </summary>
512513
private static bool IsNestedPath(string normalizedFileName) =>
513514
normalizedFileName.IndexOf('/') >= 0;

0 commit comments

Comments
 (0)