π§ AI Implementation Patterns¶
π― Purpose¶
Practical patterns and code examples for implementing AI features efficiently in GetCimple's compliance and governance platform.
π Pattern 1: WhatsApp AI Assistan¶
When to use: Answering compliance questions, providing quick guidance
Implementation: n8n workflow + Claude API
Example workflow:
{
"nodes": [
{
"name": "WhatsApp Trigger",
"type": "WhatsApp Business",
"parameters": {
"webhook": "incoming_message"
}
},
{
"name": "Claude Analysis",
"type": "HTTP Request",
"parameters": {
"method": "POST",
"url": "https://api.anthropic.com/v1/messages",
"headers": {
"x-api-key": "{{$env.ANTHROPIC_API_KEY}}"
},
"body": {
"model": "claude-3-haiku-20240307",
"max_tokens": 500,
"messages": [
{
"role": "system",
"content": "You are a cybersecurity compliance assistant.\nProvide actionable guidance on Essential Eight."
},
{
"role": "user",
"content": "{{$json.message.text}}"
}
]
}
}
},
{
"name": "Send Response",
"type": "WhatsApp Business",
"parameters": {
"operation": "sendMessage",
"to": "{{$json.from}}",
"message": "{{$node['Claude Analysis'].json.content[0].text}}"
}
}
]
}
Resource considerations: ~$0.01 per question, 2-3 second response time
π Pattern 2: Automated Report Generation¶
When to use: Weekly compliance summaries, board reports
Implementation: Scheduled n8n workflow + Claude for analysis
Key components:
// Data aggregation function
function aggregateComplianceData(tasks, timeframe) {
return {
completed: tasks.filter((t) => t.status === 'completed').length,
overdue: tasks.filter((t) => t.dueDate < new Date()).length,
riskLevel: calculateRiskScore(tasks),
trends: analyzeWeeklyTrends(tasks, timeframe),
}
}
n8n Workflow Structure:
- Schedule Trigger (Weekly, Friday 5 PM)
- Fetch Data (Supabase query for compliance tasks)
- Claude Summary (Generate executive summary)
- Format Report (HTML template with styling)
- Send via WhatsApp (To board directors group)
Template prompt for Claude:
Based on this compliance data: {{json.complianceData}}
Generate a 3-paragraph executive summary covering:
1. Overall compliance status (traffic light: green/amber/red)
2. Key achievements this week
3. Priority items requiring attention
Keep it under 200 words, suitable for board directors.
π― Pattern 3: Smart Task Categorization¶
When to use: Auto-categorizing new compliance tasks by Essential Eight domains
Implementation: Real-time n8n webhook + Claude classification
Classification prompt:
Classify this cybersecurity task into Essential Eight categories:
Task: "{{$json.taskDescription}}"
Return JSON only:
{
"category": "application_control|patch_management|
microsoft_office_hardening|user_application_hardening|
restrict_admin_privileges|patch_operating_systems|
multi_factor_authentication|daily_backups",
"priority": "low|medium|high|critical",
"estimated_effort": "1-2 hours|half-day|full-day|multiple-days",
"requires_technical_team": true/false
}
Auto-assignment logic:
function assignTask(classification, teamMembers) {
if (classification.requires_technical_team) {
return teamMembers.filter((m) => m.role === 'technical')[0]
} else {
return teamMembers.filter((m) => m.role === 'governance')[0]
}
}
π¬ Pattern 4: Context-Aware Compliance Guidance¶
When to use: Providing specific guidance based on company size/industry
Implementation: Claude with company context injection
Context template:
const companyContext = {
size: '{{company.employeeCount}}',
industry: '{{company.industry}}',
regulatoryFrameworks: [
'Essential Eight',
'ISO27001',
'{{company.additionalFrameworks}}',
],
currentMaturityLevel: '{{company.e8MaturityLevel}}',
}
const systemPrompt = `
You are providing cybersecurity compliance guidance for:
- Company size: ${companyContext.size} employees
- Industry: ${companyContext.industry}
- Current Essential Eight maturity: ${companyContext.currentMaturityLevel}
- Applicable frameworks: ${companyContext.regulatoryFrameworks.join(', ')}
Tailor your advice to their specific context and maturity level.
`
π Pattern 5: Human-in-the-Loop Risk Assessment¶
When to use: AI-assisted risk scoring with human oversigh
Implementation: Two-stage workflow with human approval
Stage 1 - AI Analysis:
async function analyzeRisk(incident) {
const analysis = await claude.analyze({
prompt: `Assess this cybersecurity incident:
Incident: ${incident.description}
Company context: ${incident.companySize} employees, ${incident.industry}
Provide:
1. Initial risk score (1-10)
2. Recommended immediate actions
3. Confidence level in assessment
4. Factors requiring human review`,
model: 'claude-3-haiku-20240307',
})
return {
...analysis,
requiresHumanReview: analysis.confidence < 0.8 || analysis.riskScore > 7,
}
}
Stage 2 - Human Review Workflow:
- If AI confidence > 80% and risk < 7: Auto-process
- Otherwise: Send to human reviewer via WhatsApp
- Include AI reasoning and request confirmation/override
π‘οΈ Pattern 6: Compliance Evidence Validation¶
When to use: Checking if uploaded evidence meets compliance requirements
Implementation: Claude vision + document analysis
Evidence validation:
async function validateEvidence(document, requirementType) {
const validation = await claude.vision({
image: document.imageData,
prompt: `
This document should demonstrate: ${requirementType}
Validate:
1. Does it clearly show the required evidence?
2. Is the date visible and recent (within 30 days)?
3. Are company identifiers visible?
4. What's missing (if anything)?
Return: {valid: true/false, missing: [], confidence: 0.0-1.0}
`,
})
return validation
}
π Implementation Guidelines¶
Resource Allocation¶
- Claude Haiku: Quick responses, simple tasks ($0.25/1M tokens)
- Claude Sonnet: Complex analysis, report generation ($3/1M tokens)
- n8n Cloud: $20/month covers most automation needs
Error Handling Pattern¶
function withFallback(aiFunction, fallbackAction) {
try {
return aiFunction()
} catch (error) {
console.log(`AI function failed: ${error.message}`)
return fallbackAction()
}
}
Rate Limiting¶
- Implement 1-second delays between API calls
- Cache common responses for 24 hours
- Use Claude Haiku for high-frequency, simple tasks
π― Quick Selection Guide¶
| Use Case | Pattern | Implementation Time | Monthly Cost |
|---|---|---|---|
| WhatsApp Q&A | Pattern 1 | 2 hours | $5-15 |
| Weekly reports | Pattern 2 | 4 hours | $10-20 |
| Task categorization | Pattern 3 | 3 hours | $5-10 |
| Contextual guidance | Pattern 4 | 2 hours | $10-25 |
| Risk assessment | Pattern 5 | 6 hours | $15-30 |
| Evidence validation | Pattern 6 | 4 hours | $20-40 |
Remember: Start with Pattern 1 (WhatsApp AI) - it provides immediate value and helps you learn the other patterns.
π Pattern 7: Full Implementation Cleanup¶
When to use: Any task involving finding and fixing patterns across multiple files
Implementation: Detection β Fix β Validate β Preven
Anti-pattern to avoid:
// WRONG: Analysis without implementation
async function auditEnterprisePatterns() {
const patterns = await scanFiles()
await createReport(patterns)
console.log('β
Audit complete!') // Task marked done!
}
Correct pattern:
async function removeEnterprisePatterns() {
// 1. DETECT - Quantify the problem
const patterns = await scanFiles()
console.log(`Found ${patterns.length} patterns in ${patterns.files} files`)
// 2. FIX - Automated implementation
const fixScript = createFixScript(patterns)
const results = await runFixScript(fixScript)
console.log(`Fixed ${results.fixed}/${patterns.length} automatically`)
// 3. VALIDATE - Ensure complete
const remaining = await scanFiles()
if (remaining.length > 0) {
throw new Error(`${remaining.length} patterns remain unfixed`)
}
// 4. PREVENT - Stop regression
await addPreCommitHook('prevent-enterprise-patterns.js')
await updateCIValidation()
return {
status: 'complete',
fixed: patterns.length,
remaining: 0,
prevention: 'active',
}
}
Key principles:
- Tasks aren't done until problems are gone AND can't return
- Always quantify: "Fixed 46/46 sections" not "Fixed sections"
- Validation scripts must show zero remaining instances
- Prevention mechanisms must be active before closing
Resource considerations:
- Initial implementation: 4-8 hours
- Automation saves 10x manual effortt
- Prevention saves 100x future effortt\n