Islamic AI Companion

Abdullah Bot API

A spiritually-grounded conversational API built on Meta's Llama-3 models. Designed for Muslim lifestyle apps — combines tone detection, journey tracking, Quranic references and multilingual support in a single, deployable FastAPI backend.

3
Llama-3 Fallback Models
13
Tone Detection Modes
11
MCQ Categories
3
Languages Supported

What is this API?

The Abdullah Bot API is a production-ready backend that powers Islamic AI companions. It wraps Hugging Face's Router API with a 3-tier model fallback system, integrates Supabase for persistent journey tracking, and delivers structured, tone-aware responses grounded in Quranic wisdom.

The API is designed to be consumed by Flutter mobile apps, web frontends, or any HTTP client. Every response includes a voice_answer, optional middle_section detail, follow_up prompt, and next_action_guidance — making it trivial to build rich, structured UIs.

Architecture

  • FastAPI backend hosted on Hugging Face Spaces (free tier)
  • Llama-3-8B → Llama-3.1-8B → Llama-3.2-1B automatic fallback chain
  • Supabase Postgres for users, journeys, MCQ answers, chat history
  • Al-Quran Cloud API for real-time Quranic verse fetching
  • Tone & language detection — 13 tones, Arabic / Urdu / Roman-Urdu / English
  • Retry logic with exponential backoff on DB cold starts
  • Structured response format optimised for voice + text hybrid UIs
ℹ️
Base URL: https://frnklnwrld-me.hf.space
All endpoints return JSON. No API key required from clients — the HF token is server-side only.
Getting Started

Quick Start

Send your first message in under 2 minutes.

01

Send a POST to /chat

The only required fields are message and user_id. The API handles everything else automatically.

02

Receive a structured response

Every response contains voice_answer (short, speakable), middle_section (detail), and follow_up (next prompt).

03

Start a journey (optional)

Send "start journey" to begin MCQ-based self-assessment. The API tracks progress per user per category in Supabase.

cURL Example

bash
curl -X POST https://frnklnwrld-me.hf.space/chat \
  -H "Content-Type: application/json" \
  -d '{
    "message": "What is the meaning of patience in Islam?",
    "user_id": "Abdullah123",
    "category": "Religious Self"
  }'

JavaScript (fetch)

javascript
const response = await fetch('https://frnklnwrld-me.hf.space/chat', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    message: 'What is sabr?',
    user_id: 'user_abc123',
    category: 'Religious Self'
  })
});

const data = await response.json();
console.log(data.voice_answer);   // Short spoken response
console.log(data.middle_section); // Detailed notes
console.log(data.follow_up);      // Next conversation prompt

Python (requests)

python
import requests

res = requests.post(
    "https://frnklnwrld-me.hf.space/chat",
    json={
        "message": "I feel sad today",
        "user_id": "testuser",
        "category": "Emotional Self"
    }
)
data = res.json()
print(data["voice_answer"])
print(data["model_used"])   # Which Llama model responded

Sample Response

json
{
  "status": "insight_only",
  "voice_answer": "SubhanAllah, I hear the weight in your words. Remember, after hardship comes ease (Quran 94:5). You are not alone — Allah is closer to you than your jugular vein.",
  "middle_section": "Sadness is a human experience acknowledged in the Quran. The Prophet ﷺ himself experienced grief deeply. Allowing yourself to feel is not weakness — it is honesty before Allah.",
  "middle_label": "Detailed Notes",
  "follow_up": "Would you like to explore what specifically is weighing on your heart today?",
  "references": "Quran 94:5 — Indeed, with hardship comes ease.",
  "model_used": "Llama-3-8B-Instruct",
  "next_action_guidance": {
    "type": "general_chat",
    "message": "Assalamu alaikum. How fares your heart today?",
    "suggested_delay_hours": 6,
    "islamic_reminder": "Quranic Principle: Do not despair of Allah's mercy (39:53)."
  }
}
Security

Authentication

No client-side API key needed. The API is publicly accessible. All sensitive credentials (HF token, Supabase keys) are stored as server-side secrets on Hugging Face Spaces.

Server-Side Secrets

The following environment variables must be set in your HF Space Settings → Secrets:

env
HF_TOKEN=hf_xxxxxxxxxxxxxxxxxx          # Hugging Face token with Inference API access
SUPABASE_URL=https://xxxx.supabase.co   # Your Supabase project URL
SUPABASE_SERVICE_KEY=sbp_xxxxxxxxxxxx   # Service role key (NOT anon key)
⚠️
Never commit credentials to code. Use the HF Spaces Secrets UI. If a key was ever hardcoded, regenerate it immediately in Supabase Dashboard → Settings → API → Regenerate.

