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.
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
https://frnklnwrld-me.hf.spaceAll endpoints return JSON. No API key required from clients — the HF token is server-side only.
Quick Start
Send your first message in under 2 minutes.
Send a POST to /chat
The only required fields are message and user_id. The API handles everything else automatically.
Receive a structured response
Every response contains voice_answer (short, speakable), middle_section (detail), and follow_up (next prompt).
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
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)
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)
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
{
"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)."
}
}
Authentication
Server-Side Secrets
The following environment variables must be set in your HF Space Settings → Secrets:
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)
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.
/chat
The core endpoint. Handles all conversation, journey flow, and MCQ submission.
Request Body
| Field | Type | Description |
|---|---|---|
| messagerequired | string | User's message. Max 1000 characters. Supports English, Urdu (script + Roman), Arabic. |
| user_idrequired | string | Unique user identifier / display name. Used to look up journey and chat history in Supabase. |
| categoryoptional | string | Journey category context. Default: "General". Use values from /categories. |
| previous_summaryoptional | object | Previously returned cumulative_summary object to carry session context forward. |
| answersoptional | array | MCQ answer submission array. Each item: {question_num, answer, score}. |
Response Fields
insight_only, asking_questions, need_more_answers, session_complete, meta_response{question: string, options: string[]}.{batch_avg: number}.previous_summary.{type, message, suggested_delay_hours, islamic_reminder}.Llama-3-8B-Instruct, Llama-3.1-8B-Instruct, Llama-3.2-1B-Instruct, or fallback.Status Values Explained
| Status | Meaning | UI Action |
|---|---|---|
insight_only | General AI response | Display voice_answer + optional middle_section |
asking_questions | MCQ journey started | Render current_mcqs as a form |
need_more_answers | More answers needed | Show remaining MCQs |
session_complete | All MCQs answered | Show progress summary + celebrate |
meta_response | User asked about bot behavior | Display explanation |
/journey
Path & Query Parameters
| Param | Type | Description |
|---|---|---|
| user_idpath | string | The user's display name / identifier. |
| categoryquery | string | Filter to a specific journey category. Default: "General". |
Example
GET /journey/Abdullah123?category=Religious+Self
Response
{
"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": [...]
}
/categories
Returns all available self-assessment journey categories with question counts. Use these values in the category field of other requests.
{
"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"
}
/reset-journey
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.
| Param | Type | Description |
|---|---|---|
| user_idpath | string | User to reset. |
| categoryquery | string | Category to reset. Default: "General". |
{
"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)."
}
/health
Use this to verify the API is running and which models are configured. Recommended for Flutter app startup checks.
{
"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
}
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.
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.Journey Flow
The journey system enables longitudinal self-assessment across 11 spiritual and personal development categories.
User sends "start journey"
API generates 6 MCQs from the selected category (or resumes pending questions). Returns status: "asking_questions" with current_mcqs array.
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".
Progress computed & saved
Scores averaged with exponential smoothing (30% new / 70% historical). Low-scoring answers recorded as "loopholes" for targeted follow-up.
Session complete
Returns status: "session_complete" with cumulative_summary. Store this and pass back as previous_summary in future requests.
MCQ Options & Score Map
{
"options": ["Always", "Often", "Sometimes", "Rarely", "Never"],
"scores": [ 5, 4, 3, 2, 1 ]
}
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
{
"message": "آج میں بہت اداس ہوں",
"user_id": "user123"
}
The API detects Urdu script, sets detected_lang: "ur", and responds in Urdu with culturally relevant Islamic phrasing and dua.
Model Fallback
A 3-tier automatic fallback ensures the API stays responsive even when primary models are rate-limited or unavailable.
Fallback Chain
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
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
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.Flutter Guide
A complete example for integrating Abdullah Bot into a Flutter/Dart app.
Service Class
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
// 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
503 responses with a "Waking up…" message and auto-retry after 5s.Error Handling
Missing required fields. Check that
message and user_id are present and non-empty.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."Unexpected error. Check HF Space logs. Common causes: missing secrets, Supabase schema mismatch, all 3 Llama models failed simultaneously.
Recommended Client Pattern
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)));
}
}
}
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.
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
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
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.
=== 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