← Back to portfolio

Azure Technical Guide

Azure AI Lab Guide

Hands-on exercises for nine Azure AI services, with setup steps, Python examples, and practical checks for expected results.

Lab Index

1. Azure OpenAI Service

Objective: Deploy a GPT-4o model and invoke it via Python to generate text completions.

Setup

  1. In the Azure portal, create an Azure OpenAI resource and open Azure OpenAI Studio.
  2. Deploy a model such as GPT-4o and note its deployment name.
  3. Install the openai Python package and run the example below with your resource details.

Quick Lab Code

from openai import AzureOpenAI

client = AzureOpenAI(
    api_key="YOUR_AZURE_OPENAI_KEY",
    api_version="2024-02-01",
    azure_endpoint="https://YOUR_RESOURCE_NAME.openai.azure.com/",
)

response = client.chat.completions.create(
    model="YOUR_GPT_4O_DEPLOYMENT_NAME",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Explain enterprise AI gateways in one sentence."},
    ],
)
print(response.choices[0].message.content)

Validation Test Case 1.1: Happy Path

Input: “Explain enterprise AI gateways in one sentence.”

Expected: A successful response with a coherent, single-sentence definition covering routing, security, and policy governance for AI APIs.

Validate: The response is non-empty, grammatical, and ends with a period.

2. Azure AI Language

Objective: Analyze the sentiment and extract key phrases from customer feedback text.

Setup

  1. Create a Language service resource and copy its endpoint and key.
  2. Install azure-ai-textanalytics, then run the sentiment analysis example.

Quick Lab Code

from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential

endpoint = "https://YOUR_LANGUAGE_RESOURCE.cognitiveservices.azure.com/"
key = "YOUR_LANGUAGE_KEY"
client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))

documents = ["The cloud deployment was seamless, but documentation could be improved."]
response = client.analyze_sentiment(documents=documents)
for document in response:
    print(f"Overall sentiment: {document.sentiment}")
    scores = document.confidence_scores
    print(f"Scores: positive={scores.positive:.2f}, neutral={scores.neutral:.2f}, negative={scores.negative:.2f}")

Validation Test Case 2.1: Mixed Sentiment Analysis

Input: “The cloud deployment was seamless, but documentation could be improved.”

Expected: Sentiment classified as mixed or neutral, with non-zero positive and negative confidence scores.

Validate: Sentiment is returned successfully and confidence scores sum to approximately 1.0.

3. Azure AI Translator

Objective: Translate a sample text block from English into multiple languages simultaneously using the REST API.

Setup

  1. Provision a Translator resource (a free tier is available) and note its key and region.
  2. Install the requests package and submit a translation request.

Quick Lab Code

import json
import uuid
import requests

key = "YOUR_TRANSLATOR_KEY"
endpoint = "https://api.cognitive.microsofttranslator.com"
region = "YOUR_REGION"
params = {"api-version": "3.0", "to": ["es", "fr", "de"]}
headers = {
    "Ocp-Apim-Subscription-Key": key,
    "Ocp-Apim-Subscription-Region": region,
    "Content-type": "application/json",
    "X-ClientTraceId": str(uuid.uuid4()),
}
body = [{"text": "Welcome to enterprise cloud architecture!"}]
response = requests.post(
    f"{endpoint}/translate", params=params, headers=headers, json=body
)
response.raise_for_status()
print(json.dumps(response.json(), indent=4, ensure_ascii=False))

Validation Test Case 3.1: Multi-language Translation

Input: “Welcome to enterprise cloud architecture!” with target languages Spanish (es), French (fr), and German (de).

Expected: A JSON response containing translations for all three languages, including a Spanish equivalent such as “¡Bienvenido a la arquitectura de nube empresarial!”.

Validate: HTTP status is 200 and the response contains a populated translation for every requested language.

5. Azure AI Document Intelligence

Objective: Extract structured data, including tables and key-value pairs, from an invoice PDF.

Setup

  1. Create a Document Intelligence resource and note its endpoint and key.
  2. Install azure-ai-formrecognizer and analyze the sample invoice with the prebuilt invoice model.

Quick Lab Code

from azure.ai.formrecognizer import DocumentAnalysisClient
from azure.core.credentials import AzureKeyCredential

endpoint = "YOUR_DOCUMENT_INTELLIGENCE_ENDPOINT"
key = "YOUR_DOCUMENT_INTELLIGENCE_KEY"
client = DocumentAnalysisClient(endpoint, AzureKeyCredential(key))
invoice_url = (
    "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/"
    "master/form-recognizer/invoice/invoice.pdf"
)
poller = client.begin_analyze_document_from_url("prebuilt-invoice", invoice_url)
result = poller.result()

for invoice in result.documents:
    vendor_name = invoice.fields.get("VendorName")
    if vendor_name:
        print(f"Vendor name: {vendor_name.value}")
    invoice_total = invoice.fields.get("InvoiceTotal")
    if invoice_total:
        print(f"Invoice total: {invoice_total.value} {invoice_total.currency_code}")

