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

ScenarioHandling
Unknown client_idregistry.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 exceededHTTPException(429) with a JSON body, before the stream starts
Anthropic API errorstream_turn() rolls back, marks the run failed, yields error naming the exception class
Any other exception in a turnSame, with a generic message. /chat turns the error into a 500
Confirming an unknown, foreign or unpaused runRunUnavailable → 404 that reveals nothing about which
DB unreachable (/healthz/db)SQLAlchemy raises → FastAPI returns 500
Invalid YAML, unknown key, unpriced modelRaised 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:

TableKey columns
clientsid (PK), name, config_snapshot
documentsid, client_id, source_uri, title, content_hash
chunksid, document_id, client_id, text, embedding (Vector), text_search (tsvector)
conversationsid (UUID PK), client_id, total_cost, total_tokens
messagesid, conversation_id, role, content (JSON), citations (JSON), run_id
runsid, conversation_id, client_id, status, current_stage, steps (JSON)
tracesid, conversation_id, span_type, tokens_in/out, cost_usd, latency_ms
eval_runsid, 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):

ModelPurpose
BrandingConfiglogo, primary_color, assistant_name, tagline, suggested_questions
ChunkingConfigchunk_size (default 800), overlap (default 100)
CorpusConfigsource path, nested ChunkingConfig
AgentConfigmodel, system_prompt_file, max_tokens, thresholds, corrective. Forbids unknown keys
CorrectiveConfigenabled, query_rewrites (1–5)
EvalsConfiggolden_set path, judge_model
LimitsConfigrate_limit_per_minute (20), daily_budget_usd (2.00)
ClientConfigRoot config; client_id validated as lowercase slug; system_prompt_path() method
ModelPriceOne row of config/pricing/claude.yaml: input, output, cache_write, cache_read

Request / response (routers/clients.py):

ModelFields
ChatRequestmessage: str, conversation_id: str | None
ChatResponseconversation_id, reply, citations: list[dict], segments: list[dict]

Internal types (agent/common.py, agent/platform.py, agent/templates/documents.py):

TypePurpose
UsageTotalsToken counts summed across a turn’s model calls; cost_usd prices them at the model’s row
TurnStateThe graph state. Plain JSON, checkpointed after every node
DepsPer-request objects (config, session, client, recorder). Passed as LangGraph context, never checkpointed
RunRecorderOwns the runs row: one committed step per node