
1# ------------------------------------2# Copyright (c) Microsoft Corporation.3# Licensed under the MIT License.4# ------------------------------------5 6"""7DESCRIPTION:8 This sample demonstrates how to use agent operations with file searching from9 the Azure Agents service using a synchronous client.10 11USAGE:12 python sample_agents_file_search.py13 14 Before running the sample:15 16 pip install azure-ai-projects azure-ai-agents azure-identity17 18 Set these environment variables with your own values:19 1) PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the Overview20 page of your Azure AI Foundry portal.21 2) MODEL_DEPLOYMENT_NAME - The deployment name of the AI model, as found under the "Name" column in22 the "Models + endpoints" tab in your Azure AI Foundry project.23"""24 25import os26from azure.ai.projects import AIProjectClient27from azure.ai.agents.models import (28 FilePurpose,29 FileSearchTool,30 ListSortOrder,31 RunAdditionalFieldList,32 RunStepFileSearchToolCall,33 RunStepToolCallDetails,34)35from azure.identity import DefaultAzureCredential36 37asset_file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../assets/product_info_1.md"))38 39project_client = AIProjectClient(40 endpoint=os.environ["PROJECT_ENDPOINT"],41 credential=DefaultAzureCredential(),42)43 44with project_client:45 agents_client = project_client.agents46 47 # Upload file and create vector store48 # [START upload_file_create_vector_store_and_agent_with_file_search_tool]49 file = agents_client.files.upload_and_poll(file_path=asset_file_path, purpose=FilePurpose.AGENTS)50 print(f"Uploaded file, file ID: {file.id}")51 52 vector_store = agents_client.vector_stores.create_and_poll(file_ids=[file.id], name="my_vectorstore")53 print(f"Created vector store, vector store ID: {vector_store.id}")54 55 # Create file search tool with resources followed by creating agent56 file_search = FileSearchTool(vector_store_ids=[vector_store.id])57 58 agent = agents_client.create_agent(59 model=os.environ["MODEL_DEPLOYMENT_NAME"],60 name="my-agent",61 instructions="Hello, you are helpful agent and can search information from uploaded files",62 tools=file_search.definitions,63 tool_resources=file_search.resources,64 )65 # [END upload_file_create_vector_store_and_agent_with_file_search_tool]66 67 print(f"Created agent, ID: {agent.id}")68 69 # Create thread for communication70 thread = agents_client.threads.create()71 print(f"Created thread, ID: {thread.id}")72 73 # Create message to thread74 message = agents_client.messages.create(75 thread_id=thread.id, role="user", content="Hello, what Contoso products do you know?"76 )77 print(f"Created message, ID: {message.id}")78 79 # Create and process agent run in thread with tools80 run = agents_client.runs.create_and_process(81 thread_id=thread.id,82 agent_id=agent.id,83 )84 print(f"Run finished with status: {run.status}")85 86 if run.status == "failed":87 # Check if you got "Rate limit is exceeded.", then you want to get more quota88 print(f"Run failed: {run.last_error}")89 90 # [START teardown]91 # Delete the file when done92 agents_client.vector_stores.delete(vector_store.id)93 print("Deleted vector store")94 95 agents_client.files.delete(file_id=file.id)96 print("Deleted file")97 98 # Delete the agent when done99 agents_client.delete_agent(agent.id)100 print("Deleted agent")101 # [END teardown]102 103 for run_step in agents_client.run_steps.list(104 thread_id=thread.id, run_id=run.id, include=[RunAdditionalFieldList.FILE_SEARCH_CONTENTS]105 ):106 if isinstance(run_step.step_details, RunStepToolCallDetails):107 for tool_call in run_step.step_details.tool_calls:108 if (109 isinstance(tool_call, RunStepFileSearchToolCall)110 and tool_call.file_search111 and tool_call.file_search.results112 and tool_call.file_search.results[0].content113 and tool_call.file_search.results[0].content[0].text114 ):115 print(116 "The search tool has found the next relevant content in "117 f"the file {tool_call.file_search.results[0].file_name}:"118 )119 # Note: technically we may have several search results, however in our example120 # we only have one file, so we are taking the only result.121 print(tool_call.file_search.results[0].content[0].text)122 print("===============================================================")123 124 # Fetch and log all messages125 messages = agents_client.messages.list(thread_id=thread.id, order=ListSortOrder.ASCENDING)126 127 # Print last messages from the thread128 file_name = os.path.split(asset_file_path)[-1]129 for msg in messages:130 if msg.text_messages:131 last_text = msg.text_messages[-1].text.value132 for annotation in msg.text_messages[-1].text.annotations:133 citation = (134 file_name if annotation.file_citation.file_id == file.id else annotation.file_citation.file_id135 )136 last_text = last_text.replace(annotation.text, f" [{citation}]")137 print(f"{msg.role}: {last_text}")Developer SDKs, repos, connectors, and infrastructure helpers. APIs, development tools, and integration resources.