Azure Functions vs AI for Document Automation in Microsoft 365: Stable Pipelines, Lower Risk
Billy Peralta
September 17, 2026 · 18 min read
Eryk Piasecki on Unsplash
Most organizations I work with are under pressure to automate document-heavy processes: invoices from a shared mailbox, HR forms in SharePoint, contracts in Teams, you name it.
The pattern is familiar: someone builds a quick Power Automate flow, adds an AI Builder model, wires it into SharePoint and the ERP, and the first demos look great.
Six months later, Finance is reporting missing invoices, IT is trying to debug three different flows with slightly different logic, AI costs are creeping up, and nobody is quite sure which model version is running in production.
This post is about avoiding that story.
We’ll walk through how to design predictable, cost-aware document automation in Microsoft 365, and how to make a deliberate choice between Azure Functions and AI services. We’ll look at a realistic invoice-processing scenario, a decision framework, and concrete architecture patterns that keep operations, governance, and compliance teams comfortable.
TL;DR
- Start with Azure Functions and deterministic logic for low-variability, high-risk, high-volume documents (e.g., standard invoices, regulated forms). Add AI only where the structure truly varies.
- Use AI Builder or Azure AI Document Intelligence when documents are unstructured or highly variable, but always wrap AI in a function or API layer that normalizes output, enforces schema validation, and centralizes logging.
- Design your document pipeline as a first-class application, not just a Power Automate flow: use service principals, Key Vault, Application Insights, and clear ownership.
- Model and monitor cost up front. AI charges are usually per page or per capacity unit; Azure Functions are consumption-based. Unplanned scale plus AI can blow through budgets if you don’t put guardrails in place.
Table of Contents
- Why This Matters (and Why Pipelines Break)
- Typical Microsoft 365 Document Automation Architecture
- Decision Framework: Azure Functions vs AI
- Real-World Scenario: Invoices from Shared Mailbox to SharePoint and ERP
- Common Mistakes and Risks
- Technical Recommendations
- Governance and Ownership: Avoiding Shadow AI
- Cost and Licensing Considerations
- Business Impact
- Practical Checklist
- Final Thoughts
Why This Matters (and Why Pipelines Break)
Document automation in Microsoft 365 looks deceptively simple:
- A document arrives (email, upload, scanner).
- A Power Automate flow triggers.
- An AI model extracts data.
- Data is written to SharePoint, Dataverse, or an ERP.
On a whiteboard, this fits in four boxes. In production, several things go wrong:
- Models change (or are retrained) and the output format shifts slightly, breaking downstream logic.
- AI confidence varies by document, but flows treat all results as equally reliable.
- Costs are opaque: nobody tied AI Builder or Azure AI usage back to volume scenarios, so a new supplier onboarding campaign doubles document volume and triples AI spend.
- Logs are scattered: some in Power Automate run history, some in custom connectors, some in Azure. Support teams can’t easily answer, “Did yesterday’s invoices process successfully?”
- Security and ownership are fuzzy: flows run under personal accounts; service accounts have broad rights; secrets are stored in environment variables instead of Key Vault.
The result: brittle, expensive automations that business stakeholders don’t fully trust.
From a governance perspective (and this comes up repeatedly in my Microsoft 365 consulting work), these pipelines become another form of shadow IT. They touch sensitive data, drive financial processes, and yet they’re not treated like real applications.
This is exactly where a cost-aware, architecture-first approach — using Azure Functions plus selective AI — makes a difference.
Typical Microsoft 365 Document Automation Architecture
Most document pipelines in Microsoft 365 follow some variation of this pattern:
-
Ingestion
- Shared mailbox (e.g., ap@contoso.com)
- Scanner to OneDrive or SharePoint
- Manual upload in a document library
-
Capture and storage
- Power Automate triggers on new email or new file.
- Attachments are saved to a specific SharePoint library or site.
- Metadata (vendor, department, status) is applied.
-
Processing and extraction
- Power Automate calls AI Builder models directly, or
- A custom connector calls Azure AI Document Intelligence, or
- An Azure Function processes the document via HTTP or queue trigger.
-
Business system integration
- Data is posted to ERP (via API, file drop, or RPA).
- Approvals are collected via Power Automate or Teams.
- Final documents live in SharePoint with retention and labels.
-
Monitoring and support
- Ideally: Application Insights, a dashboard, and alerting.
- In many orgs: checking Power Automate run history when someone complains.
The weak point is usually step 3. If AI is the first tool you reach for, you end up encoding core business logic in a model you can’t easily diff, unit test, or explain. And when something breaks, you don’t know whether it’s the model, the flow, or the downstream API.
Azure Functions give you a way to centralize and harden this processing layer, and to introduce AI in a controlled way.
Decision Framework: Azure Functions vs AI
To keep decisions pragmatic, I like a simple three-question model for document automation:
-
How variable is the document structure?
- Low: fixed layout, consistent positions (e.g., your own purchase order form).
- Medium: a few known formats (e.g., top 20 suppliers with stable templates).
- High: many suppliers, different formats, emails with embedded data.
-
What is the regulatory and business risk?
- High: financial posting, tax, payroll, HR records, contracts.
- Medium: internal reports, expense receipts.
- Low: internal routing or FYI documents.
-
What is the volume and tolerance for rework?
- High volume + low tolerance for manual fixes.
- Low volume + higher tolerance for manual intervention.
From there, you can map to patterns:
-
Pattern A: Deterministic first (Azure Functions), optional AI
- Low/medium variability, high risk, medium/high volume.
- Example: invoices from strategic suppliers, standardized HR forms.
- Use Functions with regex, simple parsing, or template-based extraction as the primary path, with AI as a fallback for exceptions.
-
Pattern B: AI inside a controlled envelope (Function or API)
- High variability, high volume, medium/high risk.
- Example: contracts from many external parties, varied invoice layouts.
- Use Azure AI Document Intelligence or AI Builder, but always behind a Function that normalizes output (JSON schema), validates, logs, and handles retries.
-
Pattern C: Light automation with AI Builder only
- Medium variability, low volume, low/medium risk.
- Example: low-volume expense receipts processed by a small finance team.
- AI Builder might be enough if you still implement governance (solutions, environment strategy, documented ownership).
The core rule: don’t let AI be the system of record for your business logic. Use it as a component inside a predictable pipeline, with Azure Functions as your “contract” between documents and downstream systems.
If you’re interested in a broader perspective on when automation should not be AI-first, you may find the post AI Can Do Everything, But Not Everything Should Be AI helpful as well.
Real-World Scenario: Invoices from Shared Mailbox to SharePoint and ERP
Let’s ground this with a concrete example that comes up often: automating AP invoice processing.
The context
- All vendor invoices arrive at
ap@contoso.com. - Attachments should be stored in a SharePoint library
AP Invoices. - Data should be pushed into the ERP (vendor, invoice number, date, total, tax, cost center).
- Finance wants a clear exception queue and auditable logs.
Option 1: AI-heavy design
A typical first attempt might look like this:
- Power Automate triggers on new email in
ap@contoso.com. - For each PDF attachment:
- Save to SharePoint
AP Invoices. - Call an AI Builder Invoice Processing model.
- Use outputs directly in the flow to:
- Create or update a SharePoint list item.
- Call an ERP API.
- Save to SharePoint
- If AI confidence is below a threshold, send an approval to AP.
What goes wrong in practice:
- AI Builder model changes cause slight field name or structure differences; Power Automate expressions break.
- Some invoices are scanned images with poor quality; model confidence drops, or values are misread.
- Finance adds new suppliers with very different formats; performance degrades until model is retrained.
- IT can’t easily measure how many invoices failed vs succeeded; the only visibility is Power Automate run history.
- AI Builder capacity runs hot at month-end; flows get throttled.
The result: irritated AP teams, surprise AI costs, and low trust in the automation.
Option 2: Azure Functions–centric design (with optional AI)
Now let’s redesign this with Azure Functions as the processing core.
-
Power Automate still triggers on new email in
ap@contoso.com. -
For each PDF attachment:
- Save to SharePoint
AP Invoices. - Add a queue message to an Azure Storage queue (e.g.,
ap-invoices) with:- File URL
- Vendor ID or email domain
- Correlation ID
- Save to SharePoint
-
An Azure Function (queue-triggered) processes each message:
- Downloads the file using Microsoft Graph (via managed identity or service principal).
- Determines the extraction strategy:
- For known vendors with fixed layouts: use deterministic parsing (text extraction + regex or coordinate-based parsing).
- For unknown or variable formats: call Azure AI Document Intelligence.
- Normalizes all results into a single JSON schema:
{ "InvoiceId": "...", "VendorId": "...", "InvoiceNumber": "...", "InvoiceDate": "2025-01-31", "Total": 1234.56, "Currency": "USD", "Tax": 123.45, "CostCenter": "IT-OPS", "Confidence": 0.98, "Source": "Deterministic" | "AI", "CorrelationId": "..." } - Validates the JSON against a schema (required fields, amount > 0, etc.).
- Logs results and metrics to Application Insights.
- Writes results to a central “Invoice Processing” table (SQL, Dataverse, or Storage).
- Places an output message on a
ap-invoices-processedqueue.
-
A second Power Automate flow triggers on
ap-invoices-processedand:- Creates or updates a SharePoint list item.
- Calls the ERP API.
- Routes low-confidence cases to a Teams-based approval.
Why this works better:
- Deterministic first: known layouts are handled by tested code. AI is used selectively for true variability.
- Stable contract: downstream systems only see one JSON schema, regardless of source.
- Monitoring: Application Insights shows success/failure rates, per-vendor error rates, and AI vs deterministic usage.
- Cost control: you can measure how many documents actually hit the AI service and adjust thresholds.
- Governance: the Function app, queue, and flows are owned by a team, deployed from source control, and documented.
AI and Azure Functions together
In this pattern, AI isn’t gone; it’s contained:
- Azure AI Document Intelligence or AI Builder is invoked from within Azure Functions when needed.
- AI output is normalized, validated, and tagged with metadata (source, confidence) before anything touches ERP.
- If Microsoft updates AI models, your Function remains the stable boundary.
If you want to go deeper on AI vs deterministic automation trade-offs in Microsoft 365, I also break this down in When Not to Use AI in Microsoft 365 Automation.
Common Mistakes and Risks
Here are patterns I see repeatedly in real projects:
-
Starting with AI for everything
- Treating AI as the default leads to overcomplicated solutions where simple parsing and rules would be more predictable.
- Risk: high cost, low explainability, and fragile flows.
-
No schema or validation layer
- Directly wiring AI outputs into Power Automate expressions means downstream logic is tightly coupled to model output.
- Risk: model updates or field renames silently break flows.
-
Relying on personal accounts for automation
- Flows and Functions use user identities for SharePoint or ERP access.
- Risk: automations break when people change roles or leave; security teams dislike broad privileges.
-
Running everything in the default Power Platform environment
- Dev, test, and prod flows live together; governance is minimal.
- Risk: hard to manage change control, and “test” flows end up processing real data.
-
No centralized logging or metrics
- Teams rely on Power Automate run history and ad hoc checks.
- Risk: you only find out about failures when business users complain.
-
Ignoring cost modeling
- Nobody estimates AI Builder capacity or Azure AI page processing under peak load.
- Risk: surprise invoices or throttling at critical periods.
-
Embedding secrets everywhere
- Connection strings and API keys live in Power Automate environment variables or Function app settings without Key Vault.
- Risk: difficult secret rotation and potential exposure.
-
No clear owner or support model
- Flows are “owned” by a single enthusiastic builder, not a team.
- Risk: automation becomes unmaintained shadow IT.
For more on the support and ownership angle, Power Automate Governance for SharePoint: What Breaks When Owners Leave dives deeper into the failure patterns.
Technical Recommendations
Pattern: Power Automate + HTTP Azure Function
A common pattern is for Power Automate to send a document to an HTTP-triggered Azure Function and get a structured JSON response.
Azure Function (C#) – HTTP trigger for document processing
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
public static class ProcessInvoice
{
[FunctionName("ProcessInvoice")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("ProcessInvoice function triggered.");
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
// Expecting base64 file content and fileName from Power Automate
string base64File = data.fileContent;
string fileName = data.fileName;
byte[] fileBytes = System.Convert.FromBase64String(base64File);
// TODO: perform deterministic parsing or call AI service here
// For demo purposes, return a simple JSON structure
var result = new
{
InvoiceNumber = "INV-12345",
VendorId = "Contoso-001",
Total = 1234.56,
Currency = "USD",
Confidence = 0.99,
Source = "Deterministic"
};
return new OkObjectResult(result);
}
}
In Power Automate, the pattern is:
- Trigger on When a file is created in a SharePoint library.
- Use Get file content to retrieve the file.
- Add an HTTP action:
- Method: POST
- URI: Function URL
- Headers:
Content-Type: application/json - Body:
{ "fileName": "@{triggerOutputs()['headers']['x-ms-file-name']}", "fileContent": "@{base64(body('Get_file_content'))}" }
- Use Parse JSON with the expected schema of the Function’s response.
- Continue with approvals or system integration.
This pattern keeps Power Automate relatively thin and pushes complex parsing logic into a reusable, testable Function.
Pattern: Queue-Based, Asynchronous Processing
For higher-volume scenarios, prefer asynchronous processing:
- Use Power Automate to enqueue a message with minimal metadata.
- Let an Azure Function (queue-triggered) handle heavy work.
- Write results to a queue or table that another flow or application consumes.
Benefits:
- Natural retry behavior for transient failures.
- Reduced risk of Power Automate timeouts.
- Easier throttling and scaling via Function host configuration.
OCR and Extraction Options
You have several options for turning documents into structured data:
-
Simple text extraction + regex (deterministic)
- For born-digital PDFs where text is selectable.
- Use libraries (e.g., PDF processing libraries in your Function) to extract text, then apply regex to capture key fields.
- Pros: predictable, cheap, easy to test; Cons: brittle if layouts change.
-
Azure AI Document Intelligence (formerly Form Recognizer)
- Best for high variability or mixed structured/semi-structured documents.
- Use prebuilt Invoice/Receipt/ID models or train custom models.
- Called from Azure Functions using REST or SDK, then normalized.
- Pros: strong extraction for complex docs; Cons: per-page cost, requires model lifecycle management.
-
AI Builder in Power Automate
- Integrated directly with Power Automate.
- Good for low/medium volume scenarios where you want to keep everything in the Power Platform.
- Pros: no-code authoring, quick to prototype; Cons: environment-scoped, capacity-based licensing, less control over output contracts.
-
Generative AI on top of deterministic extraction
- For summarization or classification (e.g., “what is this document about?”), not core field extraction.
- Use Azure OpenAI behind a Function if needed.
If you’re primarily working with images and want a step-by-step AI Builder example, see Extract Text from Images with Power Automate AI Builder and Upload to SharePoint.
Validation, Error Handling, and Logging
Regardless of extraction method, you should:
-
Validate against a JSON schema
- Use a schema in your Function to enforce required fields and formats.
- Reject or route to exceptions queue when validation fails.
-
Tag records with correlation IDs
- Generate a correlation ID per document and pass it through all logs, queues, and downstream systems.
-
Use Application Insights
- Track custom metrics: number of documents processed, failures per vendor, AI vs deterministic usage.
- Configure alerts for sustained failure rates or anomalies.
-
Implement dead-letter queues
- For messages that fail after N retries, move them to a dead-letter queue that support can review.
A small amount of upfront logging design saves many hours of production debugging.
Security, Identity, and Secrets
From a governance and security standpoint:
- Use managed identities or service principals for Azure Functions calling SharePoint/Graph.
- Grant least-privilege access (e.g., only to the specific document libraries needed).
- Store secrets in Azure Key Vault, not inline in Function app settings or Power Automate environment variables.
- Avoid using human identities for automation. Where Power Automate must use a connection, align with your organization’s service account standards.
If you’re building more advanced governance automation around SharePoint and Microsoft 365, Microsoft Graph Automation for SharePoint Governance: Where to Start Safely covers patterns for managing permissions and policies safely.
Governance and Ownership: Avoiding Shadow AI
Document pipelines that touch invoices, HR forms, and contracts should be treated as core line-of-business applications, not side projects.
Key governance practices:
-
Environment strategy
- Separate Dev/Test/Prod environments in the Power Platform.
- Use solutions to package and deploy flows and connections.
-
Ownership and support
- Assign a owning team (e.g., “Finance Automation”) with at least two named contacts.
- Maintain a runbook: where logs live, how to reprocess failures, who to contact.
-
Automation catalog
- Maintain a SharePoint list of document automations with fields like: business owner, technical owner, environments, connected systems, data classification.
-
Alignment with SharePoint governance
- Ensure document libraries used for automation follow your existing SharePoint governance patterns: sensitivity labels, retention, permissions.
-
Copilot and AI-readiness
- Well-structured, labeled document libraries and predictable pipelines make it easier to keep Copilot access safe and auditable.
- If you’re starting to roll out Copilot, aligning automation with your broader Microsoft 365 Copilot readiness workstream is important.
In many organizations, this is the point where we formalize document automation as part of a broader Microsoft 365 Consulting engagement: architecture review, environment strategy, and governance processes.
Cost and Licensing Considerations
Cost is often the quiet failure mode for AI-heavy automation.
Key considerations:
-
AI Builder vs Azure AI Document Intelligence
- AI Builder uses capacity-based licensing; Azure AI Document Intelligence typically charges per page.
- For steady, moderate volumes with strong Power Platform skills, AI Builder can be reasonable.
- For higher volumes or more advanced scenarios, Azure AI may be more cost-effective — especially when you can offload many documents to deterministic parsing.
-
Azure Functions consumption
- Azure Functions on a consumption plan bill based on execution time and resources.
- Document parsing tends to be CPU-bound but short-lived; this is usually cost-effective.
-
Guardrails and forecasting
- Estimate costs for low, medium, and high volume scenarios.
- Use Azure Cost Management budgets and alerts for AI services and Function resources.
- Consider feature flags or configuration to adjust AI use (e.g., “only use AI for unknown vendors”).
-
Licensing alignment
- Ensure Power Platform and Microsoft 365 licenses cover your use of premium connectors, AI Builder, and environments.
Skipping cost modeling doesn’t just risk higher bills; it often ends with business stakeholders losing confidence when “automation” becomes more expensive than the manual process it replaced.
Business Impact
Designing document automation with a clear Azure Functions vs AI strategy has tangible business benefits:
-
Finance and operations
- Fewer missing or duplicate invoices; clear exception queues.
- Faster month-end close because automation is predictable.
-
IT and support
- Less time spent spelunking through Power Automate run history.
- One set of logs and dashboards (Application Insights) to quickly answer, “Did everything run last night?”
-
Security and compliance
- Document flows are auditable: who processed what, when, and how.
- Sensitive data stays in governed SharePoint libraries with appropriate retention and sensitivity labels.
-
Architecture and future-readiness
- Reusable patterns for other processes: HR onboarding, contract routing, policy acknowledgements.
- Pipelines that are already structured and monitored are easier to adapt when new AI capabilities (like SharePoint or Teams agents) arrive.
The cost of not planning shows up later as cleanup projects, replatforming, and retraining users when you replace brittle automations.
Practical Checklist
Use this checklist when planning a new document automation project in Microsoft 365:
-
Clarify document types and variability
- List document sources, formats, and whether they are born-digital or scanned.
-
Classify data and risk
- Identify PII, financial, or regulated data; align with your data classification and retention policies.
-
Define a target JSON schema
- Agree on a single structured output for each document type (e.g., invoice fields) before building anything.
-
Decide deterministic vs AI approach
- For each document type, choose: deterministic-only, AI-only, or deterministic-first with AI fallback.
-
Design the pipeline architecture
- Ingestion (mailbox/library) → Power Automate → queue/HTTP → Azure Function → storage/ERP.
- Decide which steps run synchronously vs asynchronously.
-
Plan security and identity
- Choose service principals or managed identities for Function access to Microsoft 365 and downstream systems.
- Restrict SharePoint/OneDrive access to specific libraries.
-
Implement logging and monitoring
- Configure Application Insights for Function apps.
- Define dashboards and alerts (failure rate, AI usage, vendor-specific issues).
-
Implement error handling and retries
- Use dead-letter queues and exception handling paths.
- Design a manual reprocessing mechanism.
-
Model cost scenarios
- Estimate AI Builder/Azure AI usage and Functions compute under peak load.
- Set budgets and alerts in Azure.
-
Align with Power Platform governance
- Use managed solutions, non-default environments, and documented deployment pipelines.
-
Document ownership and support
- Assign business and technical owners; create a simple runbook.
-
Test with real-world samples
- Include bad scans, edge cases, and new supplier formats.
-
Plan lifecycle and evolution
- Define how you’ll onboard new document types and update models/functions without breaking production.
Final Thoughts
AI will continue to get better at reading documents. That doesn’t mean every document pipeline in Microsoft 365 should be AI-first.
For many high-value processes — invoices, HR forms, contracts — the winning pattern is deterministic where possible, AI where necessary, wrapped in a stable, testable Azure Functions layer.
If you’re looking at your current Power Automate flows and wondering whether they’ll scale, or you’re about to start a new document automation initiative and want to avoid expensive trial-and-error, this is a good moment to step back and design the architecture deliberately.
If you’d like a second set of eyes on your document automation plans or an existing implementation, I offer architecture and governance reviews as part of my Microsoft 365 Consulting services.
We can walk through your pipelines, decide where Azure Functions makes more sense than AI, set up proper monitoring, and ensure your automations are secure, auditable, and ready for the next wave of Microsoft 365 capabilities.
You can reach out via the Microsoft 365 Consulting page or the contact form when you’re ready to review your document automation roadmap.
Need help applying this in a real Microsoft 365 environment?
I help organizations turn technical fixes into maintainable SharePoint, SPFx, and Power Platform solutions that internal teams can support.
Free SharePoint planning resource
Planning a SharePoint migration or governance cleanup?
Download the SharePoint Migration & Governance Readiness Checklist to review migration scope, permissions, governance, Teams/OneDrive strategy, retention, and Copilot readiness.
Download the ChecklistBilly Peralta
SharePoint & Microsoft 365 Specialist • 16+ Years Experience
If you have questions about your SharePoint environment, feel free to reach out.
Need help applying this in a real Microsoft 365 environment?
I help organizations turn technical fixes into maintainable SharePoint, SPFx, and Power Platform solutions that internal teams can support.