Skip to content

Credit Path — Classifier First + AI Fallback (Webhook)

A WhatsApp-based credit recovery coaching workflow for Kenyan small-business owners that uses an intelligent classifier to handle most interactions deterministically, with AI fallback for cases requiring personalized empathy and warmth.

Purpose

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

How It Works

This workflow processes WhatsApp messages from Kenyan youth entrepreneurs doing credit recovery follow-up. Here's the step-by-step flow:

  1. Message Reception: Receives WhatsApp messages via Twilio webhook
  2. User Lookup: Extracts phone number and message, then looks up the user's credit recovery status in the database
  3. Credit Path Validation: Checks if the user is enrolled in the credit recovery program
  4. Date Context: Computes current date context in East Africa Time for accurate date resolution
  5. Intent Classification: Uses an LLM classifier to extract intent and structured data (amounts, dates, relationships) from the message
  6. Context Merging: Combines classifier output with user data for processing
  7. Deterministic Processing: Runs the message through a state machine that handles ~95% of cases with pre-written templates
  8. AI Fallback: For complex cases requiring empathy (fear coaching, forgot probes), routes to an AI agent
  9. Response Merging: Combines deterministic and AI responses appropriately
  10. State Updates: Updates the user's credit recovery state in the database
  11. History Logging: Records the interaction outcome for tracking
  12. WhatsApp Reply: Sends the response back to the user via Twilio

Mermaid Diagram

graph TD
    A[Twilio Webhook] --> B[Extract Twilio Fields]
    B --> C[Lookup User + Debtor]
    C --> D{Is Credit Path Youth?}
    D -->|Yes| E[Compute Dates]
    D -->|No| F[Respond OK Silent]
    E --> G[Intent Classifier]
    G --> H[Merge Context]
    H --> I[processStep]
    I --> J{Handled By AI?}
    J -->|Yes| K[AI Agent]
    J -->|No| L[Merge]
    K --> L
    L --> M[Advance State]
    L --> N{Has Outcome?}
    M --> O[Send WhatsApp Reply]
    N -->|Yes| P[Log History]
    O --> Q[Respond OK]

Trigger

Webhook: POST /webhook/sifa-creditpath-classifier

Triggered by incoming WhatsApp messages sent to the configured Twilio phone number (+12402623539).

Nodes Used

Node Type Purpose
Webhook Receives incoming WhatsApp messages from Twilio
Set (Extract Twilio Fields) Extracts phone number and message body from Twilio payload
Postgres (Lookup User + Debtor) Queries user data and active credit recovery status
If (Is Credit Path Youth?) Filters for users enrolled in credit recovery program
Code (Compute Dates) Generates date resolution table for East Africa Time
LangChain Agent (Intent Classifier) Classifies message intent and extracts structured data
Code (Merge Context) Combines classifier output with user context
Code (processStep) Deterministic state machine for credit recovery flow
If (Handled By AI?) Routes complex cases to AI fallback
LangChain Agent (AI Agent) Provides personalized responses for empathy cases
Code (Merge) Combines deterministic and AI responses
Postgres (Advance State) Updates user's credit recovery state
If (Has Outcome?) Checks if interaction had a measurable outcome
Postgres (Log History) Records interaction details for tracking
Twilio Sends WhatsApp reply to user
Respond to Webhook Returns HTTP 200 to Twilio

External Services & Credentials Required

Twilio

  • Purpose: WhatsApp messaging
  • Credential: twilioApi (Account SID, Auth Token)
  • Phone Number: +12402623539

OpenRouter

  • Purpose: LLM access for classifier and AI agent
  • Credential: openRouterApi (API Key)
  • Models Used:
    • openai/gpt-4.1 (Intent Classifier)
    • openai/gpt-5.2 (AI Agent Fallback)

PostgreSQL

  • Purpose: User data and credit recovery state management
  • Credential: postgres (sifaV4Dev)
  • Tables:
    • v4_youthEntrepreneurs
    • v4_creditpathFollowup
    • v4_creditpathHistory

Environment Variables

No explicit environment variables are used. Configuration is handled through n8n credentials and node parameters.

Data Flow

Input

  • WhatsApp Message: Raw message text from Kenyan youth entrepreneur
  • Phone Number: User's WhatsApp number (format: +254XXXXXXXXX)
  • Twilio Metadata: Message timestamp, sender info

Processing

  • Intent Classification: Extracts intent (promised, partial, full, refused, forgot, fear, no_time, etc.)
  • Structured Data: Amounts, dates, relationships, safety concerns
  • State Management: Tracks credit recovery conversation state
  • Template Selection: Chooses appropriate response template or AI generation

Output

  • WhatsApp Reply: Contextual message in Sheng/Swahili mix
  • State Updates: Updated conversation state and debtor information
  • History Record: Logged interaction with outcome and scheduling data
  • HTTP Response: 200 OK to Twilio webhook

Error Handling

  • Non-Credit Users: Silent OK response for users not in credit recovery program
  • Database Errors: Workflow continues with default values if lookups fail
  • AI Failures: Falls back to generic helpful message if AI agent fails
  • Invalid Input: Deterministic validation with re-prompting for corrections
  • Safety Override: Immediate pause and CEA alert for threat/aggression mentions

Known Limitations

Based on the workflow documentation:

  • Token Economy: ~5-10% of messages require expensive AI fallback calls
  • Language Support: Optimized for Sheng/Swahili mix, may not handle pure English well
  • Date Resolution: Limited to East Africa Time zone context
  • State Complexity: Complex state machine may be difficult to debug
  • Classifier Accuracy: Depends on LLM classification quality for routing decisions
  • [DEV-TEST] Credit Path — Deterministic First: Alternative implementation with different AI routing strategy
  • Onboarding Workflow: Referenced as pattern source for deterministic-first approach

Setup Instructions

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

  2. Configure Credentials:

    1
    2
    3
    - PostgreSQL: Create connection to sifaV4Dev database
    - Twilio API: Add Account SID and Auth Token
    - OpenRouter API: Add API key for LLM access
    

  3. Database Setup: Ensure these tables exist:

    1
    2
    3
    - v4_youthEntrepreneurs (user profiles)
    - v4_creditpathFollowup (active recovery sessions)
    - v4_creditpathHistory (interaction logs)
    

  4. Webhook Configuration:

    • Activate the workflow to generate webhook URL
    • Configure Twilio WhatsApp webhook to point to: https://your-n8n.com/webhook/sifa-creditpath-classifier
  5. Test Setup:

    • Send test message from registered credit path user
    • Verify database updates and WhatsApp responses
    • Check logs for any credential or connection issues
  6. Production Deployment:

    • Set webhook path to production endpoint
    • Monitor token usage and costs
    • Set up alerts for safety concerns and system errors