Overview
This exercise demonstrates how to create an AI agent using Azure AI Foundry with custom function tools. The agent collects details of a technical issue and generates a support ticket.
Steps & Configuration Details
1. Create an Azure AI Foundry Project
- Open Azure AI Foundry portal (https://ai.azure.com) and sign in.
- Select Create an agent.
- Configuration Items:
- Azure AI Foundry Resource: A valid name.
- Subscription: Your Azure subscription.
- Resource Group: Select or create a resource group.
- Region: Choose any AI Services-supported location.
- Project Name: A unique name.
After creation, the Agents playground opens automatically, with a GPT-4o base model deployed.
2. Clone the Repository
- Open Azure Portal (https://portal.azure.com).
- Launch Azure Cloud Shell (PowerShell environment).
- Clone the repository:
rm -r ai-agents -f git clone https://github.com/MicrosoftLearning/mslearn-ai-agents ai-agents
- Navigate to the correct folder:
cd ai-agents/Labfiles/03-ai-agent-functions/Python
- Install dependencies:
python -m venv labenv ./labenv/bin/Activate.ps1 pip install -r requirements.txt azure-ai-projects
- Open the configuration file:
code .env
- Update Configuration Values:
- Project Endpoint (copied from Azure AI Foundry portal).
- Save the configuration file.
3. Define a Custom Function
- Open the function code file:
code user_functions.py
- Add the function to generate a support ticket:
# Create a function to submit a support ticket def submit_support_ticket(email_address: str, description: str) -> str: script_dir = Path(__file__).parent ticket_number = str(uuid.uuid4()).replace('-', '')[:6] file_name = f"ticket-{ticket_number}.txt" file_path = script_dir / file_name text = f"Support ticket: {ticket_number}\nSubmitted by: {email_address}\nDescription:\n{description}" file_path.write_text(text) message_json = json.dumps({ "message": f"Support ticket {ticket_number} submitted. The ticket file is saved as {file_name}" }) return message_json
- Define the callable function set:
# Define a set of callable functions user_functions: Set[Callable[..., Any]] = {submit_support_ticket}
- Save the file.
4. Implement the AI Agent
- Open the agent code file:
code agent.py
- Add references:
from azure.identity import DefaultAzureCredential from azure.ai.agents import AgentsClient from azure.ai.agents.models import FunctionTool, ToolSet, ListSortOrder, MessageRole from user_functions import user_functions
- Connect to the Agent client:
agent_client = AgentsClient( endpoint=project_endpoint, credential=DefaultAzureCredential( exclude_environment_credential=True, exclude_managed_identity_credential=True ) )
- Define the agent with function tools:
with agent_client: functions = FunctionTool(user_functions) toolset = ToolSet() toolset.add(functions) agent_client.enable_auto_function_calls(toolset) agent = agent_client.create_agent( model=model_deployment, name="support-agent", instructions="""You are a technical support agent. When a user has a technical issue, you get their email address and a description of the issue. Then you use those values to submit a support ticket using the function available to you. If a file is saved, tell the user the file name.""", toolset=toolset ) thread = agent_client.threads.create() print(f"You're chatting with: {agent.name} ({agent.id})")
- Send a prompt to the agent:
message = agent_client.messages.create( thread_id=thread.id, role="user", content=user_prompt ) run = agent_client.runs.create_and_process(thread_id=thread.id, agent_id=agent.id)
- Check for errors:
if run.status == "failed": print(f"Run failed: {run.last_error}")
- Retrieve the latest response:
last_msg = agent_client.messages.get_last_message_text_by_role( thread_id=thread.id, role=MessageRole.AGENT, ) if last_msg: print(f"Last Message: {last_msg.text.value}")
- Get conversation history:
print("\nConversation Log:\n") messages = agent_client.messages.list(thread_id=thread.id, order=ListSortOrder.ASCENDING) for message in messages: if message.text_messages: last_msg = message.text_messages[-1] print(f"{message.role}: {last_msg.text.value}\n")
- Clean up:
agent_client.delete_agent(agent.id) print("Deleted agent")
5. Run the AI Agent
- Sign into Azure:
az login
- Run the application:
python agent.py
- Example prompt:
I have a technical problem.
- The agent should request an email address and issue description.
- Provide an email (e.g.,
[email protected]
). - Submit an issue description:
My computer won't start.
- The agent should generate a support ticket file.
6. Clean Up
- Delete Azure resources to avoid unnecessary costs:
- Open Azure Portal (https://portal.azure.com).
- Navigate to Resource Groups.
- Select the resource group and click Delete.