{"id":51069647,"url":"https://github.com/learning-zone/azure-ai-basics","last_synced_at":"2026-06-23T09:32:12.881Z","repository":{"id":356211654,"uuid":"1231521926","full_name":"learning-zone/azure-ai-basics","owner":"learning-zone","description":"Artificial Intelligence and Machine Learning Basics","archived":false,"fork":false,"pushed_at":"2026-06-01T04:52:13.000Z","size":869,"stargazers_count":3,"open_issues_count":0,"forks_count":1,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-06-01T06:24:17.066Z","etag":null,"topics":["artificial-intelligence","azure-ai","github-copilot","machine-learning"],"latest_commit_sha":null,"homepage":"https://learning-zone.github.io/azure-ai-basics/","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/learning-zone.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-05-07T03:24:12.000Z","updated_at":"2026-06-01T04:52:17.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/learning-zone/azure-ai-basics","commit_stats":null,"previous_names":["learning-zone/ai-and-ml-basics","learning-zone/azure-ai-basics"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/learning-zone/azure-ai-basics","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learning-zone%2Fazure-ai-basics","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learning-zone%2Fazure-ai-basics/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learning-zone%2Fazure-ai-basics/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learning-zone%2Fazure-ai-basics/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/learning-zone","download_url":"https://codeload.github.com/learning-zone/azure-ai-basics/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learning-zone%2Fazure-ai-basics/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34684673,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-23T02:00:07.161Z","response_time":65,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["artificial-intelligence","azure-ai","github-copilot","machine-learning"],"created_at":"2026-06-23T09:32:11.850Z","updated_at":"2026-06-23T09:32:12.868Z","avatar_url":"https://github.com/learning-zone.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Microsoft Azure AI Basics\n\n\u003e *Click \u0026#9733; if you like the project. Your contributions are heartily ♡ welcome.*\n\n\u003cbr\u003e\n\n## Related Topics\n\n* *[AI and ML Basics](ai-and-ml-basics)*\n* *[Mathematics for AI](mathematics-for-ai.md)*\n* *[Python Basics](https://github.com/learning-zone/python-basics)*\n* *[GitHub Copilot](github-copilot.md)*\n\n\u003cbr\u003e\n\n## Table of Contents\n\n* **Foundations**\n   * [Getting Started](#-1-getting-started)\n   * [Getting Started with C# and .NET SDK](#q-how-do-you-get-started-with-azure-ai-using-c-and-the-net-sdk)\n   * [Azure OpenAI Service in C#](#q-how-do-you-call-azure-openai-service-from-a-c-application)\n   * [Azure AI Vision \u0026 Document Intelligence in C#](#q-how-do-you-use-azure-ai-vision-and-document-intelligence-in-c)\n   * [Azure AI Speech Service in C#](#q-how-do-you-integrate-azure-ai-speech-service-in-a-c-application)\n* **Enterprise AI \u0026 Development Platforms**\n   * [Azure AI Foundry Overview](#-2-azure-ai-foundry-overview)\n   * [Azure AI Foundry with C# .NET SDK](#q-how-do-you-interact-with-azure-ai-foundry-using-the-c-net-sdk)\n   * [Azure OpenAI Service](#-3-azure-openai-service)\n   * [Function Calling \u0026 Embeddings in C#](#q-how-do-you-use-function-calling-and-generate-embeddings-with-azure-openai-in-c)\n   * [Foundry Tools \u0026 Catalogs](#-4-foundry-tools-and-catalogs)\n   * [Model Catalog \u0026 Deployment in C#](#q-how-do-you-browse-and-deploy-models-from-the-azure-ai-foundry-model-catalog-using-c)\n   * [Azure Machine Learning (AML)](#-5-azure-machine-learning-aml)\n   * [AML Workspace \u0026 Jobs in C#](#q-how-do-you-manage-azure-machine-learning-workspaces-and-submit-training-jobs-from-c)\n* **Vision \u0026 Multimodal**\n   * [Azure Vision Services](#-6-azure-vision-services)\n   * [Image Analysis \u0026 OCR in C#](#q-how-do-you-perform-image-analysis-and-ocr-using-azure-ai-vision-in-c)\n   * [Azure Custom Vision](#-7-azure-custom-vision)\n   * [Custom Vision Training \u0026 Prediction in C#](#q-how-do-you-train-and-call-an-azure-custom-vision-model-from-c)\n   * [Azure Face API](#-8-azure-face-api)\n   * [Face Detection \u0026 Verification in C#](#q-how-do-you-detect-faces-and-check-liveness-using-the-azure-face-api-in-c)\n   * [Azure AI Document Intelligence](#-9-azure-ai-document-intelligence)\n   * [Document Extraction in C#](#q-how-do-you-extract-structured-data-from-documents-using-azure-document-intelligence-in-c)\n* **Language \u0026 Conversational AI**\n   * [Azure AI Language](#-10-azure-ai-language)\n   * [Azure AI Language NLP in C#](#q-how-do-you-use-azure-ai-language-service-for-nlp-tasks-in-c)\n   * [Azure AI Translator](#-11-azure-ai-translator)\n   * [Text Translation \u0026 Language Detection in C#](#q-how-do-you-translate-text-and-detect-languages-using-azure-translator-in-c)\n   * [Azure AI Speech](#-12-azure-ai-speech)\n   * [Speech-to-Text, TTS \u0026 Translation in C#](#q-how-do-you-implement-real-time-speech-to-text-tts-and-speech-translation-in-c)\n   * [Microsoft Copilot Studio \u0026 Agents SDK](#-13-microsoft-copilot-studio-and-agents-sdk)\n   * [AI Agents SDK \u0026 Copilot Studio in C#](#q-how-do-you-build-an-ai-agent-with-the-azure-ai-agents-sdk-and-integrate-it-with-copilot-studio-using-c)\n* **Search \u0026 Knowledge Engineering**\n   * [Azure AI Search (formerly Cognitive Search)](#-14-azure-ai-search-formerly-cognitive-search)\n   * [Azure AI Search full-text, filtered \u0026 semantic in C#](#q-how-do-you-create-a-search-index-and-run-full-text-filtered-and-semantic-queries-with-azure-ai-search-in-c)\n   * [Azure Knowledge Mining](#-15-azure-knowledge-mining)\n   * [AI Enrichment Pipeline with Knowledge Mining in C#](#q-how-do-you-build-an-ai-enrichment-pipeline-with-azure-knowledge-mining-in-c)\n   * [Vector Search \u0026 Embedding Spaces](#-16-azure-openai-embeddings--vector-search)\n   * [Vector Search \u0026 RAG pipeline in C#](#q-how-do-you-implement-vector-search-and-a-rag-pipeline-using-azure-ai-search-and-azure-openai-in-c)\n* **Machine Learning \u0026 MLOps**\n   * [Automated ML (AutoML)](#-17-automated-ml-automl)\n   * [AutoML Forecasting Job in C#](#q-how-do-you-run-an-automl-job-in-azure-machine-learning-using-c)\n   * [Azure ML Designer](#-18-azure-ml-designer)\n   * [Trigger ML Designer Pipeline in C#](#q-how-do-you-trigger-and-monitor-an-azure-ml-designer-pipeline-from-c)\n   * [Azure ML Pipelines](#-19-azure-ml-pipelines)\n   * [Multi-step ML Pipeline in C#](#q-how-do-you-build-and-run-a-multi-step-azure-ml-pipeline-from-c)\n   * [Model Training and Hyperparameter Tuning](#-20-model-training-and-hyperparameter-tuning)\n   * [Hyperparameter Sweep Job in C#](#q-how-do-you-run-a-hyperparameter-sweep-job-in-azure-ml-using-c)\n   * [Model Deployment and Endpoints](#-21-model-deployment-and-endpoints)\n   * [Managed Online Endpoint \u0026 Scoring in C#](#q-how-do-you-create-a-managed-online-endpoint-and-invoke-it-from-c)\n   * [MLOps on Azure](#-22-mlops-on-azure)\n   * [Full MLOps CI/CD Pipeline in C#](#q-how-do-you-implement-an-mlops-cicd-pipeline-for-azure-ml-entirely-from-c)\n* **Generative AI \u0026 Agentic Orchestration**\n   * [Prompt Engineering on Azure OpenAI](#-23-prompt-engineering-on-azure-openai)\n   * [Advanced Prompt Engineering in C#](#q-how-do-you-apply-prompt-engineering-techniques-with-azure-openai-in-c)\n   * [Retrieval-Augmented Generation (RAG)](#-24-retrieval-augmented-generation-rag)\n   * [Production RAG Pipeline in C#](#q-how-do-you-build-a-production-ready-rag-pipeline-with-azure-ai-search-and-azure-openai-in-c)\n   * [Fine-Tuning Large Language Models](#-25-fine-tuning-large-language-models)\n   * [Fine-Tune \u0026 Deploy OpenAI Model in C#](#q-how-do-you-fine-tune-an-azure-openai-model-and-deploy-it-using-c)\n   * [Azure AI Agents \u0026 Function Calling](#-26-azure-ai-agents-and-function-calling)\n   * [Stateful AI Agent with Function Calling in C#](#q-how-do-you-build-a-stateful-ai-agent-with-function-calling-and-file-search-using-the-azure-ai-agents-sdk-in-c)\n* **Data Engineering \u0026 Infrastructure**\n   * [Azure Data Factory for AI Pipelines](#-27-azure-data-factory-for-ai-pipelines)\n   * [ADF Pipeline Orchestration for AI in C#](#q-how-do-you-orchestrate-an-azure-data-factory-pipeline-for-ai-data-ingestion-using-c)\n   * [Azure Databricks and Spark ML](#-28-azure-databricks-and-spark-ml)\n   * [Trigger Databricks ML Jobs from C#](#q-how-do-you-trigger-and-monitor-azure-databricks-notebook-jobs-for-ml-workloads-from-c)\n   * [Azure Synapse \u0026 Fabric Integration](#-29-azure-synapse-and-fabric-integration)\n   * [Synapse AI Pipelines \u0026 Spark Jobs in C#](#q-how-do-you-use-azure-synapse-analytics-to-orchestrate-ai-pipelines-and-invoke-azure-ml-models-from-c)\n   * [Azure AI Infrastructure (GPU Clusters, ND-Series)](#-30-azure-ai-infrastructure-gpu-clusters-nd-series)\n   * [GPU Clusters \u0026 Distributed Training in C#](#q-how-do-you-provision-gpu-compute-clusters-and-submit-distributed-training-jobs-on-azure-ai-infrastructure-using-c)\n* **Responsible AI \u0026 Safety**\n   * [Azure Responsible AI Principles](#-31-azure-responsible-ai-principles)\n   * [Responsible AI Checks \u0026 Model Card in C#](#q-how-do-you-implement-responsible-ai-checks-and-generate-a-rai-dashboard-report-using-c)\n   * [Fairness, Interpretability, and Explainability](#-32-fairness-interpretability-and-explainability)\n   * [Fairness Metrics \u0026 SHAP Explainability in C#](#q-how-do-you-assess-model-fairness-and-generate-shap-explainability-reports-using-c)\n   * [Azure AI Content Safety](#-33-azure-ai-content-safety)\n   * [Content Moderation \u0026 Prompt Shield in C#](#q-how-do-you-moderate-ai-generated-content-and-detect-prompt-injection-using-azure-ai-content-safety-in-c)\n   * [Differential Privacy and Confidential AI](#-34-differential-privacy-and-confidential-ai)\n   * [Differential Privacy for ML Training in C#](#q-how-do-you-apply-differential-privacy-to-ml-model-training-and-protect-sensitive-data-in-azure-ai-using-c)\n* **Security \u0026 Governance**\n   * [Azure AI Security Best Practices](#-35-azure-ai-security-best-practices)\n   * [OWASP LLM Top 10 hardening in C#](#q-how-do-you-harden-an-azure-ai-deployment-against-the-owasp-llm-top-10-risks-using-c)\n   * [Managed Identity and RBAC for AI Services](#-36-managed-identity-and-rbac-for-ai-services)\n   * [Managed Identity \u0026 RBAC role assignments in C#](#q-how-do-you-configure-managed-identity-and-rbac-to-access-azure-ai-services-securely-from-c)\n   * [Azure Policy and AI Compliance](#-37-azure-policy-and-ai-compliance)\n   * [Azure Policy compliance reporting in C#](#q-how-do-you-enforce-and-audit-azure-policy-compliance-for-ai-resources-using-c)\n* **Monitoring \u0026 Cost Management**\n   * [Monitoring AI Models with Azure Monitor](#-38-monitoring-ai-models-with-azure-monitor)\n   * [Monitor endpoints \u0026 detect drift in C#](#q-how-do-you-monitor-azure-ai-model-endpoints-and-detect-data-drift-using-azure-monitor-in-c)\n   * [Azure Cost Management for AI Workloads](#-39-azure-cost-management-for-ai-workloads)\n   * [Query \u0026 optimise AI workload costs in C#](#q-how-do-you-query-and-optimise-azure-ai-workload-costs-using-c)\n\n\n\u003cbr\u003e\n\n## # 1. GETTING STARTED\n\n\u003cbr\u003e\n\n## Q. What is Azure AI and what services does it include?\n\n**Azure AI** is Microsoft's cloud-based suite of artificial intelligence and machine learning services built on the Azure platform. It provides pre-built AI models, customizable tools, and infrastructure to build intelligent applications without requiring deep ML expertise.\n\n```mermaid\ngraph TD\n    A[Azure AI Platform] --\u003e B[Azure AI Services\\nVision · Speech · Language · Decision]\n    A --\u003e C[Azure OpenAI Service\\nGPT-4o · DALL-E · Embeddings]\n    A --\u003e D[Azure Machine Learning\\nTrain · Deploy · Monitor]\n    A --\u003e E[Azure AI Studio\\nBuild · Evaluate · Deploy GenAI]\n    A --\u003e F[Azure AI Search\\nVector · Semantic · Hybrid]\n    B --\u003e G[Applications\\nWeb · Mobile · Bot]\n    C --\u003e G\n    D --\u003e G\n    E --\u003e G\n    F --\u003e G\n```\n\n**Core pillars of Azure AI:**\n\n| Pillar | Description |\n|--------|-------------|\n| **Azure AI Services** | Pre-built APIs for vision, speech, language, and decision tasks (formerly Cognitive Services) |\n| **Azure OpenAI Service** | Access to GPT-4, DALL-E, Codex, and Embeddings models via Azure |\n| **Azure Machine Learning** | End-to-end MLOps platform for training, deploying, and managing models |\n| **Azure AI Studio** | Unified portal for building and deploying generative AI applications |\n| **Azure AI Search** | Intelligent search with vector, semantic, and hybrid capabilities |\n\n**Typical AI application workflow:**\n\n```\nData Sources → Azure Data Factory → Azure ML / AI Services\n                                            ↓\n                                  Model Training \u0026 Evaluation\n                                            ↓\n                              Azure ML Endpoints / Azure OpenAI\n                                            ↓\n                              Application (Web/Mobile/Bot)\n```\n\n**Getting started — install Azure CLI and ML SDK:**\n\n```bash\n# Install Azure CLI\nwinget install Microsoft.AzureCLI\n\n# Login\naz login\n\n# Install Azure ML Python SDK v2\npip install azure-ai-ml azure-identity\n\n# Create a resource group and Azure ML workspace\naz group create --name rg-ai-demo --location eastus\naz ml workspace create --name my-aml-ws --resource-group rg-ai-demo\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the key differences between Azure AI Services, Azure OpenAI, and Azure ML?\n\n| Feature | Azure AI Services | Azure OpenAI Service | Azure ML |\n|---------|------------------|---------------------|---------|\n| **Purpose** | Pre-built task APIs | Large language models | Custom model training \u0026 deployment |\n| **Customization** | Limited (Custom Vision, Custom Translator) | Fine-tuning (GPT-3.5/GPT-4) | Full control |\n| **Use case** | OCR, speech-to-text, translation | Chat, code gen, summarization | Forecasting, classification, custom DL |\n| **Billing** | Per API call | Per token consumed | Compute + storage time |\n| **Skill required** | Low (REST/SDK) | Low–Medium | Medium–High |\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you get started with Azure AI using C# and the .NET SDK?\n\n**Use case:** Build an enterprise .NET application that calls Azure AI Services for text analytics (sentiment analysis, named entity recognition) using the official `Azure.AI.TextAnalytics` NuGet package.\n\n**Install the NuGet packages:**\n\n```bash\ndotnet add package Azure.AI.TextAnalytics\ndotnet add package Azure.Identity\n```\n\n**Appsettings configuration (`appsettings.json`):**\n\n```json\n{\n  \"AzureAI\": {\n    \"Endpoint\": \"https://\u003cyour-resource\u003e.cognitiveservices.azure.com/\",\n    \"Key\": \"\u003cyour-key\u003e\"\n  }\n}\n```\n\n**Sentiment analysis and NER with C#:**\n\n```csharp\nusing Azure;\nusing Azure.AI.TextAnalytics;\nusing Microsoft.Extensions.Configuration;\n\n// Load configuration\nvar config = new ConfigurationBuilder()\n    .AddJsonFile(\"appsettings.json\")\n    .AddEnvironmentVariables()\n    .Build();\n\nstring endpoint = config[\"AzureAI:Endpoint\"]!;\nstring key      = config[\"AzureAI:Key\"]!;\n\nvar client = new TextAnalyticsClient(new Uri(endpoint), new AzureKeyCredential(key));\n\n// 1. Sentiment Analysis\nvar documents = new List\u003cstring\u003e\n{\n    \"Azure AI Services make building intelligent apps straightforward.\",\n    \"The deployment process was frustrating and took too long.\"\n};\n\nAnalyzeSentimentResultCollection sentimentResults = await client.AnalyzeSentimentBatchAsync(documents);\nforeach (AnalyzeSentimentResult result in sentimentResults)\n{\n    Console.WriteLine($\"Sentiment : {result.DocumentSentiment.Sentiment}\");\n    Console.WriteLine($\"  Positive: {result.DocumentSentiment.ConfidenceScores.Positive:P2}\");\n    Console.WriteLine($\"  Negative: {result.DocumentSentiment.ConfidenceScores.Negative:P2}\");\n}\n\n// 2. Named Entity Recognition\nRecognizeEntitiesResultCollection nerResults = await client.RecognizeEntitiesBatchAsync(documents);\nforeach (RecognizeEntitiesResult result in nerResults)\n{\n    foreach (CategorizedEntity entity in result.Entities)\n    {\n        Console.WriteLine($\"Entity : {entity.Text,-30} | Category: {entity.Category,-20} | Confidence: {entity.ConfidenceScore:P0}\");\n    }\n}\n```\n\n**Key NuGet packages for Azure AI in .NET:**\n\n| Package | Purpose |\n|---------|---------|\n| `Azure.AI.TextAnalytics` | Sentiment, NER, PII, key phrases, summarization |\n| `Azure.AI.Vision.ImageAnalysis` | Image captioning, OCR, object detection |\n| `Azure.AI.OpenAI` | Azure OpenAI chat completions, embeddings |\n| `Azure.AI.DocumentIntelligence` | Invoice, receipt, form extraction |\n| `Azure.AI.Translation.Text` | Text translation (100+ languages) |\n| `Azure.AI.ContentSafety` | Harmful content moderation |\n| `Microsoft.CognitiveServices.Speech` | Speech-to-text, text-to-speech |\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you call Azure OpenAI Service from a C# application?\n\n**Use case:** Build a C# console or ASP.NET Core application that uses GPT-4o for chat completions, such as a customer support assistant or a code explanation tool.\n\n**Install the NuGet package:**\n\n```bash\ndotnet add package Azure.AI.OpenAI\n```\n\n**Chat completion with streaming in C#:**\n\n```csharp\nusing Azure;\nusing Azure.AI.OpenAI;\nusing OpenAI.Chat;\n\nvar client = new AzureOpenAIClient(\n    new Uri(\"https://\u003cyour-resource\u003e.openai.azure.com/\"),\n    new AzureKeyCredential(\"\u003cyour-api-key\u003e\")\n);\n\nChatClient chatClient = client.GetChatClient(\"gpt-4o\"); // deployment name\n\n// Basic chat completion\nChatCompletion completion = await chatClient.CompleteChatAsync(\n[\n    new SystemChatMessage(\"You are a helpful Azure expert assistant.\"),\n    new UserChatMessage(\"Explain the difference between Azure AI Services and Azure OpenAI in 3 bullet points.\")\n]);\n\nConsole.WriteLine(completion.Content[0].Text);\n\n// Streaming response\nConsole.WriteLine(\"--- Streaming response ---\");\nawait foreach (StreamingChatCompletionUpdate update in chatClient.CompleteChatStreamingAsync(\n[\n    new SystemChatMessage(\"You are a concise C# code assistant.\"),\n    new UserChatMessage(\"Show a minimal example of dependency injection in ASP.NET Core.\")\n]))\n{\n    foreach (ChatMessageContentPart part in update.ContentUpdate)\n    {\n        Console.Write(part.Text);\n    }\n}\n```\n\n**Dependency-injected Azure OpenAI in ASP.NET Core:**\n\n```csharp\n// Program.cs\nusing Azure;\nusing Azure.AI.OpenAI;\n\nvar builder = WebApplication.CreateBuilder(args);\n\n// Register AzureOpenAIClient as a singleton\nbuilder.Services.AddSingleton(_ =\u003e\n    new AzureOpenAIClient(\n        new Uri(builder.Configuration[\"AzureOpenAI:Endpoint\"]!),\n        new AzureKeyCredential(builder.Configuration[\"AzureOpenAI:Key\"]!)\n    ));\n\nbuilder.Services.AddScoped\u003cIChatService, ChatService\u003e();\nbuilder.Services.AddControllers();\n\nvar app = builder.Build();\napp.MapControllers();\napp.Run();\n\n// ChatService.cs\npublic class ChatService : IChatService\n{\n    private readonly ChatClient _chatClient;\n\n    public ChatService(AzureOpenAIClient openAiClient)\n    {\n        _chatClient = openAiClient.GetChatClient(\"gpt-4o\");\n    }\n\n    public async Task\u003cstring\u003e AskAsync(string userMessage, string systemPrompt = \"You are a helpful assistant.\")\n    {\n        ChatCompletion result = await _chatClient.CompleteChatAsync(\n        [\n            new SystemChatMessage(systemPrompt),\n            new UserChatMessage(userMessage)\n        ]);\n        return result.Content[0].Text;\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you use Azure AI Vision and Document Intelligence in C#?\n\n**Use case:** An automated document processing pipeline in .NET that extracts text from scanned invoices and analyses images for objects and captions.\n\n**Image analysis with Azure AI Vision (C#):**\n\n```csharp\nusing Azure;\nusing Azure.AI.Vision.ImageAnalysis;\n\nvar client = new ImageAnalysisClient(\n    new Uri(\"https://\u003cyour-resource\u003e.cognitiveservices.azure.com/\"),\n    new AzureKeyCredential(\"\u003cyour-key\u003e\")\n);\n\n// Analyse image from URL\nImageAnalysisResult result = await client.AnalyzeAsync(\n    new Uri(\"https://example.com/factory-floor.jpg\"),\n    VisualFeatures.Caption | VisualFeatures.Objects | VisualFeatures.Read,\n    new ImageAnalysisOptions { Language = \"en\" }\n);\n\n// Caption\nConsole.WriteLine($\"Caption : {result.Caption.Text} (confidence: {result.Caption.Confidence:P1})\");\n\n// Detected objects\nforeach (DetectedObject obj in result.Objects.Values)\n{\n    Console.WriteLine($\"Object  : {obj.Tags[0].Name,-20} at ({obj.BoundingBox.X},{obj.BoundingBox.Y})\");\n}\n\n// OCR — printed/handwritten text\nforeach (DetectedTextBlock block in result.Read.Blocks)\n{\n    foreach (DetectedTextLine line in block.Lines)\n    {\n        Console.WriteLine($\"OCR text: {line.Text}\");\n    }\n}\n```\n\n**Invoice extraction with Azure Document Intelligence (C#):**\n\n```csharp\nusing Azure;\nusing Azure.AI.DocumentIntelligence;\n\nvar client = new DocumentIntelligenceClient(\n    new Uri(\"https://\u003cyour-resource\u003e.cognitiveservices.azure.com/\"),\n    new AzureKeyCredential(\"\u003cyour-key\u003e\")\n);\n\n// Analyse a PDF invoice from URL\nOperation\u003cAnalyzeResult\u003e operation = await client.AnalyzeDocumentAsync(\n    WaitUntil.Completed,\n    \"prebuilt-invoice\",\n    new AnalyzeDocumentContent\n    {\n        UrlSource = new Uri(\"https://example.com/invoice.pdf\")\n    });\n\nAnalyzeResult result = operation.Value;\n\nforeach (AnalyzedDocument invoice in result.Documents)\n{\n    if (invoice.Fields.TryGetValue(\"VendorName\", out DocumentField? vendor))\n        Console.WriteLine($\"Vendor  : {vendor.ValueString}\");\n\n    if (invoice.Fields.TryGetValue(\"InvoiceTotal\", out DocumentField? total))\n        Console.WriteLine($\"Total   : {total.ValueCurrency?.Amount} {total.ValueCurrency?.CurrencyCode}\");\n\n    if (invoice.Fields.TryGetValue(\"InvoiceDate\", out DocumentField? date))\n        Console.WriteLine($\"Date    : {date.ValueDate}\");\n\n    if (invoice.Fields.TryGetValue(\"InvoiceId\", out DocumentField? invoiceId))\n        Console.WriteLine($\"Invoice#: {invoiceId.ValueString}\");\n}\n```\n\n**Common use cases for Document Intelligence in .NET:**\n\n| Scenario | Model | Industry |\n|----------|-------|---------|\n| Accounts payable automation | `prebuilt-invoice` | Finance |\n| Expense management | `prebuilt-receipt` | Enterprise |\n| Identity verification | `prebuilt-idDocument` | Banking / KYC |\n| Contract review | `prebuilt-contract` | Legal |\n| Healthcare records | Custom neural model | Healthcare |\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you integrate Azure AI Speech Service in a C# application?\n\n**Use case:** A call centre application that transcribes customer calls in real time and synthesizes responses using neural text-to-speech voices.\n\n**Install the NuGet package:**\n\n```bash\ndotnet add package Microsoft.CognitiveServices.Speech\n```\n\n**Real-time speech-to-text (C#):**\n\n```csharp\nusing Microsoft.CognitiveServices.Speech;\nusing Microsoft.CognitiveServices.Speech.Audio;\n\nvar speechConfig = SpeechConfig.FromSubscription(\"\u003cspeech-key\u003e\", \"eastus\");\nspeechConfig.SpeechRecognitionLanguage = \"en-US\";\n\nusing var audioConfig  = AudioConfig.FromDefaultMicrophoneInput();\nusing var recognizer   = new SpeechRecognizer(speechConfig, audioConfig);\n\n// Continuous recognition with event handlers\nrecognizer.Recognized += (s, e) =\u003e\n{\n    if (e.Result.Reason == ResultReason.RecognizedSpeech)\n        Console.WriteLine($\"Recognised: {e.Result.Text}\");\n};\n\nrecognizer.Canceled += (s, e) =\u003e\n{\n    Console.WriteLine($\"Cancelled: {e.Reason} — {e.ErrorDetails}\");\n};\n\nConsole.WriteLine(\"Listening... Press Enter to stop.\");\nawait recognizer.StartContinuousRecognitionAsync();\nConsole.ReadLine();\nawait recognizer.StopContinuousRecognitionAsync();\n\n// Neural Text-to-Speech\nvar synthConfig = SpeechConfig.FromSubscription(\"\u003cspeech-key\u003e\", \"eastus\");\nsynthConfig.SpeechSynthesisVoiceName = \"en-US-JennyNeural\";\n\nusing var synthesizer = new SpeechSynthesizer(synthConfig);\n\nstring ssml = \"\"\"\n    \u003cspeak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'\u003e\n        \u003cvoice name='en-US-JennyNeural'\u003e\n            \u003cprosody rate='0.9' pitch='+5%'\u003e\n                Thank you for calling. How can I assist you today?\n            \u003c/prosody\u003e\n        \u003c/voice\u003e\n    \u003c/speak\u003e\n    \"\"\";\n\nSpeechSynthesisResult synthResult = await synthesizer.SpeakSsmlAsync(ssml);\n\nif (synthResult.Reason == ResultReason.SynthesizingAudioCompleted)\n    Console.WriteLine(\"Speech synthesised successfully.\");\nelse\n    Console.WriteLine($\"Synthesis failed: {synthResult.Reason}\");\n```\n\n**Real-world integration — save transcription to Azure Blob Storage:**\n\n```csharp\nusing Azure.Storage.Blobs;\n\n// After recognition is complete\nstring transcription = \"Full transcribed call text...\";\nstring connectionString = \"\u003cyour-storage-connection-string\u003e\";\n\nvar blobClient = new BlobClient(connectionString, \"transcriptions\", $\"call-{DateTime.UtcNow:yyyyMMdd-HHmmss}.txt\");\nusing var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(transcription));\nawait blobClient.UploadAsync(stream, overwrite: true);\n\nConsole.WriteLine($\"Transcription saved: {blobClient.Uri}\");\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 2. AZURE COGNITIVE SERVICES OVERVIEW\n\n\u003cbr\u003e\n\n## Q. What are Azure AI Services (Cognitive Services) and how are they categorized?\n\n**Azure AI Services** (formerly Azure Cognitive Services) are cloud-hosted REST APIs and SDKs that add AI capabilities to applications without needing ML expertise. As of 2025, they are grouped into five categories:\n\n| Category | Services |\n|----------|---------|\n| **Vision** | Computer Vision, Custom Vision, Face API, Document Intelligence |\n| **Language** | Language Service (NER, sentiment, QA), Translator, Text Analytics |\n| **Speech** | Speech-to-Text, Text-to-Speech, Speech Translation, Speaker Recognition |\n| **Decision** | Anomaly Detector, Content Moderator, Personalizer |\n| **OpenAI** | GPT-4, GPT-4o, Embeddings, DALL-E (via Azure OpenAI Service) |\n\n**Creating a multi-service resource:**\n\n```bash\n# Create a single Cognitive Services resource (covers all AI Services)\naz cognitiveservices account create \\\n  --name my-ai-services \\\n  --resource-group rg-ai-demo \\\n  --kind CognitiveServices \\\n  --sku S0 \\\n  --location eastus \\\n  --yes\n\n# Retrieve the key and endpoint\naz cognitiveservices account keys list \\\n  --name my-ai-services \\\n  --resource-group rg-ai-demo\n```\n\n**Calling AI Services with the Python SDK:**\n\n```python\nfrom azure.ai.textanalytics import TextAnalyticsClient\nfrom azure.core.credentials import AzureKeyCredential\n\nendpoint = \"https://\u003cyour-resource\u003e.cognitiveservices.azure.com/\"\nkey = \"\u003cyour-key\u003e\"\n\nclient = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))\n\ndocuments = [\"Azure AI Services make building intelligent apps straightforward.\"]\nresult = client.analyze_sentiment(documents)\n\nfor doc in result:\n    print(f\"Sentiment: {doc.sentiment}, Confidence: {doc.confidence_scores}\")\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you interact with Azure AI Foundry using the C# .NET SDK?\n\n**Use case:** A DevOps automation tool in .NET that connects to an Azure AI Foundry project, enumerates connections and deployments, and invokes a deployed chat model — enabling programmatic management of AI Foundry assets from enterprise .NET applications.\n\n**Install the NuGet packages:**\n\n```bash\ndotnet add package Azure.AI.Projects\ndotnet add package Azure.AI.OpenAI\ndotnet add package Azure.Identity\n```\n\n**Connect to a Foundry project and list deployments:**\n\n```csharp\nusing Azure.AI.Projects;\nusing Azure.Identity;\nusing OpenAI.Chat;\n\n// Connect to an Azure AI Foundry project via DefaultAzureCredential (Managed Identity / Entra ID)\nvar projectClient = new AIProjectClient(\n    new Uri(\"https://\u003cyour-foundry-endpoint\u003e.services.ai.azure.com/api/projects/\u003cyour-project\u003e\"),\n    new DefaultAzureCredential());\n\n// List all deployed models in the project\nConsole.WriteLine(\"=== Available Deployments ===\");\nawait foreach (var deployment in projectClient.GetDeployments().GetAllAsync())\n{\n    Console.WriteLine($\"  {deployment.Name,-30} | Model: {deployment.ModelName,-20} | Version: {deployment.ModelVersion}\");\n}\n\n// List all connections (AI Services, Storage, Search, etc.)\nConsole.WriteLine(\"\\n=== Project Connections ===\");\nawait foreach (var connection in projectClient.GetConnections().GetAllAsync())\n{\n    Console.WriteLine($\"  {connection.Name,-30} | Type: {connection.ConnectionType}\");\n}\n```\n\n**Invoke a deployed chat model through the Foundry project:**\n\n```csharp\n// Get a ChatClient scoped to a specific deployment — no separate endpoint/key needed\nChatClient chatClient = projectClient.GetChatCompletionsClient(deploymentName: \"gpt-4o\");\n\nChatCompletion response = await chatClient.CompleteChatAsync(\n[\n    new SystemChatMessage(\"You are a helpful Azure AI Foundry expert.\"),\n    new UserChatMessage(\"What are the key benefits of using Azure AI Foundry over managing AI services separately?\")\n]);\n\nConsole.WriteLine($\"Response:\\n{response.Content[0].Text}\");\n```\n\n**Azure AI Foundry project resource hierarchy:**\n\n```\nAI Foundry Hub  (shared infrastructure: networking, storage, monitoring)\n└── AI Foundry Project\n    ├── Deployments     → GetChatCompletionsClient() / GetEmbeddingsClient()\n    ├── Connections     → GetConnections() / GetConnectionAsync()\n    ├── Agents          → GetAgentsClient()\n    ├── Evaluations     → GetEvaluationsClient()\n    └── Telemetry       → GetTelemetryClient() (OpenTelemetry tracing)\n```\n\n**Key NuGet packages for Azure AI Foundry in .NET:**\n\n| Package | Purpose |\n|---------|--------|\n| `Azure.AI.Projects` | Core Foundry project client (deployments, connections, agents) |\n| `Azure.AI.OpenAI` | Chat completions, embeddings, image generation |\n| `Azure.AI.Inference` | Serverless inference for catalog models (Mistral, Llama, Cohere) |\n| `Azure.Identity` | Managed Identity, Entra ID, DefaultAzureCredential |\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 3. AZURE OPENAI SERVICE\n\n\u003cbr\u003e\n\n## Q. What is Azure OpenAI Service and how does it differ from OpenAI's API?\n\n**Azure OpenAI Service** provides access to OpenAI's models (GPT-4o, GPT-4, GPT-3.5-Turbo, Embeddings, DALL-E, Whisper) via Azure infrastructure with enterprise security, compliance, and regional availability.\n\n```mermaid\ngraph LR\n    A[Your Application] --\u003e|Managed Identity / API Key| B[Azure OpenAI Service]\n    B --\u003e C[GPT-4o]\n    B --\u003e D[DALL-E 3]\n    B --\u003e E[Embeddings]\n    B --\u003e F[Whisper]\n    B --- G[VNet / Private Endpoint]\n    B --- H[RBAC / Entra ID]\n    B --- I[Azure Content Safety]\n    B --- J[Regional Data Residency]\n```\n\n**Key differences from OpenAI API:**\n\n| Feature | OpenAI API | Azure OpenAI Service |\n|---------|-----------|---------------------|\n| **Data residency** | US-based (mostly) | Regional (EU, US, Asia) |\n| **Compliance** | SOC 2 | SOC 2, ISO 27001, HIPAA, FedRAMP |\n| **Network isolation** | No VNet support | VNet integration, Private Endpoints |\n| **Content filtering** | Default filters | Configurable + Azure Content Safety |\n| **Authentication** | API keys | API keys + Managed Identity + Entra ID |\n| **SLA** | 99.9% | 99.9% with Azure SLA |\n| **Fine-tuning** | GPT-3.5, GPT-4 | GPT-3.5-Turbo, Babbage |\n\n**Calling Azure OpenAI with Python:**\n\n```python\nfrom openai import AzureOpenAI\n\nclient = AzureOpenAI(\n    azure_endpoint=\"https://\u003cyour-resource\u003e.openai.azure.com/\",\n    api_key=\"\u003cyour-api-key\u003e\",\n    api_version=\"2024-05-01-preview\"\n)\n\nresponse = client.chat.completions.create(\n    model=\"gpt-4o\",          # deployment name in Azure\n    messages=[\n        {\"role\": \"system\", \"content\": \"You are a helpful AI assistant.\"},\n        {\"role\": \"user\",   \"content\": \"Explain Azure AI in 3 bullet points.\"}\n    ],\n    temperature=0.7,\n    max_tokens=300\n)\n\nprint(response.choices[0].message.content)\n```\n\n**Available models (2025/2026):**\n\n| Model | Best For |\n|-------|---------|\n| GPT-4o | Multimodal (text + image), fast |\n| GPT-4 Turbo | Long context (128k tokens) |\n| GPT-3.5-Turbo | Low-cost chat/completion |\n| text-embedding-ada-002 | Vector embeddings |\n| text-embedding-3-large | High-accuracy embeddings |\n| DALL-E 3 | Image generation |\n| Whisper | Speech transcription |\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you use function calling and generate embeddings with Azure OpenAI in C#?\n\n**Use case:** An intelligent product-search assistant that uses GPT-4o function calling to query a live product catalogue and `text-embedding-3-large` to implement semantic similarity ranking inside an ASP.NET Core application.\n\n**Install the NuGet package:**\n\n```bash\ndotnet add package Azure.AI.OpenAI\n```\n\n**Function calling — agentic loop in C#:**\n\n```csharp\nusing Azure;\nusing Azure.AI.OpenAI;\nusing OpenAI.Chat;\nusing System.ClientModel;\nusing System.Text.Json;\n\nvar openAiClient = new AzureOpenAIClient(\n    new Uri(\"https://\u003cyour-resource\u003e.openai.azure.com/\"),\n    new AzureKeyCredential(\"\u003cyour-api-key\u003e\")\n);\n\nChatClient chatClient = openAiClient.GetChatClient(\"gpt-4o\");\n\n// Define the tool (function) the model can invoke\nChatTool searchProductsTool = ChatTool.CreateFunctionTool(\n    functionName: \"search_products\",\n    functionDescription: \"Search the product catalogue by keyword and return matching items.\",\n    functionParameters: BinaryData.FromString(\"\"\"\n    {\n      \"type\": \"object\",\n      \"properties\": {\n        \"query\": { \"type\": \"string\",  \"description\": \"Search keyword\" },\n        \"limit\": { \"type\": \"integer\", \"description\": \"Max number of results\", \"default\": 5 }\n      },\n      \"required\": [\"query\"]\n    }\n    \"\"\")\n);\n\nvar messages = new List\u003cChatMessage\u003e\n{\n    new SystemChatMessage(\"You are a product assistant. Use the search tool to find products.\"),\n    new UserChatMessage(\"Show me the top 3 wireless keyboards.\")\n};\n\nvar options = new ChatCompletionOptions { Tools = { searchProductsTool } };\n\n// Agentic loop — keep going until the model stops calling tools\nwhile (true)\n{\n    ChatCompletion completion = await chatClient.CompleteChatAsync(messages, options);\n\n    if (completion.FinishReason == ChatFinishReason.ToolCalls)\n    {\n        messages.Add(new AssistantChatMessage(completion));\n\n        foreach (ChatToolCall toolCall in completion.ToolCalls)\n        {\n            using JsonDocument args = JsonDocument.Parse(toolCall.FunctionArguments);\n            string query = args.RootElement.GetProperty(\"query\").GetString()!;\n\n            // Simulate a real product database lookup\n            string result = JsonSerializer.Serialize(new[]\n            {\n                new { id = 1, name = \"Logitech MX Keys\",    price = 99.99 },\n                new { id = 2, name = \"Microsoft Sculpt\",    price = 79.99 },\n                new { id = 3, name = \"Keychron K2 Pro\",     price = 89.99 }\n            });\n\n            messages.Add(new ToolChatMessage(toolCall.Id, result));\n        }\n    }\n    else\n    {\n        Console.WriteLine(completion.Content[0].Text);\n        break;\n    }\n}\n```\n\n**Generating and comparing embeddings in C#:**\n\n```csharp\nusing OpenAI.Embeddings;\n\nEmbeddingClient embeddingClient = openAiClient.GetEmbeddingClient(\"text-embedding-3-large\");\n\nstring[] corpus =\n[\n    \"Azure Machine Learning is a cloud-based ML platform.\",\n    \"Python is a popular programming language.\",\n    \"Training neural networks requires GPU compute.\"\n];\n\n// Generate embeddings for the corpus\nClientResult\u003cEmbeddingCollection\u003e corpusResult = await embeddingClient.GenerateEmbeddingsAsync(corpus);\nfloat[][] corpusVectors = corpusResult.Value\n    .Select(e =\u003e e.ToFloats().ToArray())\n    .ToArray();\n\n// Generate embedding for the query\nstring query = \"How do I train a model on Azure?\";\nfloat[] queryVector = (await embeddingClient.GenerateEmbeddingAsync(query)).Value.ToFloats().ToArray();\n\n// Cosine similarity helper\nstatic float CosineSimilarity(float[] a, float[] b)\n{\n    float dot   = a.Zip(b, (x, y) =\u003e x * y).Sum();\n    float normA = MathF.Sqrt(a.Sum(x =\u003e x * x));\n    float normB = MathF.Sqrt(b.Sum(x =\u003e x * x));\n    return dot / (normA * normB);\n}\n\nvar ranked = corpus\n    .Zip(corpusVectors, (doc, vec) =\u003e (doc, score: CosineSimilarity(queryVector, vec)))\n    .OrderByDescending(x =\u003e x.score);\n\nConsole.WriteLine($\"Semantic search results for: \\\"{query}\\\"\");\nforeach (var (doc, score) in ranked)\n    Console.WriteLine($\"  [{score:F4}] {doc}\");\n```\n\n**Azure OpenAI capabilities available in the .NET SDK:**\n\n| Capability | Client | Method |\n|------------|--------|--------|\n| Chat completions | `ChatClient` | `CompleteChatAsync()` |\n| Streaming chat | `ChatClient` | `CompleteChatStreamingAsync()` |\n| Function calling | `ChatClient` | `ChatTool` + agentic loop |\n| Text embeddings | `EmbeddingClient` | `GenerateEmbeddingsAsync()` |\n| Image generation | `ImageClient` | `GenerateImageAsync()` |\n| Audio transcription | `AudioClient` | `TranscribeAudioAsync()` |\n| Structured output | `ChatCompletionOptions` | `ResponseFormat = ChatResponseFormat.JsonObject` |\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 4. AZURE AI STUDIO\n\n\u003cbr\u003e\n\n## Q. What is Azure AI Studio and what can you build with it?\n\n**Azure AI Studio** (ai.azure.com) is a unified development portal for building, evaluating, and deploying generative AI applications. It consolidates Azure OpenAI, Azure AI Services, Azure ML, and prompt tooling into a single interface.\n\n```mermaid\ngraph TD\n    A[AI Foundry Hub\\nShared Infrastructure] --\u003e B[AI Foundry Project]\n    B --\u003e C[Model Catalog\\n1600+ Models]\n    B --\u003e D[Deployments\\nManaged · Serverless]\n    B --\u003e E[Prompt Flows\\nVisual Orchestration]\n    B --\u003e F[Evaluations\\nGroundedness · Relevance]\n    B --\u003e G[Connections\\nSearch · Storage · AI Services]\n    B --\u003e H[Fine-tuning Jobs]\n```\n\n**Core capabilities:**\n\n| Feature | Description |\n|---------|-------------|\n| **Model Catalog** | 1,600+ open-source and proprietary models (OpenAI, Meta, Mistral, Cohere) |\n| **Playground** | Interactive testing of models with system prompts |\n| **Prompt Flow** | Visual/code orchestration of LLM pipelines (inputs → LLM → outputs) |\n| **Evaluations** | Measure groundedness, coherence, fluency, relevance of AI outputs |\n| **Deployments** | One-click deploy to managed endpoints or serverless APIs |\n| **AI Search integration** | Connect to Azure AI Search for RAG pipelines |\n\n**AI Studio project structure:**\n\n```\nAI Studio Hub (shared resources)\n└── AI Studio Project\n    ├── Deployments (models)\n    ├── Connections (storage, search, AI services)\n    ├── Prompt flows\n    ├── Evaluations\n    └── Fine-tuning jobs\n```\n\n**Creating a project with the Python SDK:**\n\n```python\nfrom azure.ai.projects import AIProjectClient\nfrom azure.identity import DefaultAzureCredential\n\nclient = AIProjectClient(\n    subscription_id=\"\u003csub-id\u003e\",\n    resource_group_name=\"rg-ai-demo\",\n    project_name=\"my-ai-project\",\n    credential=DefaultAzureCredential()\n)\n\n# List available model deployments\nfor deployment in client.deployments.list():\n    print(f\"{deployment.name}: {deployment.model_name}\")\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you browse and deploy models from the Azure AI Foundry model catalog using C#?\n\n**Use case:** A CI/CD automation script in C# that discovers available models in the Azure AI Foundry model catalog, deploys a selected open-source model to a serverless endpoint, and validates the deployment — enabling repeatable infrastructure-as-code for AI workloads.\n\n**Install the NuGet packages:**\n\n```bash\ndotnet add package Azure.AI.Projects\ndotnet add package Azure.AI.Inference\ndotnet add package Azure.Identity\n```\n\n**Browse the model catalog and inspect a specific model:**\n\n```csharp\nusing Azure.AI.Projects;\nusing Azure.AI.Projects.Models;\nusing Azure.Identity;\n\nvar projectClient = new AIProjectClient(\n    new Uri(\"https://\u003cyour-foundry-endpoint\u003e.services.ai.azure.com/api/projects/\u003cyour-project\u003e\"),\n    new DefaultAzureCredential());\n\n// ─── 1. BROWSE CATALOG ────────────────────────────────────────────────────────\nConsole.WriteLine(\"=== Model Catalog ===\");\nawait foreach (ModelInfo model in projectClient.GetModels().GetAllAsync())\n{\n    Console.WriteLine($\"  {model.Id,-45} | Publisher: {model.Publisher,-15} | Task: {model.Task}\");\n}\n\n// ─── 2. GET DETAILS FOR A SPECIFIC MODEL ─────────────────────────────────────\nModelInfo details = await projectClient.GetModelAsync(\"mistral-large-2407\");\nConsole.WriteLine($\"\\nModel      : {details.DisplayName}\");\nConsole.WriteLine($\"Publisher  : {details.Publisher}\");\nConsole.WriteLine($\"License    : {details.License}\");\nConsole.WriteLine($\"Description: {details.Description[..Math.Min(120, details.Description.Length)]}...\");\n\n// ─── 3. LIST EXISTING DEPLOYMENTS ────────────────────────────────────────────\nConsole.WriteLine(\"\\n=== Active Deployments ===\");\nawait foreach (ModelDeployment dep in projectClient.GetDeployments().GetAllAsync())\n{\n    Console.WriteLine($\"  {dep.Name,-30} | Model: {dep.ModelName,-25} | State: {dep.ProvisioningState}\");\n}\n```\n\n**Invoke a catalog model via serverless inference endpoint:**\n\n```csharp\nusing Azure.AI.Inference;\n\n// Get a chat completions client for a deployed catalog model (no OpenAI required)\nChatCompletionsClient inferenceClient = projectClient.GetChatCompletionsClient(\"mistral-large-2407\");\n\nvar inferenceOptions = new ChatCompletionsOptions\n{\n    Messages =\n    {\n        new ChatRequestSystemMessage(\"You are a concise technical assistant.\"),\n        new ChatRequestUserMessage(\"List 3 reasons to use Mistral Large over GPT-3.5-Turbo.\")\n    },\n    MaxTokens  = 400,\n    Temperature = 0.6f\n};\n\nResponse\u003cChatCompletions\u003e inferenceResponse = await inferenceClient.CompleteAsync(inferenceOptions);\nConsole.WriteLine($\"\\n{inferenceResponse.Value.Choices[0].Message.Content}\");\n```\n\n**Run a Prompt Flow evaluation from C#:**\n\n```csharp\n// Trigger a named evaluation and check its status\nvar evalClient = projectClient.GetEvaluationsClient();\n\n// Get an existing evaluation schedule\nEvaluationSchedule evalSchedule = await evalClient.GetScheduleAsync(\"rag-groundedness-eval\");\nConsole.WriteLine($\"Evaluation : {evalSchedule.Name}\");\nConsole.WriteLine($\"Status     : {evalSchedule.ProvisioningState}\");\nConsole.WriteLine($\"Description: {evalSchedule.Description}\");\n```\n\n**Model catalog selection guide:**\n\n| Model family | Publisher | Best for | Serverless deploy |\n|-------------|-----------|----------|------------------|\n| GPT-4o, GPT-4 Turbo | OpenAI | General purpose, multimodal | Yes |\n| Mistral Large / Small | Mistral AI | Cost-efficient chat, function calling | Yes |\n| Llama 3.1 / 3.2 | Meta | Open-weight, fine-tunable | Yes |\n| Phi-3 / Phi-4 | Microsoft | Edge inference, small footprint | Yes |\n| Cohere Command R+ | Cohere | RAG, long context | Yes |\n| DALL-E 3 | OpenAI | Image generation | No (Azure OpenAI) |\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 5. AZURE MACHINE LEARNING (AML)\n\n\u003cbr\u003e\n\n## Q. What is Azure Machine Learning and what are its core components?\n\n**Azure Machine Learning (AML)** is a cloud platform for the complete ML lifecycle — data preparation, training, evaluation, deployment, and monitoring. It supports both code-first and low-code approaches.\n\n```mermaid\nflowchart LR\n    A[Data Sources] --\u003e B[Data Assets\\nVersioned Datasets]\n    B --\u003e C[Training Jobs\\nCommand · Sweep · Pipeline]\n    C --\u003e D[Compute\\nCPU / GPU Clusters]\n    C --\u003e E[MLflow Tracking\\nMetrics · Params · Artifacts]\n    E --\u003e F[Model Registry]\n    F --\u003e G[Online Endpoints\\nReal-time Inference]\n    F --\u003e H[Batch Endpoints\\nBulk Scoring]\n    G --\u003e I[Applications]\n    H --\u003e I\n```\n\n**Core components:**\n\n| Component | Purpose |\n|-----------|---------|\n| **Workspace** | Top-level resource grouping all AML assets |\n| **Compute** | Compute clusters (training), compute instances (dev), inference clusters |\n| **Data assets** | Versioned datasets registered in the workspace |\n| **Environments** | Docker/conda environments for reproducible training |\n| **Jobs** | Executed training scripts (Command, Sweep, Pipeline jobs) |\n| **Models** | Registered artifacts from training runs |\n| **Endpoints** | Online (real-time) or batch inference endpoints |\n| **MLflow** | Integrated experiment tracking and model registry |\n\n**Submitting a training job with SDK v2:**\n\n```python\nfrom azure.ai.ml import MLClient, command\nfrom azure.ai.ml.entities import Environment\nfrom azure.identity import DefaultAzureCredential\n\nml_client = MLClient(\n    DefaultAzureCredential(),\n    subscription_id=\"\u003csub-id\u003e\",\n    resource_group_name=\"rg-ai-demo\",\n    workspace_name=\"my-aml-ws\"\n)\n\njob = command(\n    code=\"./src\",\n    command=\"python train.py --learning_rate ${{inputs.lr}} --epochs ${{inputs.epochs}}\",\n    inputs={\"lr\": 0.001, \"epochs\": 10},\n    environment=\"AzureML-sklearn-1.5-ubuntu20.04-py38-cpu@latest\",\n    compute=\"cpu-cluster\",\n    display_name=\"sklearn-training-job\"\n)\n\nreturned_job = ml_client.jobs.create_or_update(job)\nprint(f\"Job submitted: {returned_job.studio_url}\")\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you manage Azure Machine Learning workspaces and submit training jobs from C#?\n\n**Use case:** A GitHub Actions or Azure DevOps pipeline stage written in C# that submits a training job to AML, polls until completion, registers the best model, and creates an online endpoint — enabling full MLOps CI/CD without leaving the .NET ecosystem.\n\n**Install the NuGet packages:**\n\n```bash\ndotnet add package Azure.ResourceManager.MachineLearning\ndotnet add package Azure.Identity\n```\n\n**Connect to the workspace and list compute clusters:**\n\n```csharp\nusing Azure.Identity;\nusing Azure.ResourceManager;\nusing Azure.ResourceManager.MachineLearning;\nusing Azure.ResourceManager.MachineLearning.Models;\n\nvar credential   = new DefaultAzureCredential();\nvar armClient    = new ArmClient(credential);\n\n// Reference the AML workspace via ARM resource ID\nvar workspaceId = MachineLearningWorkspaceResource.CreateResourceIdentifier(\n    subscriptionId: \"\u003cyour-subscription-id\u003e\",\n    resourceGroupName: \"rg-ai-demo\",\n    workspaceName: \"my-aml-ws\");\n\nMachineLearningWorkspaceResource workspace =\n    armClient.GetMachineLearningWorkspaceResource(workspaceId);\n\n// List available compute clusters\nConsole.WriteLine(\"=== Compute Clusters ===\");\nawait foreach (MachineLearningComputeResource compute in\n    workspace.GetMachineLearningComputes().GetAllAsync())\n{\n    Console.WriteLine(\n        $\"  {compute.Data.Name,-25} | Type: {compute.Data.Properties?.ComputeType}\");\n}\n```\n\n**Submit a command job and poll to completion:**\n\n```csharp\n// ─── SUBMIT JOB ───────────────────────────────────────────────────────────────\nvar jobCollection = workspace.GetMachineLearningJobs();\n\nvar jobData = new MachineLearningJobData(\n    new MachineLearningCommandJob(\n        command: \"python train.py --learning-rate 0.001 --epochs 10\",\n        environmentId: \"azureml:AzureML-sklearn-1.5-ubuntu20.04-py38-cpu@latest\",\n        computeId: \"cpu-cluster\")\n    {\n        DisplayName    = \"csharp-sklearn-training-job\",\n        ExperimentName = \"csharp-cicd-experiments\",\n        Inputs =\n        {\n            [\"training_data\"] = new MachineLearningLiteralJobInput(\"azureml:sales-data:1\")\n        }\n    });\n\nstring jobName = $\"job-{DateTime.UtcNow:yyyyMMddHHmmss}\";\nArmOperation\u003cMachineLearningJobResource\u003e createOp =\n    await jobCollection.CreateOrUpdateAsync(Azure.WaitUntil.Started, jobName, jobData);\n\nMachineLearningJobResource job = createOp.Value;\nConsole.WriteLine($\"Job submitted : {job.Data.Name}\");\n\n// ─── POLL UNTIL COMPLETE ──────────────────────────────────────────────────────\nMachineLearningJobStatus? status;\ndo\n{\n    await Task.Delay(TimeSpan.FromSeconds(15));\n    job    = await workspace.GetMachineLearningJobAsync(job.Data.Name);\n    status = (job.Data.Properties as MachineLearningCommandJob)?.Status;\n    Console.WriteLine($\"  [{DateTime.UtcNow:HH:mm:ss}] Status: {status}\");\n}\nwhile (status is\n    MachineLearningJobStatus.Running or\n    MachineLearningJobStatus.Queued  or\n    MachineLearningJobStatus.Preparing);\n\nConsole.WriteLine($\"Job finished with status: {status}\");\n```\n\n**Register the trained model and create an online endpoint:**\n\n```csharp\nif (status == MachineLearningJobStatus.Completed)\n{\n    // ─── REGISTER MODEL ───────────────────────────────────────────────────────\n    var modelContainers = workspace.GetMachineLearningModelContainers();\n    await modelContainers.CreateOrUpdateAsync(\n        Azure.WaitUntil.Completed,\n        \"sales-forecast-model\",\n        new MachineLearningModelContainerData(\n            new MachineLearningModelContainerProperties\n            {\n                Description = \"Sales forecast model — C# CI/CD pipeline\"\n            }));\n\n    var modelVersions = (await modelContainers.GetAsync(\"sales-forecast-model\"))\n        .Value.GetMachineLearningModelVersions();\n\n    await modelVersions.CreateOrUpdateAsync(\n        Azure.WaitUntil.Completed, \"1\",\n        new MachineLearningModelVersionData(\n            new MachineLearningModelVersionProperties\n            {\n                ModelUri    = $\"azureml://jobs/{job.Data.Name}/outputs/model\",\n                Description = \"v1 trained from C# job\"\n            }));\n\n    Console.WriteLine(\"Model registered: sales-forecast-model:1\");\n\n    // ─── CREATE MANAGED ONLINE ENDPOINT ──────────────────────────────────────\n    var endpoints = workspace.GetMachineLearningOnlineEndpoints();\n\n    await endpoints.CreateOrUpdateAsync(\n        Azure.WaitUntil.Completed,\n        \"sales-forecast-endpoint\",\n        new MachineLearningOnlineEndpointData(workspace.Data.Location)\n        {\n            Properties = new MachineLearningOnlineEndpointProperties\n            {\n                AuthMode    = MachineLearningEndpointAuthMode.Key,\n                Description = \"Real-time endpoint for sales forecast model\"\n            }\n        });\n\n    Console.WriteLine(\"Online endpoint created: sales-forecast-endpoint\");\n}\n```\n\n**Key Azure ML ARM SDK types reference:**\n\n| Type | Purpose |\n|------|---------|\n| `MachineLearningWorkspaceResource` | Workspace-level operations |\n| `MachineLearningComputeResource` | Manage clusters and compute instances |\n| `MachineLearningJobResource` | Submit, monitor, and cancel jobs |\n| `MachineLearningModelContainerResource` | Model registry container |\n| `MachineLearningModelVersionResource` | Versioned registered models |\n| `MachineLearningOnlineEndpointResource` | Real-time inference endpoints |\n| `MachineLearningBatchEndpointResource` | Batch inference endpoints |\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 6. AZURE COMPUTER VISION\n\n\u003cbr\u003e\n\n## Q. What is Azure Computer Vision and what are its main capabilities?\n\n**Azure Computer Vision** is an AI service that analyzes images and videos to extract information such as objects, text, faces, and scene context. The latest version (4.0) integrates vision models based on Florence and GPT-4 Vision.\n\n```mermaid\nflowchart LR\n    A[Image / Video] --\u003e B[Azure AI Vision API]\n    B --\u003e C[Auto Caption]\n    B --\u003e D[Object Detection\\nBounding Boxes]\n    B --\u003e E[OCR — Read API\\nPrinted · Handwritten]\n    B --\u003e F[Tags \u0026 Confidence]\n    B --\u003e G[Spatial Analysis\\nPeople Counting · Zones]\n    B --\u003e H[Background Removal\\nPNG Matting]\n```\n\n**Key capabilities:**\n\n| Feature | Description |\n|---------|-------------|\n| **Image Analysis** | Caption, dense captions, tags, object detection, smart crop |\n| **OCR (Read API)** | Extract printed and handwritten text from images/PDFs |\n| **Spatial Analysis** | Real-time video analysis (people counting, zone detection) |\n| **Background Removal** | Segment foreground from background |\n| **Product Recognition** | Identify products on retail shelves |\n| **GPT-4 Vision** | Multimodal understanding (via Azure OpenAI) |\n\n**Example — image analysis with Python SDK:**\n\n```python\nfrom azure.ai.vision.imageanalysis import ImageAnalysisClient\nfrom azure.ai.vision.imageanalysis.models import VisualFeatures\nfrom azure.core.credentials import AzureKeyCredential\n\nclient = ImageAnalysisClient(\n    endpoint=\"https://\u003cyour-resource\u003e.cognitiveservices.azure.com/\",\n    credential=AzureKeyCredential(\"\u003cyour-key\u003e\")\n)\n\nresult = client.analyze_from_url(\n    image_url=\"https://example.com/photo.jpg\",\n    visual_features=[\n        VisualFeatures.CAPTION,\n        VisualFeatures.OBJECTS,\n        VisualFeatures.READ   # OCR\n    ],\n    language=\"en\"\n)\n\nprint(f\"Caption: {result.caption.text} (confidence: {result.caption.confidence:.2f})\")\n\nfor obj in result.objects.list:\n    print(f\"Object: {obj.tags[0].name} at {obj.bounding_box}\")\n\nif result.read:\n    for block in result.read.blocks:\n        for line in block.lines:\n            print(f\"Text: {line.text}\")\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you perform image analysis and OCR using Azure AI Vision in C#?\n\n**Use case:** A retail quality-control application that scans product images on a conveyor belt, reads printed labels via OCR, detects objects, and generates automated captions — all from a .NET worker service.\n\n**Install the NuGet package:**\n\n```bash\ndotnet add package Azure.AI.Vision.ImageAnalysis\n```\n\n**Full image analysis — caption, objects, OCR, tags (C#):**\n\n```csharp\nusing Azure;\nusing Azure.AI.Vision.ImageAnalysis;\n\nvar client = new ImageAnalysisClient(\n    new Uri(\"https://\u003cyour-resource\u003e.cognitiveservices.azure.com/\"),\n    new AzureKeyCredential(\"\u003cyour-key\u003e\")\n);\n\n// Analyse an image from a public URL\nImageAnalysisResult result = await client.AnalyzeAsync(\n    new Uri(\"https://example.com/product-shelf.jpg\"),\n    VisualFeatures.Caption\n    | VisualFeatures.DenseCaptions\n    | VisualFeatures.Objects\n    | VisualFeatures.Tags\n    | VisualFeatures.Read,            // OCR\n    new ImageAnalysisOptions { Language = \"en\", GenderNeutralCaption = true }\n);\n\n// Caption\nConsole.WriteLine($\"Caption : {result.Caption.Text} (confidence: {result.Caption.Confidence:P1})\");\n\n// Dense captions (region-level)\nConsole.WriteLine(\"\\nDense Captions:\");\nforeach (DenseCaption dc in result.DenseCaptions.Values)\n    Console.WriteLine($\"  [{dc.Confidence:P0}] {dc.Text,-50} @ ({dc.BoundingBox.X},{dc.BoundingBox.Y})\");\n\n// Detected objects\nConsole.WriteLine(\"\\nObjects:\");\nforeach (DetectedObject obj in result.Objects.Values)\n    Console.WriteLine($\"  {obj.Tags[0].Name,-20} confidence: {obj.Tags[0].Confidence:P1}\");\n\n// Tags\nConsole.WriteLine(\"\\nTags: \" + string.Join(\", \",\n    result.Tags.Values.Select(t =\u003e $\"{t.Name}({t.Confidence:P0})\")));\n\n// OCR — all text in the image\nConsole.WriteLine(\"\\nOCR Text:\");\nif (result.Read is not null)\n    foreach (DetectedTextBlock block in result.Read.Blocks)\n        foreach (DetectedTextLine line in block.Lines)\n            Console.WriteLine($\"  {line.Text}\");\n```\n\n**Analyse a local file using a stream:**\n\n```csharp\nusing var imageStream = File.OpenRead(\"./images/label.jpg\");\nImageAnalysisResult streamResult = await client.AnalyzeAsync(\n    BinaryData.FromStream(imageStream),\n    VisualFeatures.Read,\n    new ImageAnalysisOptions { Language = \"en\" }\n);\n\nConsole.WriteLine(\"Extracted text from local file:\");\nforeach (DetectedTextBlock block in streamResult.Read.Blocks)\n    foreach (DetectedTextLine line in block.Lines)\n        Console.WriteLine($\"  {line.Text}\");\n```\n\n**Background removal (foreground matting):**\n\n```csharp\n// Background removal returns a PNG with transparent background\nResponse\u003cBinaryData\u003e bgResult = await client.RemoveBackgroundAsync(\n    new Uri(\"https://example.com/person.jpg\")\n);\n\nawait File.WriteAllBytesAsync(\"output-no-bg.png\", bgResult.Value.ToArray());\nConsole.WriteLine($\"Background removed — saved to output-no-bg.png\");\n```\n\n**Azure AI Vision capabilities in .NET:**\n\n| Feature | `VisualFeatures` enum | Notes |\n|---------|----------------------|-------|\n| Auto-caption | `Caption` | Single sentence |\n| Region captions | `DenseCaptions` | Up to 10 regions |\n| Object detection | `Objects` | Bounding boxes |\n| Semantic tags | `Tags` | Confidence scored |\n| OCR | `Read` | Printed \u0026 handwritten |\n| People detection | `People` | Bounding boxes only |\n| Smart crop | `SmartCrops` | Aspect-ratio aware |\n| Background removal | `RemoveBackgroundAsync()` | Returns PNG |\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 7. AZURE CUSTOM VISION\n\n\u003cbr\u003e\n\n## Q. What is Azure Custom Vision and when should you use it?\n\n**Azure Custom Vision** is a service for building and deploying custom image classification and object detection models with minimal ML expertise. It uses transfer learning on top of pre-trained models, requiring as few as 15 images per class.\n\n```mermaid\nflowchart TD\n    A[Label Training Images] --\u003e B[Upload \u0026 Tag via SDK / Portal]\n    B --\u003e C[Train Model\\nTransfer Learning]\n    C --\u003e D[Evaluate\\nPrecision · Recall · mAP]\n    D --\u003e E{Acceptable\\nAccuracy?}\n    E -- No --\u003e A\n    E -- Yes --\u003e F[Publish Iteration]\n    F --\u003e G[REST Prediction Endpoint]\n    F --\u003e H[Export for Edge\\nONNX · TFLite · CoreML · Docker]\n```\n\n**Two main tasks:**\n\n| Task | Description | Min Images |\n|------|-------------|-----------|\n| **Image Classification** | Assign one or more labels to an image (multi-class or multi-label) | 5–15 per tag |\n| **Object Detection** | Locate and label objects within an image with bounding boxes | 15 per tag |\n\n**Workflow:**\n\n```\n1. Create Custom Vision project (portal or SDK)\n2. Upload \u0026 tag training images\n3. Train model (Quick or Advanced training)\n4. Evaluate — Precision, Recall, mAP\n5. Test with new images\n6. Publish → REST endpoint or export (ONNX, TensorFlow, CoreML, Docker)\n```\n\n**Python training example:**\n\n```python\nfrom azure.cognitiveservices.vision.customvision.training import CustomVisionTrainingClient\nfrom azure.cognitiveservices.vision.customvision.training.models import ImageFileCreateBatch, ImageFileCreateEntry\nfrom msrest.authentication import ApiKeyCredentials\nimport os\n\ncredentials = ApiKeyCredentials(in_headers={\"Training-key\": \"\u003ctraining-key\u003e\"})\ntrainer = CustomVisionTrainingClient(\"\u003ctraining-endpoint\u003e\", credentials)\n\n# Create project\nproject = trainer.create_project(\"Defect Classifier\")\n\n# Create tags\ngood_tag   = trainer.create_tag(project.id, \"good\")\ndefect_tag = trainer.create_tag(project.id, \"defect\")\n\n# Upload images\nimage_list = []\nfor fname in os.listdir(\"./images/good\"):\n    with open(f\"./images/good/{fname}\", \"rb\") as f:\n        image_list.append(ImageFileCreateEntry(name=fname, contents=f.read(), tag_ids=[good_tag.id]))\n\ntrainer.create_images_from_files(project.id, ImageFileCreateBatch(images=image_list))\n\n# Train\nimport time\niteration = trainer.train_project(project.id)\nwhile iteration.status != \"Completed\":\n    time.sleep(5)\n    iteration = trainer.get_iteration(project.id, iteration.id)\n\n# Publish\ntrainer.publish_iteration(project.id, iteration.id, \"classifyModel\", \"\u003cprediction-resource-id\u003e\")\nprint(\"Model published!\")\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you train and call an Azure Custom Vision model from C#?\n\n**Use case:** A manufacturing defect-detection system that trains a Custom Vision classifier on labelled product images and integrates real-time prediction into a .NET production-line monitoring service.\n\n**Install the NuGet packages:**\n\n```bash\ndotnet add package Microsoft.Azure.CognitiveServices.Vision.CustomVision.Training\ndotnet add package Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction\n```\n\n**Create a project, upload tagged images, and train (C#):**\n\n```csharp\nusing Microsoft.Azure.CognitiveServices.Vision.CustomVision.Training;\nusing Microsoft.Azure.CognitiveServices.Vision.CustomVision.Training.Models;\n\nstring trainingKey      = \"\u003cyour-training-key\u003e\";\nstring trainingEndpoint = \"https://\u003cyour-resource\u003e.cognitiveservices.azure.com/\";\n\nvar trainingClient = new CustomVisionTrainingClient(\n    new Microsoft.Azure.CognitiveServices.Vision.CustomVision.Training.ApiKeyServiceClientCredentials(trainingKey))\n{\n    Endpoint = trainingEndpoint\n};\n\n// ─── 1. CREATE PROJECT ────────────────────────────────────────────────────────\nProject project = await trainingClient.CreateProjectAsync(\n    \"DefectClassifier\",\n    description: \"Binary classifier — good vs defect parts\",\n    classificationType: Classifier.Multiclass);\n\nConsole.WriteLine($\"Project created: {project.Id}\");\n\n// ─── 2. CREATE TAGS ───────────────────────────────────────────────────────────\nTag goodTag   = await trainingClient.CreateTagAsync(project.Id, \"good\");\nTag defectTag = await trainingClient.CreateTagAsync(project.Id, \"defect\");\n\n// ─── 3. UPLOAD TAGGED IMAGES ─────────────────────────────────────────────────\nvar imageEntries = new List\u003cImageFileCreateEntry\u003e();\n\nforeach (string file in Directory.GetFiles(\"./images/good\"))\n{\n    byte[] bytes = await File.ReadAllBytesAsync(file);\n    imageEntries.Add(new ImageFileCreateEntry(Path.GetFileName(file), bytes,\n        tagIds: new List\u003cGuid\u003e { goodTag.Id }));\n}\n\nforeach (string file in Directory.GetFiles(\"./images/defect\"))\n{\n    byte[] bytes = await File.ReadAllBytesAsync(file);\n    imageEntries.Add(new ImageFileCreateEntry(Path.GetFileName(file), bytes,\n        tagIds: new List\u003cGuid\u003e { defectTag.Id }));\n}\n\nImageCreateSummary uploadSummary = await trainingClient.CreateImagesFromFilesAsync(\n    project.Id, new ImageFileCreateBatch(imageEntries));\n\nConsole.WriteLine($\"Uploaded: {uploadSummary.Images.Count} images\");\n\n// ─── 4. TRAIN ─────────────────────────────────────────────────────────────────\nIteration iteration = await trainingClient.TrainProjectAsync(project.Id);\n\nwhile (iteration.Status == \"Training\")\n{\n    await Task.Delay(TimeSpan.FromSeconds(5));\n    iteration = await trainingClient.GetIterationAsync(project.Id, iteration.Id);\n    Console.WriteLine($\"Training status: {iteration.Status}\");\n}\n\nConsole.WriteLine($\"Training complete — Precision: {iteration.Precision:P1}  Recall: {iteration.Recall:P1}\");\n\n// ─── 5. PUBLISH ITERATION ─────────────────────────────────────────────────────\nawait trainingClient.PublishIterationAsync(\n    project.Id, iteration.Id,\n    publishName: \"DefectClassifierV1\",\n    predictionId: \"\u003cprediction-resource-id\u003e\");\n\nConsole.WriteLine(\"Model published as 'DefectClassifierV1'.\");\n```\n\n**Run real-time prediction from C#:**\n\n```csharp\nusing Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction;\nusing Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction.Models;\n\nstring predictionKey      = \"\u003cyour-prediction-key\u003e\";\nstring predictionEndpoint = \"https://\u003cyour-resource\u003e.cognitiveservices.azure.com/\";\n\nvar predictionClient = new CustomVisionPredictionClient(\n    new Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction.ApiKeyServiceClientCredentials(predictionKey))\n{\n    Endpoint = predictionEndpoint\n};\n\n// Predict from a local file\nusing var imageStream = File.OpenRead(\"./test-images/part-001.jpg\");\nImagePrediction prediction = await predictionClient.ClassifyImageAsync(\n    project.Id,\n    publishedModelName: \"DefectClassifierV1\",\n    imageData: imageStream\n);\n\nforeach (PredictionModel pred in prediction.Predictions.OrderByDescending(p =\u003e p.Probability))\n    Console.WriteLine($\"  {pred.TagName,-10}: {pred.Probability:P1}\");\n\n// Predict from a URL\nImagePrediction urlPrediction = await predictionClient.ClassifyImageUrlAsync(\n    project.Id,\n    publishedModelName: \"DefectClassifierV1\",\n    url: new Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction.Models.ImageUrl(\n             \"https://example.com/part-002.jpg\")\n);\n\nstring topTag = urlPrediction.Predictions.MaxBy(p =\u003e p.Probability)!.TagName;\nConsole.WriteLine($\"Top prediction: {topTag}\");\n```\n\n**Custom Vision model export formats for edge deployment:**\n\n| Format | Target runtime | Use case |\n|--------|---------------|----------|\n| ONNX | Windows ML, ONNX Runtime | .NET on-device inference |\n| TensorFlow / TFLite | Android, Raspberry Pi | Mobile / IoT |\n| CoreML | iOS / macOS | Apple devices |\n| OpenVINO | Intel hardware | Industrial edge |\n| Dockerfile | Any container host | Offline REST endpoint |\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 8. AZURE FACE API\n\n\u003cbr\u003e\n\n## Q. What is the Azure Face API and what are its use cases and limitations?\n\n**Azure Face API** detects, analyzes, and identifies human faces in images. As of 2023, access to certain capabilities (identification, verification, facial attributes like emotion) requires approval through Microsoft's Responsible AI access program due to ethical concerns.\n\n```mermaid\nflowchart TD\n    A[Input Image] --\u003e B[Azure Face API]\n    B --\u003e C[Face Detection\\nBounding Box]\n    C --\u003e D[Open Access\\nGlasses · Mask · Blur · Exposure]\n    C --\u003e E[Liveness Detection\\nAnti-spoofing]\n    C --\u003e F[Face ID]\n    F --\u003e|Restricted Access| G[1:1 Verification\\nSame Person?]\n    F --\u003e|Restricted Access| H[1:N Identification\\nWho is this?]\n    F --\u003e|Restricted Access| I[Emotion · Age Attributes]\n```\n\n**Available capabilities:**\n\n| Feature | Access | Description |\n|---------|--------|-------------|\n| **Face Detection** | Open | Locate faces + bounding boxes in images |\n| **Face Attributes** | Restricted | Age, glasses, blur, exposure, noise, mask detection |\n| **Face Verification** | Restricted | Are two faces the same person? (1:1) |\n| **Face Identification** | Restricted | Who is this person? (1:N against a group) |\n| **Liveness Detection** | Open | Prevent spoofing with static photos |\n\n**Basic face detection (Python):**\n\n```python\nfrom azure.cognitiveservices.vision.face import FaceClient\nfrom msrest.authentication import CognitiveServicesCredentials\n\nface_client = FaceClient(\n    \"\u003cendpoint\u003e\",\n    CognitiveServicesCredentials(\"\u003ckey\u003e\")\n)\n\n# Detect faces in an image URL\ndetected_faces = face_client.face.detect_with_url(\n    url=\"https://example.com/group-photo.jpg\",\n    return_face_attributes=[\"age\", \"gender\", \"headPose\", \"glasses\", \"blur\"],\n    detection_model=\"detection_03\",\n    recognition_model=\"recognition_04\"\n)\n\nfor face in detected_faces:\n    r = face.face_rectangle\n    print(f\"Face at ({r.left},{r.top}) size {r.width}x{r.height}\")\n    print(f\"  Glasses: {face.face_attributes.glasses}\")\n    print(f\"  Blur: {face.face_attributes.blur.blur_level}\")\n```\n\n**Responsible use note:** Facial recognition carries privacy risks. Microsoft requires a use-case justification and legal review before granting access to identification and verification capabilities.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you detect faces and check liveness using the Azure Face API in C#?\n\n**Use case:** A workplace access-control application in .NET that detects faces in camera frames, checks for presentation-attack liveness, and verifies whether the detected face matches an enrolled employee — using only the open-access capabilities of the Azure Face API.\n\n**Install the NuGet package:**\n\n```bash\ndotnet add package Microsoft.Azure.CognitiveServices.Vision.Face\n```\n\n**Face detection with attributes (C#):**\n\n```csharp\nusing Microsoft.Azure.CognitiveServices.Vision.Face;\nusing Microsoft.Azure.CognitiveServices.Vision.Face.Models;\n\nstring faceKey      = \"\u003cyour-face-key\u003e\";\nstring faceEndpoint = \"https://\u003cyour-resource\u003e.cognitiveservices.azure.com/\";\n\nvar faceClient = new FaceClient(\n    new ApiKeyServiceClientCredentials(faceKey))\n{\n    Endpoint = faceEndpoint\n};\n\n// ─── DETECT FACES FROM URL ────────────────────────────────────────────────────\nIList\u003cDetectedFace\u003e faces = await faceClient.Face.DetectWithUrlAsync(\n    url: \"https://example.com/office-entrance.jpg\",\n    returnFaceAttributes: new List\u003cFaceAttributeType\u003e\n    {\n        FaceAttributeType.Glasses,\n        FaceAttributeType.Blur,\n        FaceAttributeType.Exposure,\n        FaceAttributeType.Mask          // open-access: mask detection\n    },\n    detectionModel : DetectionModel.Detection03,\n    recognitionModel: RecognitionModel.Recognition04,\n    returnFaceId: true\n);\n\nConsole.WriteLine($\"Detected {faces.Count} face(s):\");\nforeach (DetectedFace face in faces)\n{\n    FaceRectangle r = face.FaceRectangle;\n    Console.WriteLine($\"  Face ID  : {face.FaceId}\");\n    Console.WriteLine($\"  Location : ({r.Left},{r.Top}) {r.Width}×{r.Height}\");\n    Console.WriteLine($\"  Glasses  : {face.FaceAttributes.Glasses}\");\n    Console.WriteLine($\"  Blur     : {face.FaceAttributes.Blur?.BlurLevel}\");\n    Console.WriteLine($\"  Mask     : {face.FaceAttributes.Mask?.Type}\");\n    Console.WriteLine();\n}\n\n// ─── DETECT FACES FROM LOCAL FILE ────────────────────────────────────────────\nusing var imageStream = File.OpenRead(\"./images/entrance.jpg\");\nIList\u003cDetectedFace\u003e localFaces = await faceClient.Face.DetectWithStreamAsync(\n    image: imageStream,\n    detectionModel : DetectionModel.Detection03,\n    recognitionModel: RecognitionModel.Recognition04,\n    returnFaceId: true\n);\n\nConsole.WriteLine($\"Local image: detected {localFaces.Count} face(s).\");\n```\n\n**Face verification — are two faces the same person? (restricted access required):**\n\n```csharp\n// Note: Face verification requires approved access via Microsoft RAI program.\n// The code below demonstrates the pattern once access is granted.\n\n// Detect face from enrolled employee photo\nIList\u003cDetectedFace\u003e enrolledFaces = await faceClient.Face.DetectWithUrlAsync(\n    \"https://example.com/employee-john.jpg\",\n    returnFaceId: true,\n    recognitionModel: RecognitionModel.Recognition04,\n    detectionModel: DetectionModel.Detection03\n);\n\n// Detect face from live camera frame\nIList\u003cDetectedFace\u003e liveFaces = await faceClient.Face.DetectWithUrlAsync(\n    \"https://example.com/live-frame.jpg\",\n    returnFaceId: true,\n    recognitionModel: RecognitionModel.Recognition04,\n    detectionModel: DetectionModel.Detection03\n);\n\nif (enrolledFaces.Count \u003e 0 \u0026\u0026 liveFaces.Count \u003e 0)\n{\n    VerifyResult verifyResult = await faceClient.Face.VerifyFaceToFaceAsync(\n        faceId1: enrolledFaces[0].FaceId!.Value,\n        faceId2: liveFaces[0].FaceId!.Value\n    );\n\n    Console.WriteLine($\"Same person : {verifyResult.IsIdentical}\");\n    Console.WriteLine($\"Confidence  : {verifyResult.Confidence:P1}\");\n\n    string decision = verifyResult.IsIdentical \u0026\u0026 verifyResult.Confidence \u003e 0.8\n        ? \"ACCESS GRANTED\" : \"ACCESS DENIED\";\n    Console.WriteLine($\"Decision    : {decision}\");\n}\n```\n\n**Face API capability access summary:**\n\n| Capability | Access level | C# method |\n|------------|-------------|----------|\n| Face detection (bounding box) | Open | `DetectWithUrlAsync` / `DetectWithStreamAsync` |\n| Mask \u0026 blur attributes | Open | `FaceAttributeType.Mask`, `.Blur` |\n| Glasses, exposure attributes | Open | `FaceAttributeType.Glasses`, `.Exposure` |\n| Liveness detection | Open (separate SDK) | `FaceSessionClient` (preview) |\n| Face verification (1:1) | Restricted | `VerifyFaceToFaceAsync` |\n| Face identification (1:N) | Restricted | `IdentifyAsync` with `PersonGroup` |\n| Emotion, age attributes | Restricted | `FaceAttributeType.Emotion`, `.Age` |\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 9. AZURE DOCUMENT INTELLIGENCE\n\n\u003cbr\u003e\n\n## Q. What is Azure Document Intelligence and how does it work?\n\n**Azure Document Intelligence** (formerly Form Recognizer) is an AI service that extracts structured data — text, key-value pairs, tables, and fields — from documents such as invoices, receipts, contracts, IDs, and tax forms.\n\n```mermaid\nflowchart TD\n    A[Document\\nPDF · Image · DOCX] --\u003e B[Document Intelligence API]\n    B --\u003e C{Model Selection}\n    C --\u003e D[Prebuilt Models\\ninvoice · receipt · idDocument\\nbusinessCard · contract]\n    C --\u003e E[Layout / Read\\nGeneral OCR + Tables]\n    C --\u003e F[Custom Model\\nTemplate · Neural]\n    D --\u003e G[Structured Fields\\nKey-Value · Tables · Line Items]\n    E --\u003e G\n    F --\u003e G\n    G --\u003e H[Downstream Systems\\nERP · Database · App]\n```\n\n**Pre-built models available:**\n\n| Model | Document Type |\n|-------|--------------|\n| `prebuilt-invoice` | Invoices (vendor, amounts, line items) |\n| `prebuilt-receipt` | Receipts (merchant, total, items) |\n| `prebuilt-idDocument` | Passports, driver's licenses |\n| `prebuilt-businessCard` | Business cards (name, phone, email) |\n| `prebuilt-contract` | Legal contracts (parties, clauses) |\n| `prebuilt-layout` | General layout + tables + OCR |\n| `prebuilt-read` | Plain text extraction |\n| **Custom model** | Train on your own document types |\n\n**Analyzing an invoice with Python:**\n\n```python\nfrom azure.ai.documentintelligence import DocumentIntelligenceClient\nfrom azure.ai.documentintelligence.models import AnalyzeDocumentRequest\nfrom azure.core.credentials import AzureKeyCredential\n\nclient = DocumentIntelligenceClient(\n    endpoint=\"https://\u003cyour-resource\u003e.cognitiveservices.azure.com/\",\n    credential=AzureKeyCredential(\"\u003cyour-key\u003e\")\n)\n\npoller = client.begin_analyze_document(\n    \"prebuilt-invoice\",\n    AnalyzeDocumentRequest(url_source=\"https://example.com/invoice.pdf\")\n)\nresult = poller.result()\n\nfor invoice in result.documents:\n    fields = invoice.fields\n    print(f\"Vendor:    {fields.get('VendorName', {}).get('content')}\")\n    print(f\"Total:     {fields.get('InvoiceTotal', {}).get('content')}\")\n    print(f\"Date:      {fields.get('InvoiceDate', {}).get('content')}\")\n    print(f\"Invoice #: {fields.get('InvoiceId', {}).get('content')}\")\n```\n\n**Training a custom model:**\n\n```python\n# 1. Label documents in Document Intelligence Studio (studio.cognitiveservices.azure.com)\n# 2. Build the model\npoller = client.begin_build_document_model(\n    build_mode=\"template\",  # or \"neural\"\n    blob_container_url=\"https://\u003cstorage\u003e.blob.core.windows.net/\u003ccontainer\u003e?\u003csas\u003e\",\n    model_id=\"my-custom-invoice-model\"\n)\nmodel = poller.result()\nprint(f\"Model '{model.model_id}' built — accuracy: {model.doc_types}\")\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you extract structured data from documents using Azure Document Intelligence in C#?\n\n**Use case:** An accounts-payable automation system in .NET that processes incoming PDF invoices from Azure Blob Storage, extracts vendor details and line items using the `prebuilt-invoice` model, and writes results to a SQL database.\n\n**Install the NuGet package:**\n\n```bash\ndotnet add package Azure.AI.DocumentIntelligence\n```\n\n**Extract invoice fields with the prebuilt model (C#):**\n\n```csharp\nusing Azure;\nusing Azure.AI.DocumentIntelligence;\n\nvar client = new DocumentIntelligenceClient(\n    new Uri(\"https://\u003cyour-resource\u003e.cognitiveservices.azure.com/\"),\n    new AzureKeyCredential(\"\u003cyour-key\u003e\")\n);\n\n// ─── ANALYSE INVOICE FROM URL ─────────────────────────────────────────────────\nOperation\u003cAnalyzeResult\u003e operation = await client.AnalyzeDocumentAsync(\n    WaitUntil.Completed,\n    \"prebuilt-invoice\",\n    new AnalyzeDocumentContent\n    {\n        UrlSource = new Uri(\"https://example.com/invoice.pdf\")\n    });\n\nAnalyzeResult result = operation.Value;\n\nforeach (AnalyzedDocument invoice in result.Documents)\n{\n    Console.WriteLine(\"=== Invoice ===\");\n\n    if (invoice.Fields.TryGetValue(\"VendorName\",    out DocumentField? vendor))\n        Console.WriteLine($\"  Vendor    : {vendor.ValueString}\");\n\n    if (invoice.Fields.TryGetValue(\"InvoiceId\",     out DocumentField? invoiceId))\n        Console.WriteLine($\"  Invoice # : {invoiceId.ValueString}\");\n\n    if (invoice.Fields.TryGetValue(\"InvoiceDate\",   out DocumentField? date))\n        Console.WriteLine($\"  Date      : {date.ValueDate}\");\n\n    if (invoice.Fields.TryGetValue(\"DueDate\",       out DocumentField? due))\n        Console.WriteLine($\"  Due Date  : {due.ValueDate}\");\n\n    if (invoice.Fields.TryGetValue(\"InvoiceTotal\",  out DocumentField? total))\n        Console.WriteLine($\"  Total     : {total.ValueCurrency?.Amount:C} {total.ValueCurrency?.CurrencyCode}\");\n\n    if (invoice.Fields.TryGetValue(\"SubTotal\",      out DocumentField? sub))\n        Console.WriteLine($\"  Subtotal  : {sub.ValueCurrency?.Amount:C}\");\n\n    // ─── LINE ITEMS ────────────────────────────────────────────────────────────\n    if (invoice.Fields.TryGetValue(\"Items\", out DocumentField? items)\n        \u0026\u0026 items.ValueList is not null)\n    {\n        Console.WriteLine(\"  Line Items:\");\n        foreach (DocumentField item in items.ValueList)\n        {\n            if (item.ValueDictionary is null) continue;\n\n            item.ValueDictionary.TryGetValue(\"Description\", out DocumentField? desc);\n            item.ValueDictionary.TryGetValue(\"Quantity\",    out DocumentField? qty);\n            item.ValueDictionary.TryGetValue(\"UnitPrice\",   out DocumentField? price);\n            item.ValueDictionary.TryGetValue(\"Amount\",      out DocumentField? amount);\n\n            Console.WriteLine($\"    {desc?.ValueString,-35} qty: {qty?.ValueDouble,5} \" +\n                              $\"@ {price?.ValueCurrency?.Amount,8:C} = {amount?.ValueCurrency?.Amount,10:C}\");\n        }\n    }\n}\n```\n\n**Analyse a local PDF file using a stream:**\n\n```csharp\nusing var pdfStream = File.OpenRead(\"./invoices/march-invoice.pdf\");\nOperation\u003cAnalyzeResult\u003e streamOp = await client.AnalyzeDocumentAsync(\n    WaitUntil.Completed,\n    \"prebuilt-invoice\",\n    new AnalyzeDocumentContent { Base64Source = BinaryData.FromStream(pdfStream) }\n);\n\nAnalyzeResult streamResult = streamOp.Value;\nConsole.WriteLine($\"Pages analysed: {streamResult.Pages.Count}\");\n```\n\n**Build and use a custom document model (C#):**\n\n```csharp\n// ─── BUILD CUSTOM MODEL (run once) ────────────────────────────────────────────\n// Label documents first in Document Intelligence Studio, then:\nBuildDocumentModelOperation buildOp = await client.BuildDocumentModelAsync(\n    WaitUntil.Completed,\n    new BuildDocumentModelContent(\n        modelId  : \"purchase-order-model\",\n        buildMode: DocumentBuildMode.Template)\n    {\n        AzureBlobSource = new AzureBlobContentSource(\n            new Uri(\"https://\u003cstorage\u003e.blob.core.windows.net/\u003ccontainer\u003e?\u003csas\u003e\")\n        ),\n        Description = \"Custom PO extraction model\"\n    }\n);\n\nDocumentModelDetails model = buildOp.Value;\nConsole.WriteLine($\"Model '{model.ModelId}' built — doc types: {model.DocTypes.Count}\");\n\n// ─── USE CUSTOM MODEL ─────────────────────────────────────────────────────────\nOperation\u003cAnalyzeResult\u003e customOp = await client.AnalyzeDocumentAsync(\n    WaitUntil.Completed,\n    \"purchase-order-model\",\n    new AnalyzeDocumentContent\n    {\n        UrlSource = new Uri(\"https://example.com/po-2026-001.pdf\")\n    });\n\nforeach (AnalyzedDocument doc in customOp.Value.Documents)\n{\n    if (doc.Fields.TryGetValue(\"PONumber\",  out DocumentField? poNum))\n        Console.WriteLine($\"PO Number  : {poNum.ValueString}\");\n    if (doc.Fields.TryGetValue(\"Requester\", out DocumentField? req))\n        Console.WriteLine($\"Requester  : {req.ValueString}\");\n}\n```\n\n**Prebuilt models available in C#:**\n\n| Model ID | Document type | Key extracted fields |\n|----------|--------------|---------------------|\n| `prebuilt-invoice` | Invoices | VendorName, InvoiceTotal, Items, DueDate |\n| `prebuilt-receipt` | Receipts | MerchantName, Total, TransactionDate |\n| `prebuilt-idDocument` | Passports, licences | FirstName, LastName, DateOfBirth, DocumentNumber |\n| `prebuilt-businessCard` | Business cards | ContactNames, Emails, PhoneNumbers |\n| `prebuilt-contract` | Legal contracts | Parties, Dates, RenewalDate |\n| `prebuilt-layout` | Any document | Tables, paragraphs, selection marks |\n| `prebuilt-read` | Any document | Full text, language, handwritten text |\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 10. AZURE LANGUAGE SERVICE\n\n\u003cbr\u003e\n\n## Q. What features does Azure Language Service offer?\n\n**Azure Language Service** is a unified NLP service that consolidates text analytics, language understanding, and question answering into a single resource.\n\n```mermaid\nflowchart LR\n    A[Input Text] --\u003e B[Azure Language Service]\n    B --\u003e C[Sentiment Analysis\\nOpinion Mining]\n    B --\u003e D[Named Entity Recognition\\nPerson · Org · Location · Date]\n    B --\u003e E[PII Detection \u0026 Redaction]\n    B --\u003e F[Key Phrase Extraction]\n    B --\u003e G[Language Detection]\n    B --\u003e H[Question Answering QnA]\n    B --\u003e I[Conversational CLU\\nIntent · Entity]\n    B --\u003e J[Text Summarization\\nExtractive · Abstractive]\n    B --\u003e K[Healthcare NLP]\n```\n\n**Available features:**\n\n| Feature | Description |\n|---------|-------------|\n| **Sentiment Analysis** | Positive/negative/neutral + opinion mining |\n| **Named Entity Recognition (NER)** | Identify persons, organizations, locations, dates |\n| **PII Detection** | Detect and redact personally identifiable information |\n| **Key Phrase Extraction** | Extract the most important phrases |\n| **Language Detection** | Identify the language of text |\n| **Entity Linking** | Link entities to Wikipedia |\n| **Text Classification** | Custom single-label / multi-label classification |\n| **Custom NER** | Train models to extract domain-specific entities |\n| **Question Answering (QnA)** | Build FAQ bots from documents/URLs |\n| **Conversational Language Understanding (CLU)** | Intent + entity recognition for chatbots |\n| **Text Summarization** | Extractive and abstractive summarization |\n| **Healthcare NLP** | Clinical entities from medical text |\n\n**Example — multi-feature analysis:**\n\n```python\nfrom azure.ai.textanalytics import TextAnalyticsClient\nfrom azure.core.credentials import AzureKeyCredential\n\nclient = TextAnalyticsClient(\n    endpoint=\"https://\u003cresource\u003e.cognitiveservices.azure.com/\",\n    credential=AzureKeyCredential(\"\u003ckey\u003e\")\n)\n\ndocs = [\n    \"Microsoft released Azure AI Studio in 2024 from its Redmond headquarters.\",\n    \"Patient John Doe, DOB 01/15/1980, was prescribed Metformin 500mg.\"\n]\n\n# Named Entity Recognition\nner_results = client.recognize_entities(docs)\nfor doc in ner_results:\n    for entity in doc.entities:\n        print(f\"{entity.text:30} | Category: {entity.category:20} | Confidence: {entity.confidence_score:.2f}\")\n\n# PII Detection\npii_results = client.recognize_pii_entities([docs[1]])\nfor doc in pii_results:\n    print(f\"Redacted: {doc.redacted_text}\")\n\n# Sentiment with opinion mining\nsa_results = client.analyze_sentiment(docs, show_opinion_mining=True)\nfor doc in sa_results:\n    print(f\"Sentiment: {doc.sentiment}\")\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you use Azure AI Language Service for NLP tasks in C#?\n\n**Use case:** A customer-feedback pipeline in .NET that runs sentiment analysis with opinion mining, extracts named entities, detects PII, and generates an abstractive summary — all in a single batched call from an ASP.NET Core background worker.\n\n**Install the NuGet package:**\n\n```bash\ndotnet add package Azure.AI.TextAnalytics\n```\n\n**Sentiment analysis, NER, PII detection, and summarisation (C#):**\n\n```csharp\nusing Azure;\nusing Azure.AI.TextAnalytics;\n\nvar client = new TextAnalyticsClient(\n    new Uri(\"https://\u003cyour-resource\u003e.cognitiveservices.azure.com/\"),\n    new AzureKeyCredential(\"\u003cyour-key\u003e\")\n);\n\nvar documents = new List\u003cstring\u003e\n{\n    \"Microsoft released Azure AI Studio from its Redmond HQ in 2024. The platform is excellent.\",\n    \"Patient John Doe, DOB 01/15/1980, was prescribed Metformin 500mg by Dr. Smith.\"\n};\n\n// ─── 1. SENTIMENT WITH OPINION MINING ────────────────────────────────────────\nConsole.WriteLine(\"=== Sentiment Analysis ===\");\nAnalyzeSentimentResultCollection sentimentResults =\n    await client.AnalyzeSentimentBatchAsync(documents, options: new AnalyzeSentimentOptions\n    {\n        IncludeOpinionMining = true\n    });\n\nforeach (AnalyzeSentimentResult result in sentimentResults)\n{\n    Console.WriteLine($\"  Overall   : {result.DocumentSentiment.Sentiment}\");\n    Console.WriteLine($\"  Positive  : {result.DocumentSentiment.ConfidenceScores.Positive:P1}\");\n    Console.WriteLine($\"  Negative  : {result.DocumentSentiment.ConfidenceScores.Negative:P1}\");\n\n    foreach (SentenceSentiment sentence in result.DocumentSentiment.Sentences)\n    {\n        Console.WriteLine($\"  Sentence  : \\\"{sentence.Text}\\\" → {sentence.Sentiment}\");\n        foreach (SentenceOpinion opinion in sentence.Opinions)\n        {\n            Console.WriteLine($\"    Target  : {opinion.Target.Text} ({opinion.Target.Sentiment})\");\n            foreach (AssessmentSentiment assessment in opinion.Assessments)\n                Console.WriteLine($\"    Opinion : {assessment.Text} ({assessment.Sentiment})\");\n        }\n    }\n}\n\n// ─── 2. NAMED ENTITY RECOGNITION ─────────────────────────────────────────────\nConsole.WriteLine(\"\\n=== Named Entity Recognition ===\");\nRecognizeEntitiesResultCollection nerResults =\n    await client.RecognizeEntitiesBatchAsync(documents);\n\nforeach (RecognizeEntitiesResult result in nerResults)\n    foreach (CategorizedEntity entity in result.Entities)\n        Console.WriteLine(\n            $\"  {entity.Text,-30} | {entity.Category,-20} | Sub: {entity.SubCategory,-15} | Conf: {entity.ConfidenceScore:P0}\");\n\n// ─── 3. PII DETECTION \u0026 REDACTION ────────────────────────────────────────────\nConsole.WriteLine(\"\\n=== PII Detection ===\");\nRecognizePiiEntitiesResultCollection piiResults =\n    await client.RecognizePiiEntitiesBatchAsync(new[] { documents[1] });\n\nforeach (RecognizePiiEntitiesResult result in piiResults)\n{\n    Console.WriteLine($\"  Redacted  : {result.Entities.RedactedText}\");\n    foreach (PiiEntity entity in result.Entities)\n        Console.WriteLine($\"  PII       : {entity.Text,-25} | Category: {entity.Category}\");\n}\n\n// ─── 4. ABSTRACTIVE SUMMARISATION ────────────────────────────────────────────\nConsole.WriteLine(\"\\n=== Abstractive Summarisation ===\");\nAbstractSummaryOperation summaryOp = await client.AbstractSummaryAsync(\n    Azure.WaitUntil.Completed,\n    documents,\n    options: new AbstractSummaryOptions { SentenceCount = 2 }\n);\n\nawait foreach (AbstractSummaryResultCollection page in summaryOp)\n    foreach (AbstractSummaryResult result in page)\n        foreach (AbstractiveSummary summary in result.Summaries)\n            Console.WriteLine($\"  Summary: {summary.Text}\");\n```\n\n**Key Phrase Extraction and Language Detection:**\n\n```csharp\n// ─── KEY PHRASE EXTRACTION ────────────────────────────────────────────────────\nExtractKeyPhrasesResultCollection kpResults =\n    await client.ExtractKeyPhrasesBatchAsync(documents);\n\nforeach (ExtractKeyPhrasesResult result in kpResults)\n    Console.WriteLine(\"  Key phrases: \" + string.Join(\", \", result.KeyPhrases));\n\n// ─── LANGUAGE DETECTION ───────────────────────────────────────────────────────\nvar multiLangDocs = new List\u003cstring\u003e\n{\n    \"Azure AI is transforming enterprise applications.\",\n    \"Azure AI transformiert Unternehmensanwendungen.\",\n    \"Azure AI transforme les applications d'entreprise.\"\n};\n\nDetectLanguageResultCollection langResults =\n    await client.DetectLanguageBatchAsync(multiLangDocs);\n\nforeach (DetectLanguageResult result in langResults)\n    Console.WriteLine(\n        $\"  Language: {result.PrimaryLanguage.Name,-15} | ISO: {result.PrimaryLanguage.Iso6391Name} | Conf: {result.PrimaryLanguage.ConfidenceScore:P0}\");\n```\n\n**Azure AI Language features available in .NET:**\n\n| Feature | SDK method | Use case |\n|---------|-----------|----------|\n| Sentiment + opinion mining | `AnalyzeSentimentBatchAsync` | Customer feedback, reviews |\n| Named Entity Recognition | `RecognizeEntitiesBatchAsync` | Document processing |\n| PII Detection \u0026 redaction | `RecognizePiiEntitiesBatchAsync` | GDPR compliance |\n| Key Phrase Extraction | `ExtractKeyPhrasesBatchAsync` | Search indexing |\n| Language Detection | `DetectLanguageBatchAsync` | Multilingual routing |\n| Linked Entities | `RecognizeLinkedEntitiesBatchAsync` | Knowledge graph |\n| Abstractive Summary | `AbstractSummaryAsync` | Report summarisation |\n| Extractive Summary | `ExtractiveSummaryAsync` | Document highlights |\n| Custom Classification | `ClassifyDocumentAsync` | Domain-specific routing |\n| Healthcare NLP | `AnalyzeHealthcareEntitiesAsync` | Clinical text extraction |\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 11. AZURE TRANSLATOR\n\n\u003cbr\u003e\n\n## Q. What is Azure Translator and what are its key features?\n\n**Azure Translator** is a cloud-based neural machine translation service supporting 100+ languages and dialects. It provides text translation, transliteration, language detection, and dictionary lookup via a simple REST API.\n\n```mermaid\nflowchart LR\n    A[Source Text\\n100+ Languages] --\u003e B[Azure Translator API]\n    B --\u003e C[Language Detection\\nAuto-identify source]\n    B --\u003e D[Text Translation\\n100+ target languages]\n    B --\u003e E[Transliteration\\nScript Conversion]\n    B --\u003e F[Document Translation\\nPDF · DOCX · HTML]\n    B --\u003e G[Dictionary Lookup\\nBilingual Examples]\n    D --\u003e H[Translated Text]\n    F --\u003e I[Translated Document\\nLayout Preserved]\n```\n\n**Key features:**\n\n| Feature | Description |\n|---------|-------------|\n| **Text Translation** | Translate text in 100+ languages |\n| **Document Translation** | Asynchronously translate entire documents (PDF, DOCX, HTML) preserving layout |\n| **Custom Translator** | Fine-tune translation models with domain-specific parallel corpus |\n| **Transliteration** | Convert text between scripts (e.g., Arabic → Latin) |\n| **Language Detection** | Auto-detect source language |\n| **Dictionary Lookup** | Bilingual dictionary with examples |\n\n**Translating text with Python:**\n\n```python\nimport requests, uuid, json, os\n\nendpoint = \"https://api.cognitive.microsofttranslator.com\"\nkey = \"\u003cyour-translator-key\u003e\"\nlocation = \"eastus\"\n\ndef translate(texts: list[str], target_languages: list[str]) -\u003e list:\n    url = f\"{endpoint}/translate\"\n    params = {\"api-version\": \"3.0\", \"to\": target_languages}\n    headers = {\n        \"Ocp-Apim-Subscription-Key\": key,\n        \"Ocp-Apim-Subscription-Region\": location,\n        \"Content-type\": \"application/json\",\n        \"X-ClientTraceId\": str(uuid.uuid4())\n    }\n    body = [{\"text\": t} for t in texts]\n    response = requests.post(url, params=params, headers=headers, json=body)\n    return response.json()\n\nresults = translate(\n    [\"Hello, how are you?\", \"Azure AI is amazing.\"],\n    [\"fr\", \"de\", \"ja\"]\n)\n\nfor item in results:\n    for translation in item[\"translations\"]:\n        print(f\"[{translation['to']}] {translation['text']}\")\n```\n\n**Document Translation (async):**\n\n```python\nfrom azure.ai.translation.document import DocumentTranslationClient\nfrom azure.core.credentials import AzureKeyCredential\n\nclient = DocumentTranslationClient(\"\u003cendpoint\u003e\", AzureKeyCredential(\"\u003ckey\u003e\"))\n\npoller = client.begin_translation(\n    source_url=\"https://\u003cstorage\u003e.blob.core.windows.net/source?\u003csas\u003e\",\n    target_url=\"https://\u003cstorage\u003e.blob.core.windows.net/target-fr?\u003csas\u003e\",\n    target_language=\"fr\"\n)\n\nresult = poller.result()\nfor doc in result:\n    print(f\"Translated: {doc.source_document_url} → Status: {doc.status}\")\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How do you translate text and detect languages using Azure Translator in C#?\n\n**Use case:** A multilingual customer-support portal in ASP.NET Core that auto-detects the language of incoming messages, translates them to English for agents, and sends responses back translated into the customer's language — using the `Azure.AI.Translation.Text` NuGet package.\n\n**Install the NuGet packages:**\n\n```bash\ndotnet add package Azure.AI.Translation.Text\ndotnet add package Azure.AI.Translation.Document\n```\n\n**Text translation and language detection (C#):**\n\n```csharp\nusing Azure;\nusing Azure.AI.Translation.Text;\n\nvar client = new TextTranslationClient(\n    new AzureKeyCredential(\"\u003cyour-translator-key\u003e\"),\n    region: \"eastus\"\n);\n\n// ─── 1. DETECT LANGUAGE ───────────────────────────────────────────────────────\nstring inputText = \"Azure AI はエンタープライズ アプリケーションを変革しています。\";\n\nResponse\u003cIReadOnlyList\u003cDetectedLanguage\u003e\u003e detectResponse =\n    await client.DetectLanguageAsync(new[] { new DetectLanguageInput(inputText) });\n\nDetectedLanguage detected = detectResponse.Value[0];\nConsole.WriteLine($\"Detected language : {detected.Language} (confidence: {detected.Score:P1})\");\n\n// ─── 2. TRANSLATE TO MULTIPLE LANGUAGES ──────────────────────────────────────\nstring[] targetLanguages = [\"en\", \"fr\", \"de\", \"es\"];\n\nResponse\u003cIReadOnlyList\u003cTranslatedTextItem\u003e\u003e translateResponse =\n    await client.TranslateAsync(targetLanguages, new[] { new TextTranslationInput(inputText) });\n\nforeach (TranslatedTextItem item in translateResponse.Value)\n{\n    Console.WriteLine($\"\\nSource detected: {item.DetectedLanguage?.Language}\");\n    foreach (Translation translation in item.Translations)\n        Console.WriteLine($\"  [{translation.To}] {translation.Text}\");\n}\n\n// ─── 3. TRANSLATE WITH EXPLICIT SOURCE LANGUAGE ──────────────────────────────\nResponse\u003cIReadOnlyList\u003cTranslatedTextItem\u003e\u003e explicitResponse = await client.TranslateAsync(\n    targetLanguages: [\"en\"],\n    content: new[] { new TextTranslationInput(\"Bonjour, comment puis-je vous aider?\") },\n    sourceLanguage: \"fr\"\n);\n\nConsole.WriteLine($\"\\nFR → EN: {explicitResponse.Value[0].Translations[0].Text}\");\n\n// ─── 4. TRANSLITERATION (script conversion) ───────────────────────────────────\nResponse\u003cIReadOnlyList\u003cTransliteratedText\u003e\u003e translitResponse =\n    await client.TransliterateAsync(\n        language: \"ja\",\n        fromScript: \"Jpan\",   // Japanese script\n        toScript:   \"Latn\",   // Latin script (romaji)\n        content: new[] { new TransliterateTextInput(\"こんにちは\") }\n    );\n\nConsole.WriteLine($\"\\nTransliteration: {translitResponse.Value[0].Text}\");\n\n// ─── 5. DICTIONARY LOOKUP ─────────────────────────────────────────────────────\nResponse\u003cIReadOnlyList\u003cDictionaryLookupItem\u003e\u003e dictResponse =\n    await client.LookupDictionaryEntriesAsync(\n        sourceLanguage: \"en\",\n        targetLanguage: \"es\",\n        content: new[] { new DictionaryLookupInput(\"amazing\") }\n    );\n\nforeach (DictionaryLookupItem item in dictResponse.Value)\n{\n    Console.WriteLine($\"\\nDictionary entries for '{item.NormalizedSource}':\");\n    foreach (DictionaryTranslation entry in item.Translations.Take(3))\n        Console.WriteLine($\"  {entry.NormalizedTarget,-20} (confidence: {entry.Confidence:P0})\");\n}\n```\n\n**Async document translation (C#):**\n\n```csharp\nusing Azure.AI.Translation.Document;\n\nvar docClient = new DocumentTranslationClient(\n    new Uri(\"https://\u003cyour-resource\u003e.cognitiveservices.azure.com/\"),\n    new AzureKeyCredential(\"\u003cyour-key\u003e\")\n);\n\n// Translate all documents in a Blob container from English to French\nvar translationInputs = new List\u003cDocumentTranslationInput\u003e\n{\n    new DocumentTranslationInput(\n        sourceUri: new Uri(\"https://\u003cstorage\u003e.blob.core.windows.net/source-docs?\u003csas\u003e\"),\n        targetUri: new Uri(\"https://\u003cstorage\u003e.blob.core.windows.net/target-fr?\u003csas\u003e\"),\n        targetLanguageCode: \"fr\"\n    )\n};\n\nDocumentTranslationOperation operation =\n    await docClient.StartTranslationAsync(translationInputs);\n\nawait operation.WaitForCompletionAsync();\n\nConsole.WriteLine($\"Status       : {operation.Status}\");\nConsole.WriteLine($\"Created      : {operation.CreatedOn}\");\nConsole.WriteLine($\"Last updated : {operation.LastModified}\");\n\nawait foreach (DocumentStatusResult doc in operation.GetAllDocumentStatusesAsync())\n{\n    Console.WriteLine($\"  {Path.GetFileName(doc.SourceDocumentUri.ToString()),-40} \" +\n                      $\"→ {doc.Status,-15} ({doc.TranslatedToLanguageCode})\");\n}\n```\n\n**Azure Translator capabilities in .NET:**\n\n| Feature | SDK method | Notes |\n|---------|-----------|-------|\n| Text translation | `TranslateAsync` | 100+ languages, up to 50k chars/request |\n| Language detection | `DetectLanguageAsync` | Returns language + confidence score |\n| Transliteration | `TransliterateAsync` | Script-to-script conversion |\n| Dictionary lookup | `LookupDictionaryEntriesAsync` | Bilingual dictionary |\n| Dictionary examples | `LookupDictionaryExamplesAsync` | Contextual usage examples |\n| Supported languages | `GetSupportedLanguagesAsync` | Dynamic language list |\n| Document translation | `StartTranslationAsync` | PDF, DOCX, HTML, PPTX — async batch |\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#table-of-contents\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 12. AZURE SPEECH SERVICE\n\n\u003cbr\u003e\n\n## Q. What capabilities does Azure Speech Service provide?\n\n**Azure Speech Service** offers a comprehensive set of speech AI capabilities for converting audio to text, text to audio, translating spoken language, and verifying speaker identity.\n\n**Core features:**\n\n| Feature | Description |\n|---------|-------------|\n| **Speech-to-Text (STR)** | Real-time and batch transcription with custom acoustic/language models |\n| **Text-to-Speech (TTS)** | Neural voices (400+) in 140+ languages; custom neural voices |\n| **Speech Translation** | Real-time translation of spoken audio to another language |\n| **Speaker Recognition** | Verify or identify a speaker from their voice |\n| **Pronunciation Assessment** | Score pronunciation accuracy (for language learning) |\n| **Custom Speech** | Fine-tune STT on domain-specific vocabulary |\n| **Custom Neural Voice** | Create a branded synthetic voice |\n\n**Real-time speech-to-text example:**\n\n```python\nimport azure.cognitiveservices.speech as speechsdk\n\nspeech_config = speechsdk.SpeechConfig(\n    subscription=\"\u003cspeech-key\u003e\",\n    region=\"eastus\"\n)\nspeech_config.speech_recognition_language = \"en-US\"\n\naudio_config = speechsdk.audio.AudioConfig(use_default_microphone=True)\nrecognizer = speechsdk.SpeechRecognizer(speech_config=speech_config, audio_config=audio_config)\n\nprint(\"Speak into your microphone...\")\nresult = recognizer.recognize_once_async().get()\n\nif result.reason == speechsdk.ResultReason.RecognizedSpeech:\n    print(f\"Recognized: {result.text}\")\nelif result.reason == speechsdk.ResultReason.NoMatch:\n    print(\"No speech could be recognized.\")\nelif result.reason == speechsdk.ResultReason.Canceled:\n    print(f\"Canceled: {result.cancellation_details.reason}\")\n```\n\n**Neural Text-to-Speech:**\n\n```python\nspeech_config = speechsdk.SpeechConfig(subscription=\"\u003ckey\u003e\", region=\"eastus\")\nspeech_config.speech_synthesis_voice_name = \"en-US-JennyNeural\"\n\nsynthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config)\n\nssml = \"\"\"\n\u003cspeak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'\u003e\n    \u003cvoice nam","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flearning-zone%2Fazure-ai-basics","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flearning-zone%2Fazure-ai-basics","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flearning-zone%2Fazure-ai-basics/lists"}