Francis - SalesTrackingAgent¶
An AI-powered business coaching system that guides young entrepreneurs in Kenya through daily sales tracking, profit analysis, and debt recovery. The workflow intelligently routes conversations between two specialized agents - a main sales tracking agent (Sifa) and an engagement agent - to provide personalized business coaching via WhatsApp or SMS.
Purpose¶
No business context provided yet — add a context.md to enrich this documentation.
This workflow serves as the core conversational engine for young entrepreneurs participating in business coaching programs. It helps users track daily sales and costs, understand their profit patterns, manage customer debt, and receive actionable micro-advice to grow their businesses. The system is designed for users with limited formal education and operates in Swahili, Sheng, and English.
How It Works¶
-
Session Context Loading: The workflow starts by retrieving the user's complete business context from a PostgreSQL database, including their profile, chat history, business records, and current onboarding status.
-
Intent Routing: A deterministic router analyzes the incoming message to decide whether to use the main sales tracking agent or the engagement agent based on factors like onboarding status, business keywords, distress signals, and pending questions.
-
Agent Processing:
- Main Agent (Sifa): Handles onboarding, daily sales data collection, profit calculations, credit module, and structured business coaching
- Engagement Agent: Manages casual conversations, general business questions, and relationship building
-
Data Collection & Validation: For active users, the system collects daily sales figures, costs (stocking, transport, other), and calculates profit using business-specific baselines and fixed costs.
-
Intelligent Responses: The agents provide contextual responses based on the user's business stage, profit trends, missing data, and welfare indicators.
-
State Persistence: All conversation data, business metrics, and user progress are logged to maintain continuity across sessions.
-
Alert System: The workflow monitors for welfare concerns, declining business performance, or consecutive missed data entries and triggers alerts for Community Economic Advisors (CEAs).
Workflow Diagram¶
graph TD
A[When Executed by Another Workflow] --> B[getSessionContext]
B --> C[getUserRecord]
C --> D[chatAndBusinessHistory]
D --> E[computeContext]
E --> F[buildPromptSections]
F --> G[Intent Router]
G --> H{Route Decision}
H -->|main_agent| I[AI Agent - Sifa]
H -->|engagement_agent| J[Set Engager Context]
I --> K[Extract CEA Alert]
I --> L[logAgentError]
J --> M[engager_agent]
M --> N[messages1]
M --> O[logAgentError]
K --> P{Multiple Messages?}
P -->|Yes| Q[Split Out]
P -->|No| R[messages]
Q --> S{Youth Message?}
S -->|Yes| T[messages2]
S -->|No| U[Skip]
R --> V[Insert rows in a table]
T --> W[Insert rows in a table3]
N --> X[Insert rows in a table2]
V --> Y[persistState]
Y --> Z{CEA Alert Required?}
Z -->|Yes| AA[insertCeaAlert]
Z -->|No| BB[setOutputField]
AA --> BB
W --> CC[setOutputField3]
X --> DD[setOutputField2]
%% Tool connections to AI Agent
EE[dailySalesDataCollection] -.->|ai_tool| I
FF[updateUserDataTool] -.->|ai_tool| I
GG[updateUserStatusTool] -.->|ai_tool| I
HH[Think] -.->|ai_tool| I
II[messageTemplates] -.->|ai_tool| I
JJ[saveCreditRecordTool] -.->|ai_tool| I
KK[callBaselineDataCollection] -.->|ai_tool| I
%% Memory connections
LL[Postgres Chat Memory] -.->|ai_memory| I
MM[Engager Chat Memory] -.->|ai_memory| M
%% Output parsers
NN[Structured Output Parser2] -.->|ai_outputParser| I
OO[Structured Output Parser7] -.->|ai_outputParser| M
%% Language models
PP[sifa_main_agent_prod] -.->|ai_languageModel| I
QQ[sifa_engager_agent_prod] -.->|ai_languageModel| M
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 (used as unique identifier)
- query: The user's message or "system_nudge" for automated prompts
- 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 and flattens user data |
| Code | chatAndBusinessHistory | Formats context data for agents |
| Code | computeContext | Pre-computes business metrics and session state |
| Code | buildPromptSections | Dynamically builds agent system prompts |
| Code | Intent Router | Routes messages to appropriate agent |
| If | If | Determines which agent to use |
| LangChain Agent | AI Agent | Main sales tracking agent (Sifa) |
| LangChain Agent | engager_agent | Casual conversation agent |
| LangChain Tool Workflow | dailySalesDataCollection | Records daily business data |
| LangChain Tool Workflow | updateUserDataTool | Updates user profile information |
| LangChain Tool Workflow | updateUserStatusTool | Updates onboarding status |
| LangChain Tool Workflow | saveCreditRecordTool | Tracks credit/debt recovery |
| LangChain Tool Workflow | callBaselineDataCollection | Saves onboarding baseline data |
| LangChain Tool Workflow | messageTemplates | Retrieves message templates |
| LangChain Tool Think | Think | Internal reasoning for main agent |
| Postgres Chat Memory | Postgres Chat Memory | Maintains conversation history |
| Postgres Chat Memory | Engager Chat Memory | Maintains engagement conversation history |
| Structured Output Parser | Structured Output Parser2 | Parses main agent JSON output |
| Structured Output Parser | Structured Output Parser7 | Parses engagement agent JSON output |
| Postgres | Insert rows in a table | Logs conversations to database |
| Postgres | persistState | Updates user state in database |
| Postgres | insertCeaAlert | Creates alerts for advisors |
| Set | messages | Extracts youth message from agent output |
| Set | setOutputField | Formats final workflow output |
| HTTP Request | logMainAgentToPL | Logs main agent interactions to PromptLayer |
| HTTP Request | logEngagerAgentToPL | Logs engagement agent interactions to PromptLayer |
External Services & Credentials Required¶
Database¶
- PostgreSQL: Stores user profiles, business records, chat history, and alerts
- Credential: "Postgres account" (ID: EJPqF6MDH1ZwAzyv)
AI Language Models¶
- OpenRouter API: Provides access to GPT-5.2 and Claude Sonnet 4.6 models
- Main Agent Credential: "sifa_main_agent_prod" (ID: TCRDuARS44G76WWp)
- Engagement Agent Credential: "sifa_engager_agent_prod" (ID: hRNRvdhUlZaxUTUM)
Monitoring & Analytics¶
- PromptLayer: Logs AI interactions for monitoring and analysis
- API Key: pl_80a83a0db8150339b213693376a60afb (configured in HTTP Request nodes)
Environment Variables¶
No explicit environment variables are defined in this workflow. Configuration is handled through: - Database connection strings (in PostgreSQL credentials) - API keys (in OpenRouter and PromptLayer credentials) - Webhook URLs (hardcoded in HTTP Request nodes)
Data Flow¶
Input¶
phoneNumber(string): User's phone number identifierquery(string): User's message or system triggerchannel(string): Communication channel (WhatsApp/SMS)
Processing¶
- User context retrieved from database (profile, business data, chat history)
- Business metrics computed (current day, profit trends, missing data)
- Message routed to appropriate agent based on content and user state
- Agent processes message using tools for data collection, status updates, and calculations
- Response formatted according to channel requirements
Output¶
output(string): Final message to send back to the user- Database updates: conversation logs, business records, user state, CEA alerts
- External logging: interaction data sent to PromptLayer for analysis
Error Handling¶
The workflow implements comprehensive error handling:
- Agent Fallback: If either AI agent fails, a fallback message is provided in Swahili
- Tool Failures: All tool calls are configured to continue on error, maintaining conversation flow
- Error Logging: Failed interactions are logged to an
errorLogtable for debugging - Retry Logic: Database operations include retry mechanisms (2-3 attempts with delays)
- Silent Failures: Backend errors are never exposed to users - the conversation continues seamlessly
- CEA Escalation: Welfare concerns and system failures trigger alerts for human advisors
Known Limitations¶
Based on the workflow configuration:
- Language Models: Dependent on external OpenRouter API availability
- Database Dependency: Single point of failure if PostgreSQL becomes unavailable
- Context Window: Chat memory limited to 20 turns for main agent, 7 for engagement agent
- Channel Formatting: SMS messages must be under 160 characters and cannot include emojis
- Time Zone: Hardcoded to Africa/Nairobi timezone for business hours logic
- Tool Complexity: Multiple interconnected tool workflows create potential failure points
Related Workflows¶
The workflow references several sub-workflows:
- dailySalesDataCollection (ID: aOQRTnNvRUCjjwRE)
- updateUserDataTool (ID: ON18WqpuHwpe5jc6)
- updateUserStatusTool (ID: Ht3MkckUHVE039d0)
- saveCreditRecordTool (ID: SmNrxmAoEYSMqQDe)
- saveOnboardingBaselineTool (ID: Ro2mHPinIURfchxo)
- messageTemplates (ID: h77nzSL65k3aj1VU)
- create_business_summary (ID: 2nTlbf07leuKBdM9) - currently disabled
Setup Instructions¶
-
Import Workflow: Import the JSON into your n8n instance
-
Configure Database:
- Set up PostgreSQL database with required tables
- Create credential "Postgres account" with connection details
- Ensure stored procedure
get_session_contextexists
-
Configure AI Services:
- Create OpenRouter API credentials for both agents
- Set up PromptLayer account and obtain API key
- Update credential IDs in the workflow if different
-
Set Up Sub-Workflows:
- Import and configure all referenced tool workflows
- Ensure workflow IDs match those in the tool configurations
- Test each tool workflow independently
-
Configure Error Handling:
- Set up error workflow (ID: cuHEGQjAfvuGwIOD)
- Verify database tables for logging exist
-
Test Configuration:
- Use the pinned test data to verify workflow execution
- Test both agent paths (main and engagement)
- Verify database writes and error handling
-
Production Deployment:
- Update any test mode flags in the code nodes
- Configure appropriate retry settings for your environment
- Set up monitoring for the external service dependencies