Skip to content

Francis - SalesTrackingAgent_testing

This workflow implements Sifa, an AI-powered business coach for young entrepreneurs in Kenya's Educate! program. It provides personalized coaching through WhatsApp and SMS, helping youth track daily sales and profits, manage customer credit, and develop business skills through guided onboarding and micro-actions.

Purpose

No business context provided yet — add a context.md to enrich this documentation.

This workflow serves young entrepreneurs in Kenya by providing accessible business coaching through familiar messaging platforms. The system guides users through a structured onboarding process, teaches profit tracking fundamentals, and provides ongoing support for business growth. It's specifically designed for youth with primary or secondary education levels, using simple language and culturally appropriate communication in Swahili, Sheng, and English.

How It Works

  1. Session Context Retrieval: The workflow begins by fetching comprehensive user data including profile information, business records, chat history, and current onboarding status from a PostgreSQL database.

  2. Intent Routing: A deterministic router analyzes the incoming message to determine whether it should be handled by the main business coaching agent or a general engagement agent based on factors like onboarding status, business keywords, distress signals, and pending questions.

  3. Agent Selection:

    • Main Agent: Handles structured business coaching including onboarding, daily profit tracking, credit module, and data collection
    • Engagement Agent: Manages casual conversations and general entrepreneurship coaching using a 15-stage pedagogical model
  4. Dynamic Prompt Building: The system constructs context-aware prompts based on the user's current stage, session mode (daytime/evening), and available data.

  5. AI Processing: The selected agent processes the user's message using advanced language models, with access to specialized tools for data collection, user management, and template retrieval.

  6. Response Generation: The system generates appropriate responses following strict formatting rules for WhatsApp vs SMS, including emoji handling and character limits.

  7. Data Persistence: All interactions are logged, user states are updated, and business data is saved to the database for continuity across sessions.

  8. Alert System: The workflow monitors for welfare concerns, consecutive missed days, or declining business trends, automatically alerting Community Engagement Agents (CEAs) when intervention is needed.

Mermaid Diagram

graph TD
    A[Execute Workflow Trigger] --> B[Get Session Context]
    B --> C[Get User Record]
    C --> D[Chat & Business History]
    D --> E[Compute Context]
    E --> F[Build Prompt Sections]
    F --> G[Intent Router]

    G --> H{Route Decision}
    H -->|Main Agent| I[AI Agent - Business Coach]
    H -->|Engagement Agent| J[Engager Agent]

    I --> K[Think Tool]
    I --> L[Daily Sales Data Collection]
    I --> M[Update User Status Tool]
    I --> N[Update User Data Tool]
    I --> O[Save Credit Record Tool]
    I --> P[Call Baseline Data Collection]
    I --> Q[Message Templates]

    J --> R[Think Tool]

    I --> S[Structured Output Parser]
    J --> T[Structured Output Parser]

    S --> U{Multiple Messages?}
    U -->|Yes| V[Split Out Messages]
    U -->|No| W[Extract Youth Message]

    V --> X{Message Type}
    X -->|Youth| Y[Insert Chat Log]
    X -->|Other| Z[No Operation]

    W --> AA[Insert Chat Log]
    T --> BB[Extract Youth Message]
    BB --> CC[Insert Chat Log]

    Y --> DD[Create Business Summary]
    AA --> EE[Persist State]
    CC --> FF[Create Business Summary]

    EE --> GG{CEA Alert Required?}
    GG -->|Yes| HH[Insert CEA Alert]
    GG -->|No| II[Set Output Field]

    HH --> II
    DD --> II
    FF --> JJ[Set Output Field]

    II --> KK[Final Output]
    JJ --> LL[Final Output]

Trigger

This workflow is triggered by another workflow via the "Execute Workflow Trigger" node. It expects three input parameters: - phoneNumber: User's phone number identifier - query: The user's message content - channel: Communication channel (WhatsApp or SMS)

Nodes Used

