Skip to content

V4 - WIP - Francis - SalesTrackingAgent

A comprehensive AI-powered business coaching system for young entrepreneurs in Kenya that provides daily profit tracking, credit management, and personalized micro-actions through WhatsApp and SMS channels.

Purpose

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

This workflow serves as the main orchestration layer for the Educate! Kenya program's digital business coaching platform. It manages the complete entrepreneurship journey from initial onboarding through active business coaching, helping young entrepreneurs track daily profits, manage customer credit, and receive actionable business advice through conversational AI.

How It Works

  1. Session Context Retrieval: When triggered, the workflow first retrieves the user's complete context including their profile, business records, chat history, and current onboarding status from the database.

  2. Context Processing: The system processes and formats the retrieved data, computing key metrics like current business day, profit trends, missing data days, and session mode (onboarding vs. active coaching).

  3. Onboarding Check: The workflow determines if the user is in an onboarding phase (new user journey) or active coaching phase, routing accordingly.

  4. Intent Routing: For active users, a deterministic intent router analyzes the user's message and context to decide between the main sales tracking agent or the engagement agent based on business keywords, data collection needs, and conversation context.

  5. AI Agent Processing: The appropriate AI agent processes the user's message using contextual prompts, accessing various tools for data collection, user status updates, and credit tracking as needed.

  6. Response Generation: The AI generates structured responses in JSON format, handling both youth-facing messages and internal CEA (Community Enterprise Advisor) alerts when needed.

  7. Data Persistence: All interactions are logged to the chat history, business data is saved when collected, and user status is updated as they progress through different stages.

  8. Output Formatting: The final response is formatted according to the communication channel (WhatsApp vs SMS) and returned to the calling system.

Mermaid Diagram

graph TD
    A[When Executed by Another Workflow] --> B[getSessionContext]
    B --> C[getUserRecord]
    C --> D[chatAndBusinessHistory]
    D --> E[computeContext]
    E --> F[isOnboardingPhase?]
    F --> G{isOnboardingPhase? Route}
    G -->|Yes| H[Call OnboardingJourneyHandler]
    G -->|No| I[buildPromptSections]
    H --> J{shouldUseAI?}
    J -->|Yes| I
    J -->|No| K[onboarding_setOutput]
    I --> L[Intent Router]
    L --> M{If}
    M -->|main_agent| N[AI Agent]
    M -->|engagement_agent| O[Set Engager Context]
    N --> P[Extract CEA Alert]
    O --> Q[engager_agent]
    P --> R{If1}
    R -->|Multiple Messages| S[Split Out]
    R -->|Single Message| T[messages]
    S --> U{If2}
    U -->|Youth Message| V[messages2]
    V --> W[Insert rows in a table3]
    T --> X[Insert rows in a table]
    Q --> Y[messages1]
    Y --> Z[Insert rows in a table2]
    X --> AA[persistState]
    AA --> BB{ifCeaAlertRequired}
    BB -->|Alert Needed| CC[insertCeaAlert]
    BB -->|No Alert| DD[setOutputField]
    CC --> DD

    %% Tool connections to AI Agent
    EE[dailySalesDataCollection] -.->|ai_tool| N
    FF[updateUserDataTool] -.->|ai_tool| N
    GG[updateUserStatusTool] -.->|ai_tool| N
    HH[Think] -.->|ai_tool| N
    II[messageTemplates] -.->|ai_tool| N
    JJ[saveCreditRecordTool] -.->|ai_tool| N
    KK[callBaselineDataCollection] -.->|ai_tool| N
    LL[Postgres Chat Memory] -.->|ai_memory| N
    MM[sifa_main_agent_prod] -.->|ai_languageModel| N
    NN[Structured Output Parser2] -.->|ai_outputParser| N

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

Trigger

This workflow is triggered by another workflow via the "When Executed by Another Workflow" trigger. It expects the following input parameters: - phoneNumber: The user's phone number (unique identifier) - query: The user's message/input text - channel: Communication channel (WhatsApp or SMS)

Nodes Used

