Skip to main content
Post

#PowerPlatformTip 184: Gate Documents Before AI Builder – A Cheap Pre-Check That Saves Credits

#PowerPlatformTip 184: Gate Documents Before AI Builder – A Cheap Pre-Check That Saves Credits

TL;DR: AI Builder document processing charges you per page, whether the file is a real invoice or a 40-page terms-and-conditions attachment. Put a cheap gatekeeper in front of the model – check the file extension, the file size and a simple keyword match – and only call the AI model when the document actually looks like an invoice. Non-matching files are skipped without AI Builder cost.

💡 Challenge

Running multi-page documents through the AI Builder document processing model (invoice processing, receipt processing or a custom extraction model) consumes capacity for every page it processes. In a real mailbox-driven flow, most attachments are not the invoice you care about:

🔸 Signature images, logos and email banners saved as attachments.

🔸 Empty or near-empty scans from a misconfigured scanner.

🔸 Multi-page terms-and-conditions appendices with zero extractable business data.

🔸 Non-document files (.zip, .png, .ics) that shouldn’t hit an OCR model at all.

If you send all of that straight into the model, you pay for pages that never had any value – and your flow runs slower because of the heavier payloads.

✅ Solution

Add a fast, free pre-check in Power Automate before the AI Builder action. The metadata gates use only standard expressions and a Condition control – no premium services, no capacity cost. (The optional text check with a lightweight OCR pass in gate 3 is a different case: it adds its own processing, so count the pre-check and a possible full run together.)

🔸 Extension check – is this even a document type the model supports (.pdf, .png, .jpg)?

🔸 Size check – is the file big enough to be a real document, but not an implausibly huge attachment?

🔸 Keyword match – does the file name (or a light text extract) contain a signal like invoice, rechnung, bill or receipt?

Only files that pass all three gates are handed to the AI Builder model. Everything else is skipped and logged. This is the natural companion to #PowerPlatformTip 143 (thumbnail-first processing): #143 makes each accepted document cheaper to process, while this tip decides whether the document should be processed at all.

