Skip to content

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:

  1. Initial Setup: Resets daily flags and retrieves user profile data from the database
  2. Data Aggregation: Collects business records, chat history, credit records, and baseline configuration data
  3. Intent Routing: Determines whether to route the conversation to the main coaching agent or a lighter engagement agent
  4. AI Processing: The selected agent processes the user's message using extensive business coaching prompts and reasoning protocols
  5. Tool Integration: Agents can call various tools to update user data, collect sales information, manage credit records, and retrieve message templates
  6. Response Generation: Produces structured JSON responses with messages for youth and optional alerts for Community Education Advisors (CEAs)
  7. 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

  1. User profile and business data retrieval
  2. Chat history and context aggregation
  3. Intent analysis and routing decisions
  4. AI agent processing with tool calls
  5. 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:

  1. Agent Fallback: If AI agents fail, a fallback message is generated: "Samahani, kuna tatizo kidogo. Tafadhali jaribu tena baadaye."

  2. Error Logging: Failed agent calls are logged to an errorLog table with details about the failure

  3. Silent Tool Failures: Tool failures are handled gracefully without exposing errors to users - the conversation continues seamlessly

  4. Database Resilience: Uses alwaysOutputData and continueErrorOutput settings to prevent workflow failures from database issues

  5. Retry Logic: Main AI agent has retry configuration (5 attempts with 2-second delays)

Known Limitations

Based on the extensive system prompts and configuration:

  1. Language Support: Primarily designed for Swahili, Sheng, and English - may not handle other languages effectively

  2. SMS Constraints: Strict 160-character limits for SMS messages require careful message splitting

  3. Time Zone Dependency: Heavily dependent on Nairobi timezone (EAT) for session timing and data collection windows

  4. Onboarding Rigidity: The 13-step onboarding process must be followed exactly - no flexibility for edge cases

  5. Data Collection Windows: Evening data collection is restricted to 7-11 PM, which may not suit all users

  6. Credit Scope: Only tracks credit given TO customers, not debt owed to suppliers

  • 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

  1. 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)
  2. Set up Supabase connection with credential ID: Hw9XWerQ5RNHaVTk

2. AI Service Configuration

  1. Create OpenRouter account and obtain API key
  2. Configure credential with ID: nyvOZDRjkDTKcdPt
  3. 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

  1. Import the workflow JSON
  2. Update all credential references to match your environment
  3. Verify all external workflow IDs are correct
  4. Test with the provided pinned data for user +254707060397

5. Testing

  1. Use the manual trigger with test data
  2. Verify database connections and AI model responses
  3. Test both WhatsApp and SMS formatting paths
  4. 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.