Showing posts with label devops. Show all posts
Showing posts with label devops. Show all posts

Friday

Develop a Multi Agent Application and Deploy into Azure

                                                                      Azure


Let’s break this down into a clear roadmap so you can go from design to deployment smoothly.


🧩 Step 1: Define Your Multi‑Agent Architecture

  • Agents: Decide what roles your agents will play (e.g., data collector, analyzer, planner, executor).
  • Communication: Choose how agents will talk to each other — options include:
    • REST APIs
    • Azure Service Bus / Event Grid
    • Direct messaging via frameworks like LangChain or AutoGen
  • Coordination: Decide if you’ll use a central orchestrator (controller agent) or a peer‑to‑peer model.

⚙️ Step 2: Local Development

  • Frameworks: Use Python with LangChain, AutoGen, or Microsoft’s Semantic Kernel for agent orchestration.
  • Environment: Containerize each agent with Docker for portability.
  • Testing: Run locally with Docker Compose or Kubernetes (kind/minikube) to simulate multi‑agent interactions.

☁️ Step 3: Azure Infrastructure Setup

  1. Resource Group: Create a dedicated resource group for your project.
  2. Compute Options:
    • Azure Kubernetes Service (AKS) → best for scalable multi‑agent workloads.
    • Azure Container Apps → simpler, serverless container hosting.
    • Azure Functions → if agents are lightweight and event‑driven.
  3. Networking:
    • Use Azure Virtual Network for secure communication.
    • Configure Ingress Controller or Azure API Management for external access.

🔄 Step 4: Agent Deployment

  • Push Docker images to Azure Container Registry (ACR).
  • Deploy agents into AKS or Container Apps.
  • Use Helm charts or Bicep/ARM templates for repeatable deployments.

📡 Step 5: Communication & Orchestration

  • Service Bus/Event Grid → for asynchronous messaging between agents.
  • Azure Logic Apps or Durable Functions → for workflow orchestration if needed.
  • Cosmos DB / Azure Storage → for shared state or logs.

🔍 Step 6: Monitoring & Scaling

  • Azure Monitor + Application Insights → track agent performance and logs.
  • Autoscaling → configure AKS HPA (Horizontal Pod Autoscaler) or Container Apps scaling rules.
  • Security → manage secrets with Azure Key Vault.

🚀 Step 7: End‑to‑End Workflow Example

  1. User request hits API Gateway.
  2. Controller agent receives request, delegates tasks.
  3. Worker agents (e.g., data fetcher, analyzer, summarizer) process tasks.
  4. Results are aggregated and returned via API.
  5. Logs and metrics stored in Azure Monitor.

✅ Deliverables

  • Codebase: Python agents with orchestration logic.
  • Dockerfiles: For each agent.
  • Deployment scripts: Helm/Bicep/ARM templates.
  • Azure setup: Resource group, ACR, AKS/Container Apps, Service Bus, Monitor.

Perfect — let’s put this into something tangible. I’ll give you both a visual architecture diagram and a sample deployment manifest (Helm/YAML) so you can see how a multi‑agent system would be deployed end‑to‑end on Azure.


🏗️ High‑Level Architecture Diagram

                ┌───────────────────────────┐
                │       User / Client       │
                └─────────────┬─────────────┘
                              │
                      Azure API Management
                              │
                ┌─────────────┴─────────────┐
                │   Controller Agent Pod    │
                └─────────────┬─────────────┘
                              │
          ┌───────────────────┼───────────────────┐
          │                   │                   │
   Worker Agent A Pod   Worker Agent B Pod   Worker Agent C Pod
   (Data Fetcher)       (Analyzer)           (Summarizer)
          │                   │                   │
          └─────────────┬─────┴─────┬─────────────┘
                        │           │
                 Azure Service Bus / Event Grid
                        │
                 ┌──────┴───────────┐
                 │ Shared Storage   │
                 │ (Cosmos DB /     │
                 │  Blob Storage)   │
                 └──────────────────┘

Monitoring: Azure Monitor + App Insights
Secrets: Azure Key Vault
Images: Azure Container Registry
Deployment: AKS / Container Apps

📄 Sample Deployment YAML (AKS + Helm)

Here’s a simplified example of how you’d deploy controller and worker agents into AKS:

# values.yaml (Helm)
controller:
  image: myregistry.azurecr.io/controller-agent:latest
  replicas: 2
  resources:
    requests:
      cpu: "500m"
      memory: "512Mi"
    limits:
      cpu: "1"
      memory: "1Gi"

workers:
  - name: data-fetcher
    image: myregistry.azurecr.io/data-fetcher-agent:latest
    replicas: 3
  - name: analyzer
    image: myregistry.azurecr.io/analyzer-agent:latest
    replicas: 2
  - name: summarizer
    image: myregistry.azurecr.io/summarizer-agent:latest
    replicas: 2
# deployment.yaml (Helm template)
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ .Chart.Name }}-{{ .Values.controller.name }}
spec:
  replicas: {{ .Values.controller.replicas }}
  selector:
    matchLabels:
      app: controller-agent
  template:
    metadata:
      labels:
        app: controller-agent
    spec:
      containers:
        - name: controller-agent
          image: {{ .Values.controller.image }}
          resources:
            requests:
              cpu: {{ .Values.controller.resources.requests.cpu }}
              memory: {{ .Values.controller.resources.requests.memory }}
            limits:
              cpu: {{ .Values.controller.resources.limits.cpu }}
              memory: {{ .Values.controller.resources.limits.memory }}
---
{{- range .Values.workers }}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ $.Chart.Name }}-{{ .name }}
spec:
  replicas: {{ .replicas }}
  selector:
    matchLabels:
      app: {{ .name }}
  template:
    metadata:
      labels:
        app: {{ .name }}
    spec:
      containers:
        - name: {{ .name }}
          image: {{ .image }}
{{- end }}

🚀 End‑to‑End Flow

  1. Build & push imagesaz acr build → Azure Container Registry.
  2. Deploy Helm charthelm install multi-agent ./chart.
  3. Agents communicate via Service Bus/Event Grid.
  4. Monitor with Application Insights.
  5. Scale automatically with AKS HPA rules.

Excellent — let’s build out the Azure Bicep template so you can provision the entire environment (ACR, AKS, Service Bus, Key Vault, Monitor) in one go. This will give you an end‑to‑end infrastructure as code setup.


📄 Sample Bicep Template (multi‑agent app infra)

targetScope = 'resourceGroup'

@description('Name of the Azure Container Registry')
param acrName string = 'multiagentacr'

@description('Name of the AKS cluster')
param aksName string = 'multiagent-aks'

@description('Name of the Service Bus namespace')
param sbNamespace string = 'multiagent-sb'

@description('Name of the Key Vault')
param kvName string = 'multiagent-kv'

@description('Name of the Log Analytics workspace')
param logAnalyticsName string = 'multiagent-law'

@description('Location for all resources')
param location string = resourceGroup().location

// Azure Container Registry
resource acr 'Microsoft.ContainerRegistry/registries@2023-01-01-preview' = {
  name: acrName
  location: location
  sku: {
    name: 'Basic'
  }
  properties: {
    adminUserEnabled: true
  }
}

// Log Analytics Workspace
resource logAnalytics 'Microsoft.OperationalInsights/workspaces@2022-10-01' = {
  name: logAnalyticsName
  location: location
  properties: {
    sku: {
      name: 'PerGB2018'
    }
    retentionInDays: 30
  }
}

// AKS Cluster
resource aks 'Microsoft.ContainerService/managedClusters@2023-01-01' = {
  name: aksName
  location: location
  properties: {
    dnsPrefix: '${aksName}-dns'
    agentPoolProfiles: [
      {
        name: 'agentpool'
        count: 3
        vmSize: 'Standard_DS2_v2'
        osType: 'Linux'
        mode: 'System'
      }
    ]
    linuxProfile: {
      adminUsername: 'azureuser'
      ssh: {
        publicKeys: [
          {
            keyData: 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ...'
          }
        ]
      }
    }
    servicePrincipalProfile: {
      clientId: 'YOUR-SP-CLIENT-ID'
      secret: 'YOUR-SP-SECRET'
    }
    addonProfiles: {
      omsagent: {
        enabled: true
        config: {
          logAnalyticsWorkspaceResourceID: logAnalytics.id
        }
      }
    }
  }
}