User Identity

Users are identified by user_id (display name string) in every request. There is no JWT/session auth — the API trusts the client-provided user_id. For production apps, validate identity in your own middleware before hitting this API.

API Reference

/chat

The core endpoint. Handles all conversation, journey flow, and MCQ submission.

POST /chat Main conversation endpoint

Request Body

FieldTypeDescription
messagerequiredstringUser's message. Max 1000 characters. Supports English, Urdu (script + Roman), Arabic.
user_idrequiredstringUnique user identifier / display name. Used to look up journey and chat history in Supabase.
categoryoptionalstringJourney category context. Default: "General". Use values from /categories.
previous_summaryoptionalobjectPreviously returned cumulative_summary object to carry session context forward.
answersoptionalarrayMCQ answer submission array. Each item: {question_num, answer, score}.

Response Fields

statusstringOne of: insight_only, asking_questions, need_more_answers, session_complete, meta_response
voice_answerstringShort, conversational response — designed for TTS / display as primary message.
middle_sectionstring?Extended detail, practical takeaway, or reflective content. May be null for simple exchanges.
middle_labelstring?Label for middle_section, e.g. "Detailed Notes", "Practical Takeaway", "Progress Summary".
current_mcqsarray?Array of MCQ objects to display. Each: {question: string, options: string[]}.
answers_summaryobject?Summary of just-submitted answers: {batch_avg: number}.
cumulative_summaryobject?Full journey progress object. Persist and send back as previous_summary.
follow_upstring?Suggested next question or action to continue the conversation.
referencesstring?Quranic/Hadith reference when the message is Islamic in nature.
next_action_guidanceobjectAlways present. Contains {type, message, suggested_delay_hours, islamic_reminder}.
model_usedstring?Which model responded: Llama-3-8B-Instruct, Llama-3.1-8B-Instruct, Llama-3.2-1B-Instruct, or fallback.

Status Values Explained

StatusMeaningUI Action
insight_onlyGeneral AI responseDisplay voice_answer + optional middle_section
asking_questionsMCQ journey startedRender current_mcqs as a form
need_more_answersMore answers neededShow remaining MCQs
session_completeAll MCQs answeredShow progress summary + celebrate
meta_responseUser asked about bot behaviorDisplay explanation
API Reference

/journey

GET /journey/{user_id} Fetch user progress

Path & Query Parameters

ParamTypeDescription
user_idpathstringThe user's display name / identifier.
categoryquerystringFilter to a specific journey category. Default: "General".

Example

bash
GET /journey/Abdullah123?category=Religious+Self

Response

json
{
  "user_id": "Abdullah123",
  "category": "Religious Self",
  "total_sessions": 12,
  "spiritual_stage": "developing",
  "member_since": "2025-01-15",
  "cumulative_summary": {
    "overall_avg": 3.8,
    "progress_note": "Recent avg: 4.2/5 | Improving MashaAllah"
  },
  "main_loopholes": ["Low in Q3", "Low in Q7"],
  "pending_questions": 3,
  "recent_activity": [...]
}
API Reference

/categories

GET /categories List all MCQ journey categories

Returns all available self-assessment journey categories with question counts. Use these values in the category field of other requests.

json
{
  "categories": [
    "Religious Self",
    "Emotional Self",
    "Intellectual Self",
    "Social Self",
    "Physical Self",
    "Financial Self",
    "Family Self",
    "Professional Self",
    "Creative Self",
    "Community Self",
    "General"
  ],
  "total_questions": {
    "Religious Self": 12,
    "Emotional Self": 10,
    "General": 8
  },
  "description": "Categories for spiritual and personal development journeys"
}
API Reference

/reset-journey

POST /reset-journey/{user_id} Reset journey in a category

Clears all journey progress (MCQ answers, summary, loopholes, pending questions) for a user in a specific category. The user record and chat history are preserved.

ParamTypeDescription
user_idpathstringUser to reset.
categoryquerystringCategory to reset. Default: "General".
json — Response
{
  "status": "success",
  "message": "Journey reset for Abdullah123 in Religious Self. Ready to start fresh, insha'Allah!",
  "islamic_reminder": "Quranic Principle: Indeed, with hardship comes ease (94:5)."
}
API Reference

/health

GET /health API status & model config

Use this to verify the API is running and which models are configured. Recommended for Flutter app startup checks.

