ai
222 TopicsWaza 0.42.x: Making agent evaluations easier to trust
Waza evaluates more than skills. You can author repository, CLI, and MCP scenarios and run graded trials against skills, prompts, agent workflows, and custom agents, then inspect the evidence each trial leaves behind. Running an evaluation is only the first step, though. When an agent behaves unexpectedly, I want to know what ran, what evidence came back, and whether I can trust the result. That's the thread connecting Waza 0.42.0, 0.42.1, and 0.42.2. The first release adds production-integration building blocks; the follow-up patches tighten the day-to-day experience and make failures easier to investigate. Here's what changed. Know what produced a result Waza 0.42.0 adds signed execution provenance. A provenance bundle connects a run's inputs, runtime and model claims, runner image, artifacts, and terminal outcome. You can verify a bundle offline against a trust anchor you provide. Local Ed25519 signing is the default; GitHub Actions OIDC keyless signing is available as an opt-in. That doesn't make a result automatically correct. It gives you a way to check the evidence and notice when something has changed. The Lab screenshot uses a deliberately tampered test fixture, not a live evaluation. The release also adds component inventories bound to runner image and plugin digests. They help answer what went into the runner you consumed; they aren't a vulnerability or license assessment. See what happened—and where the limits are The new runner execution telemetry connects runs, work, attempts, and scheduler identifiers. It produces post-run telemetry from retained runner documents, with payload-free signals by default. You can inspect the resulting correlation in the opt-in Lab or export supported OTLP/JSON data. Resource budgets are more explicit, too. Waza can enforce wall time, model turns, and tool calls. Other limits have different capabilities: CPU and supported peak-memory usage are measured rather than enforced, while disk and process-count limits are unsupported. Admission and reports expose those distinctions instead of treating every requested limit as enforced. The same principle applies to isolation: Waza can describe and check capabilities, but it does not itself enforce a sandbox. Bring the isolation appropriate for your environment and verify the boundaries you rely on. One distinction worth calling out: runner execution telemetry is separate from product usage telemetry. Usage telemetry is enabled by default on developer machines, not in CI or development builds, and can be disabled. The usage telemetry guide explains the controls and data policy. Make evaluation comparisons more dependable Some of the most useful improvements aren't flashy: Inline prompt judges receive the candidate output and task input they need; missing verdicts no longer look like successful grading. Cache identity follows the skill, instruction, and fixture bytes actually consumed by a run, so a changed prompt or fixture isn't served a stale result. Pairwise grading compares successful skill-enabled and baseline outputs rather than inventing a comparison when baseline evidence is missing. Skill-disabled baselines avoid inheriting ambient skills and agent definitions. These fixes make a comparison more meaningful, whether you're changing a prompt, a custom agent, or a skill. Fix the friction found while using Waza Version 0.42.1 came from dogfooding the previous release. It fixes Windows task generation, rejects unsupported token formats instead of silently accepting them, and makes new skill --output-dir stay in the directory you selected. Generated CI is pinned, and live agent execution is an explicit choice. This comparison renders verbatim output from the published Windows binaries; it isn't a terminal screenshot. This patch also moves Waza to Copilot SDK v2 with a bundled runtime. Most users don't need to configure a separate CLI. If you explicitly override COPILOT_CLI_PATH , check the v0.42.1 compatibility notes: custom runtimes need protocol 4, and some execution modes restrict overrides. Keep useful evidence when something fails Version 0.42.2 focuses on the failure paths that are easy to overlook. If a later grader encounters an operational error, Waza now preserves earlier completed grader results as unscored partial evidence. The run still reports an error; those partial results don't count as a pass or affect the score. The patch also improves trigger-probe error handling, avoids putting free-form tool arguments in warning logs, and reports when Linux runtime cleanup cannot be confirmed. Adaptive responder sessions have a narrower set of permitted tools. For people using opt-in OpenTelemetry tracing, turn timing and usage events now reflect observed evidence more closely. The trace shape changed, so existing queries may need updates; the OpenTelemetry guide covers the compatibility details. There's one important open item: the #1123 responder fixture did not fully pass in pre-publication source checks. The responder stopped cleanly, but the case-sensitive grader expected BLUE and received Blue. The issue remains open; that check did not establish the root cause or test the published v0.42.2 binary. Try it Download Waza v0.42.2, or update an existing standalone installation: waza update To explore the opt-in dashboard Lab: waza serve --lab The azd extension is published and updated separately from the standalone CLI; see the release and download reference. The v0.42.2 published binaries passed offline native smoke checks on six standalone targets and three extension targets. Those checks did not run an authenticated evaluation, and there is no recorded authenticated evaluation of the published v0.42.2 binaries. For the details, read the release notes for 0.42.0, 0.42.1, and 0.42.2. What would make your agent evaluations easier to debug or trust?How to Use GitHub Copilot for SAP Development
When I started exploring AI-assisted coding for ABAP, I began with Copilot Chat in Eclipse. Like many developers, I first used the AI coding agent for straightforward generation tasks: creating an ABAP program, drafting an ALV report, preparing a Fiori elements list report, adding a validation, or defining a service. That was useful, but SAP development quickly exposed a bigger challenge. The objects still have to reach the correct SAP development package, activate in the right order, survive diagnostics, expose the intended behavior, and produce a result that can actually be inspected. That led to the question behind this article: how can I move beyond one-off AI-generated code, keep the convenience of Copilot Chat in Eclipse, connect the coding agent safely to the SAP development environment, and avoid re-explaining the same RAP engineering process every time I start a new business object? My experiment uses GitHub Copilot Chat and Agent Mode in Eclipse as the concrete AI coding experience, together with the ABAP/ADT MCP server and a reusable RAP development skill. I use an Equipment Request example throughout the article, not to present a magic generator, but to show how the pieces fit together from the first development request to activation diagnostics and the Fiori elements preview. The important shift is that the AI coding agent is no longer working only from an isolated chat request. The reusable skill supplies the development method, MCP exposes the permitted SAP operations, and SAP supplies the evidence that tells us whether the work actually succeeded. What You Will Learn How GitHub Copilot Chat and Agent Mode, reusable skills, project inputs, and ABAP/ADT MCP fit together How to connect the MCP client from Eclipse or Visual Studio Code without publishing environment secrets How to run read-only discovery before allowing SAP repository changes How to reuse the sap-rap-development skill for an Equipment Request RAP object How to define completion through activation, diagnostics, metadata, and preview evidence 1. Why MCP Changes the Copilot Experience Without a connected tool, Copilot can generate source. It cannot prove that an SAP repository object exists, activate it, read an activation error, or verify a service. MCP provides a standard way for the development client to discover and invoke supported tools. Component Responsibility GitHub Copilot Understands the request, plans the work, selects instructions, and invokes permitted tools. Reusable skill Describes how RAP development should be performed repeatedly. Task prompt Defines the specific business-object or Fiori elements development task. Project inputs Provide business fields, naming, package, transport, validations, and target details. ABAP/ADT MCP Exposes supported SAP development operations. SAP Enforces authorization and supplies the actual repository and runtime state. The skill tells Copilot how to work. MCP gives Copilot tools with which to work. SAP remains the source of truth. Prerequisites for Eclipse, ADT, and Copilot Before importing the starter project, prepare the Eclipse workspace and connected SAP development environment: Eclipse (2026-06 or later) with ABAP Development Tools (ADT) installed and a supported ABAP project created for the target SAP system. A user authorized to read the target ABAP project and to create or modify objects in the development package used for the example. GitHub Copilot for Eclipse installed, authorized with GitHub, and able to open Copilot Chat / Agent Mode. . Keep the authenticated ABAP project and the imported skill project in the same Eclipse workspace so Copilot can use the repository instructions while MCP operates against the authorized SAP target. 2. Enable the ADT MCP Server Start with an authenticated ABAP project in Eclipse/ADT and authorization for the intended development package. In the ADT MCP Server preferences, enable the server and configure the permitted project and package scope. The server provides the endpoint and authentication information required by the client. Figure 2. GitHub Copilot MCP configuration in Eclipse. Use the actual endpoint and authentication mechanism from the approved ADT setup. On the ADT side, the MCP Server settings expose the local endpoint, token-based authorization, ABAP edit support, and access restrictions for approved projects and packages. Figure 3. ADT MCP Server configuration with edit support and package-level access restrictions. The exact screen and tool set can vary by ADT version, SAP release, MCP server implementation, and GitHub Copilot plugin version. Treat the configuration as a workflow pattern rather than a universal value to copy. Security note: Mask tokens, credentials, internal hostnames, and sensitive target details in screenshots, repositories, prompts, and logs. { "servers": { "abap-mcp": { "url": "<ABAP_MCP_ENDPOINT>", "requestInit": { "headers": { "Authorization": "Bearer <MASKED_TOKEN>" } } } } } 3. Discover Before Changing SAP Objects The first connected request should be read-only. This exposes target and permission problems before the workflow attempts any repository change. Discover the available ABAP MCP tools and SAP development target. Check the connected ABAP project, package access, ABAP release, language compatibility, and available RAP development operations. Report unresolved target details. Do not create or modify SAP objects. Confirm the ABAP project and development package Identify the available read, create, edit, check, activate, and diagnostic operations Detect existing objects and naming conflicts Confirm release and package-language compatibility Keep missing permissions and unsupported operations visible as blockers Discover first. Develop second. Verify last. 4. Import the Starter Skill Project into Eclipse The starter repository is a normal Eclipse project that can sit beside the ABAP project in the same workspace. After cloning or downloading the repository, import it into Eclipse: Open Eclipse and select File > Import. Choose General > Existing Projects into Workspace, then select Next. Choose Select root directory and browse to the local sapdevcopilotskill repository. If you downloaded an archive, use Select archive file instead. Select the detected project. Choose Copy projects into workspace only if you want Eclipse to make a separate workspace copy; leave it cleared if you want to work directly from the cloned Git repository. Select Finish. Confirm that .github/skills, .github/prompts, docs, examples, scripts, and tests are visible in Project Explorer. Keep the authenticated ABAP development project open in the same workspace. Open .github/skills/sap-rap-development/SKILL.md and the Equipment Request example once to confirm that Eclipse can read the skill assets. Open GitHub Copilot Chat. Reference the imported project using the context/custom-instruction capabilities available in your installed Copilot plugin, then select or request the sap-rap-development skill for the RAP task. Why General Project? The repository mainly contains Markdown instructions, prompts, JSON project inputs, examples, scripts, and tests. The actual ABAP repository objects remain in the separate authenticated ADT project and are accessed through the allowed MCP operations. Use the Same Workflow from Visual Studio Code The same MCP-and-skill pattern can also be used from Visual Studio Code. In this setup, Visual Studio Code becomes the GitHub Copilot MCP client, while Eclipse/ADT continues to host the authenticated ABAP project and the ADT MCP Server. Visual Studio Code does not replace ADT for SAP repository management; it connects to the SAP development tools exposed by ADT MCP. Prerequisites Visual Studio Code with GitHub Copilot Chat and Agent mode enabled. The sapdevcopilotskill repository opened as the current workspace folder so the project skill under .github/skills can be discovered. Eclipse/ADT running with the authenticated ABAP project and ADT MCP Server enabled. Network access from Visual Studio Code to the ADT MCP endpoint. A localhost endpoint works when Visual Studio Code and Eclipse/ADT run on the same machine. The approved authentication mechanism from ADT MCP. Do not commit credentials to the workspace. Configure the ABAP MCP Server in Visual Studio Code Open the repository folder in Visual Studio Code. Open Copilot Chat and select Agent mode. Run Chat: Open Customizations, select MCP Servers, and choose Add Server. Choose an HTTP server type and enter the endpoint shown by the ADT MCP Server. Store required authorization using a protected input or local secret mechanism rather than a committed token. Start the server, review the discovered tools, and enable only the ABAP operations required for the task. Run the same read-only discovery prompt before allowing SAP changes. Visual Studio Code can store workspace MCP configuration in .vscode/mcp.json. User-level MCP configuration is stored outside the repository. Use workspace configuration only for details that are safe to share. Example workspace configuration { "servers": { "abap-mcp": { "type": "http", "url": "<ABAP_MCP_ENDPOINT>" } } } Authentication is intentionally omitted from the example. Apply the authorization mechanism required by the ADT MCP environment without committing credentials to Git. Reuse the Same Skill Visual Studio Code Agent mode supports project skills stored under .github/skills. Once the repository is open, Copilot can load .github/skills/sap-rap-development/SKILL.md when the skill description matches the request or when the request explicitly names the skill. Use the sap-rap-development skill. Read the Equipment Request example and rap-project.json. Discover the connected ABAP MCP tools and SAP target first. Create or update compatible RAP objects only after target confirmation. Activate, diagnose, and return SAP verification evidence. The practical difference is the client surface: Eclipse uses the GitHub Copilot MCP preferences, while Visual Studio Code uses Agent mode and .vscode/mcp.json. The project inputs, SAP authorization boundaries, and verification requirements remain unchanged. 5. Move the Repeated RAP Workflow into a Skill A direct prompt is appropriate for a small one-time task. A skill becomes useful when the same development sequence, standards, and acceptance checks recur across multiple business objects. Prompt: What should be built? Skill: How should this kind of development be performed? MCP: Which operations can Copilot execute in this environment? The starter project separates the reusable workflow from task and application details: .github/ skills/ sap-rap-development/ SKILL.md prompts/ rap-business-object.prompt.md rap-list-report.prompt.md rap-object-page.prompt.md rap-overview-page.prompt.md rap-analytical-page.prompt.md docs/ generation-contract.md examples/ rap-project.json SKILL.md captures target discovery, tool discovery, object sequencing, activation, diagnostics, verification, and reporting. Task prompts describe the current RAP or Fiori elements task. The generation contract contains shared naming, authorization, compatibility, and guardrail rules. Project configuration holds the business model and SAP target inputs. The reusable workflow is stored with the project. SKILL.md describes the RAP development sequence, while task prompts cover business objects and Fiori elements scenarios. Figure 5. The sap-rap-development skill and task-specific RAP prompts opened in Eclipse. 6. Configure the RAP Project JSON The skill describes the reusable development method, but it should not hard-code the business object, package, field model, or validation rules. Those application-specific inputs belong in rap-project.json. This keeps the same skill reusable across EquipmentRequest, TravelRequest, CostCenterRequest, and other RAP scenarios. The JSON file is configuration for this starter project. JSON is not a requirement of ABAP RAP or MCP. It is simply a structured way to give Copilot the inputs that change from one business object to another. { "project": { "name": "EquipmentRequestHub", "developmentMode": "connected", "abapProject": "<CONFIRMED_ADT_PROJECT>", "package": "<AUTHORIZED_PACKAGE>", "transport": "<TRANSPORT_OR_LOCAL_OBJECT>", "languageVersion": "discover" }, "businessObject": { "name": "EquipmentRequest", "shortName": "EQR", "prefix": "ZRC", "managed": true, "draftEnabled": true, "uuidKey": true, "etag": true }, "fields": [ { "name": "RequestId", "type": "UUID", "key": true }, { "name": "RequestNumber", "type": "CHAR", "length": 20, "required": true }, { "name": "EquipmentType", "type": "CHAR", "length": 30, "required": true }, { "name": "Office", "type": "CHAR", "length": 20, "required": true }, { "name": "Quantity", "type": "INT4", "required": true }, { "name": "EstimatedAmount", "type": "CURR", "length": 15, "decimals": 2 }, { "name": "Currency", "type": "CUKY", "length": 5 }, { "name": "RequiredDate", "type": "DATS" }, { "name": "Priority", "type": "CHAR", "length": 1 }, { "name": "Status", "type": "CHAR", "length": 1 } ], "validations": [ { "rule": "Quantity > 0", "message": "Quantity must be greater than zero" }, { "rule": "EstimatedAmount >= 0", "message": "Estimated amount cannot be negative" }, { "rule": "requiredFields", "fields": ["EquipmentType", "Office", "Quantity"] } ], "service": { "definition": "ZRC_UI_EQR", "binding": "ZRC_UI_EQR_O4", "protocol": "ODataV4", "ui": "FioriElements" }, "verification": { "activate": true, "checkServiceMetadata": true, "checkADTPreview": true, "loadSampleData": false } } The example above is illustrative. Use the property names and schema included in the repository version you import, and validate the file against rap-project.schema.json before running connected development. What each section controls project: Identifies the connected execution mode and the confirmed ADT project, authorized package, transport handling, and language-version strategy. Keep placeholders unresolved until the target is confirmed. businessObject: Defines the reusable object identity and RAP model: prefix, short name, managed or unmanaged implementation, draft support, UUID key, and ETag behavior. fields: Defines the business data model. Each field should specify a name and a target-compatible ABAP type or semantic type, plus length, decimals, key, required, currency, or unit relationships where applicable. validations: Captures business rules separately from the generic skill. For Equipment Request, this includes required fields, Quantity greater than zero, and EstimatedAmount greater than or equal to zero. service: Defines the intended service definition, service binding, OData version, and Fiori elements exposure. verification: Defines what the connected run must check before reporting success. This is where activation, metadata, preview, tests, and sample-data policy can be made explicit. How to prepare the JSON before running Copilot Copy the Equipment Request example configuration rather than editing the generic root configuration blindly. Replace only confirmed target values. Do not guess the ADT project, package, transport, or ABAP language version. Keep package and transport values consistent with the access restrictions configured in the ADT MCP Server. Check object names against package naming rules and the target repository before creation. Validate rap-project.json against rap-project.schema.json and fix structural errors before invoking the skill. Keep secrets out of JSON. MCP tokens and credentials belong in the Eclipse/MCP client configuration, not in project inputs. Use source-only mode when you are intentionally generating drafts without changing SAP; use connected mode only after target discovery succeeds. Example Copilot request using the JSON Use the sap-rap-development skill. Read examples/equipment-request-hub/rap-project.json. Validate the configuration and resolve required target placeholders. Use connected ABAP MCP only after the ADT project, package, transport, and available tools are confirmed. Create or update compatible RAP objects, activate them, and return SAP evidence for every verification requested in JSON. Important: The configuration expresses intent. It does not grant authorization, guarantee that a generator exists, or prove that the configured object names are available. The skill must still discover the target, inspect existing objects, and report conflicts or unsupported operations. 7. Use the Skill for Equipment Request The example business object includes Request Number, Equipment, Office, Requested Units, Estimated Cost, Currency, Required Date, Priority, and Status. Its intended base object set includes active and draft persistence, interface and projection data-model entities, behavior, a service definition, and an OData V4 UI service binding. Use the sap-rap-development skill. Follow the Equipment Request example and project configuration. Use connected ABAP MCP to develop and activate the EquipmentRequest RAP business object in the configured SAP development target. Resolve essential missing target details before making changes. Verify activation, service metadata, and supported ADT preview. The skill does not remove RAP complexity. It moves reusable complexity out of the chat and into version-controlled instructions that can be reviewed and improved. 8. What the Example Produces After Copilot reads the skill, task prompt, and rap-project.json, it can use the permitted ABAP MCP tools to create the requested RAP artifacts in the authorized SAP package. The resulting Equipment Request service can then be opened through the supported Fiori elements preview. The main value is reuse: the developer supplies the business request and project inputs, while the repository carries the repeatable development instructions. 9. Guardrails for Connected Development Do not guess the SAP target, package, or transport. Do not assume ABAP Cloud language mode. Do not overwrite incompatible existing objects. Do not expose authentication secrets. Do not claim activation without reading the SAP result. Do not claim a working service without checking real metadata. Report unsupported tools and missing permissions as blockers. Instructions and platform controls serve different purposes. The skill encodes the development method; SAP authorization and MCP access restrictions enforce the boundaries. 10. Verify the Fiori Elements Result The Equipment Request example exposes the RAP service through a Fiori elements list-report preview. The preview includes filters for request number, equipment, office, priority, status, currency, and required date, together with request rows and standard create and navigation actions. Figure 6. Equipment Request RAP service displayed in the SAP Fiori elements list-report preview. This provides a verification point beyond source generation. The development flow has reached an exposed application model that can be inspected through the supported SAP preview. Navigation from the list report opens the Equipment Request object page, where request details, delivery and priority, estimated cost, and tracking are presented as sections. Try the Starter Project The starter project is available at MonaDevAI/sapdevcopilotskill on GitHub. It provides reusable prompts and a RAP development skill for ABAP RAP business objects and RAP-based SAP Fiori elements scenarios. Useful community contributions include managed and unmanaged RAP patterns, draft compositions, actions, authorization, analytical scenarios, release-specific guidance, ATC and ABAP Unit checks, and stronger verification contracts. Final Thought GitHub Copilot in Eclipse or Visual Studio Code + Reusable SAP development workflow + ABAP / ADT MCP tools + SAP authorization boundaries + Evidence-based verification = Repeatable connected SAP development workflow The useful shift is from asking Copilot to generate isolated ABAP snippets to giving Copilot a repeatable development method, approved tools, project context, guardrails, and verifiable completion criteria. References GitHub Docs: Install the GitHub Copilot extension in Eclipse GitHub Docs: Quickstart for GitHub Copilot in Eclipse GitHub Docs: Set up an MCP server in Eclipse GitHub Docs: Adding agent skills for GitHub Copilot SAP Help: Enabling ADT MCP Server SAP Help: ABAP Development Tools for Eclipse Eclipse Help: Importing Existing Projects Starter project: MonaDevAI/sapdevcopilotskill on GitHub GitHub Docs: Agent skills in Visual Studio Code and supported IDEsWhere should LLM weights live on AKS? Three options for GPU cold starts, measured
Summary When you self-host an open-weight large language model (LLM) on Azure Kubernetes Service (AKS), each new replica needs two payloads before it can answer a request: the container image that holds the inference runtime, and the model weights. That wait is the cold start. On CPU services it is usually a minor nuisance; on GPU services it can decide whether autoscaling keeps up with demand, because keeping GPU nodes warm around the clock is costly. We ran a controlled experiment on AKS designed to change one variable: where the weights live and how they reach the GPU. The model, the inference engine (vLLM), the GPU (one NVIDIA A100 80 GB) and the method (scale from zero onto a fresh node) were held constant. We compared three weight-delivery methods: downloading the weights from Hugging Face Hub to local disk at start-up, streaming them from Azure Blob Storage with the Run:ai Model Streamer, and baking them into the container image. Option Where the weights live Image size Cold start (new node) 1. Download from Hub Hugging Face Hub, copied to local disk at start 9.11 GB 15:45 2. Stream from Blob Azure Blob Storage, streamed to the GPU 9.32 GB 13:35 3. Bake into the image Inside a single container image in Azure Container Registry 39.6 GB 20:12 Three findings stand out in our test environment. First, baking the weights into the image was the slowest option on a new node, 6 minutes 37 seconds behind streaming, and it requires an image rebuild for every model revision. Second, streaming from Azure Blob Storage gave the fastest weight transfer in our runs (80 s, roughly 450 MB/s), although the overall gap to the download-to-disk option was small enough that we treat it as directional. Third, the weights are only part of the story: about 65% of the streamed cold start was node provisioning and engine initialisation, which the weight-delivery choice does not change. These are single runs per option, so read them as a direction to test, not a benchmark. Your results will vary with the model, VM size, region, storage configuration and software versions. Why cold starts matter more on GPUs For a typical CPU microservice, keeping a few replicas warm costs relatively little, so cold starts are usually rare. GPU nodes change that arithmetic. At Azure list prices at the time of testing (Linux, pay-as-you-go, Switzerland North, November 2026), a general-purpose D4s v5 node cost $0.253 per hour, while a Standard_NC24ads_A100_v4 node with one A100 GPU cost $5.252 per hour, roughly 21 times as much. Running that GPU node 24×7 comes to about $3,834 per month, against about $185 for the CPU node. Prices vary by region, offer and agreement and change over time; see the Azure Virtual Machines pricing page for current prices. Node Hourly list price Running 24×7 (730 h) CPU: D4s v5, 4 vCPU $0.253 ~$185 per month GPU: NC24ads A100 v4, 1× A100 80 GB $5.252 ~$3,834 per month Because idle GPU nodes are still billed, many teams scale GPU pools on demand, often down to zero. That puts the cold start on the critical path: scale-outs during a traffic spike, Spot VM evictions, rolling updates and model swaps all wait for a new replica to load. The direct cost of one cold start is small on a single A100 (between $1.19 and $1.77 at list price in our runs), and it grows with the node: on an ND96isr H100 v5 node (8× H100) at a list price of $98.32 per hour, a 225.57-second default load works out to about $6.16, against about $1.01 for a 37.14-second streamed load. The larger cost is capacity that arrives late. While the new replica loads, the running replicas carry the traffic, queues can grow, and requests can start to time out at the gateway. Figure 1. Why GPU cold starts matter: the hourly price gap, the cost of keeping a GPU node warm, and the GPU time billed during one cold start in each option. Azure list prices at the time of testing; illustrative. Open weights are two things: a runtime and the weights An open-weight model is a set of files anyone can download. To serve it, you pair those files with a runtime. The two parts differ enough in size and change rate that how you package and deliver them is a genuine architectural decision. Runtime Weights What it contains vLLM engine, PyTorch and CUDA, base OS and Python, packaged as container image layers config.json, tokenizer files and *.safetensors shards, which hold almost all the bytes Typical size Around 9 GB (our images: 9.11 to 9.32 GB) Tens to hundreds of GB (our test model: ~36 GB) Update rhythm Often: frequent vLLM releases, plus CUDA and security patches Rarely: only when you adopt a new model revision Where it lives Azure Container Registry (ACR), pinned by digest Hugging Face Hub, Azure Blob Storage, or baked into the image A useful rule of thumb is that weight size is roughly the parameter count multiplied by the bytes per parameter. A 35-billion-parameter model stored in FP8 (one byte per parameter) is about 35 GB; the same model in BF16 (two bytes) is about 70 GB. The three options in this paper are three ways of combining these two parts and getting the weights onto the GPU. How a model replica starts on AKS In our setup the model runs in a vLLM pod on a GPU node pool. Each node is an Azure VM, Standard_NC24ads_A100_v4, with 24 vCPUs, 220 GiB of system memory and one NVIDIA A100 with 80 GB of GPU memory. With fully managed GPU node pools, AKS installs and maintains the NVIDIA driver, the device plugin and the DCGM metrics exporter. The device plugin advertises the GPU to the scheduler, and the vLLM pod requests nvidia.com/gpu: 1 to receive the whole GPU. The weights and the KV cache must both fit in the 80 GB of GPU memory. A cold start from zero is not one number but eight phases: Phase What happens Depends on where weights live? M0 Trigger: the pod cannot be scheduled No M1 The cluster autoscaler adds a GPU node No M2 The device plugin registers the GPU No M3 The kubelet pulls the container image Yes M4 The server fetches the weights Yes M5 The engine loads and compiles No M6 The startup probe succeeds and the endpoint is ready No M7 The first token goes out No Only two of the eight phases, the image pull and the weight transfer, depend on the weight-delivery option. Node provisioning and engine initialisation should cost about the same whichever option you choose, which is why the experiment reports phases rather than a single total. The three options Figure 2. The three weight-delivery paths compared in the experiment. Option 1: download from Hugging Face Hub The runtime image (9.11 GB) is pulled from Azure Container Registry (ACR), and at start-up the weights (~36 GB) are downloaded from Hugging Face Hub over the public internet into an emptyDir volume on the node’s local disk. vLLM then reads them back from disk into GPU memory. That is two serial copies on every start, and the GPU waits through both. The approach needs nothing staged in advance, which makes it convenient for development and testing, but each start depends on the availability of the external source and on internet bandwidth. Option 2: stream from Azure Blob Storage The weights are staged once per model revision into Azure Blob Storage under an immutable path such as az://models/<key>/<rev>/. The runtime image (9.32 GB, from ACR) starts vLLM with the Run:ai Model Streamer as its loader. The streamer reads tensors from Blob concurrently into a CPU memory buffer and copies each tensor to the GPU while the next ones are still being read, so there is no local-disk hop. A new model revision is just a new path; no image rebuild is needed. The trade-off is that you store and pay for your own copy of the weights. Option 3: bake the weights into the image The weights are downloaded at build time and written into a layer of a single container image, 39.6 GB in total, pushed to ACR. On start-up the kubelet pulls the full image to the node, and vLLM loads the weights from the image’s local /models path. Loading from local disk is fast, but in our setup each new node had to pull the entire image, and each model revision means a rebuild (about 40 minutes in our pipeline), a push and a redeploy, because runtime and weights are versioned together. Experiment setup Held constant Value Model Qwen3.6-35B-A3B-FP8 (~36 GB of weights) Inference engine vLLM GPU node Standard_NC24ads_A100_v4, 1× NVIDIA A100 80 GB Platform AKS, Switzerland North Start condition Scale from zero onto a fresh node: no image cache, no warm GPU Runs One run per option For each run we recorded timestamps for the phases above, from the trigger to the endpoint becoming ready. Time to the first token (M7) and GPU registration (M2) were not timed separately. Results Phase (seconds) Option 1: Hub Option 2: Blob Option 3: Baked Node provisioning 405 343 388 Image pull (M3) 111 147 564 Weight transfer (M4) 171 80 19 Engine initialisation 195 184 257 Unattributed 63 61 none Cold start, total 945 (15:45) 815 (13:35) 1,212 (20:12) Warm restart, image cached 441 338 271 Figure 3. Cold-start phases per option, single run each on a fresh node. “Unattributed” is the time to ready minus the sum of the measured phases. For Option 3 the measured phases add up to 16 s more than the total, so no unattributed time is shown. What the results mean Figure 4. Who wins which race. Streaming from Blob won both fresh-node races; the baked image won only the warm restart, once its image was cached. Single run per option. Keep the weights out of the image. Baking was the slowest option on a new node in our test, 6:37 (397 s) behind streaming. Of that gap, 356 s came from the image pull and weight phases, while node provisioning differed by only 45 s. Container image pulls ran at roughly 63 to 82 MB/s in our runs, so a 39.6 GB image took minutes to arrive on each new node, and each model revision adds a rebuild on top. Streaming gave the fastest weight transfer. The Blob stream delivered ~36 GB in 80 s, about 450 MB/s, against 171 s for the download-to-disk path. The total difference between Options 1 and 2 was 2:10, but only 55 s of it comes from the weight phases and about 60 s in each run is unattributed, so this comparison is directional rather than proven. It reflects the delivery method and network path in our environment, not the performance of Hugging Face Hub as a service. Streaming also brings an operational benefit that the clock does not show: each revision is a new immutable path, with no rebuild. Baking helps only nodes that survive. With the image already cached, the baked option restarted in 271 s, 67 s ahead of Blob. That advantage applies only to a pod restarting on a node that keeps its image cache; in a scale-from-zero setup, a scale-out typically lands on a new node and pays the full pull. The next lever is not the weights. About 65% of the streamed cold start (527 of 815 s) was node provisioning and engine initialisation, which the weight choice does not change. Our 80 s weight transfer is also not the ceiling: the AKS engineering team reported streaming about 29 GB in about 10 s on the same VM size using Premium block blob storage. Where the first caller cannot wait, keeping one warm replica remains the most direct answer. How the Run:ai Model Streamer makes streaming work vLLM’s default loader is a two-step relay: download every weight file to the node’s local disk, then read them back into GPU memory. Nothing reaches the GPU until the last byte has landed on disk, and the network sits idle while the disk-to-GPU load runs. The Run:ai Model Streamer replaces both steps with one overlapped stream. Many threads read tensors from storage into a CPU memory buffer at once, and each tensor is copied to GPU memory as soon as it arrives while others are still being read. The streamer is built into vLLM behind a single flag, --load-format runai_streamer, and reads from Azure Blob (az://), other object stores and file systems. Azure Blob Storage support is available from vLLM v0.18.0 and runai-model-streamer v0.15.6. Authentication uses the Azure default credential chain, so on AKS a pod can read from Azure Blob Storage with Microsoft Entra Workload ID instead of a storage account key. export AZURE_STORAGE_ACCOUNT_NAME=<storage-account> vllm serve az://<container>/<model-path> \ --load-format runai_streamer \ --model-loader-extra-config '{"concurrency":16}' Before adopting it, note that the streamer reads safetensors files only (weights in .bin or GGUF must be converted), and that its concurrency (default 8) and memory limit are worth tuning for your VM and storage account. Two public Microsoft measurements show what the streamer can do with well-provisioned storage. The AKS Engineering Blog timed microsoft/phi-4 (about 29 GB) on one Standard_NC24ads_A100_v4 node with vLLM v0.23.0: the default path took about 113 s to download and about 74 s to load, roughly 187 s in total, while streaming from Premium block blob loaded the weights in about 10 s. The Azure SDK Blog compared the default loader with the streamer on an ND96isr H100 v5 node (8× H100) with Premium block blob in the same region, averaging five runs: Model Size Default loader Run:ai streamer Speed-up Llama-3.1-8B 14.99 GiB 15.48 s 3.61 s ~4.3× GPT-OSS-120B 60.8 GiB 42.29 s 12.76 s ~3.3× Qwen3.5-122B-A10B 232.8 GiB 225.57 s 37.14 s ~6.1× Figure 5. Model load time, default vLLM loader versus Run:ai Model Streamer. Source: Azure SDK Blog, May 2026 (ND96isr H100 v5, Premium block blob, mean of five runs). In that benchmark the default path’s network throughput peaked at about 40 Gbps and fell to about 10 Gbps, while the streamer held a steady ~80 Gbps for the whole load. The largest model in that test, at 232.8 GiB, saw the largest speed-up, about 6.1×. Choosing an option Situation Recommended option Why GPU pools that scale from zero; large or frequently updated models Stream from Blob Fastest weight transfer in our test, small runtime image, a new revision is a new path A runtime that needs files on local disk, such as Hugging Face Text Embeddings Inference (TEI) Copy to local disk (for example with an init container) The runtime cannot stream, so stage the files once per start A small model on an always-on node with frequent pod restarts Bake into the image Fastest warm restart in our test, once the image is cached Whichever option you choose, a few practices carry over. Version the runtime and the weights separately and release the combination: a release is a weight revision, an image digest and a serving configuration, pinned together. Write each weight revision to an immutable path and verify file hashes before promoting it. Pin runtime images by digest rather than tag. Use Microsoft Entra Workload ID rather than storage account keys. And size startup probes from measured phase times rather than guesses. Limitations and next steps These results come from one run per option, so they are directional rather than statistical. In Option 2 the pod authenticated with a storage account key rather than Microsoft Entra Workload ID. The test model was a 36 GB FP8 model; a larger BF16 model (about 55.6 GB) will shift the balance further toward the weight phases. The A100 has no native FP8 compute, so vLLM ran the FP8 checkpoint as weight-only quantisation. GPU registration and time to first token were not measured, and the prices quoted are list prices for one region at one point in time, and they will change. The next round of measurements will repeat each option several times and report p50 and p95, use Microsoft Entra Workload ID end to end, test the larger BF16 model, and record the vLLM version, storage tier and streamer settings for every run. Disclaimer The results in this article come from a single test environment and are provided for information only. Results in other environments will vary with the model, VM size, region, storage configuration and software versions. Prices are Azure list prices for one region at the time of testing; they are shown as an illustration and are subject to change. This document is provided “as-is.” Information and views expressed in this document, including URL and other internet website references, may change without notice. You bear the risk of using it. This document does not provide you with any legal rights to any intellectual property in any Microsoft product. You may copy and use this document for your internal, reference purposes. References Microsoft Learn: Use GPUs for compute-intensive workloads on AKS. https://learn.microsoft.com/azure/aks/use-nvidia-gpu Microsoft Learn: Use Microsoft Entra Workload ID with AKS. https://learn.microsoft.com/azure/aks/workload-identity-overview Azure Virtual Machines pricing (Linux, pay-as-you-go). https://azure.microsoft.com/pricing/details/virtual-machines/linux/ vLLM documentation: Loading models with Run:ai Model Streamer (v0.23.0). https://docs.vllm.ai/en/v0.23.0/models/extensions/runai_model_streamer/Measuring Freshness for Web Grounding
When picking a web grounding service, most developers evaluate a provider's enterprise readiness, quality, latency, and cost. For applications built on changing information, one more question matters: how fresh are the results? An earnings announcement can reshape a customer brief, and a permitting update can upend a project plan. If the grounding service hasn't caught up, the result is rework at best and decisions based on outdated assumptions at worst. Freshness is hard to compare across providers: services return different kinds of content, and the time a page was fetched says little about when its information was recorded. FreshSearch is an open benchmark built to make that comparison consistent. It measures how effectively a service indexes & returns newly published content and whether the evidence it returns is demonstrably current. The repository's published results provide a common baseline, and because the methodology is open source, application owners can tailor the measurement to their needs. How the benchmark works FreshSearch is built around two tests. Each one runs against every provider with the same inputs and scoring rules, and the repository provides the scaffolding to run them yourself. Fresh Content Discovery checks whether a service has indexed articles soon after they're published. The benchmark starts from a seeded set of publisher feeds spanning a diverse range of categories and publisher scale. During each measurement run, it catalogs the 10 newest articles from each feed. Every grounding provider then receives the same query for each article—the article title plus the publisher's website—and is scored on whether that specific URL appears in the results. Hits on newer articles count for more, so an article published in the last 30 minutes carries 15 times the weight of one more than a day old. Searching by exact title is the easiest case for finding a specific article, so a miss most likely means the service hasn't indexed it yet, though retrieval or ranking can also be the cause. That makes the test deliberately narrower than open-ended news discovery, and it doesn't capture exactly when an article first entered an index. Evidence Freshness checks how current the data in a search response is for information that changes constantly. Version 0.1 asks every provider the same 120 questions, 60 about stock prices and 60 about weather, split evenly across popular, mid-tier, and long-tail stocks and locations. Each tier counts equally, and finance questions run only during market hours. For each response, the benchmark looks for a timestamp associated with the data, such as the quote time for a stock or the observation time for weather, rather than when the page was fetched. A model that doesn't know which provider produced the response finds the relevant evidence and quotes its timestamp, and code then confirms that the timestamp appears in the response. The score reflects how old that evidence was when the question was asked. All providers are tested in their documented search-only mode, with no added browsing or crawling. Whatever comes back in that mode counts, whether it's page content or structured data. Compare the sources that matter to your application The published benchmark uses a broad set of generally relevant feeds and questions, but your application may rely on a different mix of sources. You can add or bias toward Recent Content Discovery feeds that align with your use case: investor-relations announcements for company research, energy policy changes, trade publications for supplier monitoring, or agency notices for regulatory research. You can also extend Evidence Freshness to new categories that are most relevant to your use case. Each just needs a clear definition of what counts as evidence, which timestamp sets its age, and how quickly it goes stale. Whatever you customize, apply the same sources and scoring rules to every provider, and label custom inputs, categories, and weights clearly so results aren't mistaken for the standard benchmark. How to interpret the results The two tests produce separate scores, and FreshSearch's default configuration combines them into a single number for easier comparison. The leaderboard below uses that default: 80% Fresh Content Discovery and 20% Evidence Freshness, giving more weight to cross category new-content discovery versus the relatively more specific weather & finance measurements. The weights are adjustable, so developers can tune the combined score to match what their application depends on. The right weighting depends on what an application relies on. A stock-research assistant answering "What is the current price of MSFT?" depends on quote age. Its developers might move to an even 50/50 split or weight Evidence Freshness higher still, then rerun the comparison to see whether the ranking changes. A tool that monitors newly published regulatory notices might do the opposite and raise Fresh Content Discovery above the default 80%. Browsing can look like a shortcut to freshness: fetch a page directly and get its latest version. But that only works when the application already knows which page to fetch, such as the quote page for a specific stock. It doesn't help with an article published an hour ago that the application doesn't know exists. If a new page isn't in the index, browsing can't find it, which is why Fresh Content Discovery measures what's in the index itself. Latency is the other half of the tradeoff, and how much it matters also depends on the application. An assistant answering a user in real time has little room for delay, while a background job that refreshes a report can afford to wait. Even where browsing works, it adds seconds of latency that interactive applications often can't tolerate. The chart below plots average call latency, the mean time from request to complete response, against combined score. Both Web IQ endpoints sit in the upper left, with the top scores and latency well under half a second. Parallel is close on score but significantly slower, and Perplexity is fast but scores well below the rest. Build your own freshness evaluation The repository includes the public questions, feeds, scoring code, and a lightweight runner, so you can reproduce the published results or run a version tuned to your own application. A first run looks like this: Get API keys for the providers to evaluate. Configure each provider's endpoint and search-only settings, following the repository README. Run the benchmark. A full run can take a few hours depending on your harness. Review the two component scores before the combined score. Adjust the weighting, feeds, or questions as needed, and label anything custom. Save provider configurations and the scoring version with your results so you can compare runs over time, and measure latency and cost the same way for every provider. If your application browses or fetches pages after search, evaluate that workflow separately. A few caveats before you dive in. Freshness changes constantly, so scores will vary from run to run. We recommend averaging several runs over a few days, or at least several runs spread across a single day. Freshness also doesn't capture answer quality, which still needs direct testing. But it is a measurable part of choosing the right grounding service, and one you can compare across providers using the information your business depends on. Continue exploring Web IQ What is Web IQ? Web search and grounding APIs for AI agents Why AI agents need external groundingCetiRun: Taking AI Agents from Personal Tools to an Operable Platform on Azure
1. The adoption challenge is not whether an agent can write code At developer events, the demo often looks straightforward: describe a requirement, let AI inspect a project, change files, and run tests, and a few minutes later a feature is ready. But when a team tries to turn that demo into everyday practice, the question changes from "Is the model smart enough?" to: Who can open this agent? Which files can it read? Who manages model keys? Will the workspace survive a change of computer? How are costs controlled? And who can find out what happened when execution fails? Coding agents make these questions particularly concrete. They do not merely return text. They execute commands, install tools, and modify code. Running them on a developer's laptop is convenient, but it also distributes environment maintenance, credential management, and execution risk across individual users. Consider a team using GitHub Copilot CLI, Claude Code, and Codex CLI. Its platform team faces six recurring problems: Adoption problem Friction with individual installations What the platform needs to provide Three tools, installed and configured separately Environment drift and difficult reproduction Approved runtime images with pinned versions Agents execute code Local privileges and business data become intertwined Workload isolation and controlled access Model credentials live in terminals Difficult distribution, rotation, and revocation A centralized model endpoint and per-agent credentials Multiple users work concurrently Workspaces, accounts, and sessions may be mixed Private HOME volumes, separate workspaces, and ownership checks Long-running work needs durable state Shutdowns and container restarts can lose context Persistent storage and explicit lifecycle management Tools, models, and costs need governance Configuration depends on each user's discipline Enforceable policies, model scopes, and budget management This is how I approach CetiRun: it does not reinvent the agent; it gives existing agents a home that an organization can operate. 2. CetiRun addresses execution and governance, not code correctness CetiRun is an open-source managed runtime for AI agents and applications on Azure Kubernetes Service (AKS). A platform team installs it in its own Azure subscription. Shared platform services support users, while each agent receives its own execution resources.[1][2] "Managed runtime" should not be confused with an Azure-operated, maintenance-free SaaS. The organization remains responsible for identity, nodes, storage, images, model accounts, and platform upgrades. Its central idea is: Share the control plane and model governance; separate each agent's execution environment and working state. CetiRun is not limited to coding agents. It supports OpenClaw, Hermes, and administrator-approved Custom Agent images. The official Coding Agents example uses the Custom Agent contract to integrate three native coding CLIs; it does not add three built-in agent types.[3] The platform does not replace a native CLI's inference loop or automatically guarantee correct code. Code review, testing, release approval, and model-provider terms remain the team's responsibility. 3. Four core concepts: Agent, Team, AgentPolicy, and Sandbox CetiRun's starting point is not a particular CLI. It is a long-lived Agent resource owned by a user and retaining private state. OpenClaw, Hermes, and Custom identify runtime types; Agent is the common platform object that manages them. Four resources describe the platform's model:[2] Resource What it determines Agent Owner, runtime image, Team, Sandbox, model, and lifecycle settings Team Team context and skills; a policy-bound Team also specifies its policy and allowed Sandboxes AgentPolicy Permitted agent types, models, skills, budgets, rates, identity, and network rules for Sandbox Agents Sandbox Isolation type, CPU, memory, and HOME storage for Sandbox Agents These resources are cluster-scoped, but each agent's workloads run in a separate namespace. The resource diagram describes references between objects, not four kinds of running processes: Another distinction matters before discussing implementation: Concept Standard Agent Sandbox Agent Configuration source Deployment and agent chart defaults Bound AgentPolicy and Sandbox Isolation Chart selects Kata RuntimeClass by default; cluster support is required Sandbox selects Kata or container isolation Policy rate limits No AgentPolicy rate limits Can be set through AgentPolicy Execution prerequisite Normal runtime requirements Sandbox execution must also be enabled Creating a policy object does not automatically govern every agent. Sandbox execution is off by default. Platform teams must deliberately choose which agents enter the policy-governed execution path. Also, a Team is not a user membership authorization group. The documentation states that users can see and select Teams; CetiRun does not check Team membership. Teams organize agent context and policy, rather than replacing user access authorization.[6] 4. Architecture: control, access, execution, and models The most useful architectural distinction is between managing an agent and using it. he Portal, Operator, and AI Gateway are shared services. Namespaces, HOME volumes, and Virtual Keys are separated per agent. The optional Connections path requires its own configuration: a running agent does not automatically have access to external accounts.[2] 4.1 Control plane: manage agent resources, not just containers Users create or update agents through the Portal. The Portal writes Kubernetes custom resources. When enabled, admission validates resources and policies. The Operator then reconciles namespaces, Helm releases, workloads, routes, storage, and model access.[2] That is the value of declarative management: users describe the agent they want, and the Operator reconciles the configuration into running workloads. The Portal provides self-service access, and the Operator coordinates the lifecycle. Neither replaces the engine that performs inference and executes tools. 4.2 Access: authentication does not establish ownership by itself Browser requests pass through HTTPS and authentication. For agent routes, an ingress ownership check determines whether the user can open that agent's terminal or interface. Once authorized, traffic goes directly to the corresponding service. The Portal and Operator are not in the native CLI's inference loop.[2] Three independent authorization questions must remain separate: Authorization layer Question it answers What it does not establish Portal sign-in Who are you, and can you enter the platform? Entitlement to Copilot models Model authorization Which models may this agent call? Access to a particular GitHub repository Repository connection Which code resources may the agent access? Permission to use any model or elevate platform privileges The standard documented deployment uses Microsoft Entra ID, while the Istio authentication templates also support OIDC modes. Deployments with verified Entra tokens use tenant and object IDs for authorization; this is not merely a username comparison. Compatibility deployments without a token verifier retain alias-based authorization and require unique aliases that users cannot arbitrarily change.[6][7] Deployment design should therefore specify the identity provider, token verification, and ownership binding, rather than treating a successful sign-in as proof that every authorization control is correctly configured. 4.3 Execution and storage: private workspaces, not a shared writable directory Each agent retains its own HOME for working files, configuration, and state. In the Coding Agents example discussed later, the coding workspace is $HOME/workspace. Native sessions remain in each runtime's HOME and do not automatically migrate between runtimes.[2][3][4] The concept is a private, durable workspace for each agent, not a common writable directory for multiple agents. Code collaboration can use independent clones or branches and integrate results through a Git workflow. The standard agent chart selects a Kata RuntimeClass by default. Sandbox Agents use the isolation type selected by their Sandbox. Container isolation and Kata VM isolation are not equivalent. A namespace or a SandboxReady condition cannot replace verification of the actual runtime.[2][6] Persistent HOME preserves working state, but it is not a backup. Suspension normally scales the workload to zero while retaining HOME. CetiRun does not automatically suspend idle agents. Deleting an agent deletes its HOME along with its namespace, so backup and recovery require separate planning.[2] 4.4 Models: centralize provider keys and issue a Virtual Key per agent The AI Gateway is based on LiteLLM and uses PostgreSQL and Valkey. The Operator configures a separate Virtual Key for each agent, binding model access and a monthly budget. For Sandbox Agents, AgentPolicy can also supply rate limits.[2] In the Coding Agents example, startup requires the platform to inject: OPENAI_BASE_URL = the platform AI Gateway endpoint OPENAI_API_KEY = this Agent's Virtual Key, not a raw provider key The native adapter prepares the protocol and launch configuration for each CLI. It does not fabricate a model catalog when access fails or automatically fall back to a personal model account.[4] This reduces provider-key distribution, but it does not mean the agent contains no credentials. Its Virtual Key is present in the execution environment and can be read by processes in the container. Nor does it prove that every model request is impossible to route around the gateway. Standard Agents allow public IPv4 egress by default; user-supplied credentials may still allow direct service calls. Policy and network controls must address that boundary.[6] Budget and spend values are management information, not provider invoices or quota guarantees. Pricing configuration, budget enforcement, and service terms require separate verification. 4.5 Skills, Memory, and Connections are different extension mechanisms Teams can supply context and skills, and the optional Skill Marketplace publishes approved skills. Memory retains agent notes. Connections MCP, together with the Agent Identity Broker, uses owner-authorized external connections and short-lived tokens.[1][2] These are distinct concepts: a skill provides behavior, Memory provides state, and a Connection provides authorization to an external service. The Coding Agents adapter integrates platform instructions and skills through native CLI mechanisms, with a separate MCP integration for Memory. Enabling Memory does not automatically enable Connections MCP.[4] 4.6 Observability: an operating platform needs to explain what happened The Portal exposes agent status and events. Platform observability components use ADX-Mon to send logs, events, and metrics to Azure Data Explorer. The operations team still determines the actual collection scope and access permissions.[1][2] Observability answers "What happened during execution?" Tests answer "Was the result correct?" An agent showing Ready, a successful health check, or a readable model catalog cannot individually establish that a business task completed. 5. The official Coding Agents example illustrates Custom Agent extensibility With resource, identity, execution, and model boundaries established, examples/coding-agents becomes easier to understand. It is not a separate special-purpose platform. It is one concrete application of the Custom Agent concept.[3] 5.1 Unify the platform, not the tools' internal implementations Example Agent Native runtime Native role configuration directory Model integration path coding-copilot GitHub Copilot CLI .github/agents/ AI Gateway -> per-Agent private Copilot Proxy -> GitHub Copilot coding-claude Claude Code .claude/agents/ AI Gateway's Anthropic Messages-compatible route coding-codex Codex CLI .codex/agents/ AI Gateway's Responses route, with provider protocol translation as needed Each Custom Agent has a separate main runtime container, persistent HOME, Virtual Key, and authenticated terminal. The Custom Terminal is a separate workload and uses restricted exec into only its own agent's main container.[3][4] This is not three CLIs in one container or a shared writable checkout. The tools retain their own role formats, tool mechanisms, and session behavior. The platform supplies their common execution and governance needs. The example hosts CLIs, not the GitHub cloud coding agent service, Claude hosted sessions, or Codex Web. 5.2 A tool's name is not its model source, and readiness is not authorization The Copilot model path requires the owner to complete GitHub Copilot authorization in the Portal and have access to the selected model. That authorization does not replace a repository connection or any separate product sign-in required by the native CLI. Claude Code calling a third-party model through Anthropic Messages is a compatibility route, not a claim of official Claude model support. Codex also requires verification of the Responses route and any provider protocol translation. Each CLI, model, and provider combination needs its own tests for tool calls, streaming, errors, and cancellation.[3][4] An agent showing Ready is therefore not proof that upstream authorization is complete or that its coding results are correct. 5.3 Distinguish the real runtime from the offline interface demonstration Directory Purpose What it establishes app/ Runtime application invoking real native CLIs How real coding tools integrate with the platform examples/coding-runtime/ Interface demonstration labeled OFFLINE MOCK by default The Custom Chat interface, not actual execution of models, tools, or subagents The latter returns fixed synthetic data by default. It is useful for learning the interface, not for establishing real model capabilities or production readiness.[4][5] 6. From concepts to operations: a minimal example verification workflow Developer evangelism should not stop at a green status screenshot. A more convincing demonstration lets an agent create real files, execute tests, and then have a person independently verify the result. The following workflow illustrates the concepts above. It is not an acceptance record for a deployment. Start a real task only after approving model authorization, costs, and the scope of data sent to providers. Step 1: Open the agent's authenticated terminal https://<your-portal-host>/coding-copilot/term/ https://<your-portal-host>/coding-claude/term/ https://<your-portal-host>/coding-codex/term/ Use your own Portal domain and actual Agent names. Never put a platform password or model key into a prompt. Step 2: Read the catalog actually authorized for that agent Run this inside the Agent's browser terminal, not on your workstation: python3 -c 'import sys; sys.path.insert(0,"/opt/cetirun-coding"); from native import Gateway; print("\n".join(Gateway.from_environment().models()))' Select an exact model ID from the output: MODEL='<authorized-model-id>' python3 /opt/cetirun-coding/server.py doctor --model "$MODEL" coding-tui --model "$MODEL" doctor should return "requestedModelAuthorized": true. It checks the catalog and authorization without performing inference. If it fails, stop and investigate rather than switching to a personal endpoint to bypass the gateway.[3] Step 3: Give each tool the same task without sensitive data Work only in a new smoke-test directory under the current workspace. Create calculator.py with add(a, b), and create test_calculator.py using Python unittest for integers, negative values, and decimals. Actually run python3 -m unittest discover -s smoke-test -p 'test_*.py' -v. Report changed files, test output, and the exit code. Do not install dependencies, read credentials, commit, or push. After exiting the CLI, run the tests manually: cd "$HOME/workspace" python3 -m unittest discover -s smoke-test -p 'test_*.py' -v Acceptance requires real files, passing tests, and an explicit exit code, not just a code listing in a conversation. Separately check terminal reconnection, cancellation, and approved suspension and resumption. Files surviving reconnection do not establish that they survive a Pod restart or resumption. Cancellation also does not undo file changes or model charges already incurred. This exercise checks basic runtime usability. It is not a CLI or model leaderboard. Fair comparisons require controlled models, tasks, environments, and cost conditions. 7. How platform teams can reuse the pattern The objective is not to manually create three Deployments. It is to prepare approved images and let the Operator manage them through the Agent contract. This YAML adapts the official Claude Code example to connect the resource concepts in section 3 with the native runtimes in section 5. It is a field illustration with placeholders, not a manifest to deploy unchanged. apiVersion: cetirun.microsoft.com/v1alpha1 kind: Agent metadata: name: coding-claude spec: team: "<existing-policy-bound-team>" sandboxRef: "<sandbox-allowed-by-team>" user: alias: "<your-user-alias>" displayName: "<your-display-name>" modelAccess: sharedModels: true githubCopilot: false agent: type: custom image: "<your-registry>/cetirun-claude@sha256:<approved-digest>" username: vibe port: 8080 webUI: false helm: version: "<compatible-chart-version>" values: ttyd: enabled: true desktop: enabled: false Supply your own Team, Sandbox, user, image digest, and chart version. A policy-bound Sandbox Agent also requires Sandbox execution to be enabled. The documentation states that this execution capability is off by default; creating a Sandbox resource alone does not make it runnable.[2][3] Administrators approve image digests through customRuntime.approvedImages. Image builds pin native binary versions and verify SHA-256 checksums. Credentials must never enter build arguments or image layers. This runtime's HTTP application has no public authentication layer of its own and does not implement the platform's Web UI prefix contract. Keep webUI: false and do not expose port 8080 through an anonymous public endpoint.[4] The official source provides these offline checks and build commands: make -C examples/coding-agents/app test check make -C examples/coding-agents/app build The first checks adapter contracts. The second builds Linux amd64 images and requires downloading approved build dependencies. Even if both succeed, they do not establish live provider compatibility, identity authorization, or effective isolation. 8. Enterprise adoption requires explicit boundaries CetiRun turns many scattered responsibilities into platform capabilities, but it should not be marketed as "deploy it and become compliant." First, Standard Agents and policy-bound Sandbox Agents differ. AgentPolicy does not automatically cover every user and every agent. Network restrictions, rate limits, isolation types, and execution settings must be checked against actual resources. Second, administrators are part of the trust boundary. A Portal administrator does not gain the right to open another owner's terminal solely through that role. However, platform administrators with cluster permissions, and CetiAdmin when enabled, can have stronger access. "Administrators cannot see agent data" is not an accurate blanket claim.[6] Third, the source documents that default configurations can retain conversation content in the AI Gateway database, container logs, and Memory without automatic redaction. This affects internal code, prompts, and model responses. Organizations must define read permissions, retention, deletion, and provider data policies.[1][6] Finally, persistent state is not business continuity, a model budget is not an invoice cap, and native CLI tool permissions are not infrastructure isolation. Production acceptance must test each real boundary, rather than relying on a green Ready condition. 9. The next step is an operable agent platform The interesting part of CetiRun is not that it adds another AI platform. It demonstrates a reusable approach: Let developers keep familiar tools, but run those tools within a platform that provides identity, isolation, persistence, and model governance. Coding Agents illustrate that approach; they do not define its full scope. The same resource model and governance mechanisms also serve OpenClaw, Hermes, and other custom agents that implement the contract. When teams move beyond "Can AI write code?" to "Who can use it, where does it execute, how are credentials managed, and how do we verify the result?", they begin moving from agent demos to an agent platform they can actually operate. References CetiRun README and Overview Architecture: control plane, resource model, isolation, and lifecycle Official Coding Agents example Native Coding Runtime application and native.py Offline Coding Runtime demonstration and its limits Security: identity, permissions, credentials, isolation, and data handling OAuth2 Proxy: Entra, OIDC, and PKCE configuration Portal API routes and Agent status API298Views0likes0CommentsWhat's new with Web IQ: Ignite 2026 edition
Web IQ’s Ignite 2026 updates bring broader Azure availability, lower pricing, and new ways to ground AI agents. Auto and Auto Advanced simplify retrieval with cited evidence, while Weather, Places, Commerce in private preview, and health-aware ranking support real-world tasks. Scopes and Zero Query Logging give enterprises more control over sources and query privacy.Engineering an Agentic Scheduler
Authors: Gabriel Sze and Weixian Zhang 1. Engineering an Agentic Scheduler Moving from low-code to pro-code AI development brings greater flexibility and control, but also raises an important engineering question: how do we give AI the freedom to reason while ensuring its decisions remain reliable, predictable, and verifiable? In this post, we explore that challenge through a real-world agentic scheduling application we designed, built, and deployed on Azure. Using mixed martial arts training as an example, the system analyzes historical training schedules, extracts scheduling patterns and constraints, and generates new schedules with human-in-the-loop review and approval. Beyond the agent itself, we walk through the engineering decisions that make the application production-ready: from designing the agent harness and context engineering, to enforcing deterministic guardrails, implementing self-correction, and building an event-driven, asynchronous, observable architecture. The goal is to share practical engineering patterns and lessons that apply beyond scheduling to other enterprise agentic applications. 1.1 Defining the scheduling problem Scheduling looks deceptively simple until multiple constraints, shared resources, and partial commitments start interacting. Imagine scheduling a training program for a sports team. It needs four hours in total, split into two-hour sessions, with at least two days between them. Other activities already occupy parts of the week. Where should those sessions go? At first glance, this looks like a simple calendar problem. Find four free hours and place the session. So the engineering question is not simply: How do we ask an agent to generate a schedule? It is: How do we give an agent enough freedom to reason about scheduling, while keeping the resulting schedule deterministic, inspectable, and correct? Our application does not ask a model to produce a finished spreadsheet in one call. Instead, we decompose this into small steps. The agent gets a much smaller responsibility: choose candidate dates, inspect available slots through tools, and propose placements. Imagine planning mixed martial arts training for Team Red, Team Blue, and Team Yellow in a shared training facility. We call each martial arts activity a program, and each continuous training block a scheduled session. For example, a Muay Thai program for Team Red might run over three mornings in the same week, with each morning counted as a separate scheduled session. A program typically requires a certain number of hours, divided into sessions of an allowed duration. Team Red might train in striking and pad work, Team Blue in wrestling and submissions, and Team Yellow in conditioning and mobility. Some programs may need scarce evening slots. Others compete for the same mat, ring, or instructor. Programs may also require rest days between sessions. We will follow one fictional example throughout this post. Muay Thai Sparring requires four daytime hours for Team Red, split into two two-hour sessions at least two days apart. Team Blue and Team Yellow already have wrestling and conditioning sessions elsewhere in the shared calendar. Finding four empty hours is therefore not enough: the scheduler must place two valid sparring sessions without creating team, facility, or recovery conflicts. Before scheduling starts, the application converts source data and user-provided requirements into explicit, typed scheduling constraints. An optional review step allows a person to provide additional guidance. The important boundary is that the scheduler operates on structured input rather than interpreting raw source material directly. 1.2 Why involve an agent at all? Not every scheduling preference is naturally expressed as a hard constraint. Historical patterns may suggest preferred timings, while users may provide intent such as to keep Friday relatively light, or try to keep related activities in the same half of the week. These preferences require interpretation rather than simple constraint checking. We therefore use the model where reasoning is useful: interpreting intent, exploring candidate placements, and deciding what to try next. We keep explicit rules: session duration, required hours, spacing, conflicts, and other conditions that can be evaluated deterministically. It gives us a concrete contract: the agent proposes allocations against explicit requirements; the application owns the resulting state and the checks used to assess it. 2. Designing the Software Architecture Code snippets are simplified from the source to show the shape of each component, not exact signatures. 2.1 Components Frontend: a React 19 single-page app (Vite, MUI), authenticated with Entra ID. Talks to the backend through two channels only: REST calls to start or steer a run (program scheduling), and one long-lived SSE stream for everything coming back. Holds no run state of its own. Run status, progress, the live calendar and the finished workbook all arrive as replies on the stream, so a reload rebuilds the view from what the backend sends. Everything from the Gateway onwards is the backend: one Node.js service on Azure Container Apps that the frontend reaches only through REST and SSE. Gateway: a Fastify API, the backend's only entry point. Ingress is REST: POST /api/schedule starts a run; POST /api/steer resumes a paused one with the user's instructions. Egress is SSE: GET /api/events holds one stream per browser tab. Never runs agent code. It authenticates the request, writes the upload to the session's folder, enqueues a command that references that folder and returns at once: Mailroom: the asynchronous boundary between the gateway and the agents, made of two Postgres-backed queues, each drained by its own polling loop. Agents: two LangGraph graphs for Program IQ Agent and Scheduling Agent Session: one scheduling run for one user. Each last cycle training program .xlsx upload starts a new session with its own ID, so a user running three schedules at once has three sessions. Each session has its own dedicated workspace folder structure: /sessions/{username}/{sessionId}/ input/ ← the uploaded last cycle training program .xlsx work/ ← agent scratchpad: extracted-demand-profile.json, raw rows, traces output/ → the scheduled training programs .xlsx A session can hold several agent commands, such as a run plus the user's later answer through /api/steer. Every reply carries a sessionId and a commandId, so the frontend can tell which run and which command it belongs to. Storage: Postgres: the Mailroom's two queue tables, plus LangGraph checkpoints, so a run's graph state survives a restart. Using one database for queues and state removes the need for a separate message broker. Azure Files: On Azure, /sessions lives on an Azure Files share mounted into the container at /mnt /.agent, so session files are present in multiple replicas of Azure Container Apps and can survive a restart . Azure AI Foundry: hosts the model the agents call. Agent Tracer: records every model call and tool call as OpenTelemetry traces in Azure Application Insights, plus a per-session trace file in work/. Identity: Entra ID covers user sign-in and the backend's access to Postgres and Foundry, through managed identity. 2.2 Key Design Considerations Why REST in and SSE out, instead of WebSockets? Our communication pattern is asymmetric: clients submit scheduling requests, while agents produce asynchronous updates over several minutes. We chose REST for incoming requests because it handles multipart Excel uploads, authentication, and request validation through standard HTTP mechanisms. For outgoing updates, Server-Sent Events (SSE) was a better fit than WebSockets. The browser only needs to receive progress and agent responses, not maintain a bidirectional conversation. SSE also avoids the overhead of repeatedly polling for updates that arrive at unpredictable intervals. To handle disconnections, agent replies are persisted in reply_message, allowing the client to retrieve missed updates when it reconnects. The implementation is described further in this post. Why a command queue instead of executing agents directly within HTTP requests? Scheduling runs can take several minutes, making it impractical to execute agents directly within an HTTP request. Instead, we introduced a Postgres-backed command queue to separate request handling from agent execution. When a request arrives, the gateway persists the command and immediately returns 202 Accepted, allowing the agents to continue working independently of the HTTP connection. This separation also improves reliability and gives us greater control over execution. Commands are persisted before processing begins, so they are not silently lost if a worker crashes or restarts. Interrupted runs can be identified, marked as failed, and surfaced to the user. Command loop (inbound): claims the next command from agent_command, runs the agents on it, and settles it as completed, paused or failed. Claims use row locking, so several replicas can drain one queue without running a command twice. // domain/mailroom/command-loop.ts while (!stop.stopping) { if ((await pickAndExecuteCommand(helper)) !== 'idle') { idleWait = IDLE_WAIT_MS; // work arrived: drain greedily continue; } await stop.sleep(idleWait); idleWait = nextIdleWait(idleWait); // empty queue: back off } Reply loop (outbound): delivers rows from reply_message to the SSE streams that its own replica holds. Each replica serves only the users connected to it, so there's no broker and no sticky sessions. Undelivered replies stay queued until the user reconnects. const users = sse.streamingUsernames(); // who is connected to THIS replica for (const reply of await queue.getReplies(users)) { if (sse.send(reply.username, reply) > 0) await queue.clearDelivered(reply); } The loops never call each other. Commands flow in, replies flow out, and the agents write their own replies. The command loop processes one command at a time, limiting concurrent scheduling runs and preventing too many requests from hitting the model at once. Additional commands simply wait in the queue until capacity becomes available. By keeping the execution loop separate from the agent graph, we can replace the real agents with a mock implementation and test the entire flow, from the gateway through the command queue to SSE responses, without making any model calls. // domain/mailroom/agent-run.ts — the one seam: swap the import (and its call) import { runAgentStream } from '../agent/agent-graph.ts'; // import { runMockAgentStream } from '../agent/mock-agent-graph.ts'; // domain/agent/mock-agent-graph.ts — same state, same checkpointer, one node that only talks const graph = new StateGraph(AgentState) .addNode(MOCK_REPLIER, createMockReplier()) .addEdge(START, MOCK_REPLIER) .addEdge(MOCK_REPLIER, END) .compile({ checkpointer: await checkpointer() }); Why Postgres instead of Azure Service Bus or another broker? Rather than introducing a dedicated message broker, we chose to build our command queue on Postgres, which was already serving as the application's primary database. Beyond storing application data, Postgres also manages the command queue, agent replies, execution history, and LangGraph checkpoints. This allows us to consolidate several responsibilities into a single service, reducing the operational overhead of managing, securing, and monitoring additional Azure resources. We also kept the queue implementation behind a light interface (pickNext, complete, pause, fail), allowing us to swap Postgres to a dedicated broker such as Azure Service Bus if throughput requirements grow. Ultimately, we chose to optimize for simplicity at our current scale, while keeping the architecture flexible enough to evolve. 3. From historical schedules to structured demand 3.1 Uploading past programs The workflow begins when the user uploads reference programme workbooks from previous cycles, along with any relevant contextual information that can help ground the scheduler when planning future programmes. Each uploaded .xlsx file is saved to a new session folder, after which the gateway places a lightweight command on the queue containing the user, session Id, and plan start date. The files themselves are not included in the command, keeping the queue payload small. This allows the HTTP request to return immediately while the ingestion process runs asynchronously, without tying up the web server. An optional review: true flag allows users to pause the workflow after ingestion to review the extracted information before proceeding with scheduling. We'll cover this further in the Human-in-the-loop section. // api/rest-api.ts for (const upload of uploads) await writeFile(join(input, upload.filename), upload.content); const command: AgentCommand = { commandId: nextUlid(), username, sessionId, type: 'file-upload', planStart, files, review, }; 3.2 Program IQ: extracting the demand profile and insights Program IQ serves as an intelligence layer that uses historical programmes to understand the scheduling requirements for the upcoming cycle. It starts by analysing the Excel workbooks (or whatever additional context) uploaded by the user, which contain the programmes conducted in previous cycles. Rather than relying entirely on an LLM, we separate interpretation from computation. The LLM interprets the varying structures and layouts of the workbooks, while deterministic code processes the extracted information to build a demand profile for each programme and team. This captures details such as the number of sessions required, their duration, recurrence patterns, preferred time slots, and spacing between sessions. // domain/agent/program-iq/program-iq-agent-graph.ts new StateGraph(IQState) .addNode(NODES.phaseFilesPairing, createPhaseFilesPairing()) // filename → phase .addNode(NODES.extractRawPrograms, createExtractRawProgramsAgent()) // LLM: grid → rows .addNode(NODES.normalizeRawPrograms, extractProgramIQ()) // code: rows → demand .addEdge(START, NODES.phaseFilesPairing) .addEdge(NODES.phaseFilesPairing, NODES.extractRawPrograms) .addEdge(NODES.extractRawPrograms, NODES.normalizeRawPrograms) One pi-agent-core agent per sheet, up to 6 at once. Each agent gets a system prompt (how past programs are laid out, the day's periods, what to ignore), one sheet name and two tools. It loops until every activity on the sheet is reported. Two tools The Program IQ agent has two tools: one to read the spreadsheet and another to report the extracted information. Rather than following a hardcoded sequence, we chose to introduce an LLM that sits between these tools, deciding when to read the workbook and how to interpret and report its contents. read_sheet tool uses exceljs to turn a sheet into text – understands layout, merged cells, colors, column positions, and flattens that layout into plain lines the model can read. report_activities tool records what the model found. The model reports each activity as one line: date, team, program, location, colour, periods, kind. 2024-06-17 Team Red Striking · FF92D050 1,2 training From activities to demand profiles (code) Plain code counts the reported activities into a demand profile per program and team. No LLM is involved, so every number is traceable back to the source files but meant to softly guide future planning. Demand profile What it holds Volume Total day and night periods Session length Shortest and longest session Rhythm How often it recurs, e.g. weekly on Fridays Slot pattern Which periods of the day it used Spacing Fewest days between two sessions The demand profile is the signature. Teams with identical demand profiles are grouped together to avoid duplicating the same scheduling requirements. For example, if Team Red and Team Blue require the same number of sessions, durations, recurrence patterns, and spacing, they can share a single demand profile. This grouping is purely for representation – each team still needs its own sessions scheduled independently. The output: One row per program and matching group of teams: Open Mat [Team Red, Team Blue] 4 hours a week · 4-hour sessions · weekly on Fri · ≥ 7 days apart Sparring [Team Red] 6 hours a week · 2–3-hour sessions · Tue and Thu · ≥ 2 days apart demand profile .xlsx as input to Scheduler Agent Nobody types this demand in; it is read back from what the teams previously trained. It is what the Scheduling Agent places onto next cycle's calendar, and shared rows become shared batches. 4. Human-in-the-loop: review, steer and resume Historical activity tells us what happened before, but not necessarily what should happen next. Users may want lighter Fridays, prefer certain activities earlier in the week, or restrict specific programmes to specific days. Before scheduling begins, users can review the extracted requirements and provide additional instructions through a separate steer command. This command incorporates their preferences into the existing requirements and resumes the scheduling workflow. We currently support two types of steering guides: Overall preferences apply to the scheduling run as a whole: Prefer lighter Friday afternoons where possible. Program-specific apply to a particular programme in “User Steering” column These instructions are propagated to the relevant scheduling agents, with programme-specific instructions attached to the corresponding activities across the scheduling tiers. Where user instructions conflict with historical patterns, current user intent takes precedence. However, steering an LLM is not the same as enforcing a constraint. Natural-language instructions can influence how agents propose and evaluate placements, but only constraints explicitly implemented in code can be deterministically enforced. For example, "Prefer lighter Friday afternoons" may influence which slots an agent considers, while "Sessions must be at least two days apart" can be validated after every placement. 4.1 Extracted Program IQ: pause for human steering and approval Rather than keeping an agent running while waiting for user input, the system persists the paused state in the store and sends a steer-request containing the extracted programmes for review. This allows the agent to process other requests in the meantime. The user can then review the extracted demand profile and choose to either approve it as-is or provide additional instructions: Approve as-is: submit a steer command without steering guides. Steer and approve: submit a steer command with steering guides to influence the scheduling process. In both cases, the steer command resumes the workflow and initiates scheduling using the approved requirements. // domain/agent/agent-graph.ts await writeExtractedPrograms(session, { plan, programs }); if (command.review === true) { await enqueueReply(newSteerRequest(command, steerableProgrammes({ plan, programs }))); return 'paused'; } 4.2 Steer and Resume As shared, steering can take two forms: program-specific (guides[]) and an overall preference that applies to the entire scheduling run. Both are optional and serve as guidance for the scheduling agents rather than automatically enforced constraints. The request creates a new steer command associated with the existing session. Instead of reprocessing the original Excel workbooks, the workflow reloads the saved demand-profile.json, attaches any programme-specific instructions to their corresponding records, and proceeds directly to scheduling. if (command.type === 'steer') { const steered = withSteeringGuides(await readExtractedPrograms(session), command.guides); yield* schedulePhases(command, session, steered, command.brief ?? '', onProgress); } 5. Inside the Scheduling Agent and Harness Engineering Before we dive in, let's establish a few key terms and how they relate to one another: Slot (or Period): A single unit of time, typically 1 hour, but configurable to other durations. Session: A scheduled training instance consisting of one or more slots. Program: A type of training, such as Muay Thai Clinching or Pad Work. Each program can have multiple sessions. Grid (or Calendar): The scheduling interface where slots and sessions are organized and displayed. In short, a program contains sessions, each session occupies one or more slots, and everything is represented on a calendar grid. The LLM's reasoning and tool-calling loop is only one part of the scheduling system. Around it, we need to manage what context the agent receives, which tools it can access, how scheduling state is maintained, how proposed changes are applied, and what happens when the schedule remains incomplete. In our implementation, LangGraph orchestrates the overall scheduling workflow, while pi-agent-core manages the LLM's reasoning and tool-calling interactions within individual stages. Other stages, such as deterministic seeding and schedule evaluation, run entirely through code without invoking an LLM. new StateGraph(AgentState) .addEdge(START, 'HolidaySeeder') // code .addEdge('HolidaySeeder', 'RoutineSeeder') // code .addEdge('RoutineSeeder', 'EventScheduler') // LLM .addEdge('EventScheduler', 'ProgramScheduler') .addEdge('ProgramScheduler', 'Evaluator') // code .addConditionalEdges('Evaluator', (s) => failed(s) && s.round <= 3 ? 'ProgramScheduler' : 'FillerScheduler') .addEdge('FillerScheduler', END) .compile({ checkpointer: new PostgresSaver(pool) }); Before each agentic scheduling phase, the harness prepares the context relevant to the current batch and provides tools scoped to that task. The agent can inspect availability and propose placements, but it does not maintain its own separate version of the schedule. Instead, its tools interact with the same calendar state used by the application, ensuring that scheduling decisions are based on a consistent view. The process begins deterministically. Existing routines, breaks, and recurring activities that can be reliably identified are placed onto the calendar before the agent begins scheduling. The agent then works with this partially populated calendar to find suitable slots for the remaining activities. Once placements are made, deterministic evaluators check the updated schedule for completeness and constraint violations, rather than relying on the LLM to assess its own work. 5.1 What the agent works with (context engineering) An important part of building the scheduling agent is deciding what information the LLM needs, what it can retrieve through tools, and what should remain in application state. Rather than asking the model to work out information the application already knows, we provide stable facts such as available dates, their corresponding weekdays, and the ordering of scheduling periods directly in its context. Our approach to context engineering follows a simple principle: provide stable facts upfront, retrieve changing calendar information through tools, and keep the authoritative scheduling state outside the conversation. Calendar grid (agent state) - The calendar is a nested dictionary held in memory, schedule[day][team][period], where each entry holds what is scheduled in that slot. The agent tools and calendar inventory work on this one object directly, so a write is visible to the next read at once, with no database in between. System prompt - The system prompt is a Markdown template, batch-schedule-prompt.md, read from disk once. Before the first turn, code fills its {placeholders} with this run's values: // domain/training/scheduler.ts systemPrompt: fillPromptTemplate(template, { day_keys: phase.dayKeysJson, // the dates the model may use day_of_week: phase.dayReference, // each date whether is it a weekday so model knows the weekdays period_table: PERIOD_TABLE, // the slots in a day // … }), The filled prompt tells the model: Role: which program to place, and the one write tool bound to it. Facts: dates, weekdays and slot layout, worked out in advance. The prompt says "never compute these yourself", because models get calendar arithmetic wrong. Rules: what a valid session looks like, stated so the model can plan without trial and error. Tool protocol: read once, then send every placement in one reply. Strategy: plan → confirm → commit. User prompt holds what changes from run to run: the user’s steering guide and, on a retry, only the sessions that failed. 5.2 What the scheduling agent does An important part of designing the scheduling agent is deciding what it can read and what it is allowed to change. Rather than giving the agent unrestricted access to the calendar, we expose a set of tools with clearly defined boundaries. Read tools provide the information needed to make scheduling decisions, while write tools constrain how placements can be made. A query specifies candidate days, teams, and an optional slot window. The response distinguishes between: empty slots commitments that may be overridden hard blocks that cannot be changed To minimise unnecessary context, the response is compressed. For example, if an entire day is unavailable, the tool returns a short marker rather than listing every blocked period individually. The prompt encourages a simple search pattern: choose candidate dates → query free slots in candidate dates → propose a placement → inspect alternatives if necessary Agent loop The agent runs a plain loop: model turn → tool call[]? → run each tool → append result → model turn. Each result is the model's only view of the calendar. The loop ends when there is no tool call. 1. Plan - The model chooses candidate days from the facts in its prompt, without calling a tool. The planning is cheap reasoning, so the tools only confirm and commit. 2. Read with getFreePeriod The model pass in the dates as tool parameter for every team it needs, in one call: { "days": ["12/14/26", "12/16/26"], "teams": ["Red"] } It gets back one answer per day and team: { "day": "12/14/26", "team": "Red", "free": ["1", "2"], "override": ["3"], "blocked": ["night1", "night2"] } free is empty, override holds an overridable routine activity (e.g resting) the program may replace, and blocked is off limits. The model picks from these lists rather than reading the calendar, so the context window stays small. 3. Write with placeProgram - The model sends all the program's sessions in one call. The tool runs two checks: 3.1 Work out how many slots the program is left to place - Each programme owes a fixed number of slots per company. The tool subtracts the slots the calendar already holds, and refuses any session that would go over what's left. // domain/agent/tools/place-program.ts const inventory = takeCalendarInventory(plan); for (const team of program.teams) { const placed = getPlacedPeriods(inventory, program, team); remaining.set(team, program.demand - placed.periods); // what it may still place placedDays.set(team, placed.days); // what the spacing rule checks against } The count is read from the calendar grid, not kept in the tool. On a retry, a fresh tool is built over the same grid, so sessions placed in earlier rounds still count against the budget and the spacing rule. 3.2 Check every rule at once - Each rule is a small function that returns a reason, or nothing if the session passes. placeProgram runs them all on every session and keeps every reason. Some examples of the rules: nonContiguousReason() - the slots run back to back with no gaps resolveDayOrNight() - all daytime or all night-time, never both tooCloseReason() - enough days after the program's last session overDayNightPoolBudget() - no more slots than the program still needs Reflection pattern: a session that fails any rule is refused, and all its reasons go back to the model. The model fixes them in one resend instead of one retry per rule. 4. Commit - Valid sessions are written to the grid. The tool replies with placed, refused (with reasons) and still owed. 5. Definition of done - A program is scheduled when it owes zero periods for every team. The model then makes no tool call, and the loop ends with a one-line summary. Anything still owed → the scheduler re-prompts with INCOMPLETE 5.3 Batches, lanes and the agent loop The harness doesn't hand every program to one agent. It splits the work into small batches, each running its own agent loop, then uses planLanes() to decide which batches can run at the same time. const { sharedLane, teamLanes } = planLanes(programs, batchSize=3); Plan Lanes - Plans two kinds of lane by comparing each team's demand profile: rhythm, session length, volume, spacing and slot pattern. We earlier discussed how the demand profile is the team’s signature – it's basically reusing this concept. Several teams with the same demand profile → the shared lane. One team, or a demand profile no other team matches → that team's team lane. The split is by matching demand profile, not by program name, all five parts must be equal. Team Red and Team Blue both do Open Mat, 4 hours a week on Fridays → one row - Open Mat [Team Red, Team Blue], in the shared lane. Team Red does Sparring 6 hours a week, Team Blue 4 → two rows - Sparring [Team Red] and Sparring [Team Blue], each in its own team lane. It then cuts each lane's programs into batches of BATCH_SIZE = 3, and returns a LanePlan (example at the end of this section). 1. Shared lane - It holds programmes that several teams need in the same amounts, such as Open Mat. It runs first, one batch at a time, because its batches write into several teams' calendars and nothing else can safely run alongside them. 2. Team lanes - Each team gets one lane, and a lane runs one agent at a time. A lane's batches run in order. Each batch of up to three programmes gets a new agent, which places them and ends before the next batch starts. Lanes run in parallel. Up to LANE_WIDTH = 4 lanes run at once, and a fifth team's lane starts when one of the first four finishes. All lanes write into one shared calendar, but each writes only its own team's columns, so parallel lanes can't collide. interface LanePlan { shared: TrainingProgram[][]; // batches → programs, same calendar grid lanes: TrainingProgram[][][]; // lanes → batches → programs, same calendar grid } { shared: [ [Open Mat] ], lanes: [ [ [Striking, Grappling, Pad Work], [Clinch Work, Footwork] ], // Team Red: 2 batches [ [Wrestling, Takedowns, Submissions], [Guard Passing] ], // Team Blue: 2 batches [ [Conditioning, Mobility] ], // Team Gold: 1 batch ], } - shared[0] = [Open Mat], the first shared batch, which is one agent. - lanes[0] = Team Red's lane, a list of 2 batches. - lanes[0][0] = [Striking, Grappling, Pad Work], Team Red's batch 1, which is one agent conversation. - lanes[0][1] = [Clinch Work, Footwork], Team Red's batch 2, the next agent. - lanes[0][0][1] = the Grappling TrainingProgram. 6. How we determine correctness The two level evaluators checks five rule families: exact coverage of day and night requirements spacing between scheduled sessions session length valid day/night pools and meal boundaries resource capacity. It reads the accumulated calendar grid after the main scheduling pass, not a summary written by the model. Write-time evaluation and whole-grid evaluation serve different purposes. Two individually acceptable blocks can touch and become one overlong block in the assembled calendar. Likewise, refusing to exceed a budget does not establish that the full budget was placed. 6.1 Whole-grid evaluation Plain code grades the calendar; the model never judges its own work. Five rules run, and only the failing programs go back, up to 3 times. The evaluator gives an objective pass or fail. The model never judges its own work. Five rules. coverage: placed equals demanded. gap: sessions are spaced far enough apart. session-length: each session is the right size. pool: day work in day slots, night work in night slots, nothing in meal times. resource: no location over capacity. Failures. Each failure names its program, team and what broke. On a retry, the scheduler re-runs only the failing programs, each with its own list of what to fix. 6.2 Write-time checks Before a scheduled session is committed, the placeProgram tool checks constraints such as: allowed session length spacing from existing sessions remaining scheduling budget resource capacity If a check fails, the proposed session is rejected before the calendar changes. The tool returns a reason that the agent can use on its next attempt. Suppose Activity A requires two-hour sessions, but the agent proposes only slot 1. That one-hour block fails the session-length check. Nothing is written. The agent can then resubmit slots 1–2. If the new proposal passes the checks, those two hours are committed. The important distinction is that the agent is correcting a rejected proposal, not undoing an already committed placement. 7. Agent's real-time progress The agents report as they work; the browser never polls. Progress status, calendar snapshots and finished workbooks stream in over SSE. A run takes minutes per phase, so the user sees agent working instead of a spinner. Graph nodes post replies onto the reply queue as they go, and the mailroom reply-loop streams them to the browser over SSE. Three reply kinds ephemeral-notice: a progress line, e.g. "Phase 1 — programs to schedule: 42". grid: a snapshot of the calendar, so that frontend gets live calendar updates of programmes’ slots. file-download: Each workbook is saved to output/ as soon as it's finished, then sent straight to the browser as a download over SSE. 8. Tracing agent trajectory pi-agent-core exposes an onPayload hook that intercepts requests before they reach the model, allowing us to trace every prompt, tool call, and final answer. Tool results are also traced but truncated. Each trace goes to three sinks at once: the console, the session's work/ folder and Azure Application Insights. We study the conversation logs to identify excessive conversation turns and tool calls, and to trace incorrect schedules back totheir root cause. const agent = createPiAgent(plan) { onPayload: (payload) => { trace(payload as LLMPayload); } } Example. Each agent writes its own conversation as .jsonl files in session's work/ folder. /sessions/{username}/{sessionId}/work/ program-iq-Wk-1.jsonl ← one file per sheet program-iq-Wk-2.jsonl ProgramSchedulerAgent-Striking-Grappling-Pad-Work.jsonl ← one per batch Each turn in a conversation is one JSON line. {"agent":"program-iq-Wk-2","turn":1,"role":"user","content":"Sheet: Wk 2. Report every activity in it."} {"agent":"program-iq-Wk-2","turn":2,"role":"assistant","tool_calls":[{"name":"read_sheet","arguments":{"sheet":"Wk 2"}}]} {"agent":"program-iq-Wk-2","turn":3,"role":"assistant","tool_calls":[{"name":"report_activities","arguments":{"activities":["2025-04-01 Team Red Striking Main Gym 4,5 training","2025-04-01 Team Blue Wrestling Mat Room 4,5 training","…"]}}]} {"agent":"program-iq-Wk-2","turn":3,"role":"tool","content":"24 activities, 24 so far."} 9. Looking forward: the potential applications and improvements Although this application was designed for training programme scheduling, the underlying engineering tactics and patterns applies to other planning problems that combine structured constraints with less explicit human preferences. Potential domains include workforce rostering, facility and equipment allocation, maintenance planning, logistics coordination, and project scheduling. These domains share similar characteristics: multiple parties compete for limited resources, some requirements must always be satisfied, and other preferences require interpretation and trade-offs. There are also several areas where the scheduler could be improved. Optimizing beyond correctness The current implementation primarily determines whether a schedule is complete and valid. A future version could score multiple valid schedules against objectives such as resource utilization, schedule compactness, adherence to user preferences, or the number of existing activities overridden. This would allow the system to distinguish between a schedule that simply passes validation and one that is operationally preferable. Targeted replanning A user may want to change one programme, unavailable date, or resource constraint after the schedule has been generated. Rather than regenerating the entire calendar, the scheduler could identify the affected placements and replan only that portion of the schedule. Supporting targeted replanning would require the system to preserve dependencies between scheduling decisions so that it can determine which programmes and resources are affected by a change. Clearer explanations for scheduling decisions The current traces make the agent's execution inspectable to developers. A future version could expose model’s reasoning and turn traces into user-facing explanations, such as why a programme was placed on a particular date or which preference could not be satisfied. These explanations should be derived from tool results and evaluator outcomes rather than relying on the model to reconstruct its reasoning after the schedule has been completed. This boundary is what makes the pattern reusable: give the agent room to reason, while keeping the resulting system deterministic, inspectable, and operationally manageable. Libraries and Resources pi-agent-core - https://github.com/earendil-works/pi/tree/main/packages/agent LangGraph - https://github.com/langchain-ai/langgraph exceljs - https://github.com/exceljs/exceljs zod - https://zod.dev/#introduction Azure Database for PostgreSQL - https://learn.microsoft.com/en-us/azure/postgresql/ Azure Container Apps - https://learn.microsoft.com/en-us/azure/container-apps/overview Microsoft Foundry - https://azure.microsoft.com/en-us/products/ai-foundry/models/Build an AI-assisted invoice approval workflow with Power Automate and AI Builder
Difficulty: Intermediate Your team receives invoice PDFs by email. Before approving them, someone needs to find the purchase order, compare the amount, and make sure the invoice has not already been registered. The next invoice starts the same sequence again. If your company already uses Power Automate and SharePoint, how can you use them to automate these checks and the handoff to a reviewer? In this step-by-step tutorial, you will build a Power Automate workflow that reads invoice attachments with AI Builder, checks them against purchase-order data in SharePoint, and sends invoices that pass validation to a person for approval. It records approved and rejected decisions, and flags validation exceptions for investigation. You will see the completed flow and its results first, then build it one step at a time. What is AI Builder? AI Builder is a Microsoft Power Platform capability that lets you use prebuilt or custom AI models in Power Automate and Power Apps. Here, you will use its prebuilt invoice-processing model to extract fields such as the invoice number, vendor name, purchase-order number, and invoice total from a PDF. You do not need to train a model for this tutorial. Power Automate uses those extracted values to run the checks and route the invoice. The example uses Northwind Components, a fictional business, and synthetic invoices. SharePoint stores the extracted values, source identifiers, and processing status. The original PDF remains in the shared mailbox. AI extracts candidate values. Rules decide whether an invoice is ready for review. A person makes the approval decision. Approval in this tutorial records a review outcome; it does not create an accounting entry or release a payment. See the finished workflow first Here is the completed flow you will build. Follow the center of the diagram from the email trigger to invoice extraction, the two SharePoint lookups, and the validation condition. The left branch creates a pending invoice, waits for a human decision, and updates the record. The right branch records an exception without requesting approval. The workflow you'll build: Extract invoice data from incoming emails, check purchase orders and duplicates, route valid invoices for human approval, and record approval outcomes or validation exceptions in SharePoint. In the diagram, Condition 1 checks the review outcome. Update item records Approved, while Update item 1 records Rejected on the same pending invoice record. The result is a list a person can act on. In the lab, one invoice was approved, another was rejected, and three submissions were held for a total mismatch, a missing purchase order, or a duplicate invoice. Five observed outcomes in InvoiceRegister. This view excludes setup and earlier test rows; those rows remain in the list. You will build this in four stages: prepare the lists, test extraction on one PDF, add the validation branches, and connect the human review. Each stage ends with a checkpoint so you can find mistakes before adding the next part. What you will build The accounts-payable team at Northwind receives PDF invoices by email. For this exercise, one invoice refers to one purchase order, and the expected total is recorded in a small SharePoint register. The team needs a visible answer to two questions: 'Can I review this invoice now?' and 'If not, what needs to be fixed?' The intended outcomes are: Situation Intended result Required fields are present and the purchase order and total match Request a human review. A required field is missing or the purchase order cannot be matched Keep the invoice in an exception state with a reason. The extracted total differs from the expected total Hold the invoice for investigation. An invoice has already been registered Prevent a second approval request for the same registered invoice. The reviewer approves or rejects Record that decision without posting or paying the invoice. Processing fails or a review expires Requires additional failure and timeout handling, described under production considerations. The first five outcomes were observed in the lab. Failure recovery and approval expiry remain extensions to implement before production use. For a short example of the broader business problem, see Microsoft's Komatsu Australia customer story. Northwind, its sample documents, and the implementation in this tutorial are independent teaching examples. Who this is for This walkthrough is for Power Automate makers who can create a cloud flow and want to move beyond extracting text from a PDF. It focuses on the point where an extracted value becomes a business decision: validating it, recording an exception, and giving a reviewer enough context to decide. In this tutorial Prepare the invoice documents and purchase-order register. Extract the invoice fields and inspect the actual model output. Validate the invoice and record its processing state. Add human review and test the normal and exception paths. Architecture and resources Service Purpose Outlook shared mailbox Receive the PDF invoice for the lab. Power Automate Orchestrate the intake, validation, and review steps. AI Builder invoice processing Extract candidate invoice values from the document. SharePoint Store the sample purchase orders, extracted invoice values, and review status. Approvals Collect a human decision after validation. The purchase-order register is the reference for this exercise. The invoice model does not decide whether a supplier should be paid or whether a purchase order is legitimate. The AI service used here is AI Builder invoice processing. You do not need a Microsoft Foundry project or a Copilot Studio agent to complete this lab. A suggested Copilot Studio extension appears after the tested walkthrough. Scope and boundaries The supplied PDFs are synthetic. They contain no real supplier, customer, bank, or payment details. Use them in a development environment. This first version covers a single-currency, one-invoice-per-PDF exercise. It compares an invoice total with a registered expected total. It does not perform line-item reconciliation, goods-receipt matching, tax validation, supplier onboarding, ERP posting, or payment execution. Matching a total alone is not sufficient evidence that a real invoice should be paid. Prerequisites and cost Prepare a development Power Platform environment with Dataverse, permission to create flows, a SharePoint site where you can create lists, and access to a shared Outlook mailbox. Use an approver account that you control for the lab. Check licensing before building. An AI Builder action makes this a premium Power Automate flow. Flow licensing and AI processing capacity are separate requirements. AI Builder runs consume available AI Builder credits or Copilot Credits; a successful sign-in does not establish that capacity is available. AI Builder trials have been discontinued. Check your environment's allocation with your administrator and review the current AI Builder licensing overview before running the sample. For this exercise, use the supplied single-page PDFs. Microsoft's invoice model requirements specify supported file formats and a 20 MB file-size limit. Keeping one invoice in each PDF also avoids mixing values from separate invoices. If processing a page range, it must cover a single invoice. See invoice processing in Power Automate. Sample files Download the five PDF attachments at the end of this article. Create the two CSV files from the copyable blocks in Steps 1 and 3 before importing the lists. File Purpose 01-valid.pdf A USD 2,400 invoice referencing the open sample purchase order. 02-total-mismatch.pdf A USD 2,550 invoice referencing the same order. 03-missing-po.pdf An invoice with no usable purchase-order reference. 04-second-valid.pdf A separate valid invoice for the rejected review path. 05-third-valid.pdf A separate valid invoice for the approved review path. purchase-orders.csv An open order and a closed order for the reference register. invoice-register.csv The setup schema for tracking invoice results. Step 1: Prepare the invoice documents and reference data Services and tools used in this step Service or tool Purpose SharePoint Prepare the purchase-order register and invoice tracking data. Sample PDFs and CSV Provide repeatable inputs with known expected values. Create the purchase-order register Save the following UTF-8 text as purchase-orders.csv : Title,VendorName,Currency,ExpectedTotal,POStatus,VendorId PO-2026-1001,CONTOSO COMPONENTS,USD,2400.00,Open,VENDOR-001 PO-2026-1002,CONTOSO COMPONENTS,USD,1800.00,Closed,VENDOR-001 Open your lab SharePoint site and select Site contents. Select New. The menu contains several resource types; choose List. In How would you like to start?, find Import from and select CSV. The blank List tile would start without the supplied columns and rows. On From CSV, select Upload file beside Upload from this device. In the file picker, choose the purchase-orders.csv file you saved above and select Open. Wait for Customize. Check that the first row became column headers and that the preview contains the two purchase orders. The controls above the headers define the SharePoint column types. Open the type selector above ExpectedTotal and select Number. A formatted amount stored as text is unsuitable for the numeric total comparison later in the flow. Keep Currency as text containing USD . Check the remaining types against this table. Use the horizontal scrollbar below the preview to reach VendorId on the right. Column Type Meaning Title Title Purchase-order reference used for the lookup. VendorName Single line of text Expected supplier name for this exercise. Currency Single line of text Currency recorded in the reference data. ExpectedTotal Number Expected invoice total, not a formatted currency string. POStatus Single line of text Open or Closed . VendorId Single line of text Stable supplier identifier from the reference register. Select Next. In the list-name field, enter InvoicePurchaseOrders. Keep Show list in site navigation selected so you can reopen the register from the site navigation. Select Create and wait for the list to open. If you are repeating the lab and this list already exists, open that existing list and verify its schema instead of creating a second reference register. The creation-dialog screenshots above replay the import settings; the following screenshot is the existing register used in the verified runs. Check the two imported rows: Title VendorName Currency ExpectedTotal POStatus VendorId PO-2026-1001 CONTOSO COMPONENTS USD 2400.00 Open VENDOR-001 PO-2026-1002 CONTOSO COMPONENTS USD 1800.00 Closed VENDOR-001 Checkpoint: the first order is open, the second is closed, and ExpectedTotal is numeric. Both belong to the same supplier. A supplier identifier is more stable than using the AI-extracted name as the identity of a business record. The purchase-order register provides the expected supplier, currency, total, and order status. Step 2: Extract the invoice fields Services and tools used in this step Service or tool Purpose Power Automate Run a small extraction check before building the full flow. AI Builder Process a sample PDF and expose its extracted values. In the current lab designer, the invoice action is labeled Process invoices. The extraction check starts with a manual trigger containing a file input named Invoice PDF. This allows the PDF and model output to be checked before email intake and business rules are added. The RW - prefix identifies the example flows in this tutorial. You can use your own flow names. Keep the action names inside each flow as shown, because the expressions reference them. Open Power Automate and confirm the development environment in the header. Select Create in the left navigation. Under Start from blank, select Instant cloud flow. An instant flow lets you supply one PDF manually before you connect email intake. In Flow name, enter RW - Invoice Extraction Check, or a name of your choice. Select Manually trigger a flow in the trigger list. The additional 'Walkthrough' suffix identifies the separate flow used to replay the creation screens. The successful extraction results below come from the original verified lab flow. Select Create. When the designer opens, select the Manually trigger a flow card. Its Parameters pane contains Add an input. Select Add an input. The designer displays six input types. Select File, the document icon. Replace the default input label with Invoice PDF. Leave the adjacent Please select file or image box unchanged. You will supply the PDF when you test the flow, not while defining the trigger. Collapse the trigger pane and select the + below Manually trigger a flow. If the card is outside the visible canvas, use Zoom view to fit first. The Add an action pane opens. Enter Process invoices in Search for an action or connector. Under AI Builder, select Process invoices. Check the connector heading because other connectors also appear in the search results. Wait for the action's Parameters pane. If prompted, sign in to the Microsoft Dataverse connection with your lab account. The bottom of the pane should show a connected connection name. Invoice file is the required input. Click inside Invoice file. Press / and select Insert dynamic content. In the dynamic-content search box, enter Invoice PDF. Select Invoice PDF contentBytes. This token contains the uploaded document. Invoice PDF name contains only its filename and cannot provide the document for extraction. The required-field warning shown while the input is empty should clear after the token is inserted. Select Save in the designer toolbar. Wait for Your flow is ready to go. We recommend you test it. Check that the canvas contains the manual trigger followed by Process invoices, and that Invoice file contains the blue dynamic-content token. Select Test in the toolbar. In Test Flow, select Manually, then select Test at the bottom of the pane. Automatically is unavailable until the flow has a previous run to reuse. In Run flow, select Import beside Invoice PDF. Choose 01-valid.pdf from the sample files and confirm that its filename appears in the field. Select Run flow and open the completed run. This step invokes AI Builder and consumes the environment's available AI capacity. The walkthrough screenshots above replay setup through file selection; the results below are from the original completed lab run. Expand Process invoices and inspect its output. The values are under responsev2 > predictionOutput > result > fields in this run. The single-page sample completed successfully in 14 seconds. These are the values observed in the lab, not values copied from the source PDF and assumed to be model output: Output Observed value Confidence Invoice ID INV-2026-1001 0.985 Invoice date 2026-10-31 0.93 Due date 2026-11-30 0.93 Purchase order PO-2026-1001 0.982 Vendor name CONTOSO COMPONENTS 0.79 Customer name Northwind Components 0.94 Invoice total 2400 0.984 Currency code USD 0.984 Checkpoint: operationStatus is Success , pageCount is 1 , and the invoice total contains both the numeric value and currencyCode . In this environment, this run reported 8 Copilot Credits and 0 AI Builder credits. That is an observed result for this one run, not a pricing estimate. Capacity and metering can differ by environment and licensing configuration. The confidence value is the model's confidence in an extracted field. It is not measured accuracy and it is not approval evidence. Notice that the vendor name was extracted correctly with a confidence of 0.79. If you use confidence in a rule, make the threshold a documented workflow setting and send lower-confidence records to review rather than discarding them. Check the successful action output before using its fields in downstream expressions. Step 3: Validate the invoice and record its state Services and tools used in this step Service or tool Purpose Outlook shared mailbox Start the workflow when an invoice email arrives. AI Builder Extract candidate values from each PDF attachment. SharePoint Look up the purchase order and keep an auditable invoice state. Power Automate expressions Apply explicit validation and duplicate rules. Create the invoice register Save the following UTF-8 text as invoice-register.csv . Create a second SharePoint list from it and name the list InvoiceRegister. The CSV contains one setup row so SharePoint can infer every column. Exclude that setup row from your result view; it is not a valid invoice or duplicate seed. Title,SourceKey,BusinessKey,VendorId,VendorName,PurchaseOrder,Currency,InvoiceTotal,Status,ExceptionReason,ApprovalId,DecisionComments,ReceivedAt,ProcessedAt SETUP-REMOVE,SETUP-REMOVE,SETUP-REMOVE,VENDOR-SETUP,SETUP VENDOR,PO-SETUP,USD,0,Setup,Remove this setup row after importing the list,,,2026-10-31T00:00:00Z,2026-10-31T00:00:00Z Return to your lab site's Site contents and start another New > List > CSV import. Upload invoice-register.csv . Confirm that the first row is used as column headers. In Customize, open the type selector above SourceKey, the second column. Select Multiple lines of text. This is where the combined Outlook message and attachment identifiers will be stored; they can exceed a single-line text field's limit. Move the preview's horizontal scrollbar to the right until ExceptionReason is visible. Open its selector and choose Multiple lines of text. Continue right to DecisionComments and choose Multiple lines of text there too. Leave ApprovalId as Single line of text. The screenshot shows the resulting types after these selections. Check InvoiceTotal and keep its type set to Number. At the right end of the preview, check ReceivedAt and ProcessedAt and select Date and time for each. In the observed import, these three types were inferred correctly; the long-text fields required a change. Review every remaining type against the table below, then select Next. Enter InvoiceRegister in the name field and select Create. If the list already exists from an earlier lab run, cancel this replay and open the existing list to check its column settings. Keep the setup row identifiable as SETUP-REMOVE and exclude it from the view you use to inspect invoice outcomes. An imported setup row is not evidence that invoice processing has run. Use these column types: Column Type Purpose Title Title Display key for the invoice. This lab uses VendorId|InvoiceId , without spaces around the separator. SourceKey Multiple lines of text Email message ID and attachment ID, useful for tracing the source. Outlook source identifiers can exceed SharePoint's 255-character single-line limit. BusinessKey Single line of text Stable duplicate key. This lab also uses VendorId|InvoiceId . VendorId Single line of text Supplier identity from the purchase-order register, not from AI. VendorName Single line of text AI-extracted supplier name for comparison and display. PurchaseOrder Single line of text AI-extracted purchase-order reference. Currency Single line of text AI-extracted currency code. InvoiceTotal Number AI-extracted numeric total. Status Single line of text Pending , Approved , Rejected , or Needs Review . ExceptionReason Multiple lines of text The first failed validation rule. ApprovalId Single line of text Approval record identifier. DecisionComments Multiple lines of text The approval response summary. ReceivedAt Date and time Email receipt time. ProcessedAt Date and time Approval completion time. The lab writes the same composite key to Title and BusinessKey for validated invoices and queries Title for duplicates. Exception rows use the extracted invoice ID as their title. A supplier name can vary in punctuation or spelling, so the lab resolves VendorId from the purchase order before building the key. Keep the key format identical when writing and querying it. Lab-verified schema note: The first live valid-invoice run produced a 333-character source value. A single-line SourceKey failed before SharePoint created the pending row because that type accepts at most 255 characters. Microsoft documents the 255-character single-line limit and the supported conversion to multiple-line text. Set this column to Multiple lines of text before you test the flow. Create the email-triggered flow Use the action names shown below before pasting expressions. Power Automate references them using internal names such as Process_invoices and Get_PO_record . If you use different names, update the references in every expression. A display label copied into a text field is not the same as selecting dynamic content or inserting an expression. Open Power Automate in the same development environment used for the extraction check. Select Create in the left navigation. Under Start from blank, select Automated cloud flow. In Build an automated cloud flow, enter RW - Invoice Email Intake and Review, or a name of your choice, in Flow name. In Choose your flow's trigger, search for shared mailbox . Select When a new email arrives in a shared mailbox (V2) under Office 365 Outlook. A blue check appears beside the selected result and Create becomes available. Select Create to open the designer, then select the trigger card to open Parameters. If you already have the completed lab flow, cancel the creation dialog and open that flow instead. This screenshot replays trigger selection; the following configuration screenshots show the original verified flow. Enter your own lab mailbox in Original Mailbox Address. Select the matching mailbox result so the address appears as a token. Open the arrow in Advanced parameters. Select the checkbox beside Folder, then Importance, Only with Attachments, Include Attachments, and Subject Filter. Reopen the menu if it closes after a selection. Fields already displayed in the pane do not appear again in this list. This menu screenshot replays the field-selection state before configuration. On a new trigger, select the required fields; do not clear an already configured trigger to follow the tutorial. Use these target values: Setting Lab value Original Mailbox Address Your lab shared mailbox address Folder Inbox Importance Any Only with Attachments Yes Include Attachments Yes Subject Filter Invoice Keep Importance set to Any. Open the arrow at the right of Only with Attachments. The menu offers No, Yes, and a custom value. Select Yes in Only with Attachments. This is a filter on incoming messages. Open the arrow at the right of Include Attachments. Select Yes in Include Attachments. This supplies attachment content for extraction; it serves a different purpose from the preceding message filter. Enter Invoice in Subject Filter. Set Folder to Inbox, then compare all six settings with the completed pane below. Select + below the trigger and search for Apply to each. Choose the Control action. The saved lab canvas labels this container For each. Click Select an output from previous steps in the loop's Parameters pane. Select the lightning icon at the right edge of that input to open dynamic content. Under When a new email arrives in a shared mailbox (V2), locate Attachments, described as 'The file attachments for the message.' Select Attachments. Confirm that the loop input contains one Attachments token. If you are inspecting an existing flow that already has the token, close the picker without inserting another copy. Select + inside the loop and search for Process invoices, as in Step 2. Choose the AI Builder action. Click Invoice file, then select its lightning icon to open dynamic content. Enter content in the picker's search box. Locate Attachments Content, described as 'Attachment content.' Attachments Content-Type is MIME metadata, and Attachments Content Id is an identifier; neither supplies the PDF bytes. Select Attachments Content. Keep Process invoices inside the existing attachment loop. The saved lab token is displayed as contentBytes and resolves to item()?['contentBytes'] , the current attachment's content. Do not add a second token when inspecting the saved configuration. Leave the manual extraction-check flow separate. Its Invoice PDF contentBytes input is useful for testing one file, but it is not the input to this email flow. Checkpoint: the canvas now has the email trigger, one attachment loop, and Process invoices inside that loop. For the supplied tests, attach one PDF to each email. The trigger requires an attachment but does not itself guarantee that every attachment is a valid PDF invoice. Look up the purchase order Inside the same loop, select + after Process invoices. In Add an action, search for Get items . Under SharePoint, select Get items (plural). This action supports a filter query; Get item requires an item ID that this lookup does not yet have. Click the editable action title at the top of its pane and name it Get PO record. The field is labeled Card title for accessibility. Use this exact name before inserting expressions that reference Get_PO_record . Open Site Address and select your lab site. The example uses RW Lab. Open List Name. Type Invoice to narrow the available list names. Select InvoicePurchaseOrders from the results. Do not select Use 'Invoice' as a custom value; the search text is not the list name. Confirm that the full selected name appears in the field. Open the Advanced parameters arrow. Select the checkbox beside Filter Query. Reopen the menu if needed and select Top Count. Click outside the menu to return to the action fields, then enter 1 in Top Count. The next screenshot shows the completed lookup configuration: Click Filter Query, then select the fx icon at its right edge to open the expression editor. Insert the following expression there. Do not paste it as a literal filter string: concat('Title eq ''', body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['purchaseOrder']?['valueText'], '''') Select Add when inserting a new expression, or Update when editing an existing expression. Back in Filter Query, confirm that the value is an expression token. The screenshot shows the saved expression open for inspection. For 01-valid.pdf , the expression produces Title eq 'PO-2026-1001' . The outer concat creates the OData filter; the quotes around the PO reference are part of that filter. This lab uses the supplied PO references. A production implementation must handle apostrophes and other unexpected input safely when constructing OData filters. Look for an existing invoice Add another SharePoint Get items immediately after Get PO record, still inside the attachment loop. Rename it Get duplicate invoices. Select the same lab site and InvoiceRegister as the list. Expose Filter Query and Top Count. Set Top Count to 1 because this lookup only needs to establish whether a matching invoice exists. Click Filter Query, then select its fx icon. If the field already contains a purple expression token, click that token to reopen its editor. Insert the following expression into the expression editor: concat( 'Title eq ''', coalesce( first(union(body('Get_PO_record')?['value'], createArray(json('{}'))))?['VendorId'], 'NO-PO' ), '|', body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['invoiceId']?['valueText'], '''' ) Select Add for a new expression or Update when replacing an existing token. Confirm that Filter Query contains the purple concat(...) token and Top Count remains 1 . The screenshot shows the saved expression reopened for inspection; the code block preserves the same expression with line breaks for copying. union(array, createArray(json('{}'))) ensures that first() still receives one object when the PO query returns no rows. Without that guard, a missing purchase order can fail the flow before it reaches the exception branch. For the approved sample invoice, the resulting filter is Title eq 'VENDOR-001|INV-2026-1005' . The NO-PO fallback lets the duplicate lookup complete when the PO is missing; it does not make that invoice valid. The next condition rejects the unmatched PO. Add the validation gate After Get duplicate invoices, select + inside the attachment loop. Search for Condition , select the Built-in filter, then choose Condition under Control. Rename it Invoice is valid and unique. Click the left Choose a value field and select the fx icon. Insert the entire and(...) expression below into the expression editor. The formatted code block is the copyable source; the screenshot that follows shows the beginning of the saved expression in the editor. and( equals(length(body('Get_PO_record')?['value']), 1), equals(length(body('Get_duplicate_invoices')?['value']), 0), equals(coalesce(first(union(body('Get_PO_record')?['value'], createArray(json('{}'))))?['field_4'], ''), 'Open'), equals( toUpper(trim(coalesce(first(union(body('Get_PO_record')?['value'], createArray(json('{}'))))?['field_1'], ''))), toUpper(trim(coalesce(body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['vendorName']?['valueText'], ''))) ), equals( toUpper(trim(coalesce(first(union(body('Get_PO_record')?['value'], createArray(json('{}'))))?['field_2'], ''))), toUpper(trim(coalesce(body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['invoiceTotal']?['currencyCode'], ''))) ), equals( float(coalesce(first(union(body('Get_PO_record')?['value'], createArray(json('{}'))))?['field_3'], 0)), float(coalesce(body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['invoiceTotal']?['valueNumber'], -1)) ), not(empty(body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['invoiceId']?['valueText'])), greaterOrEquals( float(coalesce(body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['vendorName']?['confidence'], 0)), 0.75 ) ) Select Add for a new expression, or Update if editing an existing token. The left field should now contain a purple and(...) token. Keep the middle operator set to is equal to. Click the right Choose a value field and open its fx expression editor. Enter true without quotation marks. The lab compares the left expression's Boolean result with Boolean true , rather than the text string 'true' . Select Add or Update to insert the right-side expression. Confirm that both fields display purple expression tokens. The completed comparison is the row containing the two expression tokens. The additional empty row visible in this designer view is not another validation rule to populate. Important: field_1 through field_4 are the internal SharePoint names observed in this lab for vendor, currency, expected total, and PO status. Your internal names can differ, especially when columns are renamed after creation. Use dynamic content or inspect a successful Get items output and replace these names with your own. Do not copy the field_* names blindly. This gate requires one returned PO, no registered duplicate, an open PO, matching normalized vendor and currency, an exact numeric total, an invoice ID, and vendor confidence of at least 0.75 . The threshold is a lab choice, not a Microsoft default or a guarantee of accuracy. Because the PO query has Top Count = 1, it cannot detect duplicate PO references in the source list; keep the sample references unique and enforce uniqueness in a production register. Create the pending record In the validation condition's True branch, add SharePoint Create item. Rename it Create pending invoice. Select the lab site and InvoiceRegister. Open the Advanced parameters arrow. Select Title, VendorName, PurchaseOrder, Currency, InvoiceTotal, Status, SourceKey, BusinessKey, VendorId, and ReceivedAt, one checkbox at a time. Reopen the menu when needed, then click outside it. Use the mapping below to fill the exposed fields: AI Builder supplies extracted values, while the matched PO supplies VendorId . The same InvoiceRegister column names are available to the exception and update actions later. For the pending record, leave ExceptionReason, ApprovalId, DecisionComments, and ProcessedAt unused. Enter Pending as the Status text. Leave the approval result fields empty until the reviewer responds. Field Value Title and BusinessKey PO VendorId , | , and extracted invoice ID, with no separator spaces SourceKey Email message ID, | , and attachment ID VendorId VendorId from the matched PO VendorName vendorName.valueText PurchaseOrder purchaseOrder.valueText Currency invoiceTotal.currencyCode InvoiceTotal invoiceTotal.valueNumber Status Pending ReceivedAt Trigger receivedDateTime Click Title and select its fx icon. In the Function editor, paste the following expression. If the field already contains a purple expression token, click that token to inspect it. concat( first(body('Get_PO_record')?['value'])?['VendorId'], '|', body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['invoiceId']?['valueText'] ) Select Add, or Update when editing an existing expression. Confirm that Title contains a purple expression token. Scroll to BusinessKey, open its fx editor, paste the same expression, and select Add. The two fields must use the same separator without spaces around it. Here first() is inside the validated branch: the condition has already confirmed that a PO was returned. Keep the empty-array guard in the earlier duplicate lookup and validation expression. Click SourceKey, open its fx editor, and paste the following expression. It joins the email message ID and the current attachment ID: concat(triggerOutputs()?['body/id'], '|', item()?['id']) Select Add or Update to keep the expression in SourceKey. This is a source-tracing value; the duplicate lookup uses the business key instead. For VendorId, open the expression editor and insert first(body('Get_PO_record')?['value'])?['VendorId'] . Click ReceivedAt, open dynamic content with its lightning icon, and select Received Time under the email trigger. This corresponds to triggerOutputs()?['body/receivedDateTime'] in the lab. Scroll down in the same Parameters pane to verify the supplier identity and receipt time. These fields belong to Create pending invoice, not a second Create item action. When a named AI Builder token is difficult to distinguish, use its verified output path. For example, VendorName uses: body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['vendorName']?['valueText'] Use the same prefix through ['fields'] for the purchaseOrder , invoiceTotal.currencyCode , and invoiceTotal.valueNumber paths in the table. Preserve the exact casing shown by your extraction run. Create the exception record In the validation condition's False branch, add another SharePoint Create item. Rename it Create exception record and select the lab site and InvoiceRegister. Set Title to the extracted invoice ID and Status to the literal text Needs Review . Map VendorName, PurchaseOrder, Currency, InvoiceTotal, and ReceivedAt from the same sources used above. Expose ExceptionReason and insert the expression below. This branch ends after the exception is recorded; do not add an approval action to it. The lab records one of: Duplicate business key , Missing or unmatched purchase order , Purchase order is not open , Vendor name mismatch , Currency mismatch , Invoice total mismatch , Missing invoice ID , Vendor confidence below 0.75 , or Validation failed . Set its Title to the extracted invoice ID and ReceivedAt to the trigger's received time. Map vendor, PO, currency, and total as above. The lab leaves source key, business key, supplier ID, approval metadata, and processed time empty on exception rows. For production traceability, extend this branch to retain the source identifiers too. Click ExceptionReason and open its fx editor. Paste this expression, replacing the internal PO column names if needed: if(greater(length(body('Get_duplicate_invoices')?['value']),0),'Duplicate business key', if(not(equals(length(body('Get_PO_record')?['value']),1)),'Missing or unmatched purchase order', if(not(equals(coalesce(first(union(body('Get_PO_record')?['value'],createArray(json('{}'))))?['field_4'],''),'Open')),'Purchase order is not open', if(not(equals(toUpper(trim(coalesce(first(union(body('Get_PO_record')?['value'],createArray(json('{}'))))?['field_1'],''))),toUpper(trim(coalesce(body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['vendorName']?['valueText'],''))))),'Vendor name mismatch', if(not(equals(toUpper(trim(coalesce(first(union(body('Get_PO_record')?['value'],createArray(json('{}'))))?['field_2'],''))),toUpper(trim(coalesce(body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['invoiceTotal']?['currencyCode'],''))))),'Currency mismatch', if(not(equals(float(coalesce(first(union(body('Get_PO_record')?['value'],createArray(json('{}'))))?['field_3'],0)),float(coalesce(body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['invoiceTotal']?['valueNumber'],-1)))),'Invoice total mismatch', if(empty(body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['invoiceId']?['valueText']),'Missing invoice ID', if(less(float(coalesce(body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['vendorName']?['confidence'],0)),0.75),'Vendor confidence below 0.75','Validation failed')))))))) Scroll inside the editor to check the complete expression, then select Add or Update. The screenshot shows its beginning; the code block above contains the full expression. Confirm that Status is Needs Review , ExceptionReason contains the expression token, and ReceivedAt contains the email receipt time. Keep this branch separate from Review invoice. The flow configuration was saved successfully and Power Automate reported Your flow is ready to go. That message verifies the designer configuration, not the business outcome. The test matrix in Step 4 supplies the outcome evidence. Checkpoint: the saved flow contains the shared-mailbox trigger, one attachment loop, AI Builder extraction, guarded PO and duplicate lookups, a validation condition, a Pending approval branch, and a reason-specific Needs Review branch. Power Automate must report that the flow is ready before you send a test message. Do not treat that designer message as proof that any invoice outcome passed. Compare your branch layout with the completed flow shown at the start of the article. At this point the validation and record-creation actions are in place; Step 4 adds the approval and its two final updates to the validated branch. Step 4: Add human review and test the workflow Services and tools used in this step Service or tool Purpose Approvals Collect a controlled human decision. SharePoint Update the same pending record with the final review state. Synthetic invoice set Exercise normal, duplicate, and exception paths. Configure the approval In the validation condition's True branch, select + after Create pending invoice. In Add an action, select the All filter if Built-in is still selected. Search for Start and wait for an approval , then choose that action under Standard approvals. Rename the card Review invoice. Open the Approval type dropdown. Locate Approve/Reject - First to respond. Select Approve/Reject - First to respond. Confirm that this exact choice remains in the field after the menu closes. Click the people-search box under Assigned to. Enter at least two characters of the name or email address of an account you control. Wait for the directory result. Select an approver account that you control from the results. Confirm that it appears as a selected account token. Email addresses are hidden in the screenshots for privacy. The screenshot inspects an existing selection, so do not add the same reviewer twice. Click Title, then select fx to open the Function editor. Build a title that includes the invoice ID, vendor, currency, and amount: Review invoice <invoice ID> from <vendor> for <currency> <amount> The angle-bracket values above are placeholders, not literal text to leave in the approval. To reproduce the saved lab title, insert this expression into Title: concat( 'Review invoice ', body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['invoiceId']?['valueText'], ' from ', body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['vendorName']?['valueText'], ' for ', body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['invoiceTotal']?['currencyCode'], ' ', string(body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['invoiceTotal']?['valueNumber']) ) Select Add, or Update when editing an existing title. Confirm that Title contains the purple expression token. The screenshot shows the beginning of the saved expression; use the complete code block above. Click Details, then select fx. Include the invoice ID, vendor, purchase order, amount, the checks that passed, and this boundary statement: Approval records a review decision only. It does not post or pay the invoice. Use the same extracted fields as the title. The saved lab separates the sections with decodeUriComponent('%0A%0A') , which inserts a blank line. Here is its Details expression, formatted for copying: concat( '**Invoice ID:** ', body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['invoiceId']?['valueText'], decodeUriComponent('%0A%0A'), '**Vendor:** ', body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['vendorName']?['valueText'], decodeUriComponent('%0A%0A'), '**Purchase order:** ', body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['purchaseOrder']?['valueText'], decodeUriComponent('%0A%0A'), '**Invoice total:** ', body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['invoiceTotal']?['currencyCode'], ' ', string(body('Process_invoices')?['responsev2']?['predictionOutput']?['result']?['fields']?['invoiceTotal']?['valueNumber']), decodeUriComponent('%0A%0A'), '**Validation:** Open PO matched; vendor, currency, and total matched; no registered duplicate.', decodeUriComponent('%0A%0A'), 'Approval records a review decision only. It does not post or pay the invoice.' ) Select Add or Update to insert the Details expression. Scroll within the editor when checking it; the full expression is longer than the visible editor area. Leave Item link and Item link description empty for this lab. Keep Enable notifications and Enable reassignment set to Yes, matching the inspected configuration. The lab includes invoice context in the approval but does not attach the source PDF or provide a source-document link. A production reviewer needs an authorized route to the original invoice as well. Create the pending record before requesting a review, then update that same record after the decision. Save the review decision to the same record Under Review invoice, add a Condition. The saved lab names it Condition 1. Select Outcome from Review invoice as the left value. Choose is equal to and enter Approve on the right. The approval output is Approve ; the SharePoint status you will store is Approved . In this condition's True branch, add SharePoint Update item. Select your lab site and InvoiceRegister. Click Id, then select the lightning icon to open dynamic content. Locate the Create pending invoice section. The picker also offers IDs from the two earlier lookups, so check the action heading before choosing a value. Select ID under Create pending invoice. Confirm that Id contains one token. If inspecting the saved flow, close the picker without inserting a duplicate token. Open Advanced parameters and expose Status, ApprovalId, DecisionComments, and ProcessedAt. Enter Approved as literal text in Status. Click ApprovalId and select the lightning icon. Under Review invoice, locate Approval ID. Select Approval ID for ApprovalId. Click DecisionComments, open its dynamic-content picker, and select Response summary under Review invoice. Click ProcessedAt, open its dynamic-content picker, and select Completion date under Review invoice. Compare all five fields with this table: Update item field Value or dynamic content Verified expression Id ID from Create pending invoice outputs('Create_pending_invoice')?['body/ID'] Status Literal text Approved No expression needed. ApprovalId Approval ID from Review invoice outputs('Review_invoice')?['body/name'] DecisionComments Response summary from Review invoice outputs('Review_invoice')?['body/responseSummary'] ProcessedAt Completion date from Review invoice outputs('Review_invoice')?['body/completionDate'] In the outcome condition's False branch, add another Update item. The saved lab names this card Update item 1. Use the same site, list, pending item ID, and approval metadata. Set Status to Rejected instead of Approved . Save the flow and check for designer errors before sending a test invoice. Keep both update actions after the approval, inside the validated branch of the outer condition. Updating the ID returned by Create pending invoice matters. A second lookup can find the wrong row when retries or duplicate submissions are being investigated. The verified Approved branch updates the existing pending invoice with the review outcome and approval metadata. The pending approval request created by the verified email-triggered run. Configuration checkpoint: the approval uses Approve/Reject - First to respond, is assigned to a controlled lab account, includes the invoice and validation context, and is followed by separate Approved and Rejected updates that target the ID returned by Create pending invoice. Run the test matrix Test one path at a time so the email, flow run, approval, and list row can be matched without guessing. Send each synthetic PDF to your shared mailbox with Invoice in the subject. Use one attachment per message for the clearest run history. Send 05-third-valid.pdf with a subject such as Invoice lab - approved - INV-2026-1005 . Open the flow's run history and select the run for that email. Check that extraction and both SharePoint lookups complete, and that Invoice is valid and unique selects the True branch. Open InvoiceRegister while the approval is waiting. Find VENDOR-001|INV-2026-1005 and confirm that its status is Pending . Open the approval as the assigned reviewer. Compare the supplier, PO, currency, and amount with the sample. Select Approve and complete the response. Return to the run and the same SharePoint row. Confirm that Update item completes, the row becomes Approved , and the approval ID, response summary, and completion time are recorded. Send that same PDF again in a new email. Confirm that the duplicate lookup finds the existing composite key, the validation condition selects False, and Review invoice is skipped. The new exception row should say Needs Review with Duplicate business key . Send 04-second-valid.pdf in a separate email. Reject its approval and verify that Update item 1 records Rejected on its pending row. Send 02-total-mismatch.pdf . Confirm Needs Review and Invoice total mismatch , with no approval request. Send 03-missing-po.pdf . Confirm Needs Review and Missing or unmatched purchase order , with no approval request. For each test, compare the business result with the table below as well as the run status. A flow can succeed while taking an unintended branch; a green run alone is not the acceptance criterion. These are the recorded results from the lab: Test Input Expected record Evidence status Valid and approved 05-third-valid.pdf , then Approve Pending to Approved Verified 2026-11-01 11:50 KST; run 08584081058602629821308106869CU15 succeeded and saved the final state and approval metadata Duplicate replay Send the approved 05-third-valid.pdf again Needs Review , Duplicate business key Verified 2026-11-01 11:58 KST; run 08584081049678939975499423226CU05 succeeded, and the approval action was skipped Total mismatch 02-total-mismatch.pdf Needs Review , Invoice total mismatch Observed 2026-11-01 09:41 KST, run 08584081131932657744975275828CU19 , succeeded and created the expected reason-specific row Missing PO 03-missing-po.pdf Needs Review , Missing or unmatched purchase order Observed 2026-11-01 09:41 KST, run 08584081131932657743975275828CU27 , succeeded and created the expected reason-specific row Valid and rejected 04-second-valid.pdf , then Reject Pending to Rejected Verified 2026-11-01 11:51 KST; run 08584081056621189571001129958CU31 succeeded and saved the final state and approval metadata Review expires Valid invoice with a short test timeout and no response Visible unresolved or timed-out state owned by a follow-up process Not implemented in this lab version Extraction fails Unsupported or unreadable input Visible exception owned by a failure-handling branch Not implemented in this lab version Do not treat the final two rows as passing tests. They expose production controls that still need to be added. A production flow should place the main actions in a Try scope, use a Catch scope configured with Run after, and update the register to a visible failure state before terminating. Approval expiry needs its own timeout and follow-up branch. Checkpoint: all five business outcomes were observed in successful email-triggered runs and in their final SharePoint records. The corrected duplicate run evaluated the validation condition to false , skipped Create pending invoice and Review invoice, and created the exception record. Compare your five outcomes with the InvoiceRegister screenshot at the start of the article. Filter your view to the records from these tests. Keep earlier setup and failed-test rows separate so that an old record does not look like the result of the run you are checking. Where Copilot Studio fits Optional extension, not implemented or tested in this lab. The email flow already starts automatically. Copilot Studio becomes useful when a person wants to ask questions about its work: 'Which invoices need review?' or 'Why was INV-2026-1002 held?' My suggested first extension is an invoice review assistant with a small, read-only tool that queries InvoiceRegister. Copilot Studio can call an agent flow as a tool to retrieve data. For this design, return the matching row's ID, status, exception reason, amount, and a link to the record. Have the agent explain those returned facts, identify missing data, and link the user to the record. It should not invent a reason or treat a conversational reply as an approval. Keep two information sources distinct: User question Suggested source Agent's role 'What is the status of this invoice?' A query of InvoiceRegister through a tool Report the current stored status and link to the matching record. 'Why does this invoice need review?' The row's ExceptionReason and recorded values Explain the recorded failure; ask the user to inspect the invoice or PO when the evidence is incomplete. 'What is our process for resolving a mismatch?' An approved procedure document in SharePoint Explain the procedure with source references, separately from the invoice's status. SharePoint documents can provide knowledge for generative answers. That is useful for procedures; an explicit list query is the design proposed here for current transaction status. Configure and test access separately for knowledge and tools. A flow that uses a maker's connection must not become a route to invoices the caller is not allowed to see. For the lookup tool, use a separate flow with When an agent calls the flow and Respond to the agent, in a solution in the same environment as the agent. Microsoft requires a synchronous response within the 100-second action limit. Keep the human approval wait in the existing email flow; a lookup should return the current status promptly. See the agent-flow requirements and creating an agent flow tool. Before extending this to updates or reprocessing, define a separate authorized action, confirmation behavior, and audit record. The existing validation rules, duplicate checks, and human approval remain responsible for changing an invoice's processing state. This extension is a possible next lab, not a capability demonstrated by the screenshots above. Troubleshooting The Dataverse or AI Builder connection times out during sign-in Wait for the Microsoft account picker to finish loading and complete the sign-in in the same browser profile. If the designer still shows a failed connection, reopen the action's connection picker and create or select the connection again. Do not rebuild the flow until the action actually shows a connected account. The invoice action receives the filename instead of the file Choose the attachment's file content, not its name. In the manual probe, the correct value was Invoice PDF contentBytes . In the email flow, use the current attachment content inside Apply to each. A resubmitted email run fails before extraction Replay is not always equivalent to a fresh file trigger. In this lab, both Resubmit and Automatically > With a recently used trigger contained PDF base64 input but failed at Process invoices with InvalidPredictionInput: Unable to identify the mimetype input . Fresh emails containing the same PDFs passed extraction. The cause of the replay failure was not established. A fresh synthetic email can help distinguish a replay-specific failure from a document extraction problem. A missing PO causes first() to fail Do not call first(body('Get_PO_record')?['value']) on an array that may be empty. The expressions in this tutorial union the result with createArray(json('{}')) before calling first() . Currency or total is blank In the observed AI Builder output, currency and amount are both children of invoiceTotal . Use invoiceTotal.currencyCode and invoiceTotal.valueNumber . Inspect your run output instead of assuming a schema from an older screenshot. The vendor and PO fields in this run use the case-sensitive paths vendorName.valueText and purchaseOrder.valueText . Incorrect casing or a valueString property produced blank SharePoint values during testing. A duplicate invoice creates another approval request Compare the exact stored key with the lookup expression. In the lab, VENDOR-001|INV-2026-1005 was stored without spaces, while an earlier lookup inserted spaces around the separator. After using | consistently, resending the same PDF created Needs Review / Duplicate business key and skipped approval. Existing test rows were preserved; the unintended duplicate request was rejected. The condition never matches even though the list looks correct Check SharePoint's internal column names in the Get items output. Display names and internal names are not always the same. Also confirm that ExpectedTotal is a Number column and that the PO status is exactly Open after trimming. The approval succeeds but the wrong row is updated Use the item ID returned by Create pending invoice. Do not search by vendor name or invoice number after the approval completes. Create item rejects SourceKey as longer than 255 characters Change the SourceKey column from Single line of text to Multiple lines of text. In this lab, the concatenated Outlook message and attachment identifiers were 333 characters, so the SharePoint connector rejected the single-line field before creating the pending record. After changing the column type, refresh the SharePoint action's list schema in the designer before retesting. Production considerations Before using this pattern with real invoices, replace the sample register with an authoritative source, define supplier identity and duplicate rules, and decide who owns unresolved invoices. Add a unique constraint or another concurrency-safe idempotency control; the lab's lookup-then-create pattern can race when two copies arrive at the same time. Add explicit retention, access, data-loss prevention, retry, timeout, and monitoring policies. Decide how corrections are audited and how a reviewer opens the source document from the approval. Validate taxes, line items, goods receipt, and supplier bank-detail changes through the systems and controls that own those facts. Approval and payment remain separate business controls. The lab's extracted values and confidence scores do not replace those controls, and this flow must not be connected directly to payment execution without the organization's accounting and segregation-of-duties design. Clean up When you have finished the lab: Turn off both flows you created in this tutorial. If you used the example names, these are RW - Invoice Email Intake and Review and RW - Invoice Extraction Check. Remove the synthetic messages from the lab mailbox if your test-data policy requires it. Delete or archive the InvoiceRegister test rows and sample approvals according to your lab policy. Delete the InvoicePurchaseOrders and InvoiceRegister lists only if they were created solely for this exercise. Remove the lab connections only when no other flow uses them. These steps remove test resources. They do not reverse any real accounting action because this tutorial never posts or pays an invoice.From Writing Scripts to Running a Newsroom: A 24-Hour News Station with Microsoft Copilot Harness
Picture an evening commute. You open a page on your phone and hear two anchors delivering a coherent news bulletin. Headlines and timestamps move across the bottom of the screen. Tap a headline and the audio jumps to that story. Tap its source and the original report opens separately. Switch to English and you hear the same underlying facts—not an unrelated second news selection. That is the idea behind Meridian 24: a half-hourly China and world news podcast, with Chinese and English audio and a single HTML, JavaScript and CSS3 page. At first, it sounds like a simple recipe: search for news, ask a model to write a script, and turn the script into speech. Once we started building, the real challenge became clear. Getting AI to speak was relatively easy. Keeping a small newsroom working responsibly was not. 1. Why Introduce Microsoft Copilot Harness? The first script needed a better process, not prettier sentences Give a model a pile of headlines and it can produce a pile of summaries. The stories may not connect. Some search results contain too little detail, inviting the model to fill space with commentary. One agency may dominate simply because its reporting is easier to retrieve. Another instruction to “sound more professional” does not solve that problem. We needed an editorial method: collect public reporting, consolidate related events, identify missing details, research those gaps, prepare evidence-backed facts, and only then write a coherent two-anchor programme. A model can be a capable editor. A newsroom still needs a workbench, a filing system, task assignments and handovers. Microsoft Copilot Harness supplies a managed execution foundation for that work. Microsoft Foundry operates the agent loop and sandbox, coordinates model and tool steps, and supports native subagents, file operations and reusable skills, among other capabilities.[1][2] Developers can spend less time constructing the newsroom's office equipment and more time teaching it how to do useful work. A 22:30 production job should not lose its progress A bulletin involves retrieval, editorial requests, speech synthesis and audio encoding. If the service stops after ten speech segments have already been synthesized, starting everything again wastes time and money. Two capabilities matter here, and they should not be confused. Microsoft Copilot Harness operates the managed editorial runtime. Long-running resilience for Hosted Agents provides a foundation for restarting interrupted work. The application still decides what progress to save, how to resume and how to prevent duplicate publication.[1] We therefore did not put the entire station into one prompt. Nor did we interpret “managed” as “nothing left to engineer.” 2. How Do We Build the Application with Microsoft Copilot Harness? A managed editor, with a separate audio production room The existing Hosted service already knew how to call WebIQ, invoke speech synthesis, run FFmpeg and write to Blob. Instead of replacing it, we kept those deterministic responsibilities there and created a separate Prompt Agent using Microsoft Copilot Harness for research and editing. Figure 1: The purple boundary contains managed editorial execution. WebIQ and audio production run in external Hosted services. Important results are stored in Blob, not entrusted to a permanently available sandbox. Microsoft Copilot Harness owns the editorial execution: researching, organizing, delegating and drafting. Hosted code owns external API execution, validation, synthesis and publication. That boundary is also a practical preview requirement. You cannot switch an existing agent to a different harness during the initial public preview. We created a new editor and retained the original Hosted Agent's type and responsibilities.[2] Here is an abbreviated excerpt from the project's definition, omitting the full instructions and custom news tools: kind: prompt name: newsradio24-editor model: gpt-6.1-sol harness: type: microsoft_copilot_preview tools: - type: microsoft_copilot_toolset_preview defaultConfig: enabled: false configs: - name: filesystem_read enabled: true - name: filesystem_write enabled: true - name: shell enabled: true - name: subagents enabled: true gpt-6.1-sol is the model deployment name used in this project, not a promise that it is available in every project. Use a supported model already deployed in your own project region. See the full newsroom.yaml, and check official documentation for current preview fields and supported tools. Subagents are backstage editors, not extra presenters The audience still hears just two anchors. Behind the scenes, the work has three logical roles: Subtask role Input Output China research China reporting and evidence IDs Consolidated events, facts and research gaps World research International reporting and agency coverage Topic order, citations and expansion needs Fact verification Expanded evidence, briefs or scripts Citation checks, conflicts and bilingual consistency issues The parent editor delegates bounded tasks and merges their results. This project allows at most three subtasks per editorial request. These are not three separately deployed, permanently running services, nor an identical fixed trio instantiated in every phase. The sandbox acts as an editor's workbench: shell and file tools help organize JSON and inspect evidence IDs and topic order. Each conversation has a separate workspace, but that workspace is not a durable archive. Important outputs belong in durable storage.[2] The station currently describes its method through version-controlled instructions and request-level procedures. It has not published those procedures as separate Foundry Skills. Reusable skills are a supported extension opportunity, not something we should claim this implementation already uses. Let tools bring evidence, not credentials The editor requests discovery and expansion through collect_news and expand_news. Both accept an empty object. The server binds the news window and context, and the WebIQ key remains in the Hosted service. When an external function call arrives, Hosted code executes the search and returns a function_call_output with the matching call_id in the same conversation. The editor can continue without receiving credentials. This excerpt shows only the editorial request entry point—not the full tool-execution loop. payload carries the phase's procedure, evidence and output contract: import json import os from azure.ai.projects.aio import AIProjectClient from azure.identity.aio import DefaultAzureCredential async def request_editor(payload): async with ( DefaultAzureCredential() as credential, AIProjectClient( endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"], credential=credential, allow_preview=True, ) as project, project.get_openai_client( agent_name="newsradio24-editor", timeout=900, max_retries=2, ) as client, ): conversation = await client.conversations.create() return await client.responses.create( conversation=conversation.id, input=json.dumps(payload, ensure_ascii=False), ) The project uses azure-ai-projects 2.9.0. Read your own project endpoint from a server-side environment. Never put keys, real resource-group names or complete environment files into an article, browser code or sandbox. The complete adapter is in harness.py. 3. Where does it offer an advantage over a typical self-built agent harness? As a technical evangelist, I prefer describing the responsibility it removes rather than implying that nobody else can implement these capabilities. Open-source frameworks and custom systems can also support tools, delegation, state management and sandboxes. The distinction is that Microsoft Copilot Harness delegates part of that execution infrastructure to Foundry and connects it with the platform's agent definitions, identity and tool configuration. Question Typical self-built approach Microsoft Copilot Harness Who maintains the internal model/tool loop? Your team builds it or operates a framework runtime Foundry operates that runtime How are files, commands and subtasks integrated? Your team assembles execution and delegation mechanisms Use supported native capabilities How are agent definitions delivered? Establish your own configuration and release conventions Version declarative definitions alongside application code How is tool access governed? Depends on your framework and integrations Connect with Foundry roles, agent identity and connections How much runtime control is available? Greater control, with greater maintenance responsibility Less runtime operation, within supported capabilities and preview limits For a news station, that trade-off leaves more engineering time for evidence quality, editorial coherence and listening experience. It does not make reporting automatically true, remove permission configuration or support arbitrary models and tools. If you need to control the framework, dependencies, process model or specialized middleware, a Hosted Agent remains a sensible choice.[1][2] Costs do not disappear either. Inference, speech, retrieval, storage, traffic and runtime usage require a budget. Consult current regional service pricing and your agreement. The advantage is not “all engineering done for you.” It is a clearer opportunity to spend engineering effort on what makes your application different. 4. What Techniques Matter Most When Building a 24-Hour News Station? Turn reporting into facts before turning facts into sound Our production flow does not send raw search results directly to speech synthesis. It produces explicit intermediate deliverables: Figure 2: Each blue node has an inspectable data shape. Research gaps trigger an expansion loop. Editorial execution and audio production have separate validation gates. WebIQ searches public reporting from Xinhua, AP, AFP and Bloomberg. We check sources and dates. Homepages, advisories and headline-only results are discovery leads, not sufficient factual evidence. Related reports become topics. Missing details become targeted searches. If expansion still does not find enough evidence, shorten or omit the story rather than fill the silence with opinions. A section without sufficient facts should prevent publication. “Trending” also needs an honest definition: this implementation selects using relevance, recency and cross-source coverage. It does not possess a measured audience-popularity leaderboard. Agency balance must come from evidence, not relabeling Early programmes leaned toward Xinhua because more usable reporting was available. The answer was not to label those stories “AP.” We reserved candidate space for underrepresented agencies and added bounded expansion searches. Final selection keeps at most two China topics and four world topics. When at least two reliable non-Xinhua topics are selected, Xinhua is capped at half the programme. Sparse evidence may still produce an uneven mix. The page reports actual sources rather than inventing four-agency coverage. Neutrality is not achieved by asking the male and female anchors to exchange opposing opinions. They complement each other with cited facts and background, finish one story before moving on, and use transitions without manufacturing debate. Two languages should share one factual foundation If Chinese and English select stories independently, they can become different programmes. We prepare an ordered factual brief, draft the Chinese body, and adapt the English version from the same brief and Chinese content. Deterministic code adds introductions, AI-voice disclosure, greetings and polite sign-offs rather than hoping the model remembers every time. The Chinese anchors use MAI Voice 2.1's Wei and Mei; English uses Grant and Harper. The station has no sports section or third anchor.[3] “The voice is too slow” turned out to be a timing problem too Wei's Chinese delivery needed more pace. Instead of accelerating the entire programme in the browser, we applied pitch-preserving 1.25x tempo to Wei's synthesized tracks on the server. Mei and both English anchors remain at 1.0x. That decision requires measuring the processed tracks again before calculating story starts, assembling audio and encoding it. Otherwise, a “jump to story two” button may land in the wrong sentence. WAVs are working files. The final MP4 contains real AAC audio; it is not an MP3 with a different extension. The complete bulletin and every section must remain within 1,200 seconds, measured from actual audio. Oversized output is rejected, not cut in the middle of a sentence. Inspect the handover sheet, not the AI's claim of completion The station stores records for collection, topic organization, expansion, final briefs, Chinese scripts and English scripts. All four editorial phases must actually execute native subtasks and shell operations. A response saying “I checked it” is not sufficient. Here is an abbreviated illustration of two gates. Production checks runtime records per phase and duration after audio production: observed = harness.native_tools(response_outputs) if not {"task", "shell"} <= observed: raise RuntimeError("Missing native editorial execution") audio.check_duration(chapters, total_seconds) Native subtasks and shell operations run through the platform. They must not be mistaken for unresolved external functions that Hosted code still needs to execute. The implementation uses actual response events and call_id pairing, not the model's self-assessment. In one completed end-to-end run, Chinese audio measured 268.1 seconds and English 271.0 seconds. Verification covered all six phase records and story starts derived from actual WAVs. Those are results for one particular edition—not guarantees of future latency, quality or availability. Passing these gates establishes structural, citation and execution conditions. It is not proof of truth or semantic neutrality. Human editorial review still matters. Put recovery into the data and publication into a handover Completed evidence, scripts, WAVs and status live in private Blob storage. A resumed task reads checkpoints and reuses synthesized tracks rather than repeating every completed action. Only after Chinese and English are complete does a publication lease protect the catalogue update. One write reveals both outputs. Scheduled editions and manual extras have separate catalogues, so a manual success cannot be passed off as proof of a successful scheduled run. We also encountered a very practical deployment hurdle: the Hosted service's instance identity lacked project permission to create managed editorial conversations. Assigning Foundry User at the project scope to the correct calling identity, then allowing propagation, resolved it. Your user account having permission does not imply that the running agent has it.[2] Midnight is a real handover, not another replay “Keep one day” requires a shared definition of the day. We use the current Asia/Shanghai calendar date—not a rolling 24 hours, and not each visitor's local day for deleting shared Blob content. A separate task runs at Beijing midnight to prune expired catalogues, public/private audio, evidence, scripts, WAVs and runtime records, including snapshots and stored versions. Each production also sweeps to catch missed cleanup. Dated writes and cleanup share the publication lease, so an old job cannot recreate yesterday's files after deletion. The browser stops expired audio at rollover even if catalogue refresh fails. If today's first programme is not ready, it waits. Repeating the latest completed programme is allowed only within the current station day. Cleanup does not silently disable account-wide Azure soft-delete protection. If enabled, recoverable copies remain subject to that policy. Previously downloaded files cannot be recalled. The final details live on a phone screen The frontend needs no elaborate framework: a lightweight single page can offer a persistent player, headline ticker, source links, language switching and current-day listening on demand. A headline seeks the audio; a source link opens the report. Keeping those actions separate avoids an ambiguous click. Display all times in the listener's browser timezone while retaining Beijing time for paths and cleanup. Refresh catalogues every 45 seconds. Expect browser autoplay restrictions to require an initial tap. A desktop demonstration is not enough: exercise mobile playback, scrolling, seeking and timezone conversion. Closing Thought: A Useful Agent Is More than a Beautiful Answer The takeaway is not simply that AI can generate a podcast. It is that we gave the station understandable responsibilities, durable data and inspectable handovers. Microsoft Copilot Harness gives the managed editor tools, a workbench and delegation. Application code protects evidence, permissions, duration, publication and lifecycle boundaries. That is the agent story I want to tell as a technical evangelist: bring intelligence into a real workflow, rather than hide the workflow inside a prompt. Explore the current programme and interactive data-node diagram on the Meridian 24 page. The page retains only the current station day's content; it is not a permanent episode archive. Source Code Repo - https://github.com/kinfey/MSCopilotHarness.NewsPodcast References Microsoft announcement: Microsoft Copilot Harness and Hosted Agent long-running resilience Microsoft Learn: Microsoft Copilot Harness, including identity, workspaces and preview limitations Microsoft Learn: MAI Voice 2.1 and MAI Voice 2.1 Flash Project implementation and documentation Source Code Repo379Views0likes0Comments