get started
132 TopicsBuild 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.Beyond One-Size-Fits-All: Decision Routing for GitHub Copilot in CLI & VS Code
As developer tools move into the age of agentic AI, it is easy to fall into a familiar habit: when a task matters, choose the strongest—and usually most expensive—model available. Real software work is more varied than that. Explaining a function, editing a README, adding a boundary test, debugging a cross-module race condition and reviewing authentication logic demand very different levels of reasoning, context, tool use and reliability. A fixed model for every turn either wastes latency and budget or leaves difficult tasks underpowered. That is the motivation behind decision-ghc-router: GitHub Copilot continues to execute, while a Decision Router selects a sufficiently reliable and economically sensible model at the start of each new user turn. (The design also draws on gargpratyush/jev-router, especially its per-turn routing, native CLI preservation and model pinning across tool continuations.) The goal is not to build another agent outside Copilot or replace the native developer experience with a custom chat UI. GitHub Copilot CLI and the VS Code GitHub Copilot extension should keep their existing authentication, model catalog, tools, permissions, sessions and streaming behavior. The router adds one short, explicit decision step—and then gets out of the way. 1. Start with the distinction: a Decision Model is not a Model Router Before discussing implementation, two frequently conflated concepts need to be separated. A Decision Model makes bounded, structured judgments A Decision Model is not prompted with “write an article.” It receives: a current state, expressed as text or JSON; one or more bounded questions; explicit options or grading criteria. It returns typed results and probabilities that software can act on immediately, rather than free-form prose. For example: noul: Does this tool call touch production data? Return a probability between 0 and 1. choice: Should this task use the Fast, Balanced or Strong tier? Return the selected option and a probability for every option. score: How risky is this code change? Return an ordered score and its probability distribution. A Decision Model is therefore a fast, calibratable judgment primitive. Its uses extend beyond model selection to classification, ranking, prioritization, validation, agent control, safety screening and AI judging. A Model Router turns judgment into execution A Model Router is a system pattern, not a single model. A production-ready router must typically: discover models actually available to the signed-in account; reject candidates that are unavailable, unpriced, context-insufficient or API-incompatible; build a minimal routing state; invoke a scorer—which might be rules, a benchmark table, an LLM classifier or a Decision Model; apply confidence, cost, latency, safety and organizational policy; select a concrete model and start native execution; pin that model across tool continuations; emit decisions, estimates and failures for audit and tuning. In short: The Decision Model judges what is most suitable. The Model Router makes that judgment usable, compliant, executable, observable and recoverable. A Decision Router does not replace the larger routing system. It gives that system a specialized, fast and threshold-friendly scoring engine. Decision Model versus Model Router Dimension Decision Model Model Router Nature Specialized model capability Application or platform architecture pattern Input State, bounded questions, options or grading criteria User task, account catalog, prices, context limits and policy Output Typed answer and probabilities Concrete model, execution path, policy outcome and telemetry Content generation Does not produce free-form content Usually dispatches a generative model Account entitlement Not responsible Responsible API compatibility Not responsible Responsible Failure handling Provides uncertainty Must define fallback or stop behavior Broader use Classification, scoring, routing and validation Multi-model orchestration, cost governance and runtime control 2. Microsoft-Decision-1: why it fits developer-tool routing Microsoft introduced Microsoft-Decision-1 in October 2026 as a specialized model for fast decision scoring, available through Microsoft Foundry. Unlike a generative LLM, it does not produce an essay or a written chain of reasoning. It makes a focused judgment about text or JSON and returns typed numerical decisions. Microsoft describes the model as a post-trained Qwen3.5-9B designed for single-pass scoring over fixed options. It reports the highest accuracy in a 36-benchmark comparison spanning nearly 150,000 questions kept blind from training, P50 latency roughly 35 times faster than GPT-6 Sol, and an average 1.3% decision-flip rate across eight perturbation types. At launch, Microsoft listed input at US$0.042 per million tokens with no output-token charge; pricing is dynamic, so a deployment should use the current Microsoft Foundry listing. Those are Microsoft-published benchmark results, not a substitute for evaluation on a team’s own development workload. Microsoft-Decision-1 exposes three question types that map naturally to an AI control plane: noul for binary gates such as “May this command run automatically?” choice for bounded routing such as “Which model tier should handle this turn?” score for ordered grading such as “How severe is the change risk?” Why not use a small LLM classifier? That is a valid architecture. Many model routers ask a lightweight LLM to emit easy, medium or hard. GitHub Agentic Workflows’ experimental model routing also classifies a task before ranking allowed model-and-effort combinations through precompiled routing tables. A dedicated Decision Model, however, offers four useful properties for developer tools: Bounded output. A router needs a label and probabilities, not persuasive prose. Predictable latency. Agent workflows amplify the cost of every sequential control-plane call. Policy-ready confidence. If the top probability is below 0.65, a local policy can avoid downgrading, keep the current model or request manual selection. Composable governance. One structured request can score model tier, operational risk and the need for human review. A conceptual choice request for Copilot routing The following is simplified pseudodata—not repository source—and omits deployment and authentication details: { "state": { "task": "Fix intermittent failures in the authentication integration tests", "estimatedContextTokens": 18000, "toolUseExpected": true, "workspaceScope": "multi-file", "latencyPreference": "balanced" }, "questions": { "model_tier": { "type": "choice", "instructions": "Choose the least expensive tier likely to complete the task reliably in one pass.", "criteria": { "fast": "Simple explanation, formatting, lookup, or small deterministic edit", "balanced": "Normal coding, tests, debugging, or limited multi-file work", "strong": "Ambiguous architecture, security, difficult debugging, or broad multi-file reasoning" } } } } The response identifies a tier and assigns a probability to every tier. The router then maps the abstract choice to a concrete model that is truly available to the current GitHub account. That separation matters: a Decision Model should not assume that a user owns or can access a particular model. The account catalog is the source of truth. 3. The decision-ghc-router scenario and reference architecture The architecture has two hosts but one consistent decision model. 3.1 GitHub Copilot CLI: put the router in native /model In the public predecessor implementation, a user-level extension adds a router entry to GitHub Copilot CLI’s native /model menu. The user can select the router or choose a concrete model directly: Select Decision Router: route every new user turn. Select a concrete model: bypass routing and return to native fixed-model behavior. Continue a tool call: keep the model chosen for that turn; do not classify again. Explicitly request a model: the explicit request should win. The CLI path uses a random-port 127.0.0.1 proxy to expose the router as a temporary provider while preserving Copilot authentication, sessions, tools, permissions and streaming. GitHub credentials should remain in memory and be used only for HTTPS requests to GitHub. The local proxy uses separate random credentials; GitHub credentials must not be written to logs or sent to the Decision API. This is the design principle I care about most: The router changes which model is selected, not how Copilot works. 3.2 VS Code and VS Code Insiders: enter the Chat Model Picker The editor integration is a separate extension. It registers decision-router in VS Code Chat’s model picker and uses the public Language Model API to discover Copilot models available to the account signed into that editor. The privacy boundary is intentional: The Decision Model receives an unambiguously extracted task or a routing-only summary entered by the user. If the task cannot be reliably isolated from editor context, the extension should not automatically upload attachments, source files or the full conversation. The selected Copilot model still receives the full conversation, tool definitions and workspace context. VS Code invokes native tools, while tool-call IDs maintain model consistency. The short version is: minimize data for decision; maximize context for execution. 3.3 The seven-step loop for each new user turn Receive the task through native Copilot CLI or VS Code Chat. Discover candidates from account models, prices, context capabilities and API compatibility. Build routing state with the minimum sufficient task summary and bounded choices. Call Microsoft-Decision-1 and receive choice probabilities. Apply local policy for confidence, cost, compatibility and manual overrides. Execute natively with the selected model, existing tools, permissions, session and streaming. Pin and trace the model for tool continuations while recording the decision and estimate. 3.4 Why not reroute every tool continuation? Imagine a model runs tests, reads the failure output and then edits code. If the router chooses a new model after every tool result: prompt-cache benefits may disappear, increasing total cost; the new model may interpret earlier tool calls differently; the debugging chain becomes harder to reproduce and audit. I therefore retain one of jev-router’s strongest ideas: make one decision at the start of a new user turn, then pin that model for the resulting tool chain. Main conversations and sub-agents should be pinned independently. 4. Main technologies and frameworks Based on mechanisms verifiable in the public predecessor and the Microsoft-Decision-1 evolution described here, the project separates into the following layers. Node.js and ESM modules The core router uses Node.js and .mjs modules to handle: CLI startup and argument forwarding; model catalog and price adaptation; the local HTTP proxy; configuration and environment variables; Decision API calls; policy, errors and telemetry. The public predecessor requires Node.js 22.16 or later and uses Microsoft’s npm package source for relevant dependencies. GitHub Copilot CLI extension interfaces The CLI integration relies on experimental extension interfaces to register the router as a native model entry. It explicitly enables the provider-endpoint interface and obtains the model catalog, runtime inference endpoint and authentication from the active session. Three rules are essential: Do not modify the user’s global default model. Do not automatically grant shell or other tool permissions. If initialization fails, report a clear error instead of pretending routing succeeded. Local loopback proxy The loopback proxy is the adapter that preserves the native CLI: listen only on 127.0.0.1; use a random port and random local credentials; map the router’s selection to a real Copilot execution model; preserve streaming, tool calls, sessions and permission prompts; never create a second hidden agent loop. VS Code Extension API The editor extension discovers current candidates through: vscode.lm.selectChatModels({ vendor: "copilot" }) and is packaged as a VSIX. The CLI and editor are independent hosts and may use different GitHub accounts with different entitlements. Candidate discovery must therefore be host-specific, session-specific and dynamic—not a hardcoded list of model IDs. Microsoft Foundry and the Decision API Microsoft-Decision-1 can be deployed in Microsoft Foundry through GlobalStandard or, in selected regions, DataZoneStandard. Authentication can use Microsoft Entra ID (recommended) or an API key. In this architecture, the Decision API only scores choices: Input: minimal task state, bounded candidates and explicit criteria. Output: selected option, option probabilities and usage. Not its responsibility: GitHub credentials, developer tools, full workspace access or code execution. That separation makes the decision plane and execution plane independently governable. Model catalog, pricing and capability adapters The public predecessor discovers models from the signed-in account instead of hardcoding them. Before scoring, a router should exclude: auto, hidden, disabled or unconfigured entries; models without usable price information; candidates with insufficient input context; models incompatible with the host’s wire API; models restricted by administrator policy. Cost estimation supports ranking and user feedback; it is not a final bill. Promotions, cache discounts, hidden context, retries and later tool rounds all affect the result. GitHub Billing remains authoritative. 5. What I borrow from jev-router—and what changes The value of gargpratyush/jev-router is not merely “use a small model for easy tasks.” It embeds routing into familiar CLIs without taking away their native behavior. The ideas I retain include: one routing decision per new user turn; a router sentinel in the native model picker; concrete-model selection pauses routing; abstract Fast, Balanced, Strong and Long tiers map to host-specific models; tool continuations keep the tier selected at the start of the turn; explicit model requests win; low confidence should not trigger an aggressive downgrade; large conversations must account for cache and migration cost; explanation data should show why a tier was selected. The decision-ghc-router evolution replaces the external JEV/System One scorer with Microsoft-Decision-1 and emphasizes five changes: Probability is a first-class signal. Policy can threshold the decision instead of accepting a label blindly. Bounded choices come from the real catalog. Decision-1 only chooses among already eligible candidates. Local policy owns the final answer. Organizational rules, compatibility and manual overrides remain deterministic. The Decision Model is reusable. A single structured call can also score operational risk and the need for human review. Local and cloud responsibilities are explicit. Cloud scoring is isolated from credentials and execution. 6. Representative use cases A. Fast explanation and small edits “Explain this regular expression,” “turn this note into a table,” or “add a null-value test to an existing function.” The router can often select the Fast tier. The objective is not the weakest model; it is the least expensive model likely to complete the task reliably in one pass. B. Normal development and debugging “Fix the failing test,” “refactor this module without changing its API,” or “use the stack trace to locate the bug.” These tasks require code reading, tool use and moderate reasoning, so they often land in Balanced. C. Security, architecture and broad multi-file reasoning “Review this OAuth callback for state confusion,” “design cross-region failover,” or “find a race condition across services.” The router should choose Strong even when it costs more. Routing optimization means “economical subject to reliable completion,” not “always cheaper.” D. Long context and large repositories If a candidate cannot hold the estimated input, it must be removed before scoring. For an already large conversation, the router should also avoid downgrading when lost cache work or context migration would cost more than the model-price saving. E. Organizational policy and risk gates The same Decision API request can include additional noul or score questions: Does the task involve production data? Is the proposed command destructive? What is the security risk level of the change? Should execution be handed to a human reviewer? At that point the router grows from a cost optimizer into a lightweight control plane for agents. 7. Policies I would keep for production Filter deterministically before scoring Entitlement, API compatibility, context limits and administrator restrictions are facts. The Decision Model should not be asked to guess them. Do not automatically downgrade on low confidence When the top probability falls below a calibrated threshold, the router can: keep the current model; cap automatic movement at Balanced; request manual selection; send high-risk tasks to Strong or human review. The threshold must be calibrated on labeled tasks from the target environment, not copied from an example. Explicit intent beats automatic routing If the user says “use the Strong model” or selects a concrete entry in the picker, the router should step aside immediately. Never substitute silently Missing credentials, Decision API timeouts, unknown pricing and insufficient context should produce an explicit state. Whether to fail open, fail closed or keep the current model must be an intentional host or organizational policy. Record decisions without logging every prompt by default Useful telemetry includes: anonymized session and turn IDs; candidates and exclusion reasons; selected tier, probabilities and policy overrides; estimated input/output and one-turn cost; completion, retry and manual-reselection outcomes. Full prompts, source code and tool results should be excluded by default or governed by explicit retention and data-handling policy. Evaluate the router on task success, not the cheapest request Better metrics include: first-pass completion rate; total time to completion; total cost including retries and tool rounds; manual model-change rate; low-confidence and misrouting rates; safety and policy violations. 8. Why this matters beyond one repository From a developer-advocacy perspective, the Decision Router is not simply a token-saving utility. It illustrates a clearer division of responsibilities in agent engineering: Generative models understand, reason, write code and call tools. Decision Models make fast, structured and probabilistic judgments. Routers and policy engines place those judgments inside real account, budget, compatibility and governance constraints. Developer-tool hosts retain identity, permission, context and execution control. Future AI developer tools will not be tied to one “default large model.” They will manage a portfolio of models with different speed, cost, context and capability profiles. The differentiator will no longer be merely which model a product connects to, but: Can it select the right model at the right moment, in an explainable and governable way, without breaking the developer experience? That is why I am adding a Decision Router to GitHub Copilot CLI and the VS Code GitHub Copilot extension. GitHub Copilot keeps executing. Microsoft-Decision-1 makes the fast judgment. The local router turns that judgment into a usable engineering decision. References decision-ghc-router jev-ghc-router gargpratyush/jev-router Microsoft-Decision-1: Our model for fast decision-making Deploy and use Microsoft-Decision-1 in Microsoft Foundry GitHub Agentic Workflows — Model Routing GitHub Copilot model billing and pricing889Views0likes0CommentsI NEED HUMAN HELP -- I am having issues with my Microsoft business email, I can't access Word
888 319 8920 I am having issues with my Microsoft business email, I can't access Word. I've tried calling multiple numbers and haven't been able to reach a human and the automated machine is no help. If someone would please give me a good number to call or an email address, I'd greatly appreciate it.306Views0likes2CommentsIntroducing bicep docs: generate documentation from your Bicep modules
TL;DR: The Bicep CLI has a new experimental command, bicep docs generate . Point it at a Bicep module and it writes a README.md next to it that describes the module's resources, parameters, types, outputs and usage examples, all read straight from your code. You can change the layout with your own templates, add details that aren't in the code, and document every module in a repository with one command. It's available now in Bicep CLI v0.47.16 and later. bicep docs generate ./main.bicep Why we built it Module documentation has a habit of drifting away from the code it describes. Someone renames a parameter, adds an output or changes an allowed value, and the README quietly goes out of date. Teams that publish a lot of modules often end up writing their own scripts to keep the two in step. bicep docs moves that job into the Bicep CLI. It compiles your module and uses the compiler's own understanding of it, so it picks up the details Bicep already knows: metadata , @description decorators, default values, allowed values, length limits, user-defined types, exported types, variables and functions, outputs, and the local modules it references. Run it again whenever the module changes, and the documentation will match the code. Get started You need Bicep CLI v0.47.16 or later. Check your version with bicep --version , and see Install Bicep tools if you need to upgrade. There's no feature flag to turn on. Here's a small storage account module: metadata name = 'Storage Account' metadata description = 'Deploys a storage account with secure defaults.' @description('Required. The name of the storage account. Must be globally unique.') @minLength(3) @maxLength(24) param name string @description('Optional. The Azure region to deploy the storage account to.') param location string = resourceGroup().location @description('Optional. The storage account SKU.') @allowed([ 'Standard_LRS' 'Standard_GRS' 'Standard_ZRS' ]) param skuName string = 'Standard_LRS' resource storageAccount 'Microsoft.Storage/storageAccounts@2025-06-01' = { name: name location: location kind: 'StorageV2' sku: { name: skuName } properties: { allowBlobPublicAccess: false minimumTlsVersion: 'TLS1_2' } } @description('The resource ID of the storage account.') output resourceId string = storageAccount.id Generate its documentation: bicep docs generate ./modules/storage-account/main.bicep Bicep writes README.md next to main.bicep . For this module, the built-in layout includes a list of sections, the resource types, a usage example (more on those below), the parameters with the details of each one, and the outputs. When a module has them, it also covers exported types, variables and functions, and referenced modules. Here's an excerpt: # Storage Account Deploys a storage account with secure defaults. ## Parameters | Name | Type | Required | Description | | :-- | :-- | :-- | :-- | | `location` | `string` | No | Optional. The Azure region to deploy the storage account to. | | `name` | `string` | Yes | Required. The name of the storage account. Must be globally unique. | | `skuName` | `string` | No | Optional. The storage account SKU. | ### `location` - Default value: `resourceGroup().location` ### `name` - Min length: 3 - Max length: 24 ### `skuName` - Default value: `'Standard_LRS'` - Allowed values: `Standard_GRS`, `Standard_LRS`, `Standard_ZRS` A couple of options you'll use often: --stdout prints the result to the terminal instead of writing a file, which is handy for a quick preview. --outfile writes to a file of your choice, and --outdir writes the documentation into another folder. Because the command is experimental, Bicep prints a warning each time you run it. Usage examples are included automatically Examples are often the most useful part of module documentation, so bicep docs looks for them next to your module. By default it picks up: .bicep files in an examples folder, and main.bicep files in its subfolders *.test.bicep files anywhere under a tests folder Files named dependencies*.bicep are skipped. Each example's heading comes from its metadata name . Without one, Bicep uses the name of the folder the example is in, or its file name if it's not in a subfolder. The description comes from metadata description , or else the // comments at the top of the file. For example, this file in modules/storage-account/examples becomes a "Zone-redundant storage account" example in the README: metadata name = 'Zone-redundant storage account' metadata description = 'Deploys a storage account that keeps copies of your data in three availability zones.' module storageAccount '../main.bicep' = { params: { name: 'stdocsdemo001' skuName: 'Standard_ZRS' } } If your examples live somewhere else, list their locations in documentation.examples.sources in bicepconfig.json . Your list replaces the default locations. Make it your own with templates The built-in layout is a good start, but you'll probably have your own conventions. bicep docs renders documentation with Scriban, a lightweight text templating language. Write a template, then point to it from bicepconfig.json : { "documentation": { "template": { "file": "templates/readme.scriban" } } } The template path is relative to the bicepconfig.json file. As with its other settings, Bicep uses the bicepconfig.json nearest to each module. This template writes a parameters table and an outputs table: # {{ module.name }} {{ module.description }} ## Parameters | Name | Type | Required | Description | | :-- | :-- | :-- | :-- | {{~ for parameter in module.parameters ~}} | `{{ parameter.name }}` | `{{ parameter.type }}` | {{ if parameter.required }}Yes{{ else }}No{{ end }} | {{ parameter.description }} | {{~ end ~}} ## Outputs | Name | Type | Description | | :-- | :-- | :-- | {{~ for output in module.outputs ~}} | `{{ output.name }}` | `{{ output.type }}` | {{ output.description }} | {{~ end ~}} The ~ inside the braces removes the spaces and line breaks next to a tag, so the loops don't add blank lines that would break the tables. Your template receives a module object with the module's name , description , targetScope , resourceTypes , parameters , exportedTypes , exportedVariables , exportedFunctions , outputs , references and usageExamples . The command documentation lists every field. A couple of tips: Split a big template into smaller files with Scriban's include , and set documentation.template.includeRoot to the folder that holds them. The built-in Markdown template is a Scriban template too, so it's a good place to start. Add details that aren't in your code Some information doesn't belong in Bicep, such as the team that owns a module, where to get support, or the module's version. Pass it in as custom values and use them in your template as custom.<key> : **Owner:** {{ custom.owner }} | **Version:** {{ custom.version }} | [Get support]({{ custom.supportUrl }}) Supply values one at a time with --custom-template-value , or load several from a JSON file with --custom-template-value-file-path : bicep docs generate ./modules/storage-account/main.bicep ` --custom-template-value owner="Platform Team" ` --custom-template-value-file-path ./docs-values.json Where docs-values.json contains: { "supportUrl": "https://contoso.example/support", "version": "1.0.0" } Both options can be repeated. If the same key is set more than once, the last one on the command line wins. Go beyond Markdown Scriban writes whatever text your template contains, so the output doesn't have to be Markdown. A template could produce JSON for a module catalogue, HTML for an internal portal, or input for another tool. This template produces JSON, and Scriban's object.to_json function takes care of quotes and escaping: { "name": {{ module.name | object.to_json }}, "description": {{ module.description | object.to_json }}, "parameters": [ {{~ for parameter in module.parameters ~}} { "name": {{ parameter.name | object.to_json }}, "type": {{ parameter.type | object.to_json }}, "required": {{ parameter.required | object.to_json }} }{{ if !for.last }},{{ end }} {{~ end ~}} ] } Set documentation.template.file to this template, then use --outfile to save the result with a .json file name: bicep docs generate ./modules/storage-account/main.bicep --outfile ./modules/storage-account/module.json To change the default file name for every module instead, set documentation.output.file in bicepconfig.json . Each module uses the one template set in its nearest bicepconfig.json . To get both Markdown and JSON from the same modules, make that template a small switch that includes the right template based on a custom value: {{~ if custom.format == "json" ~}} {{~ include "catalog.scriban" ~}} {{~ else ~}} {{~ include "readme.scriban" ~}} {{~ end ~}} Set documentation.template.includeRoot to the folder that holds the templates. Then run the command as normal for the README, and add --custom-template-value format=json --outfile ./modules/storage-account/module.json for the JSON. Document every module in one go Use --pattern to document every module that matches a wildcard: bicep docs generate --pattern './modules/**/main.bicep' Each module gets its own README.md next to its main.bicep . Add --outdir ./docs to put them in a separate folder instead, and Bicep recreates the folder structure beneath it. If a module has compile errors, Bicep reports them, carries on documenting the other modules, and returns exit code 1 at the end. To see this at scale, the demo repository generates Azure Verified Modules (AVM) style documentation for 20 App Service modules, including their child modules, with a single command. Its template works out each module's registry reference and main resource type from the module itself. The AVM team is standardising and consolidating its tooling, and bicep docs is part of that work. Keep documentation up to date in CI Because the documentation comes from the code, your pipeline can check that it's current. Regenerate it, then fail the build if anything changed: bicep docs generate --pattern './modules/**/main.bicep' if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } $changes = git status --porcelain if ($changes) { $changes throw 'Module documentation is out of date. Run bicep docs generate and commit the result.' } The generated documentation is only as good as your descriptions, so the new description linter rules in Bicep v0.47 make a good partner. They're off by default and flag missing or empty @description decorators. Turn on the ones you need in bicepconfig.json : { "analyzers": { "core": { "rules": { "use-description-params": { "level": "warning" }, "use-description-outputs": { "level": "warning" }, "use-description-types": { "level": "warning" }, "use-description-type-properties": { "level": "warning" } } } } } There's also use-description-vars for variables. Thanks to @johnlokerse for contributing these rules! Building tools on top of Bicep? The same generator is available through the Bicep CLI's JSON-RPC interface as bicep/generateDocs . It returns the rendered text and leaves writing files to you. For .NET, the Azure.Bicep.RpcClient package wraps it. It's experimental, and we'd love your feedback bicep docs is experimental. The command options, configuration, template model and built-in layout may change between releases without a breaking-change notice. One change is already on the way. In v0.47 you can also choose a template with the --template-file and --template-root options. The next release removes these options, so templates are set only with documentation.template.file and documentation.template.includeRoot in bicepconfig.json . The examples in this post already use bicepconfig.json , so they'll keep working. Try it on your own modules and tell us what works and what's missing by opening an issue in the Bicep repository. Learn more bicep docs command documentation Demo repository, with step-by-step demos from the built-in layout to AVM-style documentation Bicep v0.47.16 release notes Scriban language reference bicep docs is also featured in the September 2026 Bicep community call. Community call recordings are on the Azure Deployments & Governance YouTube channel, and you can sign up to join future calls.994Views2likes0CommentsBuilding a Fully Automated Azure Landing Zone Deployment Using Azure DevOps and Terraform
Discover how to build a fully automated Azure Landing Zone using Azure DevOps and Terraform. This article walks through real-world Git workflows, CI/CD automation, environment promotion strategies, and governance integration to create secure, scalable, and enterprise-ready Azure environments.1.6KViews1like0CommentsWelcome! Let's get started.
We're gathering the early adopters of Microsoft Agent 365 to connect, share, and answer questions about deploying agents in your organization with observability, security, and governance. Welcome! So... how many agents are in your Registry? -- Nichole466Views1like1CommentFrom Multi-Model Chaos to a Governed AI Gateway: Cost Optimization on Azure
What is Multi-Model Chaos, and what cost and security challenges does it pose? Multi-model chaos describes the sprawl that emerges when an organization rapidly adopts many large language and foundation models—OpenAI, Anthropic, Meta Llama, Mistral, and a long tail of open-source and fine-tuned variants—across teams and applications without any unifying control plane. Instead of a single governed entry point, each team wires its own keys, endpoints, SDKs, and prompts directly to whichever provider it prefers, leaving the enterprise with a fragmented, duplicated, and largely invisible AI estate. On the cost side, this fragmentation makes spend almost impossible to predict or contain, identical workloads run against premium models when cheaper ones would suffice, token consumption goes unmeasured, redundant calls and missing caching inflate bills, and finance teams have no consolidated view to attribute usage back to a team, product, or customer. On the security and governance side, the risks compound: API keys are scattered across code and config files, sensitive or regulated data flows to external endpoints with no data-loss prevention or residency guarantees, prompt-injection and jailbreak attempts go unmonitored, and there is no centralized authentication, rate limiting, auditing, or content filtering. The net effect is an uncontrolled attack surface and a compliance blind spot—precisely the conditions that motivate consolidating model access behind a governed AI gateway. In short, multi-model chaos trades short-term speed for runaway costs and an unmanaged security risk, making a governed AI Gateway essential. What is a Governed AI Gateway, and how do they help reduce cost and improve security? A governed AI gateway is an enterprise control plane built on Azure API Management (APIM) that consolidates every model behind a single, governed endpoint. It unifies Azure OpenAI (the gpt-5.4 family) and Azure AI Foundry (open-source and partner models such as grok-4.3 and DeepSeek-V4-Pro), so consumers reach any of them through one consistent, policy-enforced entry point rather than a tangle of direct connections. Every backend is password-less, authenticated through managed identity, which eliminates scattered API keys. On top of this foundation, the gateway enforces per-consumer model permissions, token-based rate limits, and cost-based budget downgrade—automatically routing teams to more economical models as they approach their spend limits—all administered from a self-service Admin UI. One governed endpoint for every backend. Azure OpenAI and Azure AI Foundry (OSS and partner) models are bundled behind a single governance endpoint. Each backend is reachable only over a private endpoint with key authentication disabled, so APIM authenticates using its own managed identity—no model keys ever live on the gateway. Per-consumer governance, edited live in the Admin UI with no redeployment: Allowed models — a consumer can call only the models explicitly granted to it; anything else returns a 403. Rate limits — per-consumer TPM and token-quota tiers (small / medium / large), returning a 429 once exceeded. Cost budget — a daily USD spend limit; when it is exceeded, requests are automatically downgraded to a cheaper model along a configured ladder, including cross-backend downgrades (e.g. gpt → OSS or OSS → gpt). Self-service Admin UI (React + FastAPI, Entra ID login, gated to an admin group) to issue consumer keys, set model, limit, and budget policies, and review the usage dashboard and request logs. Built-in observability — per-call token metrics, broken down by consumer and model, stream to Application Insights, surfaced through the Admin UI's usage dashboard and a request / blocked & downgrade-event log. Flexible client authentication — an APIM subscription key by default, or an Entra ID JWT (client_auth_mode). How is it different from APIM AI Gateway? APIM already provides useful GenAI gateway primitives: token rate limiting, token-usage metrics, semantic caching, backend routing, endpoint import, authentication, authorization, and monitoring. The difference is that APIM enables the enforcement runtime and policy control point, but not the full operating model required to run a shared, multi-tenant AI platform across teams, models, and budgets. Inside the policy pipeline, APIM remains the load-bearing layer: llm-token-limit enforces per-consumer token-per-minute and quota limits, llm-emit-token-metric streams token usage into our metrics namespace, and standard APIM capabilities handle endpoint exposure, access control, and platform monitoring. The governed AI Gateway adds the governance layer APIM does not provide out of the box: Self-service onboarding — a platform team can issue or revoke consumer keys and manage access from the Admin UI, without raising a pull request or redeploying infrastructure. Per-consumer model entitlements — every consumer has an explicit allow-list of model deployments. The gateway calculates the effective allowed set per request and returns 403 when a caller asks for a model it is not entitled to use. Live configuration without redeployment — entitlements, rate tiers, token quotas, budgets, and downgrade levels live in the configuration store. A sync worker projects those values into APIM named values continuously, so operational changes can take effect without a terraform apply while the policy logic stays version-controlled in IaC. Managed-identity-only, private backends — key-based authentication is disabled on Azure OpenAI and Azure AI Foundry. APIM injects a managed identity token on every backend call, and the backends are reachable only over private endpoints. Cost-based downgrade across backends — when a consumer approaches its budget, the gateway can route to a cheaper model while preserving availability, including cross-backend downgrades between Azure OpenAI and Azure AI Foundry. APIM’s AI gateway is the enforcement runtime while the governed AI Gateway is the platform operating model around it. APIM handles the gateway primitives extremely well, while our governance layer adds identity, self-service administration, entitlement management, live configuration, cost controls, and cross-model routing so teams can safely consume multiple models without creating new cost, security, or compliance sprawl. Solution overview Figure 1 shows the end-to-end architecture of the governed AI gateway. Client applications never talk to the models directly; instead, every request passes through Azure API Management, which acts as the single governed entry point that authenticates callers, applies per-consumer policy, and routes traffic privately to the appropriate model backend. Around this gateway sit the supporting planes for administration, identity, and observability, giving the organization one consistent place to control access, contain cost, and monitor usage across both Azure OpenAI and Azure AI Foundry models. This solution is also completely serverless. Key components: Client / consumer applications — the apps and services that call for model inference, each identified by its own consumer key or Entra ID identity. Azure API Management (the gateway) — the single governance endpoint that handles authentication, allowed-model checks, rate limiting, and cost-based budget downgrade before any request reaches a model. Model backends — Azure OpenAI (the gpt-5.4 family) and Azure AI Foundry (OSS and partner models such as grok-4.3 and DeepSeek-V4-Pro), each reachable only over a private endpoint. Microsoft Entra ID — provides identity for both clients (optional JWT auth) and the gateway's own managed identity used to reach the backends without password credentials. Admin UI (React + FastAPI) — the self-service control plane for issuing consumer keys and setting model, rate-limit, and budget policies. Application Insights — collects per-call token metrics by consumer and model, powering the usage dashboard and request / blocked-event logs. 1: Solution architecture diagram Request flow Authenticate — a client calls the gateway with an APIM subscription key (or an Entra ID JWT) instead of any model key. Authorize the model — APIM checks whether the consumer is permitted to call the requested model; if not, it returns 403. Enforce limits — the gateway applies the consumer's TPM and token-quota tier, returning 429 when the limit is exceeded. Apply the cost budget — if the consumer's daily USD budget is exhausted, the request is automatically downgraded to a cheaper model along the configured ladder. Route to the backend — APIM forwards the request over a private endpoint, authenticating with its managed identity to Azure OpenAI or Azure AI Foundry. Return and record — the model response is returned to the client while per-call token metrics are emitted to Application Insights and surfaced in the Admin UI dashboard and logs. Implement the solution This section describes how to deploy the solution architecture. In this post, you’ll perform the following tasks: Create APIM Create Cosmos DB Create Microsoft foundry with Gpt-5.4, Gpt-5.4-mini, DeepSeek-V4-Pro and Grok-4.3 deployed Create the Admin UI on container apps Create a consumer with an APIM subscription key on the Admin UI Integrate APIM endpoint with Github Copilot chat and Copilot CLI Create a budget and rate limit in the Admin UI Simulate and validate auto downgrade feature Ensure that you have the following prerequisites deployed before moving to the next section An Azure subscription with model quota (Azure OpenAI and, optionally, Azure AI Foundry models). Tools: Git, Terraform ≥ 1.7, Azure CLI, and az login to the subscription. Container images are built remotely in Azure Container Registry, so Docker is not required. VScode and Copilot CLI Deploy the Azure AI Gateway Clone the repository from https://github.com/microsoft/apim-foundry-governance git clone https://github.com/microsoft/apim-foundry-governance git checkout english By default the solution deploys in koreacentral region. Export your custom variables if needed. export location=eastus2 export backend-rg=rg-aigw-tfstate-dev-eastus2 export storage-prefix=staigwtfstate export state-key=ai-gateway-eus2.tfstate Bootstrap the Terraform state backend (once per subscription) This creates an eastus2 resource group + storage account for remote state (Entra auth, public blob access blocked). ./scripts/bootstrap-backend.sh \ --location $location \ --backend-rg $backend-rg \ --storage-prefix $storage-prefix \ --state-key $state-key Set Terraform variables cp infra/terraform.tfvars.example infra/terraform.tfvars # Edit infra/terraform.tfvars: prefix, location, owner, cost_center, apim_publisher_*, budget_* Create the Gateway Core On the first apply, leave worker_image and admin_ui_image empty (default ""). The images don't exist yet, and the worker Job / Admin UI app are count-gated on these variables. cd infra terraform init # If you are moving an existing state from another backend, run `terraform init -migrate-state` instead. terraform apply Build and push the container images with app registrations After the registry is created, build the worker and Admin UI images remotely (no local Docker needed). acr=$(terraform output -raw registry_login_server) reg=$(terraform output -raw registry_name) az acr build --registry $reg --image config-sync-worker:latest ../app/config-sync-worker az acr build --registry $reg --image admin-ui:latest ../app/admin-ui The worker and Admin UI requires entra app registrations for a user to access the frontend. Create the admin security group, BFF API App registrations and SPA public-client app registrations. ./scripts/app-registration.sh Enable the worker and Admin UI From the output above, populate the image references and the three Entra variables from the prerequisites into infra/terraform.tfvars and apply again. worker_image = "<registry_login_server>/config-sync-worker:latest" admin_ui_image = "<registry_login_server>/admin-ui:latest" admin_ui_public = true # external FQDN (still Entra-gated). false = VNet-only admin_group_object_id = "<entra security group object id>" bff_api_audience = "api://<bff app id>" spa_client_id = "<spa app id>" entra_tenant_id = "<tenant id>" CosmosDB Seed configuration Cosmos is private with key auth disabled, so the initial config is seeded from a jumpbox inside the VNet. Default confguration of enable_jumpbox = true in infra/terraform.tfvars triggers Terraform to: provision the jumpbox VM, grant it’s managed identity the Cosmos DB Built-in Data Contributor role (scoped to the config container), and runs a VM run-command that seeds both documents automatically: Global config (id=global) — allowed models + token limits. Per-model pricing (id=pricing) — prompt/completion rates for cost-based budgeting. To seed manually instead (jumpbox connected via Bastion), the same scripts can be run directly: # Global allowed models + limits ./scripts/seed-cosmos-jumpbox.sh https://<cosmos-account>.documents.azure.com:443/ # Per-model pricing (for cost-based budgeting) ./scripts/seed-pricing-jumpbox.sh https://<cosmos-account>.documents.azure.com:443/ Access the AdminUI Update the SPA with your containerapps url spa_app_id="$(az ad app list --display-name "AI Gateway SPA" --query "[].appId" -o tsv)" # spa_client_id fqdn=$(terraform output -raw admin_ui_fqdn) # run from infra/ oid=$(az ad app show --id "$spa_app_id" --query id -o tsv) az rest --method PATCH \ --uri "https://graph.microsoft.com/v1.0/applications/$oid" \ --headers 'Content-Type=application/json' \ --body "{\"spa\":{\"redirectUris\":[\"https://$fqdn\"]}}" Browse to the admin_ui_fqdn, which is also the container apps fqdn. You will need to login via EntraID (Users will need to be added to the Entra group for them to login). Go ahead and register the consumer with a name and issue the API key. The API key is the APIM subscription key and will only be shown once on the UI, so copy and paste it somewhere safe. 2: AI Gateway Consumers and Keys Next, on the left hand tab, click on budgets. This will set the daily budget limit a user is allowed to consume in a day and is also where the model downgrade logic resides. For the purpose of demonstration, set a low budget of $1.8 and select the model priority that you want the downgrade to occur. In this case, gpt-5.4 will be used first, followed by gpt-5.4-mini, DeepSeek then Grok. 3: AI Gateway Budgets Lastly, on the land hand tab, select Rate limits. This sets the amount of tokens a user can consume in a day. It is a daily limit and resets after 24 hours. Select the large tier. 4: AI Gateway Rate Limits Browse to Dashboard, it shows you all the token information, request status codes and group them by consumer and model. You can also view the budget downgrade for a specific user. 5: AI Gateway Captions Integrate endpoint with github copilot chat in vscode In VScode, type “Ctrl + Shift + p” and select “Chat: Manage Language Model”. Select Add Models and choose Azure. 6: Add models toGithubCopilot Chat Follow through the prompts. It will create or edit a chatLanguageModels.json file. Your file should look like this. Take note that you will need to use the /vscode path. [ { "name": "Azure", "vendor": "azure", "models": [ { "id": "gpt-5.4", "name": "gpt-5.4 (APIM)", "url": "https://<REPLACE WITH YOUR APIM ENDPOINT>.azure-api.net/vscode/openai/deployments/gpt-5.4/chat/completions?api-version=2025-01-01-preview", "toolCalling": true, "vision": true, "maxInputTokens": 128000, "maxOutputTokens": 16000, "requestHeaders": { "Ocp-Apim-Subscription-Key": "<REPLACE WITH YOUR SUBSCRIPTION KEY" } } ] } ] Now select the gpt-5.4 (APIM) model and ask it a question. Integrate endpoint with copilot cli As copilot only accepts api-key headers, a separate api is used. Replace and export the following variables before using copilot cli. export COPILOT_PROVIDER_TYPE="azure" export COPILOT_PROVIDER_BASE_URL="<REPLACE WITH YOUR APIM ENDPOINT>" export COPILOT_PROVIDER_API_KEY="<REPLACE WITH YOUR SUBSCRIPTION KEY>" export COPILOT_MODEL="gpt-5.4" export COPILOT_PROVIDER_AZURE_API_VERSION="2025-01-01-preview" export COPILOT_PROVIDER_MODEL_ID="gpt-5.4" You should see a similar response. 7: Integration of APIM to copilot cli Simulate downgrade feature Continue to ask more questions to consume more tokens. Once it hits the 80% cost threshold, you should see that the tag has been switched to “Auto-switch level 1”, meaning it will downgrade to gpt-5.4-mini for future requests. 8: AI Gateway Downgrade Feature Validate by running this command in your terminal with your own endpoints and api-key. curl -sS -i -X POST "https://<REPLACE>.azure-api.net/openai/deployments/gpt-5.4/chat/completions?api-version=2025-01-01-preview" -H "api-key: <REPLACE WITH API KEY>" -H "Content-Type: application/json" -d '{"messages":[{"role":"user","content":"hi"}],"max_completion_tokens":8}' Inspect the headers, you should see that the downgrade level is 1 and the effective model is gpt-5.4-mini despite hitting the same endpoint of gpt-5.4. 9: Model downgrade Conclusion This post started with the problem of multi-model chaos: teams moving quickly with different models, endpoints, SDKs, keys, quotas, and cost profiles, but without a common control plane resulting in ineffective cost control and potential security leaks with model API keys. The governed AI Gateway addresses that by putting Azure OpenAI and Azure AI Foundry behind a single APIM-based entry point, where access, limits, routing, identity, telemetry, and budget behavior can be applied consistently for every consumer. We also walked through how the gateway is different from APIM’s native AI gateway capabilities. APIM provides the enforcement runtime and the GenAI policy primitives, such as token limits, token metrics, semantic caching, and backend routing. The governed AI Gateway builds the operating model around those primitives: self-service onboarding, per-consumer model entitlements, live configuration without redeployment, managed-identity-only private backends, per-call cost telemetry, and cost-based downgrade across model providers. From there, we integrated the APIM endpoint with Github Copilot Chat and Copilot CLI, and validated the downgrade behavior when spend thresholds were reached. The result is not just an AI proxy, but a reusable enterprise pattern for running AI access as a governed platform: developers keep a simple model endpoint experience, while the platform team keeps control over security, cost, observability, and operational change. Overall, this post helps organizations bring multi-model AI usage under one governed entry point, reducing sprawl across endpoints, keys, policies, and cost controls. It also gives platform teams centralized control over model access, rate limits, budgets, telemetry, and private backend access while preserving a simple endpoint experience for developers. References AI gateway capabilities in Azure API Management Policies in Azure API Management Azure API Management policy reference - llm-emit-token-metric Using GitHub Copilot CLI - GitHub Docs AI language models in VS Code1.2KViews3likes0CommentsMicrosoft Leads a New Era of Software Supply Chain Transparency
Microsoft announces the general availability of Microsoft’s Signing Transparency (MST) – a first-of-its-kind capability that brings unprecedented visibility and trust to our software supply chain. With this release, Microsoft is leading the industry by recording the build of critical cloud services into a publicly readable and verifiable SCITT standard (Supply Chain Integrity, Transparency, and Trust) compliant ledger. This means every production software build for in scope services like Azure Attestation and Azure Managed HSM (Hardware Security Module), Azure confidential ledger, Microsoft Signing Transparency itself (and others over time) – is now logged in an immutable, tamper-evident record. Only builds that are in the MST ledger are deployed to production; this gives customers confidence that the supply chain for these critical services can be audited at anytime. Notably, the MST ledger is fully open source and built to align with the emerging IETF SCITT standard. By embracing SCITT’s principles and open protocols, Microsoft ensures that MST not only secures our own ecosystem but also contributes to a broader industry movement toward standardized supply chain transparency. The open-source MST ledger serves as a verifiable trust anchor that any organization or researcher can inspect, audit, or even integrate with their own tooling. MST itself meets the highest levels of transparency, backed by a tamper-proof confidential ledger, open-source, and independently verified. Specifically, we are making the foundation of our trust model transparent and accessible to everyone – reinforcing that trust must be earned through proof, not just promises. This launch marks a major milestone in our commitment to Zero Trust principles, extending “never trust, always verify” all the way into the build itself. Building on a public preview introduced late last year, MST’s general availability delivers verifiable transparency at the software level. It transforms traditional code signing with an additive trust layer that is accessible via an open verification model. Every new software update is accompanied by a publicly auditable proof of integrity, enabling security teams to proactively confirm that each update is authentic and unaltered. To help organizations get the most out of this capability, we are also introducing a free tool to explore the contents – Ledger Explorer – an offline tool that allows security teams to examine MST ledger entries, verify cryptographic proofs, and even validate the ledger’s integrity independently. This tool, combined with MST’s open design, ensures that every Microsoft customer – and the broader community – can hold us accountable in real time for the software we run on their behalf. Key Benefits of Microsoft’s Signing Transparency (MST) Verified Code Integrity – Every software release is cryptographically logged in MST’s ledgers. This makes each build tamper-evident and traceable. If an attacker attempts to inject malicious code or sign an unauthorized update, it will be evident through the well-defined validation step built into the SCITT standard. Organizations gain the assurance that code integrity can be independently confirmed at any time. Independent Verification & Zero Trust – MST enables customers and auditors to verify software authenticity on their own, without having to solely rely on vendor attestations. For each update, Microsoft provides a transparency “receipt” (proof of logging) that you can use to prove the update was officially published and unaltered. This fosters a “don’t just trust, verify” approach, empowering security teams to double-check everything running in their environment aligns with what Microsoft intended. Audit-Trail & Compliance – The transparency ledger creates a permanent, auditable timeline of code deployments. Every entry is a record of what was released and when, backed by cryptographic proofs. This simplifies compliance reporting and accelerates forensic analysis. In the event of an incident, you can quickly audit the ledger to see if any unexpected code was introduced. For highly regulated industries, MST offers concrete evidence of software integrity and policy compliance over time. Leadership & Open Standards – We are delivering real transparency now, encouraging a future where all critical software is released with verifiable integrity. MST’s open source implementation and SCITT-compliant design exemplify our commitment to openness and collaboration. We believe widespread adoption of these standards will strengthen supply chain security for everyone, making trust verification a universal practice. Next Steps Microsoft’s Signing Transparency is more than a new security feature and shapes the advances in trust technology. As threats grow more sophisticated, we must evolve the way we assure our customers about the software they depend on. With MST now generally available, we are leading by example: proving that it is possible to open up the traditionally opaque process of software deployment and turn it into a source of strength and trust, i.e. empowering each person with verifiable transparency. We invite the industry to join us on this journey and get started by reading the documentation and exploring Ledger Explorer today! Together, by embracing transparency and open standards, we can turn “trust but verify” from a slogan into an everyday reality for digital infrastructure.1.2KViews0likes0CommentsWe Gave Ourselves 20 Minutes to Build an AI Agent for a Lumber Company. The Timer's Still on Screen.
Here's a confession: most "build with AI" webinars are 60 minutes of slides, 5 minutes of a polished demo someone rehearsed for a week, and a closing CTA. You leave inspired but not really sure what you saw. So we tried something different. We put a visible countdown timer on the screen and gave ourselves 20 minutes to do two things, live: Build an AI agent that solves a real business problem Deploy a working AI application to Azure No edits to hide the awkward parts. No "and here's one I prepared earlier." Just the timer, the screen, and a working app at the end. The on-demand recording is up now. Here's what's in it and why you should carve out 20 minutes for it this week. The setup: why lumber? 🏘️ We needed a real business problem, not a toy one. So for the demo, we role-play as the owner of Contoso Lumber — a regional lumber business with a very specific, very real headache: Should we sell our inventory now, or hold it longer? Sell too early, miss a better price. Hold too long, eat storage costs. Lumber prices fluctuate with global competition, macro shifts, even the weather. In the past, decisions like this came from morning meetings and gut instinct, or maybe the occasional ad-hoc spreadsheet that nobody could reuse a month later. It's the kind of decision that should have an analyst behind it — except most growing businesses can't afford to hire one full-time. So we build the AI agent that does. (Yes, lumber. We know. Stick with us — the boring industry is exactly the point. If it works here, it works for your business too.) What we actually build (in 20 minutes flat) The webinar walks through the entire flow, end to end: Part 1 — The agent. We open Microsoft Foundry at ai.azure.com, browse the model leaderboard (there are over 11,000 models to choose from — we compare a few on the cost-vs-quality chart), pick one, write a plain-English instruction for the agent, upload a CSV of historical lumber pricing, and ask it a real question: "If I cannot sell one of my products today unless I offer my clients a 35% discount, and knowing the historical pricing data, should I still sell it?" The agent runs a break-even analysis and comes back with a reasoned recommendation — hold for 3–6 months, here's the math on why, here's where storage costs start eating the upside. Then we add voice mode (now you can ask the agent for pricing recs from a coffee shop on your phone), and lock down guardrails to block jailbreaks, prompt injection, data leakage, and — because we're feeling fancy — profanity in responses. Part 2 — The app. With the agent done, we pivot to deploying a full AI chat application to Azure. From scratch. Using exactly five commands in Azure Cloud Shell: azd auth login git clone <repo> cd <folder> azd up azd down # (this one's for when you're done — kills everything to avoid surprise bills) That's it. The template handles the Container Apps setup, the architecture-aligned-to-Well-Architected-Framework stuff, all the boilerplate that usually eats half a sprint. By the end of the segment, there's a working AI chatbot running on a real Azure URL. We even pause the timer when we're just explaining things, so you know the 20-minute clock is honest about build time, not talk time. Why this format is more useful than another slide deck A few things this webinar shows that a written tutorial can't: The Foundry UI is super navigable. You watch someone do it. You see where the buttons are. You see what the leaderboard looks like when you're comparing GPT-5.3 Codex against Kimi K2.5 on a cost-to-quality chart. (Spoiler: Kimi wins this particular trio. Your mileage will vary depending on your workload.) The "no-stitching" claim is real. Models, data, agents, guardrails, deployment — all in one place. You don't need to leave Foundry to wire seven products together. The webinar makes that concrete by showing you the actual flow without cutting. Five commands really is five commands. This is the part people are most skeptical about until they see it. azd up does the work. The infrastructure provisioning, the container app, the AI service hookup — all of it. You can delete it just as fast. azd down tears everything back down. Useful when you're experimenting and don't want a $40 surprise on your Azure bill next month. What's on screen at the end By the 20-minute mark: A published AI agent named for the lumber business, with guardrails, voice mode enabled, ready to be called from Teams, Microsoft 365 Copilot, or any application via endpoint A separate AI chat application deployed to Azure Container Apps, with a live URL Logs, observability, the full Foundry control plane — all available out of the box And in the closing minutes, four very concrete next steps for what you do next if this sparked an idea for your own business — including Azure Accelerate (if you want Microsoft experts in the room with you), the partner network, and the Microsoft marketplace if you'd rather buy than build. Watch the recording The on-demand recording is available now. Block 20 minutes — that's literally all it takes — and ideally watch with your Azure portal open in another tab so you can follow along. If you're the kind of person who learns by doing, pause at the agent-building section and try it yourself in parallel. Foundry is free to explore; the agent we build in the webinar costs cents to run. → Watch the on-demand webinar A few things we'd love feedback on If you watch it, we'd genuinely love to know: Did the timer help or distract? (We thought it would feel gimmicky. It turned out to be the most-mentioned thing in early feedback.) What use case from your business would you want to see in the next one? We're picking the next demo problem from comments. Was the lumber thing weirdly compelling or were you just here for the Azure parts? Drop a comment, tag us, or grab a partner and try building your own version this week. The timer's reset. Your 20 minutes start whenever you press play. Want to go deeper than the webinar? Two companion reads: From Idea to Impact: How Growing Businesses Scale with Azure (five real customer stories with the full architectures) and AI Made Simple: 3 Practical Moves for Growing Businesses (the structured playbook for figuring out what to build first).