1# pylint: disable=line-too-long,useless-suppression
2# ------------------------------------
3# Copyright (c) Microsoft Corporation.
4# Licensed under the MIT License.
5# ------------------------------------
6
7"""
8DESCRIPTION:
9 This sample demonstrates how to use agents with Logic Apps to execute the task of sending an email.
10
11PREREQUISITES:
12 1) Create a Logic App within the same resource group as your Azure AI Project in Azure Portal
13 2) To configure your Logic App to send emails, you must include an HTTP request trigger that is
14 configured to accept JSON with 'to', 'subject', and 'body'. The guide to creating a Logic App Workflow
15 can be found here:
16 https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/agents-logic-apps#create-logic-apps-workflows-for-function-calling
17
18USAGE:
19 python sample_agents_logic_apps.py
20
21 Before running the sample:
22
23 pip install azure-ai-projects azure-ai-agents azure-identity azure-mgmt-logic
24
25 Set this environment variables with your own values:
26 1) PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the Overview
27 page of your Azure AI Foundry portal.
28 2) MODEL_DEPLOYMENT_NAME - The deployment name of the AI model, as found under the "Name" column in
29 the "Models + endpoints" tab in your Azure AI Foundry project.
30
31 Replace the following values in the sample with your own values:
32 1) <LOGIC_APP_NAME> - The name of the Logic App you created.
33 2) <TRIGGER_NAME> - The name of the trigger in the Logic App you created (the default name for HTTP
34 triggers in the Azure Portal is "When_a_HTTP_request_is_received").
35 3) <RECIPIENT_EMAIL> - The email address of the recipient.
36"""
37
38import os
39import sys
40from typing import Set
41
42from azure.ai.projects import AIProjectClient
43from azure.ai.agents.models import ToolSet, FunctionTool
44from azure.identity import DefaultAzureCredential
45
46# Example user function
47current_path = os.path.dirname(__file__)
48root_path = os.path.abspath(os.path.join(current_path, os.pardir, os.pardir))
49if root_path not in sys.path:
50 sys.path.insert(0, root_path)
51from samples.utils.user_functions import fetch_current_datetime
52
53# Import AzureLogicAppTool and the function factory from user_logic_apps
54from utils.user_logic_apps import AzureLogicAppTool, create_send_email_function
55
56# Create the agents client
57project_client = AIProjectClient(
58 endpoint=os.environ["PROJECT_ENDPOINT"],
59 credential=DefaultAzureCredential(),
60)
61
62# [START register_logic_app]
63# Extract subscription and resource group from the project scope
64subscription_id = os.environ["SUBSCRIPTION_ID"]
65resource_group = os.environ["resource_group_name"]
66
67# Logic App details
68logic_app_name = "<LOGIC_APP_NAME>"
69trigger_name = "<TRIGGER_NAME>"
70
71# Create and initialize AzureLogicAppTool utility
72logic_app_tool = AzureLogicAppTool(subscription_id, resource_group)
73logic_app_tool.register_logic_app(logic_app_name, trigger_name)
74print(f"Registered logic app '{logic_app_name}' with trigger '{trigger_name}'.")
75
76# Create the specialized "send_email_via_logic_app" function for your agent tools
77send_email_func = create_send_email_function(logic_app_tool, logic_app_name)
78
79# Prepare the function tools for the agent
80functions_to_use: Set = {
81 fetch_current_datetime,
82 send_email_func, # This references the AzureLogicAppTool instance via closure
83}
84# [END register_logic_app]
85
86with project_client:
87 agents_client = project_client.agents
88
89 # Create an agent
90 functions = FunctionTool(functions=functions_to_use)
91 toolset = ToolSet()
92 toolset.add(functions)
93
94 agents_client.enable_auto_function_calls(toolset)
95
96 agent = agents_client.create_agent(
97 model=os.environ["MODEL_DEPLOYMENT_NAME"],
98 name="SendEmailAgent",
99 instructions="You are a specialized agent for sending emails.",
100 toolset=toolset,
101 )
102 print(f"Created agent, ID: {agent.id}")
103
104 # Create a thread for communication
105 thread = agents_client.threads.create()
106 print(f"Created thread, ID: {thread.id}")
107
108 # Create a message in the thread
109 message = agents_client.messages.create(
110 thread_id=thread.id,
111 role="user",
112 content="Hello, please send an email to <RECIPIENT_EMAIL> with the date and time in '%Y-%m-%d %H:%M:%S' format.",
113 )
114 print(f"Created message, ID: {message.id}")
115
116 # Create and process an agent run in the thread
117 run = agents_client.runs.create_and_process(thread_id=thread.id, agent_id=agent.id)
118 print(f"Run finished with status: {run.status}")
119
120 if run.status == "failed":
121 print(f"Run failed: {run.last_error}")
122
123 # Delete the agent when done
124 agents_client.delete_agent(agent.id)
125 print("Deleted agent")
126
127 # Fetch and log all messages
128 messages = agents_client.messages.list(thread_id=thread.id)
129 for msg in messages:
130 if msg.text_messages:
131 last_text = msg.text_messages[-1]
132 print(f"{msg.role}: {last_text.text.value}")