The AI
Background processing
Run the pipeline with FastAPI BackgroundTasks after the upload returns, save the status of every step, and retry from the first unfinished section.
By the end of this page an upload returns at once. The pipeline runs in the background and saves the status of the contract and of every section as it goes, so the admin page on the next page can follow along.
Six model calls take a while. There is no worker container and no queue here. A background task in the same process, with the status in the database, is enough for one user. A restart marks unfinished work as failed, and Retry continues from the first section that is not done.
Run the pipeline in the background
Replace backend/app/main.py.
from contextlib import asynccontextmanager
from fastapi import BackgroundTasks, FastAPI, HTTPException
from pydantic import BaseModel, Field
from sqlalchemy import select, update
from sqlalchemy.orm.attributes import flag_modified
from app import ai
from app.config import settings
from app.db import Base, Contract, SessionDep, engine, new_session
from app.templates import TEMPLATES
@asynccontextmanager
async def lifespan(app: FastAPI):
Base.metadata.create_all(engine) # Creates the table if it is missing. Never alters it.
# Work that was running when the app stopped will never finish. Retry picks it up.
with new_session() as session:
session.execute(update(Contract).where(Contract.status.in_(["pending", "processing"]))
.values(status="failed", reason="Interrupted by a restart"))
session.commit()
yield
app = FastAPI(title="Contract drafting", lifespan=lifespan)
@app.get("/health")
def health() -> dict:
return {"status": "ok", "company": settings.company_name}
def found[T](row: T | None) -> T:
if row is None:
raise HTTPException(404, "Not found")
return row
# Admin API. Not published: the browser reaches it only through Next.js, which asks for
# the admin password.
class Upload(BaseModel):
notes: str = Field(min_length=20, max_length=50_000)
@app.post("/api/contracts")
def upload(upload: Upload, background: BackgroundTasks, session: SessionDep) -> dict:
title = upload.notes.strip().splitlines()[0].strip("# ")[:120]
contract = Contract(title=title, notes=upload.notes)
session.add(contract)
session.commit()
background.add_task(process, contract.id)
return {"id": contract.id}
@app.get("/api/contracts")
def list_contracts(session: SessionDep) -> list[dict]:
columns = Contract.id, Contract.title, Contract.status, Contract.contract_type
return session.execute(select(*columns).order_by(Contract.id.desc())).mappings().all()
@app.get("/api/contracts/{contract_id}")
def get_contract(contract_id: int, session: SessionDep) -> dict:
return found(session.get(Contract, contract_id)).as_dict()
@app.post("/api/contracts/{contract_id}/retry")
def retry(contract_id: int, background: BackgroundTasks, session: SessionDep) -> dict:
# with_for_update locks the row until commit, so two clicks cannot both pass the check.
contract = found(session.get(Contract, contract_id, with_for_update=True))
if contract.status != "failed":
raise HTTPException(409, "Not failed")
contract.status = "pending"
session.commit()
background.add_task(process, contract_id)
return {"status": "pending"}
def process(contract_id: int) -> None:
"""Runs after the response, in its own session. Every commit shows in the admin page."""
with new_session() as session:
contract = session.get(Contract, contract_id)
contract.status, contract.reason = "processing", None
session.commit()
try:
if not contract.fields: # LLM step 1, then Python decides.
extraction = ai.extract(contract.notes)
reasons = ai.review_reasons(extraction, contract.notes)
contract.contract_type = extraction.contract_type
contract.fields = extraction.model_dump(mode="json")
if reasons:
contract.status, contract.reason = "needs_review", "\n".join(reasons)
session.commit()
return
template = TEMPLATES[contract.contract_type]
contract.title = f"{template['title']}: {contract.fields['client_company']}"
contract.sections = [{"key": key, "title": title, "status": "pending", "text": ""}
for key, (title, _) in template["sections"].items()]
session.commit()
prompts = TEMPLATES[contract.contract_type]["sections"]
for section in [s for s in contract.sections if s["status"] != "done"]: # LLM step 2
section["status"] = "writing"
flag_modified(contract, "sections") # SQLAlchemy can't see changes inside a list.
session.commit()
title, prompt = prompts[section["key"]]
section["text"] = ai.write_section(contract.notes, contract.fields, title, prompt)
section["status"] = "done"
flag_modified(contract, "sections")
session.commit()
contract.status = "drafted"
session.commit()
except Exception as error:
session.rollback()
contract.status, contract.reason = "failed", str(error)
session.commit()upload saves the row, adds process as a background task, and returns. FastAPI runs the task after it sends the response.
process opens its own session with new_session(). The request's session closes when the response goes out, and the task runs after that. Every commit() saves one step, so the admin page sees each status change.
process runs LLM step 1 and the Python checks. With review reasons, it saves them and stops at needs_review. Otherwise it creates one entry per template section, all pending, and gives the contract a title such as "Statement of Work: Harborview Dental Group". Then it writes the sections one by one and saves every status change, first writing and then done.
SQLAlchemy only notices a new value for an attribute. Changing a dict inside the sections list changes nothing it can see, so flag_modified(contract, "sections") tells it the list changed. Without that line the section statuses never reach the database.
Every step reads what is already saved. A contract that has fields skips step 1, and sections that are done are skipped. That is what makes Retry continue where it stopped.
retry loads the contract with with_for_update=True. Postgres locks the row until commit(), so two clicks on Retry cannot both pass the failed check and start the work twice. An unknown ID gives a 404.
lifespan runs when the app starts. After create_all(), it marks every contract that was pending or processing as failed with the reason "Interrupted by a restart", because a task that was running when the app stopped will never finish.
Check
From the backend folder, upload sample 01. The command keeps the ID of the new contract in ID, so the next commands read the right contract, whatever you uploaded before.
ID=$(python3 -c 'import json, sys; print(json.dumps({"notes": sys.stdin.read()}))' \
< ../samples/intakes/01-dental-phone-receptionist.md \
| curl -s -H 'content-type: application/json' -d @- http://localhost:8000/api/contracts \
| python3 -c 'import json, sys; print(json.load(sys.stdin)["id"])')The upload returns right away. Read the contract a few times:
curl http://localhost:8000/api/contracts/$IDThe status goes from processing to drafted, and the sections move from pending to writing to done.
| Test | Expected |
|---|---|
Upload 06 or 07 | needs_review, with the reason in reason |
Upload 01 again, stop the API with Ctrl+C during the run, then start it again | failed, with the reason "Interrupted by a restart" |
curl -X POST http://localhost:8000/api/contracts/$ID/retry on that contract | It finishes and reaches drafted |
Retry a contract that is not failed | 409 with {"detail":"Not failed"} |
Run the upload command above for the restart test, so ID points at the contract you interrupt. On Windows, use curl.exe for the retry.
fastapi dev reloads on every save, and a reload counts as a restart. Don't save files while a contract is processing. If it happens, use Retry. The test contract from the last page was still pending when the API reloaded with this code, so it is now failed too.
One section at a time
The sections of one contract run one after another. Two different contracts do run at the same time, because FastAPI runs each background task in its own worker thread.