V4 - WIP - Francis - SalesTrackingAgent¶
A sophisticated AI-powered business coaching system that provides personalized guidance to young entrepreneurs in Kenya through WhatsApp and SMS. The workflow intelligently routes conversations between specialized agents based on user context, onboarding status, and conversation content to deliver targeted support for sales tracking, debt recovery, and business development.
Purpose¶
No business context provided yet — add a context.md to enrich this documentation.
Based on the workflow implementation, this system appears to serve young entrepreneurs in Kenya by: - Guiding them through a structured onboarding process to understand their business - Collecting daily sales and cost data to track profit trends - Providing personalized micro-actions to improve business performance - Managing credit/debt recovery with customers - Escalating welfare concerns to Community Engagement Advisors (CEAs) - Delivering coaching in local languages (Swahili, Sheng, English) via accessible channels
How It Works¶
- Session Initialization: The workflow receives a phone number, user query, and communication channel (WhatsApp/SMS)
- Context Gathering: Retrieves user profile, business records, chat history, and credit information from the database
- Context Analysis: Pre-computes key metrics like current business day, profit trends, missing data, and session mode
- Routing Decision: Determines whether to use the main sales tracking agent or engagement agent based on:
- Onboarding status (new users go to main agent)
- Business keywords or numbers in the message
- Time of day and data collection needs
- Pending questions or welfare signals
- Agent Processing:
- Main Agent: Handles onboarding, daily data collection, credit module, and structured business coaching
- Engagement Agent: Manages casual conversations and general entrepreneurship coaching
- Response Generation: Creates contextually appropriate messages with proper channel formatting
- Data Persistence: Logs conversations, updates user status, and triggers alerts for Community Engagement Advisors when needed
- Business Intelligence: Generates business summaries and tracks progress metrics
Workflow Diagram¶
graph TD
A[When Executed by Another Workflow] --> B[getSessionContext]
B --> C[getUserRecord]
C --> D[chatAndBusinessHistory]
D --> E[computeContext]
E --> F[isOnboardingPhase?]
F --> G{isOnboardingPhase? Route}
G -->|Yes| H[Call V4 - OnboardingJourneyHandler]
G -->|No| I[buildPromptSections]
H --> J{shouldUseAI?}
J -->|Yes| K[callOnboardingAI]
J -->|No| L[onboarding_setOutput]
K --> M[setOnboardingAIOutput]
I --> N[Intent Router]
N --> O{If}
O -->|main_agent| P[AI Agent]
O -->|engagement_agent| Q[Set Engager Context]
P --> R[Extract CEA Alert]
Q --> S[engager_agent]
R --> T{If1}
T -->|Multiple Messages| U[Split Out]
T -->|Single Message| V[messages]
U --> W{If2}
W -->|youth| X[messages2]
S --> Y[messages1]
V --> Z[Insert rows in a table]
X --> AA[Insert rows in a table3]
Y --> BB[Insert rows in a table2]
Z --> CC[persistState]
CC --> DD{ifCeaAlertRequired}
DD -->|Alert Needed| EE[insertCeaAlert]
DD -->|No Alert| FF[setOutputField]
%% Tool connections to AI Agent
GG[dailySalesDataCollection] -.->|ai_tool| P
HH[updateUserDataTool] -.->|ai_tool| P
II[updateUserStatusTool] -.->|ai_tool| P
JJ[Think] -.->|ai_tool| P
KK[messageTemplates] -.->|ai_tool| P
LL[saveCreditRecordTool] -.->|ai_tool| P
MM[callBaselineDataCollection] -.->|ai_tool| P
NN[Structured Output Parser2] -.->|ai_outputParser| P
OO[Postgres Chat Memory] -.->|ai_memory| P
PP[sifa_main_agent_prod] -.->|ai_languageModel| P
%% Engager agent connections
QQ[Structured Output Parser7] -.->|ai_outputParser| S
RR[Engager Chat Memory] -.->|ai_memory| S
SS[sifa_engager_agent_prod] -.->|ai_languageModel| S
Trigger¶
This workflow is triggered by another workflow via the "Execute Workflow Trigger" node. It expects three input parameters:
- phoneNumber: User's phone number (used as unique identifier)
- query: The user's message or system nudge
- channel: Communication channel (WhatsApp or SMS)
Nodes Used¶
| Node Type | Node Name | Purpose |
|---|---|---|
| Execute Workflow Trigger | When Executed by Another Workflow | Receives input from parent workflow |
| Postgres | getSessionContext | Retrieves user context via stored procedure |
| Code | getUserRecord | Unpacks user data from database response |
| Code | chatAndBusinessHistory | Formats context data for AI agents |
| Code | computeContext | Pre-computes business metrics and session state |
| Code | isOnboardingPhase? | Determines if user is in onboarding flow |
| If | isOnboardingPhase? Route | Routes to onboarding handler or main flow |
| Execute Workflow | Call V4 - OnboardingJourneyHandler | Handles structured onboarding process |
| HTTP Request | callOnboardingAI | Alternative AI endpoint for onboarding |
| Code | buildPromptSections | Assembles dynamic system prompts |
| Code | Intent Router | Routes messages between main and engagement agents |
| If | If | Determines which agent to use |
| AI Agent | AI Agent | Main sales tracking and coaching agent |
| AI Agent | engager_agent | General engagement and conversation agent |
| LangChain Tools | dailySalesDataCollection | Records daily business data |
| LangChain Tools | updateUserDataTool | Updates user profile information |
| LangChain Tools | updateUserStatusTool | Updates onboarding status |
| LangChain Tools | saveCreditRecordTool | Tracks credit/debt recovery progress |
| LangChain Tools | callBaselineDataCollection | Saves onboarding baseline data |
| LangChain Tools | messageTemplates | Retrieves message templates |
| LangChain Tool | Think | Internal reasoning and analysis tool |
| Postgres Chat Memory | Memory nodes | Maintains conversation context |
| Postgres | Multiple insert nodes | Logs conversations and alerts |
| Set | Multiple set nodes | Formats output data |
| HTTP Request | PromptLayer logging | Logs AI interactions for monitoring |
External Services & Credentials Required¶
Database Connections¶
- Postgres account: Main database for user records, business data, chat logs, and alerts
- Tables:
v4_youthEntrepreneurs,v4_chatLog,ceaAlerts,errorLog,v4_creditTracking
- Tables:
AI Services¶
- OpenRouter API:
sifa_main_agent_prod: GPT-5.2 for main business coachingsifa_engager_agent_prod: Claude Sonnet 4.6 for general engagement
- PromptLayer API: For logging and monitoring AI interactions
External Workflows¶
aOQRTnNvRUCjjwRE: dailySalesDataCollectionON18WqpuHwpe5jc6: updateUserDataToolHt3MkckUHVE039d0: updateUserStatusToolSmNrxmAoEYSMqQDe: saveCreditRecordToolRo2mHPinIURfchxo: saveOnboardingBaselineToolh77nzSL65k3aj1VU: messageTemplatesQVsCitg5rxMQx0Z3: V4 - OnboardingJourneyHandler2nTlbf07leuKBdM9: create_business_summary
Environment Variables¶
No explicit environment variables are defined in this workflow. Configuration is handled through: - Credential references for database and API connections - Workflow ID references for sub-workflow calls - Hard-coded URLs for external services (PromptLayer, onboarding AI endpoint)
Data Flow¶
Input¶
1 2 3 4 5 | |
Output¶
1 2 3 | |
Internal Data Processing¶
- User Context: Profile, onboarding status, business records, chat history
- Computed Metrics: Current business day, profit trends, missing data, session mode
- Agent Routing: Determines appropriate AI agent based on context
- Tool Interactions: Updates databases, retrieves templates, processes business logic
- Response Formatting: Channel-appropriate message formatting (emoji handling, length limits)
Error Handling¶
The workflow implements comprehensive error handling:
- Agent Failures: If AI agents fail, fallback messages are provided in local languages
- Tool Failures: Database write failures are handled silently to maintain user experience
- Error Logging: Failed interactions are logged to
errorLogtable with context - Graceful Degradation: System continues functioning even with partial failures
- CEA Escalation: Welfare concerns and system errors trigger alerts to Community Engagement Advisors
- Retry Logic: Critical nodes have retry mechanisms with exponential backoff
Known Limitations¶
Based on the implementation: - Data collection is time-sensitive (evening sessions preferred) - Sunday data collection is restricted for active users - Credit module requires 3+ days of business data before activation - SMS messages are limited to 160 characters and require emoji stripping - Tool failures may result in data inconsistencies that require manual intervention - Complex onboarding flow with 13+ steps that must be completed sequentially
Related Workflows¶
This workflow orchestrates multiple sub-workflows: - V4 - OnboardingJourneyHandler: Manages structured user onboarding - dailySalesDataCollection: Records and calculates daily business metrics - User management tools: Profile updates, status changes, baseline data collection - Credit tracking system: Manages debt recovery and customer credit - Business summary generator: Creates periodic business intelligence reports - Message templates: Provides standardized responses for different scenarios
Setup Instructions¶
- Import Workflow: Import the JSON into your n8n instance
- Configure Database:
- Set up Postgres connection with credential ID
EJPqF6MDH1ZwAzyv - Ensure required tables exist:
v4_youthEntrepreneurs,v4_chatLog,ceaAlerts,errorLog
- Set up Postgres connection with credential ID
- Configure AI Services:
- Set up OpenRouter credentials for both GPT-5.2 and Claude Sonnet 4.6
- Configure PromptLayer API key for logging
- Link Sub-Workflows: Ensure all referenced workflow IDs exist and are accessible
- Test Connections: Verify database connectivity and external API access
- Configure Error Workflow: Set up error workflow ID
cuHEGQjAfvuGwIODfor fallback handling - Validate Permissions: Ensure workflow has
workflowsFromSameOwnercaller policy - Test with Sample Data: Use the pinned test data to verify functionality
The workflow is designed to be self-contained but requires the full ecosystem of related workflows and database schema to function properly.