// Service Bus Namespace
resource sb 'Microsoft.ServiceBus/namespaces@2021-06-01-preview' = {
  name: sbNamespace
  location: location
  sku: {
    name: 'Standard'
    tier: 'Standard'
  }
}

// Key Vault
resource kv 'Microsoft.KeyVault/vaults@2022-07-01' = {
  name: kvName
  location: location
  properties: {
    tenantId: subscription().tenantId
    sku: {
      name: 'standard'
      family: 'A'
    }
    accessPolicies: []
  }
}

🚀 How to Deploy

  1. Save the file as main.bicep.
  2. Run:
    az group create --name multiagent-rg --location eastus
    az deployment group create --resource-group multiagent-rg --template-file main.bicep
    
  3. This provisions:
    • ACR → for storing agent images.
    • AKS → for running multi‑agent workloads.
    • Service Bus → for agent communication.
    • Key Vault → for secrets.
    • Log Analytics + Monitor → for observability.

🔄 Next Steps

  • Push your agent Docker images into ACR.
  • Deploy Helm chart (from earlier step) into AKS.
  • Configure agents to use Service Bus for messaging.
  • Store sensitive configs in Key Vault.
  • Monitor with Application Insights linked to Log Analytics.

Perfect — let’s design a CI/CD pipeline so your multi‑agent application can be built, pushed, and deployed into Azure AKS automatically. I’ll show you a GitHub Actions workflow (you could adapt it to Azure DevOps if you prefer).


⚙️ CI/CD Pipeline Overview

  1. Trigger: On push to main or PR merge.
  2. Build: Build Docker images for each agent.
  3. Push: Push images to Azure Container Registry (ACR).
  4. Deploy: Use kubectl or Helm to deploy into AKS.
  5. Monitor: Integrate with Application Insights/Log Analytics.

📄 GitHub Actions Workflow Example

# .github/workflows/deploy.yml
name: Multi-Agent CI/CD

on:
  push:
    branches:
      - main

env:
  REGISTRY: multiagentacr.azurecr.io
  AKS_CLUSTER: multiagent-aks
  RESOURCE_GROUP: multiagent-rg

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest

    steps:
    - name: Checkout code
      uses: actions/checkout@v3

    - name: Log in to Azure
      uses: azure/login@v1
      with:
        creds: ${{ secrets.AZURE_CREDENTIALS }}

    - name: Log in to ACR
      run: az acr login --name $REGISTRY

    - name: Build and push Controller Agent
      run: |
        docker build -t $REGISTRY/controller-agent:latest ./controller
        docker push $REGISTRY/controller-agent:latest

    - name: Build and push Worker Agents
      run: |
        docker build -t $REGISTRY/data-fetcher-agent:latest ./workers/data-fetcher
        docker push $REGISTRY/data-fetcher-agent:latest
        docker build -t $REGISTRY/analyzer-agent:latest ./workers/analyzer
        docker push $REGISTRY/analyzer-agent:latest
        docker build -t $REGISTRY/summarizer-agent:latest ./workers/summarizer
        docker push $REGISTRY/summarizer-agent:latest

    - name: Set AKS context
      run: |
        az aks get-credentials --resource-group $RESOURCE_GROUP --name $AKS_CLUSTER

    - name: Deploy with Helm
      run: |
        helm upgrade --install multi-agent ./helm-chart \
          --set controller.image=$REGISTRY/controller-agent:latest \
          --set workers[0].image=$REGISTRY/data-fetcher-agent:latest \
          --set workers[1].image=$REGISTRY/analyzer-agent:latest \
          --set workers[2].image=$REGISTRY/summarizer-agent:latest

🔑 Secrets Required

  • AZURE_CREDENTIALS: JSON output from az ad sp create-for-rbac (Service Principal).
  • Docker images will be tagged and pushed to ACR.
  • Helm chart values updated automatically with latest image tags.

🚀 Deployment Flow

  1. Developer pushes code → GitHub Actions triggers.
  2. Pipeline builds Docker images for all agents.
  3. Images pushed to ACR.
  4. Helm deploys/updates AKS workloads.
  5. Agents start communicating via Service Bus/Event Grid.
  6. Logs flow into Application Insights.

Great — here’s the Azure DevOps pipeline version of the CI/CD flow we built earlier. This YAML will automate building your agents, pushing them to ACR, and deploying them into AKS using Helm.


📄 Azure DevOps Pipeline (azure-pipelines.yml)

trigger:
  branches:
    include:
      - main

variables:
  REGISTRY: multiagentacr.azurecr.io
  AKS_CLUSTER: multiagent-aks
  RESOURCE_GROUP: multiagent-rg
  IMAGE_TAG: $(Build.BuildId)

stages:
- stage: Build
  displayName: Build and Push Images
  jobs:
  - job: BuildPush
    pool:
      vmImage: 'ubuntu-latest'
    steps:
    - task: AzureCLI@2
      inputs:
        azureSubscription: 'AzureServiceConnection'
        scriptType: 'bash'
        scriptLocation: 'inlineScript'
        inlineScript: |
          az acr login --name $REGISTRY
          docker build -t $REGISTRY/controller-agent:$(IMAGE_TAG) ./controller
          docker push $REGISTRY/controller-agent:$(IMAGE_TAG)

          docker build -t $REGISTRY/data-fetcher-agent:$(IMAGE_TAG) ./workers/data-fetcher
          docker push $REGISTRY/data-fetcher-agent:$(IMAGE_TAG)

          docker build -t $REGISTRY/analyzer-agent:$(IMAGE_TAG) ./workers/analyzer
          docker push $REGISTRY/analyzer-agent:$(IMAGE_TAG)

          docker build -t $REGISTRY/summarizer-agent:$(IMAGE_TAG) ./workers/summarizer
          docker push $REGISTRY/summarizer-agent:$(IMAGE_TAG)

- stage: Deploy
  displayName: Deploy to AKS
  dependsOn: Build
  jobs:
  - job: HelmDeploy
    pool:
      vmImage: 'ubuntu-latest'
    steps:
    - task: AzureCLI@2
      inputs:
        azureSubscription: 'AzureServiceConnection'
        scriptType: 'bash'
        scriptLocation: 'inlineScript'
        inlineScript: |
          az aks get-credentials --resource-group $RESOURCE_GROUP --name $AKS_CLUSTER
          helm upgrade --install multi-agent ./helm-chart \
            --set controller.image=$REGISTRY/controller-agent:$(IMAGE_TAG) \
            --set workers[0].image=$REGISTRY/data-fetcher-agent:$(IMAGE_TAG) \
            --set workers[1].image=$REGISTRY/analyzer-agent:$(IMAGE_TAG) \
            --set workers[2].image=$REGISTRY/summarizer-agent:$(IMAGE_TAG)

🔑 Setup Requirements

  • Azure Service Connection: Create a service connection in Azure DevOps pointing to your subscription (used in azureSubscription above).
  • ACR & AKS: Already provisioned via the Bicep template we built earlier.
  • Helm chart: Stored in your repo under helm-chart/.
  • Secrets: Managed via Azure DevOps Library or Key Vault integration.

🚀 Workflow

  1. Developer pushes code → Pipeline triggers.
  2. Build stage → Docker images built & pushed to ACR.
  3. Deploy stage → Helm upgrades AKS workloads with new images.
  4. Agents start running and communicating via Service Bus.
  5. Logs flow into Application Insights for monitoring.

Now we will develop a small multi‑agent application that can automatically handle the full deployment pipeline we’ve been discussing (infra provisioning, container builds, pushing to ACR, Helm deploy to AKS, monitoring setup). Let’s design this as a multi‑agent system where each agent has a clear responsibility, and together they orchestrate the end‑to‑end deployment.


🧩 Multi‑Agent Application Design

