Datalumina

The AI

Contract sections

Store the three contract types as plain data, and let LLM step 2 write each section with its own prompt and its own model call.

By the end of this page each contract type is a template, and the model writes every section of it with its own prompt and its own call.

A small prompt per section is easier to read, test, and fix than one prompt for a whole contract. When the milestones come out wrong, you change one line. A template is a title and a dict of prompts, with no classes.

Write the templates

backend/app/templates.py
CLIENT_INPUT = ("What we need from the client", "Access, data, people and decisions, as bullets.")

# The three contract types. "sections" are written by the AI, one call each, with their own
# prompt. The model never writes a price, a date or a legal clause.
TEMPLATES = {
    "fixed_price": {
        "title": "Statement of Work",
        "sections": {
            "summary": ("Project summary", "Two or three sentences: the problem and the change."),
            "scope": ("Scope and deliverables", "What we build and hand over, as bullets."),
            "milestones": ("Milestones", "The phases in order and what each delivers, as bullets."),
            "client_input": CLIENT_INPUT,
            "out_of_scope": ("Out of scope", "Exclusions as bullets. Never restate the scope."),
        },
    },
    "retainer": {
        "title": "Monthly Retainer",
        "sections": {
            "purpose": ("Purpose", "In two or three sentences: what the retainer is for."),
            "services": ("Monthly services", "The work we do every month, as bullets."),
            "requests": ("How the client asks for work", "How requests reach us and get priority."),
            "reporting": ("Reporting", "What we report to the client each month."),
            "client_input": CLIENT_INPUT,
            "not_included": ("Not included", "What the retainer does not cover, as bullets."),
        },
    },
    "discovery": {
        "title": "Discovery & AI Audit",
        "sections": {
            "context": ("Context", "In two or three sentences: the business and why audit now."),
            "questions": ("Questions we answer", "The main questions of the audit, as bullets."),
            "approach": ("Approach", "Interviews, data and process review, as bullets."),
            "roadmap": ("Deliverable: the AI roadmap", "What the report contains, as bullets."),
        },
    },
}

Each section has a title and a prompt. The key, such as scope, is how the app finds the section again later. CLIENT_INPUT is shared, because fixed-price work and retainers need the same things from the client.

Add the section writer

Replace backend/app/ai.py. The highlighted lines are new.

backend/app/ai.py
import re
from datetime import date
from typing import Literal

from pydantic import BaseModel, Field
from pydantic_ai import Agent

from app.config import settings


# LLM step 1: route the intake to a contract type and extract the facts, as structured output.
class Extraction(BaseModel):
    contract_type: Literal["fixed_price", "retainer", "discovery", "none"]
    reason: str = Field(description="One sentence: why this contract type")
    client_company: str | None
    contact_name: str | None
    contact_email: str | None
    price: float | None = Field(description="Agreed total, or the monthly fee")
    currency: str | None = Field(description="ISO code, e.g. USD")
    start_date: date | None
    duration: str | None = Field(description="As written, e.g. '6 weeks'")
    hours_per_month: int | None = Field(description="Retainers only")


extractor = Agent(
    settings.ai_model,
    output_type=Extraction,
    instructions=f"""
You read the notes of a client intake meeting at {settings.company_name}, a small AI
consultancy. Pick the contract type and extract the agreed facts.

- fixed_price: a project with a fixed scope and one agreed total price.
- retainer: ongoing monthly work for a monthly fee.
- discovery: a short, paid audit or discovery phase that ends in a roadmap.
- none: anything else, for example a job offer or no deal at all.

The price is the agreed total, or the monthly fee for a retainer. It is never a budget
range, an hourly rate, a single milestone payment or the client's own costs.
When a fact is not agreed in the notes, use null. Never guess.
""",
)


def extract(notes: str) -> Extraction:
    return extractor.run_sync(notes).output


def amounts_in(text: str) -> set[float]:
    """Every amount in the text as a number: '$18,500' -> 18500, '22k' -> 22000, '6k/mo' -> 6000."""
    found = re.findall(r"(\d[\d,]*(?:\.\d+)?)\s*(k)?\b", text, re.IGNORECASE)
    return {float(number.replace(",", "")) * (1000 if k else 1) for number, k in found}


def review_reasons(extraction: Extraction, notes: str) -> list[str]:
    """The model proposes, Python decides. Any reason sends the contract to a person."""
    reasons = []
    if extraction.contract_type == "none":
        reasons.append(f"No contract type fits: {extraction.reason}")
    if extraction.price is None:
        reasons.append("The notes have no agreed price.")
    elif extraction.price not in amounts_in(notes):
        reasons.append(f"The price {extraction.price:g} is not in the notes.")
    if not (extraction.client_company and extraction.contact_name and extraction.contact_email):
        reasons.append("The notes do not name the client, a contact and an email.")
    return reasons


# LLM step 2: one call per contract section, each with its own prompt.
writer = Agent(
    settings.ai_model,
    instructions=f"""
You write one section of a client agreement for {settings.company_name}, a small AI
consultancy. Use only facts from the intake notes; when they say nothing, write less.
Plain text, under 120 words. For lists, use lines that start with "- ".
No headings, no Markdown, no money amounts and no dates: the contract adds those itself.
Write "we" for {settings.company_name} and "the client" for the client.
""",
)


def write_section(notes: str, fields: dict, title: str, prompt: str) -> str:
    request = f"Write the section '{title}': {prompt}\n\nAgreed facts: {fields}\n\nNotes:\n{notes}"
    return writer.run_sync(request).output.strip()


if __name__ == "__main__":
    import sys
    from pathlib import Path

    from app.templates import TEMPLATES

    notes = Path(sys.argv[1]).read_text()
    extraction = extract(notes)
    print(extraction.model_dump_json(indent=2), review_reasons(extraction, notes) or "Ready")
    if extraction.contract_type in TEMPLATES:  # Step 2, every section of the template
        for title, prompt in TEMPLATES[extraction.contract_type]["sections"].values():
            text = write_section(notes, extraction.model_dump(mode="json"), title, prompt)
            print(f"\n## {title}\n{text}")

The writer has no structured output. It returns plain text with - bullets, which the contract turns into lists later. The instructions forbid money amounts and dates, because Python writes those from the checked fields. Each call gets the section prompt, the extracted facts, and the full notes.

Check

uv run --locked --no-sync python -m app.ai ../samples/intakes/03-ecommerce-support-retainer.md

Run it from the backend folder. Sample 03 is a retainer, so after the extraction you see six sections, from ## Purpose to ## Not included. Each one is plain text with - bullets and no amounts or dates.

## Purpose
...

## Monthly services
- ...

That is six model calls, one after another, so it takes a while. The next page moves that wait out of the request.

ai.py
config.py
db.py
main.py
templates.py

On this page