json
{
  "status": "OK",
  "mode": "HF Router API (Free Tier)",
  "models": [
    "Llama-3-8B-Instruct",
    "Llama-3.1-8B-Instruct",
    "Llama-3.2-1B-Instruct"
  ],
  "api_url": "https://router.huggingface.co/v1/chat/completions",
  "token_configured": true
}
Concepts

Tone Detection

The API automatically detects the emotional tone of every message and adjusts response style, persona, and language accordingly.

Tone is detected via multilingual keyword matching across 13 emotional states. The detected tone shapes the system prompt, persona, and Islamic framing of the response — no configuration required from the client.

sad
Gentle, Quranic comfort. Validates feelings, offers 1-2 grounded steps.
anxious
Soothing, tawakkul-based grounding. 3 practical steps.
angry
Calm, de-escalating. Short sentences, prophetic patience.
energetic
High-energy, motivating. Islamic encouragement + action prompts.
curious
Engaging, instructive. Concise explanation + follow-up question.
confused
Supportive, numbered steps. Asks one clarifying question.
grateful
Warm, reflective. Acknowledges with Alhamdulillah.
reflective
Introspective. Quranic metaphor + one practical takeaway.
urgent
Direct, numbered steps (1-3). Safety check when relevant.
dive_deep
Structured sections: Summary / Details / Example.
humorous
Playful, kind. Maintains adab (respect).
skeptical
Evidence-focused. Islamic sources + counterexample.
neutral
Balanced, friendly. Default for all unmatched messages.
💡
Tone keywords work in English, Roman Urdu (e.g. dukhi, ghussa), and Urdu script (e.g. افسردہ, غصہ). The model_used field in the response won't tell you the tone — but next_action_guidance.message will reflect the tone persona used.
Concepts

Journey Flow

The journey system enables longitudinal self-assessment across 11 spiritual and personal development categories.

1

User sends "start journey"

API generates 6 MCQs from the selected category (or resumes pending questions). Returns status: "asking_questions" with current_mcqs array.

2

User submits answers

Send answers in answers array: [{question_num: 1, answer: "Often", score: 4}]. Or inline in message text: "1. Often 2. Rarely 3. Always".

3

Progress computed & saved

Scores averaged with exponential smoothing (30% new / 70% historical). Low-scoring answers recorded as "loopholes" for targeted follow-up.

4

Session complete

Returns status: "session_complete" with cumulative_summary. Store this and pass back as previous_summary in future requests.

MCQ Options & Score Map

json
{
  "options": ["Always", "Often", "Sometimes", "Rarely", "Never"],
  "scores":  [   5,       4,        3,          2,        1   ]
}
Concepts

Multilingual

The API detects and mirrors the user's language automatically — no configuration needed.

Supported Languages

  • English — default, full feature support
  • Urdu script (نستعلیق) — detected via Unicode range U+0600–U+06FF + Urdu-specific characters
  • Roman Urdu — detected via keyword matching (ap, kya, kyun, bhai, alaikum, hain…)
  • Arabic — detected via Unicode; uses Arabic Islamic terminology

Example — Urdu Input

json — Request
{
  "message": "آج میں بہت اداس ہوں",
  "user_id": "user123"
}

The API detects Urdu script, sets detected_lang: "ur", and responds in Urdu with culturally relevant Islamic phrasing and dua.

Concepts

Model Fallback

A 3-tier automatic fallback ensures the API stays responsive even when primary models are rate-limited or unavailable.

Fallback Chain

priority order
1. meta-llama/Meta-Llama-3-8B-Instruct    → Best quality
2. meta-llama/Llama-3.1-8B-Instruct       → Latest stable  
3. meta-llama/Llama-3.2-1B-Instruct       → Fastest / lightest

Each model is tried with up to 2 retries and exponential backoff on rate limits (429). If all 3 models fail, a graceful Islamic fallback message is returned rather than a 500 error.

Retry Logic

python
for model in MODELS:           # Try each model in priority order
    for attempt in range(2):   # Up to 2 retries per model
        if status == 429:
            time.sleep(2 ** attempt)   # 1s, then 2s backoff
            continue
        if status == 200:
            return answer, model_name  # Success — stop here
        break                  # Other error — try next model
ℹ️
The model_used field in every response tells you which model actually answered. Values: Llama-3-8B-Instruct, Llama-3.1-8B-Instruct, Llama-3.2-1B-Instruct, fallback, or emergency_fallback.
Integration

Flutter Guide

A complete example for integrating Abdullah Bot into a Flutter/Dart app.