Node Type Purpose
Execute Workflow Trigger Receives input from parent workflows
Code (JavaScript) Data processing, context computation, and intent routing
Postgres Database operations for user data, chat logs, and business records
AI Agent Main business coaching agent with LangChain integration
Engager Agent General entrepreneurship coaching agent
Think Tool Internal reasoning and decision-making for AI agents
Structured Output Parser Ensures consistent JSON response format
OpenRouter Chat Model Language model integration for AI responses
Postgres Chat Memory Conversation history management
Tool Workflow nodes Integration with specialized business tools
Set nodes Data transformation and output formatting
If nodes Conditional logic and flow control
Split Out Message array processing
No Operation Flow control for unused branches

External Services & Credentials Required

Required Credentials:

  • PostgreSQL Database (kdpTestEnv): Stores user data, business records, chat history, and system state
  • OpenRouter API (OpenRouter KDP): Provides access to advanced language models (GPT-5.4-nano, Claude Sonnet-4.6)

External Workflows:

  • Daily Sales Data Collection workflow
  • Update User Data Tool workflow
  • Update User Status Tool workflow
  • Save Credit Record Tool workflow
  • Save Onboarding Baseline Tool workflow
  • Message Templates workflow
  • Create Business Summary workflow

Environment Variables

The workflow uses database connections and API credentials configured in n8n's credential system. No explicit environment variables are referenced in the workflow configuration.

Data Flow

Input:

  • phoneNumber: String - User identifier
  • query: String - User's message content
  • channel: String - Communication platform (WhatsApp/SMS)

Processing:

  • User context retrieval from database
  • Intent classification and routing
  • AI agent processing with tool access
  • Business data validation and storage
  • Response formatting for target channel

Output:

  • output: String - Formatted response message for the user
  • Chat log entries in database
  • Updated user status and business records
  • CEA alerts when intervention is needed
  • Business summary updates

Error Handling

The workflow implements comprehensive error handling:

  1. Agent Fallback: If the main AI agent fails, a fallback message is generated and errors are logged to the database
  2. Tool Failures: All tool calls are configured with onError: "continueErrorOutput" to prevent workflow crashes
  3. Silent Failures: Database write failures are handled silently to maintain user experience
  4. Retry Logic: The main AI agent has retry configuration (5 attempts, 2-second intervals)
  5. Error Logging: Failed operations are logged to an errorLog table for monitoring
  6. Graceful Degradation: The system continues functioning even when individual components fail

Known Limitations

Based on the workflow configuration: - The system is currently in testing mode as indicated by the workflow name - Language models are accessed through OpenRouter, creating dependency on external service availability - The workflow processes one user message at a time and may not handle high-concurrency scenarios - SMS responses are limited to 160 characters and require careful formatting - The system relies heavily on PostgreSQL for state management, creating a single point of failure

This workflow integrates with several specialized sub-workflows: - Daily Sales Data Collection: Handles business transaction recording - User Management Tools: Update user profiles and onboarding status - Credit Module Tools: Manages customer debt tracking - Message Templates: Provides standardized response templates - Business Summary Generator: Creates periodic business performance summaries

Setup Instructions

  1. Import Workflow: Import the JSON configuration into your n8n instance

  2. Configure Database Credentials:

    • Set up PostgreSQL connection named kdpTestEnv
    • Ensure database contains required tables: youthEntrepreneursReal, chatLog, ceaAlerts, errorLog
  3. Configure API Credentials:

    • Set up OpenRouter API credential named OpenRouter KDP
    • Ensure access to required models: openai/gpt-5.4-nano, anthropic/claude-sonnet-4.6
  4. Deploy Sub-workflows:

    • Import and configure all referenced tool workflows
    • Verify workflow IDs match the references in tool nodes
  5. Database Schema:

    • Execute the get_session_context stored procedure setup
    • Ensure proper indexing on phone numbers and timestamps
  6. Test Configuration:

    • Use the pinned test data to verify workflow functionality
    • Test both WhatsApp and SMS formatting paths
    • Verify error handling with invalid inputs
  7. Activate Workflow: Enable the workflow once all dependencies are configured and tested