Francis - SalesTrackingAgent¶
This workflow implements Sifa, an AI business coach that helps young entrepreneurs in Kenya track their daily profits and manage customer credit through WhatsApp and SMS. The system guides users through a comprehensive onboarding process, collects daily sales data, and provides personalized business coaching based on profit trends and credit recovery needs.
Purpose¶
No business context provided yet — add a context.md to enrich this documentation.
Based on the workflow implementation, this system serves young entrepreneurs aged 18-30 in Makueni County, Kenya, who are part of the Educate! Kenya program. The core business problem being addressed is that youth extend credit to friends and family without proper tracking systems, which erodes their working capital and drives business failure. The system aims to achieve a 20% uplift in youth business profit through daily profit tracking, credit management, and targeted micro-actions.
How It Works¶
-
User Authentication & Data Preparation: The workflow receives a phone number, user query, and communication channel, then fetches user records, business history, chat history, and credit information from the database.
-
Intent Routing: An AI router analyzes the incoming message and user context to determine whether to route to the main structured coaching agent or a lighter engagement agent for casual conversations.
-
Main Agent Processing: The primary AI agent (Sifa) processes the user's message using a comprehensive system prompt that handles:
- Onboarding Flow: 13-step process including welcome, bio confirmation, expectation setting, practice data collection, and baseline configuration
- Daily Data Collection: Evening sessions (7-11 PM) to collect sales, costs, and calculate profit
- Credit Module: Advanced tracking for customers who owe money, with recovery targets and micro-actions
- Welfare Protocol: Safety checks for users in distress with automatic CEA (Community Education Advisor) alerts
-
Tool Integration: The agent can call various tools to:
- Save daily sales and cost data
- Update user status and profile information
- Store onboarding baseline data
- Record credit tracking information
- Retrieve message templates
-
Response Processing: The system formats responses based on the communication channel (WhatsApp vs SMS), logs conversations, and triggers business summary generation.
-
Error Handling: Multiple fallback mechanisms ensure users always receive a response, even when tools fail or unexpected errors occur.
Mermaid Diagram¶
graph TD
A[When Executed by Another Workflow] --> B[resetDailyFlagsIfNewDay]
B --> C[getUserRecord]
C --> D[getProfitData]
C --> E[getCreditRecord]
C --> F[getPendingDaytimeMessages]
C --> G[getBaseline]
D --> H[Aggregate Business Records]
D --> I[getChatHistory]
I --> J[Filter Chat Messages]
J --> K[Limit to 20 Messages]
K --> L[chatHistory Aggregate]
E --> M[AggregateCreditRecord]
F --> N[dayTimeFields]
N --> O[AggregatePendingMessages]
G --> P[baselineData]
P --> Q[Aggregate3]
H --> R[Merge All Data]
L --> R
M --> R
O --> R
Q --> R
R --> S[Aggregate1]
S --> T[chatAndBusinessHistory]
T --> U[Intent Router]
U --> V{Route Decision}
V -->|main_agent| W[AI Agent - Sifa]
V -->|engagement_agent| X[engager_agent]
W --> Y{Multiple Messages?}
Y -->|Yes| Z[Split Out Messages]
Y -->|No| AA[messages]
Z --> BB{Message to Youth?}
BB -->|Yes| CC[messages2]
BB -->|No| DD[No Operation]
X --> EE[messages1]
AA --> FF[Insert Chat Log]
CC --> GG[Insert Chat Log 3]
EE --> HH[Insert Chat Log 2]
FF --> II[Create Business Summary]
GG --> JJ[Create Business Summary 4]
HH --> KK[Create Business Summary 3]
II --> LL[setOutputField]
JJ --> MM[setOutputField3]
KK --> NN[setOutputField2]
%% Tool connections to AI Agent
OO[dailySalesDataCollection] -.->|tool| W
PP[updateUserDataTool] -.->|tool| W
QQ[updateUserStatusTool] -.->|tool| W
RR[messageTemplates] -.->|tool| W
SS[saveCreditRecordTool] -.->|tool| W
TT[callBaselineDataCollection] -.->|tool| W
UU[Think Tool] -.->|tool| W
UU -.->|tool| X
%% Memory and LLM connections
VV[Postgres Chat Memory] -.->|memory| W
VV -.->|memory| U
VV -.->|memory| X
WW[OpenRouter Chat Model] -.->|llm| W
WW -.->|llm| U
XX[OpenRouter Chat Model4] -.->|llm| X
Trigger¶
This workflow is triggered by another workflow through the "Execute Workflow Trigger" node. It expects three input parameters:
- phoneNumber: The user's phone number (used as unique identifier)
- query: The user's message content
- channel: Communication channel (WhatsApp, SMS, or Call center)
Nodes Used¶
| Node Type | Node Name | Purpose |
|---|---|---|
| Execute Workflow Trigger | When Executed by Another Workflow | Receives input from parent workflow |
| Postgres | getUserRecord, getProfitData, getChatHistory, etc. | Database operations for user data, business records, and chat history |
| AI Agent | AI Agent (Sifa), engager_agent | Main conversational AI agents with different specializations |
| AI Agent | Intent Router | Routes messages between main agent and engagement agent |
| LangChain Memory | Postgres Chat Memory | Maintains conversation context across sessions |
| LangChain LLM | OpenRouter Chat Model | Provides AI language model capabilities |
| LangChain Tools | dailySalesDataCollection, updateUserDataTool, etc. | Workflow tools for database operations |
| LangChain Tool | Think | Internal reasoning tool for AI agents |
| Code | Format, chatHistory1, etc. | Data transformation and formatting |
| Aggregate | Multiple aggregate nodes | Combine data from multiple sources |
| Merge | Merge | Combine data streams |
| Set | Various set nodes | Data field assignment and transformation |
| If/Filter | Conditional routing and data filtering | Control flow based on conditions |
| Execute Workflow | call_create_summary_subworkflow | Triggers business summary generation |
External Services & Credentials Required¶
Database Connection¶
- PostgreSQL:
kdpTablescredential for accessing user data, business records, chat logs, and credit tracking tables
AI Services¶
- OpenRouter API:
OpenRouter KDPcredential for accessing GPT-5.2 and Claude Sonnet models
Required Tables¶
youthEntrepreneursReal: User profiles and onboarding statusdailyProfitTracking: Daily sales and cost recordsn8n_chat_histories: Conversation historycreditTracking: Credit module datachatLog: Message loggingceaAlerts: Community Education Advisor alertserrorLog: Error trackingpendingDaytimeMessages: Daytime message queue
Environment Variables¶
No explicit environment variables are defined in this workflow. Configuration is handled through: - Database credentials stored in n8n credential system - API keys for OpenRouter stored in n8n credential system - Workflow-specific settings in node parameters
Data Flow¶
Input¶
phoneNumber: User identifier (string)query: User message content (string)channel: Communication channel (WhatsApp/SMS/Call center)
Processing¶
- User data retrieval from multiple database tables
- Context aggregation (chat history, business records, credit data)
- Intent analysis and routing decision
- AI agent processing with tool calls for data operations
- Response formatting based on channel requirements
Output¶
output: Formatted response message for the user (string)- Side effects: Database updates, chat logging, business summaries, CEA alerts
Error Handling¶
The workflow implements comprehensive error handling:
-
Agent Fallback: If the main AI agent fails, a fallback message is provided: "Samahani, kuna tatizo kidogo. Tafadhali jaribu tena baadaye."
-
Error Logging: Failed agent calls are logged to the
errorLogtable with details about the error and input context. -
Tool Failure Resilience: The system is designed to continue operation even when individual tools fail, with silent error handling to maintain user experience.
-
Graceful Degradation: Multiple conditional paths ensure users always receive some form of response, even in edge cases.
Known Limitations¶
Based on the implementation:
- Channel-Specific Constraints: SMS messages are limited to 160 characters and must have all emojis stripped
- Time-Based Restrictions: Data collection only occurs during evening hours (7-11 PM) unless explicitly requested
- Language Support: Primarily designed for Swahili, Sheng, and English with primary/secondary education level vocabulary
- Connectivity Assumptions: Designed for areas with low connectivity and basic smartphones
Related Workflows¶
The workflow references several sub-workflows:
- dailySalesDataCollection: Handles daily sales data storage
- updateUserDataTool: Updates user profile information
- updateUserStatusTool: Manages onboarding status transitions
- messageTemplates: Provides templated responses
- saveCreditRecordTool: Manages credit tracking data
- saveOnboardingBaselineTool: Stores baseline configuration
- create_business_summary_for_youth: Generates business performance summaries
Setup Instructions¶
-
Import Workflow: Import the JSON workflow definition into your n8n instance
-
Configure Database Credentials:
- Create PostgreSQL credential named
kdpTables - Ensure connection to database with required tables listed above
- Create PostgreSQL credential named
-
Configure AI Service Credentials:
- Create OpenRouter API credential named
OpenRouter KDP - Ensure access to GPT-5.2 and Claude Sonnet models
- Create OpenRouter API credential named
-
Set Up Required Tables: Create the PostgreSQL tables referenced in the workflow:
youthEntrepreneursRealdailyProfitTrackingn8n_chat_historiescreditTrackingchatLogceaAlertserrorLogpendingDaytimeMessages
-
Configure Sub-Workflows: Ensure all referenced sub-workflows are imported and properly configured
-
Test Integration: Use the manual trigger or call from another workflow with test data to verify proper operation
-
Monitor Error Logs: Check the
errorLogtable regularly to identify and resolve any system issues
The workflow is designed to be robust and self-contained, with extensive error handling and fallback mechanisms to ensure reliable operation in challenging connectivity environments.