Skip to content

V4 - ProfitOutcomeHandler - Warenga

This workflow processes profit-focused micro-action outcomes for Kenyan youth entrepreneurs in the SIFA coaching program. It combines AI-powered intent classification with deterministic conversation routing to provide personalized business coaching through WhatsApp, tracking progress and awarding points for completed actions.

Purpose

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

How It Works

  1. Input Validation: Receives WhatsApp message data (phone number, message content, channel, message ID) from a parent workflow
  2. User Lookup: Queries the database to find the youth entrepreneur and their current profit coaching state, including duplicate message detection
  3. Eligibility Check: Verifies the user is on the profit coaching path and the message isn't a duplicate
  4. Date Computation: Calculates Kenya local time (EAT) and builds a date reference table for context-aware responses
  5. Intent Classification: Uses AI to classify the youth's message intent (sold, tried but no sale, afraid, forgot, no time, etc.)
  6. Context Merging: Combines user data, classified intent, and business type mapping into a unified context
  7. Coaching Library Lookup: Retrieves business-specific coaching content from the database
  8. Conversation Routing: Deterministically routes to appropriate coaching branches (P1-P5) or delegates to AI for complex cases
  9. Response Generation: Either uses pre-built coaching templates or AI-generated personalized responses
  10. State Management: Updates the user's coaching progress and conversation state
  11. Micro-Action Tracking: Records completed actions and assigns new ones as needed
  12. History Logging: Saves the interaction outcome for analytics and follow-up
  13. Points Award: Grants points for successful completion of micro-actions
  14. Response Return: Sends back the coaching message to be delivered via WhatsApp

Workflow Diagram

graph TD
    A[When Executed by Another Workflow] --> B[Extract Twilio Fields]
    B --> C[Lookup User + Debtor]
    C --> D{Is Credit Path Youth?}
    D -->|No/Duplicate| E[Return Skip]
    D -->|Yes| F[Compute Dates]
    F --> G[Intent Classifier]
    G --> H[Merge Context]
    H --> I[Lookup Coaching Library]
    I --> J[Lookup Coaching Item]
    J --> K[Route Conversation]
    K --> L{Handled By AI?}
    L -->|Yes| M[AI Agent]
    L -->|No| N[Merge]
    M --> N
    N --> O[Advance State]
    O --> P[Save Micro Inline]
    P --> Q{Has Outcome?}
    Q -->|Yes| R[Log History]
    Q -->|No| S[Return Result]
    R --> T[Award Points]
    T --> S

    U[Classifier Chat Model] -.-> G
    V[Fallback Chat Model] -.-> M

Trigger

Execute Workflow Trigger: Called by another workflow with the following inputs: - phoneNumber: Youth's WhatsApp number - query: The message content from the youth - channel: Communication channel (typically "whatsapp") - messageSid: Unique message identifier for deduplication

Nodes Used

Node Type Node Name Purpose
Execute Workflow Trigger When Executed by Another Workflow Receives input from parent workflow
Set Extract Twilio Fields Extracts and structures input parameters
Postgres Lookup User + Debtor Finds user data and checks for duplicates
If Is Credit Path Youth? Validates user eligibility and message uniqueness
Code Compute Dates Calculates Kenya time and date references
LangChain Agent Intent Classifier AI classification of message intent
Code Merge Context Combines user data with classified intent
Postgres Lookup Coaching Library Retrieves business-specific coaching content
Code Lookup Coaching Item Attaches coaching library to context
Code Route Conversation Deterministic conversation flow logic
If Handled By AI? Determines if AI intervention is needed
LangChain Agent AI Agent Generates personalized responses for complex cases
Code Merge Combines deterministic and AI responses
Postgres Advance State Updates user's coaching progress
Code Save Micro Inline Records micro-action completion and assignment
If Has Outcome? Checks if interaction produced a trackable outcome
Postgres Log History Records interaction for analytics
Postgres Award Points Grants points for completed actions
Code Return Result Formats final response for parent workflow
Code Return Skip Handles ineligible users silently

External Services & Credentials Required

Database Connection

  • Credential: sifaV4Dev (PostgreSQL)
  • Purpose: Access to user data, coaching content, conversation state, and points system

AI Services

  • Credential: sifa_dev_env (OpenRouter API)
  • Models Used:
    • openai/gpt-4.1 for intent classification (temperature: 0)
    • openai/gpt-5.2 for conversational AI (temperature: 0.4)

Environment Variables

No explicit environment variables are referenced in this workflow. Configuration is handled through n8n credentials and database settings.

Data Flow

Input

1
2
3
4
5
6
{
  "phoneNumber": "+254712287952",
  "query": "Ndio, na nikauza",
  "channel": "whatsapp",
  "messageSid": "unique_message_id"
}

Output

1
2
3
4
5
{
  "output": "Coaching response message in Sheng/Swahili",
  "outputType": "plain",
  "outputOptions": []
}

Internal Data Tracking

  • User coaching state and progress
  • Micro-action assignments and completions
  • Points awarded for achievements
  • Conversation history and outcomes
  • Safety concerns and escalations

Error Handling

  • Duplicate Detection: Messages are deduplicated using messageSid to prevent double-processing
  • User Validation: Non-profit-path users are silently skipped without error
  • AI Fallbacks: When coaching library content is missing, AI generates appropriate responses
  • Attempt Limits: After 2 failed explanation attempts, conversations are escalated to human support
  • Safety Override: Safety concerns immediately pause coaching and alert support staff

Known Limitations

Based on the workflow structure: - Requires active database connection for all operations - Dependent on OpenRouter API availability for AI functions - Limited to profit-path youth entrepreneurs only - Coaching content must be pre-populated in the database - No direct integration with external business systems

This is a sub-workflow called by parent workflows that handle: - WhatsApp message reception - Message routing and dispatch - Twilio integration for message delivery

Setup Instructions

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

  2. Configure Database Credential:

    • Create PostgreSQL credential named sifaV4Dev
    • Ensure access to required tables:
      • v4_youthEntrepreneurs
      • v4_profitpathFollowup
      • v4_profitpathHistory
      • v4_microaction_history
      • v4_pointsledger
      • v4_profitCoachingLibrary
  3. Configure AI Credential:

    • Create OpenRouter API credential named sifa_dev_env
    • Ensure access to GPT-4.1 and GPT-5.2 models
  4. Database Schema Setup:

    • Create required tables with appropriate columns
    • Populate coaching library with business-specific content
    • Set up user records with profit coaching flags
  5. Test Integration:

    • Verify workflow can be called by parent workflows
    • Test with sample youth entrepreneur data
    • Confirm database writes and point awards work correctly
  6. Monitor Performance:

    • Track AI model response times
    • Monitor database query performance
    • Review conversation escalation rates