Skip to content
/

The whole desk

Ready for real workChapter 15 of 159 min read

Each chapter built one part of the desk in a demo.py of its own. This last chapter answers: what does the whole desk look like, and what does it do with the three documents in the inbox?


One flow reads a document, sorts it, checks it, and asks a person before it files the report:

Drawing diagram…
InputToolResultThe whole desk
  • Desk: the finished flow, in desk.py. Agents read; Python checks; a person decides.
  • run_desk.py: runs the desk on one document, named on the command line, and uses the file's name as the run's id.

Set up#

If you closed the terminal, go back into the folder and switch the environment on:

Terminal
$ cd document-desk
$ source env/bin/activate

This chapter calls the model, so .env must hold your key, as in chapter 8.

The files#

The typed answers and the state go in one file. Sorting and Invoice are what the agents hand back, as in chapter 8. Let's save this as models.py:

models.py
# models.py
from datetime import date
from typing import Literal

from pydantic import BaseModel, ConfigDict, Field

Kind = Literal["contract", "invoice", "other"]


class Sorting(BaseModel):
    kind: Kind = Field(description="contract, invoice, or other")


class Invoice(BaseModel):
    total_due: int | None = Field(description="The total due in dollars, or null if there is none")
    invoice_date: date | None = Field(description="The date of the invoice")
    payment_due: date | None = Field(description="The date payment is due")


class DeskState(BaseModel):
    model_config = ConfigDict(validate_assignment=True)

    path: str = ""
    text: str = ""
    kind: Kind | None = None
    memo: str = ""
    invoice: Invoice | None = None
    findings: list[str] = []
    report: str = ""

The checks work each fact out in Python, as in chapter 10. The contract's terms are written in from its sections. Let's save this as checks.py:

checks.py
# checks.py
from datetime import date, timedelta

# From the contract: the term ends February 28, 2027 (2.1), notice is due 60 days
# before that (2.2), the fee is 18,000 dollars (3.1) and may rise by 7% (2.3),
# and invoices are due within 30 days (3.2).
TERM_ENDS = date(2027, 2, 28)
NOTICE_DAYS = 60
FEE = 18_000
MOST_INCREASE = 7
DAYS_TO_PAY = 30


def written(day):
    return f"{day:%B} {day.day}, {day.year}"


def check_memo(memo):
    deadline = TERM_ENDS - timedelta(days=NOTICE_DAYS)
    forms = [written(deadline), f"{deadline.day} {deadline:%B %Y}", str(deadline)]
    if any(form in memo for form in forms):
        return []
    return [f"Notice is due by {written(deadline)}, and the memo doesn't say so."]


def check_invoice(invoice):
    findings = []
    most = FEE * (100 + MOST_INCREASE) // 100
    if invoice.total_due is not None and invoice.total_due > most:
        findings.append(f"It asks for {invoice.total_due:,} dollars. The contract allows {most:,}.")
    if invoice.invoice_date and invoice.payment_due:
        allowed = invoice.invoice_date + timedelta(days=DAYS_TO_PAY)
        if invoice.payment_due < allowed:
            findings.append(f"It wants payment by {written(invoice.payment_due)}. The contract gives until {written(allowed)}.")
    return findings

ask puts one question to one agent, and stops if the answer doesn't fit the shape. Change agents.py:

agents.py
# agents.py
from crewai import Agent

from models import Invoice, Sorting


def ask(role, goal, question, shape):
    agent = Agent(role=role, goal=goal, backstory="You work at a small company's front desk.")
    answer = agent.kickoff(question, response_format=shape)
    if answer.pydantic is None:
        raise ValueError(f"The answer wasn't a {shape.__name__}.")
    return answer.pydantic


def sort_document(text):
    question = "Is this document a contract, an invoice, or something else?\n\n" + text
    return ask("Mail clerk", "Say what each document is", question, Sorting).kind


def read_invoice(text):
    question = "Copy the facts from this invoice.\n\n" + text
    return ask("Invoice reader", "Copy facts from invoices exactly", question, Invoice)


