Skip to content

AI Coach Iganga - Complete PostgreSQL Version

An AI-powered coaching workflow that enables coaches to conduct structured mentoring sessions with young entrepreneurs via WhatsApp, automatically identifying business bottlenecks and providing intelligent coaching guidance through a complete PostgreSQL-backed system.

Purpose

No business context provided yet — add a context.md to enrich this documentation.

This workflow appears to serve as a comprehensive coaching platform where field coaches can interact with young entrepreneurs through WhatsApp messages. The system intelligently processes coaching conversations, identifies business development bottlenecks across seven stages (from Psychological Activation to Scaling), and provides AI-generated coaching recommendations while maintaining detailed session records and youth profiles.

How It Works

  1. Coach Authentication: Incoming WhatsApp messages are validated against registered coaches in the PostgreSQL database
  2. Command Processing: The system parses coach messages for specific commands (START, STATUS, DONE) or treats them as coaching observations
  3. Session Management:
    • START command initiates new coaching sessions with youth phone numbers
    • Existing active sessions are automatically closed when starting new ones
    • Youth profiles are created if they don't exist, triggering a profile collection flow
  4. Profile Collection: For new youth, the system guides coaches through collecting name, location, and business type
  5. AI-Powered Coaching: Regular messages are processed by Claude AI to provide coaching guidance and identify bottlenecks
  6. Bottleneck Detection: The AI analyzes conversations against seven business development stages and records identified bottlenecks
  7. Session Tracking: All messages, bottlenecks, and session data are stored for historical analysis
  8. Status Monitoring: Coaches can check current session status and view bottleneck history
  9. Session Completion: DONE command properly closes sessions with summary statistics

Workflow Diagram

graph TD
    A[Webhook Trigger] --> B[Clean Phone Number]
    B --> C[Get Coach Details]
    C --> D{Coach Exists?}
    D -->|No| E[Respond: Not Registered]
    D -->|Yes| F{Coach Active?}
    F -->|No| G[Respond: Inactive Account]
    F -->|Yes| H[Parse Command]
    H --> I[Route by Command]

    I -->|START| J[Extract Youth Phone]
    J --> K[Check Existing Session]
    K --> L{Has Active Session?}
    L -->|Yes| M[Close Old Session]
    M --> N[Lookup Youth Profile]
    L -->|No| N
    N --> O{Youth Exists?}
    O -->|No| P[Create Youth Profile]
    P --> Q[Create Profile Collection Session]
    Q --> R[Send Profile Collection Start]
    O -->|Yes| S[Create Coaching Session]
    S --> T[Fetch Youth History]
    T --> U[Build Welcome Message]
    U --> V[Send Welcome Message]

    I -->|STATUS| W[Lookup Active Session]
    W --> X{Has Active Session?}
    X -->|No| Y[Send No Session Error]
    X -->|Yes| Z[Load Session Bottlenecks]
    Z --> AA[Load Youth History]
    AA --> BB[Build STATUS Response]
    BB --> CC[Send STATUS Response]

    I -->|DONE| DD[Lookup Active Session]
    DD --> EE{Has Active Session?}
    EE -->|No| FF[Send No Session Error]
    EE -->|Yes| GG[Count Messages & Bottlenecks]
    GG --> HH[Close Session]
    HH --> II[Build DONE Response]
    II --> JJ[Send DONE Response]

    I -->|MESSAGE| KK[Lookup Active Session]
    KK --> LL{Session Exists?}
    LL -->|No| MM[Send No Session Error]
    LL -->|Yes| NN{Profile Collection Mode?}
    NN -->|Yes| OO[Handle Profile Collection]
    OO --> PP[Update Youth Profile]
    PP --> QQ[Update Session Step]
    QQ --> RR[Send Profile Response]
    NN -->|No| SS[Load Session Bottlenecks]
    SS --> TT[Load Youth History]
    TT --> UU[Build AI Context]
    UU --> VV[Call AI OpenRouter]
    VV --> WW[Parse AI Response]
    WW --> XX[Log Messages]
    WW --> YY{Bottleneck Detected?}
    YY -->|Yes| ZZ[Save Bottleneck]
    ZZ --> AAA[Update Youth Stage]
    AAA --> BBB[Update Session Stage]
    YY -->|No| BBB
    BBB --> CCC[Send Coaching Response]

Trigger

Webhook: Postman Endpoint (Manual Trigger) - Receives HTTP POST requests on path 82cafd15-fd65-4dfc-a659-8fa88cbd0a8e, typically from WhatsApp webhook integration.