Agents & Roles

  • Infra Agent

    • Provisions Azure resources (ACR, AKS, Service Bus, Key Vault, Monitor) using Bicep/ARM.
    • Runs az deployment group create commands.
  • Build Agent

    • Builds Docker images for each micro‑agent (controller, workers).
    • Pushes images to ACR.
  • Deploy Agent

    • Applies Helm charts to AKS.
    • Updates image tags automatically.
  • Monitor Agent

    • Configures Application Insights and Log Analytics.
    • Ensures telemetry is wired up.
  • Coordinator Agent

    • Orchestrates the workflow: triggers Infra → Build → Deploy → Monitor.
    • Handles retries and error reporting.

⚙️ Implementation Approach

  • Framework: Python with AutoGen or Semantic Kernel (github.com in Bing) for agent orchestration.
  • Communication: Agents interact via async tasks or Azure Service Bus.
  • Deployment: Each agent runs as a container in AKS or locally during bootstrap.

📄 Example Python Skeleton

from autogen import AssistantAgent, UserProxyAgent

# Infra Agent
infra_agent = AssistantAgent(name="InfraAgent", system_message="Provision Azure infra with Bicep.")
# Build Agent
build_agent = AssistantAgent(name="BuildAgent", system_message="Build and push Docker images to ACR.")
# Deploy Agent
deploy_agent = AssistantAgent(name="DeployAgent", system_message="Deploy Helm charts to AKS.")
# Monitor Agent
monitor_agent = AssistantAgent(name="MonitorAgent", system_message="Configure monitoring and logging.")
# Coordinator
coordinator = UserProxyAgent(name="Coordinator", human_input_mode="NEVER")

# Define workflow
def deployment_workflow():
    coordinator.initiate_chat(infra_agent, message="Provision infra resources")
    coordinator.initiate_chat(build_agent, message="Build and push images")
    coordinator.initiate_chat(deploy_agent, message="Deploy Helm charts")
    coordinator.initiate_chat(monitor_agent, message="Setup monitoring")

if __name__ == "__main__":
    deployment_workflow()

🚀 How It Works

  1. Coordinator Agent kicks off the workflow.
  2. Infra Agent provisions infra via Azure CLI/Bicep.
  3. Build Agent builds/pushes images.
  4. Deploy Agent applies Helm charts.
  5. Monitor Agent configures observability.
  6. Workflow completes with a fully deployed multi‑agent app in AKS.

🔄 Next Step

To make this truly automatic, you can:

  • Package each agent as a container.
  • Deploy them into AKS with a controller agent orchestrating tasks.
  • Or run them locally as part of a CI/CD pipeline.

Let’s put this all together into a working prototype of a multi‑agent application that can automatically deploy the full Azure environment, build/push images, and deploy to AKS. I’ll give you a Python-based orchestration example where each agent is a class with a clear responsibility. You can extend this into containers later.


🧩 Multi‑Agent Python Prototype

import subprocess

class InfraAgent:
    def provision(self):
        print("🚀 Provisioning Azure infra...")
        subprocess.run([
            "az", "deployment", "group", "create",
            "--resource-group", "multiagent-rg",
            "--template-file", "main.bicep"
        ], check=True)

class BuildAgent:
    def build_and_push(self):
        print("🔨 Building and pushing Docker images...")
        agents = {
            "controller": "./controller",
            "data-fetcher": "./workers/data-fetcher",
            "analyzer": "./workers/analyzer",
            "summarizer": "./workers/summarizer"
        }
        registry = "multiagentacr.azurecr.io"
        for name, path in agents.items():
            image = f"{registry}/{name}-agent:latest"
            subprocess.run(["docker", "build", "-t", image, path], check=True)
            subprocess.run(["docker", "push", image], check=True)

class DeployAgent:
    def deploy(self):
        print("📦 Deploying agents to AKS...")
        registry = "multiagentacr.azurecr.io"
        subprocess.run([
            "az", "aks", "get-credentials",
            "--resource-group", "multiagent-rg",
            "--name", "multiagent-aks"
        ], check=True)
        subprocess.run([
            "helm", "upgrade", "--install", "multi-agent", "./helm-chart",
            "--set", f"controller.image={registry}/controller-agent:latest",
            "--set", f"workers[0].image={registry}/data-fetcher-agent:latest",
            "--set", f"workers[1].image={registry}/analyzer-agent:latest",
            "--set", f"workers[2].image={registry}/summarizer-agent:latest"
        ], check=True)

class MonitorAgent:
    def configure(self):
        print("📊 Configuring monitoring...")
        subprocess.run([
            "az", "monitor", "app-insights", "component", "create",
            "--app", "multiagent-app",
            "--location", "eastus",
            "--resource-group", "multiagent-rg"
        ], check=True)

class CoordinatorAgent:
    def __init__(self):
        self.infra = InfraAgent()
        self.build = BuildAgent()
        self.deploy = DeployAgent()
        self.monitor = MonitorAgent()

    def run_workflow(self):
        self.infra.provision()
        self.build.build_and_push()
        self.deploy.deploy()
        self.monitor.configure()
        print("✅ Multi-agent deployment complete!")

if __name__ == "__main__":
    CoordinatorAgent().run_workflow()

🚀 How to Use

  1. Save this as multi_agent_deploy.py.
  2. Ensure you have:
    • Azure CLI installed and logged in (az login).
    • Docker installed and running.
    • Helm installed.
    • Your main.bicep and helm-chart/ ready.
  3. Run:
    python multi_agent_deploy.py
    
  4. The workflow will:
    • Provision infra (ACR, AKS, Service Bus, Key Vault, Monitor).
    • Build/push agent images.
    • Deploy Helm chart to AKS.
    • Configure monitoring.

🔄 Next Steps

  • Wrap each agent into its own container for true distributed execution.
  • Use Azure Service Bus for inter‑agent communication instead of sequential Python calls.
  • Add error handling and retries for robustness.

Excellent — let’s extend the prototype into a containerized multi‑agent application so each agent runs independently inside AKS. This way, the deployment itself is automated and self‑contained.


🧩 Containerized Multi‑Agent Setup

1. Dockerfiles for Each Agent

Example: InfraAgent

# controller/Dockerfile
FROM python:3.10-slim

WORKDIR /app
COPY infra_agent.py .

RUN pip install azure-cli

CMD ["python", "infra_agent.py"]

Repeat similar Dockerfiles for build_agent.py, deploy_agent.py, and monitor_agent.py.
Each agent script contains its logic (Azure CLI, Docker, Helm commands).


2. Kubernetes Manifests (AKS)

infra-agent-deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: infra-agent
spec:
  replicas: 1
  selector:
    matchLabels:
      app: infra-agent
  template:
    metadata:
      labels:
        app: infra-agent
    spec:
      containers:
      - name: infra-agent
        image: multiagentacr.azurecr.io/infra-agent:latest
        env:
        - name: AZURE_SUBSCRIPTION_ID
          valueFrom:
            secretKeyRef:
              name: azure-secrets
              key: subscriptionId

build-agent-deployment.yaml, deploy-agent-deployment.yaml, monitor-agent-deployment.yaml follow the same pattern, each pointing to its respective image.


3. Coordinator Agent (Orchestrator)

You can run the CoordinatorAgent as a Job in Kubernetes:

apiVersion: batch/v1
kind: Job
metadata:
  name: coordinator-agent
spec:
  template:
    spec:
      containers:
      - name: coordinator
        image: multiagentacr.azurecr.io/coordinator-agent:latest
      restartPolicy: Never

This job triggers the workflow: Infra → Build → Deploy → Monitor.
Agents can communicate via Azure Service Bus or HTTP APIs inside the cluster.


4. Secrets & Config

  • Store credentials in Azure Key Vault or Kubernetes Secrets.
  • Example secret:
apiVersion: v1
kind: Secret
metadata:
  name: azure-secrets
type: Opaque
data:
  subscriptionId: <base64-encoded-value>
  clientId: <base64-encoded-value>
  clientSecret: <base64-encoded-value>

