2 min read Beginner Updated Jun 2026

Welcome to Kasi Docs

Technical guides, system architectures, and deployment playbooks for Kasi's AI-powered conversational commerce platform.

Core Systems

πŸ€–

SalesAI Engine

Custom LLM pipeline handling product catalog parsing, dynamic pricing, and automated negotiations.

πŸ’¬

Evolution API

Self-hosted WhatsApp Baileys listener for multi-instance message routing and webhook management.

πŸ“±

Meta Graph Framework

Multi-platform Instagram and Facebook DM processor with OAuth and Graph API integration.

πŸ›‘οΈ

Gatekeeper Service

Spam filtering and auto-reply muting system for when vendors need manual attention.

Supported Channels

Kasi connects merchants to customers across four messaging platforms:

🟒 WhatsApp Business πŸ”΅ Telegram 🟣 Instagram DM

Architecture Overview

Kasi operates as a multi-tenant messaging router. Each merchant account maintains isolated product catalogs, conversation histories, and automation rules while sharing a unified API layer and webhook infrastructure.

Component Technology Purpose
Backend API Flask + SQLAlchemy REST API, webhook handlers, AI orchestration
Frontend Dashboard React + Vite Merchant portal, settings, analytics
Database PostgreSQL (prod) / SQLite (dev) Users, products, invoices, integrations
Task Queue Celery + Redis Background jobs, scheduled tasks
Deployment Docker Compose Containerized production stack on VPS
8 min read Advanced Updated Jun 2026

Social Media Integrations

Technical guide for how Kasi connects, authorizes, and handles multi-tenant messaging across WhatsApp, Telegram, Instagram, and Facebook Messenger.

1. Data Model

Core DB Model: Integration

Every connected channel is stored in the integrations table:

ColumnTypeDescription
user_idInteger FKLinks integration to a specific merchant
platformString'whatsapp', 'telegram', 'instagram', or 'facebook'
instance_nameStringUnique session/account identifier (e.g. Evolution instance name, Page ID, IG Business Account ID)
access_tokenStringAPI credentials (Meta PAT, Telegram Bot Token)
connection_statusString'connected', 'pending', or 'disconnected'
is_automatedBooleanToggle to mute/unmute AI auto-replies

2. Platform Breakdowns

🟒 Channel A β€” WhatsApp Business (Evolution API)

WhatsApp integration is powered by the Evolution API (self-hosted service running Node.js + Baileys library).

Connection Flow

  1. Initiation: Merchant enters their phone number in Kasi Settings.
  2. Instance Creation: Backend POST /api/whatsapp/connect provisions a new WhatsApp instance via Evolution API:
    • Endpoint: POST {EVOLUTION_API_URL}/instance/create
    • Webhook Subscription: Instance registers {BASE_URL}/api/whatsapp/webhook for CONNECTION_UPDATE and MESSAGES_UPSERT events.
  3. Pairing Code: Backend polls:
    GET {EVOLUTION_API_URL}/instance/connect/{instance_name}?number={phone}
    Returns an 8-character code (e.g. ABCD-1234).
  4. Linkage: Merchant inputs code in WhatsApp β†’ Linked Devices β†’ Link with Phone Number.
  5. Activation: Evolution API fires CONNECTION_UPDATE with status 'open'. Backend updates integration to connected.

Webhook Message Flow

POST /api/whatsapp/webhook

  • Deduplication: Uses IdempotencyKey table + memory cache (PROCESSED_MESSAGES) to prevent duplicate processing.
  • Audio Transcription: Voice notes are fetched via media API, transcribed by OpenAI Whisper or Groq Whisper, prepended with 🎀 [Voice Note]:.
  • Rider Interceptor: If sender matches a vendor's saved logistics rider and confirms, the invoice is marked "In Transit" with automatic notifications.
  • AI Processing: Routes text to SalesAI.process and images to SalesAI.process_image.

πŸ”΅ Channel B β€” Telegram Bots

Telegram integrations use dedicated bots created via @BotFather.

Connection Flow

  1. Credential Entry: Merchant creates a Telegram bot, obtains the Bot Token, and inputs it in Kasi Settings.
  2. Webhook Registration: Kasi registers the webhook:
    POST https://api.telegram.org/bot{token}/setWebhook?url={BASE_URL}/api/telegram/webhook/{token}
  3. Database Save: Integration saved with platform 'telegram', access_token = token.

Webhook Message Flow

POST /api/telegram/webhook/<token>

  • Routing: Bot token from URL β†’ Integration.query.filter_by(access_token=token) β†’ identifies merchant.
  • Processing: Text passed to SalesAI.process.
  • Dispatch: Reply via POST https://api.telegram.org/bot{token}/sendMessage.

🟣 Channel C β€” Instagram DM & Facebook Messenger

Meta messaging channels use a single Meta Developer App with Graph API and OAuth.

