mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
Python: AzureAI OpenAPI + Memory Search Samples (#2390)
* openapi + memory search samples * readme update * memory store name fix
This commit is contained in:
committed by
GitHub
Unverified
parent
c78edda64f
commit
e303cc963d
@@ -25,7 +25,9 @@ This folder contains examples demonstrating different ways to create and use age
|
||||
| [`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. |
|
||||
| [`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. |
|
||||
| [`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. |
|
||||
| [`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. |
|
||||
| [`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. |
|
||||
| [`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. |
|
||||
| [`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. |
|
||||
|
||||
## Environment Variables
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
import asyncio
|
||||
import os
|
||||
import uuid
|
||||
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from azure.ai.projects.aio import AIProjectClient
|
||||
from azure.ai.projects.models import MemoryStoreDefaultDefinition, MemoryStoreDefaultOptions
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
|
||||
"""
|
||||
Azure AI Agent with Memory Search Example
|
||||
|
||||
This sample demonstrates usage of AzureAIClient with memory search capabilities
|
||||
to retrieve relevant past user messages and maintain conversation context across sessions.
|
||||
It shows explicit memory store creation using Azure AI Projects client and agent creation
|
||||
using the Agent Framework.
|
||||
|
||||
Prerequisites:
|
||||
1. Set AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_MODEL_DEPLOYMENT_NAME environment variables.
|
||||
2. Set AZURE_AI_CHAT_MODEL_DEPLOYMENT_NAME for the memory chat model.
|
||||
3. Set AZURE_AI_EMBEDDING_MODEL_DEPLOYMENT_NAME for the memory embedding model.
|
||||
4. Deploy both a chat model (e.g. gpt-4.1) and an embedding model (e.g. text-embedding-3-small).
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
endpoint = os.environ["AZURE_AI_PROJECT_ENDPOINT"]
|
||||
# Generate a unique memory store name to avoid conflicts
|
||||
memory_store_name = f"agent_framework_memory_store_{uuid.uuid4().hex[:8]}"
|
||||
|
||||
async with AzureCliCredential() as credential:
|
||||
# Create the memory store using Azure AI Projects client
|
||||
async with AIProjectClient(endpoint=endpoint, credential=credential) as project_client:
|
||||
# Create a memory store using proper model classes
|
||||
memory_store_definition = MemoryStoreDefaultDefinition(
|
||||
chat_model=os.environ["AZURE_AI_CHAT_MODEL_DEPLOYMENT_NAME"],
|
||||
embedding_model=os.environ["AZURE_AI_EMBEDDING_MODEL_DEPLOYMENT_NAME"],
|
||||
options=MemoryStoreDefaultOptions(user_profile_enabled=True, chat_summary_enabled=True),
|
||||
)
|
||||
|
||||
memory_store = await project_client.memory_stores.create(
|
||||
name=memory_store_name,
|
||||
description="Memory store for Agent Framework conversations",
|
||||
definition=memory_store_definition,
|
||||
)
|
||||
print(f"Created memory store: {memory_store.name} ({memory_store.id}): {memory_store.description}")
|
||||
|
||||
# Then, create the agent using Agent Framework
|
||||
async with AzureAIClient(async_credential=credential).create_agent(
|
||||
name="MyMemoryAgent",
|
||||
instructions="""You are a helpful assistant that remembers past conversations.
|
||||
Use the memory search tool to recall relevant information from previous interactions.""",
|
||||
tools={
|
||||
"type": "memory_search",
|
||||
"memory_store_name": memory_store.name,
|
||||
"scope": "user_123",
|
||||
"update_delay": 1, # Wait 1 second before updating memories (use higher value in production)
|
||||
},
|
||||
) as agent:
|
||||
# First interaction - establish some preferences
|
||||
print("=== First conversation ===")
|
||||
query1 = "I prefer dark roast coffee"
|
||||
print(f"User: {query1}")
|
||||
result1 = await agent.run(query1)
|
||||
print(f"Agent: {result1}\n")
|
||||
|
||||
# Wait for memories to be processed
|
||||
print("Waiting for memories to be stored...")
|
||||
await asyncio.sleep(5) # Reduced wait time for demo purposes
|
||||
|
||||
# Second interaction - test memory recall
|
||||
print("=== Second conversation ===")
|
||||
query2 = "Please order my usual coffee"
|
||||
print(f"User: {query2}")
|
||||
result2 = await agent.run(query2)
|
||||
print(f"Agent: {result2}\n")
|
||||
|
||||
# Clean up - delete the memory store
|
||||
async with AIProjectClient(endpoint=endpoint, credential=credential) as project_client:
|
||||
await project_client.memory_stores.delete(memory_store_name)
|
||||
print("Memory store deleted")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,54 @@
|
||||
# Copyright (c) Microsoft. All rights reserved.
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import aiofiles
|
||||
from agent_framework.azure import AzureAIClient
|
||||
from azure.identity.aio import AzureCliCredential
|
||||
|
||||
"""
|
||||
Azure AI Agent with OpenAPI Tool Example
|
||||
|
||||
This sample demonstrates usage of AzureAIClient with OpenAPI tools
|
||||
to call external APIs defined by OpenAPI specifications.
|
||||
|
||||
Prerequisites:
|
||||
1. Set AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_MODEL_DEPLOYMENT_NAME environment variables.
|
||||
2. The countries.json OpenAPI specification is included in the resources folder.
|
||||
"""
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
# Load the OpenAPI specification
|
||||
resources_path = Path(__file__).parent.parent / "resources" / "countries.json"
|
||||
|
||||
async with aiofiles.open(resources_path, "r") as f:
|
||||
content = await f.read()
|
||||
openapi_countries = json.loads(content)
|
||||
|
||||
async with (
|
||||
AzureCliCredential() as credential,
|
||||
AzureAIClient(async_credential=credential).create_agent(
|
||||
name="MyOpenAPIAgent",
|
||||
instructions="""You are a helpful assistant that can use country APIs to provide information.
|
||||
Use the available OpenAPI tools to answer questions about countries, currencies, and demographics.""",
|
||||
tools={
|
||||
"type": "openapi",
|
||||
"openapi": {
|
||||
"name": "get_countries",
|
||||
"spec": openapi_countries,
|
||||
"description": "Retrieve information about countries by currency code",
|
||||
"auth": {"type": "anonymous"},
|
||||
},
|
||||
},
|
||||
) as agent,
|
||||
):
|
||||
query = "What is the name and population of the country that uses currency with abbreviation THB?"
|
||||
print(f"User: {query}")
|
||||
result = await agent.run(query)
|
||||
print(f"Agent: {result}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user