An AI-powered USSD-based educational chatbot for primary school mathematics in Botswana, delivering lessons and quizzes via SMS with cost-optimized delivery.
- π 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
- π€ 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
- π¬ 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
- π 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
βββββββββββββββ βββββββββββββββ βββββββββββββββ
β USSD β β FastAPI β β Africa's β
β *384*...# βββββββΆβ Backend βββββββΆβ Talking β
βββββββββββββββ βββββββββββββββ β SMS API β
β βββββββββββββββ
β
ββββββββ΄βββββββ
β β
ββββββββΌββββββ ββββββΌββββββ
β Redis β β Groq β
β Sessions β β LLM API β
ββββββββββββββ ββββββββββββ
*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)
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)- Clone the repository
git clone https://github.com/immanueln98/ussd-edu.git
cd ussd-edu- Create virtual environment
python -m venv venv
source venv/bin/activate # Mac/Linux
# or: venv\Scripts\activate # Windows- Install dependencies
pip install -r requirements.txt- Configure environment variables
cp .env.example .env
# Edit .env with your credentialsRequired .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#You need 3 terminal windows running simultaneously:
Terminal 1: Start Redis
redis-serverTerminal 2: Start FastAPI Backend
source venv/bin/activate
uvicorn app.main:app --reload --port 8000Terminal 3: Expose with ngrok
ngrok http 8000Copy the ngrok HTTPS URL (e.g., https://abc123.ngrok.io)
- Sign up at Africa's Talking
- Go to Sandbox mode
- Navigate to USSD β Create Channel
- Service Code:
*384*20251129#(or any available code) - Callback URL:
https://YOUR-NGROK-URL/ussd/callback
- Service Code:
- Go to Settings β API Key β Generate/Copy
- Update
.envwith yourAT_API_KEY
- Sign up at Groq Console
- Navigate to API Keys β Create API Key
- Copy the key and add to
.envasGROQ_API_KEY
- In Africa's Talking dashboard, click Launch Simulator
- Enter a phone number (format:
+267XXXXXXXXfor Botswana) - Dial your USSD code (e.g.,
*384*20251129#) - Navigate through menus and complete a quiz!
Test the USSD logic locally using curl:
curl -X POST http://localhost:8000/ussd/callback \
-d "sessionId=test-123" \
-d "phoneNumber=+26771234567" \
-d "serviceCode=*384*20251129#" \
-d "text="# 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"# 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"# 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"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
| 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) |
curl http://localhost:8000/health/llmResponse:
{
"status": "healthy",
"healthy": true,
"response_time_ms": 1847,
"model": "llama-3.1-8b-instant"
}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) | - | |
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.
- User selects quiz β Topic + Question count
- LLM Service called β Groq API with structured prompt
- Response parsing β JSON validation with Pydantic
- Fallback handling β If LLM fails, use static questions
- Session tracking β Stores quiz source (LLM vs static)
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"}]}
"""- Typical LLM response time: 2-4 seconds
- Total quiz generation: <5 seconds
- USSD timeout budget: 15 seconds (safe margin)
- Fallback activation time: <100ms
- Topic & Mode Selection β User selects math topic and conversation type
- Question Input β User types question via USSD
- LLM Processing β Groq API generates response with 6-second timeout
- Smart Truncation β Response trimmed to 90 chars for USSD display
- SMS Fallback β If truncated or timeout, full answer sent via SMS
- Context Tracking β Last 3 Q&A turns maintained for continuity
| 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?" |
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:
- β Perfect: Response β€90 chars, delivered instantly
β οΈ Truncated: Response >90 chars, truncated + SMS sent- β° Deferred: LLM timeout, fallback message + SMS queued
- β Failed: LLM error, friendly error message displayed
# Truncation priority (preserves readability):
1. Try sentence boundary (. ! ?)
2. Try clause boundary (, ; :)
3. Try word boundary (space)
4. Hard cut with ... (last resort)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
π 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)
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)
- Remove emojis β Force GSM-7 encoding (160 vs 70 chars)
- Show only wrong answers β Reduce content by 60-80%
- Compact operators β
3+4=7instead of3 + 4 = 7 - Minimize whitespace β Fewer blank lines
- Condensed practice questions β All on one line
Result: 60-70% reduction in SMS costs while maintaining clarity!
Run the included test script to verify LLM integration:
python test_llm.pyExpected 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!
Solution: Start Redis server
redis-serverCauses:
- 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
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_KEYin.env
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.
Causes:
- Different
sessionIdused across requests - Redis session expired (5 min default)
- Redis server not running
Solutions:
- Use same
sessionIdfor conversation flow - Increase
SESSION_TIMEOUTin.env - Verify Redis:
redis-cli ping(should returnPONG)
# Terminal 1
redis-server
# Terminal 2
source venv/bin/activate
uvicorn app.main:app --reload --port 8000
# Terminal 3
ngrok http 8000# Test LLM integration
python test_llm.py
# Test SMS formatting (debug mode)
curl http://localhost:8000/test-sms/+26771234567# FastAPI logs
# Watch Terminal 2 for request logs
# ngrok requests
# Open http://localhost:4040 in browser
# Redis commands
redis-cli monitor- 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
- 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)
- 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
MIT License - see LICENSE file for details.
Immanuel Nanyaro
- Email: nnyimm001@myuct.ac.za
- GitHub: @immanueln98
- Africa's Talking for USSD/SMS infrastructure
- Groq for ultra-fast LLM inference
- FastAPI for the excellent async framework
- Built with assistance from Claude Code
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
For issues, questions, or suggestions:
- Open an issue on GitHub
- Email: nnyimm001@myuct.ac.za
Built for Education. Optimized for Africa. Powered by AI.