ApprovalML AI Workflow Generation
ApprovalML AI Workflow Generation
This module provides AI-powered workflow generation capabilities for creating ApprovalML YAML workflows from natural language descriptions.
Overview
The system consists of three main components:
- Syntax Reference (
syntax_reference.py) - Complete ApprovalML syntax documentation for AI training - AI Workflow Generator (
ai_workflow_generator.py) - Google Gemini integration for YAML generation - YAML Validator (
yaml_validator.py) - Comprehensive validation utilities
Quick Start
1. Environment Setup
Add your Google Gemini API key to the environment:
export GOOGLE_GEMINI_API_KEY="your-api-key-here"2. API Endpoints
The system provides two new API endpoints:
Generate Workflow
POST /services/v1/workflows/generateGenerate a complete ApprovalML workflow from natural language:
{
"description": "Create an expense approval workflow where managers approve amounts under $500, and finance team approves amounts over $500",
"workflow_type": "expense_approval",
"company_name": "Acme Corp",
"additional_context": "Include receipt upload requirement"
}Validate Workflow
POST /services/v1/workflows/validate-detailedPerform comprehensive validation of ApprovalML YAML:
{
"yaml_content": "name: 'Test Workflow'\n...",
"check_roles": true
}3. Python Usage
from app.services.ai_workflow_generator import (
create_ai_workflow_generator,
WorkflowGenerationRequest
)
from app.core.approvalml.yaml_validator import validate_workflow_yaml
# Generate workflow
generator = create_ai_workflow_generator()
request = WorkflowGenerationRequest(
description="Purchase request workflow with manager and finance approval",
available_roles=["manager", "finance_team", "purchasing_officer"]
)
result = generator.generate_workflow(request)
if result.success:
print("Generated YAML:")
print(result.workflow_yaml)
else:
print("Validation errors:")
for error in result.validation_errors:
print(f"- {error}")
# Validate existing YAML
yaml_content = """
name: "Test Workflow"
form:
fields:
- name: "amount"
type: "currency"
label: "Amount"
required: true
workflow:
approval:
name: "approval"
type: "decision"
approver: "manager"
on_approve:
end_workflow: true
"""
is_valid, issues = validate_workflow_yaml(yaml_content, ["manager", "finance_team"])
print(f"Valid: {is_valid}")
for issue in issues:
print(f"{issue.severity}: {issue.message}")Features
AI Generation Capabilities
- Natural Language Processing: Converts plain English descriptions into structured workflows
- Role Validation: Validates approvers against available company roles
- Business Logic: Generates realistic conditional routing and approval chains
- Form Generation: Creates appropriate form fields based on workflow type
- Error Handling: Provides detailed feedback on generation issues
Validation Features
- YAML Syntax: Validates proper YAML structure
- ApprovalML Structure: Ensures all required fields and proper nesting
- Field Types: Validates form field definitions and constraints
- Workflow Logic: Checks step routing and termination paths
- Role References: Validates approver roles and dynamic references
- Cross-Validation: Ensures consistency between form fields and workflow conditions
Supported Workflow Patterns
The AI can generate workflows for common business scenarios:
- Expense Approval: Travel, meals, office supplies with amount-based routing
- Purchase Requests: Multi-level approval with department-specific routing
- Leave Requests: Manager approval with HR notification
- IT Equipment: Technical approval with asset tracking
- Document Signing: Legal review with digital signatures
- Budget Approvals: Finance team with escalation paths
Architecture
Syntax Reference System
The syntax_reference.py module contains the complete ApprovalML specification that gets sent to the AI model. This ensures consistent, valid YAML generation.
Key components:
- Field type definitions with validation rules
- Step type specifications with required properties
- Approval type descriptions and behaviors
- Conditional expression syntax and operators
- Common patterns and best practices
AI Generator Integration
The ai_workflow_generator.py service integrates with Google Gemini using the Generative AI SDK:
- Prompt Engineering: Builds comprehensive prompts with syntax reference and role context
- Response Processing: Extracts and validates YAML from AI responses
- Error Recovery: Handles API failures and invalid generations gracefully
- Validation Integration: Uses the YAML validator for quality assurance
Validation Engine
The yaml_validator.py module provides multi-level validation:
- Syntax Level: YAML parsing and structure validation
- Schema Level: ApprovalML field and step type validation
- Business Level: Role availability and routing logic validation
- Cross-Reference: Consistency between form fields and workflow conditions
Examples
Simple Expense Workflow
Input:
"Manager approves expenses under $1000, finance team approves higher amounts"Generated Output:
name: "Expense Approval"
description: "Employee expense approval workflow"
form:
fields:
- name: "amount"
type: "currency"
label: "Expense Amount"
required: true
- name: "description"
type: "textarea"
label: "Description"
required: true
- name: "receipt"
type: "file_upload"
label: "Receipt"
required: true
workflow:
manager_approval:
name: "manager_approval"
type: "decision"
description: "Manager Review"
approver: "${requestor.manager}"
on_approve:
continue_to: "amount_check"
on_reject:
end_workflow: true
amount_check:
name: "amount_check"
type: "conditional_split"
description: "Amount-based Routing"
choices:
- conditions: "amount >= 1000"
continue_to: "finance_approval"
default:
continue_to: "processing"
finance_approval:
name: "finance_approval"
type: "decision"
description: "Finance Team Approval"
approver: "finance_team"
on_approve:
continue_to: "processing"
on_reject:
end_workflow: true
processing:
name: "processing"
type: "automatic"
description: "Process Expense"
on_complete:
notify_requestor: "Expense approved and processed"
end_workflow: trueComplex Purchase Request
The AI can generate sophisticated workflows with multiple approval paths, parallel approvals, and conditional routing based on department, amount, urgency, and other factors.
Error Handling
The system provides detailed error reporting at multiple levels:
- API Errors: Gemini API connectivity and quota issues
- Generation Errors: Invalid AI responses or YAML extraction failures
- Validation Errors: ApprovalML syntax and business logic violations
- Role Errors: Missing or invalid approver roles
Each error includes contextual information and suggested fixes when possible.
Performance Considerations
- Caching: Generated workflows can be cached to reduce API calls
- Validation: Client-side validation reduces server load
- Role Lookup: Employee roles are cached per company
- Async Processing: All operations are async-compatible
Security
- API Key Management: Gemini API keys stored securely in environment variables
- Input Validation: All user inputs validated before processing
- Role Authorization: Only company-specific roles are accessible
- Output Sanitization: Generated YAML is validated before storage
This system enables non-technical users to create sophisticated approval workflows through natural language, while maintaining the full power and flexibility of the ApprovalML specification.