Multi-level approval workflows are the backbone of decision-making in large enterprises, ensuring compliance, transparency, and accountability. However, manual approval chains are slow, error-prone, and difficult to audit. With advances in AI and workflow automation, it's now possible to build robust, scalable, and intelligent approval pipelines that adapt to complex business rules and organizational hierarchies.
As we covered in our complete guide to AI-powered approval workflow automation, this area deserves a deeper look—especially for organizations facing multi-tiered approval requirements. In this hands-on tutorial, you'll learn how to design, implement, and test an automated multi-level approval workflow using modern tools and AI-driven logic.
Prerequisites
- Technical Knowledge: Familiarity with Python, REST APIs, and basic workflow concepts.
-
Tools & Versions:
- Python 3.10+ (
python --version) - Docker 24+
- PostgreSQL 14+ (for workflow state storage)
- Node.js 18+ (for optional frontend/dashboard)
- OpenAI API Key (or Azure OpenAI, for AI decision logic)
- Git (for version control)
- Python 3.10+ (
- Accounts: Access to a cloud provider (AWS, Azure, or GCP) if deploying beyond local testing.
1. Define Your Multi-Level Approval Workflow
Before coding, map out the approval stages, decision criteria, and escalation paths. For this tutorial, we'll automate a 3-level purchase order approval:
- Manager Approval (Level 1)
- Finance Approval (Level 2, if amount > $10,000)
- Director Approval (Level 3, if amount > $100,000)
Each step can be auto-approved, rejected, or escalated, with AI providing recommendations based on policy and context.
Sample Workflow Diagram
(Imagine a diagram here: "Submit Request → Manager → Finance (conditional) → Director (conditional) → Finalize")
2. Scaffold Your Project
We'll use the Temporal workflow engine for orchestration, FastAPI for the API layer, and OpenAI GPT-4 for AI-driven decision support.
-
Clone the starter repo:
git clone https://github.com/yourorg/ai-multi-approval-workflow.git cd ai-multi-approval-workflow
-
Set up a virtual environment and install dependencies:
python3 -m venv venv source venv/bin/activate pip install fastapi[all] temporalio openai psycopg2-binary
-
Start Temporal (Docker):
docker compose up -d temporal
(Assumes
docker-compose.ymlis provided. If not, see Temporal's official docs.) -
Configure environment variables:
export OPENAI_API_KEY=sk-xxxxxxx export DATABASE_URL=postgresql://user:password@localhost:5432/approvaldb
3. Model the Approval Workflow in Temporal
Temporal lets you define workflows as Python classes. We'll create a workflow that routes requests through each approval level, invoking AI for recommendations.
-
Create a new file
workflows/approval_workflow.py:from temporalio import workflow, activity from typing import Dict @workflow.defn class MultiLevelApprovalWorkflow: @workflow.run async def run(self, request: Dict) -> str: result = await workflow.execute_activity( "activities.manager_approval", request, start_to_close_timeout=300, ) if not result["approved"]: return "Rejected by Manager" if request["amount"] > 10000: result = await workflow.execute_activity( "activities.finance_approval", request, start_to_close_timeout=300, ) if not result["approved"]: return "Rejected by Finance" if request["amount"] > 100000: result = await workflow.execute_activity( "activities.director_approval", request, start_to_close_timeout=300, ) if not result["approved"]: return "Rejected by Director" return "Approved"
4. Implement AI-Powered Approval Activities
Each approval activity can use AI to recommend (or auto-approve) based on policy, context, and past patterns. We'll use OpenAI's GPT-4 for this.
-
Create
activities/ai_approvals.py:import openai def ai_decision(prompt: str) -> dict: completion = openai.ChatCompletion.create( model="gpt-4", messages=[{"role": "system", "content": "You are an enterprise approval assistant."}, {"role": "user", "content": prompt}], max_tokens=100, temperature=0.2, ) decision = completion.choices[0].message["content"].strip().lower() if "approve" in decision: return {"approved": True, "reason": decision} else: return {"approved": False, "reason": decision} def manager_approval(request): prompt = f"Manager approval needed for a purchase order of ${request['amount']} by {request['requester']}. Policy: Approve if under $50,000 and no flagged issues." return ai_decision(prompt) def finance_approval(request): prompt = f"Finance approval needed for a purchase order of ${request['amount']} by {request['requester']}. Policy: Approve if budget allows and documentation is complete." return ai_decision(prompt) def director_approval(request): prompt = f"Director approval needed for a purchase order of ${request['amount']} by {request['requester']}. Policy: Approve only for strategic purchases." return ai_decision(prompt) -
Register these as Temporal activities:
from temporalio import activity @activity.defn def manager_approval(request): # ... as above @activity.defn def finance_approval(request): # ... as above @activity.defn def director_approval(request): # ... as above
5. Build the API Layer
Expose endpoints for submitting requests, checking status, and retrieving audit trails.
-
Create
main.py:from fastapi import FastAPI, HTTPException from temporalio.client import Client import uuid app = FastAPI() temporal = Client.connect("localhost:7233") @app.post("/submit") async def submit_request(request: dict): workflow_id = str(uuid.uuid4()) handle = await temporal.start_workflow( "workflows.approval_workflow.MultiLevelApprovalWorkflow.run", request, id=workflow_id, task_queue="approval-tasks" ) return {"workflow_id": workflow_id} @app.get("/status/{workflow_id}") async def get_status(workflow_id: str): handle = await temporal.get_workflow_handle(workflow_id) result = await handle.result() return {"status": result} -
Run the API server:
uvicorn main:app --reload
6. Store and Audit Approval Decisions
To meet enterprise compliance, log every decision in a PostgreSQL database.
-
Install SQLAlchemy:
pip install sqlalchemy asyncpg
-
Define a simple audit model (
models.py):from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, String, Integer, DateTime from datetime import datetime Base = declarative_base() class ApprovalAudit(Base): __tablename__ = "approval_audit" id = Column(Integer, primary_key=True) workflow_id = Column(String) level = Column(String) decision = Column(String) reason = Column(String) timestamp = Column(DateTime, default=datetime.utcnow) -
Log decisions inside each activity (pseudo-code):
def log_decision(workflow_id, level, decision, reason): # Insert into PostgreSQL using SQLAlchemy session pass def manager_approval(request): result = ai_decision(...) log_decision(request["workflow_id"], "manager", result["approved"], result["reason"]) return result
7. Test the Workflow End-to-End
Let's try a real approval scenario.
-
Submit a sample request:
curl -X POST "http://localhost:8000/submit" \ -H "Content-Type: application/json" \ -d '{"requester": "Alice", "amount": 120000, "purpose": "New ERP system"}' -
Check status:
curl "http://localhost:8000/status/{workflow_id}"The response should indicate whether the request was approved or rejected, and you can audit the chain in your database.
-
Review audit logs in PostgreSQL:
psql -U user -d approvaldb -c "SELECT * FROM approval_audit ORDER BY timestamp DESC;"
Common Issues & Troubleshooting
-
Temporal connection errors: Ensure Docker is running and the Temporal service is healthy. Check with
docker ps
. -
OpenAI API errors: Verify your API key and network access. Test with:
python -c "import openai; print(openai.Model.list())" -
Database connection issues: Double-check
DATABASE_URLand PostgreSQL credentials. - Long workflow execution times: Review activity timeouts and AI model response times. Consider using prompt engineering best practices to optimize.
- Audit logs not appearing: Ensure SQLAlchemy models are migrated and your logging code is called in each activity.
Next Steps
You've now built a multi-level, AI-powered approval workflow suitable for large enterprises. This foundation can be extended with:
- Dynamic approval chains based on org chart or policy rules
- Human-in-the-loop review for ambiguous cases
- Custom dashboards for tracking and analytics
- Integration with Slack, Teams, or email for notifications
- Advanced compliance automation (see our step-by-step compliance workflow guide)
For a broader strategy and more advanced scenarios, revisit our Ultimate Playbook for AI-Powered Approval Workflow Automation. If you want to dive deeper into prompt design for workflow automation, check out our Generative AI Prompt Engineering for Approval Workflow Automation article. For a focused tutorial on document approval, see How to Build an Automated Document Approval Workflow With AI.
Now you have a reproducible, scalable, and auditable multi-level approval workflow—ready for enterprise deployment.