5. Deployment Flow

  1. Build Docker images for each agent.
    docker build -t multiagentacr.azurecr.io/infra-agent:latest ./infra
    docker push multiagentacr.azurecr.io/infra-agent:latest
    
  2. Apply manifests:
    kubectl apply -f infra-agent-deployment.yaml
    kubectl apply -f build-agent-deployment.yaml
    kubectl apply -f deploy-agent-deployment.yaml
    kubectl apply -f monitor-agent-deployment.yaml
    kubectl apply -f coordinator-agent-job.yaml
    
  3. Coordinator triggers workflow → agents execute tasks → full deployment automated.

✅ With this setup, you now have a self‑deploying multi‑agent system inside AKS. Each agent is containerized, scalable, and independently responsible for its part of the pipeline.


Let’s wrap everything into a Helm chart so you can deploy the entire multi‑agent system (infra, build, deploy, monitor, coordinator) with a single helm install command.


🏗️ Helm Chart Structure

multi-agent-chart/
├── Chart.yaml
├── values.yaml
├── templates/
│   ├── infra-agent-deployment.yaml
│   ├── build-agent-deployment.yaml
│   ├── deploy-agent-deployment.yaml
│   ├── monitor-agent-deployment.yaml
│   ├── coordinator-agent-job.yaml
│   └── _helpers.tpl

📄 Chart.yaml

apiVersion: v2
name: multi-agent
description: Helm chart for multi-agent deployment automation
version: 0.1.0
appVersion: "1.0"

📄 values.yaml

registry: multiagentacr.azurecr.io

infraAgent:
  image: infra-agent:latest
  replicas: 1

buildAgent:
  image: build-agent:latest
  replicas: 1

deployAgent:
  image: deploy-agent:latest
  replicas: 1

monitorAgent:
  image: monitor-agent:latest
  replicas: 1

coordinatorAgent:
  image: coordinator-agent:latest

📄 templates/infra-agent-deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: infra-agent
spec:
  replicas: {{ .Values.infraAgent.replicas }}
  selector:
    matchLabels:
      app: infra-agent
  template:
    metadata:
      labels:
        app: infra-agent
    spec:
      containers:
      - name: infra-agent
        image: "{{ .Values.registry }}/{{ .Values.infraAgent.image }}"

📄 templates/build-agent-deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: build-agent
spec:
  replicas: {{ .Values.buildAgent.replicas }}
  selector:
    matchLabels:
      app: build-agent
  template:
    metadata:
      labels:
        app: build-agent
    spec:
      containers:
      - name: build-agent
        image: "{{ .Values.registry }}/{{ .Values.buildAgent.image }}"

📄 templates/deploy-agent-deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: deploy-agent
spec:
  replicas: {{ .Values.deployAgent.replicas }}
  selector:
    matchLabels:
      app: deploy-agent
  template:
    metadata:
      labels:
        app: deploy-agent
    spec:
      containers:
      - name: deploy-agent
        image: "{{ .Values.registry }}/{{ .Values.deployAgent.image }}"

📄 templates/monitor-agent-deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: monitor-agent
spec:
  replicas: {{ .Values.monitorAgent.replicas }}
  selector:
    matchLabels:
      app: monitor-agent
  template:
    metadata:
      labels:
        app: monitor-agent
    spec:
      containers:
      - name: monitor-agent
        image: "{{ .Values.registry }}/{{ .Values.monitorAgent.image }}"

📄 templates/coordinator-agent-job.yaml

apiVersion: batch/v1
kind: Job
metadata:
  name: coordinator-agent
spec:
  template:
    spec:
      containers:
      - name: coordinator
        image: "{{ .Values.registry }}/{{ .Values.coordinatorAgent.image }}"
      restartPolicy: Never

🚀 Deployment

  1. Package and install:
    helm install multi-agent ./multi-agent-chart
    
  2. Helm will deploy all agents (infra, build, deploy, monitor) plus the coordinator job.
  3. Coordinator triggers the workflow → agents execute tasks → full deployment automated.

Great — let’s extend the Helm chart with Azure Service Bus integration so your agents can communicate asynchronously inside AKS. This way, instead of just running sequentially, they’ll publish/subscribe to topics and queues for coordination.


🧩 Updated Helm Chart Structure

multi-agent-chart/
├── Chart.yaml
├── values.yaml
├── templates/
│   ├── infra-agent-deployment.yaml
│   ├── build-agent-deployment.yaml
│   ├── deploy-agent-deployment.yaml
│   ├── monitor-agent-deployment.yaml
│   ├── coordinator-agent-job.yaml
│   ├── servicebus-secret.yaml
│   ├── servicebus-configmap.yaml

📄 values.yaml (extended)

registry: multiagentacr.azurecr.io

serviceBus:
  namespace: multiagent-sb
  connectionString: "" # injected via secret

infraAgent:
  image: infra-agent:latest
  replicas: 1

buildAgent:
  image: build-agent:latest
  replicas: 1

deployAgent:
  image: deploy-agent:latest
  replicas: 1

monitorAgent:
  image: monitor-agent:latest
  replicas: 1

coordinatorAgent:
  image: coordinator-agent:latest

📄 templates/servicebus-secret.yaml

apiVersion: v1
kind: Secret
metadata:
  name: servicebus-secret
type: Opaque
stringData:
  connectionString: {{ .Values.serviceBus.connectionString | quote }}

📄 templates/servicebus-configmap.yaml

apiVersion: v1
kind: ConfigMap
metadata:
  name: servicebus-config
data:
  namespace: {{ .Values.serviceBus.namespace }}

📄 Example Agent Deployment with Service Bus Integration

build-agent-deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: build-agent
spec:
  replicas: {{ .Values.buildAgent.replicas }}
  selector:
    matchLabels:
      app: build-agent
  template:
    metadata:
      labels:
        app: build-agent
    spec:
      containers:
      - name: build-agent
        image: "{{ .Values.registry }}/{{ .Values.buildAgent.image }}"
        env:
        - name: SERVICEBUS_CONNECTION
          valueFrom:
            secretKeyRef:
              name: servicebus-secret
              key: connectionString
        - name: SERVICEBUS_NAMESPACE
          valueFrom:
            configMapKeyRef:
              name: servicebus-config
              key: namespace

🔄 Communication Flow with Service Bus

  • Coordinator Agent publishes a message to a topic (e.g., deployment-steps).
  • Infra Agent subscribes to infra queue → provisions infra → publishes completion event.
  • Build Agent listens on build queue → builds/pushes images → publishes completion event.
  • Deploy Agent listens on deploy queue → applies Helm → publishes completion event.
  • Monitor Agent listens on monitor queue → configures monitoring → publishes completion event.

This makes the workflow event-driven and resilient.


🚀 Deployment

  1. Inject your Service Bus connection string into Helm:
    helm install multi-agent ./multi-agent-chart \
      --set serviceBus.connectionString="Endpoint=sb://multiagent-sb.servicebus.windows.net/...;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=..."
    
  2. All agents will be deployed with Service Bus credentials and namespace.
  3. Agents communicate asynchronously via topics/queues.

Let’s wire up the agents’ communication logic using the Azure Service Bus SDK for Python. This will let each agent send and receive messages asynchronously via queues/topics, making the system event‑driven instead of sequential.


🧩 Install Dependencies

pip install azure-servicebus

📄 Example Agent Code

Coordinator Agent (Publisher)

from azure.servicebus import ServiceBusClient, ServiceBusMessage

CONNECTION_STR = "<your-servicebus-connection-string>"
QUEUE_NAME = "infra-queue"

def send_message():
    with ServiceBusClient.from_connection_string(CONNECTION_STR) as client:
        sender = client.get_queue_sender(queue_name=QUEUE_NAME)
        with sender:
            msg = ServiceBusMessage("Provision infra")
            sender.send_messages(msg)
            print("✅ Coordinator sent: Provision infra")

if __name__ == "__main__":
    send_message()

Infra Agent (Subscriber)

from azure.servicebus import ServiceBusClient

CONNECTION_STR = "<your-servicebus-connection-string>"
QUEUE_NAME = "infra-queue"

