|
| 1 | +# Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import os |
| 5 | +from collections.abc import MutableSequence |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +from agent_framework import Context, ContextProvider, Message |
| 9 | +from agent_framework.azure import AzureOpenAIResponsesClient |
| 10 | +from azure.identity import AzureCliCredential |
| 11 | + |
| 12 | +""" |
| 13 | +Agent Memory with Context Providers |
| 14 | +
|
| 15 | +Context providers let you inject dynamic instructions and context into each |
| 16 | +agent invocation. This sample defines a simple provider that tracks the user's |
| 17 | +name and enriches every request with personalization instructions. |
| 18 | +
|
| 19 | +Environment variables: |
| 20 | + AZURE_AI_PROJECT_ENDPOINT — Your Azure AI Foundry project endpoint |
| 21 | + AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME — Model deployment name (e.g. gpt-4o) |
| 22 | +""" |
| 23 | + |
| 24 | + |
| 25 | +# <context_provider> |
| 26 | +class UserNameProvider(ContextProvider): |
| 27 | + """A simple context provider that remembers the user's name.""" |
| 28 | + |
| 29 | + def __init__(self) -> None: |
| 30 | + self.user_name: str | None = None |
| 31 | + |
| 32 | + async def invoking(self, messages: Message | MutableSequence[Message], **kwargs: Any) -> Context: |
| 33 | + """Called before each agent invocation — add extra instructions.""" |
| 34 | + if self.user_name: |
| 35 | + return Context(instructions=f"The user's name is {self.user_name}. Always address them by name.") |
| 36 | + return Context(instructions="You don't know the user's name yet. Ask for it politely.") |
| 37 | + |
| 38 | + async def invoked( |
| 39 | + self, |
| 40 | + request_messages: Message | list[Message] | None = None, |
| 41 | + response_messages: "Message | list[Message] | None" = None, |
| 42 | + invoke_exception: Exception | None = None, |
| 43 | + **kwargs: Any, |
| 44 | + ) -> None: |
| 45 | + """Called after each agent invocation — extract information.""" |
| 46 | + msgs = [request_messages] if isinstance(request_messages, Message) else list(request_messages or []) |
| 47 | + for msg in msgs: |
| 48 | + text = msg.text if hasattr(msg, "text") else "" |
| 49 | + if isinstance(text, str) and "my name is" in text.lower(): |
| 50 | + # Simple extraction — production code should use structured extraction |
| 51 | + self.user_name = text.lower().split("my name is")[-1].strip().split()[0].capitalize() |
| 52 | +# </context_provider> |
| 53 | + |
| 54 | + |
| 55 | +async def main() -> None: |
| 56 | + # <create_agent> |
| 57 | + credential = AzureCliCredential() |
| 58 | + client = AzureOpenAIResponsesClient( |
| 59 | + project_endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], |
| 60 | + deployment_name=os.environ["AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME"], |
| 61 | + credential=credential, |
| 62 | + ) |
| 63 | + |
| 64 | + memory = UserNameProvider() |
| 65 | + |
| 66 | + agent = client.as_agent( |
| 67 | + name="MemoryAgent", |
| 68 | + instructions="You are a friendly assistant.", |
| 69 | + context_provider=memory, |
| 70 | + ) |
| 71 | + # </create_agent> |
| 72 | + |
| 73 | + thread = agent.get_new_thread() |
| 74 | + |
| 75 | + # The provider doesn't know the user yet — it will ask for a name |
| 76 | + result = await agent.run("Hello! What's the square root of 9?", thread=thread) |
| 77 | + print(f"Agent: {result}\n") |
| 78 | + |
| 79 | + # Now provide the name — the provider extracts and stores it |
| 80 | + result = await agent.run("My name is Alice", thread=thread) |
| 81 | + print(f"Agent: {result}\n") |
| 82 | + |
| 83 | + # Subsequent calls are personalized |
| 84 | + result = await agent.run("What is 2 + 2?", thread=thread) |
| 85 | + print(f"Agent: {result}\n") |
| 86 | + |
| 87 | + print(f"[Memory] Stored user name: {memory.user_name}") |
| 88 | + |
| 89 | + |
| 90 | +if __name__ == "__main__": |
| 91 | + asyncio.run(main()) |
0 commit comments