Skip to content

Commit e303cc9

Browse files
authored
Python: AzureAI OpenAPI + Memory Search Samples (#2390)
* openapi + memory search samples * readme update * memory store name fix
1 parent c78edda commit e303cc9

File tree

3 files changed

+142
-0
lines changed

3 files changed

+142
-0
lines changed

python/samples/getting_started/agents/azure_ai/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,9 @@ This folder contains examples demonstrating different ways to create and use age
2525
| [`azure_ai_with_sharepoint.py`](azure_ai_with_sharepoint.py) | Shows how to use SharePoint grounding with Azure AI agents to search through SharePoint content and answer user questions with proper citations. Requires a SharePoint connection configured in your Azure AI project. |
2626
| [`azure_ai_with_thread.py`](azure_ai_with_thread.py) | Demonstrates thread management with Azure AI agents, including automatic thread creation for stateless conversations and explicit thread management for maintaining conversation context across multiple interactions. |
2727
| [`azure_ai_with_image_generation.py`](azure_ai_with_image_generation.py) | Shows how to use the `ImageGenTool` with Azure AI agents to generate images based on text prompts. |
28+
| [`azure_ai_with_memory_search.py`](azure_ai_with_memory_search.py) | Shows how to use memory search functionality with Azure AI agents for conversation persistence. Demonstrates creating memory stores and enabling agents to search through conversation history. |
2829
| [`azure_ai_with_microsoft_fabric.py`](azure_ai_with_microsoft_fabric.py) | Shows how to use Microsoft Fabric with Azure AI agents to query Fabric data sources and provide responses based on data analysis. Requires a Microsoft Fabric connection configured in your Azure AI project. |
30+
| [`azure_ai_with_openapi.py`](azure_ai_with_openapi.py) | Shows how to integrate OpenAPI specifications with Azure AI agents using dictionary-based tool configuration. Demonstrates using external REST APIs for dynamic data lookup. |
2931
| [`azure_ai_with_web_search.py`](azure_ai_with_web_search.py) | Shows how to use the `HostedWebSearchTool` with Azure AI agents to perform web searches and retrieve up-to-date information from the internet. |
3032

3133
## Environment Variables
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# Copyright (c) Microsoft. All rights reserved.
2+
import asyncio
3+
import os
4+
import uuid
5+
6+
from agent_framework.azure import AzureAIClient
7+
from azure.ai.projects.aio import AIProjectClient
8+
from azure.ai.projects.models import MemoryStoreDefaultDefinition, MemoryStoreDefaultOptions
9+
from azure.identity.aio import AzureCliCredential
10+
11+
"""
12+
Azure AI Agent with Memory Search Example
13+
14+
This sample demonstrates usage of AzureAIClient with memory search capabilities
15+
to retrieve relevant past user messages and maintain conversation context across sessions.
16+
It shows explicit memory store creation using Azure AI Projects client and agent creation
17+
using the Agent Framework.
18+
19+
Prerequisites:
20+
1. Set AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_MODEL_DEPLOYMENT_NAME environment variables.
21+
2. Set AZURE_AI_CHAT_MODEL_DEPLOYMENT_NAME for the memory chat model.
22+
3. Set AZURE_AI_EMBEDDING_MODEL_DEPLOYMENT_NAME for the memory embedding model.
23+
4. Deploy both a chat model (e.g. gpt-4.1) and an embedding model (e.g. text-embedding-3-small).
24+
"""
25+
26+
27+
async def main() -> None:
28+
endpoint = os.environ["AZURE_AI_PROJECT_ENDPOINT"]
29+
# Generate a unique memory store name to avoid conflicts
30+
memory_store_name = f"agent_framework_memory_store_{uuid.uuid4().hex[:8]}"
31+
32+
async with AzureCliCredential() as credential:
33+
# Create the memory store using Azure AI Projects client
34+
async with AIProjectClient(endpoint=endpoint, credential=credential) as project_client:
35+
# Create a memory store using proper model classes
36+
memory_store_definition = MemoryStoreDefaultDefinition(
37+
chat_model=os.environ["AZURE_AI_CHAT_MODEL_DEPLOYMENT_NAME"],
38+
embedding_model=os.environ["AZURE_AI_EMBEDDING_MODEL_DEPLOYMENT_NAME"],
39+
options=MemoryStoreDefaultOptions(user_profile_enabled=True, chat_summary_enabled=True),
40+
)
41+
42+
memory_store = await project_client.memory_stores.create(
43+
name=memory_store_name,
44+
description="Memory store for Agent Framework conversations",
45+
definition=memory_store_definition,
46+
)
47+
print(f"Created memory store: {memory_store.name} ({memory_store.id}): {memory_store.description}")
48+
49+
# Then, create the agent using Agent Framework
50+
async with AzureAIClient(async_credential=credential).create_agent(
51+
name="MyMemoryAgent",
52+
instructions="""You are a helpful assistant that remembers past conversations.
53+
Use the memory search tool to recall relevant information from previous interactions.""",
54+
tools={
55+
"type": "memory_search",
56+
"memory_store_name": memory_store.name,
57+
"scope": "user_123",
58+
"update_delay": 1, # Wait 1 second before updating memories (use higher value in production)
59+
},
60+
) as agent:
61+
# First interaction - establish some preferences
62+
print("=== First conversation ===")
63+
query1 = "I prefer dark roast coffee"
64+
print(f"User: {query1}")
65+
result1 = await agent.run(query1)
66+
print(f"Agent: {result1}\n")
67+
68+
# Wait for memories to be processed
69+
print("Waiting for memories to be stored...")
70+
await asyncio.sleep(5) # Reduced wait time for demo purposes
71+
72+
# Second interaction - test memory recall
73+
print("=== Second conversation ===")
74+
query2 = "Please order my usual coffee"
75+
print(f"User: {query2}")
76+
result2 = await agent.run(query2)
77+
print(f"Agent: {result2}\n")
78+
79+
# Clean up - delete the memory store
80+
async with AIProjectClient(endpoint=endpoint, credential=credential) as project_client:
81+
await project_client.memory_stores.delete(memory_store_name)
82+
print("Memory store deleted")
83+
84+
85+
if __name__ == "__main__":
86+
asyncio.run(main())
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Copyright (c) Microsoft. All rights reserved.
2+
import asyncio
3+
import json
4+
from pathlib import Path
5+
6+
import aiofiles
7+
from agent_framework.azure import AzureAIClient
8+
from azure.identity.aio import AzureCliCredential
9+
10+
"""
11+
Azure AI Agent with OpenAPI Tool Example
12+
13+
This sample demonstrates usage of AzureAIClient with OpenAPI tools
14+
to call external APIs defined by OpenAPI specifications.
15+
16+
Prerequisites:
17+
1. Set AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_MODEL_DEPLOYMENT_NAME environment variables.
18+
2. The countries.json OpenAPI specification is included in the resources folder.
19+
"""
20+
21+
22+
async def main() -> None:
23+
# Load the OpenAPI specification
24+
resources_path = Path(__file__).parent.parent / "resources" / "countries.json"
25+
26+
async with aiofiles.open(resources_path, "r") as f:
27+
content = await f.read()
28+
openapi_countries = json.loads(content)
29+
30+
async with (
31+
AzureCliCredential() as credential,
32+
AzureAIClient(async_credential=credential).create_agent(
33+
name="MyOpenAPIAgent",
34+
instructions="""You are a helpful assistant that can use country APIs to provide information.
35+
Use the available OpenAPI tools to answer questions about countries, currencies, and demographics.""",
36+
tools={
37+
"type": "openapi",
38+
"openapi": {
39+
"name": "get_countries",
40+
"spec": openapi_countries,
41+
"description": "Retrieve information about countries by currency code",
42+
"auth": {"type": "anonymous"},
43+
},
44+
},
45+
) as agent,
46+
):
47+
query = "What is the name and population of the country that uses currency with abbreviation THB?"
48+
print(f"User: {query}")
49+
result = await agent.run(query)
50+
print(f"Agent: {result}\n")
51+
52+
53+
if __name__ == "__main__":
54+
asyncio.run(main())

0 commit comments

Comments
 (0)