Skip to content

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

  1. 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.

  2. 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.

  3. 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
  4. 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
  5. Response Processing: The system formats responses based on the communication channel (WhatsApp vs SMS), logs conversations, and triggers business summary generation.

  6. 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: kdpTables credential for accessing user data, business records, chat logs, and credit tracking tables

AI Services

  • OpenRouter API: OpenRouter KDP credential for accessing GPT-5.2 and Claude Sonnet models

Required Tables

  • youthEntrepreneursReal: User profiles and onboarding status
  • dailyProfitTracking: Daily sales and cost records
  • n8n_chat_histories: Conversation history
  • creditTracking: Credit module data
  • chatLog: Message logging
  • ceaAlerts: Community Education Advisor alerts
  • errorLog: Error tracking
  • pendingDaytimeMessages: 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

  1. User data retrieval from multiple database tables
  2. Context aggregation (chat history, business records, credit data)
  3. Intent analysis and routing decision
  4. AI agent processing with tool calls for data operations
  5. 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:

  1. Agent Fallback: If the main AI agent fails, a fallback message is provided: "Samahani, kuna tatizo kidogo. Tafadhali jaribu tena baadaye."

  2. Error Logging: Failed agent calls are logged to the errorLog table with details about the error and input context.

  3. Tool Failure Resilience: The system is designed to continue operation even when individual tools fail, with silent error handling to maintain user experience.

  4. Graceful Degradation: Multiple conditional paths ensure users always receive some form of response, even in edge cases.

Known Limitations

Based on the implementation:

  1. Channel-Specific Constraints: SMS messages are limited to 160 characters and must have all emojis stripped
  2. Time-Based Restrictions: Data collection only occurs during evening hours (7-11 PM) unless explicitly requested
  3. Language Support: Primarily designed for Swahili, Sheng, and English with primary/secondary education level vocabulary
  4. Connectivity Assumptions: Designed for areas with low connectivity and basic smartphones

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

  1. Import Workflow: Import the JSON workflow definition into your n8n instance

  2. Configure Database Credentials:

    • Create PostgreSQL credential named kdpTables
    • Ensure connection to database with required tables listed above
  3. Configure AI Service Credentials:

    • Create OpenRouter API credential named OpenRouter KDP
    • Ensure access to GPT-5.2 and Claude Sonnet models
  4. Set Up Required Tables: Create the PostgreSQL tables referenced in the workflow:

    • youthEntrepreneursReal
    • dailyProfitTracking
    • n8n_chat_histories
    • creditTracking
    • chatLog
    • ceaAlerts
    • errorLog
    • pendingDaytimeMessages
  5. Configure Sub-Workflows: Ensure all referenced sub-workflows are imported and properly configured

  6. Test Integration: Use the manual trigger or call from another workflow with test data to verify proper operation

  7. Monitor Error Logs: Check the errorLog table 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.