Service Class

dart
import 'dart:convert';
import 'package:http/http.dart' as http;

class AbdullahBotService {
  static const String baseUrl = 'https://frnklnwrld-me.hf.space';

  Future sendMessage({
    required String message,
    required String userId,
    String category = 'General',
    Map? previousSummary,
    List? answers,
  }) async {
    final response = await http.post(
      Uri.parse('$baseUrl/chat'),
      headers: {'Content-Type': 'application/json'},
      body: jsonEncode({
        'message': message,
        'user_id': userId,
        'category': category,
        if (previousSummary != null) 'previous_summary': previousSummary,
        if (answers != null) 'answers': answers,
      }),
    );

    if (response.statusCode == 200) {
      return jsonDecode(response.body);
    } else if (response.statusCode == 503) {
      throw Exception('Service waking up — please retry in a moment');
    } else {
      throw Exception('API error: ${response.statusCode}');
    }
  }

  Future getJourney(String userId, {String category = 'General'}) async {
    final response = await http.get(
      Uri.parse('$baseUrl/journey/$userId?category=$category'),
    );
    return jsonDecode(response.body);
  }
}

Widget Usage

dart
// In your chat widget:
final bot = AbdullahBotService();
final data = await bot.sendMessage(
  message: userInput,
  userId: currentUser.id,
  category: selectedCategory,
);

// Render the structured response:
Text(data['voice_answer'])          // Primary message bubble
Text(data['middle_section'] ?? '')  // Expandable detail card
Text(data['follow_up'] ?? '')       // Suggested reply chip
Text(data['references'] ?? '')      // Quranic reference footer
⚠️
Cold start handling: On first request after inactivity, Supabase may take 3-7s to wake. Show a loading indicator and handle 503 responses with a "Waking up…" message and auto-retry after 5s.
Integration

Error Handling

400
Bad Request
Missing required fields. Check that message and user_id are present and non-empty.
503
Service Unavailable
Supabase cold start. Retry after 5 seconds. The API returns a human-readable detail message: "Database is waking up — please retry in a few seconds."
500
Internal Server Error
Unexpected error. Check HF Space logs. Common causes: missing secrets, Supabase schema mismatch, all 3 Llama models failed simultaneously.

Recommended Client Pattern

javascript
async function chatWithRetry(message, userId, retries = 3) {
  for (let i = 0; i < retries; i++) {
    try {
      const res = await fetch('/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message, user_id: userId })
      });

      const text = await res.text();
      let data;
      try { data = JSON.parse(text); }
      catch { throw new Error('Server error: ' + text.slice(0, 100)); }

      if (res.status === 503) {
        // Supabase cold start — wait and retry
        await new Promise(r => setTimeout(r, 5000));
        continue;
      }
      if (!res.ok) throw new Error(data.detail || 'Request failed');
      return data;

    } catch (err) {
      if (i === retries - 1) throw err;
      await new Promise(r => setTimeout(r, 2000 * (i + 1)));
    }
  }
}
Upwork Proposal Materials

Proposal Kit

Ready-to-use materials for hiring Flutter developers, backend engineers, or AI integration specialists on Upwork.

🎯 Proposal Template — Flutter Developer

Copy, personalise, and post as a job or use as an opening message.

Upwork Job Post — Flutter Developer
Title: Flutter Developer — Islamic AI Companion App (Abdullah Bot)

We're building a Flutter mobile app powered by a live FastAPI backend
(hosted on Hugging Face Spaces). The backend is complete and production-ready.
We need an experienced Flutter developer to build the mobile UI.

=== BACKEND OVERVIEW ===
• Live API: https://frnklnwrld-me.hf.space
• Swagger docs: https://frnklnwrld-me.hf.space/docs
• AI Model: Meta Llama-3 (3-tier fallback)
• Database: Supabase (Postgres)
• Features: Tone detection (13 modes), Journey tracking, MCQ system,
  Multilingual (English/Urdu/Arabic), Quranic references

=== YOUR RESPONSIBILITIES ===
1. Build Flutter chat UI consuming POST /chat endpoint
2. Render structured responses: voice_answer + middle_section + follow_up
3. Implement MCQ journey screen (render current_mcqs array as interactive form)
4. Journey progress screen using GET /journey/{user_id}
5. Category picker using GET /categories
6. Handle cold-start 503 errors with graceful retry UX
7. State management (Provider or Riverpod preferred)
8. Local caching of cumulative_summary

