Skip to content

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:

  1. Refuse to start with a weak JWT_SECRET (unless ALLOW_INSECURE_DEFAULTS=true).
  2. Set up logging (text or JSON) and optional LangSmith tracing.
  3. Apply the database migrations to the latest revision (upgrade_database).
  4. 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.
  5. Probe the model server in the background (app/llm/probe.py).
  6. Create the admin from ADMIN_USERNAME on an empty database.
  7. Find runs that a crash cut off and resubmit them, then start a thread that keeps looking every 15 seconds.
  8. 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 ​

PackageWhat 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.pyAccess rules, per-user limits, memory layers, branching chats

The API ​

All endpoints live under /api. The routers:

RouterEndpointsArea
auth11Set-up, sign-in and out, refresh, sign-up, password, sessions, personal access tokens
users6Accounts, approval of sign-ups (admin)
library20Upload, import, list, edit, re-index, delete, chunks, table of contents, publishing
spaces12Spaces, their sources and members
invites5Space invite links
threads17Chats, messages, runs, run events (SSE), branches, export, attachments
code7Code cells and the chat's kernel
signin5The sign-in browser and saved sign-ins
memory4Memory items and proposals
notes4Notes and highlights
study16Study sets, items, reviews, quiz attempts, the study guide
capture9The browser extension: capture, references, highlights
admin3Settings saved in the app, and their tests
oversight5An admin's read-only view of a user's content
system3Health, status, probe
quality2Eval reports
agent1The 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.academic or verify. 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_schema with 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.delta run events while the model writes.
  • One priority gate (app/llm/scheduler.py) keeps at most LLM_CONCURRENCY calls 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.