Skip to content
immanueln98Public

About

USSD-based educational chatbot for schools in Botswana (currently)

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

5 Commits

Folders and files

Repository files navigation

πŸ“š EduBot - USSD Educational Platform

An AI-powered USSD-based educational chatbot for primary school mathematics in Botswana, delivering lessons and quizzes via SMS with cost-optimized delivery.

FastAPI Python Redis License

🌟 Features

βœ… Phase 1: Core USSD Experience (Complete)

  • πŸ“– Learn Mode: Browse math topics (Addition, Subtraction, Multiplication, Division)
  • ✏️ Quiz Mode: Interactive quizzes via USSD with instant feedback
  • πŸ“± SMS Delivery: Lessons and quiz results sent via optimized SMS
  • πŸ’Ύ Session Management: Redis-based state persistence for seamless conversations
  • πŸ”„ Session Summary: Complete activity summary on exit

βœ… Phase 2: LLM Integration (Complete)

  • πŸ€– AI Quiz Generation: Dynamic quiz questions using Groq's Llama 3.1 8B model
  • ⚑ Fast Inference: <5 second quiz generation (within USSD 15s timeout)
  • πŸ›‘οΈ Graceful Fallback: Automatic switch to pre-stored questions if LLM fails
  • πŸ“Š Dual Source Tracking: Monitors whether questions are LLM-generated or static

βœ… Phase 3: Live Chat with AI Tutor (Complete)

  • πŸ’¬ Chat with AI Tutor: Free-form Q&A about math topics via USSD
  • 🎯 4 Conversation Types: Explain concepts, Show examples, Solve problems, Free chat
  • 🧠 Context-Aware: 3-turn sliding window for natural conversations
  • ⏱️ Smart Timeout Handling: 6-second USSD timeout with SMS fallback
  • πŸ“ Intelligent Truncation: 90-char responses optimized for USSD screens
  • πŸ“¨ Conversation History: Full Q&A chat log sent via SMS on exit

πŸ’° SMS Cost Optimization

  • πŸ“‰ 60-70% Cost Reduction: Optimized formatting reduces SMS count dramatically
  • πŸ”€ GSM-7 Encoding: No emojis = 160 chars/SMS instead of 70 chars/SMS (Unicode)
  • 🎯 Smart Results: Shows only incorrect answers to minimize message length
  • πŸ“¦ Compact Lessons: Condensed content maintains educational value in fewer SMS

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   USSD      β”‚      β”‚   FastAPI   β”‚      β”‚   Africa's  β”‚
β”‚  *384*...#  │─────▢│   Backend   │─────▢│   Talking   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β”‚   SMS API   β”‚
                            β”‚              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                            β”‚
                     β”Œβ”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”
                     β”‚             β”‚
              β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”
              β”‚   Redis    β”‚ β”‚   Groq   β”‚
              β”‚  Sessions  β”‚ β”‚  LLM API β”‚
              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

USSD Flow Diagram

*384*20251129#
    β”‚
    β”œβ”€β”€β”€ [1] Learn a Topic
    β”‚       β”œβ”€ [1] Addition ──────────────► SMS: Lesson (2 SMS)
    β”‚       β”œβ”€ [2] Subtraction ───────────► SMS: Lesson (2 SMS)
    β”‚       β”œβ”€ [3] Multiplication ────────► SMS: Lesson (2 SMS)
    β”‚       β”œβ”€ [4] Division ──────────────► SMS: Lesson (2 SMS)
    β”‚       └─ [0] Back to Main Menu
    β”‚
    β”œβ”€β”€β”€ [2] Take a Quiz
    β”‚       β”œβ”€ Select topic (1-4)
    β”‚       β”œβ”€ Choose count (3, 5, 10)
    β”‚       β”œβ”€ Answer Q1, Q2, Q3...
    β”‚       └─ Complete ──────────────────► SMS: Results (1-2 SMS)
    β”‚
    β”œβ”€β”€β”€ [3] Chat with AI Tutor
    β”‚       β”œβ”€ Select topic (1-4)
    β”‚       β”œβ”€ Choose mode (Explain/Example/Solve/Free)
    β”‚       β”œβ”€ Ask questions via USSD (context-aware)
    β”‚       β”‚   β”œβ”€ [1] Ask another question
    β”‚       β”‚   β”œβ”€ [2] Change topic
    β”‚       β”‚   └─ [0] Exit chat
    β”‚       └─ Exit ───────────────────────► SMS: Full conversation (2-3 SMS)
    β”‚
    └─── [4] Exit ────────────────────────► SMS: Session Summary (1 SMS)