=== API RESPONSE STRUCTURE ===
Every /chat response returns:
- voice_answer (string): Primary message — display as main chat bubble
- middle_section (string?): Detail card — collapsible
- follow_up (string?): Suggested next message chip
- current_mcqs (array?): MCQ questions to render as form
- model_used (string): Which AI model responded
- next_action_guidance (object): UI hints

=== REQUIREMENTS ===
• 3+ years Flutter experience
• REST API integration (http or dio package)
• Clean architecture preferred
• Portfolio of chat/messaging UIs required
• Islamic/Arabic UI experience is a strong plus

=== DELIVERABLES ===
• Complete Flutter project (clean code, well-commented)
• APK for testing
• README with setup instructions

Please share 2-3 examples of chat apps you've built.
Budget: [your budget] | Timeline: 2-3 weeks
💡
Pro tip: Attach the live API URL (https://frnklnwrld-me.hf.space) and Swagger docs link to your Upwork job post. Developers can test the API before applying, which filters for engineers who actually read the brief.

🎯 Proposal Template — Backend / DevOps

Upwork Job Post — Backend Engineer
Title: FastAPI / Python Developer — Enhance Islamic AI Bot Backend

We have a production FastAPI backend for an Islamic AI companion app.
The core is working. We need help with improvements and scaling.

=== CURRENT STACK ===
• FastAPI + Python 3.10
• Hugging Face Spaces (hosting)
• Supabase (Postgres + REST)
• Meta Llama-3 via HF Router API (3-model fallback)
• Live at: https://frnklnwrld-me.hf.space

=== TASKS ===
1. Add async support — convert sync DB calls to async (supabase-py async client)
2. Add proper rate limiting middleware (slowapi)
3. Implement background tasks for non-critical operations (chat logging)
4. Add Redis caching layer for frequently fetched data (categories, user journeys)
5. Improve error responses — standardise error schema across all endpoints
6. Add /admin endpoints for analytics (total users, avg scores by category)
7. Write pytest suite — target 80% coverage on business logic
8. Add Pydantic v2 migration (currently v1 syntax)

=== CODEBASE HIGHLIGHTS ===
• Tone detection: 13 emotional tones, multilingual (EN/UR/AR)
• Model fallback: 3-tier Llama-3 chain with exponential backoff
• Journey tracking: MCQ system with score smoothing
• Structured responses: voice_answer + middle_section + follow_up format

=== REQUIREMENTS ===
• Strong FastAPI & SQLAlchemy/PostgREST experience
• Supabase or PostgreSQL background
• Experience with async Python (asyncio, httpx)
• Understanding of LLM API integration patterns

Please share your GitHub or sample FastAPI project.
Budget: [your budget] | Timeline: 1-2 weeks

📋 Technical Spec Sheet

Share this with any developer you're interviewing.

Technical Spec — For Developer Interview
=== ABDULLAH BOT API — TECHNICAL SPEC ===

LIVE ENDPOINTS
  Base: https://frnklnwrld-me.hf.space
  Docs: https://frnklnwrld-me.hf.space/docs
  Health: https://frnklnwrld-me.hf.space/health

KEY ENDPOINTS
  POST /chat          — Main AI conversation (requires: message, user_id)
  GET  /journey/:id   — User progress stats
  GET  /categories    — Available MCQ categories (11 total)
  POST /reset-journey — Reset user journey in a category

RESPONSE FORMAT (all /chat responses)
  status:            "insight_only" | "asking_questions" | "session_complete"
  voice_answer:      string  — short, speakable primary response
  middle_section:    string? — extended detail or notes
  follow_up:         string? — suggested next message
  current_mcqs:      [{question, options[5]}]? — MCQ form data
  model_used:        "Llama-3-8B-Instruct" | "fallback" | ...
  next_action_guidance: {type, message, suggested_delay_hours, islamic_reminder}

MCQ ANSWER SUBMISSION
  Send in: answers: [{question_num: 1, answer: "Often", score: 4}]
  Scores: Always=5, Often=4, Sometimes=3, Rarely=2, Never=1

ERROR CODES
  400 — Missing required fields
  503 — Supabase cold start (retry after 5s)
  500 — Server error (check HF Space logs)

TECH STACK
  Python 3.10, FastAPI, Uvicorn
  supabase-py, httpx, requests
  pydantic v1, python-dotenv

SECRETS REQUIRED (HF Space Settings → Secrets)
  HF_TOKEN, SUPABASE_URL, SUPABASE_SERVICE_KEY
FastAPI Python Flutter Supabase Llama-3 HuggingFace Islamic App Urdu/Arabic REST API