def receive_message():
    with ServiceBusClient.from_connection_string(CONNECTION_STR) as client:
        receiver = client.get_queue_receiver(queue_name=QUEUE_NAME)
        with receiver:
            for msg in receiver:
                print(f"📥 InfraAgent received: {msg.body}")
                # Run infra provisioning logic here (az deployment group create ...)
                receiver.complete_message(msg)

if __name__ == "__main__":
    receive_message()

Build Agent (Subscriber + Publisher)

from azure.servicebus import ServiceBusClient, ServiceBusMessage

CONNECTION_STR = "<your-servicebus-connection-string>"
QUEUE_NAME = "build-queue"

def receive_and_build():
    with ServiceBusClient.from_connection_string(CONNECTION_STR) as client:
        receiver = client.get_queue_receiver(queue_name=QUEUE_NAME)
        with receiver:
            for msg in receiver:
                print(f"📥 BuildAgent received: {msg.body}")
                # Run docker build/push logic here
                receiver.complete_message(msg)

                # Publish completion event
                sender = client.get_queue_sender(queue_name="deploy-queue")
                with sender:
                    sender.send_messages(ServiceBusMessage("Build complete"))
                    print("✅ BuildAgent published: Build complete")

if __name__ == "__main__":
    receive_and_build()

Deploy Agent (Subscriber)

from azure.servicebus import ServiceBusClient

CONNECTION_STR = "<your-servicebus-connection-string>"
QUEUE_NAME = "deploy-queue"

def receive_and_deploy():
    with ServiceBusClient.from_connection_string(CONNECTION_STR) as client:
        receiver = client.get_queue_receiver(queue_name=QUEUE_NAME)
        with receiver:
            for msg in receiver:
                print(f"📥 DeployAgent received: {msg.body}")
                # Run helm upgrade/install logic here
                receiver.complete_message(msg)

if __name__ == "__main__":
    receive_and_deploy()

Monitor Agent (Subscriber)

from azure.servicebus import ServiceBusClient

CONNECTION_STR = "<your-servicebus-connection-string>"
QUEUE_NAME = "monitor-queue"

def receive_and_monitor():
    with ServiceBusClient.from_connection_string(CONNECTION_STR) as client:
        receiver = client.get_queue_receiver(queue_name=QUEUE_NAME)
        with receiver:
            for msg in receiver:
                print(f"📥 MonitorAgent received: {msg.body}")
                # Configure Application Insights / Log Analytics here
                receiver.complete_message(msg)

if __name__ == "__main__":
    receive_and_monitor()

🔄 Workflow Example

  1. Coordinator Agent publishes "Provision infra"infra-queue.
  2. Infra Agent provisions infra → publishes "Infra complete"build-queue.
  3. Build Agent builds/pushes images → publishes "Build complete"deploy-queue.
  4. Deploy Agent applies Helm → publishes "Deploy complete"monitor-queue.
  5. Monitor Agent configures monitoring → workflow ends.

🚀 Next Step

You can containerize each agent with its own Dockerfile and deploy them via the Helm chart we built earlier. Each agent will subscribe to its queue, perform its task, and publish the next step — giving you a fully automated, event‑driven multi‑agent deployment system on Azure.


Let’s extend the automation so your Helm chart + Bicep template not only deploys the agents but also provisions Service Bus queues/topics automatically. This way, you won’t need to manually create messaging infrastructure — it’s fully declarative.


🧩 Updated Bicep Template (Service Bus Queues/Topics)

Add this to your main.bicep:

// Service Bus Namespace
resource sb 'Microsoft.ServiceBus/namespaces@2021-06-01-preview' = {
  name: sbNamespace
  location: location
  sku: {
    name: 'Standard'
    tier: 'Standard'
  }
}

// Queues for each agent
resource infraQueue 'Microsoft.ServiceBus/namespaces/queues@2021-06-01-preview' = {
  parent: sb
  name: 'infra-queue'
  properties: {
    enablePartitioning: true
  }
}

resource buildQueue 'Microsoft.ServiceBus/namespaces/queues@2021-06-01-preview' = {
  parent: sb
  name: 'build-queue'
  properties: {
    enablePartitioning: true
  }
}

resource deployQueue 'Microsoft.ServiceBus/namespaces/queues@2021-06-01-preview' = {
  parent: sb
  name: 'deploy-queue'
  properties: {
    enablePartitioning: true
  }
}

resource monitorQueue 'Microsoft.ServiceBus/namespaces/queues@2021-06-01-preview' = {
  parent: sb
  name: 'monitor-queue'
  properties: {
    enablePartitioning: true
  }
}

This provisions the namespace + queues for Infra, Build, Deploy, and Monitor agents.


📄 Helm Chart Integration

values.yaml

serviceBus:
  namespace: multiagent-sb
  connectionString: "" # injected via secret
  queues:
    infra: infra-queue
    build: build-queue
    deploy: deploy-queue
    monitor: monitor-queue

templates/servicebus-secret.yaml

apiVersion: v1
kind: Secret
metadata:
  name: servicebus-secret
type: Opaque
stringData:
  connectionString: {{ .Values.serviceBus.connectionString | quote }}

Example Agent Deployment (Build Agent)

apiVersion: apps/v1
kind: Deployment
metadata:
  name: build-agent
spec:
  replicas: {{ .Values.buildAgent.replicas }}
  selector:
    matchLabels:
      app: build-agent
  template:
    metadata:
      labels:
        app: build-agent
    spec:
      containers:
      - name: build-agent
        image: "{{ .Values.registry }}/{{ .Values.buildAgent.image }}"
        env:
        - name: SERVICEBUS_CONNECTION
          valueFrom:
            secretKeyRef:
              name: servicebus-secret
              key: connectionString
        - name: QUEUE_NAME
          value: {{ .Values.serviceBus.queues.build }}

Each agent gets its queue name injected via Helm values.


🚀 Deployment Flow

  1. Run Bicep → provisions ACR, AKS, Service Bus namespace + queues.
  2. Helm install → deploys all agents with Service Bus credentials + queue names.
  3. Agents subscribe/publish to their queues automatically.
  4. Workflow becomes event‑driven: Infra → Build → Deploy → Monitor.

✅ With this, you now have a self‑deploying, event‑driven multi‑agent system on Azure.
The infra, messaging, and agents are all provisioned declaratively.


It will help to gain more knowledge https://learn.microsoft.com/en-us/azure/devops/pipelines/?view=azure-devops


Deploy ML Application to Azure

Azure DevOps + Azure ML based ML application deployment tutorial:


🔷 Introduction: Context of Azure, Azure ML & Azure DevOps

1. Azure Overview Azure is Microsoft’s cloud computing platform offering a vast ecosystem of services for compute, storage, networking, databases, machine learning, DevOps, and more. It enables organizations to build, deploy, and manage applications and services through Microsoft-managed data centers.

Key Benefits:

  • Global scalability and reliability

  • Pay-as-you-go pricing

  • Integrated security and compliance

  • Strong ecosystem for enterprise DevOps and AI/ML workflows


2. What is Azure Machine Learning (Azure ML)? Azure Machine Learning is a cloud-based platform for training, deploying, automating, and managing machine learning models. It supports both code-first (Python SDK, CLI) and no-code (Designer, Studio) approaches.

Key Components:

  • Workspaces: Central place to manage assets and operations

  • Compute Targets: For training & inference (e.g., Azure ML Compute, AKS, ACI)

  • Datasets & Datastores: For accessing and versioning data

  • Pipelines: For orchestrating workflows (training, evaluation, deployment)

  • Endpoints: Real-time and batch deployment options


3. What is Azure DevOps? Azure DevOps is a SaaS platform providing a complete DevOps toolchain for software development and deployment. It is widely used for continuous integration (CI) and continuous deployment (CD) of applications, including ML workflows.

Core Services:

  • Azure Repos: Git repositories for version control

  • Azure Pipelines: CI/CD for building, testing, and deploying code

  • Azure Boards: Agile project planning

  • Azure Artifacts: Package management

  • Test Plans: Manual and automated testing


🎯 Purpose of This Tutorial This tutorial aims to build an end-to-end CI/CD pipeline for a machine learning application using:

  • Azure ML for model training & deployment

  • Azure DevOps for version control, build, and release automation

