For Each¶
The For Each block executes a single block sequence several times.
Each iteration of the sub-sequence gets its own independent scratchpad.
The sub-sequence can be made of several blocks. The same block transition logic occurs within the sub-sequence as within the “main” sequence. The sub-sequence can even be nested.
The For each block takes a CEL expression, that must resolve to a list, and that drives the iteration. For each value in the list, the value will be copied in a new CEL variable, and the iteration runs.
The Parallel block terminates when all iterations have terminated.
Example use case¶
Imagine an agent that need to fetch news articles and summarize them. You want the summary to run for each article.
A first block in the Agent flow will fetch the news articles, and store in the state a list of the URLs. So for example you will have, in the state, the variable urls, containing ["url1", "url2", "url3"]
You then use a for-each block, with expression state.urls, and with target block a Core Loop with a web scraping tool.
The expression resolves to a list of 2 items, so the Core Loop block will be called twice.
You configure the For Each block with the_url as the “Input variable name”. This means that for each iteration, there will be a variable the_url available for CEL templating, containing the URL for this particular iteration.
You can then, for example, in the Core Loop block, use the following settings:
Pass History: no
Tool: the web scraping tool
Instructions:
Fetch and summarize the article at {{the_url}}
Output¶
Once a for each block completes, it’s possible to grab the text output of each iteration, and to create a key in the state of scratchpad, that will contain a list of the outputs of each individual iteration
Cautions¶
Inherently, the For Each block is not interactive. If you are using a Core Loop block within a For Each block, it will not be possible to resume from it. When the Core Loop block within the For Each block terminates, control will move to the block after For Each.
Be very careful about writing to the state from a For Each block iteration, as several iterations may run in parallel. You should usually only write to the Scratchpad (there is one separate scratchpad per iteration)