Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Adaptive Python Tutor API: FastAPI + SQLite

· 6 min read · Home Tech

In this article
  1. What "Adaptive" Means in a Tutor API
  2. Why FastAPI and SQLite Fit This Project
  3. Core Data Model for the Tutor
  4. Implementing the Adaptive Logic
  5. Handling Code Evaluation Safely
  6. Common Pitfalls and How to Avoid Them
  7. Comparing with Alternatives
  8. Frequently Asked Questions

Yes, you can build an adaptive Python tutor API with FastAPI and SQLite, and it is a practical choice for a self-contained learning system. You define the tutoring logic (question selection, difficulty adjustment, and progress tracking) in Python, expose it through FastAPI endpoints, and store user data and question metadata in SQLite. This article walks through the architecture, data model, and key implementation details, plus common pitfalls and alternatives.

What "Adaptive" Means in a Tutor API

An adaptive tutor adjusts the difficulty or content of questions based on the learner's past performance. Unlike a static quiz, it tracks each user's responses and uses that history to pick the next question. In a simple implementation, you can use a rule-based system: if a user answers correctly, increase difficulty; if wrong, decrease it. More sophisticated approaches use item response theory (IRT) or knowledge tracing, but those require more data and computation.

For a Python tutor, the adaptation can target specific topics (loops, functions, classes) or difficulty levels (beginner, intermediate, advanced). The API receives a user's answer, evaluates it (either by comparing to a stored answer or running code in a sandbox), updates the user's skill estimate, and returns the next question.

Why FastAPI and SQLite Fit This Project

FastAPI is a modern Python web framework that is fast, asynchronous, and automatically generates OpenAPI documentation. It is well-suited for building a REST API with minimal boilerplate. SQLite is a file-based relational database that requires no separate server, making it ideal for small-to-medium projects, prototypes, or educational tools. Together, they let you build a fully functional tutor API with just a few files and no external services.

Key advantages:

  • FastAPI uses Pydantic for request validation, reducing bugs.
  • SQLite is transactional and ACID-compliant, so data stays consistent.
  • You can run the entire stack on a single machine, even a Raspberry Pi.
  • FastAPI's async support works well with SQLite via libraries like aiosqlite.

Core Data Model for the Tutor

You need at least three tables: users, questions, and attempts. The users table stores a unique ID and optional metadata like name or skill level. The questions table holds the question text, the correct answer, the topic, and a difficulty score (e.g., 1 to 5). The attempts table records each user's answer, whether it was correct, and a timestamp.

Example schema:

CREATE TABLE users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT
);

CREATE TABLE questions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    topic TEXT NOT NULL,
    difficulty INTEGER NOT NULL,
    prompt TEXT NOT NULL,
    answer TEXT NOT NULL
);

CREATE TABLE attempts (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    question_id INTEGER NOT NULL,
    correct BOOLEAN NOT NULL,
    timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id),
    FOREIGN KEY (question_id) REFERENCES questions(id)
);

You can extend this with a user_skills table to store per-topic mastery levels, but the attempts table alone is enough to compute a simple moving average of correctness.

Implementing the Adaptive Logic

The core of the tutor is the algorithm that selects the next question. A simple, effective method is the difficulty adjustment based on recent performance. Keep a sliding window of the last N attempts (e.g., 5) for a user. If the proportion correct is above 80%, increase difficulty by 1 (up to a max). If below 50%, decrease by 1. Otherwise, keep the same.

In code, you might have an endpoint like GET /next-question/{user_id} that:

  1. Fetches the last N attempts for that user.
  2. Computes the success rate.
  3. Determines the target difficulty.
  4. Selects a random question from the questions table with that difficulty (and optionally a topic the user has not yet mastered).

When the user submits an answer via POST /answer, you validate it, store the attempt, and return whether they were correct along with the next question.

Handling Code Evaluation Safely

If your questions ask the user to write Python code, you need to evaluate it. Running arbitrary code on your server is dangerous. For a tutor, you have a few options:

  • Compare output: Run the user's code in a restricted subprocess (e.g., using subprocess with a timeout) and compare the printed output to the expected output.
  • Unit tests: Run a set of predefined test cases against the user's function.
  • Static analysis: Use the ast module to check for forbidden constructs (like eval) before running.

Always use a timeout and resource limits to prevent infinite loops or memory exhaustion. For a production system, consider running code in a container or a sandbox like Docker, but for a small tutor, a subprocess with a timeout is acceptable if you trust the users (e.g., in a closed classroom).

Common Pitfalls and How to Avoid Them

One frequent mistake is not handling concurrent writes to SQLite correctly. SQLite locks the entire database on writes, so if multiple users submit answers simultaneously, you may get "database is locked" errors. Use a connection per request, enable WAL mode (PRAGMA journal_mode=WAL), and set a busy timeout. FastAPI's async nature can also cause issues if you use blocking SQLite calls; use aiosqlite or run queries in a thread pool.

Another pitfall is the cold-start problem: a new user has no attempt history, so you need a default difficulty. Start at a middle level (e.g., 3) or ask the user to self-assess. Also, ensure your question bank has enough questions at each difficulty level; otherwise, the algorithm may get stuck.

Finally, do not overfit the adaptation. If you adjust difficulty after every single answer, the user may bounce between levels too quickly. Smooth the difficulty changes using a moving average or a small learning rate.

Comparing with Alternatives

FastAPI + SQLite is not the only option. You could use Django REST Framework with PostgreSQL, but that is heavier and requires more setup. Flask is lighter but lacks built-in validation and async support. For the database, PostgreSQL offers better concurrency, but SQLite is simpler for a small tutor. If you expect many concurrent users or need complex analytics, consider migrating to PostgreSQL later; the data model is similar.

For the adaptive logic, you could use a library like pyirt for item response theory, but that adds complexity. For most tutoring scenarios, a simple rule-based system works well and is easier to debug.

Frequently Asked Questions

How do I deploy a FastAPI + SQLite tutor API?

You can run it with Uvicorn: uvicorn main:app --host 0.0.0.0 --port 8000. For production, use a reverse proxy like Nginx and run multiple Uvicorn workers. SQLite works fine on a single server; if you scale to multiple servers, you would need to move to a networked database.

Can I use SQLite with FastAPI's async features?

Yes, use aiosqlite for asynchronous database access. Alternatively, you can use the synchronous sqlite3 module but call it in a thread pool using FastAPI's run_in_threadpool to avoid blocking the event loop.

How do I store user progress between sessions?

Store a user ID in a cookie or token. On each request, include the user ID in the URL or in an Authorization header. The attempts table already records all history, so progress is automatically saved.

What if the user answers a question with multiple correct answers?

Design questions to have a single correct answer, or store a list of acceptable answers in the database. For code questions, compare output or run multiple test cases. In the attempts table, store a boolean for whether the answer was accepted.

Is it safe to run user code on my server?

No, it is not safe without restrictions. Use subprocess with a timeout, disable network access, and limit memory. For a public tutor, consider running code in a sandboxed container like Docker with no network. For a small private tutor, subprocess with a timeout is often acceptable.

How do I handle the cold start for new users?

Start with a default difficulty (e.g., 3 out of 5) or ask the user to choose a level. You can also use a short placement quiz to estimate initial skill. The adaptive algorithm will quickly adjust based on the first few answers.