FastAPI Internals
Application bootstrap, dependency injection, error handling patterns, database layer, and Pydantic models.
apps/api/app/main.py installs the graph’s checkpointer and wires the two routers:
@asynccontextmanager
async def lifespan(_app: FastAPI):
async with postgres_checkpointer(DATABASE_URL):
yield
app = FastAPI(title="Configent API", version="0.1.0", lifespan=lifespan)
app.include_router(health.router) # /healthz, /healthz/db
app.include_router(clients.router) # /api/...
The lifespan opens LangGraph’s Postgres saver and compiles the support graph against it. Without it, stream_turn() raises: the ticket pause cannot work with no checkpointer.
ConfigRegistry is still lazy. get_registry() builds it on first call, so a bad YAML file, an unknown key or an unpriced model surfaces on the first request rather than at process start.
Dependency injection
Request
│
├─ Depends(get_db) ──► AsyncSessionLocal().__aenter__()
│ yields AsyncSession
│ __aexit__ closes on response end
│
└─ get_registry() ──► module-level ConfigRegistry singleton
(called inline, not as a Depends)
get_db is a standard async generator dependency. FastAPI opens the session before the handler runs and closes it after sending the response. The streaming endpoint (/chat/stream) cannot use this pattern because the session must outlive the HTTP headers. It opens its own session inside the event_source generator instead.
get_registry() is not a Depends. It returns the singleton directly, so calling it repeatedly is safe.
Graph integration
The router delegates to agent/platform.py. No background tasks, no worker queue: the graph runs inline with async/await.
Streaming path (/chat/stream):
return StreamingResponse(event_source(), media_type="text/event-stream", ...)
event_source() iterates stream_turn() and re-yields each (name, data) tuple as an SSE frame. FastAPI flushes each yield immediately.
Sync path (/chat):
state = await run_turn(req.message, template=documents.TEMPLATE, cfg=cfg, ...)
return ChatResponse(conversation_id=state["conversation_id"], reply=state["answer"], ...)
run_turn() drains stream_turn() and returns the final state, so the two paths cannot drift.
See The Support Graph for what runs inside, and SSE Streaming for the event contract.
Error handling
| Scenario | Handling |
|---|---|
Unknown client_id | registry.get() raises KeyError → caught in router → HTTPException(404) |
| Conversation owned by another client | _check_conversation_ownership() → 404, before the stream starts |
| Rate limit or daily budget exceeded | HTTPException(429) with a JSON body, before the stream starts |
| Anthropic API error | stream_turn() rolls back, marks the run failed, yields error naming the exception class |
| Any other exception in a turn | Same, with a generic message. /chat turns the error into a 500 |
| Confirming an unknown, foreign or unpaused run | RunUnavailable → 404 that reveals nothing about which |
DB unreachable (/healthz/db) | SQLAlchemy raises → FastAPI returns 500 |
| Invalid YAML, unknown key, unpriced model | Raised in config/registry.py when get_registry() first loads |
Streaming errors cannot use HTTP status codes because FastAPI already sent the headers before the error occurs. They surface via the error SSE event. The frontend renders the message inside the assistant bubble rather than crashing.
Database layer
database.py creates a single async engine and session factory:
engine = create_async_engine(DATABASE_URL, echo=False, pool_pre_ping=True)
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_db() -> AsyncSession:
async with AsyncSessionLocal() as session:
yield session
pool_pre_ping=True silently recycles stale connections before handing them to a handler.
expire_on_commit=False prevents ORM objects from expiring immediately after commit().
checkpoint_session() is the third way to get a session: short-lived, committing on exit, used only for durability writes to runs. See Runs & Durability.
Tables:
| Table | Key columns |
|---|---|
clients | id (PK), name, config_snapshot |
documents | id, client_id, source_uri, title, content_hash |
chunks | id, document_id, client_id, text, embedding (Vector), text_search (tsvector) |
conversations | id (UUID PK), client_id, total_cost, total_tokens |
messages | id, conversation_id, role, content (JSON), citations (JSON), run_id |
runs | id, conversation_id, client_id, status, current_stage, steps (JSON) |
traces | id, conversation_id, span_type, tokens_in/out, cost_usd, latency_ms |
eval_runs | id, client_id, git_sha, scores (JSON) |
LangGraph’s saver creates its own checkpoint tables on startup.
client_id is denormalized onto chunks so pgvector similarity queries can filter by tenant without joining to documents on the hot path.
Pydantic models
Config (app/config/schema.py, app/config/pricing.py):
| Model | Purpose |
|---|---|
BrandingConfig | logo, primary_color, assistant_name, tagline, suggested_questions |
ChunkingConfig | chunk_size (default 800), overlap (default 100) |
CorpusConfig | source path, nested ChunkingConfig |
AgentConfig | model, system_prompt_file, max_tokens, thresholds, corrective. Forbids unknown keys |
CorrectiveConfig | enabled, query_rewrites (1–5) |
EvalsConfig | golden_set path, judge_model |
LimitsConfig | rate_limit_per_minute (20), daily_budget_usd (2.00) |
ClientConfig | Root config; client_id validated as lowercase slug; system_prompt_path() method |
ModelPrice | One row of config/pricing/claude.yaml: input, output, cache_write, cache_read |
Request / response (routers/clients.py):
| Model | Fields |
|---|---|
ChatRequest | message: str, conversation_id: str | None |
ChatResponse | conversation_id, reply, citations: list[dict], segments: list[dict] |
Internal types (agent/common.py, agent/platform.py, agent/templates/documents.py):
| Type | Purpose |
|---|---|
UsageTotals | Token counts summed across a turn’s model calls; cost_usd prices them at the model’s row |
TurnState | The graph state. Plain JSON, checkpointed after every node |
Deps | Per-request objects (config, session, client, recorder). Passed as LangGraph context, never checkpointed |
RunRecorder | Owns the runs row: one committed step per node |