Connection Flow (OAuth)

  1. Authorization Request: Frontend redirects to Facebook's OAuth URL:
    https://www.facebook.com/v21.0/dialog/oauth?client_id={APP_ID}&redirect_uri={FRONTEND_URL}/settings&scope=pages_show_list,pages_messaging,instagram_basic,instagram_manage_messages,pages_read_engagement&response_type=code&state={platform}
  2. Facebook Redirect: After authorization, Facebook redirects back:
    https://usekasi.com/settings?code={auth_code}&state={instagram|facebook}
  3. Code Exchange: Frontend sends code to backend:
    POST /api/meta/oauth/callback
  4. Token Exchange: Backend exchanges auth code for User Access Token via Meta API.
  5. Page List Query: Backend calls /me/accounts to fetch Page IDs and Page Access Tokens.
  6. Account Resolution:
    • Facebook: First Page's ID β†’ instance_name, Page Access Token β†’ access_token.
    • Instagram: Queries each page for instagram_business_account. If found, IG Account ID β†’ instance_name, Page Access Token β†’ access_token.

Webhook Message Flow

POST /api/meta/webhook

  • Signature Verification: Validates x-hub-signature-256 using HMAC-SHA256 with META_APP_SECRET.
  • Routing: Inspects entry.messaging.recipient.id β†’ queries Integration by instance_name.
  • Image Support: CDN URLs fetched, converted to base64, passed to SalesAI.process_image.
  • Response Dispatch:
    POST https://graph.facebook.com/v21.0/me/messages?access_token={page_access_token}
{
  "recipient": {"id": "sender_id"},
  "message": {"text": "AI response text here"}
}

3. Environment Variables

Configuration checklist for backend .env:

# Meta Graph API configuration
META_APP_ID=**********************
META_APP_SECRET=********************************
META_VERIFY_TOKEN=********************************

# Evolution API (WhatsApp) configuration
EVOLUTION_API_URL=http://localhost:8080
EVOLUTION_GLOBAL_API_KEY=************************

# General config
BASE_URL=https://api.usekasi.com

4. Troubleshooting

  1. Meta Webhook Handshake Failing:
    Ensure META_VERIFY_TOKEN matches exactly between the Meta Developer portal and backend .env.
  2. Instagram Webhooks Not Delivering:
    • Verify the Instagram account is set to Business type (Creator type has restrictions).
    • Verify the IG account is linked to the Facebook Page in Settings.
    • Confirm the PAT was granted instagram_manage_messages permission.
  3. WhatsApp Pairing Code Failing:
    Check Evolution API container health: docker ps | grep evolution. Ensure the global API key matches.
5 min read Intermediate Updated Jun 2026

VPS Production Deployment

Command-by-command guide for staging, pushing, deploying, and rebuilding Kasi on a Hostinger VPS with Docker Compose.

1. Architecture Overview

The production VPS uses a containerized Docker network. The database container (kasi_db) runs PostgreSQL on port 5432 with no public port exposure, fully isolated inside the private Docker network (kasi-network).

Development runs on SQLite locally. Production uses PostgreSQL. Schema changes are synchronized via Alembic migration scripts.


2. Git Staging & Pushing (Local)

# Check modified files
git status

# Stage all files
git add .

# Commit with semantic message
git commit -m "feat: complete meta integration webhook"

# Push to GitHub
git push origin main

3. Deploy on VPS

# SSH into VPS
ssh root@***.***.*.* 

# Navigate to backend
cd ~/kasi-backend

# Pull latest
git pull origin main

# Force-rebuild and recreate all containers
docker compose up -d --build --force-recreate

4. Log Tracing (VPS)

# Flask backend logs
docker compose logs -f kasi-backend

# Celery worker logs
docker compose logs -f celery-worker

# Evolution API logs
docker compose logs -f evolution-api

# PostgreSQL logs
docker compose logs -f kasi_db

# Filter for AI intent / errors
docker compose logs -f kasi-backend | grep -E "intent|Intent|Error"

5. Database Migrations

Migrations run inside the Flask container via docker compose exec:

# Standard upgrade
docker compose exec kasi-backend flask db upgrade

# Check current migration version
docker compose exec kasi-backend flask db current

# Stamp database to specific revision (if diverged)
docker compose exec kasi-backend flask db stamp <revision_id>

6. Direct Database Access

# Log into PostgreSQL console
docker exec -it kasi_db psql -U ******** -d ****************

Useful commands:

CommandDescription
\dtList all tables
SELECT id, business_name, kasi_credits FROM users;View merchant credits
SELECT reference, customer_name, total_amount, status FROM invoices ORDER BY created_at DESC LIMIT 5;Last 5 invoices
\qExit console

7. Automated Backups

Set up daily midnight PostgreSQL backups via cron:

# Edit system cron
crontab -e

# Append this line for daily midnight backup
0 0 * * * mkdir -p /root/db-backups && docker exec -t kasi_db pg_dump -U ******** **************** > /root/db-backups/backup_$(date +\%F).sql 2>&1