Skip to content

V4 - saveCreditFollowupTool

A state machine workflow that handles daily credit recovery follow-up interactions for youth entrepreneurs, processing their reports on debt collection attempts and guiding them through structured outcome paths with appropriate coaching and scheduling.

Purpose

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

This workflow serves as both a standalone state machine and an LLM tool for processing credit recovery follow-ups. It handles the complex logic of tracking youth entrepreneurs' attempts to collect debts from customers, providing appropriate responses based on outcomes (promises, partial payments, refusals, fears, etc.), and scheduling appropriate follow-up actions.

How It Works

  1. Input Processing: Receives user data, phone number, and query text from a parent workflow or LLM agent
  2. Safety Check: Immediately detects any mentions of threats or aggression and pauses recovery with CEA alerts
  3. State Machine Logic: Routes through different conversation paths based on the current step and user responses:
    • Outcome Selection: Youth chooses from 7 possible outcomes (promised, partial payment, full payment, refused, forgot, scared, no time)
    • Data Collection: Gathers additional details like relationship type, payment amounts, commitment dates
    • LLM Handoffs: For complex scenarios requiring personalized coaching or scripts
  4. Database Updates: Saves all interaction data and state changes to the youth entrepreneur record
  5. Response Generation: Returns appropriate messages, interactive options, or hands control to parent LLM
  6. Follow-up Scheduling: Sets scheduling signals for future nudges based on outcomes

The workflow includes two operational modes: - State Machine Mode: Direct execution with structured conversation flows - LLM Tool Mode: Simplified input validation and database recording for AI agents

Mermaid Diagram

graph TD
    A[When Executed by Another Workflow] --> B[processStep]
    B --> C{isHandledByAI?}
    C -->|Yes| D[saveAIData]
    C -->|No| E[saveStep]
    D --> F[setPassthrough]
    E --> G[setResponse]

    H[Webhook] --> I[validateAndEncode]
    I --> J[upsertCreditFollowup]
    I --> K[logFollowupHistory]
    J --> L[setOutput]

Trigger

  • Primary: Execute Workflow Trigger - called by parent workflows handling youth entrepreneur interactions
  • Secondary: Webhook endpoint at /credit-path for LLM tool integration

Nodes Used

Node Type Node Name Purpose
Execute Workflow Trigger When Executed by Another Workflow Receives calls from parent workflows
Code processStep Main state machine logic with safety checks and conversation routing
If isHandledByAI? Routes between AI handoff and direct response paths
Postgres saveAIData Updates database when handing off to LLM
Postgres saveStep Updates database for direct responses
Set setPassthrough Prepares AI handoff data
Set setResponse Formats direct response output
Webhook Webhook HTTP endpoint for LLM tool mode
Code validateAndEncode Validates and encodes LLM tool inputs
Postgres upsertCreditFollowup Updates main youth entrepreneur record
Postgres logFollowupHistory Creates historical log entry
Set setOutput Formats tool response for LLM

External Services & Credentials Required

  • PostgreSQL Database: sifaV4Dev credential required
    • Access to v4_youthEntrepreneurs table
    • Access to creditFollowupHistory table

Environment Variables

No specific environment variables are documented in the workflow configuration.

Data Flow

Input (State Machine Mode)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
{
  "phoneNumber": "string (E.164 format)",
  "query": "string (user's text response)",
  "user": {
    "currentCreditFollowupStep": "string",
    "target_debtor_name": "string",
    "target_debtor_amount": "number",
    "target_debtor_relationship": "string",
    "first_micro_action": "string",
    "next_open_debtor_name": "string",
    "next_open_debtor_amount": "number",
    "next_open_debtor_days": "number"
  }
}

Input (LLM Tool Mode)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
{
  "phoneNumber": "string (required)",
  "outcome": "enum (promised|partial|full|refused|forgot|fear|no_time)",
  "relationship_type": "enum (regular|friend|stranger|family)",
  "committed_date_raw": "string",
  "partial_amount": "number",
  "target_debtor_name": "string",
  "target_debtor_amount": "number",
  "fear_description": "string",
  "next_target_accepted": "boolean",
  "reminder_requested": "boolean",
  "safety_concern": "boolean"
}

Output (State Machine Mode)

1
2
3
4
5
6
7
8
{
  "handledByAI": "boolean",
  "output": "string (message text)",
  "outputOptions": "array (interactive buttons)",
  "outputType": "string (plain|interactive)",
  "ai_intent": "string (when handledByAI=true)",
  "ai_context": "string (JSON context for LLM)"
}

Output (LLM Tool Mode)

1
2
3
{
  "output": "string (instruction for LLM on what was recorded and next steps)"
}

Error Handling

  • Input Validation: Invalid outcomes or missing phone numbers return error messages
  • Safety Override: Aggressive language triggers immediate safety protocols
  • Database Errors: PostgreSQL connection issues would cause workflow failure
  • State Validation: Unknown states fall back to outcome selection prompt

Known Limitations

  • Relies on parent workflows for user data retrieval
  • Safety word detection is limited to predefined Swahili/English terms
  • Date parsing for commitments is free-text and may require manual interpretation
  • No built-in retry logic for database operations
  • Parent LLM agent workflows that call this as a tool
  • Scheduler workflows that process credit_followup_scheduled_for signals
  • CEA alert workflows triggered by safety concerns

Setup Instructions

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

  2. Configure Database Credential:

    • Create PostgreSQL credential named sifaV4Dev
    • Ensure access to required tables: v4_youthEntrepreneurs, creditFollowupHistory
  3. Database Schema Setup:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    -- Add required columns to v4_youthEntrepreneurs table
    ALTER TABLE "v4_youthEntrepreneurs" ADD COLUMN IF NOT EXISTS "currentCreditFollowupStep" TEXT;
    ALTER TABLE "v4_youthEntrepreneurs" ADD COLUMN IF NOT EXISTS "target_debtor_relationship" TEXT;
    ALTER TABLE "v4_youthEntrepreneurs" ADD COLUMN IF NOT EXISTS "committed_date_raw" TEXT;
    -- ... (additional columns as documented in sticky notes)
    
    -- Create creditFollowupHistory table
    CREATE TABLE IF NOT EXISTS "creditFollowupHistory" (
      id SERIAL PRIMARY KEY,
      "phoneNumber" TEXT,
      outcome TEXT,
      relationship_type TEXT,
      partial_amount NUMERIC,
      new_balance NUMERIC,
      committed_date_raw TEXT,
      fear_description TEXT,
      schedule_signal TEXT,
      scheduled_at TIMESTAMPTZ,
      safety_concern BOOLEAN DEFAULT FALSE,
      created_at TIMESTAMPTZ DEFAULT NOW()
    );
    

  4. Integration Options:

    • As Execute Workflow: Call from parent workflows using Execute Workflow node
    • As LLM Tool: Use the webhook endpoint with LangChain Tool Workflow node
  5. Testing: Send test payloads to verify state transitions and database updates work correctly

  6. Monitoring: Set up alerts for safety concerns and failed database operations