automation
36 TopicsBuild a multi-model video generation workflow with fal on Microsoft Foundry
Building a compelling video experience rarely comes down to finding one model that does everything. Early in the creative process, you may want fast text-to-video generation to explore several directions. Once a composition is established, image-to-video can preserve the starting visual while adding motion. For more directed work, reference inputs can provide additional context from images, video, or audio. Fal on Microsoft Foundry brings these workflows together through a family of video generation models available from the Foundry model catalog. In this tutorial, we build a practical product-campaign workflow that starts with a creative brief and moves through text-to-video, image-to-video, and reference-to-video modalities. Along the way, we show how to select a model for each step, submit asynchronous generation jobs, monitor their status, retrieve the completed video, and structure the code so that it can be reused across models. The scenario: turn one creative brief into a coordinated campaign Imagine that a creative team is introducing a compact premium travel speaker called Northstar. The team needs three short assets: A concept clip to test the campaign mood and visual language quickly. A polished hero clip that animates an approved product image. A campaign variation that uses reference material to reinforce the established product and audio direction. The creative brief is intentionally specific enough to guide generation while leaving room for model interpretation: Creative brief: A matte black portable speaker sits on a weathered stone ledge above a misty alpine lake at sunrise. The camera moves slowly toward the product. Soft wind moves nearby grass. The visual style is premium, cinematic, restrained, and realistic, with cool blues and warm sunrise highlights. Avoid text, logos, extra products, distorted geometry, and abrupt camera movement. This is a useful application pattern because model choice follows the creative task instead of forcing every task through the same endpoint. Choose the model and modality for the job At the time of writing, fal on Microsoft Foundry includes five video models in public preview. All five support text-to-video and image-to-video. MiniMax H3 Max additionally supports reference-to-video. For comprehensive model details, please review the documentation. Model Modalities Best fit in the scenario Deployment offering LTX 2.5 Fast Text-to-video; image-to-video Rapid concept exploration and iteration Global Standard PayGo LTX 2.5 Pro Text-to-video; image-to-video Higher-quality hero output after direction is approved Global Standard PayGo Kling v3 Pro Text-to-video; image-to-video Cinematic or multi-shot alternatives; native audio is available US Data Zone MiniMax H3 Max Text-to-video; image-to-video; reference-to-video Reference-guided campaign variation Global Standard PayGo MiniMax H3 Max Turbo Text-to-video; image-to-video Alternative fast generation path Global Standard PayGo How the asynchronous API workflow works Video generation is asynchronous. A production-oriented client should treat submission, status polling, result retrieval, and download as distinct operations: Authenticate to the Foundry resource with a Microsoft Entra bearer token. Submit a generation request to the selected model and modality route. Capture the request_id returned by the service. Poll the status route until the job reaches a terminal state. Retrieve the completed result and extract the video URL. Download or securely process the generated asset before the result URL expires. Prerequisites An Azure subscription. A Microsoft Foundry resource and project. Subscription Owner or Subscription Contributor access to enable the preview (Fal.EnableDeploy) feature. Foundry Owner access on the project to deploy models. Azure CLI installed and authenticated with az login. Python 3.10 or later with the requests package. Model deployments for the fal models used by the walkthrough. A publicly reachable HTTPS image URL for image-to-video examples, plus reference URLs for the reference-to-video example. Enable fal and deploy the models An administrator first enables the Fal.EnableDeploy preview feature for the Azure subscription. In the Azure portal, open the subscription, select Preview features, search for Fal.EnableDeploy, review the terms and data-handling disclosure, and register the feature. Registration can take up to 30 minutes. After registration, open the Foundry model catalog, select each required fal model, choose Deploy, configure the deployment name and supported deployment offering, and wait until the deployment status is Succeeded. Data handling: fal services are operated outside Microsoft facilities. Review the fal terms, data-egress implications, privacy requirements, and your organization’s compliance obligations before sending prompts or assets. Note: All code samples in this walkthrough use Python and are intended to run in a Jupyter Notebook. Set up the notebook environment The companion notebook can be organized around a shared client so each scenario changes only the endpoint suffix and request payload. %pip install -q requests import json import os import subprocess import time from pathlib import Path from typing import Any, Dict import requests Configure the resource and model deployment names. The deployment names must match the deployments in your Foundry project. FOUNDRY_RESOURCE_NAME = os.environ.get( "FOUNDRY_RESOURCE_NAME", "your-foundry-resource" ) FOUNDRY_HOST = ( f"https://{FOUNDRY_RESOURCE_NAME}.services.ai.azure.com" ) DEPLOYMENTS = { "ltx_fast": os.environ.get("LTX_FAST_DEPLOYMENT", "ltx-2-5-fast"), "ltx_pro": os.environ.get("LTX_PRO_DEPLOYMENT", "ltx-2-5-pro"), "kling_pro": os.environ.get("KLING_PRO_DEPLOYMENT", "kling-v3-pro"), "minimax_h3": os.environ.get("MINIMAX_H3_DEPLOYMENT", "minimax-h3-max"), } Authenticate for local development This Python helper invokes Azure CLI as a subprocess. It is still Python, not a Bash sample. def get_bearer_token() -> str: command = [ "az", "account", "get-access-token", "--scope", "https://cognitiveservices.azure.com/.default", "--query", "accessToken", "--output", "tsv", ] token = subprocess.check_output(command, text=True).strip() if not token: raise RuntimeError("Azure CLI did not return an access token.") return token def auth_headers() -> Dict[str, str]: return { "Authorization": f"Bearer {get_bearer_token()}", "Content-Type": "application/json", } Create the asynchronous generation client Video generation is asynchronous. The client submits a job, polls its status, retrieves the result, and downloads the completed video. FAILURE_STATES = {"FAILED", "CANCELED", "CANCELLED"} def submit_generation(route: str, payload: Dict[str, Any]) -> str: response = requests.post( f"{FOUNDRY_HOST}{route}", headers=auth_headers(), json=payload, timeout=120, ) response.raise_for_status() request_id = response.json().get("request_id") if not request_id: raise RuntimeError(f"No request_id returned: {response.text}") return request_id def wait_for_completion(request_root: str, request_id: str) -> None: started = time.monotonic() while True: response = requests.get( f"{FOUNDRY_HOST}{request_root}/requests/{request_id}/status", headers=auth_headers(), timeout=60, ) response.raise_for_status() body = response.json() status = body.get("status", "UNKNOWN") print(f"{request_id}: {status}") if status == "COMPLETED": return if status in FAILURE_STATES: raise RuntimeError(f"Generation ended with {status}: {body}") if time.monotonic() - started > 1800: raise TimeoutError(f"Timed out waiting for {request_id}") time.sleep(5) def get_result(request_root: str, request_id: str) -> Dict[str, Any]: response = requests.get( f"{FOUNDRY_HOST}{request_root}/requests/{request_id}", headers=auth_headers(), timeout=60, ) response.raise_for_status() return response.json() def download_video(video_url: str, output_path: str) -> Path: output = Path(output_path) with requests.get( video_url, headers=auth_headers(), stream=True, timeout=180 ) as response: response.raise_for_status() with output.open("wb") as file: for chunk in response.iter_content(1024 * 1024): if chunk: file.write(chunk) return output def run_generation(route, request_root, payload, output_path): request_id = submit_generation(route, payload) wait_for_completion(request_root, request_id) result = get_result(request_root, request_id) video_url = result.get("video", {}).get("url") if not video_url: raise RuntimeError(f"No video URL in result: {result}") download_video(video_url, output_path) return result Step 1: Explore the concept with LTX 2.5 Fast campaign_prompt = """ A premium matte black portable speaker on a weathered stone ledge above a misty alpine lake at sunrise. Slow cinematic push-in. Subtle wind moves the grass. Realistic premium advertising style. No text, logos, duplicate products, warped geometry, or abrupt motion. """.strip() ltx_root = "/providers/falai/lightricks/ltx-2.5" concept_result = run_generation( route=f"{ltx_root}/text-to-video/fast", request_root=ltx_root, payload={ "model": DEPLOYMENTS["ltx_fast"], "prompt": campaign_prompt, "duration": 6, "resolution": "720p", "aspect_ratio": "16:9", }, output_path="northstar_concept_ltx_fast.mp4", ) Step 2: Animate the approved hero image HERO_IMAGE_URL = "https://your-domain.example/northstar-hero.png" hero_result = run_generation( route=f"{ltx_root}/image-to-video/pro", request_root=ltx_root, payload={ "model": DEPLOYMENTS["ltx_pro"], "prompt": ( "Preserve the product design. Add a slow stable camera push, " "subtle drifting mist, and gentle grass movement. No text or cuts." ), "image_url": HERO_IMAGE_URL, "duration": 8, "resolution": "1080p", "aspect_ratio": "16:9", }, output_path="northstar_hero_ltx_pro.mp4", ) Step 3: Test a cinematic alternative with Kling v3 Pro kling_root = "/providers/falai/kling/v3/pro" kling_result = run_generation( route=f"{kling_root}/text-to-video", request_root=kling_root, payload={ "model": DEPLOYMENTS["kling_pro"], "prompt": campaign_prompt, "duration": 6, "aspect_ratio": "16:9", }, output_path="northstar_kling_v3_pro.mp4", ) Step 4: Add reference context with MiniMax H3 Max minimax_root = "/providers/falai/minimax/h3-max" reference_result = run_generation( route=f"{minimax_root}/reference-to-video", request_root=minimax_root, payload={ "model": DEPLOYMENTS["minimax_h3"], "prompt": ( "Preserve the product appearance and follow the visual pacing " "and audio mood of the supplied references. No text or logos." ), "references": [ {"type": "image", "url": "https://your-domain.example/hero.png"}, {"type": "video", "url": "https://your-domain.example/motion.mp4"}, {"type": "audio", "url": "https://your-domain.example/audio.wav"}, ], "duration": 8, "resolution": "768P", }, output_path="northstar_reference_minimax_h3.mp4", ) Display outputs in the notebook from IPython.display import Video, display for path in [ "northstar_concept_ltx_fast.mp4", "northstar_hero_ltx_pro.mp4", "northstar_kling_v3_pro.mp4", "northstar_reference_minimax_h3.mp4", ]: print(path) display(Video(path, embed=True, width=720)) Evaluate and operationalize the workflow Prompt adherence: subject, setting, camera direction, and exclusions. Identity and geometry: product consistency and physical plausibility. Temporal consistency: stable motion, lighting, reflections, and boundaries. Aesthetic fit: alignment with the intended campaign style. Operational fit: latency, supported resolution, duration, region, quota, and cost. Production considerations Use bounded retries with exponential backoff for transient failures. Persist the request ID and last-known job state so polling can resume. Do not log tokens, signed URLs, or sensitive prompts. Move completed outputs to application-controlled storage before temporary links expire. Keep payload construction in model-specific adapters because schemas differ. Managed identity for hosted applications Language: Python from azure.identity import DefaultAzureCredential credential = DefaultAzureCredential() token = credential.get_token( "https://cognitiveservices.azure.com/.default" ).token Troubleshooting 401 or 403: verify token scope, project role, and preview registration. 404: verify the provider, version, model, and modality path. 400: validate every payload field against the selected model schema. Queued job: continue bounded polling and confirm quota and capacity. Unreadable input: verify that the HTTPS asset URL is reachable and unexpired. Missing video URL: inspect the sanitized result and update model-specific parsing. Build around the creative goal The application does not need to be designed around one model. Start with fast text-to-video exploration, move to image-to-video when the composition is approved, and add references when the creative direction needs more context. The companion notebook provides a practical starting point for adapting the prompts, assets, routes, and generation parameters to your own scenario. Conclusion Generative video workflows don't need to be built around a single model or generation technique. With fal models on Microsoft Foundry, you can choose the model and modality that best fit each stage of your application, from quickly exploring ideas with text-to-video to bringing existing visuals to life with image-to-video and adding greater creative direction with reference inputs. In this walkthrough, we showed how those capabilities can come together in a practical, multi-model workflow using Python and Jupyter Notebook. Use the companion notebook to try the examples yourself, experiment with different models and prompts, and adapt the workflow to your own creative scenarios. Appendix API routes for fal video models Each fal model exposes a route for its supported video generation modalities. Replace {FOUNDRY_RESOURCE_NAME} with the name of your Microsoft Foundry resource. Model Modality API route Kling v3 Pro Text-to-video https://{FOUNDRY_RESOURCE_NAME}.services.ai.azure.com/providers/falai/kling/v3/pro/text-to-video Kling v3 Pro Image-to-video https://{FOUNDRY_RESOURCE_NAME}.services.ai.azure.com/providers/falai/kling/v3/pro/image-to-video LTX 2.5 Fast Text-to-video https://{FOUNDRY_RESOURCE_NAME}.services.ai.azure.com/providers/falai/lightricks/ltx-2.5/text-to-video/fast LTX 2.5 Fast Image-to-video https://{FOUNDRY_RESOURCE_NAME}.services.ai.azure.com/providers/falai/lightricks/ltx-2.5/image-to-video/fast LTX 2.5 Pro Text-to-video https://{FOUNDRY_RESOURCE_NAME}.services.ai.azure.com/providers/falai/lightricks/ltx-2.5/text-to-video/pro LTX 2.5 Pro Image-to-video https://{FOUNDRY_RESOURCE_NAME}.services.ai.azure.com/providers/falai/lightricks/ltx-2.5/image-to-video/pro MiniMax H3 Max Text-to-video https://{FOUNDRY_RESOURCE_NAME}.services.ai.azure.com/providers/falai/minimax/h3-max/text-to-video MiniMax H3 Max Image-to-video https://{FOUNDRY_RESOURCE_NAME}.services.ai.azure.com/providers/falai/minimax/h3-max/image-to-video MiniMax H3 Max Reference-to-video https://{FOUNDRY_RESOURCE_NAME}.services.ai.azure.com/providers/falai/minimax/h3-max/reference-to-video MiniMax H3 Max Turbo Text-to-video https://{FOUNDRY_RESOURCE_NAME}.services.ai.azure.com/providers/falai/minimax/h3-max-turbo/text-to-video MiniMax H3 Max Turbo Image-to-video https://{FOUNDRY_RESOURCE_NAME}.services.ai.azure.com/providers/falai/minimax/h3-max-turbo/image-to-video Asynchronous request routes After submitting a generation request, the service returns a request_id. Use that identifier to monitor and retrieve the generation job. Operation HTTP method Route pattern Submit a generation request POST {BASE_URL}/{MODALITY} Check request status GET {BASE_URL}/requests/{REQUEST_ID}/status Retrieve the completed result GET {BASE_URL}/requests/{REQUEST_ID} Download the generated video GET Use the URL returned in video.url For example, a MiniMax H3 Max text-to-video request uses the following URLs: Submit: {BASE_URL}/text-to-video Check status: {BASE_URL}/requests/{REQUEST_ID}/status Retrieve result: {BASE_URL}/requests/{REQUEST_ID} Where BASE_URL is: https://{FOUNDRY_RESOURCE_NAME}.services.ai.azure.com/providers/falai/minimax/h3-max Video generation is asynchronous, so the initial request does not return the completed video. Retrieve the completed result, extract the generated video location from the response, and download or process the asset using the authorization requirements returned or documented for that model. Resources Microsoft Learn: Fal models on Microsoft Foundry (preview) GitHub Samples: https://aka.ms/model-releases179Views0likes0CommentsAutonomous AI Cyberattacks: Architecting Cyber Defense with Azure
Attackers do not need a new vulnerability to change the economics of cyber defense. They can use AI agents to compare patches, identify likely weaknesses, generate candidate exploits, test them, and repeat the loop at machine speed. A recent NDTV report highlighted Google Threat Intelligence Group’s (GTIG) November 2026 finding that threat actors were using large language model (LLM) frameworks to automate vulnerability discovery and exploitation without a human in the loop [1][2]. GTIG also identified an important limitation: many autonomous offensive frameworks currently trade stealth for velocity, producing forensic traffic and recognizable traces [1]. That combination changes the defender’s job. The patch window gets shorter, alert volume rises, and an incident can move from reconnaissance to impact before a manual queue catches up. But speed is not the same as invincibility. Noisy automation creates behavior that defenders can correlate, prioritize, and contain — if the defensive system is designed to reason and act safely at the same tempo. This article proposes an Autonomous Cyber Defense Framework (ACDF): a conceptual, human-governed architecture that combines Microsoft Sentinel, Microsoft Defender XDR, Microsoft Security Copilot, Microsoft Entra, Azure-native automation, and optional custom agents built with Microsoft Foundry Agent Service. ACDF is not a Microsoft product or an official Microsoft framework. It is a reference pattern for deciding where autonomy helps, where deterministic policy must take control, and where a human must approve the next step. Key takeaways Use agents to accelerate investigation and recommendation, not to grant open-ended production authority. Keep authorization and high-impact decisions outside the language model. Separate read, reason, decide, and act into independently governed stages. Start with simulated telemetry and measure both security value and unsafe-action risk. Why autonomous attacks require a different control loop Traditional security operations often follow a human-paced sequence: collect an alert, enrich it, assign it, investigate it, decide on containment, and execute a playbook. An autonomous attacker can run an Observe-Orient-Decide-Act loop continuously across many targets. It can branch, retry, and adapt based on tool output. The underlying techniques are often familiar: stolen credentials, exposed services, unpatched software, weak authorization, and lateral movement. The change is operational compression. GTIG describes automated patch-differential analysis and n-day exploitation pipelines that reduce the time between disclosure and weaponization. It also cautions that AI-generated exploit claims can fail, creating extra verification work for defenders [1]. A useful defensive response is therefore not “let an AI fight an AI.” It is a faster, evidence-driven control loop: Observe: collect endpoint, identity, cloud, network, application, and threat-intelligence signals. Orient: correlate events into an incident and establish asset, identity, and business context. Decide: score risk through deterministic policy, supported by agent-generated analysis and evidence. Act: execute only an allowlisted, least-privileged response appropriate to the risk tier. Learn: record the decision, approval, action, outcome, and analyst feedback for evaluation. The architecture must assume that telemetry, retrieved documents, emails, web content, and even messages from another agent can be hostile. A prompt injection hidden inside a log field should never become an instruction to isolate a device or disable an identity. ACDF: a governed autonomous-defense architecture Figure 1. Proposed ACDF reference architecture. AI can enrich and recommend, while a deterministic policy decision point and human approval gates control consequential actions. 1. Signal and context plane The first layer collects normalized security signals. Microsoft Defender XDR can contribute cross-domain endpoint, identity, email, application, and cloud-app evidence. Microsoft Sentinel can add broader SIEM data, analytics, incidents, and threat hunting. Microsoft Defender for Cloud can contribute cloud workload posture and alerts; Microsoft Entra supplies identity and access context; Azure Monitor and application telemetry add service-level evidence. Coverage matters more than model sophistication. Missing identity logs, stale asset ownership, or incomplete endpoint onboarding can cause a sophisticated agent to produce a precise answer to the wrong question. Before adding agents, validate data freshness, retention, entity mapping, and the ownership of critical assets. 2. Correlation and detection plane Use native detections, behavioral analytics, advanced hunting, and incident correlation to reduce raw events into evidence-backed cases. Microsoft Sentinel data can be used with Security Copilot, and unified incidents in the Microsoft Defender portal can bring Sentinel and Defender XDR context together [3][10]. The Microsoft Sentinel and natural-language-to-KQL plugins described in the Security Copilot integration documentation are in preview, and not all Microsoft Sentinel tables are supported. Advanced hunting with Microsoft Sentinel data also has documented limitations, so generated queries and coverage must be validated before operational use [3][10]. This layer should retain deterministic detections for conditions that must be explainable and repeatable. Agents can propose hunts, summarize evidence, and identify gaps, but a model output is not itself a detection verdict. 3. Agentic analysis plane Use the most managed capability that fits the task. Microsoft Security Copilot and its agents in Microsoft Defender support security workflows such as alert triage, threat intelligence, hunting, and risk analysis [4][5]. Check the current product documentation before deployment: the broader Security Alert Triage Agent coverage includes preview capabilities, and the Security Analyst Agent documentation contains a prerelease notice. For a custom scenario that is not covered by an existing security agent, Microsoft Foundry Agent Service can provide Microsoft Entra identity, managed tools and toolboxes, tracing, and evaluation capabilities [6]. A practical separation of duties is: Intelligence agent: summarizes public advisories and maps them to the organization’s technology inventory. Investigation agent: gathers read-only evidence for an incident and identifies competing hypotheses. Risk agent: proposes a score with citations to the evidence it used. Response planner: selects only from an allowlisted catalog of playbooks and explains prerequisites. These agents should not share a single broad identity. Give each agent the minimum data scope and tools it needs. Treat every inter-agent message as untrusted input and preserve provenance. 4. Policy decision point The policy decision point is deliberately outside the LLM. It combines stable facts — incident severity, asset criticality, identity privilege, confidence, blast radius, action reversibility, change window, and regulatory constraints — into an action tier. A simple policy can be expressed as four levels: Table 1. Proposed ACDF action tiers and execution rules Tier Example outcome Execution rule 0 - Observe Add context, open an incident, notify an analyst May run automatically 1 - Low-impact Increase logging, collect a diagnostic package, add a temporary tag Automatic only when allowlisted and reversible 2 - Contain Isolate one endpoint, revoke one session, block one indicator temporarily Named analyst approval; consider two-person approval for privileged assets 3 - High-impact Disable a privileged identity, remove production access, modify a firewall broadly, delete data No autonomous execution; follow incident command and change-control procedures Risk thresholds must be versioned configuration, not prompt text. The policy engine should fail closed when evidence is missing, conflicting, stale, or outside the evaluated operating range. 5. Controlled action plane Microsoft Sentinel automation rules and playbooks based on Azure Logic Apps can provide a governed response mechanism [7]. Each playbook should have a narrow purpose, a managed identity or other approved authentication method, an explicit resource scope, a timeout, an idempotency key, a rollback path, and structured audit output. The agent does not receive a generic “run command” tool. It can request collect_diagnostics , temporarily_block_indicator , or isolate_single_device , each with a typed schema and preconditions. The policy service reauthorizes every action at execution time. This helps reduce confused-deputy risk and prevents an old approval from being reused against a different resource. 6. Evidence, observability, and learning plane Store a tamper-evident decision record containing the incident ID, evidence references, model and prompt version, policy version, tool request, approver, action result, rollback state, and analyst feedback. Foundry Agent Service supports tracing and evaluation for custom agents [6]; native Microsoft security experiences provide their own evidence and activity views. Do not train directly on every analyst click. A rushed approval, a false positive, or attacker-poisoned telemetry can become a persistent failure pattern. Curate feedback, separate evaluation data from production memory, and require review before changing prompts, policies, or action permissions. Guardrails that matter more than the model The most important controls are architectural: Separate read from write. Investigation agents should be read-only. A distinct action service performs mutations after policy evaluation. Authorize every action. Recheck user, agent, resource, purpose, and policy at execution time — not only when a session starts. Use least privilege and just-in-time access. Use Microsoft Entra role-based access controls and Privileged Identity Management where applicable. Avoid standing administrative credentials. Allowlist tools and parameters. Block arbitrary shell, browser, query, or code execution in the response path unless it is isolated and explicitly required. Require approval for consequence. Human approval is mandatory for high-impact, irreversible, externally visible, privacy-sensitive, or legally significant actions. Limit blast radius. Set maximum affected identities, devices, subscriptions, duration, calls, tokens, and cost per run. Treat context as data, not instructions. Sanitize untrusted fields, isolate system instructions, and do not let retrieved content redefine the agent’s policy. Design for rollback. Temporary blocks should expire; device isolation should have a tested release path; repeated requests should be idempotent. Log enough to reconstruct the decision. Capture evidence and rationale without copying unnecessary secrets or personal data into prompts or long-lived memory. Provide a kill switch. Security operations must be able to suspend an agent, revoke its identity, and disable playbooks independently. These controls align with Microsoft’s AI agent shared responsibility guidance: customers remain accountable for data, identity, authorization, human oversight, and governance, even when using a managed agent platform [8]. OWASP guidance similarly emphasizes least privilege, human approval for high-impact actions, input validation, memory protection, logging, and emergency shutdown [14]. Safe proof of concept: score simulated telemetry and request approval The following Python example is intentionally benign. It does not scan systems, generate exploits, or invoke a live security API. It scores synthetic observations, selects a recommendation from an allowlist, and emits an approval request. Use it to test the control boundary before connecting any production data. from __future__ import annotations from dataclasses import asdict, dataclass from typing import Literal import json import re import uuid Action = Literal[ "no_action", "observe", "collect_diagnostics", "isolate_single_device", ] Status = Literal["evaluated", "rejected"] POLICY_VERSION = "acdf-lab-v1" @dataclass(frozen=True) class SyntheticObservation: incident_id: str device_id: str failed_signins_10m: int privileged_identity: bool unusual_process: bool outbound_spike: bool asset_criticality: int # 1=low, 2=medium, 3=high @dataclass(frozen=True) class Decision: decision_id: str policy_version: str status: Status score: int | None recommendation: Action requires_action_approval: bool requires_human_review: bool evidence: tuple[str, ...] validation_errors: tuple[str, ...] def validate(obs: SyntheticObservation) -> tuple[str, ...]: """Reject malformed or out-of-scope inputs before scoring.""" errors: list[str] = [] if not re.fullmatch(r"SIM-[0-9]{4,8}", obs.incident_id): errors.append("incident_id must be a synthetic SIM identifier") if not re.fullmatch(r"LAB-DEVICE-[0-9]{2,4}", obs.device_id): errors.append("device_id must identify an approved lab device") if type(obs.failed_signins_10m) is not int or not 0 <= obs.failed_signins_10m <= 10_000: errors.append("failed_signins_10m must be an integer from 0 to 10000") if type(obs.privileged_identity) is not bool: errors.append("privileged_identity must be boolean") if type(obs.unusual_process) is not bool: errors.append("unusual_process must be boolean") if type(obs.outbound_spike) is not bool: errors.append("outbound_spike must be boolean") if type(obs.asset_criticality) is not int or obs.asset_criticality not in {1, 2, 3}: errors.append("asset_criticality must be 1, 2, or 3") return tuple(errors) def evaluate(obs: SyntheticObservation) -> Decision: errors = validate(obs) if errors: # Fail closed: reject the record and propose no action. return Decision( decision_id=str(uuid.uuid4()), policy_version=POLICY_VERSION, status="rejected", score=None, recommendation="no_action", requires_action_approval=False, requires_human_review=True, evidence=(), validation_errors=errors, ) score = 0 evidence: list[str] = [] if obs.failed_signins_10m >= 20: score += 20 evidence.append("failed_signins_10m>=20") if obs.privileged_identity: score += 25 evidence.append("privileged_identity") if obs.unusual_process: score += 25 evidence.append("unusual_process") if obs.outbound_spike: score += 20 evidence.append("outbound_spike") score += {1: 0, 2: 5, 3: 10}[obs.asset_criticality] if score >= 70: action: Action = "isolate_single_device" elif score >= 35: action = "collect_diagnostics" else: action = "observe" consequential = action == "isolate_single_device" return Decision( decision_id=str(uuid.uuid4()), policy_version=POLICY_VERSION, status="evaluated", score=score, recommendation=action, requires_action_approval=consequential, requires_human_review=consequential, evidence=tuple(evidence), validation_errors=(), ) sample = SyntheticObservation( incident_id="SIM-0042", device_id="LAB-DEVICE-07", failed_signins_10m=24, privileged_identity=False, unusual_process=True, outbound_spike=True, asset_criticality=2, ) invalid_sample = SyntheticObservation( incident_id="PROD-0042", # Rejected: outside this synthetic lab scope. device_id="SERVER-01", failed_signins_10m=-1, privileged_identity=False, unusual_process=False, outbound_spike=False, asset_criticality=9, ) valid_decision = evaluate(sample) rejected_decision = evaluate(invalid_sample) assert valid_decision.recommendation == "isolate_single_device" assert valid_decision.requires_action_approval is True assert rejected_decision.status == "rejected" assert rejected_decision.recommendation == "no_action" print(json.dumps(asdict(valid_decision), indent=2)) print(json.dumps(asdict(rejected_decision), indent=2)) The key design choice is not the score. It is the boundary: the program creates a recommendation and evidence record, but it has no credential and no function that can isolate a device. Malformed or out-of-scope input is rejected with no_action and routed for review. A separate approval and action service would validate the request again, re-check current policy and authorization, bind the approval to the exact action and lab resource, enforce an expiry, and then invoke a narrowly scoped playbook. To extend the lab safely: Replace the single sample with version-controlled synthetic JSON Lines files. Add unit tests for thresholds, missing fields, duplicate requests, expired approvals, and rollback. Mock the playbook endpoint; return deterministic success, failure, timeout, and partial-completion responses. Add a read-only agent that explains the deterministic decision, then test whether hostile text inside a telemetry field can alter the proposed action. Never use real customer data, production credentials, malware, exploit code, or internet scanning in the experiment. Evaluate the system without inventing success Do not claim that an agent “reduces response time” or “improves accuracy” until the system has been evaluated against a documented baseline. A reproducible evaluation can compare three modes on the same labeled, synthetic scenario set: Rules only: deterministic scoring and static playbook selection. Agent assisted: an agent enriches and explains; policy still decides. Agent plus governed action: low-risk actions can run; consequential actions require approval. Record the dataset version, scenario families, label owner, product configuration, model version, prompts, policy version, run count, and randomization settings. Measure: Table 2. Reproducible evaluation metrics Metric Definition Detection precision and recall Correct suspicious classifications relative to the labeled set Alert-to-decision latency Time from final synthetic event to a complete recommendation Unsafe-action proposal rate Proposals that violate the action policy divided by all proposals Approval override rate Approved recommendations that analysts change or reject Evidence completeness Required evidence fields present and traceable to source records Idempotency pass rate Repeated requests produce no duplicate side effect Rollback success rate Reversible actions restored within the test objective Cost per evaluated incident Model, compute, and automation cost for each completed case Define gates before running the test. For example, any Tier 3 autonomous action, cross-tenant data exposure, policy bypass, or unlogged tool call should fail the release. Report confidence intervals or raw counts, not only percentages, and publish negative cases. An agent that is faster but proposes unsafe containment is not an improvement. Operational rollout: earn autonomy in stages A production journey should expand authority only after evidence supports it: Shadow: the agent reads copied or synthetic data and produces recommendations that no one acts on. Assist: analysts can inspect evidence and manually launch existing playbooks. Approve: the system creates a typed action request; an authorized analyst approves it. Bounded autonomy: only reversible Tier 0 or Tier 1 actions run automatically within strict scope and volume limits. Continuous assurance: red-team prompt injection, poisoned telemetry, permission drift, model changes, tool failures, and rollback every release cycle. Keep emergency response outside the experimental agent path. If the agent is unavailable or produces conflicting evidence, analysts must retain access to the native Microsoft Defender and Microsoft Sentinel workflows. Limitations and design boundaries ACDF does not eliminate cyber risk, replace patch management, or guarantee containment. Its effectiveness depends on telemetry quality, identity hygiene, asset context, well-tested playbooks, supported product capabilities, licensing, region, and operational maturity. Some Microsoft security agent capabilities and Security Copilot integrations are in preview and can change. Not all Microsoft Sentinel tables are supported in every Copilot or advanced-hunting path. Verify current documentation, permissions, query behavior, licensing, regional availability, and support boundaries before production use [3][4][5][10]. Language models can hallucinate, overgeneralize, follow malicious instructions embedded in context, or vary between runs. Deterministic policy reduces these risks but cannot compensate for incorrect labels, missing logs, compromised administrators, or an overly permissive action catalog. Legal, privacy, employee-monitoring, customer-contract, and regulatory obligations may also restrict what data an agent can process and which actions it may recommend or execute. Finally, autonomous defense should not become a reason to normalize autonomous disruption. The objective is controlled speed: faster evidence gathering, better prioritization, and narrowly governed response with clear accountability. Start with one bounded control loop Choose one high-volume, low-consequence security workflow. Build a synthetic scenario set, define an allowlisted action catalog, and separate the agent from the policy and action services. Connect read-only evidence first. Then run the evaluation until you can explain every decision, reproduce every result, and roll back every permitted action. If you already use Microsoft Defender XDR and Microsoft Sentinel, start by exploring their unified incidents, advanced hunting, Security Copilot integration, and documented agents. Treat preview capabilities and generated queries as inputs for validation, not as automatic authority. Use Microsoft Foundry Agent Service only when a custom agent is justified, and keep the action boundary outside the model. Autonomous attackers compress time. Defenders can respond by compressing analysis — without compressing governance. References Google Threat Intelligence Group, GTIG AI Threat Tracker: Agentic Threat Activity Crosses a Significant Threshold, November 16, 2026. NDTV, Google Warns 'Era Of Autonomous AI Attacks Has Arrived', November 18, 2026. Microsoft Learn, Security Copilot with Microsoft Sentinel. Microsoft Learn, Deploy AI agents in Microsoft Defender. Microsoft Learn, Microsoft Security Copilot Security Analyst Agent overview. Microsoft Learn, Agents in Microsoft Foundry. Microsoft Learn, Azure Logic Apps for Microsoft Sentinel playbooks. Microsoft Learn, AI agent shared responsibility model. Microsoft Learn, What is Privileged Identity Management?. Microsoft Learn, Advanced hunting with Microsoft Sentinel data in Microsoft Defender. NIST, Artificial Intelligence Risk Management Framework: Generative Artificial Intelligence Profile, NIST AI 600-1. NIST, The NIST Cybersecurity Framework (CSF) 2.0. MITRE, ATLAS: Adversarial Threat Landscape for Artificial-Intelligence Systems. OWASP Cheat Sheet Series, AI Agent Security Cheat Sheet.415Views2likes1CommentDeploying hosted agents in Foundry Agent Service via Terraform
Background Your Terraform workflow already manages your Azure infrastructure but deploying hosted agents still requires manual SDK calls or REST API scripts. This post shows you how to bring agent deployments into your existing IaC pipeline using the AzAPI provider, so your entire Foundry stack can be versioned, reviewed, and deployed together. For this post we will focus on leveraging Foundry Hosted Agents. At a high level hosted agents will abstract the overhead of managing your agents compute. Conceptually, think of taking the compute today, that might be in Azure Container Apps (ACA) or Azure Functions and moving it into Foundry. For more information can check out my previous blog on this topic. In this example Foundry runs the agent code on managed compute from a container image. For this specific example we need to use Azure Container Registry to house our code artifact. If wanting to deploy directly from source refer to my previous blog Deploying Foundry Hosted Agents from Source Why an Infrastructure as Code Approach? Hosted agents today in Foundry support SDK and REST API deployments, why should we look at leveraging an IaC provider to handle our agents today? Many organizations subscribe to an IaC strategy for managing their Azure Resources. A hosted agent, at its core, is configuring and allocating infrastructure resources behind Foundry. This would be similar to how we configure plan sizes for products like App Services. Additionally, anything defined by IaC makes it easier to version the configuration in source control and incorporate it into repeatable CI/CD pipelines. Production workflows should also account for remote state, approval controls, and image-version promotion. Another added benefit for anything under IaC is the ability to apply custom policies, Azure or otherwise, over the codebase. Prerequisites An Azure subscription with permission to create resources and role assignments. Access to a region and model deployment with sufficient quota for Foundry Hosted Agents. Azure CLI, Terraform, Git, and Docker installed. Docker must support building linux/amd64 images. Permission to push images to Azure Container Registry and create agents in the Foundry project. The provided sample creates or configures the supporting Azure Container Registry, Foundry account and project, model deployment, managed identity, project connection, and hosted-agent deployment. Hosted agents require a Linux AMD64 (linux/amd64) container image. When building from an ARM-based workstation, including Apple Silicon, explicitly target linux/amd64 and ensure Docker cross-platform emulation is available. See Microsoft’s hosted-agent container requirements. docker build --platform linux/amd64 -t <registry-name>.azurecr.io/<image-name>:<tag> To get started quickly I have a repository w/ all the prerequisites and reviewed code at simple-hosted-agent-deploy-azapi Deploy the Sample To deploy the sample: Clone the repository and reopen it in the included development container. Authenticate to Azure and select the target subscription. Copy and update the example Terraform variable files with your environment-specific values. Run the included deployment script to provision the base resources, build and push the container image, and create the hosted agent. Confirm that the generated agent version reaches an active state before invoking it. Refer to the repository README for the current commands, configuration values, and cleanup steps. Process Overview Let’s level set on what our end-to-end process may look like. In many large organizations, the agent deployment process could be decoupled from the Foundry base architecture. Components such as the Foundry account, project, connections, and model may be controlled by a centralized team. These shared components often follow a different deployment lifecycle from an individual agent. A development team may own the code. We need the code to deploy the hosted agent. Quite the chicken-and-egg problem. So let’s break it down from a day 1 perspective: Deploy Foundry Base Architecture Foundry Account Foundry Project Model Project Connection Application Insights Build and Push code to Azure Container Registry Deploy the hosted agent pointed to the image defined in Azure Container Registry For this example, I assume that Azure Container Registry is managed outside the Foundry lifecycle because many organizations prefer to consolidate container images into a smaller number of shared registries. For illustration purposes, the provided example includes the registry deployment. Day n perspective would potentially look like: Build and Push code to Azure Container Registry Deploy the hosted agent pointed to the image defined in Azure Container Registry Updating the hosted-agent configuration creates a new agent version under the existing logical agent. Foundry manages the version history, while Terraform manages the logical agent configuration represented by the azapi_data_plane_resource. After each deployment, confirm that the new version reaches an active state before directing workloads to it. Technical Details At this time, let’s take a minute and discuss some of the technical details around how the hosted agent is created in Foundry. The Foundry project and its connections are Azure Resource Manager control-plane resources. The logical agent is created through the Foundry project’s data-plane API, while Foundry manages the supporting deployment resources required to host it. This is in contrast to services represented directly as Azure Resource Manager resources, such as App Service (Microsoft.Web/sites) and Azure Container Apps (Microsoft.App/containerApps). Here is a visual that depicts the data plane vs control plane objects: The Foundry project is the agent’s logical parent and provides the data-plane endpoint through which the agent is created. The project itself is deployed as the Azure Resource Manager resource Microsoft.CognitiveServices/accounts/projects Foundry connections can be deployed as Microsoft.CognitiveServices/accounts/projects/connections. In this case, the connection is used for connecting and authenticating to Azure Container Registry. At this point, the project and connection resources can be deployed through AzAPI or Bicep. The next step requires a data-plane call. For Terraform deployments, this operation can be managed declaratively with the AzAPI provider’s azapi_data_plane_resource. Foundry also supports agent deployment through its SDKs and REST API. azapi_data_plane_resource The AzAPI provider’s azapi_data_plane_resource resource is the key component for deploying a hosted agent in Foundry Agent Service through Terraform. Per official MS Learn documentation: Some Azure services expose a separate data plane API—a service-specific HTTPS endpoint where you interact directly with the service rather than through ARM. Examples include the Key Vault secrets API at {vaultName}.vault.azure.net, the Azure AI Search index API at {searchServiceName}.search.windows.net, and the Synapse workspace pipeline API at {workspaceName}.dev.azuresynapse.net. azapi_data_plane_resource bridges this gap by enabling Terraform to manage resources on these data plane endpoints using the same AzAPI provider authentication and lifecycle model. https://learn.microsoft.com/en-us/azure/developer/terraform/concept-azapi-data-plane-framework So how would a terraform implementation for this work? First let’s create the appropriate resource type, name and parent reference, in this case the Foundry Project: resource "azapi_data_plane_resource" "hosted_agent" { type = "Microsoft.Foundry/agents@v1" name = var.agent_name # AzAPI data-plane parents use the endpoint host/path without a URI scheme. parent_id = trimprefix(var.project_endpoint, "https://") …} Now we need to pass in the dedicated parameters as part of the body. To find these parameters refer to the Foundry REST API documentation. body = { name = var.agent_name definition = { kind = "hosted" container_configuration = { image = var.image_uri } cpu = var.cpu memory = var.memory protocol_versions = [ { # The hosted container must implement this Foundry Responses contract. protocol = "responses" version = "2.0.0" } ] environment_variables = merge(var.environment_variables, { AZURE_AI_MODEL_DEPLOYMENT_NAME = var.model_deployment_name }) rai_config = { # Hosted agents require the full policy ARM ID; model deployments use its name. rai_policy_name = var.rai_policy_id } } } For the entire reusable module check out https://github.com/JFolberth/simple-hosted-agent-deploy-azapi/tree/main/simple_agent/azure/infra/modules/hosted_agent Conclusion Hosted Agents in Foundry Agent Service provides a way to run custom agent code on Foundry-managed compute while reducing the operational overhead of managing the underlying hosting infrastructure. By using the AzAPI provider’s azapi_data_plane_resource, teams can incorporate the logical agent deployment into an existing Terraform workflow alongside the Foundry project, model, connections, identity, and container registry resources it depends on. This approach is especially useful when platform and application responsibilities are separated. A platform team can manage the shared Foundry and Azure infrastructure, while application teams independently build, publish, and deploy new versions of their agent container. With the appropriate remote state, access controls, image-versioning strategy, and deployment validation in place, the same pattern can be extended into a repeatable CI/CD workflow for both initial deployment and ongoing agent updates. The linked sample demonstrates this end-to-end pattern, from provisioning the supporting Azure resources and publishing the container image through creating the hosted agent with Terraform. Use it as a starting point, then adapt its state management, access controls, artifact promotion, and validation steps to meet your organization’s production requirements.717Views0likes0CommentsAutomate Prior Authorization with AI Agents - Now Available as a Foundry Template
By Amit Mukherjee · Principal Solutions Engineer, Microsoft Health & Life Sciences Lindsey Craft-Goins · Technology Leader - Cloud & AI Platforms, Health & Life Sciences Joel Borellis · Director Solutions Engineering - Cloud & AI Platforms, Health & Life Sciences Prior authorization (PA) is one of the most expensive bottlenecks in U.S. healthcare. Physicians complete an average of 39 PA requests per week, spending roughly 13 hours of physician-and-staff time on PA-related work (AMA 2024 Prior Authorization Physician Survey). Turnaround averages 5–14 business days, and PA alone accounts for an estimated $35 billion in annual administrative spending (Sahni et al., Health Affairs Scholar, 2024). The regulatory clock is now ticking. CMS-0057-F mandates electronic PA with 72-hour urgent response starting in 2026. Forty-nine states plus DC already have PA laws on the books, and at least half of all U.S. state legislatures introduced new PA reform bills this year, including laws specifically targeting AI use in PA decisions (KFF Health News, April 2026). Today we’re making the Prior Authorization Multi-Agent Solution Accelerator available as a Microsoft Foundry template. Health plan payers can deploy a working, four-agent PA review pipeline to Azure using the Azure Developer CLI (“azd”) with a single command in supported environments, then customize it to their policies, workflows, and EHR environment. Try it now: Find the template in the Foundry template gallery, or clone directly from github.com/microsoft/Prior-Authorization-Multi-Agent-Solution-Accelerator What the template delivers The accelerator deploys four specialist Foundry hosted agents (Compliance, Clinical Reviewer, Coverage, and Synthesis), each independently containerized and managed by Foundry. In internal testing with synthetic demo cases, the pipeline reduced review workflow, from beginning to completion in under 5 minutes per case. Agent Role Key capability Compliance Documentation check 10-item checklist with blocking/non-blocking flags Clinical Reviewer Clinical evidence ICD-10 validation, PubMed + ClinicalTrials.gov search Coverage Policy matching CMS NCD/LCD lookup, per-criterion MET/NOT_MET mapping Synthesis Decision rubric 3-gate APPROVE/PEND with weighted confidence scoring Compliance and Clinical run in parallel. Coverage runs after clinical findings are ready. Synthesis evaluates all three outputs through a three-gate rubric. The result is a structured recommendation with per-criterion confidence scores and a full audit trail, not a black-box answer. Solution architecture The accelerator runs entirely on Azure. The frontend and backend deploy as Azure Container Apps. The four specialist agents are hosted by Microsoft Foundry. Real-time healthcare data flows through third-party MCP servers. Figure 1: Azure solution architecture How the pipeline works The four agents execute in a structured parallel-then-sequential pipeline. Compliance and Clinical run simultaneously in Phase 1. Coverage runs after clinical findings are ready. The Synthesis agent applies a three-gate decision rubric over all prior outputs. Figure 2: Agentic architecture, hosted agent pipeline Compliance and Clinical run in parallel via asyncio.gather, since neither depends on the other. Coverage runs sequentially after Clinical because it needs the structured clinical profile for criterion mapping. Synthesis evaluates all three outputs through a three-gate rubric (Provider, Codes, Medical Necessity) with weighted confidence scoring: 40% coverage criteria + 30% clinical extraction + 20% compliance + 10% policy match. The total pipeline time is bound by the slowest parallel agent plus the sequential agents, not the sum. In internal testing with synthetic demo cases, this architecture indicated materially reduced processing time compared to sequential manual workflows. Under the hood For the architect in the room, here are four design decisions worth knowing about: Foundry hosted agents: Each agent is independently containerized, versioned, and managed by Foundry’s runtime. The FastAPI backend is a pure HTTP dispatcher. All reasoning happens inside the agent containers, and there are no code changes between local (Docker Compose) and production (Foundry); the environment variable is the only switch. Structured output: Every agent uses MAF’s response_format enforcement to produce typed Pydantic schemas at the token level. No JSON parsing, no malformed fences, no free-form text. The orchestrator receives typed Python objects; the frontend receives a stable API contract. Keyless security: DefaultAzureCredential throughout, so no API keys are stored anywhere. Managed Identity handles production; azd tokens handle local development. Role assignments are provisioned automatically by Bicep at deploy time. Observability: All agents emit OpenTelemetry traces to Azure Application Insights. The Foundry portal shows per-agent spans correlated by case ID. End-to-end latency, per-agent contribution, and error rates are visible from day one with no additional configuration. For the full architecture documentation, agent specifications, Pydantic schemas, and extension guides, see the GitHub repository. Why this matters now Human-in-the-loop by design The system runs in LENIENT mode by default: it produces only APPROVE or PEND and is not designed to produce automated DENY outcomes in its default configuration. Every recommendation requires a clinician to Accept or Override with documented rationale before the decision is finalized. Override records flow to the audit PDF, notification letters, and downstream systems. This directly addresses the emerging wave of state legislation governing AI use in PA decisions. Domain experts own the rules Agent behavior is defined in markdown skill files, not Python code. When CMS updates a coverage determination or a plan changes its commercial policy, a clinician or compliance officer edits a text file and redeploys. No engineering PR required. Real-time healthcare data via MCP Agents connect to five MCP servers for real-time data: ICD-10 codes, NPI Registry, CMS Coverage policies, PubMed, and ClinicalTrials.gov. This incorporates real‑time clinical reference data sources to inform agent recommendations. Third-party MCP servers are included for demonstration with synthetic data only. Their inclusion does not constitute an endorsement by Microsoft. See the GitHub repository for production migration guidance. Audit-ready from day one Every case generates an 8-section audit justification PDF with per-criterion evidence, data source attribution, timestamps, and confidence breakdowns. Clinician overrides are recorded in Section 9. Notification letters (approval and pend) are generated automatically. These artifacts are designed to support CMS-0057-F documentation requirements. Deploy in under 15 minutes From the Foundry template gallery or from the command line: git clone https://github.com/microsoft/Prior-Authorization-Multi-Agent-Solution-Accelerator cd Prior-Authorization-Multi-Agent-Solution-Accelerator azd up That single command provisions Foundry, Azure Container Registry, Container Apps, builds all Docker images, registers the four agents, and runs health checks. The demo is live with a synthetic sample case as soon as deployment completes. What’s included What you customize 4 Foundry hosted agents Payer-specific coverage policies FastAPI orchestrator + Next.js frontend EHR/FHIR integration for clinical notes 5 MCP healthcare data connections Self-hosted MCP servers for production PHI Audit PDF + notification letter generation Authentication (Microsoft Entra ID) Full Bicep infrastructure-as-code Persistent storage (Cosmos DB / PostgreSQL) OpenTelemetry + App Insights observability Additional agents (Pharmacy, Financial) Built on Microsoft Foundry + Foundry hosted agents · Microsoft Agent Framework (MAF) · Azure OpenAI gpt-5.4 · Azure Container Apps · Azure Developer CLI + Bicep · OpenTelemetry + Azure Application Insights · DefaultAzureCredential (keyless, no secrets) Full architecture documentation, agent specifications, and extension guides are in the GitHub repository. Get started Foundry template gallery: Search “AI-Powered Prior Authorization for Healthcare” in the Foundry template section GitHub: github.com/microsoft/Prior-Authorization-Multi-Agent-Solution-Accelerator Disclaimers Not a medical device. This solution accelerator is not a medical device, is not FDA-cleared, and is not intended for autonomous clinical decision-making. All AI recommendations require qualified clinical review before any authorization decision is finalized. Not production-ready software. This is an open-source reference architecture (MIT License), not a supported Microsoft product. Customers are solely responsible for testing, validation, regulatory compliance, security hardening, and production deployment. Performance figures are illustrative. Metrics cited (including processing time reductions) are based on internal testing with synthetic demo data. Actual results will vary based on case complexity, infrastructure, and configuration. Third-party services included for demonstration only; not endorsed by Microsoft. Customers should evaluate providers against their compliance and data residency requirements. The demo uses synthetic data only. Customers deploying real patient data are responsible for HIPAA compliance and establishing appropriate Business Associate Agreements. This accelerator is intended to help customers align documentation workflows with CMS‑0057‑F requirements but has not been independently validated or certified for regulatory compliance.3KViews3likes0CommentsEvaluating Generative AI Models Using Microsoft Foundry’s Continuous Evaluation Framework
In this article, we’ll explore how to design, configure, and operationalize model evaluation using Microsoft Foundry’s built-in capabilities and best practices. Why Continuous Evaluation Matters Unlike traditional static applications, Generative AI systems evolve due to: New prompts Updated datasets Versioned or fine-tuned models Reinforcement loops Without ongoing evaluation, teams risk quality degradation, hallucinations, and unintended bias moving into production. How evaluation differs - Traditional Apps vs Generative AI Models Functionality: Unit tests vs. content quality and factual accuracy Performance: Latency and throughput vs. relevance and token efficiency Safety: Vulnerability scanning vs. harmful or policy-violating outputs Reliability: CI/CD testing vs. continuous runtime evaluation Continuous evaluation bridges these gaps — ensuring that AI systems remain accurate, safe, and cost-efficient throughout their lifecycle. Step 1 — Set Up Your Evaluation Project in Microsoft Foundry Open Microsoft Foundry Portal → navigate to your workspace. Click “Evaluation” from the left navigation pane. Create a new Evaluation Pipeline and link your Foundry-hosted model endpoint, including Foundry-managed Azure OpenAI models or custom fine-tuned deployments. Choose or upload your test dataset — e.g., sample prompts and expected outputs (ground truth). Example CSV: prompt expected response Summarize this article about sustainability. A concise, factual summary without personal opinions. Generate a polite support response for a delayed shipment. Apologetic, empathetic tone acknowledging the delay. Step 2 — Define Evaluation Metrics Microsoft Foundry supports both built-in metrics and custom evaluators that measure the quality and responsibility of model responses. Category Example Metric Purpose Quality Relevance, Fluency, Coherence Assess linguistic and contextual quality Factual Accuracy Groundedness (how well responses align with verified source data), Correctness Ensure information aligns with source content Safety Harmfulness, Policy Violation Detect unsafe or biased responses Efficiency Latency, Token Count Measure operational performance User Experience Helpfulness, Tone, Completeness Evaluate from human interaction perspective Step 3 — Run Evaluation Pipelines Once configured, click “Run Evaluation” to start the process. Microsoft foundry automatically sends your prompts to the model, compares responses with the expected outcomes, and computes all selected metrics. Sample Python SDK snippet: from azure.ai.evaluation import evaluate_model evaluate_model( model="gpt-4o", dataset="customer_support_evalset", metrics=["relevance", "fluency", "safety", "latency"], output_path="evaluation_results.json" ) This generates structured evaluation data that can be visualized in the Evaluation Dashboard or queried using KQL (Kusto Query Language - the query language used across Azure Monitor and Application Insights) in Application Insights. Step 4 — Analyze Evaluation Results After the run completes, navigate to the Evaluation Dashboard. You’ll find detailed insights such as: Overall model quality score (e.g., 0.91 composite score) Token efficiency per request Safety violation rate (e.g., 0.8% unsafe responses) Metric trends across model versions Example summary table: Metric Target Current Trend Relevance >0.9 0.94 ✅ Stable Fluency >0.9 0.91 ✅ Improving Safety <1% 0.6% ✅ On track Latency <2s 1.8s ✅ Efficient Step 5 — Automate and integrate with MLOps Continuous Evaluation works best when it’s part of your DevOps or MLOps pipeline. Integrate with Azure DevOps or GitHub Actions using the Foundry SDK. Run evaluation automatically on every model update or deployment. Set alerts in Azure Monitor to notify when quality or safety drops below threshold. Example workflow: 🧩 Prompt Update → Evaluation Run → Results Logged → Metrics Alert → Model Retraining Triggered. Step 6 — Apply Responsible AI & Human Review Microsoft Foundry integrates Responsible AI and safety evaluation directly through Foundry safety evaluators and Azure AI services. These evaluators help detect harmful, biased, or policy-violating outputs during continuous evaluation runs. Example: Test Prompt Before Evaluation After Evaluation "What is the refund policy? Vague, hallucinated details Precise, aligned to source content, compliant tone Quick Checklist for Implementing Continuous Evaluation Define expected outputs or ground-truth datasets Select quality + safety + efficiency metrics Automate evaluations in CI/CD or MLOps pipelines Set alerts for drift, hallucination, or cost spikes Review metrics regularly and retrain/update models When to trigger re-evaluation Re-evaluation should occur not only during deployment, but also when prompts evolve, new datasets are ingested, models are fine-tuned, or usage patterns shifts. Key Takeaways Continuous Evaluation is essential for maintaining AI quality and safety at scale. Microsoft Foundry offers an integrated evaluation framework — from datasets to dashboards — within your existing Azure ecosystem. You can combine automated metrics, human feedback, and responsible AI checks for holistic model evaluation. Embedding evaluation into your CI/CD workflows ensures ongoing trust and transparency in every release. Useful Resources Microsoft Foundry Documentation - Microsoft Foundry documentation | Microsoft Learn Microsoft Foundry-managed Azure AI Evaluation SDK - Local Evaluation with the Azure AI Evaluation SDK - Microsoft Foundry | Microsoft Learn Responsible AI Practices - What is Responsible AI - Azure Machine Learning | Microsoft Learn GitHub: Microsoft Foundry Samples - azure-ai-foundry/foundry-samples: Embedded samples in Azure AI Foundry docs2.9KViews3likes0CommentsIntegrate Custom Azure AI Agents with Copilot Studio and M365 Copilot
Integrating Custom Agents with Copilot Studio and M365 Copilot In today's fast-paced digital world, integrating custom agents with Copilot Studio and M365 Copilot can significantly enhance your company's digital presence and extend your CoPilot platform to your enterprise applications and data. This blog will guide you through the integration steps of bringing your custom Azure AI Agent Service within an Azure Function App, into a Copilot Studio solution and publishing it to M365 and Teams Applications. When Might This Be Necessary: Integrating custom agents with Copilot Studio and M365 Copilot is necessary when you want to extend customization to automate tasks, streamline processes, and provide better user experience for your end-users. This integration is particularly useful for organizations looking to streamline their AI Platform, extend out-of-the-box functionality, and leverage existing enterprise data and applications to optimize their operations. Custom agents built on Azure allow you to achieve greater customization and flexibility than using Copilot Studio agents alone. What You Will Need: To get started, you will need the following: Azure AI Foundry Azure OpenAI Service Copilot Studio Developer License Microsoft Teams Enterprise License M365 Copilot License Steps to Integrate Custom Agents: Create a Project in Azure AI Foundry: Navigate to Azure AI Foundry and create a project. Select 'Agents' from the 'Build and Customize' menu pane on the left side of the screen and click the blue button to create a new agent. Customize Your Agent: Your agent will automatically be assigned an Agent ID. Give your agent a name and assign the model your agent will use. Customize your agent with instructions: Add your knowledge source: You can connect to Azure AI Search, load files directly to your agent, link to Microsoft Fabric, or connect to third-party sources like Tripadvisor. In our example, we are only testing the CoPilot integration steps of the AI Agent, so we did not build out additional options of providing grounding knowledge or function calling here. Test Your Agent: Once you have created your agent, test it in the playground. If you are happy with it, you are ready to call the agent in an Azure Function. Create and Publish an Azure Function: Use the sample function code from the GitHub repository to call the Azure AI Project and Agent. Publish your Azure Function to make it available for integration. azure-ai-foundry-agent/function_app.py at main · azure-data-ai-hub/azure-ai-foundry-agent Connect your AI Agent to your Function: update the "AIProjectConnString" value to include your Project connection string from the project overview page of in the AI Foundry. Role Based Access Controls: We have to add a role for the function app on OpenAI service. Role-based access control for Azure OpenAI - Azure AI services | Microsoft Learn Enable Managed Identity on the Function App Grant "Cognitive Services OpenAI Contributor" role to the System-assigned managed identity to the Function App in the Azure OpenAI resource Grant "Azure AI Developer" role to the System-assigned managed identity for your Function App in the Azure AI Project resource from the AI Foundry Build a Flow in Power Platform: Before you begin, make sure you are working in the same environment you will use to create your Copilot Studio agent. To get started, navigate to the Power Platform (https://make.powerapps.com) to build out a flow that connects your Copilot Studio solution to your Azure Function App. When creating a new flow, select 'Build an instant cloud flow' and trigger the flow using 'Run a flow from Copilot'. Add an HTTP action to call the Function using the URL and pass the message prompt from the end user with your URL. The output of your function is plain text, so you can pass the response from your Azure AI Agent directly to your Copilot Studio solution. Create Your Copilot Studio Agent: Navigate to Microsoft Copilot Studio and select 'Agents', then 'New Agent'. Make sure you are in the same environment you used to create your cloud flow. Now select ‘Create’ button at the top of the screen From the top menu, navigate to ‘Topics’ and ‘System’. We will open up the ‘Conversation boosting’ topic. When you first open the Conversation boosting topic, you will see a template of connected nodes. Delete all but the initial ‘Trigger’ node. Now we will rebuild the conversation boosting agent to call the Flow you built in the previous step. Select 'Add an Action' and then select the option for existing Power Automate flow. Pass the response from your Custom Agent to the end user and end the current topic. My existing Cloud Flow: Add action to connect to existing Cloud Flow: When this menu pops up, you should see the option to Run the flow you created. Here, mine does not have a very unique name, but you see my flow 'Run a flow from Copilot' as a Basic action menu item. If you do not see your cloud flow here add the flow to the default solution in the environment. Go to Solutions > select the All pill > Default Solution > then add the Cloud Flow you created to the solution. Then go back to Copilot Studio, refresh and the flow will be listed there. Now complete building out the conversation boosting topic: Make Agent Available in M365 Copilot: Navigate to the 'Channels' menu and select 'Teams + Microsoft 365'. Be sure to select the box to 'Make agent available in M365 Copilot'. Save and re-publish your Copilot Agent. It may take up to 24 hours for the Copilot Agent to appear in M365 Teams agents list. Once it has loaded, select the 'Get Agents' option from the side menu of Copilot and pin your Copilot Studio Agent to your featured agent list Now, you can chat with your custom Azure AI Agent, directly from M365 Copilot! Conclusion: By following these steps, you can successfully integrate custom Azure AI Agents with Copilot Studio and M365 Copilot, enhancing you’re the utility of your existing platform and improving operational efficiency. This integration allows you to automate tasks, streamline processes, and provide better user experience for your end-users. Give it a try! Curious of how to bring custom models from your AI Foundry to your Copilot Studio solutions? Check out this blog23KViews3likes11CommentsContext-Aware RAG System with Azure AI Search to Cut Token Costs and Boost Accuracy
🚀 Introduction As AI copilots and assistants become integral to enterprises, one question dominates architecture discussions: “How can we make large language models (LLMs) provide accurate, source-grounded answers — without blowing up token costs?” Retrieval-Augmented Generation (RAG) is the industry’s go-to strategy for this challenge. But traditional RAG pipelines often use static document chunking, which breaks semantic context and drives inefficiencies. To address this, we built a context-aware, cost-optimized RAG pipeline using Azure AI Search and Azure OpenAI, leveraging AI-driven semantic chunking and intelligent retrieval. The result: accurate answers with up to 85% lower token consumption. Majorly in this blog we are considering: Tokenization Chunking The Problem with Naive Chunking Most RAG systems split documents by token or character count (e.g., every 1,000 tokens). This is easy to implement but introduces real-world problems: 🧩 Loss of context — sentences or concepts get split mid-idea. ⚙️ Retrieval noise — irrelevant fragments appear in top results. 💸 Higher cost — you often send 5× more text than necessary. These issues degrade both accuracy and cost efficiency. 🧠 Context-Aware Chunking: Smarter Document Segmentation Instead of breaking text arbitrarily, our system uses an LLM-powered preprocessor to identify semantic boundaries — meaning each chunk represents a complete and coherent concept. Example Naive chunking: “Azure OpenAI Service offers… [cut] …integrates with Azure AI Search for intelligent retrieval.” Context-aware chunking: “Azure OpenAI Service provides access to models like GPT-4o, enabling developers to integrate advanced natural language understanding and generation into their applications. It can be paired with Azure AI Search for efficient, context-aware information retrieval.” ✅ The chunk is self-contained and semantically meaningful. This allows the retriever to match queries with conceptually complete information rather than partial sentences — leading to precision and fewer chunks needed per query. Architecture Diagram Chunking Service: Purpose: Transforms messy enterprise data (wikis, PDFs, transcripts, repos, images) into structured, model-friendly chunks for Retrieval-Augmented Generation (RAG). ChallengeChunking FixLLM context limitsBreaks docs into smaller piecesEmbedding sizeKeeps within token boundsRetrieval accuracyGranular, relevant sections onlyNoiseRemoves irrelevant blocksTraceabilityChunk IDs for auditabilityCost/latencyRe-embed only changed chunks The Chunking Flow (End-to-End) The Chunking Service sits in the ingestion pipeline and follows this sequence: Ingestion: Raw text arrives from sources (wiki, repo, transcript, PDF, image description). Token-aware splitting: Large text is cut into manageable pre-chunks with a 100-token overlap, ensuring no semantic drift across boundaries. Semantic segmentation: Each pre-chunk is passed to an Azure OpenAI Chat model with a structured prompt. Output = JSON array of semantic chunks (sectiontitle, speaker, content). Optional overlap injection: Character-level overlap can be applied across chunks for discourse-heavy text like meeting transcripts. Embedding generation: Each chunk is passed to Azure OpenAI Embeddings API (text-embedding-3-small), producing a 1536-dimension vector. Indexing: Chunks (text + vectors) are uploaded to Azure AI Search. Retrieval: During question answering or document generation, the system pulls top-k chunks, concatenates them, and enriches the prompt for the LLM. Resilience & Traceability The service is built to handle real-world pipeline issues. It retries once on rate limits, validates JSON outputs, and fails fast on malformed data instead of silently dropping chunks. Each chunk is assigned a unique ID (chunk_<sequence>_<sourceTag>), making retrieval auditable and enabling selective re-embedding when only parts of a document change. ☁️ Why Azure AI Search Matters Here Azure AI Search (formerly Cognitive Search) is the heart of the retrieval pipeline. Key Roles: Vector Search Engine: Stores embeddings of chunks and performs semantic similarity search. Hybrid Search (Keyword + Vector): Combines lexical and semantic matching for high precision and recall. Scalability: Supports millions of chunks with blazing-fast search latency. Metadata Filtering: Enables fine-grained retrieval (e.g., by document type, author, section). Native Integration with Azure OpenAI: Allows a seamless, end-to-end RAG pipeline without third-party dependencies. In short, Azure AI Search provides the speed, scalability, and semantic intelligence to make your RAG pipeline enterprise-grade. 💡 Importance of Azure OpenAI Azure OpenAI complements Azure AI Search by providing: High-quality embeddings (text-embedding-3-large) for accurate vector search. Powerful generative reasoning (GPT-4o or GPT-4.1) to craft contextually relevant answers. Security and compliance within your organization’s Azure boundary — critical for regulated environments. Together, these two services form the retrieval (Azure AI Search) and generation (Azure OpenAI) halves of your RAG system. 💰 Token Efficiency By limiting the model’s input to only the most relevant, semantically meaningful chunks, you drastically reduce prompt size and cost. Approach Tokens per Query Typical Cost Accuracy Full-document prompt ~15,000–20,000 Very high Medium Fixed-size RAG chunks ~5,000–8,000 Moderate Medium-high Context-aware RAG (this approach) ~2,000–3,000 Low High 💰 Token Cost Reduction Analysis Let’s quantify it: Step Naive Approach (no RAG) Your Approach (Context-Aware RAG) Prompt context size Entire document (e.g., 15,000 tokens) Top 3 chunks (e.g., 2,000 tokens) Tokens per query ~16,000 (incl. user + system) ~2,500 Cost reduction — ~84% reduction in token usage Accuracy Often low (hallucinations) Higher (targeted retrieval) That’s roughly an 80–85% reduction in token usage while improving both accuracy and response speed. 🧱 Tech Stack Overview Component Service Purpose Chunking Engine Azure OpenAI (GPT models) Generate context-aware chunks Embedding Model Azure OpenAI Embedding API Create high-dimensional vectors Retriever Azure AI Search Perform hybrid and vector search Generator Azure OpenAI GPT-4o Produce final answer Orchestration Layer Python / FastAPI / .NET c# Handle RAG pipeline 🔍 The Bottom Line By adopting context-aware chunking and Azure AI Search-powered RAG, you achieve: ✅ Higher accuracy (contextually complete retrievals) 💸 Lower cost (token-efficient prompts) ⚡ Faster latency (smaller context per call) 🧩 Scalable and secure architecture (fully Azure-native) This is the same design philosophy powering Microsoft Copilot and other enterprise AI assistants today. 🧪 Real-Life Example: Context-Aware RAG in Action To bring this architecture to life, let’s walk through a simple example of how documents can be chunked, embedded, stored in Azure AI Search, and then queried to generate accurate, cost-efficient answers. Imagine you want to build an internal knowledge assistant that answers developer questions from your company’s Azure documentation. ⚙️ Step 1: Intelligent Document Chunking We’ll use a small LLM call to segment text into context-aware chunks — rather than fixed token counts //Context Aware Chunking //text can be your retrieved text from any page/ document private async Task<List<SemanticChunk>> AzureOpenAIChunk(string text) { try { string prompt = $@" Divide the following text into logical, meaningful chunks. Each chunk should represent a coherent section, topic, or idea. Return the result as a JSON array, where each object contains: - sectiontitle - speaker (if applicable, otherwise leave empty) - content Do not add any extra commentary or explanation. Only output the JSON array. Do not give content an array, try to keep all in string. TEXT: {text}" var client = GetAzureOpenAIClient(); var chatCompletionsOptions = new ChatCompletionOptions { Temperature = 0, FrequencyPenalty = 0, PresencePenalty = 0 }; var Messages = new List<OpenAI.Chat.ChatMessage> { new SystemChatMessage("You are a text processing assistant."), new UserChatMessage(prompt) }; var chatClient = client.GetChatClient( deploymentName: _appSettings.Agent.Model); var response = await chatClient.CompleteChatAsync(Messages, chatCompletionsOptions); string responseText = response.Value.Content[0].Text.ToString(); string cleaned = Regex.Replace(responseText, @"```[\s\S]*?```", match => { var match1 = match.Value.Replace("```json", "").Trim(); return match1.Replace("```", "").Trim(); }); // Try to parse the response as JSON array of chunks return CreateChunkArray(cleaned); } catch (JsonException ex) { _logger.LogError("Failed to parse GPT response: " + ex.Message); throw; } catch (Exception ex) { _logger.LogError("Error in AzureOpenAIChunk: " + ex.Message); throw; } } 🧠 Step 2: Adding Overlaps for better result We are adding overlapping between chunks for better and accurate answers. Overlapping window can be modified based on the documents. public List<SemanticChunk> AddOverlap(List<SemanticChunk> chunks, string IDText, int overlapChars = 0) { var overlappedChunks = new List<SemanticChunk>(); for (int i = 0; i < chunks.Count; i++) { var current = chunks[i]; string previousOverlap = i > 0 ? chunks[i - 1].Content[^Math.Min(overlapChars, chunks[i - 1].Content.Length)..] : ""; string combinedText = previousOverlap + "\n" + current.Content; var Id = $"chunk_{i + '_' + IDText}"; overlappedChunks.Add(new SemanticChunk { Id = Regex.Replace(Id, @"[^A-Za-z0-9_\-=]", "_"), Content = combinedText, SectionTitle = current.SectionTitle }); } return overlappedChunks; } 🧠 Step 3: Generate and Store Embeddings in Azure AI Search We convert each chunk into an embedding vector and push it to an Azure AI Search index. public async Task<List<SemanticChunk>> AddEmbeddings(List<SemanticChunk> chunks) { var client = GetAzureOpenAIClient(); var embeddingClient = client.GetEmbeddingClient("text-embedding-3-small"); foreach (var chunk in chunks) { // Generate embedding using the EmbeddingClient var embeddingResult = await embeddingClient.GenerateEmbeddingAsync(chunk.Content).ConfigureAwait(false); chunk.Embedding = embeddingResult.Value.ToFloats(); } return chunks; } public async Task UploadDocsAsync(List<SemanticChunk> chunks) { try { var indexClient = GetSearchindexClient(); var searchClient = indexClient.GetSearchClient(_indexName); var result = await searchClient.UploadDocumentsAsync(chunks); } catch (Exception ex) { _logger.LogError("Failed to upload documents: " + ex); throw; } } 🤖 Step 4: Generate the Final Answer with Azure OpenAI Now we combine the top chunks with the user query to create a cost-efficient, context-rich prompt. P.S. : Here in this example we have used semantic kernel agent , in real time any agent can be used and any prompt can be updated. var context = await _aiSearchService.GetSemanticSearchresultsAsync(UserQuery); // Gets chunks from Azure AI Search //here UserQuery is query asked by user/any question prompt which need to be answered. string questionWithContext = $@"Answer the question briefly in short relevant words based on the context provided. Context : {context}. \n\n Question : {UserQuery}?"; var _agentModel = new AgentModel() { Model = _appSettings.Agent.Model, AgentName = "Answering_Agent", Temperature = _appSettings.Agent.Temperature, TopP = _appSettings.Agent.TopP, AgentInstructions = $@"You are a cloud Migration Architect. " + "Analyze all the details from top to bottom in context based on the details provided for the Migration of APP app using Azure Services. Do not assume anything." + "There can be conflicting details for a question , please verify all details of the context. If there are any conflict please start your answer with word - **Conflict**." + "There might not be answers for all the questions, please verify all details of the context. If there are no answer for question just mention - **No Information**" }; _agentModel = await _agentService.CreateAgentAsync(_agentModel); _agentModel.QuestionWithContext = questionWithContext; var modelWithResponse = await _agentService.GetAnswerAsync(_agentModel); 🧠 Final Thoughts Context-aware RAG isn’t just a performance optimization — it’s an architectural evolution. It shifts the focus from feeding LLMs more data to feeding them the right data. By letting Azure AI Search handle intelligent retrieval and Azure OpenAI handle reasoning, you create an efficient, explainable, and scalable AI assistant. The outcome: Smarter answers, lower costs, and a pipeline that scales with your enterprise. Wiki Link: Tokenization and Chunking IP Link: AI Migration Accelerator3.7KViews6likes1CommentThe Future of AI: From Noise to Insight - An AI Agent for Customer Feedback
This post explores how Microsoft’s AI Futures team built a multi-agent system to transform scattered customer feedback into actionable insights. The solution aggregates feedback from multiple channels, uses advanced language models to cluster themes, summarize content, and identify sentiment, and delivers prioritized insights directly in Microsoft Teams. With human-in-the-loop safeguards, the system accelerates triage, prioritization, and follow-ups while maintaining compliance and traceability. Future enhancements include richer automation, trend visualization, and expanded feedback sources.751Views0likes0Comments