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 custom functions from9 the Azure Agents service using a synchronous client.10 11USAGE:12 python sample_agents_functions.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"""24import os, time, sys25from azure.ai.projects import AIProjectClient26from azure.identity import DefaultAzureCredential27from azure.ai.agents.models import (28 FunctionTool,29 ListSortOrder,30 RequiredFunctionToolCall,31 SubmitToolOutputsAction,32 ToolOutput,33)34 35current_path = os.path.dirname(__file__)36root_path = os.path.abspath(os.path.join(current_path, os.pardir, os.pardir))37if root_path not in sys.path:38 sys.path.insert(0, root_path)39from samples.utils.user_functions import user_functions40 41project_client = AIProjectClient(42 endpoint=os.environ["PROJECT_ENDPOINT"],43 credential=DefaultAzureCredential(),44)45 46# Initialize function tool with user functions47functions = FunctionTool(functions=user_functions)48 49with project_client:50 agents_client = project_client.agents51 52 # Create an agent and run user's request with function calls53 agent = agents_client.create_agent(54 model=os.environ["MODEL_DEPLOYMENT_NAME"],55 name="my-agent",56 instructions="You are a helpful agent",57 tools=functions.definitions,58 )59 print(f"Created agent, ID: {agent.id}")60 61 thread = agents_client.threads.create()62 print(f"Created thread, ID: {thread.id}")63 64 message = agents_client.messages.create(65 thread_id=thread.id,66 role="user",67 content="Hello, send an email with the datetime and weather information in New York?",68 )69 print(f"Created message, ID: {message.id}")70 71 run = agents_client.runs.create(thread_id=thread.id, agent_id=agent.id)72 print(f"Created run, ID: {run.id}")73 74 while run.status in ["queued", "in_progress", "requires_action"]:75 time.sleep(1)76 run = agents_client.runs.get(thread_id=thread.id, run_id=run.id)77 78 if run.status == "requires_action" and isinstance(run.required_action, SubmitToolOutputsAction):79 tool_calls = run.required_action.submit_tool_outputs.tool_calls80 if not tool_calls:81 print("No tool calls provided - cancelling run")82 agents_client.runs.cancel(thread_id=thread.id, run_id=run.id)83 break84 85 tool_outputs = []86 for tool_call in tool_calls:87 if isinstance(tool_call, RequiredFunctionToolCall):88 try:89 print(f"Executing tool call: {tool_call}")90 output = functions.execute(tool_call)91 tool_outputs.append(92 ToolOutput(93 tool_call_id=tool_call.id,94 output=output,95 )96 )97 except Exception as e:98 print(f"Error executing tool_call {tool_call.id}: {e}")99 100 print(f"Tool outputs: {tool_outputs}")101 if tool_outputs:102 agents_client.runs.submit_tool_outputs(thread_id=thread.id, run_id=run.id, tool_outputs=tool_outputs)103 104 print(f"Current run status: {run.status}")105 106 print(f"Run completed with status: {run.status}")107 108 # Delete the agent when done109 agents_client.delete_agent(agent.id)110 print("Deleted agent")111 112 # Fetch and log all messages113 messages = agents_client.messages.list(thread_id=thread.id, order=ListSortOrder.ASCENDING)114 for msg in messages:115 if msg.text_messages:116 last_text = msg.text_messages[-1]117 print(f"{msg.role}: {last_text.text.value}")
Ecosystems, libraries, and foundations to build on. Orchestration frameworks, agent platforms, and development foundations.