1# pylint: disable=line-too-long,useless-suppression2# ------------------------------------3# Copyright (c) Microsoft Corporation.4# Licensed under the MIT License.5# ------------------------------------6 7"""8DESCRIPTION:9 This sample demonstrates how to use agent operations with the10 Azure AI Search tool from the Azure agents service using a synchronous client.11 12PREREQUISITES:13 You will need an Azure AI Search Resource.14 If you already have one, you must create an agent that can use an existing Azure AI Search index:15 https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/azure-ai-search?tabs=azurecli%2Cpython&pivots=overview-azure-ai-search16 17 If you do not already have an agent Setup with an Azure AI Search resource, follow the guide for a Standard agent setup:18 https://learn.microsoft.com/azure/ai-services/agents/quickstart?pivots=programming-language-python-azure19 20USAGE:21 python sample_agents_azure_ai_search.py22 23 Before running the sample:24 25 pip install azure-ai-projects azure-ai-projects azure-identity26 27 Set these environment variables with your own values:28 1) PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the Overview29 page of your Azure AI Foundry portal.30 2) MODEL_DEPLOYMENT_NAME - The deployment name of the AI model, as found under the "Name" column in31 the "Models + endpoints" tab in your Azure AI Foundry project.32 3) AI_SEARCH_CONNECTION_NAME - The connection name of the AI Search connection to your Foundry project,33 as found under the "Name" column in the "Connected Resources" tab in your Azure AI Foundry project.34"""35 36import os37from azure.ai.projects import AIProjectClient38from azure.ai.projects.models import ConnectionType39from azure.identity import DefaultAzureCredential40from azure.ai.agents.models import AzureAISearchQueryType, AzureAISearchTool, ListSortOrder, MessageRole41 42with AIProjectClient(43 endpoint=os.environ["PROJECT_ENDPOINT"],44 credential=DefaultAzureCredential(),45) as project_client:46 47 # [START create_agent_with_azure_ai_search_tool]48 conn_id = project_client.connections.get_default(ConnectionType.AZURE_AI_SEARCH).id49 50 print(conn_id)51 52 # Initialize agent AI search tool and add the search index connection id53 ai_search = AzureAISearchTool(54 index_connection_id=conn_id,55 index_name="sample_index",56 query_type=AzureAISearchQueryType.SIMPLE,57 top_k=3,58 filter="",59 )60 61 # Create agent with AI search tool and process agent run62 agents_client = project_client.agents63 64 agent = agents_client.create_agent(65 model=os.environ["MODEL_DEPLOYMENT_NAME"],66 name="my-agent",67 instructions="You are a helpful agent",68 tools=ai_search.definitions,69 tool_resources=ai_search.resources,70 )71 # [END create_agent_with_azure_ai_search_tool]72 print(f"Created agent, ID: {agent.id}")73 74 # Create thread for communication75 thread = agents_client.threads.create()76 print(f"Created thread, ID: {thread.id}")77 78 # Create message to thread79 message = agents_client.messages.create(80 thread_id=thread.id,81 role="user",82 content="What is the temperature rating of the cozynights sleeping bag?",83 )84 print(f"Created message, ID: {message.id}")85 86 # Create and process agent run in thread with tools87 run = agents_client.runs.create_and_process(thread_id=thread.id, agent_id=agent.id)88 print(f"Run finished with status: {run.status}")89 90 if run.status == "failed":91 print(f"Run failed: {run.last_error}")92 93 # Fetch run steps to get the details of the agent run94 run_steps = agents_client.run_steps.list(thread_id=thread.id, run_id=run.id)95 for step in run_steps:96 print(f"Step {step['id']} status: {step['status']}")97 step_details = step.get("step_details", {})98 tool_calls = step_details.get("tool_calls", [])99 100 if tool_calls:101 print(" Tool calls:")102 for call in tool_calls:103 print(f" Tool Call ID: {call.get('id')}")104 print(f" Type: {call.get('type')}")105 106 azure_ai_search_details = call.get("azure_ai_search", {})107 if azure_ai_search_details:108 print(f" azure_ai_search input: {azure_ai_search_details.get('input')}")109 print(f" azure_ai_search output: {azure_ai_search_details.get('output')}")110 print() # add an extra newline between steps111 112 # Delete the agent when done113 agents_client.delete_agent(agent.id)114 print("Deleted agent")115 116 # [START populate_references_agent_with_azure_ai_search_tool]117 # Fetch and log all messages118 messages = agents_client.messages.list(thread_id=thread.id, order=ListSortOrder.ASCENDING)119 for message in messages:120 if message.role == MessageRole.AGENT and message.url_citation_annotations:121 placeholder_annotations = {122 annotation.text: f" [see {annotation.url_citation.title}] ({annotation.url_citation.url})"123 for annotation in message.url_citation_annotations124 }125 for message_text in message.text_messages:126 message_str = message_text.text.value127 for k, v in placeholder_annotations.items():128 message_str = message_str.replace(k, v)129 print(f"{message.role}: {message_str}")130 else:131 for message_text in message.text_messages:132 print(f"{message.role}: {message_text.text.value}")133 # [END populate_references_agent_with_azure_ai_search_tool]
Business, governance, and adoption-focused material. Real-world implementations, case studies, and industry impact.