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:
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:
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:
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:
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:
Add review_all to demo.py, before main:
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:
asyncio.run starts Python's loop for waiting jobs, and gives back what review_all returns.
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:
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:
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:
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:
Let's remove the program. .env and the inbox stay for the next chapter.
The two ways side by side#
Compare where 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.
What comes next#
The desk now has every part: a router, checks, agents, a person, saved state, and runs side by side:
What does the whole thing look like?