Node Type Node Name Purpose
Execute Workflow Trigger When Executed by Another Workflow Receives calls from other workflows with user input
PostgreSQL getSessionContext Retrieves complete user context from database
Code getUserRecord Processes and flattens user data for downstream use
Code chatAndBusinessHistory Formats context data for AI agents
Code computeContext Pre-computes session metrics and business analytics
Code isOnboardingPhase? Determines if user is in onboarding vs active phase
If isOnboardingPhase? Route Routes between onboarding and active coaching flows
Execute Workflow Call OnboardingJourneyHandler Handles structured onboarding journey
Code buildPromptSections Builds contextual system prompts for AI agents
Code Intent Router Routes between main agent and engagement agent
AI Agent AI Agent Main sales tracking and coaching agent
AI Agent engager_agent Handles casual conversation and engagement
LangChain Tools dailySalesDataCollection Saves daily business data to database
LangChain Tools updateUserDataTool Updates user profile information
LangChain Tools updateUserStatusTool Updates user onboarding status
LangChain Tools saveCreditRecordTool Manages credit/debt tracking data
LangChain Tools callBaselineDataCollection Saves onboarding baseline configuration
LangChain Tools messageTemplates Retrieves message templates for consistent communication
LangChain Tools Think Provides reasoning capabilities to AI agents
PostgreSQL Chat Memory Postgres Chat Memory Maintains conversation history for main agent
PostgreSQL Chat Memory Engager Chat Memory Maintains conversation history for engagement agent
OpenRouter LLM sifa_main_agent_prod GPT-5.2 model for main coaching agent
OpenRouter LLM sifa_engager_agent_prod Claude Sonnet 4.6 model for engagement agent
PostgreSQL Multiple Insert Nodes Log conversations and manage data persistence
HTTP Request Logging Nodes Send interaction logs to PromptLayer for monitoring

External Services & Credentials Required

Database

  • PostgreSQL Database: Stores user profiles, business records, chat history, and system state
    • Required tables: v4_youthEntrepreneurs, v4_chatLog, v4_dailyProfitTracking, ceaAlerts, onboardingBaseline, creditTracking

AI Services

  • OpenRouter API: Provides access to multiple LLM models
    • GPT-5.2 for main coaching agent
    • Claude Sonnet 4.6 for engagement agent
    • Requires OpenRouter API key

Monitoring & Analytics

  • PromptLayer: Logs AI interactions for monitoring and dataset creation
    • Requires PromptLayer API key
    • Used for conversation analytics and model performance tracking

Sub-workflows

  • OnboardingJourneyHandler: Manages structured user onboarding
  • dailySalesDataCollection: Handles business data persistence
  • create_business_summary: Generates business performance summaries

Environment Variables

The workflow requires the following credentials to be configured in n8n: - PostgreSQL database connection credentials - OpenRouter API key for LLM access - PromptLayer API key for logging (optional but recommended)

Data Flow

Input

1
2
3
4
5
{
  "phoneNumber": "string",
  "query": "string", 
  "channel": "WhatsApp|SMS"
}

Output

1
2
3
{
  "output": "string"
}

Internal Data Structures

  • User Context: Complete user profile, business history, and session state
  • Business Records: Daily sales, costs, and profit tracking data
  • Chat History: Conversation context for AI agents
  • CEA Alerts: Internal notifications for human advisors when intervention is needed

Error Handling

The workflow implements comprehensive error handling:

  1. Tool Failures: AI tools that fail are handled silently - the conversation continues without exposing backend errors to users
  2. Agent Fallbacks: If the main AI agent fails, a fallback message is provided: "Samahani, kuna tatizo kidogo kwa sasa..."
  3. Data Validation: Input validation prevents invalid business data from being saved
  4. Error Logging: All errors are logged to the errorLog table for debugging
  5. Graceful Degradation: The system continues operating even if non-critical services fail

Known Limitations

Based on the workflow structure, potential limitations include: - Dependency on external AI services (OpenRouter) for core functionality - Complex state management across multiple database tables - Language processing primarily optimized for Swahili/English mix - SMS character limits may truncate longer coaching messages - Real-time performance dependent on database query efficiency

  • V4 - OnboardingJourneyHandler: Manages the structured user onboarding process
  • dailySalesDataCollection: Handles business data persistence and validation
  • updateUserDataTool: Manages user profile updates
  • create_business_summary: Generates periodic business performance reports
  • messageTemplates: Provides consistent messaging templates

Setup Instructions

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

  2. Configure Database:

    • Set up PostgreSQL database with required tables
    • Configure database credentials in n8n
  3. Set Up AI Services:

    • Obtain OpenRouter API key
    • Configure OpenRouter credentials in n8n
    • Test LLM model access
  4. Configure Sub-workflows:

    • Import and configure all related workflows
    • Ensure proper workflow IDs are referenced
  5. Set Up Monitoring (Optional):

    • Configure PromptLayer API key for interaction logging
    • Set up monitoring dashboards
  6. Test Integration:

    • Test with sample user data
    • Verify database writes and AI responses
    • Test both WhatsApp and SMS formatting
  7. Deploy:

    • Activate the workflow
    • Configure calling workflows to use this endpoint
    • Monitor initial interactions for proper functionality