Repository navigation
Expand file tree
/
Copy path04_memory.py
More file actions
69 lines (56 loc) · 2.1 KB
/
Copy path04_memory.py
File metadata and controls
69 lines (56 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# Copyright (c) Microsoft. All rights reserved.
"""Persist a user's name with a context provider.
The provider stores the name in session state and injects it into later calls.
"""
import asyncio
from typing import Any
from agent_framework import Agent, AgentSession, ContextProvider, SessionContext
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential
class UserMemoryProvider(ContextProvider):
def __init__(self) -> None:
super().__init__("user_memory")
async def before_run(
self,
*,
agent: Any,
session: AgentSession | None,
context: SessionContext,
state: dict[str, Any],
) -> None:
user_name = state.get("user_name")
instructions = (
f"The user's name is {user_name}. Address them by name." if user_name else "Ask for the user's name."
)
context.extend_instructions(self.source_id, instructions)
async def after_run(
self,
*,
agent: Any,
session: AgentSession | None,
context: SessionContext,
state: dict[str, Any],
) -> None:
for message in context.input_messages:
text = message.text
if not isinstance(text, str):
continue
_, marker, name = text.lower().partition("my name is")
if marker and name.strip():
state["user_name"] = name.split()[0].capitalize()
async def main() -> None:
agent = Agent(
client=FoundryChatClient(
project_endpoint="https://your-account.services.ai.azure.com/api/projects/your-project",
model="gpt-6-luna",
credential=AzureCliCredential(),
),
instructions="You are a friendly assistant.",
context_providers=[UserMemoryProvider()],
)
session = agent.create_session()
print(await agent.run("Hello! What's the square root of 9?", session=session))
print(await agent.run("My name is Alice", session=session))
print(await agent.run("What is 2 + 2?", session=session))
if __name__ == "__main__":
asyncio.run(main())