πŸš€ Quick Start

Prerequisites

Ensure you have the following installed:

# Python 3.11+ (3.13 recommended)
python --version  # Should be 3.11.0 or higher

# Redis (session storage)
redis-server --version  # Install via: brew install redis (Mac)

# ngrok (local tunnel for USSD callbacks)
ngrok version  # Install via: brew install ngrok (Mac)

Installation

  1. Clone the repository
git clone https://github.com/immanueln98/ussd-edu.git
cd ussd-edu
  1. Create virtual environment
python -m venv venv
source venv/bin/activate  # Mac/Linux
# or: venv\Scripts\activate  # Windows
  1. Install dependencies
pip install -r requirements.txt
  1. Configure environment variables
cp .env.example .env
# Edit .env with your credentials

Required .env configuration:

# Africa's Talking Credentials
AT_USERNAME=sandbox
AT_API_KEY=your_api_key_here

# Groq API (for LLM quiz generation)
GROQ_API_KEY=your_groq_api_key_here
LLM_MODEL=llama-3.1-8b-instant

# Redis Configuration
REDIS_HOST=localhost
REDIS_PORT=6379

# App Settings
DEBUG=true
USE_LLM_QUIZ=true
USE_LLM_CHAT=true

# USSD Service Code
USSD_SERVICE_CODE=*384*20251129#

Running the Application

You need 3 terminal windows running simultaneously:

Terminal 1: Start Redis

redis-server

Terminal 2: Start FastAPI Backend

source venv/bin/activate
uvicorn app.main:app --reload --port 8000

Terminal 3: Expose with ngrok

ngrok http 8000