Nodes Used

Node Type Count Purpose
Webhook 1 Receives incoming WhatsApp messages
Code 7 Data processing, phone number cleaning, AI context building
PostgreSQL 20 Database operations for coaches, youth, sessions, messages, bottlenecks
If (Conditional) 8 Decision logic for coach validation, session states, bottleneck detection
Switch 1 Routes messages by command type (START/STATUS/DONE/MESSAGE)
HTTP Request 1 Calls OpenRouter AI API for coaching analysis
Respond to Webhook 9 Sends responses back to WhatsApp
Sticky Note 4 Workflow documentation and organization

External Services & Credentials Required

OpenRouter AI API

  • Purpose: AI-powered coaching analysis and bottleneck detection
  • Model: anthropic/claude-sonnet-4
  • Credential: API key for OpenRouter service
  • Headers: Authorization Bearer token

PostgreSQL Database

  • Purpose: Stores all coaching data including coaches, youth profiles, sessions, messages, and bottlenecks
  • Credential: "Postgres account 2" (hEIpy8sP7d9s8mtf)
  • Tables Required:
    • coaches (id, phone_number, status)
    • youth_profiles (id, phone_number, name, location, business_type, current_stage)
    • coaching_sessions (id, coach_id, youth_id, mode, status, profile_collection_step, started_at, ended_at)
    • messages (session_id, sender, content, sent_at)
    • bottleneck_diagnoses (session_id, youth_id, stage, bottleneck_name, confidence, ai_reasoning, micro_action_recommended)

Environment Variables

No explicit environment variables are defined in this workflow. Configuration is handled through: - Hardcoded OpenRouter API key (should be moved to environment variable) - PostgreSQL credentials stored in n8n credential system

Data Flow

Input

  • WhatsApp webhook payload with From, To, and Body fields
  • Phone numbers in various formats (with/without whatsapp: prefix)
  • Coach commands: START +254XXXXXXXXX, STATUS, DONE, or coaching messages

Output

  • JSON responses with status and message fields
  • Database records for all interactions, sessions, and bottlenecks
  • AI-generated coaching guidance and bottleneck analysis

Data Transformations

  • Phone number normalization (removes prefixes, standardizes to +254 format)
  • Command parsing and routing
  • AI response parsing and structured data extraction
  • Session state management and profile collection workflow

Error Handling

The workflow includes several error handling paths:

  1. Unregistered Coach: Returns error message for phone numbers not in coach database
  2. Inactive Coach: Blocks access for coaches with non-active status
  3. No Active Session: Prevents STATUS/DONE commands when no session exists
  4. Invalid Phone Format: Validates Kenyan phone number format in START command
  5. Missing Session Data: Handles cases where session lookup fails
  6. AI Response Parsing: Includes error handling for malformed AI responses

Known Limitations

Based on the workflow structure, potential limitations include: - Hardcoded API key in OpenRouter request (security risk) - Single coach per session limitation - No session timeout mechanism - Limited to Kenyan phone number format (+254) - No message delivery confirmation - Profile collection must complete in sequence (name → location → business_type)

No related workflows are mentioned in the current context.

Setup Instructions

  1. Import Workflow: Import the JSON into your n8n instance

  2. Configure PostgreSQL Database:

    • Set up PostgreSQL database with required tables
    • Create credential "Postgres account 2" in n8n with connection details
    • Populate coaches table with registered coach phone numbers and active status
  3. Configure OpenRouter API:

    • Sign up for OpenRouter account
    • Replace hardcoded API key with environment variable or credential
    • Ensure access to anthropic/claude-sonnet-4 model
  4. Set Up WhatsApp Integration:

    • Configure WhatsApp Business API to send webhooks to the workflow endpoint
    • Update webhook URL to match your n8n instance: https://your-n8n-instance.com/webhook/82cafd15-fd65-4dfc-a659-8fa88cbd0a8e
  5. Database Schema Setup:

    1
    2
    3
    -- Create required tables with appropriate columns and relationships
    -- Ensure proper indexing on phone_number and session_id fields
    -- Set up foreign key constraints between tables
    

  6. Test the Workflow:

    • Send test messages from registered coach phone numbers
    • Verify START command creates sessions and profiles
    • Test STATUS and DONE commands
    • Confirm AI responses and bottleneck detection
  7. Monitor and Maintain:

    • Set up logging for failed AI requests
    • Monitor database performance with high message volumes
    • Regularly backup coaching session data