Validation Test Case 5.1: Invoice Field Extraction

Input: Process the public sample invoice PDF using the prebuilt-invoice model.

Expected: Extracted VendorName (for example, Contoso) and InvoiceTotal with its currency code.

Validate: The poller succeeds and the extracted field values match the sample document.

6. Azure AI Vision

Objective: Analyze an image to detect tags, objects, and descriptive captions.

Setup

  1. Create a Computer Vision resource and note its endpoint and key.
  2. Install requests, then submit an image URL to the Vision REST API.

Quick Lab Code

import requests

endpoint = "YOUR_VISION_ENDPOINT"
key = "YOUR_VISION_KEY"
analyze_url = f"{endpoint.rstrip('/')}/vision/v3.2/analyze"
image_url = (
    "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d7/"
    "Desktop_computer_clipart_-_Yellow.svg/800px-Desktop_computer_clipart_-_Yellow.svg.png"
)
headers = {"Ocp-Apim-Subscription-Key": key}
params = {"visualFeatures": "Categories,Description,Color"}
response = requests.post(
    analyze_url, headers=headers, params=params, json={"url": image_url}
)
response.raise_for_status()
analysis = response.json()
captions = analysis.get("description", {}).get("captions", [])
if captions:
    print(captions[0]["text"])

Validation Test Case 6.1: Image Caption Generation

Input: The sample desktop-computer clipart image URL.

Expected: A JSON response containing a descriptive caption (for example, “a yellow desktop computer”) and a confidence score.

Validate: HTTP status is 200 and a non-empty caption is returned.

7. Azure AI Speech

Objective: Convert spoken audio from a WAV file into text using speech-to-text.

Setup

  1. Provision a Speech resource and note its key and region.
  2. Install azure-cognitiveservices-speech and provide a WAV file containing clear speech.

Quick Lab Code

import azure.cognitiveservices.speech as speechsdk

speech_key = "YOUR_SPEECH_KEY"
service_region = "YOUR_REGION"
speech_config = speechsdk.SpeechConfig(
    subscription=speech_key, region=service_region
)
audio_config = speechsdk.audio.AudioConfig(filename="your_audio_file.wav")
recognizer = speechsdk.SpeechRecognizer(
    speech_config=speech_config, audio_config=audio_config
)

result = recognizer.recognize_once()
if result.reason == speechsdk.ResultReason.RecognizedSpeech:
    print(f"Recognized: {result.text}")
elif result.reason == speechsdk.ResultReason.NoMatch:
    print("No speech could be recognized.")
elif result.reason == speechsdk.ResultReason.Canceled:
    print(f"Speech recognition canceled: {result.cancellation_details.reason}")

Validation Test Case 7.1: WAV Audio Transcription

Input: A WAV file containing clear speech such as “Test speech recognition”.

Expected: The result reason is RecognizedSpeech and the recognized text matches the spoken phrase.

Validate: The transcription matches the expected test-audio transcript.

8. Azure AI Video Indexer

Objective: Upload a video and explore its automatically generated transcripts and insights.

Setup

  1. Open the Azure AI Video Indexer portal.
  2. Upload a short sample video under three minutes.
  3. Explore the generated timeline, including speech transcription, face detection, OCR, and scene segmentation.

Quick Lab Configuration

Video Indexer is typically managed through its dedicated portal UI or Server-to-Server REST APIs for enterprise pipelines.

Validation Test Case 8.1: Video Indexing Pipeline

Input: Upload an MP4 sample under three minutes through the Video Indexer portal.

Expected: The indexing status changes from Processing to Processed, with a visible transcript and timeline insights.

Validate: The insights dashboard displays speech-to-text transcript blocks and detected visual labels.

9. Azure AI Content Safety

Objective: Check text for harmful or toxic content across hate, self-harm, sexual, and violence categories.

Setup

  1. Create an AI Content Safety resource and note its endpoint and key.
  2. Install azure-ai-contentsafety and submit text for analysis.

Quick Lab Code

from azure.ai.contentsafety import ContentSafetyClient
from azure.ai.contentsafety.models import AnalyzeTextOptions
from azure.core.credentials import AzureKeyCredential

endpoint = "YOUR_CONTENT_SAFETY_ENDPOINT"
key = "YOUR_CONTENT_SAFETY_KEY"
client = ContentSafetyClient(endpoint, AzureKeyCredential(key))
request = AnalyzeTextOptions(text="You are hopeless and should give up.")
response = client.analyze_text(request)
for assessment in response.categories_analysis:
    print(f"Category: {assessment.category}, Severity: {assessment.severity}")

Validation Test Case 9.1: Toxicity & Harassment Detection

Input: “You are hopeless and should give up.”

Expected: Severity ratings on a 0-7 scale for the configured safety categories.

Validate: The API returns HTTP 200 with structured integer severity scores.