Backend and API
The backend is one FastAPI application in backend/app. This page explains how it starts, how the code is laid out, and the shared pieces every request uses: settings, the database session, the model client and the job queue.
Start-up
app/main.py builds the app with create_app(). Its lifespan does this, in order:
- Refuse to start with a weak
JWT_SECRET(unlessALLOW_INSECURE_DEFAULTS=true). - Set up logging (text or JSON) and optional LangSmith tracing.
- Apply the database migrations to the latest revision (
upgrade_database). - Build the shared state (
AppState): the session factory, the vector store with hybrid search, the embedder, the chat model, the web search chain and the LangGraph checkpointer. - Probe the model server in the background (
app/llm/probe.py). - Create the admin from
ADMIN_USERNAMEon an empty database. - Find runs that a crash cut off and resubmit them, then start a thread that keeps looking every 15 seconds.
- Start the job worker in a thread, when
RUN_WORKER_IN_API=true.
Tests call create_app(preset) with a migrated test database and fake models instead.
The API runs as one process. The cancel flags of running answers live in that process's memory, so several API workers would not see each other's cancels.
Code layout
| Package | What it holds |
|---|---|
routers/ | The HTTP endpoints, one module per area |
schemas/ | Pydantic request and response models |
db/ | SQLAlchemy models, the session, and Alembic migrations |
auth/ | Passwords, JWT and refresh tokens, the current_user dependency |
agent/ | The answer graph: nodes, prompts, evidence handling, code steps |
execution/ | The run pool, the durable runner, run events, checkpoints |
ingestion/ | Parsing, structure, chunking, embedding, imports, citation metadata, the reference finder |
retrieval/ | Hybrid search and the reranker client |
web/ | Search providers, page fetching, the MCP browser, sign-in |
sandbox/ | The client for the code sandbox |
study/ | Study sets, grading, spaced repetition, concept maps, the study-guide export |
llm/ | The chat client, its priority gate, and the probe |
jobs/, worker/ | The job queue and the worker loop |
admin/ | Settings saved in the app |
access.py, limits.py, memory.py, branches.py | Access rules, per-user limits, memory layers, branching chats |
The API
All endpoints live under /api. The routers:
| Router | Endpoints | Area |
|---|---|---|
auth | 11 | Set-up, sign-in and out, refresh, sign-up, password, sessions, personal access tokens |
users | 6 | Accounts, approval of sign-ups (admin) |
library | 20 | Upload, import, list, edit, re-index, delete, chunks, table of contents, publishing |
spaces | 12 | Spaces, their sources and members |
invites | 5 | Space invite links |
threads | 17 | Chats, messages, runs, run events (SSE), branches, export, attachments |
code | 7 | Code cells and the chat's kernel |
signin | 5 | The sign-in browser and saved sign-ins |
memory | 4 | Memory items and proposals |
notes | 4 | Notes and highlights |
study | 16 | Study sets, items, reviews, quiz attempts, the study guide |
capture | 9 | The browser extension: capture, references, highlights |
admin | 3 | Settings saved in the app, and their tests |
oversight | 5 | An admin's read-only view of a user's content |
system | 3 | Health, status, probe |
quality | 2 | Eval reports |
agent | 1 | The answer graph's shape, for the Flow view |
FastAPI serves the generated documentation at /docs and the schema at /openapi.json. See the API reference.
Errors use one shape: {"detail": {"code": "...", "message": "..."}}. The code is stable, for example token_scope or reference_only. The message is for people.
Settings
app/config.py defines every setting with its default (see the configuration reference). get_settings() reads .env, then lays the settings saved in the app on top (app/admin/settings_store.py). It runs once per process, so a saved change takes effect at the next restart.
The database session
Each request gets a session through the get_db dependency. It commits when the endpoint returns and rolls back on an error. Background threads use session_scope() the same way.
The model client
app/llm/client.py wraps the OpenAI-compatible chat API.
- Every call names its step, for example
draft.academicorverify. The step's preset sets thinking, reasoning effort, sampling, output length and priority. Admins can override presets per step. - Structured replies ask for
response_format: json_schemawith a Pydantic schema. The reply is parsed tolerantly (the first JSON object in the content or the reasoning), validated, and repaired once by asking again. - Drafts stream. Draft and revise tokens go out as
token.deltarun events while the model writes. - One priority gate (
app/llm/scheduler.py) keeps at mostLLM_CONCURRENCYcalls in flight. A waiting call with higher priority goes first: drafting an answer, then checks, then background work such as section summaries. So a long summary job never holds up a student's answer.
The job queue
app/jobs/queue.py keeps jobs in the jobs table. Workers claim a job with SELECT … FOR UPDATE SKIP LOCKED, so several workers can run safely. A failed job retries with back-off up to JOB_MAX_ATTEMPTS. A job whose worker stopped reporting for JOB_STALE_SECONDS is taken over. Errors the user must fix, such as a private address, are not retried.
The job kinds: index_document (uploads and imports), index_session_file (chat attachments), summarize_document, generate_study_set, grade_quiz_attempt and purge_events (old run events).
Logging
Loggers are named scholarlens.<area>, for example scholarlens.runs or scholarlens.ingestion. LOG_FORMAT=json writes one JSON object per line for a log collector.