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.
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
1# models.py2from datetime import date
3from typing import Literal
45from pydantic import BaseModel, ConfigDict, Field
67Kind = Literal["contract","invoice","other"]8910classSorting(BaseModel):11 kind: Kind = Field(description="contract, invoice, or other")121314classInvoice(BaseModel):15 total_due:int|None= Field(description="The total due in dollars, or null if there is none")16 invoice_date: date |None= Field(description="The date of the invoice")17 payment_due: date |None= Field(description="The date payment is due")181920classDeskState(BaseModel):21 model_config = ConfigDict(validate_assignment=True)2223 path:str=""24 text:str=""25 kind: Kind |None=None26 memo:str=""27 invoice: Invoice |None=None28 findings:list[str]=[]29 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
1# checks.py2from datetime import date, timedelta
34# From the contract: the term ends February 28, 2027 (2.1), notice is due 60 days5# before that (2.2), the fee is 18,000 dollars (3.1) and may rise by 7% (2.3),6# and invoices are due within 30 days (3.2).7TERM_ENDS = date(2027,2,28)8NOTICE_DAYS =609FEE =18_00010MOST_INCREASE =711DAYS_TO_PAY =30121314defwritten(day):15returnf"{day:%B}{day.day}, {day.year}"161718defcheck_memo(memo):19 deadline = TERM_ENDS - timedelta(days=NOTICE_DAYS)20 forms =[written(deadline),f"{deadline.day}{deadline:%B %Y}",str(deadline)]21ifany(form in memo for form in forms):22return[]23return[f"Notice is due by {written(deadline)}, and the memo doesn't say so."]242526defcheck_invoice(invoice):27 findings =[]28 most = FEE *(100+ MOST_INCREASE)//10029if invoice.total_due isnotNoneand invoice.total_due > most:30 findings.append(f"It asks for {invoice.total_due:,} dollars. The contract allows {most:,}.")31if invoice.invoice_date and invoice.payment_due:32 allowed = invoice.invoice_date + timedelta(days=DAYS_TO_PAY)33if invoice.payment_due < allowed:34 findings.append(f"It wants payment by {written(invoice.payment_due)}. The contract gives until {written(allowed)}.")35return findings
ask puts one question to one agent, and stops if the answer doesn't fit the shape. Change agents.py:
agents.py
1# agents.py2from crewai import Agent
34from models import Invoice, Sorting
567defask(role, goal, question, shape):8 agent = Agent(role=role, goal=goal, backstory="You work at a small company's front desk.")9 answer = agent.kickoff(question, response_format=shape)10if answer.pydantic isNone:11raise ValueError(f"The answer wasn't a {shape.__name__}.")12return answer.pydantic
131415defsort_document(text):16 question ="Is this document a contract, an invoice, or something else?\n\n"+ text
17return ask("Mail clerk","Say what each document is", question, Sorting).kind
181920defread_invoice(text):21 question ="Copy the facts from this invoice.\n\n"+ text
22return ask("Invoice reader","Copy facts from invoices exactly", question, Invoice)232425defwrite_memo(text):26 writer = Agent(27 role="Contract analyst",28 goal="Tell a manager what could cost them money",29 backstory="You read contracts for a small company.",30)31 answer = writer.kickoff(32"Write a memo of at most 60 words about the risks in this contract. "33"Give the last day to send notice that stops the renewal, as a full date.\n\n"+ text
34)35return 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
1# desk.py2from pathlib import Path
34from crewai.flow import human_feedback
5from crewai.flow.flow import Flow, listen, or_, router, start
6from crewai.flow.persistence import SQLiteFlowPersistence, persist
7from dotenv import load_dotenv
89import agents
10import checks
11from models import DeskState, Kind
1213load_dotenv()141516@persist(SQLiteFlowPersistence("desk.db"))17classDesk(Flow[DeskState]):18 suppress_flow_events =True1920@start()21defread_document(self):22ifnot self.state.text:23 self.state.text = Path(self.state.path).read_text()2425@router(read_document)26defsort_document(self)-> Kind:27if self.state.kind isNone:28 self.state.kind = agents.sort_document(self.state.text)29return self.state.kind
3031@listen("contract")32defreview_contract(self):33ifnot self.state.memo:34 self.state.memo = agents.write_memo(self.state.text)35 self.state.findings = checks.check_memo(self.state.memo)3637@listen("invoice")38defcheck_invoice(self):39if self.state.invoice isNone:40 self.state.invoice = agents.read_invoice(self.state.text)41 self.state.findings = checks.check_invoice(self.state.invoice)4243@listen("other")44defhand_to_person(self):45 self.state.findings =["A person needs to decide where this goes."]4647@listen(or_(review_contract, check_invoice, hand_to_person))48@human_feedback(message="Type approve to file this report, or press Enter to hold it.")49defwrite_report(self):50 findings = self.state.findings or["Nothing wrong was found."]51 lines =[f"{Path(self.state.path).name}, sorted as {self.state.kind}:"]52 self.state.report ="\n".join(lines +["- "+ finding for finding in findings])+"\n"53return self.state.report
5455@listen(write_report)56deffile_report(self):57 answer = self.last_human_feedback.feedback.strip().lower()58 folder = Path("filed"if answer =="approve"else"held")59 folder.mkdir(exist_ok=True)60 place = folder / Path(self.state.path).name
61 place.write_text(self.state.report)62returnstr(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:
The checks need no model, so the tests call them directly, as in chapter 11. Change test_desk.py:
test_desk.py
1# test_desk.py2from datetime import date
34import checks
5from models import Invoice
678deftest_a_wrong_deadline_is_found():9assert checks.check_memo("Send notice by December 31, 2026.")==[10"Notice is due by December 30, 2026, and the memo doesn't say so."11]121314deftest_a_right_deadline_passes():15assert checks.check_memo("Send notice by 30 December 2026.")==[]161718deftest_an_invoice_over_the_fee_is_found():19 invoice = Invoice(total_due=19_800, invoice_date=date(2027,3,1), payment_due=date(2027,3,31))20assert checks.check_invoice(invoice)==["It asks for 19,800 dollars. The contract allows 19,260."]
Terminal
1(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.
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:
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:
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:
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
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.