def write_memo(text):
    writer = Agent(
        role="Contract analyst",
        goal="Tell a manager what could cost them money",
        backstory="You read contracts for a small company.",
    )
    answer = writer.kickoff(
        "Write a memo of at most 60 words about the risks in this contract. "
        "Give the last day to send notice that stops the renewal, as a full date.\n\n" + text
    )
    return answer.raw

The desk joins every chapter's part. -> Kind tells CrewAI the three words the router can return, so it knows the paths before a run. Each step that calls an agent looks in the state first, as in chapter 13. Change desk.py:

desk.py
# desk.py
from pathlib import Path

from crewai.flow import human_feedback
from crewai.flow.flow import Flow, listen, or_, router, start
from crewai.flow.persistence import SQLiteFlowPersistence, persist
from dotenv import load_dotenv

import agents
import checks
from models import DeskState, Kind

load_dotenv()


@persist(SQLiteFlowPersistence("desk.db"))
class Desk(Flow[DeskState]):
    suppress_flow_events = True

    @start()
    def read_document(self):
        if not self.state.text:
            self.state.text = Path(self.state.path).read_text()

    @router(read_document)
    def sort_document(self) -> Kind:
        if self.state.kind is None:
            self.state.kind = agents.sort_document(self.state.text)
        return self.state.kind

    @listen("contract")
    def review_contract(self):
        if not self.state.memo:
            self.state.memo = agents.write_memo(self.state.text)
        self.state.findings = checks.check_memo(self.state.memo)

    @listen("invoice")
    def check_invoice(self):
        if self.state.invoice is None:
            self.state.invoice = agents.read_invoice(self.state.text)
        self.state.findings = checks.check_invoice(self.state.invoice)

    @listen("other")
    def hand_to_person(self):
        self.state.findings = ["A person needs to decide where this goes."]

    @listen(or_(review_contract, check_invoice, hand_to_person))
    @human_feedback(message="Type approve to file this report, or press Enter to hold it.")
    def write_report(self):
        findings = self.state.findings or ["Nothing wrong was found."]
        lines = [f"{Path(self.state.path).name}, sorted as {self.state.kind}:"]
        self.state.report = "\n".join(lines + ["- " + finding for finding in findings]) + "\n"
        return self.state.report

    @listen(write_report)
    def file_report(self):
        answer = self.last_human_feedback.feedback.strip().lower()
        folder = Path("filed" if answer == "approve" else "held")
        folder.mkdir(exist_ok=True)
        place = folder / Path(self.state.path).name
        place.write_text(self.state.report)
        return str(place)

sys.argv[1] is the first word after the program's name. Path(path).stem is the file's name without .md. Let's save this as run_desk.py:

run_desk.py
# run_desk.py
import sys
from pathlib import Path

from desk import Desk

path = sys.argv[1]
print(Desk().kickoff(inputs={"id": Path(path).stem, "path": path}))

Test the checks#

The checks need no model, so the tests call them directly, as in chapter 11. Change test_desk.py:

test_desk.py
# test_desk.py
from datetime import date

import checks
from models import Invoice


def test_a_wrong_deadline_is_found():
    assert checks.check_memo("Send notice by December 31, 2026.") == [
        "Notice is due by December 30, 2026, and the memo doesn't say so."
    ]


def test_a_right_deadline_passes():
    assert checks.check_memo("Send notice by 30 December 2026.") == []


def test_an_invoice_over_the_fee_is_found():
    invoice = Invoice(total_due=19_800, invoice_date=date(2027, 3, 1), payment_due=date(2027, 3, 31))
    assert checks.check_invoice(invoice) == ["It asks for 19,800 dollars. The contract allows 19,260."]
Terminal
(env)$ python -m pytest -q
Output
...                                                                      [100%]3 passed in 0.07s

Three checks passed in less than a tenth of a second, with no key and no model.

Run each document#

Let's run the contract, and approve its report. echo approve | types the word at the prompt for you, as in chapter 12:

Terminal
(env)$ echo approve | python run_desk.py inbox/acme-saas-agreement.md
Output
No flow state found for UUID: acme-saas-agreement...══════════════════════════════════════════════════  OUTPUT FOR REVIEW══════════════════════════════════════════════════
acme-saas-agreement.md, sorted as contract:- Notice is due by December 30, 2026, and the memo doesn't say so.

══════════════════════════════════════════════════
Type approve to file this report, or press Enter to hold it.(Press Enter to skip, or type your feedback)
Your feedback: filed/acme-saas-agreement.md

... stands for the boxes CrewAI draws while the agents work. Your agent's memo will differ. The mail clerk sorted the document as a contract, the analyst wrote a memo, and the check in code found its notice deadline wrong, as in every run of a real agent since chapter 9.

approve was typed, so the report went to filed. The path after "Your feedback:" is what file_report returned; the typed word isn't shown:

Drawing diagram…
InputToolResultThe contract's path

Now the invoice:

Terminal
(env)$ echo approve | python run_desk.py inbox/acme-invoice-renewal.md
Output
No flow state found for UUID: acme-invoice-renewal...══════════════════════════════════════════════════  OUTPUT FOR REVIEW══════════════════════════════════════════════════
acme-invoice-renewal.md, sorted as invoice:- It asks for 19,800 dollars. The contract allows 19,260.- It wants payment by March 16, 2027. The contract gives until March 31, 2027.

══════════════════════════════════════════════════
Type approve to file this report, or press Enter to hold it.(Press Enter to skip, or type your feedback)
Your feedback: filed/acme-invoice-renewal.md

The invoice reader copied three facts, and Python did the sums: 18,000 dollars plus 7% is 19,260, and March 1 plus 30 days is March 31. The invoice asks for more, and sooner:

Drawing diagram…
ToolResultThe invoice's path

And the agenda, held this time:

Terminal
(env)$ echo | python run_desk.py inbox/team-offsite-agenda.md
Output
No flow state found for UUID: team-offsite-agenda...══════════════════════════════════════════════════  OUTPUT FOR REVIEW══════════════════════════════════════════════════
team-offsite-agenda.md, sorted as other:- A person needs to decide where this goes.

══════════════════════════════════════════════════
Type approve to file this report, or press Enter to hold it.(Press Enter to skip, or type your feedback)
Your feedback: held/team-offsite-agenda.md

The agenda is neither a contract nor an invoice, so the router sent it to hand_to_person. Enter held it, for a person to look at:

Drawing diagram…
ToolResultThe agenda's path

Run it again#

Let's run the contract a second time:

Terminal
(env)$ echo approve | python run_desk.py inbox/acme-saas-agreement.md
Output
Loading flow state from memory for UUID: acme-saas-agreement
══════════════════════════════════════════════════  OUTPUT FOR REVIEW══════════════════════════════════════════════════
acme-saas-agreement.md, sorted as contract:- Notice is due by December 30, 2026, and the memo doesn't say so.

══════════════════════════════════════════════════
Type approve to file this report, or press Enter to hold it.(Press Enter to skip, or type your feedback)
Your feedback: filed/acme-saas-agreement.md

This time there are no boxes: no agent ran. The state under acme-saas-agreement already had the kind and the memo, so sort_document and review_contract used them, and only the check ran again:

Drawing diagram…
InputToolResultThe second run uses what the first paid for

What the runs showed#

Each part did the job its chapter gave it:

Drawing diagram…
InputResultWho did what in the runs

The agents read well and sorted every document right, but the memo's deadline was wrong again. The code caught it, because it works the date out instead of reading an argument. And nothing was filed until a person said so.

Let agents read, let Python check, and let a person decide what's done.

What to try next#

The desk reads one document per run. Chapter 14 read three at once, but here each run stops to ask a person:

Drawing diagram…
InputResultThree runs, one person

How would you let the agents read the whole inbox at once, and still show the person one report at a time?