flowchart TD
    A[New email with attachment] --> B{Extension in<br/>pdf/png/jpg?}
    B -- No --> S[Skip &#43; log: unsupported type]
    B -- Yes --> C{File size<br/>within range?}
    C -- No --> S2[Skip &#43; log: too small/large]
    C -- Yes --> D{Name/text contains<br/>invoice / rechnung / bill?}
    D -- No --> S3[Skip &#43; log: not an invoice]
    D -- Yes --> E[Run AI Builder<br/>document processing]
    E --> F[Extract fields &#43; continue]

🔧 How It’s Done

  1. Trigger and loop the attachments 🔸 Use When a new email arrives (V3) with Include Attachments = Yes, then Apply to each over triggerOutputs()?['body/attachments'].

    🔸 Inside the loop you have the name, the content (ContentBytes) and the size of each attachment available. Property names are case-sensitive: use exactly the spelling you see in the trigger output of a real run (or pick the dynamic content), the expressions below use Name, ContentBytes and Size.

    🔸 The attachment content is already loaded at this point, so the gate prevents the model call, not the loading. File names can contain confidential details: restrict who can see the run history and prefer an internal reference over the full file name in the skip log.

  2. Gate 1 – file extension 🔸 Add a Condition (advanced mode, is equal to true). Use the expression: contains(createArray('.pdf','.png','.jpg','.jpeg'), concat('.', toLower(last(split(items('Apply_to_each')?['Name'], '.'))))) 🔸 split returns the extension without the dot, so it is prefixed with concat('.', ...) before comparing with the list. toLower makes Invoice.PDF and scan.PNG both resolve correctly.

    🔸 A file name without a dot (for example just pdf) makes last(split(...)) return the whole name, so .pdf would pass: also require contains(items('Apply_to_each')?['Name'], '.'). The extension check is a filter on the name, not proof of the content format.

  3. Gate 2 – file size 🔸 Use the attachment’s size field: items('Apply_to_each')?['Size']. It is a few hundred bytes above the real file size (in a test: +165 to +182 bytes), which does not matter for a range check. length(base64ToBinary(...)) fails here, because base64ToBinary() returns an object, not a string.

    🔸 Condition: greater than 20000 (skip tiny/blank scans) and less than 20000000 (skip absurdly large bundles). Tune both thresholds to your real document mix.

  4. Gate 3 – simple keyword match 🔸 Cheapest signal: match on the file name. or(contains(toLower(items('Apply_to_each')?['Name']),'invoice'), contains(toLower(items('Apply_to_each')?['Name']),'rechnung'), contains(toLower(items('Apply_to_each')?['Name']),'bill'), contains(toLower(items('Apply_to_each')?['Name']),'receipt')) 🔸 Need more certainty? Extract text cheaply first (for example the thumbnail-first trick from #143 or a lightweight OCR pass) and run the same contains() check against that text before committing to the full model.

    🔸 Combine the three gates with one and(...) condition, or nest the Conditions, so a file must pass all of them.

  5. Only now: call AI Builder 🔸 In the true branch of the combined gate, add Extract information from invoices (or your custom document processing model) and pass ContentBytes.

    🔸 In the false branch, do not call the model – append the file name and reason to an array variable or write a row to a log list.

  6. Log the skip/accept ratio 🔸 Track how many attachments were skipped vs. processed. This helps you tune the thresholds and keywords over time. The skip rate counts attachments while the model bills pages, so it doesn’t prove the savings by itself: compare model calls, pages and consumption before and after the change on a comparable inbox.

🎉 Result

The gate is a pre-selection of whole attachments: files that look like invoices by name, type and size reach the AI Builder model. Whole attachments that fail the gates, such as a signature image or a T&C appendix that arrives as its own small or wrongly named file, are filtered out before any AI Builder call, because the metadata gates use only standard expressions and a Condition control. The gate doesn’t read content: an empty file called invoice.pdf passes if it is large enough, a real invoice called scan001.pdf can be rejected, and pages inside an accepted PDF (such as T&C pages) are not removed. Check accepted and skipped files by sampling. You stop paying for whole attachments that fail the gates, and your flow runs faster because there are fewer AI calls. Measure the real saving by comparing processed pages and consumption (step 6), including any lightweight OCR pass you add.

🌟 Key Advantages

🔸 Capacity saved: non-invoice attachments never consume AI Builder document processing pages.

🔸 Zero added cost: extension, size and keyword checks run on standard connectors/expressions only.

🔸 Faster flows: fewer and lighter AI calls per run.

🔸 Tunable: thresholds and keywords adapt to your real document mix (invoice/rechnung/bill/receipt).

🔸 Composable: pairs cleanly with thumbnail-first processing (#143) – gate first, then process the accepted document cheaply.

🔸 Governance-friendly: the gate itself uses only standard expressions and the Condition control. The AI Builder action behind it has its own licensing and capacity rules.

⚠️ Watch Out

A file-name keyword match is a heuristic, not proof. If your senders don’t name files predictably (scan001.pdf), a name-only gate will wrongly skip real invoices. In that case, keep the extension and size gates strict but move the keyword check onto a cheap text extract (thumbnail/first-page OCR) instead of the file name, and always log skipped files so you can review false negatives and retune before they cost you a missed invoice.

🎥 Video Tutorial

🛠️ FAQ

1. Doesn’t this overlap with the thumbnail-first tip (#143)?

No – they solve different halves of the problem. #143 makes each accepted document cheaper to process (smaller payload, thumbnail before full PDF). This tip decides whether a document should be processed at all, filtering out non-invoices before any AI call. Use both: gate first, then thumbnail-first.

2. How do I read the file size inside the loop?

Use items('Apply_to_each')?['Size'], it is a few hundred bytes above the real file size, close enough for lower and upper bounds. If you need the exact byte count, derive it from the Base64 length: sub(div(mul(length(items('Apply_to_each')?['ContentBytes']),3),4),if(endsWith(items('Apply_to_each')?['ContentBytes'],'=='),2,if(endsWith(items('Apply_to_each')?['ContentBytes'],'='),1,0))). Compare it with a lower bound (skip blank scans) and an upper bound (skip oversized bundles). Start around 20 KB / 20 MB and adjust to your real files.

3. The file name is unreliable – can I still gate on content?

Yes. Keep the extension and size gates, but replace the name check with a cheap text signal: extract the first page or thumbnail text (see #143) and run the same contains(toLower(text),'invoice') / 'rechnung' check against that. It costs far less than a full multi-page model run and dramatically reduces false skips.

4. Where do I see how much AI Builder capacity I’m actually saving?

Check the AI Builder capacity and usage information in the Power Platform admin center before and after adding the gate, and combine it with your own skip/accept log so you can attribute the reduction to the pre-check.

🔸 #PowerPlatformTip 143 – Reduce AI Costs with Thumbnail-First Document Processing: once a document passes the gate, process only its thumbnail first and fall back to the full PDF only when needed.

🔸 #PowerPlatformTip 115 – AI OCR Models: choose the right OCR model (AI Builder vs. Azure Document Intelligence) for the documents that pass the gate.

🔸 #PowerPlatformTip 140 – Free Invoice OCR: build the invoice extraction pipeline this pre-check protects.

This tip is by Marcel Lehmann, Microsoft MVP (Business Applications) and founder of the Power Platform Academy, which runs free live workshops (in German). See the next free workshop dates (in German). For companies that want this implemented for them, see KMUpower: Power Platform consulting & automation for SMEs (DACH).

This post is licensed under CC BY 4.0 by the author.

Microsoft and the Power Platform product names (for example Power Apps, Power Automate, Copilot Studio) are trademarks of the Microsoft group of companies. This is an independent website. It is not operated, sponsored or endorsed by Microsoft.