Skip to content

Sifa Agent Internal Team Test

This workflow implements the core Sifa chatbot agent for youth entrepreneur coaching in Kenya. It processes incoming messages through a sophisticated intent analysis system, then generates contextually appropriate responses using AI agents with access to business tracking tools and message templates.

Purpose

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

How It Works

  1. Message Reception: The workflow receives an incoming message with user phone number, query text, and channel information
  2. User Context Loading: Retrieves the user's profile, business records (last 20 entries), and recent chat history (last 25 messages) from the database
  3. Intent Analysis: An AI agent analyzes the conversation state, determines the current stage of interaction, identifies missing data fields, and flags any system actions needed
  4. Conversation State Check: Validates whether the conversation is concluded or should continue processing
  5. Main Agent Processing: The primary AI agent generates an appropriate response using the intent analysis, user context, and available tools
  6. Response Generation: Creates structured JSON output containing messages for the youth and potentially CEA alerts
  7. Message Logging: Saves the conversation turn to the chat log database
  8. Output Formatting: Returns the final response message for delivery

Mermaid Diagram

graph TD
    A[When Executed by Another Workflow] --> B[getUserRecord]
    B --> C[getProfitData]
    C --> D[getChatHistory]
    C --> E[Aggregate - Business Records]
    D --> F[Limit - Chat History]
    F --> G[chatHistory - Aggregate]
    E --> H[Merge]
    G --> H
    H --> I[Aggregate1]
    I --> J[Intent Analysis Tool]
    J --> K[Json Object]
    K --> L[Intent analysis object]
    L --> M[concluded?]
    M -->|Not Concluded| N[AI Agent]
    M -->|Concluded| O[No Operation]
    N --> P[Structured Output Parser2]
    P --> Q[messages]
    Q --> R[Insert rows in a table]
    R --> S[setOutputField]

    T[Postgres Chat Memory] -.-> N
    U[OpenRouter Chat Model] -.-> N
    V[OpenRouter Chat Model1] -.-> J
    W[Think] -.-> J
    X[dailySalesDataCollection] -.-> N
    Y[updateUserDataTool] -.-> N
    Z[updateUserStatusTool] -.-> N
    AA[messageTemplates] -.-> N

Trigger

This workflow is executed by another workflow (parent workflow) that passes in: - phoneNumber: User's phone number for identification - query: The incoming message text - channel: Communication channel (whatsapp/sms/callcenter)

Nodes Used

Node Type Purpose
When Executed by Another Workflow Receives trigger data from parent workflow
Postgres Retrieves user records, business data, and chat history from database
Aggregate Combines multiple database records into structured arrays
Limit Restricts chat history to last 25 messages for context
Merge Combines chat history and business records for analysis
AI Agent (Intent Analysis) Analyzes conversation state and determines next actions
AI Agent (Main) Generates contextual responses using tools and templates
Postgres Chat Memory Maintains conversation context across sessions
OpenRouter Chat Model Provides GPT-5.2 language model capabilities
Structured Output Parser Ensures AI responses follow required JSON schema
Tool Workflow Connects to external workflows for data operations and templates
Think Tool Provides internal reasoning protocol for the intent analysis
Set Formats and structures data between nodes
If Controls flow based on conversation conclusion status
No Operation Handles concluded conversations without further processing

External Services & Credentials Required

Database

  • PostgresOnSupabase: Main database connection for user records, business data, and chat logs

AI Services

  • OpenRouter API: Access to GPT-5.2 model for both intent analysis and main agent processing
    • Credential: "Prompt Testing for Design team"
    • Credential: "OpenRouter account"

Connected Workflows

  • dailySalesDataCollection (ID: fBc6cSMp9Wz1brlZ): Handles daily business data entry
  • updateUserDataTool (ID: xVkMVJOCq5ptCOHj): Updates user profile information
  • updateUserStatusTool (ID: nfVcA8ei8x9dE06Z): Manages user onboarding status
  • messageTemplates (ID: IIuvQx5MoV7CkTAJ): Provides contextual message templates

Environment Variables

No specific environment variables are configured in this workflow. All external connections use stored credentials.

Data Flow

Input

1
2
3
4
5
{
  "phoneNumber": "string",
  "query": "string", 
  "channel": "whatsapp|sms|callcenter"
}

Output

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

Internal Data Structures

The workflow processes complex user context including: - User profile (name, business type, onboarding status) - Business records (sales, costs, profit history) - Chat history (recent conversation turns) - Intent analysis (conversation state, data collection status, system actions)

Error Handling

The workflow includes several error handling mechanisms:

  1. Parse Error Handling: Intent analysis includes fallback for malformed JSON with safe default states
  2. Database Graceful Handling: Uses alwaysOutputData on profit data queries to handle missing records
  3. Conversation State Validation: Checks if conversation is concluded before proceeding with main agent
  4. Tool Validation: Pre-flight checks before calling data collection tools

Known Limitations

Based on the workflow configuration: - Currently set to active: false - workflow is in testing/development mode - Relies on external workflow dependencies that must be available - Limited to 25 recent chat messages for context - Requires specific database schema structure for user and business data

  • dailySalesDataCollection: Handles business data entry and validation
  • updateUserDataTool: Manages user profile updates during onboarding
  • updateUserStatusTool: Tracks user progress through onboarding stages
  • messageTemplates: Provides contextual message generation

Setup Instructions

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

  2. Configure Database Connection:

    • Set up PostgreSQL connection with credential name "PostgresOnSupabase"
    • Ensure required tables exist: youthEntrepreneursReal, dailyProfitTracking, chatLog, n8n_chat_histories
  3. Configure AI Services:

    • Set up OpenRouter API credentials for GPT-5.2 access
    • Create two credential entries: "Prompt Testing for Design team" and "OpenRouter account"
  4. Deploy Connected Workflows:

    • Import and configure the four dependent workflows listed in External Services
    • Ensure they are active and properly configured
  5. Database Schema Setup:

    • Create required database tables with appropriate columns
    • Set up proper indexes for performance on phone number lookups
  6. Test Configuration:

    • Activate the workflow
    • Test with sample input data to verify all connections work
    • Monitor logs for any credential or connection issues
  7. Production Deployment:

    • Set active: true in workflow configuration
    • Configure appropriate error monitoring and alerting
    • Set up backup and recovery procedures for chat history and user data