|
| 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