You'll learn how to:

  • Train ML models in Azure ML

  • Store and manage code using Azure Repos

  • Trigger training via Azure Pipelines

  • Deploy models as endpoints

  • Automate the entire ML lifecycle


✅ Step 1: Setup & Prerequisites for starting the Azure ML + Azure DevOps deployment tutorial.


🔹 Step 1: Prerequisites & Initial Setup

📌 Objective:
Set up the Azure and DevOps environment required for ML application CI/CD deployment.


🧰 Prerequisites:

  1. Azure Subscription

  2. Azure DevOps Account

    • Sign up or log in: https://dev.azure.com

    • Create an organization and a project (e.g., ml-deployment-demo)

  3. Azure Machine Learning Workspace

    • Create a workspace from the Azure portal or CLI

    • It should include:

      • A resource group

      • A region (e.g., East US)

      • Storage Account

      • Key Vault

      • Application Insights

      • Container Registry (optional)

  4. Git & GitHub (Optional but Recommended)

    • For managing code in local repo and syncing with Azure Repos

  5. Local Setup (for development)

    • Python ≥ 3.8

    • Install Azure CLI:

      curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash
      
    • Install Azure ML CLI extension:

      az extension add -n azure-cli-ml
      
    • Install Azure ML SDK:

      pip install azureml-sdk
      
  6. Azure DevOps Agent (Optional for self-hosted runs)

    • Can be added later for running jobs on your own compute


📁 Output of This Step:

  • Azure DevOps project is ready

  • Azure ML workspace is created

  • Local dev environment is ready

  • CLI and SDK tools installed



🖼️ Azure ML CI/CD Flow

This diagram shows the end-to-end ML model lifecycle in an Azure DevOps pipeline using Azure ML.

🧩 Components Explained:

  1. Create/Get Workspace

    • Use Azure CLI or Azure ML SDK to create or fetch an existing Azure ML workspace.

    • All assets (models, experiments, compute, images) are tied to this workspace.

  2. Model Training (Experiment Run)

    • Train your ML model (e.g., using scikit-learn, TensorFlow, etc.)

    • Log metrics, outputs, and register as an experiment run in Azure ML.

  3. Model Evaluation

    • Compare current trained model against a baseline/production model using evaluation metrics.

    • Decision logic: Promote model only if metrics improve.

  4. Model Registration

    • Register the trained model in Azure ML Model Registry with versioning.

    • Enables reproducibility and controlled model promotion.

  5. Scoring Image Creation (Docker)

    • Create a Docker scoring image using Azure ML for deployment.

    • This image will include the model + score.py + dependencies.


Step 2: Create Azure ML Workspace

🔧 Tools:

  • Azure CLI

  • Azure ML Python SDK

📍Steps:

(A) Using Azure CLI

az login
az group create --name ml-demo-rg --location eastus
az ml workspace create --name ml-demo-ws --resource-group ml-demo-rg

(B) Using Python SDK

from azureml.core import Workspace

workspace = Workspace.create(
    name='ml-demo-ws',
    resource_group='ml-demo-rg',
    create_resource_group=True,
    location='eastus'
)
workspace.write_config()  # saves config.json locally

📁 Output of This Step:

  • Azure ML workspace created

  • Config file config.json saved to local project (used by SDK/CLI to auto-connect)



Step 3: Prepare Training Script & Register Experiment in Azure ML

🎯 Objective:
Train your ML model and log it as an experiment run in Azure ML.


🧱 Project Folder Structure (Suggested)

ml_project/
├── train.py
├── environment.yml  (or conda_dependencies.yml)
├── config.json      (created in Step 2)
└── outputs/         (for model artifacts)

🧪 Training Script: train.py (Example)

from azureml.core import Run
import joblib
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split

# Get run context
run = Run.get_context()

# Load data
X, y = load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y)

# Train model
model = Ridge(alpha=0.5)
model.fit(X_train, y_train)

# Log metrics
score = model.score(X_test, y_test)
run.log("r2_score", score)

# Save model
joblib.dump(model, "outputs/model.pkl")

📦 Define Environment: environment.yml

name: sklearn-env
dependencies:
  - python=3.8
  - scikit-learn
  - pip
  - pip:
      - azureml-defaults

🚀 Submit Training Script to Azure ML

from azureml.core import Workspace, Experiment, ScriptRunConfig, Environment

# Load workspace from config.json
ws = Workspace.from_config()

# Create experiment
exp = Experiment(workspace=ws, name='train-diabetes-model')

# Set up environment
env = Environment.from_conda_specification(name='sklearn-env', file_path='environment.yml')

# Submit job
src = ScriptRunConfig(source_directory='.', script='train.py', environment=env)
run = exp.submit(config=src)
run.wait_for_completion(show_output=True)

📁 Output of This Step:

  • train.py runs in Azure ML

  • Metrics (r2_score) are logged

  • Model saved to outputs/model.pkl

  • Experiment is visible in Azure ML portal



🖼️ Azure ML Model Lifecycle (Training to Deployment)

This diagram shows the end-to-end ML lifecycle on a Linux VM agent using Azure Machine Learning:

🔁 Overview of Steps:

  1. Get or Create Workspace
    Set up the Azure ML workspace using CLI, SDK, or UI.

  2. Train the Model
    Run your training script on the Linux VM and log results as an experiment.

  3. Evaluate Model
    Compare the new model’s performance with existing/production models.

  4. Register the Trained Model
    Store the trained model in Azure ML Model Registry for versioning and reuse.

  5. Create a Scoring Image (Docker-based)
    Build a container image using the trained model + scoring script + environment. This is used for deployment to endpoints (AKS, ACI, etc.).

The bottom section (Source Code, Configs, Output) represents all your assets used throughout this workflow.


Step 4: Register Trained Model in Azure ML

Once the training script has completed and model.pkl is saved in the outputs/ folder, we can register it.


📌 Code to Register Model

from azureml.core import Workspace, Model

# Load workspace
ws = Workspace.from_config()

# Register model from outputs folder
model = Model.register(
    workspace=ws,
    model_path="outputs/model.pkl",  # Path to model file
    model_name="diabetes-ridge-model",  # Name for model in registry
    tags={"area": "diabetes", "type": "regression"},
    description="Ridge regression model to predict diabetes progression"
)

print("Model registered:", model.name, "version:", model.version)

📁 Output of This Step:

  • Model appears in Azure ML Model Registry with versioning.

  • You can now deploy this model via ACI/AKS.




Step 5: Create Scoring Image (Inference Setup)

This step prepares the model for deployment by packaging it with a scoring script and environment in a Docker image using Azure ML.


📁 What You Need:

  • Registered model

  • Scoring script (score.py)

  • Environment file (myenv.yml or CondaDependencies)


🧠 1. Create score.py

This script defines how input data is processed and predictions are returned.

import joblib
import json
from azureml.core.model import Model
from sklearn.linear_model import Ridge

def init():
    global model
    model_path = Model.get_model_path('diabetes-ridge-model')
    model = joblib.load(model_path)

def run(raw_data):
    data = json.loads(raw_data)
    prediction = model.predict([data['data']])
    return prediction.tolist()

📦 2. Create Environment (e.g., myenv.yml)

name: diabetes-env
dependencies:
  - python=3.8
  - scikit-learn
  - pandas
  - pip:
      - azureml-defaults

🛠️ 3. Build the Inference Image

from azureml.core import Environment
from azureml.core.model import InferenceConfig
from azureml.core.webservice import AciWebservice, Webservice

# Load workspace
ws = Workspace.from_config()

# Define environment
env = Environment.from_conda_specification(name='diabetes-env', file_path='myenv.yml')

# Define inference config
inference_config = InferenceConfig(entry_script='score.py', environment=env)

# Define deployment config
deployment_config = AciWebservice.deploy_configuration(cpu_cores=1, memory_gb=1)

# Deploy as web service (next step)













Step 6: Deploy Model on ACI (Azure Container Instance)


🖼️ 50-deployOnAci.py

This script deploys your scoring image on Azure Container Instances (ACI) using:

  • CPU: 1 core

  • Memory: 1 GB

  • Tags: area=diabetes, type=regression

  • Dynamically generated ACI name using timestamp


