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¶
- Input Validation: Receives WhatsApp message data (phone number, message content, channel, message ID) from a parent workflow
- User Lookup: Queries the database to find the youth entrepreneur and their current profit coaching state, including duplicate message detection
- Eligibility Check: Verifies the user is on the profit coaching path and the message isn't a duplicate
- Date Computation: Calculates Kenya local time (EAT) and builds a date reference table for context-aware responses
- Intent Classification: Uses AI to classify the youth's message intent (sold, tried but no sale, afraid, forgot, no time, etc.)
- Context Merging: Combines user data, classified intent, and business type mapping into a unified context
- Coaching Library Lookup: Retrieves business-specific coaching content from the database
- Conversation Routing: Deterministically routes to appropriate coaching branches (P1-P5) or delegates to AI for complex cases
- Response Generation: Either uses pre-built coaching templates or AI-generated personalized responses
- State Management: Updates the user's coaching progress and conversation state
- Micro-Action Tracking: Records completed actions and assigns new ones as needed
- History Logging: Saves the interaction outcome for analytics and follow-up
- Points Award: Grants points for successful completion of micro-actions
- 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.1for intent classification (temperature: 0)openai/gpt-5.2for 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 | |
Output¶
1 2 3 4 5 | |
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
messageSidto 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
Related Workflows¶
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¶
-
Import Workflow: Import the JSON configuration into your n8n instance
-
Configure Database Credential:
- Create PostgreSQL credential named
sifaV4Dev - Ensure access to required tables:
v4_youthEntrepreneursv4_profitpathFollowupv4_profitpathHistoryv4_microaction_historyv4_pointsledgerv4_profitCoachingLibrary
- Create PostgreSQL credential named
-
Configure AI Credential:
- Create OpenRouter API credential named
sifa_dev_env - Ensure access to GPT-4.1 and GPT-5.2 models
- Create OpenRouter API credential named
-
Database Schema Setup:
- Create required tables with appropriate columns
- Populate coaching library with business-specific content
- Set up user records with profit coaching flags
-
Test Integration:
- Verify workflow can be called by parent workflows
- Test with sample youth entrepreneur data
- Confirm database writes and point awards work correctly
-
Monitor Performance:
- Track AI model response times
- Monitor database query performance
- Review conversation escalation rates