Francis - SalesTrackingAgent¶
A comprehensive AI-powered business coaching system that guides young entrepreneurs in Kenya through onboarding, daily profit tracking, and credit management via WhatsApp and SMS channels.
Purpose¶
No business context provided yet — add a context.md to enrich this documentation.
This workflow serves as the main conversational engine for Sifa, an AI business coach deployed as part of the Educate! Kenya program in Makueni County. The system helps young entrepreneurs (aged 18-30) who struggle with profit visibility and credit management by providing structured onboarding, daily data collection, and personalized micro-actions to improve business performance.
The workflow targets out-of-school youth with primary or secondary education levels, communicating in their preferred language (Swahili, Sheng, or English) and adapting to their communication channel (WhatsApp or SMS with strict formatting requirements).
How It Works¶
The workflow operates as a sophisticated conversational AI system with multiple phases:
- Initial Setup: Resets daily flags and retrieves user profile data from the database
- Data Aggregation: Collects business records, chat history, credit records, and baseline configuration data
- Intent Routing: Determines whether to route the conversation to the main coaching agent or a lighter engagement agent
- AI Processing: The selected agent processes the user's message using extensive business coaching prompts and reasoning protocols
- Tool Integration: Agents can call various tools to update user data, collect sales information, manage credit records, and retrieve message templates
- Response Generation: Produces structured JSON responses with messages for youth and optional alerts for Community Education Advisors (CEAs)
- Logging & Follow-up: Records all interactions and triggers business summary generation
The system handles complex onboarding flows (13 detailed steps), daily profit tracking (Day 1, 2, and 3+ flows), credit module management, and welfare/safety protocols.
Workflow 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[getChatHistory]
H --> I[Filter]
I --> J[Limit]
J --> K[chatHistory]
D --> L[Aggregate]
E --> M[AggregateCreditRecord]
F --> N[dayTimeFields]
N --> O[AggregatePendingMessages]
G --> P[baselineData]
P --> Q[Aggregate3]
K --> R[Merge]
L --> R
M --> R
O --> R
Q --> R
R --> S[Aggregate1]
S --> T[chatAndBusinessHistory]
T --> U[Intent Router]
U --> V[If]
V --> W[AI Agent]
V --> X[engager_agent]
W --> Y[messages]
X --> Z[messages1]
Y --> AA[Insert rows in a table]
Z --> BB[Insert rows in a table2]
AA --> CC[call_create_summary_subworkflow1]
BB --> DD[call_create_summary_subworkflow3]
CC --> EE[setOutputField]
DD --> FF[setOutputField2]
W --> GG[logAgentError]
X --> GG
GG --> HH[call_create_summary_subworkflow2]
HH --> II[agentFallbackMessage]
Trigger¶
This workflow is triggered by another workflow via the "Execute Workflow Trigger" node. It expects three input parameters:
- phoneNumber: The user's phone number (unique identifier)
- query: The user's message content
- channel: Communication channel (WhatsApp or SMS)
Nodes Used¶
| Node Type | Node Name | Purpose |
|---|---|---|
| Execute Workflow Trigger | When Executed by Another Workflow | Receives incoming messages from parent workflows |
| Postgres | getUserRecord, getProfitData, getChatHistory, etc. | Database operations for user data, business records, and chat history |
| AI Agent | AI Agent, 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 Model | OpenRouter Chat Model | GPT-5.2 language model for AI responses |
| LangChain Tool | Think | Internal reasoning tool for structured decision-making |
| Workflow Tool | dailySalesDataCollection, updateUserStatusTool, etc. | External workflow calls for data operations |
| Aggregate | Multiple aggregation nodes | Combines data from multiple sources |
| Set | Various data transformation nodes | Formats and structures data between nodes |
| Filter | Filter | Processes chat history to include only relevant message types |
| If/Merge | Conditional routing and data merging | Controls workflow logic and data flow |
External Services & Credentials Required¶
Database Connections¶
- PostgresOnSupabase: Primary database connection for all user data, business records, chat logs, and system tables
AI Services¶
- OpenRouter API: Access to GPT-5.2 and Claude Sonnet models for conversational AI
- Used for main coaching agent, engagement agent, and intent routing
External Workflows¶
- dailySalesDataCollection: Handles sales and cost data persistence
- updateUserDataTool: Updates user profile information
- updateUserStatusTool: Manages user onboarding status
- messageTemplates: Retrieves standardized message templates
- saveCreditRecordTool: Manages credit/debt tracking data
- saveOnboardingBaselineTool: Stores baseline configuration data
- create_business_summary_for_youth: Generates business performance summaries
Environment Variables¶
The workflow uses dynamic time calculations and database queries but doesn't appear to require specific environment variables. All configuration is handled through: - Database connection credentials - API keys for AI services - Workflow IDs for external tool calls
Data Flow¶
Input¶
- phoneNumber: User identifier (string)
- query: User message content (string)
- channel: Communication channel - "WhatsApp" or "SMS" (string)
Processing¶
- User profile and business data retrieval
- Chat history and context aggregation
- Intent analysis and routing decisions
- AI agent processing with tool calls
- Response generation and validation
Output¶
- output: Final message to send to the user (string)
- Chat logs: Stored in database for conversation history
- Business summaries: Generated asynchronously for performance tracking
- CEA alerts: Triggered for welfare concerns or business issues
Error Handling¶
The workflow implements comprehensive error handling:
-
Agent Fallback: If AI agents fail, a fallback message is generated: "Samahani, kuna tatizo kidogo. Tafadhali jaribu tena baadaye."
-
Error Logging: Failed agent calls are logged to an
errorLogtable with details about the failure -
Silent Tool Failures: Tool failures are handled gracefully without exposing errors to users - the conversation continues seamlessly
-
Database Resilience: Uses
alwaysOutputDataandcontinueErrorOutputsettings to prevent workflow failures from database issues -
Retry Logic: Main AI agent has retry configuration (5 attempts with 2-second delays)
Known Limitations¶
Based on the extensive system prompts and configuration:
-
Language Support: Primarily designed for Swahili, Sheng, and English - may not handle other languages effectively
-
SMS Constraints: Strict 160-character limits for SMS messages require careful message splitting
-
Time Zone Dependency: Heavily dependent on Nairobi timezone (EAT) for session timing and data collection windows
-
Onboarding Rigidity: The 13-step onboarding process must be followed exactly - no flexibility for edge cases
-
Data Collection Windows: Evening data collection is restricted to 7-11 PM, which may not suit all users
-
Credit Scope: Only tracks credit given TO customers, not debt owed to suppliers
Related Workflows¶
- dailySalesDataCollection: Core data persistence workflow
- messageTemplates: Template management system
- create_business_summary_for_youth: Performance analytics generator
- updateUserStatusTool: User lifecycle management
- saveCreditRecordTool: Credit/debt tracking system
Setup Instructions¶
1. Database Setup¶
-
Configure PostgreSQL database with required tables:
youthEntrepreneursReal(user profiles)dailyProfitTracking(business records)chatLog(conversation history)n8n_chat_histories(LangChain memory)creditTracking(credit module data)pendingDaytimeMessages(message queue)ceaAlerts(escalation system)errorLog(error tracking)
-
Set up Supabase connection with credential ID:
Hw9XWerQ5RNHaVTk
2. AI Service Configuration¶
- Create OpenRouter account and obtain API key
- Configure credential with ID:
nyvOZDRjkDTKcdPt - Ensure access to GPT-5.2 and Claude Sonnet models
3. External Workflow Dependencies¶
Import and configure these supporting workflows:
- fBc6cSMp9Wz1brlZ (dailySalesDataCollection)
- xVkMVJOCq5ptCOHj (updateUserDataTool)
- nfVcA8ei8x9dE06Z (updateUserStatusTool)
- IIuvQx5MoV7CkTAJ (messageTemplates)
- sHQtICupLdgJd4sK (saveCreditRecordTool)
- ozK9ncMrgpe1rbG6 (saveOnboardingBaselineTool)
- Z9ekLMmXz9mHDKut (create_business_summary_for_youth)
4. Workflow Import¶
- Import the workflow JSON
- Update all credential references to match your environment
- Verify all external workflow IDs are correct
- Test with the provided pinned data for user
+254707060397
5. Testing¶
- Use the manual trigger with test data
- Verify database connections and AI model responses
- Test both WhatsApp and SMS formatting paths
- Validate error handling with intentionally broken inputs
The workflow is production-ready but requires careful attention to the extensive business rules and formatting requirements documented in the system prompts.