Skip to content

Mark - SalesTrackingAgent

This workflow implements Sifa, an AI-powered business coach for young entrepreneurs in rural Kenya. It provides daily profit tracking, credit management guidance, and personalized micro-actions through WhatsApp and SMS channels. The system uses a sophisticated two-stage AI analysis approach to understand user intent and generate contextually appropriate responses in Swahili, English, or Sheng.

Purpose

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

This workflow serves young entrepreneurs aged 18-30 in Makueni County, Kenya, who are struggling with business profit visibility and credit management. It's part of the Educate! Kenya Digital Product program supporting out-of-school youth entrepreneurs. The core business problem it addresses is that youth extend credit to friends and family without proper tracking systems, which erodes their working capital and leads to business failure. The program's goal is to achieve a 20% uplift in youth business profit through daily coaching and actionable insights.

How It Works

  1. Message Reception: The workflow receives incoming messages from youth entrepreneurs via WhatsApp or SMS
  2. User Context Loading: Retrieves user profile, business records, and chat history from the database
  3. Intent Analysis: An AI agent analyzes the conversation state, determines the current stage of interaction, and identifies what data needs to be collected
  4. Conversation State Check: Determines if the conversation is concluded or needs to continue
  5. Main AI Agent Processing: The primary Sifa agent generates appropriate responses based on the intent analysis, using message templates and business logic
  6. Tool Integration: Calls various tools for data collection (sales tracking), user management (profile updates), and message templating
  7. Response Delivery: Sends the generated message back to the user and logs the interaction
  8. Business Summary Generation: Triggers a separate workflow to create business summaries for the user

The system handles multiple conversation flows including onboarding new users, daily profit tracking, credit management coaching, and providing business advice while maintaining context across sessions.

Mermaid Diagram

graph TD
    A[When Executed by Another Workflow] --> B[getUserRecord]
    B --> C[getProfitData]
    C --> D[Aggregate Business Records]
    C --> E[getChatHistory]
    E --> F[Limit Chat History]
    F --> G[chatHistory Aggregate]
    D --> H[Merge Data]
    G --> H
    H --> I[Aggregate All Data]
    I --> J[Intent Analysis Tool]
    J --> K[Json Object Parser]
    K --> L[Intent Analysis Object]
    L --> M{Conversation Concluded?}
    M -->|No| N[AI Agent - Main Sifa]
    M -->|Yes| O[No Operation]
    N --> P[Message Parser]
    P --> Q[Insert Chat Log]
    Q --> R[Business Summary Workflow]
    R --> S[Set Output Field]

    T[dailySalesDataCollection] -.-> N
    U[updateUserDataTool] -.-> N
    V[updateUserStatusTool] -.-> N
    W[messageTemplates] -.-> N

    X[Postgres Chat Memory] -.-> N
    Y[OpenRouter Chat Model] -.-> N
    Z[Think Tool] -.-> J
    AA[OpenRouter Chat Model1] -.-> J

Trigger

The workflow is triggered by another workflow via the "Execute Workflow Trigger" node, which receives three input parameters: - phoneNumber: The user's phone number - query: The message content from the user - channel: The communication channel (WhatsApp, SMS, or Call center)

Nodes Used

Node Type Purpose
Execute Workflow Trigger Receives incoming messages from external workflows
Postgres Retrieves user records, business data, and chat history from database
Aggregate Combines multiple data sources into structured objects
Limit Restricts chat history to last 25 messages for context management
Merge Combines chat history and business records for AI processing
AI Agent (Intent Analysis) Analyzes conversation state and determines next actions
AI Agent (Main Sifa) Generates contextual responses as the business coach
Code Parses JSON output from AI agents
Set Structures data for downstream processing
If Conditional logic to check conversation state
No Operation Handles concluded conversations
Tool Workflow Integrates external tools for data collection and user management
Postgres Chat Memory Maintains conversation context across sessions
OpenRouter Chat Model Provides AI language model capabilities
Think Tool Internal reasoning protocol for AI agents

External Services & Credentials Required

  • PostgreSQL Database (Supabase): Stores user profiles, business records, and chat history
    • Credential: "PostgresOnSupabase"
  • OpenRouter API: Provides access to GPT-5.2 language model
    • Credentials: "Prompt Testing for Design team", "OpenRouter account"

Environment Variables

No explicit environment variables are defined in this workflow. Configuration is handled through n8n credentials and node parameters.

Data Flow

Input: - Phone number (string) - User message/query (string) - Communication channel (WhatsApp/SMS/Call center)

Processing: - User profile and business history - Chat conversation context - AI-generated intent analysis - Business coaching logic and templates

Output: - Contextual response message to user - Updated chat log entry - Potential database updates (sales records, user status) - Business summary generation trigger

Error Handling

The workflow includes several error handling mechanisms:

  • JSON Parsing Errors: The Format node includes error handling for malformed AI responses with graceful fallbacks
  • Database Connection Issues: Postgres nodes are configured with error handling
  • AI Model Failures: Multiple AI model credentials provide redundancy
  • Conversation State Recovery: Intent analysis provides fallback states for interrupted conversations

Known Limitations

Based on the workflow configuration:

  • Language Support: Primarily designed for Swahili, English, and Sheng languages
  • SMS Character Limits: Messages must be under 160 characters for SMS channels
  • Channel Restrictions: Call center users have limited functionality (data collection only)
  • Conversation Memory: Limited to 25 recent messages for context
  • Business Record Scope: Focuses specifically on profit tracking and credit management
  • dailySalesDataCollection (fBc6cSMp9Wz1brlZ): Handles daily sales and cost data entry
  • updateUserDataTool (xVkMVJOCq5ptCOHj): Manages user profile updates
  • updateUserStatusTool (nfVcA8ei8x9dE06Z): Updates user onboarding status
  • messageTemplates (IIuvQx5MoV7CkTAJ): Provides message templates for responses
  • create_business_summary_for_youth (Z9ekLMmXz9mHDKut): Generates business summaries

Setup Instructions

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

  2. Configure Database Credentials:

    • Set up PostgreSQL connection to Supabase
    • Ensure database contains required tables: youthEntrepreneursReal, dailyProfitTracking, chatLog, n8n_chat_histories
  3. Configure AI Model Access:

    • Set up OpenRouter API credentials for GPT-5.2 access
    • Configure multiple credential sets for redundancy
  4. Set Up Related Workflows:

    • Import and configure all dependent workflows listed in Related Workflows section
    • Ensure proper workflow IDs are referenced in tool nodes
  5. Database Schema Setup:

    • Create required database tables with proper schema
    • Set up user profiles with fields: firstName, secondName, businessOwned, phoneNumber, onboardingStatus, channel, recruiterName
  6. Test Configuration:

    • Test with sample user data
    • Verify message delivery through intended channels
    • Confirm database updates are working correctly
  7. Channel Integration:

    • Configure WhatsApp Business API integration
    • Set up SMS gateway for feature phone users
    • Implement call center routing if required