Skip to content
/

Many documents at once

Ready for real workChapter 14 of 155 min read

The inbox holds three documents, and the desk reads them one after another. Each one waits for the one before it, though they share nothing. So this chapter answers: how does the desk read many documents at once?


Each document gets its own run, and the runs wait for their agents together:

Drawing diagram…
InputToolResultThree runs, side by side
  • kickoff_async: starts a run that can wait alongside other runs, instead of holding up the program.
  • asyncio.gather: starts several waiting jobs together, and hands back all their results, in the order they were given.

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 needs no model. time.sleep(1) stands in for the agent from chapter 11: a second of waiting, the way a step waits for the model's answer.

Way 1: one document after another#

main runs the desk once for each name in NAMES, and times the lot. Let's save this as demo.py:

demo.py
# demo.py
import time

from crewai.flow.flow import Flow, listen, start
from pydantic import BaseModel, ConfigDict

NAMES = ["acme-saas-agreement.md", "acme-invoice-renewal.md", "team-offsite-agenda.md"]


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

    name: str = ""
    memo: str = ""


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

    @start()
    def review_document(self):
        time.sleep(1)
        self.state.memo = "memo for " + self.state.name

    @listen(review_document)
    def write_report(self):
        return self.state.memo


def main():
    began = time.perf_counter()
    reports = [Desk().kickoff(inputs={"name": name}) for name in NAMES]
    for report in reports:
        print(report)
    print(f"{time.perf_counter() - began:.1f} seconds")


main()
Terminal
(env)$ python demo.py
Output
memo for acme-saas-agreement.mdmemo for acme-invoice-renewal.mdmemo for team-offsite-agenda.md4.0 seconds

Your times will differ a little. Three seconds went on waiting, one after another, and about one more on CrewAI getting ready before the first step. Each run waited for the one before it, though none of them needed its result:

Drawing diagram…
InputResultEach run waits its turn

Way 2: all three at once#

kickoff_async starts a run that waits without holding up the others. CrewAI runs a plain step like review_document in a thread of its own, so three steps can sleep at the same time. review_all starts the three runs, and asyncio.gather waits for them all. Add the import to demo.py:

Python
import asyncio

Add review_all to demo.py, before main:

Python
async def review_all():
    return await asyncio.gather(*(Desk().kickoff_async(inputs={"name": name}) for name in NAMES))

async def marks a function that can wait, and await waits for its result. The * hands the three runs to gather one by one. Change main in demo.py:

Python
def main():
    began = time.perf_counter()
    reports = asyncio.run(review_all())
    for report in reports:
        print(report)
    print(f"{time.perf_counter() - began:.1f} seconds")

asyncio.run starts Python's loop for waiting jobs, and gives back what review_all returns.

Terminal
(env)$ python demo.py
Output
memo for acme-saas-agreement.mdmemo for acme-invoice-renewal.mdmemo for team-offsite-agenda.md2.0 seconds

The same three reports, in the same order, in half the time. The three seconds of waiting became one, because the three steps slept at the same time, each in its own thread. In a probe that ran the loop first, so CrewAI was already ready, gather took 1.0 seconds:

Drawing diagram…
InputToolResultThe runs wait together

One desk for three documents#

Making a Desk() for each name looks wasteful. Let's make one, and use it for all three. Change review_all in demo.py:

Python
async def review_all():
    desk = Desk()
    return await asyncio.gather(*(desk.kickoff_async(inputs={"name": name}) for name in NAMES))
Terminal
(env)$ python demo.py
Output
memo for team-offsite-agenda.mdmemo for team-offsite-agenda.mdmemo for team-offsite-agenda.md2.3 seconds

It was still quick, and every report is the agenda's. One Desk() has one state. Each run put its own name into that state, and the last name written was team-offsite-agenda.md, so all three steps read it:

Drawing diagram…
InputToolResultThree runs, one state

No error says so. With an agent in the step, it would review one document three times, and report on the wrong one twice.

Change review_all in demo.py back:

Python
async def review_all():
    return await asyncio.gather(*(Desk().kickoff_async(inputs={"name": name}) for name in NAMES))

Let's remove the program. .env and the inbox stay for the next chapter.

Terminal
(env)$ rm demo.py

The two ways side by side#

Compare where the time goes:

Drawing diagram…
InputResultWhere the time goes

When documents don't depend on each other, start a flow for each with kickoff_async, and wait for them together with asyncio.gather.

Drawing diagram…
InputResultRun them at once?

What comes next#

The desk now has every part: a router, checks, agents, a person, saved state, and runs side by side:

Drawing diagram…
InputToolResultThe parts so far

What does the whole thing look like?