Personal project
ExamGen AI — AI-Powered Exam Generation
A FastAPI backend that turns a teacher's syllabus into a complete exam with an LLM: questions, answer key and grading rubric, exported as student and teacher PDFs.
My role
Solo project. API design, data model, LLM integration, PDF generation, Docker setup and a React client.
- REST endpoints
- 15
- database tables
- 6
- question types
- 3
- PDF versions per exam
- 2
Responsibilities by layer
- API
- Python, FastAPI, Pydantic, JWT (python-jose), bcrypt (passlib)
- Database
- PostgreSQL, SQLAlchemy 2.0
- AI
- OpenAI Python SDK against an OpenAI-compatible endpoint (Groq), JSON mode
- Documents
- ReportLab
- Infrastructure
- Docker, Docker Compose, Nginx config
- Client
- React, Vite, Zustand, Axios
How an exam is generated
1Validate
Pydantic checks the request; the JWT identifies the user; a dependency confirms an active subscription.
2Authorize
The syllabus must belong to one of the user's subjects, otherwise 403.
3Context
Questions from recent exams on the same syllabus are gathered to steer the model away from them.
4Generate
One chat completion in JSON mode returns questions, answers, rubric and answer key.
5Persist
The full JSON is stored on the exam and each question is saved as its own row, in one transaction.
6Render
PDFs are produced on request from the stored JSON, with or without answers.
Problem and solution
Writing exams takes teachers hours, and reusing them invites copying. ExamGen lets a teacher create a subject, paste a syllabus and request an exam by difficulty, number of questions and question types.
The API asks an LLM for the whole exam as JSON, stores it, and renders two PDFs: one for students and one for the teacher with answers and rubric. It can also generate an alternative version of an exam to discourage copying.
Backend architecture
The code is split by responsibility: core (settings, database session, security), models (SQLAlchemy), schemas (Pydantic), routers (HTTP layer) and services (exam orchestration, LLM calls, PDF rendering). Routers stay thin; the generation flow lives in exam_service.
Settings are loaded from environment variables with pydantic-settings, so secrets and the model name never live in code.
Authentication and authorization
Registration and login return a JWT. Passwords are hashed with bcrypt after a SHA-256 pre-hash, which avoids bcrypt's 72-byte input limit.
Authorization is enforced in the queries themselves: subjects, syllabuses and exams are always filtered by the current user's id, so one user can never read or delete another user's data. Exam generation additionally requires an active subscription, checked by a dedicated dependency.
Data model
Six tables: users, subjects, syllabuses, exams, questions and subscriptions. Deleting a subject cascades to its syllabuses and exams.
Each exam keeps the complete LLM response as JSON next to normalized question rows. The JSON is what the PDF renderer reads; the rows make questions individually queryable for the anti-repetition logic.
LLM integration and structured output
The prompt carries the subject, level, difficulty, question types, the syllabus text and the exact JSON shape expected. The call uses JSON mode (response_format json_object) so the response parses directly.
The client is the official OpenAI SDK with a configurable base URL and model, currently pointed at Groq. Switching providers is a configuration change, not a code change.
Avoiding repeated questions
Before generating, the service collects questions from the latest exams on the same syllabus and adds them to the prompt as topics to avoid.
Embedding storage and a cosine-similarity check (threshold 0.88) are implemented as building blocks for a semantic duplicate filter; they are not yet wired into the generation flow.
PDF generation
ReportLab builds the PDF from the stored exam JSON: header with student fields, instructions, questions with options, and, in the teacher version, the answer key, rubric and grading scale. The endpoint streams the file with a proper Content-Disposition filename.
Validation and errors
Request bodies are validated with Pydantic: difficulty must be one of three values and question count is limited to 3–50. The API returns 201 on creation, 204 on deletion, 400 for a duplicate email, 401 for bad credentials, 403 without a subscription and 404 for missing or foreign resources.
Running it
docker-compose starts PostgreSQL 16 with a health check, the FastAPI backend with live reload and the Vite dev server. An Nginx config is included for serving the built React app and proxying /api to the backend.
REST API (selected endpoints)
| Method | Path | Purpose | Auth |
|---|---|---|---|
| POST | /api/auth/register | Create account, returns JWT | Public |
| POST | /api/auth/login | Log in, returns JWT | Public |
| GET | /api/auth/me | Current user | JWT |
| POST | /api/subjects/ | Create subject | JWT |
| GET | /api/subjects/ | List my subjects | JWT |
| POST | /api/subjects/{id}/syllabuses | Add syllabus to a subject | JWT |
| POST | /api/exams/generate | Generate an exam with the LLM | JWT + subscription |
| GET | /api/exams/{id} | Exam with questions | JWT |
| GET | /api/exams/{id}/pdf | PDF; ?include_answers=true for teacher version | JWT |
| DELETE | /api/exams/{id} | Delete exam | JWT |
A small decision in code
bcrypt only reads the first 72 bytes of input. Pre-hashing with SHA-256 gives every password a fixed 64-character input, so long passphrases are not silently truncated.
def get_password_hash(password: str) -> str:
safe_password = hashlib.sha256(password.encode()).hexdigest()
return pwd_context.hash(safe_password)
def verify_password(plain_password: str, hashed_password: str) -> bool:
safe_password = hashlib.sha256(plain_password.encode()).hexdigest()
return pwd_context.verify(safe_password, hashed_password)Decisions and trade-offs
Store the raw LLM JSON and normalized rows
The raw JSON keeps everything the model produced (rubric, answer key) for rendering. Question rows support querying and comparing questions. Some duplication, in exchange for simpler reads on both paths.
Provider-agnostic LLM client
Using the OpenAI SDK with a configurable base URL means the same code talks to OpenAI or any compatible provider. Cost and speed can change without touching the service.
Authorization in the query, not after it
Filtering by user_id inside every query means a request for someone else's resource gets a 404 instead of their data.
PDFs on demand
PDFs are rendered when requested instead of stored. No file storage to manage, and a fix to the template applies to every past exam.
What I would improve next
This is a personal project, not a deployed product. Before running it for real users, I would close these gaps:
- Validate the LLM response against a Pydantic schema before saving, and retry on malformed output
- Wire the embedding similarity check into generation and move vectors to pgvector
- Replace create_all with the Alembic migrations already in requirements
- Add pytest coverage for auth, ownership checks and the generation service (with the LLM mocked)
- Verify webhook signatures for subscription events