Step-by-step deployment guide to implement AI automation in your existing Compliance Scorecard installation. Start with $0 budget, scale strategically.
Deploy 70% automation with zero AI costs - immediate ROI
Add required tables for AI tracking and caching
# Navigate to your Laravel project
cd /path/to/polygon-be
# Create the migration files
php artisan make:migration create_ai_usage_logs_table
php artisan make:migration create_compliance_cache_table
# Copy the migration code from the implementation guide
# Then run migrations
php artisan migrate
# Verify tables were created
php artisan tinker
DB::select('SHOW TABLES LIKE "ai_usage_logs"');
DB::select('SHOW TABLES LIKE "compliance_cache"');
Test migrations on staging environment first. These tables are new additions and won't affect existing data.
Add the AI automation classes to your Laravel application
# Create directory structure
mkdir -p app/Services/AI
mkdir -p app/Services/RulesEngine
mkdir -p app/Services/RulesEngine/Rules
mkdir -p app/Services/Caching
# Copy classes from implementation guide:
# 1. SmartComplianceRouter.php → app/Services/
# 2. ComplianceRulesEngine.php → app/Services/RulesEngine/
# 3. UserAccessRules.php → app/Services/RulesEngine/Rules/
# 4. AssetInventoryRules.php → app/Services/RulesEngine/Rules/
# 5. ComplianceCacheService.php → app/Services/Caching/
# Create the interface
cat > app/Services/RulesEngine/Rules/ComplianceRuleInterface.php << 'EOF'
Configure the application for AI automation
# Add to .env file
cat >> .env << 'EOF'
# AI Configuration (Phase 1 - FREE)
AI_ENABLED=true
AI_DAILY_BUDGET=0
AI_MONTHLY_BUDGET=0
AI_ADMIN_EMAIL=your-email@company.com
# Processing Thresholds
AI_COMPLEXITY_THRESHOLD_BASIC=0.3
AI_COMPLEXITY_THRESHOLD_ADVANCED=0.7
# Cache Settings
COMPLIANCE_CACHE_TTL=3600
COMPLIANCE_CACHE_DRIVER=database
EOF
# Create AI configuration file
cat > config/ai.php << 'EOF'
env('AI_ENABLED', false),
'daily_budget' => env('AI_DAILY_BUDGET', 0),
'monthly_budget' => env('AI_MONTHLY_BUDGET', 0),
'admin_email' => env('AI_ADMIN_EMAIL'),
'thresholds' => [
'basic' => env('AI_COMPLEXITY_THRESHOLD_BASIC', 0.3),
'advanced' => env('AI_COMPLEXITY_THRESHOLD_ADVANCED', 0.7),
],
'cache' => [
'ttl' => env('COMPLIANCE_CACHE_TTL', 3600),
'driver' => env('COMPLIANCE_CACHE_DRIVER', 'database'),
],
'models' => [
'basic' => 'gpt-3.5-turbo',
'advanced' => 'gpt-4',
],
'pricing' => [
'gpt-3.5-turbo' => 0.002,
'gpt-4' => 0.03,
],
];
EOF
Register AI services in Laravel's service container
# Create AI Service Provider
php artisan make:provider AIServiceProvider
# Replace contents with:
cat > app/Providers/AIServiceProvider.php << 'EOF'
app->singleton(ComplianceCacheService::class, function ($app) {
return new ComplianceCacheService();
});
// Register rules engine
$this->app->singleton(ComplianceRulesEngine::class, function ($app) {
return new ComplianceRulesEngine();
});
// Register smart router (Phase 1: no AI service needed)
$this->app->singleton(SmartComplianceRouter::class, function ($app) {
return new SmartComplianceRouter(
$app->make(ComplianceRulesEngine::class),
null, // No AI service in Phase 1
$app->make(ComplianceCacheService::class)
);
});
}
}
EOF
# Register the provider in config/app.php
# Add to 'providers' array:
# App\Providers\AIServiceProvider::class,
Connect AI automation to your existing assessment processing
collectEvidenceData($question);
// Manual analysis and scoring...
// After (AI-powered processing):
use App\Services\SmartComplianceRouter;
class AssessmentService
{
private SmartComplianceRouter $aiRouter;
public function __construct(SmartComplianceRouter $aiRouter)
{
$this->aiRouter = $aiRouter;
}
public function processEvidence(string $questionId): array
{
$question = AssessmentEventsQuestion::find($questionId);
// Collect evidence data (your existing logic)
$evidenceData = $this->collectEvidenceData($question);
// NEW: Route to AI processing
$analysis = $this->aiRouter->processEvidenceRequest($questionId, $evidenceData);
// Update question with AI results
$question->update([
'auditor_notes' => $analysis['summary'],
'auditor_conformity_mark' => $analysis['conformity_mark'],
'selected_option_id' => $this->getOptionByScore($analysis['compliance_score']),
'responsibility' => 'tool', // Automated processing
'evidence_location' => json_encode($evidenceData),
'question_notes' => implode("\n", $analysis['recommendations'] ?? [])
]);
return $analysis;
}
}
Test the rules engine with existing assessment data
# Test the implementation
php artisan tinker
# Test 1: Basic router functionality
$router = app(App\Services\SmartComplianceRouter::class);
$testData = [
'users' => [
['name' => 'John Doe', 'role' => 'admin', 'last_login' => '2025-01-15'],
['name' => 'Jane Smith', 'role' => 'user', 'last_login' => '2025-01-20']
]
];
$result = $router->processEvidenceRequest('test-question-id', $testData);
dd($result);
# Test 2: Check database logging
DB::table('ai_usage_logs')->get();
# Test 3: Verify caching
use App\Services\Caching\ComplianceCacheService;
$cache = app(ComplianceCacheService::class);
$cache->put('test-key', ['test' => 'data'], 3600);
$cached = $cache->get('test-key');
dd($cached);
Add strategic AI processing for complex analysis
Configure OpenAI integration for strategic AI usage
# Install OpenAI PHP client
composer require openai-php/laravel
# Publish configuration
php artisan vendor:publish --provider="OpenAI\Laravel\ServiceProvider"
# Add OpenAI credentials to .env
cat >> .env << 'EOF'
# OpenAI Configuration
OPENAI_API_KEY=your_openai_api_key_here
OPENAI_ORGANIZATION=your_organization_id_here
# Update AI Budget for Phase 2
AI_DAILY_BUDGET=16.67
AI_MONTHLY_BUDGET=500
EOF
# Test OpenAI connection
php artisan tinker
$client = OpenAI::client(env('OPENAI_API_KEY'));
$response = $client->chat()->create([
'model' => 'gpt-3.5-turbo',
'messages' => [['role' => 'user', 'content' => 'Hello, this is a test.']],
'max_tokens' => 10
]);
echo $response->choices[0]->message->content;
Add the AI analysis classes and update service provider
# Copy AI service classes from implementation guide:
# 1. AIAnalysisService.php → app/Services/AI/
# 2. AICostTracker.php → app/Services/AI/CostMonitoring/
# Update service provider to include AI services
cat > app/Providers/AIServiceProvider.php << 'EOF'
app->singleton(OpenAIClient::class, function ($app) {
return OpenAI::client(config('openai.api_key'));
});
// Register cost tracker
$this->app->singleton(AICostTracker::class, function ($app) {
return new AICostTracker();
});
// Register AI analysis service
$this->app->singleton(AIAnalysisService::class, function ($app) {
return new AIAnalysisService(
$app->make(OpenAIClient::class),
$app->make(AICostTracker::class)
);
});
// Register cache service
$this->app->singleton(ComplianceCacheService::class, function ($app) {
return new ComplianceCacheService();
});
// Register rules engine
$this->app->singleton(ComplianceRulesEngine::class, function ($app) {
return new ComplianceRulesEngine();
});
// Register smart router with AI support
$this->app->singleton(SmartComplianceRouter::class, function ($app) {
return new SmartComplianceRouter(
$app->make(ComplianceRulesEngine::class),
$app->make(AIAnalysisService::class), // Now includes AI
$app->make(ComplianceCacheService::class)
);
});
}
}
EOF
Configure real-time cost tracking and alerts
# Create mail notification for budget alerts
php artisan make:mail AIBudgetAlert
# Create the alert email template
cat > app/Mail/AIBudgetAlert.php << 'EOF'
subject('AI Budget Alert - ' . round(($this->currentSpend / $this->dailyBudget) * 100) . '% Used')
->view('emails.ai-budget-alert')
->with([
'percentage' => round(($this->currentSpend / $this->dailyBudget) * 100),
'currentSpend' => $this->currentSpend,
'dailyBudget' => $this->dailyBudget,
'remainingBudget' => $this->dailyBudget - $this->currentSpend
]);
}
}
EOF
# Create email template
mkdir -p resources/views/emails
cat > resources/views/emails/ai-budget-alert.blade.php << 'EOF'
AI Budget Alert
Your AI processing budget is at {{ $percentage }}% for today.
- Current Spend: ${{ number_format($currentSpend, 2) }}
- Daily Budget: ${{ number_format($dailyBudget, 2) }}
- Remaining: ${{ number_format($remainingBudget, 2) }}
The system will automatically fallback to rules-based processing if budget is exceeded.
EOF
Validate AI processing and cost tracking
# Test AI analysis
php artisan tinker
# Test basic AI analysis
$router = app(App\Services\SmartComplianceRouter::class);
$complexData = [
'users' => [/* complex user data */],
'policies' => [/* policy documents */],
'complexity_indicators' => ['multiple_frameworks', 'risk_analysis_required']
];
$result = $router->processEvidenceRequest('complex-question-id', $complexData);
dd($result);
# Check cost tracking
DB::table('ai_usage_logs')->orderBy('created_at', 'desc')->limit(5)->get();
# Test budget monitoring
$costTracker = app(App\Services\AI\CostMonitoring\AICostTracker::class);
$costTracker->logUsage('test_operation', 1.50, 750); // Simulate $1.50 cost
Complete AI automation with advanced features
Activate GPT-4 processing and advanced analysis capabilities
# Update environment for full AI capability
cat >> .env << 'EOF'
# Phase 3: Full AI Budget
AI_DAILY_BUDGET=50
AI_MONTHLY_BUDGET=1500
# Enable advanced features
AI_ADVANCED_ENABLED=true
AI_GPT4_ENABLED=true
# Advanced processing thresholds
AI_EXECUTIVE_SUMMARY_ENABLED=true
AI_PREDICTIVE_ANALYSIS_ENABLED=true
EOF
# Update AI configuration
cat >> config/ai.php << 'EOF'
'advanced_features' => [
'enabled' => env('AI_ADVANCED_ENABLED', false),
'gpt4_enabled' => env('AI_GPT4_ENABLED', false),
'executive_summaries' => env('AI_EXECUTIVE_SUMMARY_ENABLED', false),
'predictive_analysis' => env('AI_PREDICTIVE_ANALYSIS_ENABLED', false),
],
EOF
Add real-time monitoring for AI processing performance
# Create monitoring controller
php artisan make:controller AIMonitoringController
# Create monitoring routes
cat >> routes/web.php << 'EOF'
// AI Monitoring Dashboard (admin only)
Route::middleware(['auth', 'admin'])->group(function () {
Route::get('/admin/ai-monitoring', [AIMonitoringController::class, 'dashboard']);
Route::get('/admin/ai-usage-stats', [AIMonitoringController::class, 'usageStats']);
Route::post('/admin/ai-budget-update', [AIMonitoringController::class, 'updateBudget']);
});
EOF
# Create monitoring view
mkdir -p resources/views/admin
cat > resources/views/admin/ai-monitoring.blade.php << 'EOF'
@extends('layouts.app')
@section('content')
AI Processing Monitoring
${{ number_format($todaySpend, 2) }}
Today's Spend
Budget: ${{ number_format($dailyBudget, 2) }}
{{ $totalRequests }}
Requests Today
{{ $aiPercentage }}% AI, {{ 100 - $aiPercentage }}% Rules
{{ $avgResponseTime }}ms
Avg Response Time
{{ $cacheHitRate }}%
Cache Hit Rate
@endsection
EOF
Deploy to production with zero-downtime strategy
# Production deployment checklist
# 1. Backup current database
mysqldump -u root -p your_database > backup_$(date +%Y%m%d_%H%M%S).sql
# 2. Deploy code changes
git checkout production
git pull origin main
# 3. Install dependencies
composer install --optimize-autoloader --no-dev
# 4. Run migrations
php artisan migrate --force
# 5. Clear and cache configs
php artisan config:clear
php artisan config:cache
php artisan route:cache
php artisan view:cache
# 6. Restart services
sudo supervisorctl restart laravel-worker:*
sudo service nginx restart
sudo service php8.3-fpm restart
# 7. Test AI functionality
php artisan tinker
$router = app(App\Services\SmartComplianceRouter::class);
// Run test with real data
# 8. Monitor logs
tail -f storage/logs/laravel.log
Error: "Rate limit exceeded"
Solution: Implement exponential backoff in AI service, reduce concurrent requests
Error: AI processing disabled mid-day
Solution: Check daily budget settings, increase budget or optimize prompt efficiency
Issue: Low cache hit rates
Solution: Tune cache TTL settings, implement better cache key strategies
# Check AI service health
php artisan tinker
app(App\Services\SmartComplianceRouter::class);
# Monitor real-time costs
watch -n 5 'php artisan tinker --execute="
echo \"Today: $\" . DB::table(\"ai_usage_logs\")
->whereDate(\"created_at\", today())
->sum(\"cost\");
"'
# Test cache performance
php artisan cache:clear
php artisan tinker --execute="
\$cache = app(\App\Services\Caching\ComplianceCacheService::class);
\$cache->put('test', ['data'], 3600);
dd(\$cache->get('test'));
"
# Check queue processing
php artisan queue:work --verbose
# Monitor application logs
tail -f storage/logs/laravel.log | grep -E "(AI|ERROR)"