Skip to content

Credit Path

A comprehensive credit recovery workflow for Kenyan small-business owners that guides users through structured follow-up conversations with customers who owe money. The system uses AI-powered intent classification and deterministic state machines to provide personalized coaching while maintaining conversation flow across multiple debtors.

Purpose

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

How It Works

  1. Input Processing: Receives WhatsApp messages containing phone number, query text, channel, and optional outcome step from button interactions
  2. User Validation: Looks up the user in the database and verifies they are enrolled in the credit recovery program
  3. Context Building: Retrieves active debtor information, calculates dates in East Africa Time, and builds conversation context
  4. Intent Classification: Uses AI to classify the user's message intent (promised payment, partial payment, refusal, fear, etc.) or synthesizes intent from button presses
  5. Conversation Routing: A deterministic state machine processes the classified intent and current conversation state to generate appropriate responses
  6. AI Fallback: For complex emotional situations (fear coaching, post-conversation chat), routes to an AI agent for personalized responses
  7. State Management: Updates debtor status, conversation state, and schedules follow-up reminders in the database
  8. Safety Handling: Detects safety concerns and alerts Community Engagement Advisors (CEAs) when threats are reported
  9. Message Formatting: Formats the final response with interactive buttons when appropriate and sends via WhatsApp

Mermaid Diagram

graph TD
    A[Sub-workflow Entry] --> 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[Has Outcome Step?]
    G -->|Yes| H[Synthesize Intent]
    G -->|No| I[Intent Classifier]
    H --> J[Merge Context]
    I --> J
    J --> K[Route Conversation]
    K --> L[Handled By AI?]
    L -->|Yes| M[AI Agent]
    L -->|No| N[Merge]
    M --> N
    N --> O[Advance State]
    N --> P[Has Outcome?]
    O --> Q[Activate Next Debtor]
    O --> R[Safety Triggered?]
    P -->|Yes| S[Log History]
    Q --> T[Format Message]
    R -->|Yes| U[Insert CEA Alert]
    S --> V[Award Points]
    T --> W[Format For Caller]
    U --> X[Has CEA Phone?]
    X -->|Yes| Y[Send CEA WhatsApp]
    Y --> Z[Mark CEA Alert Sent]

    %% AI connections
    AA[Classifier Chat Model] -.-> I
    BB[Fallback Chat Model] -.-> M
    CC[Conversation Memory] -.-> M

Trigger

This workflow is triggered as a sub-workflow by other n8n workflows. It accepts four input parameters: - phoneNumber: The user's phone number - query: The message text from the user - channel: Communication channel (typically "whatsapp") - outcomeStep: Optional outcome step from button interactions (C1-C7)

Nodes Used

Node Type Purpose
Execute Workflow Trigger Receives input parameters from calling workflows
Set Extracts and structures input fields
Postgres Database operations for user lookup, state management, and logging
If Conditional logic for routing and validation
Code JavaScript processing for date calculations, intent synthesis, and data merging
LangChain Agent AI-powered intent classification and conversational responses
LangChain Chat Model OpenRouter integration for AI language models
LangChain Memory PostgreSQL-based conversation history storage
Twilio WhatsApp message sending and CEA alerts
HTTP Request Direct Twilio API calls for message delivery
Execute Workflow Sub-workflow calls for message formatting
Respond to Webhook HTTP response handling

External Services & Credentials Required

Required Credentials

  • PostgreSQL Database (sifaV4Dev): Main application database
  • OpenRouter API (sifa_dev_env): AI language model access
  • Twilio API (Twilio account 3): WhatsApp messaging
  • Twilio Basic Auth (Twilio Basic Auth): Direct API authentication

External Services

  • OpenRouter (GPT-4.1 for classification, Gemini-2.5-Flash for conversations)
  • Twilio WhatsApp Business API
  • PostgreSQL database with specific schema for credit recovery

Environment Variables

No explicit environment variables are referenced in this workflow. Configuration is handled through n8n credentials and direct node parameters.

Data Flow

Input

1
2
3
4
5
6
{
  "phoneNumber": "string",
  "query": "string", 
  "channel": "string",
  "outcomeStep": "string (optional)"
}

Output

1
2
3
4
5
{
  "output": "string (formatted message)",
  "outputType": "string (plain|interactive)",
  "outputOptions": "array (button options if interactive)"
}

Internal Data Processing

  • User and debtor information from PostgreSQL
  • AI-classified intent and extracted entities (amounts, dates, relationships)
  • State machine decisions and next steps
  • Scheduled reminders and follow-up actions
  • Points awarded for completed actions
  • Safety alerts when threats are detected

Error Handling

The workflow includes several error handling mechanisms:

  • Silent failures for non-credit path users (responds OK without processing)
  • AI fallback parsing with multiple JSON extraction attempts
  • Validation whitelists for AI-generated structured outputs
  • Graceful degradation to deterministic responses when AI fails
  • Safety overrides that pause recovery and alert CEAs for threats
  • Orphan state recovery when no active debtor is found

Known Limitations

Based on the workflow structure, potential limitations include:

  • Dependency on external AI services (OpenRouter) for classification
  • Complex state machine logic that may be difficult to debug
  • WhatsApp-only communication channel
  • Requires specific PostgreSQL schema structure
  • Limited to East Africa Time zone calculations
  • CEA alerts depend on recruiter name matching in the database
  • Message Formatting Workflow (ID: 8pNZfAG0jWfYqqy4): Handles interactive button formatting and Twilio Content SID lookup
  • Daily nudge workflows: Referenced for bringing debtors back based on database state
  • Morning nudge workflow: Handles fresh session step resets

Setup Instructions

  1. Import Workflow: Import this workflow JSON into your n8n instance

  2. Configure Credentials:

    • Set up PostgreSQL connection with access to v4_* tables
    • Configure OpenRouter API key for AI services
    • Set up Twilio account credentials for WhatsApp messaging
  3. Database Schema: Ensure the following tables exist:

    • v4_youthEntrepreneurs: User profiles and program enrollment
    • v4_creditpathFollowup: Debtor tracking and conversation state
    • v4_creditpathHistory: Outcome logging and reminder scheduling
    • v4_ceaalerts: Safety alert management
    • v4_pointsledger: Points tracking system
    • v4_credit_chat_histories: Conversation memory storage
  4. Configure Sub-workflow: Set up the message formatting workflow (ID: 8pNZfAG0jWfYqqy4) that this workflow calls

  5. Test Integration: Verify the workflow can be called by other workflows with the required input parameters

  6. Enable Monitoring: Set up monitoring for AI service availability and database connectivity

  7. CEA Setup: Configure the v4_cea_contacts table with active Community Engagement Advisor contact information