Challenge 22: Azure AI Agent Service
Estimated Time
60 min | Cost: $3-8 (estimated) | Domain: Implement Agentic Solutions (5-10%)
Exam skills covered
- Create an agent with Azure AI Agent Service
- Configure agent tools (file search, code interpreter)
- Manage threads and runs for agent conversations
Overview
Azure AI Agent Service provides a managed platform for building AI agents. It handles thread management, tool execution (file search, code interpreter, custom functions), run lifecycle, and file management.
The architecture: create an agent → create a thread → add messages → create a run → poll until complete → read responses.
Prerequisites
- Azure subscription
- Azure AI Foundry hub and project
- Python 3.9+ or .NET 8
- Packages:
azure-ai-projects,azure-identity
Implementation
Task 1: Set Up Azure AI Foundry Project
az group create --name rg-ai102-foundry-agents --location eastus2
az extension add --name ml
az ml workspace create \
--name hub-ai102-agents \
--resource-group rg-ai102-foundry-agents \
--kind hub \
--location eastus2
Task 2: Create Agent with File Search
- Python SDK
- REST API
import os
import time
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import FilePurpose, FileSearchTool, RunStatus
from azure.identity import DefaultAzureCredential
project_client = AIProjectClient(
credential=DefaultAzureCredential(),
endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
)
# Upload a knowledge file
with open("pricing-info.md", "w") as f:
f.write("# Azure AI Pricing\n- GPT-4o: $2.50/1M input, $10/1M output\n- Vision: $1/1K calls\n")
uploaded_file = project_client.agents.upload_file(
file_path="pricing-info.md",
purpose=FilePurpose.AGENTS
)
vector_store = project_client.agents.create_vector_store_and_poll(
file_ids=[uploaded_file.id],
name="pricing-kb"
)
# Create agent with file search tool
agent = project_client.agents.create_agent(
model="gpt-4o",
name="Pricing Assistant",
instructions="You are a pricing assistant. Use file search to answer questions accurately.",
tools=[FileSearchTool()],
tool_resources={"file_search": {"vector_store_ids": [vector_store.id]}}
)
print(f"Created agent: {agent.id}")
# Create thread and run
thread = project_client.agents.create_thread()
project_client.agents.create_message(
thread_id=thread.id, role="user",
content="How much does GPT-4o cost per million input tokens?"
)
run = project_client.agents.create_run(thread_id=thread.id, agent_id=agent.id)
while run.status in [RunStatus.QUEUED, RunStatus.IN_PROGRESS]:
time.sleep(1)
run = project_client.agents.get_run(thread_id=thread.id, run_id=run.id)
if run.status == RunStatus.COMPLETED:
messages = project_client.agents.list_messages(thread_id=thread.id)
for msg in reversed(messages.data):
if msg.role == "assistant":
for block in msg.content:
if hasattr(block, "text"):
print(f"Assistant: {block.text.value}")
project_client.agents.delete_agent(agent.id)
ENDPOINT="https://<project>.services.ai.azure.com"
API_VERSION="2025-05-01"
TOKEN=$(az account get-access-token --resource https://management.azure.com --query accessToken -o tsv)
# Create agent
curl -s "${ENDPOINT}/agents?api-version=${API_VERSION}" \
-H "Authorization: Bearer ${TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o",
"name": "Pricing Assistant",
"instructions": "Answer pricing questions using file search.",
"tools": [{"type": "file_search"}]
}' | jq .
# Create thread
curl -s "${ENDPOINT}/agents/threads?api-version=${API_VERSION}" \
-H "Authorization: Bearer ${TOKEN}" \
-H "Content-Type: application/json" \
-d '{}' | jq .
# Add message (replace THREAD_ID)
curl -s "${ENDPOINT}/agents/threads/THREAD_ID/messages?api-version=${API_VERSION}" \
-H "Authorization: Bearer ${TOKEN}" \
-H "Content-Type: application/json" \
-d '{"role": "user", "content": "How much does GPT-4o cost?"}' | jq .
# Create run (replace THREAD_ID, AGENT_ID)
curl -s "${ENDPOINT}/agents/threads/THREAD_ID/runs?api-version=${API_VERSION}" \
-H "Authorization: Bearer ${TOKEN}" \
-H "Content-Type: application/json" \
-d '{"assistant_id": "AGENT_ID"}' | jq .
# Poll status (replace THREAD_ID, RUN_ID)
curl -s "${ENDPOINT}/agents/threads/THREAD_ID/runs/RUN_ID?api-version=${API_VERSION}" \
-H "Authorization: Bearer ${TOKEN}" | jq .status
# Get messages
curl -s "${ENDPOINT}/agents/threads/THREAD_ID/messages?api-version=${API_VERSION}" \
-H "Authorization: Bearer ${TOKEN}" | jq '.data[] | select(.role=="assistant")'
Task 3: Code Interpreter Tool
- Python SDK
from azure.ai.projects.models import CodeInterpreterTool
code_agent = project_client.agents.create_agent(
model="gpt-4o",
name="Data Analyst",
instructions="You are a data analyst. Use code interpreter for calculations and charts.",
tools=[CodeInterpreterTool()]
)
thread = project_client.agents.create_thread()
project_client.agents.create_message(
thread_id=thread.id, role="user",
content="Calculate monthly cost: 500K GPT-4o input tokens/day, 100K output/day. Show breakdown."
)
run = project_client.agents.create_and_process_run(
thread_id=thread.id, agent_id=code_agent.id
)
if run.status == RunStatus.COMPLETED:
messages = project_client.agents.list_messages(thread_id=thread.id)
for msg in messages.data:
if msg.role == "assistant":
for block in msg.content:
if hasattr(block, "text"):
print(block.text.value)
project_client.agents.delete_agent(code_agent.id)
Expected Output
Break & fix
| Scenario | Symptom | Root Cause | Fix |
|---|---|---|---|
Run stuck in in_progress | Timeout | Large file indexing or model latency | Use create_and_process_run with timeout; check vector store status |
requires_action status | Run pauses | Agent needs function call results | Submit tool outputs via submit_tool_outputs |
| File search returns nothing | Generic response | File not indexed yet | Wait for vector store completed status before running |
| 404 on thread | Thread not found | Thread ID incorrect or deleted | Verify thread ID; threads persist until explicitly deleted |
| Model deployment error | Agent creation fails | Model not deployed in project | Deploy model via AI Foundry portal first |
Knowledge Check
1. What is the correct sequence for using Azure AI Agent Service?
2. What does the file_search tool provide in Azure AI Agent Service?
3. What is the purpose of the code_interpreter tool?
4. How should you handle the 'requires_action' run status?
5. What is the relationship between agents and threads?
Cleanup
az group delete --name rg-ai102-foundry-agents --yes --no-wait