Every fact so far was written into the code. On the real desk an AI reads the invoice, so this chapter answers: how does an agent become one step of the flow?
The step hands the invoice's text to an agent, and puts its answer in the state:
Drawing diagram…
InputAgentToolResultAn agent inside read_invoice
Agent: an AI with a role, a goal and a backstory, which answers what it's asked.
kickoff(): asks an agent one question, and gives back its answer.
Typed answer: an answer in the shape of a Pydantic model, asked for with response_format.
If you closed the terminal, go back into the folder and switch the environment on:
Terminal
1$ cd document-desk
2$ source env/bin/activate
An agent needs a model and a key, and CrewAI reads both from a file called .env. MODEL names the model the way CrewAI's list of providers writes it, and the key's name depends on the provider:
read_invoice makes an agent and calls its kickoff() with a question and the text. answer.raw is what the agent wrote. load_dotenv() reads .env when the program starts. Let's save this as demo.py:
demo.py
1# demo.py2from crewai import Agent
3from crewai.flow.flow import Flow, listen, start
4from dotenv import load_dotenv
5from pydantic import BaseModel, ConfigDict
67load_dotenv()8910classDeskState(BaseModel):11 model_config = ConfigDict(validate_assignment=True)1213 path:str=""14 text:str=""15 amount:int=0161718classDesk(Flow[DeskState]):19 suppress_flow_events =True2021@start()22defread_document(self):23withopen(self.state.path)asfile:24 self.state.text =file.read()2526@listen(read_document)27defread_invoice(self):28 reader = Agent(29 role="Invoice reader",30 goal="Copy numbers from invoices exactly",31 backstory="You open the mail at a small company.",32)33 answer = reader.kickoff("What is the total due?\n\n"+ self.state.text)34print(answer.raw)35 self.state.amount = answer.raw
3637@listen(read_invoice)38defcheck_invoice(self):39 over = self.state.amount -1800040returnf"the invoice is {over} over the contract"414243documents =["inbox/acme-invoice-renewal.md"]44for path in documents:45 desk = Desk()46print(desk.kickoff(inputs={"path": path}))
Terminal
1(env)$ python demo.py
Output
...Total due: 19,800.00...Error executing listener read_invoice: 1 validation error for StateWithIdamount Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='Total due: 19,800.00', input_type=str]...pydantic_core._pydantic_core.ValidationError: 1 validation error for StateWithId
CrewAI draws a box as the agent starts and ends, and ... stands for them. Your agent's words may differ. The agent found the total, but in a sentence. The state's rule from chapter 4 stopped it at the door:
Drawing diagram…
InputAgentResultA sentence where a number belongs
Cutting the number out of the sentence would break the day the agent words it another way.
A Pydantic model says what shape the answer must take, and response_format=Invoice asks the agent for it. answer.pydantic is then an Invoice. Add Field to the import in demo.py:
Python
1from pydantic import BaseModel, ConfigDict, Field
Field(description=...) tells the agent what the field means. Add Invoice to demo.py, before DeskState:
Python
1classInvoice(BaseModel):2 total_due:int= Field(description="The total due, in dollars")
Change read_invoice in demo.py:
Python
1@listen(read_document)2defread_invoice(self):3 reader = Agent(4 role="Invoice reader",5 goal="Copy numbers from invoices exactly",6 backstory="You open the mail at a small company.",7)8 answer = reader.kickoff("What is the total due?\n\n"+ self.state.text, response_format=Invoice)9print(answer.pydantic)10 self.state.amount = answer.pydantic.total_due
Terminal
1(env)$ python demo.py
Output
...total_due=19800...the invoice is 1800 over the contract
19,800 less 18,000 is 1,800 over. CrewAI hands the shape to the model with the question, and Pydantic builds the answer from what comes back:
...total_due=19800...the invoice is 1800 over the contract...total_due=0...the invoice is -18000 over the contract
The agenda has no total, but total_due had to be a whole number. So the agent filled in 0, and the check reported a bill 18,000 below the contract:
Drawing diagram…
InputAgentToolResultA shape that must be filled
Give the shape a way to say there's nothing. int | None takes a whole number or None. Change Invoice and DeskState in demo.py:
Python
1classInvoice(BaseModel):2 total_due:int|None= Field(description="The total due in dollars, or null if there is none")345classDeskState(BaseModel):6 model_config = ConfigDict(validate_assignment=True)78 path:str=""9 text:str=""10 amount:int|None=None
Change check_invoice in demo.py:
Python
1@listen(read_invoice)2defcheck_invoice(self):3if self.state.amount isNone:4return"no total to check"5 over = self.state.amount -180006returnf"the invoice is {over} over the contract"
Terminal
1(env)$ python demo.py
Output
...total_due=19800...the invoice is 1800 over the contract...total_due=None...no total to check
Let's remove the program. The folder, .env and the inbox stay for the next chapter.