🧾 Deployment Code Snippet:

from azureml.core.webservice import AciWebservice, Webservice
import datetime

aci_config = AciWebservice.deploy_configuration(
    cpu_cores=1,
    memory_gb=1,
    tags={"area": "diabetes", "type": "regression"},
    description="A sample description",
)

aci_service_name = "aciwebservice" + datetime.datetime.now().strftime("%m%d%H")

service = Webservice.deploy_from_image(
    deployment_config=aci_config,
    image=image,
    name=aci_service_name,
    workspace=ws,
)

service.wait_for_deployment(show_output=True)
print("Deployed ACI Webservice: {}\nWebservice URI: {}".format(
    service.name, service.scoring_uri
))

No, I haven’t described how to create, save (.pkl), and load the model yet. Here's a quick complete snippet for that:


🧠 Train & Save ML Model (.pkl)

train_model.py

import pickle
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

# Load dataset
X, y = load_iris(return_X_y=True)

# Train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Train model
clf = RandomForestClassifier()
clf.fit(X_train, y_train)

# Save to .pkl
with open("model.pkl", "wb") as f:
    pickle.dump(clf, f)

Load .pkl in FastAPI

Already shared in the main.py:

with open("model.pkl", "rb") as f:
    model = pickle.load(f)

Let me know if you also want to:

  • Save as .joblib or .onnx

  • Add test script for the FastAPI endpoint

  • Package this into CI/CD YAML pipeline automatically

📌 Next Step: Test ACI Webservice

Once deployed, we'll write a script to send a test request to the model endpoint (60-AciWebserviceTest.py).



💼 Project Context

  • Project: ML-Devops

  • Pipeline: Deploy Webservice

  • Release: Release-17

  • Artifact Source: devops-for-ai-CI from branch master


📦 Continuous Deployment Trigger

  • User: 99.user.name

  • Date/Time: 12/04/2023, 18:53

  • Trigger Type: Automatic – the release is automatically triggered when new artifacts are available.


🚀 Deployment Stages

1. QA - Deploy on ACI (Azure Container Instances)

  • Status: In Progress

  • Tasks: 5 out of 6 completed

  • Current Task: 50. Deploy Webservice on ACI

  • Start Time: 12/04/2023, 18:54

  • Triggered At: 18:53

  • Details:

    • Deployment is automatically triggered.

    • It’s deploying on ACI, ideal for lightweight, quick QA/staging deployments.


2. Prod - Deploy on AKS (Azure Kubernetes Service)

  • Status: Not Deployed

  • Triggered After: QA stage completes successfully.

  • Target: Full-scale production deployment using AKS for scalability and orchestration.


📑 Logs and Tracking

  • Tabs: Summary, Commits, Work Items, View Logs

  • Associated Changes:

    • Commit ID: 32

    • Branch: master


Here’s a structured response covering both parts:


1. YAML Configuration & Pipeline Task Explanation

🔧 Pipeline Tasks in Deploy Webservice

Typical tasks in a deployment stage for an ML model using Azure DevOps:

  1. Download Artifacts
    Downloads model files from previous CI pipeline (e.g., .pkl, .onnx, or .joblib model).

  2. Install Dependencies
    Sets up Python environment and required libraries using pip.

  3. Build Docker Image
    Uses a Dockerfile to containerize the FastAPI service wrapping the model.

  4. Push Docker Image to ACR
    Pushes image to Azure Container Registry.

  5. Deploy to ACI/AKS
    Uses Azure CLI or Kubernetes manifests to deploy on ACI (QA) or AKS (Prod).

  6. Post-deployment Tests (Optional)
    Runs integration tests or probes service health.


📝 YAML Snippet Example

trigger:
- master

stages:
- stage: DeployWebservice
  jobs:
  - job: DeployModel
    pool:
      vmImage: 'ubuntu-latest'
    steps:
    - task: UsePythonVersion@0
      inputs:
        versionSpec: '3.9'

    - script: pip install -r requirements.txt
      displayName: 'Install dependencies'

    - task: Docker@2
      inputs:
        containerRegistry: '$(dockerRegistryServiceConnection)'
        repository: 'fastapi-ml-model'
        command: 'buildAndPush'
        Dockerfile: '**/Dockerfile'
        tags: |
          $(Build.BuildId)

    - task: AzureCLI@2
      inputs:
        azureSubscription: 'YourAzureSub'
        scriptType: 'bash'
        scriptLocation: 'inlineScript'
        inlineScript: |
          az container create \
            --resource-group your-rg \
            --name fastapi-model \
            --image youracr.azurecr.io/fastapi-ml-model:$(Build.BuildId) \
            --dns-name-label your-model-api \
            --ports 80

🚀 2. FastAPI-Based Webservice to Serve ML Model

📁 Folder Structure

fastapi-ml-service/
├── model.pkl
├── Dockerfile
├── main.py
├── requirements.txt

main.py Example

from fastapi import FastAPI, Request
import pickle
from pydantic import BaseModel

app = FastAPI()

# Load model
with open("model.pkl", "rb") as f:
    model = pickle.load(f)

# Request schema
class PredictRequest(BaseModel):
    feature1: float
    feature2: float
    # Add more features as per model input

@app.post("/predict")
def predict(request: PredictRequest):
    input_data = [[request.feature1, request.feature2]]
    prediction = model.predict(input_data)
    return {"prediction": prediction[0]}

requirements.txt

fastapi
uvicorn
scikit-learn
pydantic

Dockerfile

FROM python:3.9

WORKDIR /app

COPY . .

RUN pip install -r requirements.txt

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]

Let me know if you need:

  • Sample model training + pickle code

  • Kubernetes manifest for AKS

  • ACI-specific deployment CLI

  • Health check integration


All images used in this tutorial are credited to Azure. Also, you can find informative tutorials on Azure DevOps here and here.

You can find many tutorials related to Fastapi and other Python frameworks on how to develop web services which can call the ML model. 

Sunday

Migrate CI/CD from Gitlab CI/CD to Azure or AWS

 


Migrating from GitLab CI/CD to Azure DevOps for Experienced Users

This tutorial guides experienced GitLab CI/CD users on migrating their workflows to Azure DevOps. It compares key concepts and provides step-by-step instructions with code and YAML examples to facilitate a smooth transition.

Comparison of Key Concepts:

FeatureGitLab CI/CDAzure DevOps
Version control systemGitLabGit
PipelinesStages and jobsPipelines and stages
YAML definition.gitlab-ci.ymlazure-pipelines.yml
CI triggersPush events, merge requests, tagsBranches, pushes, pull requests, tags
CD triggersTags, environmentsReleases, environments
ArtifactsDownloadable artifactsPipeline artifacts
RunnersSelf-hosted or shared runnersPipelines run on Microsoft-hosted agents or self-hosted agents
VariablesVariables defined in .gitlab-ci.ymlVariables defined in pipeline configuration or Azure Pipelines YAML
SecretsGitLab SecretsAzure Key Vault

Step-by-Step Migration Guide:

1. Install Azure Pipelines extension for GitLab:

  • This extension helps migrate your GitLab CI/CD pipelines to Azure DevOps.
  • Install it from the GitLab Marketplace.

2. Analyze your existing GitLab CI/CD pipeline:

  • Review your .gitlab-ci.yml file and understand the stages, jobs, and scripts used.
  • Identify the CI triggers, CD triggers, and artifact management strategies.
  • Analyze the variables and secrets used in your pipeline.

3. Create an Azure DevOps project:

4. Import your GitLab repository:

  • In your Azure DevOps project, navigate to Repos and click Import.
  • Select Git as the source and provide the URL of your GitLab repository.
  • Import the repository with the desired branch and history.

5. Convert your GitLab CI/CD pipeline to Azure DevOps YAML:

  • Use the Azure Pipelines extension for GitLab to automatically convert your .gitlab-ci.yml file to an azure-pipelines.yml file.
  • Review the converted YAML file and make necessary adjustments.

