The AI
Route and extract
LLM step 1 with Pydantic AI and structured output picks the contract type and extracts the facts, then plain Python decides whether the contract can be drafted.
By the end of this page one model call reads an intake, picks the contract type, and extracts the client, the price, and the dates. Python then decides whether the contract can be drafted or needs a person.
The model proposes, code decides. The model picks which number in the notes is the price. Python checks that the number really appears there. Whether the model picked the right number is what the evals measure later.
Add the API key
In the Claude Console, open API keys, create a key named contract-drafting, and set it in .env. The model is already set.
ANTHROPIC_API_KEY=sk-ant-...
AI_MODEL=anthropic:claude-opus-5-5AI_MODEL=test runs without a key and without cost. It returns placeholder data with a price of 0, so every intake goes to review. Use it to test the plumbing, not the AI.
Add the AI settings
Replace backend/app/config.py.
import os
from pathlib import Path
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
# Local runs read .env in the project root. In Docker, Compose passes the same values.
model_config = SettingsConfigDict(env_file=Path(__file__).parents[2] / ".env", extra="ignore")
company_name: str = "Pinewick Systems"
database_url: str
anthropic_api_key: str = ""
ai_model: str = "anthropic:claude-opus-5-5" # "test" runs without a key
settings = Settings()
# Pydantic AI reads the Anthropic key from the environment.
if settings.anthropic_api_key:
os.environ["ANTHROPIC_API_KEY"] = settings.anthropic_api_keyPydantic AI reads the key from the environment, not from your settings object, so the last lines copy it there.
Write the extraction
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
if __name__ == "__main__":
import sys
from pathlib import Path
notes = Path(sys.argv[1]).read_text()
extraction = extract(notes)
print(extraction.model_dump_json(indent=2), review_reasons(extraction, notes) or "Ready")Extraction is the structured output. The model has to fill in every field, and null is a valid answer, which is how it says a fact is missing. The Literal limits the contract type to four values, and the Field descriptions tell the model what each value means.
The instructions name the traps in plain words. A price is never a budget range, an hourly rate, or a single milestone. When a fact is not agreed, the answer is null.
amounts_in() reads every number in the notes, including 22k and 6k/mo. review_reasons() is plain Python, and any reason it returns sends the contract to a person. Only the price is checked against the text. Dates are written in too many ways, such as "first Monday of March 2027", for a short check, so the evals test them instead.
The block at the bottom lets you run the file on one sample. The samples are plain notes, so the model sees exactly what an upload would send.
Check
cd backend
uv run --locked --no-sync python -m app.ai ../samples/intakes/05-logistics-automation-backend.md
uv run --locked --no-sync python -m app.ai ../samples/intakes/06-recruitment-crm-retainer.mdSample 05 is a messy note where the price only appears as "22k", next to a $1,100 Zapier bill. It should come back as fixed_price with the price 22000 and no reasons:
{
"contract_type": "fixed_price",
...
"client_company": "Northgate Freight",
...
"price": 22000.0,
...
} ReadySample 06 is a retainer call where nobody agreed on a price. Its list of reasons should include The notes have no agreed price. Run 07 as well. It is a job offer, so it gets the reason "No contract type fits".