Build AI solutions with Azure AI services including OpenAI, Cognitive Services, Document Intelligence, and AI Search. Use for enterprise AI, document processing, and intelligent applications on Azure.
Build AI solutions with Azure AI services including OpenAI, Cognitive Services, Document Intelligence, and AI Search. Use for enterprise AI, document processing, and intelligent applications on Azure.
Azure AI Skill
Complete guidance for building, configuring, troubleshooting, and managing Azure AI services.
Quick Reference
Service Categories
Category
Services
AI Platform
Microsoft Foundry (Azure AI Foundry), Azure AI Hub, AI Projects
Generative AI
Azure OpenAI Service (GPT-4, GPT-4o, o1, DALL-E, Whisper)
Search & RAG
Azure AI Search (vector, semantic, hybrid, agentic retrieval)
AI Agents
Azure AI Agent Service, Foundry Agent Service, Multi-agent Orchestration
Document AI
Document Intelligence (OCR, form extraction, prebuilt models)
# Create resource group
az group create --name rg-ai-foundry --location eastus
# Create AI Hub (shared infrastructure)
az ml workspace create \
--name ai-hub-prod \
--resource-group rg-ai-foundry \
--kind hub \
--location eastus
# Create AI Project (linked to hub)
az ml workspace create \
--name ai-project-chatbot \
--resource-group rg-ai-foundry \
--kind project \
--hub-id /subscriptions/{sub}/resourceGroups/rg-ai-foundry/providers/Microsoft.MachineLearningServices/workspaces/ai-hub-prod
Python SDK Setup
# Install SDK# pip install azure-ai-projects azure-identityfrom azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
# Initialize client
project = AIProjectClient(
credential=DefaultAzureCredential(),
endpoint="https://<hub-name>.api.azureml.ms",
project_name="ai-project-chatbot"
)
# List models in projectfor model in project.models.list():
print(f"{model.name}: {model.description}")
Connections Management
# List connections in hub
az ml connection list --workspace-name ai-hub-prod --resource-group rg-ai-foundry
# Create Azure OpenAI connection
az ml connection create \
--file connection.yml \
--workspace-name ai-hub-prod \
--resource-group rg-ai-foundry
# List all deployments
az cognitiveservices account deployment list \
--name openai-prod \
--resource-group rg-ai \
--output table
# List available models in region
az cognitiveservices account list-models \
--name openai-prod \
--resource-group rg-ai
from azure.search.documents import SearchClient
from azure.search.documents.models import VectorizedQuery
search_client = SearchClient(
endpoint="https://search-prod.search.windows.net",
index_name="documents-index",
credential=AzureKeyCredential("<query-key>")
)
# Get query embedding (from Azure OpenAI)
query_embedding = get_embedding("What is machine learning?")
# Hybrid search (keyword + vector)
results = search_client.search(
search_text="machine learning",
vector_queries=[
VectorizedQuery(
vector=query_embedding,
k_nearest_neighbors=5,
fields="content_vector"
)
],
query_type="semantic",
semantic_configuration_name="semantic-config",
top=10
)
for result in results:
print(f"{result['title']}: {result['@search.score']}")
Agentic Retrieval (Knowledge Store)
# pip install azure-ai-projectsfrom azure.ai.projects import AIProjectClient
from azure.ai.projects.models import AgentKnowledgeStore
# Create knowledge store linked to search index
knowledge_store = project.agents.knowledge_stores.create(
name="docs-knowledge",
index_name="documents-index",
search_endpoint="https://search-prod.search.windows.net",
semantic_configuration="semantic-config"
)
# Use in agent
agent = project.agents.create(
name="doc-assistant",
model="gpt-4o",
knowledge_store_ids=[knowledge_store.id]
)
4. Azure AI Agents
Agent Types
Type
Description
Use Case
Foundry Agent
Managed agent with tools
Chat assistants
Code Interpreter
Python execution sandbox
Data analysis
File Search
Document retrieval
RAG applications
Function Calling
Custom function execution
API integration
Multi-Agent
Orchestrated agent swarm
Complex workflows
Create Basic Agent
# pip install azure-ai-projects azure-ai-agentsfrom azure.ai.projects import AIProjectClient
from azure.ai.agents import AgentsClient
from azure.identity import DefaultAzureCredential
# Initialize
project = AIProjectClient(
credential=DefaultAzureCredential(),
endpoint="https://<hub>.api.azureml.ms",
project_name="my-project"
)
# Create agent with tools
agent = project.agents.create_agent(
model="gpt-4o",
name="data-analyst",
instructions="You are a data analyst. Analyze data and create visualizations.",
tools=[
{"type": "code_interpreter"},
{"type": "file_search"}
]
)
# Create thread and run
thread = project.agents.create_thread()
message = project.agents.create_message(
thread_id=thread.id,
role="user",
content="Analyze the sales data and create a trend chart"
)
run = project.agents.create_run(
thread_id=thread.id,
agent_id=agent.id
)
# Wait for completionimport time
while run.status in ["queued", "in_progress"]:
time.sleep(1)
run = project.agents.get_run(thread_id=thread.id, run_id=run.id)
# Get response
messages = project.agents.list_messages(thread_id=thread.id)
for msg in messages.data:
if msg.role == "assistant":
print(msg.content[0].text.value)
Function Calling Agent
# Define custom functions
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"]
}
},
"required": ["location"]
}
}
}
]
agent = project.agents.create_agent(
model="gpt-4o",
name="weather-assistant",
instructions="Help users with weather information.",
tools=tools
)
# Handle function calls in run loopwhile run.status == "requires_action":
tool_calls = run.required_action.submit_tool_outputs.tool_calls
tool_outputs = []
for call in tool_calls:
if call.function.name == "get_weather":
args = json.loads(call.function.arguments)
result = fetch_weather(args["location"]) # Your function
tool_outputs.append({
"tool_call_id": call.id,
"output": json.dumps(result)
})
run = project.agents.submit_tool_outputs(
thread_id=thread.id,
run_id=run.id,
tool_outputs=tool_outputs
)
Multi-Agent Orchestration
# Supervisor pattern - one agent coordinates others
supervisor = project.agents.create_agent(
model="gpt-4o",
name="supervisor",
instructions="""You are a supervisor coordinating a team:
- researcher: Finds information
- writer: Creates content
- reviewer: Reviews and edits
Delegate tasks and synthesize results."""
)
researcher = project.agents.create_agent(
model="gpt-4o",
name="researcher",
instructions="You research topics and provide factual information.",
tools=[{"type": "file_search"}]
)
writer = project.agents.create_agent(
model="gpt-4o",
name="writer",
instructions="You write clear, engaging content based on research."
)
reviewer = project.agents.create_agent(
model="gpt-4o",
name="reviewer",
instructions="You review content for accuracy, clarity, and style."
)
# Orchestration logic handles routing between agents
# pip install azure-ai-vision-imageanalysisfrom azure.ai.vision.imageanalysis import ImageAnalysisClient
from azure.ai.vision.imageanalysis.models import VisualFeatures
from azure.core.credentials import AzureKeyCredential
client = ImageAnalysisClient(
endpoint="https://vision-prod.cognitiveservices.azure.com",
credential=AzureKeyCredential("<key>")
)
# Analyze image
result = client.analyze(
image_url="https://example.com/image.jpg",
visual_features=[
VisualFeatures.CAPTION,
VisualFeatures.TAGS,
VisualFeatures.OBJECTS,
VisualFeatures.DENSE_CAPTIONS,
VisualFeatures.READ, # OCR
VisualFeatures.SMART_CROPS,
VisualFeatures.PEOPLE
]
)
print(f"Caption: {result.caption.text} ({result.caption.confidence:.2f})")
print(f"Tags: {', '.join([t.name for t in result.tags.list])}")
for obj in result.objects.list:
print(f"Object: {obj.tags[0].name} at {obj.bounding_box}")
Speech
# pip install azure-cognitiveservices-speechimport azure.cognitiveservices.speech as speechsdk
speech_config = speechsdk.SpeechConfig(
subscription="<key>",
region="eastus"
)
# Speech-to-text
audio_config = speechsdk.AudioConfig(filename="audio.wav")
recognizer = speechsdk.SpeechRecognizer(
speech_config=speech_config,
audio_config=audio_config
)
result = recognizer.recognize_once()
print(f"Recognized: {result.text}")
# Text-to-speech
speech_config.speech_synthesis_voice_name = "en-US-JennyNeural"
synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config)
result = synthesizer.speak_text_async("Hello, this is Azure Speech.").get()
audio_data = result.audio_data
Language
# pip install azure-ai-textanalyticsfrom azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential
client = TextAnalyticsClient(
endpoint="https://language-prod.cognitiveservices.azure.com",
credential=AzureKeyCredential("<key>")
)
documents = ["Azure AI is amazing! I love using it for my projects."]
# Sentiment analysis
result = client.analyze_sentiment(documents)[0]
print(f"Sentiment: {result.sentiment} ({result.confidence_scores})")
# Key phrase extraction
result = client.extract_key_phrases(documents)[0]
print(f"Key phrases: {result.key_phrases}")
# Entity recognition
result = client.recognize_entities(documents)[0]
for entity in result.entities:
print(f"Entity: {entity.text} ({entity.category})")
# Language detection
result = client.detect_language(documents)[0]
print(f"Language: {result.primary_language.name}")
Translator
# pip install azure-ai-translation-textfrom azure.ai.translation.text import TextTranslationClient
from azure.core.credentials import AzureKeyCredential
client = TextTranslationClient(
credential=AzureKeyCredential("<key>"),
region="eastus"
)
# Translate text
result = client.translate(
body=["Hello, how are you?"],
to_language=["es", "fr", "de"]
)
for translation in result[0].translations:
print(f"{translation.to}: {translation.text}")
# Detect language
result = client.detect_language(body=["Bonjour le monde"])
print(f"Detected: {result[0].language} ({result[0].score})")
# pip install azure-ai-contentsafetyfrom azure.ai.contentsafety import ContentSafetyClient
from azure.ai.contentsafety.models import AnalyzeTextOptions, TextCategory
from azure.core.credentials import AzureKeyCredential
client = ContentSafetyClient(
endpoint="https://content-safety-prod.cognitiveservices.azure.com",
credential=AzureKeyCredential("<key>")
)
# Analyze text
request = AnalyzeTextOptions(
text="Sample text to analyze for safety",
categories=[
TextCategory.HATE,
TextCategory.VIOLENCE,
TextCategory.SEXUAL,
TextCategory.SELF_HARM
]
)
result = client.analyze_text(request)
for category_result in result.categories_analysis:
print(f"{category_result.category}: severity {category_result.severity}")
# Check if content should be blocked (threshold-based)defshould_block(result, threshold=4):
for cat in result.categories_analysis:
if cat.severity >= threshold:
returnTruereturnFalseif should_block(result):
print("Content blocked due to safety concerns")
Image Moderation
from azure.ai.contentsafety.models import AnalyzeImageOptions, ImageData
# Analyze imagewithopen("image.jpg", "rb") as f:
image_data = f.read()
request = AnalyzeImageOptions(
image=ImageData(content=image_data)
)
result = client.analyze_image(request)
for category in result.categories_analysis:
print(f"{category.category}: {category.severity}")
8. Azure Machine Learning
Workspace Management
# Create ML workspace
az ml workspace create \
--name ml-workspace-prod \
--resource-group rg-ai \
--location eastus
# List workspaces
az ml workspace list --resource-group rg-ai --output table
# Create compute cluster
az ml compute create \
--name gpu-cluster \
--type AmlCompute \
--size Standard_NC6s_v3 \
--min-instances 0 \
--max-instances 4 \
--workspace-name ml-workspace-prod \
--resource-group rg-ai
from azure.ai.evaluation import HateSpeechEvaluator, ViolenceEvaluator
# Evaluate model outputs for harmful content
hate_evaluator = HateSpeechEvaluator()
violence_evaluator = ViolenceEvaluator()
# Batch evaluation
results = []
for response in model_responses:
hate_score = hate_evaluator.evaluate(response=response)
violence_score = violence_evaluator.evaluate(response=response)
results.append({
"response": response,
"hate_score": hate_score,
"violence_score": violence_score
})
Troubleshooting
Common Issues
Authentication Errors
# Check logged in identity
az account show
# Re-login
az login
# Use service principal
az login --service-principal -u <app-id> -p <password> --tenant <tenant-id>
# Check role assignments
az role assignment list --assignee <identity>
Quota Exceeded
# Check current usage
az cognitiveservices usage list \
--name openai-prod \
--resource-group rg-ai
# Request quota increase via Azure Portal > Quotas
Model Not Available
# List available models in region
az cognitiveservices account list-models \
--name openai-prod \
--resource-group rg-ai \
--output table
# Check model availability by region# https://learn.microsoft.com/azure/ai-services/openai/concepts/models
Rate Limiting (429 Errors)
import time
from tenacity import retry, wait_exponential, stop_after_attempt
@retry(wait=wait_exponential(min=1, max=60), stop=stop_after_attempt(5))defcall_with_retry():
return client.chat.completions.create(...)
Search Index Issues
# Check index status
az search service show --name search-prod --resource-group rg-ai
# Rebuild index# Use indexer reset via REST API or SDK