Copy the ngrok HTTPS URL (e.g., https://abc123.ngrok.io)

Africa's Talking Setup

  1. Sign up at Africa's Talking
  2. Go to Sandbox mode
  3. Navigate to USSD β†’ Create Channel
    • Service Code: *384*20251129# (or any available code)
    • Callback URL: https://YOUR-NGROK-URL/ussd/callback
  4. Go to Settings β†’ API Key β†’ Generate/Copy
  5. Update .env with your AT_API_KEY

Get Groq API Key (for LLM features)

  1. Sign up at Groq Console
  2. Navigate to API Keys β†’ Create API Key
  3. Copy the key and add to .env as GROQ_API_KEY

Testing in Simulator

  1. In Africa's Talking dashboard, click Launch Simulator
  2. Enter a phone number (format: +267XXXXXXXX for Botswana)
  3. Dial your USSD code (e.g., *384*20251129#)
  4. Navigate through menus and complete a quiz!

πŸ§ͺ Local Testing (Without Simulator)

Test the USSD logic locally using curl:

Main Menu

curl -X POST http://localhost:8000/ussd/callback \
  -d "sessionId=test-123" \
  -d "phoneNumber=+26771234567" \
  -d "serviceCode=*384*20251129#" \
  -d "text="

Learn Mode Flow

# Select "Learn" (option 1)
curl -X POST http://localhost:8000/ussd/callback \
  -d "sessionId=test-123" \
  -d "phoneNumber=+26771234567" \
  -d "serviceCode=*384*20251129#" \
  -d "text=1"

# Select "Addition" (option 1)
curl -X POST http://localhost:8000/ussd/callback \
  -d "sessionId=test-123" \
  -d "phoneNumber=+26771234567" \
  -d "serviceCode=*384*20251129#" \
  -d "text=1*1"

Quiz Mode Flow

# Start quiz (option 2)
curl -X POST http://localhost:8000/ussd/callback \
  -d "sessionId=quiz-456" \
  -d "phoneNumber=+26771234567" \
  -d "serviceCode=*384*20251129#" \
  -d "text=2"

# Select Addition (option 1)
curl -X POST http://localhost:8000/ussd/callback \
  -d "sessionId=quiz-456" \
  -d "phoneNumber=+26771234567" \
  -d "serviceCode=*384*20251129#" \
  -d "text=2*1"

# Choose 5 questions
curl -X POST http://localhost:8000/ussd/callback \
  -d "sessionId=quiz-456" \
  -d "phoneNumber=+26771234567" \
  -d "serviceCode=*384*20251129#" \
  -d "text=2*1*5"

# Answer first question (e.g., "7")
curl -X POST http://localhost:8000/ussd/callback \
  -d "sessionId=quiz-456" \
  -d "phoneNumber=+26771234567" \
  -d "serviceCode=*384*20251129#" \
  -d "text=2*1*5*7"

Chat Mode Flow

# Start chat (option 3)
curl -X POST http://localhost:8000/ussd/callback \
  -d "sessionId=chat-789" \
  -d "phoneNumber=+26771234567" \
  -d "serviceCode=*384*20251129#" \
  -d "text=3"

# Select Addition (option 1)
curl -X POST http://localhost:8000/ussd/callback \
  -d "sessionId=chat-789" \
  -d "phoneNumber=+26771234567" \
  -d "serviceCode=*384*20251129#" \
  -d "text=3*1"

# Choose Free Chat (option 4)
curl -X POST http://localhost:8000/ussd/callback \
  -d "sessionId=chat-789" \
  -d "phoneNumber=+26771234567" \
  -d "serviceCode=*384*20251129#" \
  -d "text=3*1*4"

# Ask a question
curl -X POST http://localhost:8000/ussd/callback \
  -d "sessionId=chat-789" \
  -d "phoneNumber=+26771234567" \
  -d "serviceCode=*384*20251129#" \
  -d "text=3*1*4*What+is+5+plus+3"

# Ask another question (option 1)
curl -X POST http://localhost:8000/ussd/callback \
  -d "sessionId=chat-789" \
  -d "phoneNumber=+26771234567" \
  -d "serviceCode=*384*20251129#" \
  -d "text=3*1*4*What+is+5+plus+3*1*How+do+I+add+big+numbers"

# Exit chat and receive SMS summary (option 0)
curl -X POST http://localhost:8000/ussd/callback \
  -d "sessionId=chat-789" \
  -d "phoneNumber=+26771234567" \
  -d "serviceCode=*384*20251129#" \
  -d "text=3*1*4*What+is+5+plus+3*1*How+do+I+add+big+numbers*0"

πŸ“ Project Structure

ussd-edu-demo/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ main.py                 # FastAPI application & endpoints
β”‚   β”œβ”€β”€ config.py               # Pydantic settings (env vars)
β”‚   β”‚
β”‚   β”œβ”€β”€ routers/
β”‚   β”‚   └── ussd.py             # USSD callback handler & menu logic
β”‚   β”‚
β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”œβ”€β”€ session.py          # Redis session management
β”‚   β”‚   β”œβ”€β”€ sms.py              # Africa's Talking SMS (optimized)
β”‚   β”‚   β”œβ”€β”€ llm.py              # Groq LLM integration (quiz + chat)
β”‚   β”‚   β”œβ”€β”€ quiz.py             # Quiz service (LLM + fallback)
β”‚   β”‚   └── chat.py             # Chat service (timeout & truncation)
β”‚   β”‚
β”‚   └── data/
β”‚       └── content.py          # Pre-stored lessons, quiz bank & chat prompts
β”‚
β”œβ”€β”€ test_llm.py                 # LLM service testing script
β”œβ”€β”€ requirements.txt            # Python dependencies
β”œβ”€β”€ .env                        # Environment variables (not in git)
β”œβ”€β”€ .env.example                # Environment template
β”œβ”€β”€ .gitignore                  # Git ignore rules
└── README.md                   # This file

πŸ”Œ API Endpoints

Endpoint Method Description
/ GET Service info and status
/ POST USSD callback fallback (Africa's Talking)
/health GET Health check
/health/llm GET LLM service health & latency
/ussd/callback POST Main USSD webhook (Africa's Talking)
/test-sms/{phone} GET Test SMS delivery (debug mode)
/simulate GET USSD simulation examples
/docs GET Interactive API docs (debug mode)

Example: Test LLM Health

curl http://localhost:8000/health/llm

Response:

{
  "status": "healthy",
  "healthy": true,
  "response_time_ms": 1847,
  "model": "llama-3.1-8b-instant"
}

βš™οΈ Configuration

All settings are managed via .env file using Pydantic Settings:

Variable Description Default Required
AT_USERNAME Africa's Talking username sandbox βœ…
AT_API_KEY Africa's Talking API key - βœ…
GROQ_API_KEY Groq API key (LLM) - ⚠️ Optional*
LLM_MODEL Groq model name llama-3.1-8b-instant No
LLM_TIMEOUT LLM timeout (seconds) 10 No
LLM_MAX_TOKENS Max tokens per LLM response 500 No
REDIS_HOST Redis server host localhost βœ…
REDIS_PORT Redis server port 6379 βœ…
REDIS_DB Redis database number 0 No
DEBUG Enable debug mode true No
SESSION_TIMEOUT Session timeout (seconds) 300 No
USE_LLM_QUIZ Enable LLM quiz generation true No
USE_LLM_CHAT Enable LLM chat responses true No
USSD_SERVICE_CODE USSD service code *384*123# No

*If GROQ_API_KEY is not set, quizzes will use pre-stored questions and chat will use static fallback responses.

🧠 LLM Integration Details

Quiz Generation Flow

  1. User selects quiz β†’ Topic + Question count
  2. LLM Service called β†’ Groq API with structured prompt
  3. Response parsing β†’ JSON validation with Pydantic
  4. Fallback handling β†’ If LLM fails, use static questions
  5. Session tracking β†’ Stores quiz source (LLM vs static)

Prompt Engineering

The system uses carefully crafted prompts with:

  • Clear role definition: "You are a primary school maths teacher"
  • Explicit output format: JSON schema with examples
  • Topic-specific guidance: Number ranges, difficulty constraints
  • Strict instructions: "Output ONLY valid JSON"

Example prompt snippet:

"""Generate exactly 5 addition questions for primary school students.

RULES:
- Use numbers between 1-20. Answers should be under 30.
- Answers must be single numbers (no fractions)
- Questions should be clear and simple

OUTPUT FORMAT:
{"questions": [{"question": "What is 2 + 3?", "answer": "5"}]}
"""

Performance Metrics

  • Typical LLM response time: 2-4 seconds
  • Total quiz generation: <5 seconds
  • USSD timeout budget: 15 seconds (safe margin)
  • Fallback activation time: <100ms

πŸ’¬ Chat Feature Details

How Chat Works

  1. Topic & Mode Selection β†’ User selects math topic and conversation type
  2. Question Input β†’ User types question via USSD
  3. LLM Processing β†’ Groq API generates response with 6-second timeout
  4. Smart Truncation β†’ Response trimmed to 90 chars for USSD display
  5. SMS Fallback β†’ If truncated or timeout, full answer sent via SMS
  6. Context Tracking β†’ Last 3 Q&A turns maintained for continuity

Conversation Types

Type Description Example Question
Explain Get concept definitions "What is addition?"
Example See worked examples "Show me 5 + 3 step by step"
Solve Solve a specific problem "What is 12 + 18?"
Free Chat Ask anything about the topic "How do I add big numbers?"

Timeout Strategy

The chat feature uses a dual-timeout approach:

  • USSD Timeout: 6 seconds (tighter than quiz's 10s)
  • Background SMS: Up to 30 seconds for complete answer
  • Graceful Degradation:
    1. βœ… Perfect: Response ≀90 chars, delivered instantly
    2. ⚠️ Truncated: Response >90 chars, truncated + SMS sent
    3. ⏰ Deferred: LLM timeout, fallback message + SMS queued
    4. ❌ Failed: LLM error, friendly error message displayed

Smart Truncation Algorithm

# Truncation priority (preserves readability):
1. Try sentence boundary (. ! ?)
2. Try clause boundary (, ; :)
3. Try word boundary (space)
4. Hard cut with ... (last resort)

SMS Conversation Summary Format

When user exits chat, they receive an SMS with full history:

EDUBOT SESSION SUMMARY

CHAT - Addition

Q1: What is 2 plus 3
A: 2 plus 3 is 5.

Q2: How do I add big numbers
A: Add numbers one by one, like 456 + 278: 456 + 200 = 656,
then 656 + 70 = 726, then 726 + 8 = 734.

Thanks for learning!
Dial back anytime.

Key Features:

  • No emojis (GSM-7 encoding saves 56% per SMS)
  • Full answers (not truncated versions)
  • Numbered Q&A for easy reference
  • Typically 2-3 SMS per conversation

πŸ’° SMS Cost Optimization Strategy

Before Optimization (Quiz Results Example)

πŸ“ QUIZ RESULTS

Topic: Addition
Score: 3/5 (60%)

πŸ‘ Good job!

Q1: What is 3 + 4?
Your answer: 7 βœ“

Q2: What is 5 + 8?
Your answer: 10 βœ—
Correct: 13
...

Cost: ~4-5 SMS (Unicode encoding due to emojis: 70 chars/SMS)

After Optimization

QUIZ RESULTS - Addition
Score: 3/5 (60%)
Good job!

Review these:
Q2: 5+8=?
You:10 Ans:13
Q4: 9+6=?
You:14 Ans:15

Dial back to practice more!

Cost: ~1-2 SMS (GSM-7 encoding: 160 chars/SMS)

Optimization Techniques

  1. Remove emojis β†’ Force GSM-7 encoding (160 vs 70 chars)
  2. Show only wrong answers β†’ Reduce content by 60-80%
  3. Compact operators β†’ 3+4=7 instead of 3 + 4 = 7
  4. Minimize whitespace β†’ Fewer blank lines
  5. Condensed practice questions β†’ All on one line

Result: 60-70% reduction in SMS costs while maintaining clarity!

πŸ” Testing LLM Features

Run the included test script to verify LLM integration:

python test_llm.py

Expected output:

==================================================
Testing LLM Service
==================================================

1. Health Check:
   Status: healthy
   Response time: 1847ms

2. Generate Addition Quiz (5 questions):
   Time: 3.21s
   βœ“ Generated 5 questions:
      Q1: What is 2 + 3? = 5
      Q2: What is 7 + 4? = 11
      Q3: What is 5 + 6? = 11
      Q4: What is 3 + 9? = 12
      Q5: What is 8 + 5? = 13

βœ“ All tests complete!

πŸ› Troubleshooting

"Connection refused" to Redis

Solution: Start Redis server

redis-server

USSD timeout (>15 seconds)

Causes:

  • Slow LLM response (network latency)
  • Redis not running locally
  • ngrok tunnel instability

Solutions:

  • Check ngrok logs: http://localhost:4040
  • Ensure Redis is local (not remote)
  • Verify Groq API key is valid

SMS not received in sandbox

Causes:

  • Invalid phone number format
  • Africa's Talking API key missing/wrong
  • Sandbox limitations

Solutions:

  • Use test format: +254711XXXXXX (Kenya sandbox)
  • Check Africa's Talking logs in dashboard
  • Verify AT_API_KEY in .env

LLM validation error

Error: Input should be a valid string

Cause: LLM returning integers as answers

Solution: Already handled! The QuizQuestion model uses Union[str, int] with automatic conversion.

Session not persisting between requests

Causes:

  • Different sessionId used across requests
  • Redis session expired (5 min default)
  • Redis server not running

Solutions:

  • Use same sessionId for conversation flow
  • Increase SESSION_TIMEOUT in .env
  • Verify Redis: redis-cli ping (should return PONG)

🚦 Development Workflow

Running in development

# Terminal 1
redis-server

# Terminal 2
source venv/bin/activate
uvicorn app.main:app --reload --port 8000

# Terminal 3
ngrok http 8000

Running tests

# Test LLM integration
python test_llm.py

# Test SMS formatting (debug mode)
curl http://localhost:8000/test-sms/+26771234567

Monitoring logs

# FastAPI logs
# Watch Terminal 2 for request logs

# ngrok requests
# Open http://localhost:4040 in browser

# Redis commands
redis-cli monitor

πŸ›£οΈ Roadmap

βœ… Completed (Phases 1-3)

  • Core USSD menu system
  • Redis session management
  • Africa's Talking SMS integration
  • Static quiz bank (4 topics, 10 questions each)
  • LLM quiz generation (Groq integration)
  • SMS cost optimization (60-70% reduction)
  • Graceful LLM fallback
  • Live chat with AI tutor (4 conversation types)
  • Context-aware conversations (3-turn window)
  • Smart response truncation & SMS fallback
  • Full conversation history via SMS

πŸ”œ Future Enhancements (Phase 4+)

  • Multi-language support (English + Setswana)
  • Progress tracking (student performance analytics)
  • Teacher dashboard (monitor student activity)
  • Advanced topics (fractions, decimals, word problems)
  • WhatsApp integration (alternative to SMS)
  • Voice-based learning (IVR integration)

πŸ“Š Tech Stack

  • Backend: FastAPI 0.115.6 (async Python web framework)
  • Session Store: Redis 7.0+ (in-memory data store)
  • LLM: Groq with Llama 3.1 8B Instant
  • SMS Gateway: Africa's Talking API
  • Validation: Pydantic 2.10.5 (data validation)
  • HTTP Client: httpx (async requests)
  • Dev Tools: ngrok, uvicorn, python-dotenv

πŸ“„ License

MIT License - see LICENSE file for details.

πŸ‘¨β€πŸ’» Author

Immanuel Nanyaro

πŸ™ Acknowledgments

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ“§ Support

For issues, questions, or suggestions:


Built for Education. Optimized for Africa. Powered by AI.

About

USSD-based educational chatbot for schools in Botswana (currently)

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages