Skip to content
/

One agent in a step

Agents as stepsChapter 8 of 156 min read

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.

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

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:

.env
# .env

MODEL=<provider>/<model>
<PROVIDER>_API_KEY=<your key>

Download the invoice, and a document that isn't one:

Terminal
(env)$ mkdir inbox
(env)$ curl -o inbox/acme-invoice-renewal.md https://textview.ai/learn-files/agent-workflows-with-crewai-flow/acme-invoice-renewal.md
(env)$ curl -o inbox/team-offsite-agenda.md https://textview.ai/learn-files/agent-workflows-with-crewai-flow/team-offsite-agenda.md

The invoice asks for 19,800 dollars, and the contract's price, 18,000, stays written in for now.

Way 1: ask for the total in words#

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
# demo.py
from crewai import Agent
from crewai.flow.flow import Flow, listen, start
from dotenv import load_dotenv
from pydantic import BaseModel, ConfigDict

load_dotenv()


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

    path: str = ""
    text: str = ""
    amount: int = 0


class Desk(Flow[DeskState]):
    suppress_flow_events = True

    @start()
    def read_document(self):
        with open(self.state.path) as file:
            self.state.text = file.read()

    @listen(read_document)
    def read_invoice(self):
        reader = Agent(
            role="Invoice reader",
            goal="Copy numbers from invoices exactly",
            backstory="You open the mail at a small company.",
        )
        answer = reader.kickoff("What is the total due?\n\n" + self.state.text)
        print(answer.raw)
        self.state.amount = answer.raw

    @listen(read_invoice)
    def check_invoice(self):
        over = self.state.amount - 18000
        return f"the invoice is {over} over the contract"


documents = ["inbox/acme-invoice-renewal.md"]
for path in documents:
    desk = Desk()
    print(desk.kickoff(inputs={"path": path}))
Terminal
(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.

Way 2: ask for a typed answer#

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
from pydantic import BaseModel, ConfigDict, Field

Field(description=...) tells the agent what the field means. Add Invoice to demo.py, before DeskState:

Python
class Invoice(BaseModel):
    total_due: int = Field(description="The total due, in dollars")

Change read_invoice in demo.py:

Python
    @listen(read_document)
    def read_invoice(self):
        reader = Agent(
            role="Invoice reader",
            goal="Copy numbers from invoices exactly",
            backstory="You open the mail at a small company.",
        )
        answer = reader.kickoff("What is the total due?\n\n" + self.state.text, response_format=Invoice)
        print(answer.pydantic)
        self.state.amount = answer.pydantic.total_due
Terminal
(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:

Drawing diagram…
InputAgentToolResultHow a typed answer is made

A document with no total#

Let's give the desk the agenda as well. Change documents in demo.py:

Python
documents = ["inbox/acme-invoice-renewal.md", "inbox/team-offsite-agenda.md"]
Terminal
(env)$ python demo.py
Output
...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
class Invoice(BaseModel):
    total_due: int | None = Field(description="The total due in dollars, or null if there is none")


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

    path: str = ""
    text: str = ""
    amount: int | None = None

Change check_invoice in demo.py:

Python
    @listen(read_invoice)
    def check_invoice(self):
        if self.state.amount is None:
            return "no total to check"
        over = self.state.amount - 18000
        return f"the invoice is {over} over the contract"
Terminal
(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.

Terminal
(env)$ rm demo.py

The two ways side by side#

Compare what reaches the state:

Drawing diagram…
InputResultWhat the step puts in the state

When a later step uses what an agent found, ask for a typed answer, and let each field say when there's nothing to find.

Drawing diagram…
InputResultanswer.raw or a typed answer?

What comes next#

One agent gives one answer. The contract's review needs two: one agent writes a memo, and another checks every date in it against the contract:

Drawing diagram…
InputAgentResultA job for two agents

So how do two agents work together inside one step?