Skip to content

Francis - SalesTrackingAgent

An AI-powered business coaching system that provides personalized guidance to young entrepreneurs in Kenya through WhatsApp and SMS. The workflow features two specialized AI agents: a main sales tracking agent (Sifa) that handles onboarding and daily business data collection, and an engagement agent that manages casual conversations and entrepreneurial coaching.

Purpose

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

Based on the workflow implementation, this system appears to serve young entrepreneurs in Kenya by: - Guiding them through a structured onboarding process to understand their business - Collecting daily sales and cost data to track profit trends - Providing micro-actions and coaching based on business performance - Managing credit/debt recovery with customers - Escalating welfare concerns to Community Education Advisors (CEAs) - Offering entrepreneurial coaching across 15 development stages

How It Works

  1. Session Context Retrieval: The workflow starts by fetching the user's complete context from a PostgreSQL stored procedure, including their profile, business records, chat history, and credit information.

  2. Context Processing: Multiple processing nodes analyze the user data to determine their current stage, onboarding status, profit trends, missing data, and session requirements.

  3. Intent Routing: A deterministic router analyzes the user's message and context to decide which AI agent should handle the conversation:

    • Main agent for onboarding, data collection, business keywords, distress signals
    • Engagement agent for casual conversation and general entrepreneurial coaching
  4. AI Agent Processing: The selected agent processes the user's message using:

    • Comprehensive system prompts with business coaching protocols
    • Multiple specialized tools for data collection, user management, and credit tracking
    • PostgreSQL chat memory for conversation continuity
    • Structured output parsing to ensure consistent responses
  5. Data Persistence: The workflow saves conversation logs, updates user status, manages CEA alerts for welfare concerns, and tracks business performance metrics.

  6. Response Delivery: The final response is formatted appropriately for the user's channel (WhatsApp or SMS) and returned as structured output.

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]
    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
    LL[Structured Output Parser2] -.->|ai_outputParser| I
    MM[Postgres Chat Memory] -.->|ai_memory| I
    NN[sifa_main_agent_prod] -.->|ai_languageModel| I

    %% Engager agent connections
    OO[Structured Output Parser7] -.->|ai_outputParser| M
    PP[Engager Chat Memory] -.->|ai_memory| M
    QQ[sifa_engager_agent_prod] -.->|ai_languageModel| M

Trigger

The workflow is triggered by another workflow via the "Execute Workflow Trigger" node, expecting three input parameters: - phoneNumber: User's phone number (unique identifier) - query: User's message or system nudge - channel: Communication channel (WhatsApp or SMS)

Nodes Used

Node Type Node Name Purpose
Execute Workflow Trigger When Executed by Another Workflow Receives input from calling workflow
PostgreSQL getSessionContext Retrieves user context via stored procedure
Code getUserRecord Unpacks user data from stored procedure result
Code chatAndBusinessHistory Formats context data for AI agents
Code computeContext Pre-computes business metrics and session state
Code buildPromptSections Assembles conditional system prompts
Code Intent Router Routes messages to appropriate AI agent
If If Routes based on intent decision
LangChain Agent AI Agent Main business coaching agent (Sifa)
LangChain Agent engager_agent General entrepreneurial coaching agent
LangChain Tool Workflow dailySalesDataCollection Records daily sales and cost data
LangChain Tool Workflow updateUserDataTool Updates user profile information
LangChain Tool Workflow updateUserStatusTool Updates onboarding status
LangChain Tool Workflow saveCreditRecordTool Manages credit/debt tracking
LangChain Tool Workflow callBaselineDataCollection Saves onboarding baseline data
LangChain Tool Workflow messageTemplates Retrieves message templates
LangChain Tool Think Think Internal reasoning for main agent
LangChain Output Parser Structured Output Parser2/7 Ensures consistent JSON output
LangChain Memory Postgres Chat Memory/Engager Chat Memory Maintains conversation history
LangChain LLM sifa_main_agent_prod/sifa_engager_agent_prod OpenRouter LLM connections
Set Various message nodes Formats response data
PostgreSQL Insert rows in a table (multiple) Logs conversations and data
PostgreSQL persistState Updates user state in database
PostgreSQL insertCeaAlert Creates alerts for Community Education Advisors
PostgreSQL logAgentError Records system errors
If ifCeaAlertRequired Checks if CEA alert is needed
Split Out Split Out Handles multiple message responses
HTTP Request logMainAgentToPL/logEngagerAgentToPL Logs interactions to PromptLayer
HTTP Request addMainToPLDataset/addEngagerToPLDataset Adds logs to PromptLayer datasets