6. Configure your CI/CD pipeline in Azure DevOps:

  • In your Azure DevOps project, navigate to Pipelines.
  • Click Create pipeline and select YAML.
  • Choose the azure-pipelines.yml file you created.
  • Configure the CI triggers, CD triggers, and artifact management strategies.
  • Define the variables and secrets in your pipeline configuration or Azure Key Vault.

7. Run your pipeline:

  • Once your pipeline is configured, you can run it manually or automatically based on the triggers.
  • Monitor the pipeline execution and review the results.

8. Migrate your CI/CD artifacts:

  • Download your artifacts from GitLab and upload them to Azure DevOps.
  • This can be done manually or using a script.

9. Update your development workflow:

  • Update your development workflow to integrate with Azure DevOps.
  • This includes commit messages, pull requests, and code reviews.

Benefits of Migrating to Azure DevOps:

  • Enhanced security: Azure DevOps offers robust security features, including Azure Key Vault for managing secrets.
  • Improved performance: Microsoft-hosted agents offer better performance and scalability than self-hosted runners.
  • Integrated tools: Azure DevOps integrates with other Microsoft tools and services, such as Azure Boards and Azure Repos.
  • Continuous improvement: Microsoft actively develops and updates Azure DevOps with new features and functionalities.

Additional Resources:

By following this guide and utilizing the provided resources, experienced GitLab CI/CD users can smoothly transition their workflows to Azure DevOps and leverage its advanced features and powerful integrations. Remember, the specific steps may vary slightly depending on your individual CI/CD pipeline.

End-to-End Example: Migrating a GitLab CI/CD pipeline for a Web App

Scenario:

  • You have a web application hosted on GitLab and currently use GitLab CI/CD for continuous integration and deployment.
  • The GitLab CI/CD pipeline includes the following stages:
    • Build: Compiles the web application code.
    • Test: Runs unit and integration tests.
    • Deploy: Deploys the application to a staging environment.
  • You want to migrate your CI/CD pipeline to Azure DevOps.

Step 1: Analyze GitLab CI/CD Pipeline:

  • Review your .gitlab-ci.yml file and identify the stages and jobs for each stage:
YAML
stages:
  - build
  - test
  - deploy

build:
  script:
    - npm install
    - npm run build

test:
  script:
    - npm run test

deploy:
  script:
    - aws deploy --profile staging ...

Step 2: Import GitLab Repository to Azure DevOps:

  • Create a new project in Azure DevOps.
  • Import your GitLab repository to the project.

Step 3: Convert .gitlab-ci.yml to azure-pipelines.yml:

  • Use the Azure Pipelines extension for GitLab to convert your .gitlab-ci.yml file.
  • Review and adjust the converted YAML:
YAML
jobs:
  - job: build
    pool:
      vmImage: ubuntu-latest
    steps:
      - script: npm install
      - script: npm run build

  - job: test
    pool:
      vmImage: ubuntu-latest
    dependsOn: build
    steps:
      - script: npm run test

  - job: deploy
    pool:
      vmImage: ubuntu-latest
    dependsOn: test
    steps:
      - script: aws deploy --profile staging ...

Step 4: Configure CI/CD Triggers in Azure DevOps:

  • Define triggers for your pipeline:
    • Build and test jobs to run on every push to the main branch.
    • Deploy job to run manually or automatically on successful build and test.

Step 5: Configure Variables and Secrets:

  • Define variables and secrets used in your pipeline:
    • Variable for AWS profile name in Azure Key Vault.

Step 6: Configure Artifacts:

  • Configure artifact publishing for the build job.
  • This allows download and use of build output in subsequent jobs.

Step 7: Migrate CI/CD Artifacts:

  • Download build artifacts from GitLab.
  • Upload them to Azure DevOps pipeline artifacts.

Step 8: Update Development Workflow:

  • Use Azure DevOps for pull requests, code reviews, and pipeline execution.

Step 9: Verify and Test:

  • Trigger your Azure DevOps pipeline and verify its execution.
  • Test the functionality of your web app after deployment.

Benefits:

  • Improved security with Azure Key Vault.
  • Scalable build and test jobs on Microsoft-hosted agents.
  • Integrated with Azure Boards and Azure Repos for end-to-end workflows.

This example demonstrates a basic migration of a GitLab CI/CD pipeline to Azure DevOps. Customize the specific steps and configurations based on your environment and needs. Remember to test your pipeline thoroughly after migration to ensure its smooth functioning.


Migrating from GitLab CI/CD to AWS CodePipeline

Scenario:

  • You have a web application hosted on GitLab and currently use GitLab CI/CD for continuous integration and deployment.
  • Your GitLab CI/CD pipeline includes the following stages:
    • Build: Compiles the web application code.
    • Test: Runs unit and integration tests.
    • Deploy: Deploys the application to an AWS Elastic Beanstalk environment.
  • You want to migrate your CI/CD pipeline to AWS CodePipeline.

Step 1: Analyze GitLab CI/CD Pipeline:

  • Review your .gitlab-ci.yml file and identify the stages and jobs for each stage:
YAML
stages:
  - build
  - test
  - deploy

build:
  script:
    - npm install
    - npm run build

test:
  script:
    - npm run test

deploy:
  script:
    - aws deploy --profile staging ...

Step 2: Create AWS Resources:

  • In your AWS account, create the necessary resources for your pipeline:
    • An IAM role with permissions to perform the required actions, such as building, testing, and deploying your application.
    • An S3 bucket to store your build artifacts.
    • A CodeBuild project for building your application.
    • A CodeCommit repository to store your code.
    • A CodePipeline pipeline to orchestrate the build, test, and deployment stages.
    • An AWS Elastic Beanstalk environment for deploying your application.

Step 3: Configure AWS CodePipeline:

  • In your AWS console, navigate to CodePipeline.
  • Create a new pipeline and define the following stages:
    • Source: Choose GitLab as the source provider and connect your GitLab repository.
    • Build: Choose CodeBuild as the build provider and configure the previously created CodeBuild project.
    • Test: You can implement different testing strategies here, depending on your needs.
      • Manual testing: Define a manual approval stage for testing before deployment.
      • Automated testing: Use CodeBuild or another service to run automated tests.
    • Deploy: Choose AWS Elastic Beanstalk as the deployment provider and configure the deployment settings.

Step 4: Configure Artifacts:

  • Configure artifact publishing for the build stage in CodeBuild.
  • This allows saving the build output to the S3 bucket for use in the deploy stage.

Step 5: Configure Triggers and IAM Role:

  • Define triggers for your pipeline:
    • Build and test stages to run on every push to the main branch.
    • Deploy stage to run manually or automatically on successful build and test.
  • Attach the IAM role with appropriate permissions to your CodePipeline pipeline for its execution.

Step 6: Migrate CI/CD Artifacts:

  • Download build artifacts from GitLab.
  • If your GitLab CI/CD pipeline already publishes artifacts, you can configure CodePipeline to access them directly from GitLab artifacts storage.
  • Alternatively, upload the downloaded artifacts to the S3 bucket used by CodeBuild.

Step 7: Update Development Workflow:

  • Use AWS CodeCommit for your code repository and CodePipeline for continuous integration and deployment.
  • Integrate code reviews, approvals, and deployments into your workflow using AWS services.

Step 8: Verify and Test:

  • Trigger your AWS CodePipeline pipeline and verify its execution.
  • Test the functionality of your web app after deployment.

Benefits:

  • Leverage AWS managed services for build, test, and deploy stages.
  • Seamless integration with AWS resources and services.
  • Scalable and reliable pipeline execution.
  • Secure access with IAM roles and permissions.

Remember, this is a general guide, and the specific steps may vary depending on your environment and needs. Consider your specific setup and requirements when migrating your CI/CD pipeline to AWS CodePipeline.

GitLab to Azure Tutorials:

Official Azure DevOps Documentation:

Articles and Tutorials:

GitLab to AWS Tutorials:

Official GitLab Documentation:

Articles and Tutorials:

I hope these links provide valuable resources for your journey from GitLab to Azure and AWS.

House Based Manufacturing Micro Clustering

                                 image generated by meta ai House-based manufacturing micro-clustering in China refers to the hyper-local, v...