External Services & Credentials Required

PostgreSQL Database

  • Credential: "Postgres account" (ID: EJPqF6MDH1ZwAzyv)
  • Purpose: Stores user data, business records, chat history, and system state
  • Tables: youthEntrepreneursReal, chatLog, ceaAlerts, errorLog, and related tables

OpenRouter API

  • Credentials:
    • "sifa_main_agent_prod" (ID: TCRDuARS44G76WWp)
    • "sifa_engager_agent_prod" (ID: hRNRvdhUlZaxUTUM)
  • Purpose: Provides access to GPT-5.2 and Claude Sonnet 4.6 models
  • Models Used:
    • openai/gpt-5.2 for main sales tracking agent
    • anthropic/claude-sonnet-4.6 for engagement agent

PromptLayer API

  • API Key: pl_80a83a0db8150339b213693376a60afb
  • Purpose: Logs AI interactions for monitoring and analysis
  • Datasets: Separate tracking for main agent (20286) and engager agent (20287)

Environment Variables

No explicit environment variables are defined in the workflow configuration. All external service connections use stored credentials.

Data Flow

Input

  • phoneNumber: String - User's phone number identifier
  • query: String - User's message or "system_nudge" for automated prompts
  • channel: String - "WhatsApp" or "SMS"

Processing

  1. User context retrieval from database
  2. Business metrics calculation (profit trends, missing data, current stage)
  3. Intent classification and agent routing
  4. AI agent processing with tool calls for data management
  5. Response formatting based on channel requirements

Output

  • output: String - Final message to send to user
  • Side effects: Database updates, conversation logging, CEA alerts

Error Handling

The workflow implements comprehensive error handling:

  1. Agent Fallback: If AI agents fail, a fallback message is provided in Swahili with contact information for manual support
  2. Tool Failure Resilience: Tool failures are handled silently without disrupting user experience
  3. Error Logging: All errors are logged to the errorLog table with context
  4. Retry Logic: Database operations include retry mechanisms (2-3 attempts with delays)
  5. Continue on Error: Most nodes are configured to continue execution even if errors occur
  6. Graceful Degradation: Missing data or context is handled with safe defaults

Known Limitations

Based on the workflow implementation:

  1. Language Support: Primarily designed for Swahili, Sheng, and English speakers in Kenya
  2. Channel Restrictions: Limited to WhatsApp and SMS communication
  3. Time Zone Dependency: Hardcoded to Nairobi timezone (EAT, UTC+3)
  4. Data Collection Windows: Specific time-based rules for when data collection can occur
  5. Single User Processing: Processes one user conversation at a time
  6. Database Dependency: Requires PostgreSQL with specific schema and stored procedures

The workflow references several sub-workflows: - dailySalesDataCollection (aOQRTnNvRUCjjwRE) - updateUserDataTool (ON18WqpuHwpe5jc6) - updateUserStatusTool (Ht3MkckUHVE039d0) - saveCreditRecordTool (SmNrxmAoEYSMqQDe) - saveOnboardingBaselineTool (Ro2mHPinIURfchxo) - messageTemplates (h77nzSL65k3aj1VU) - create_business_summary (2nTlbf07leuKBdM9)

Setup Instructions

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

  2. Configure Database:

    • Set up PostgreSQL database with required schema
    • Create the stored procedure get_session_context
    • Configure the "Postgres account" credential
  3. Set Up AI Services:

    • Create OpenRouter API accounts
    • Configure credentials for both main and engager agents
    • Set up PromptLayer account for logging (optional)
  4. Deploy Sub-workflows:

    • Import and configure all referenced sub-workflows
    • Ensure workflow IDs match the references in tool configurations
  5. Configure Credentials:

    • Add PostgreSQL connection details
    • Add OpenRouter API keys
    • Add PromptLayer API key (if using logging)
  6. Test Setup:

    • Use the pinned test data to verify functionality
    • Test with different user scenarios (new user, active user, etc.)
    • Verify database connections and tool workflows
  7. Production Deployment:

    • Update any test mode configurations
    • Set up monitoring for error logs and CEA alerts
    • Configure backup and recovery procedures for the database