Skip to content

Recursive agents

A subagent is just a nested invoke: because the agent writes and runs Python (see the Quick start), its code can call invoke again, spawning a child agent. This is how one agent decomposes a task into smaller ones — the resulting parent/child agents form a tree (or forest). Each nested agent gets its own execution scope — a fresh REPL and its own conversation history, separate from its parent’s — while pool budgets and observability hooks are shared across the whole tree. (Concepts defines these terms in one place.)

from jaz import invoke
from jaz.hooks import ReturnType, RecursionLimit
items = ["alpha", "beta", "gamma"]
with RecursionLimit(max_depth=3): # optional cap; recursion is unbounded by default
result = invoke(
ReturnType(list),
task="""
For each item, use invoke to process it.
Combine and return the results.
""",
items=items,
)

Inside its REPL the agent calls invoke directly — it is available as a tool (a plain function the agent can call) bound under that name automatically, so no import or setup is needed.

When deciding whether (and how) to recurse, agents can use these patterns:

  • Simple — no recursion; solve the task directly.
  • Search — try multiple approaches to a task or subtask and pick the best.
  • Extra guidance / tools — build a tailored prompt and pass in the specific tools a nested invoke needs for a subtask.
  • Decompose — break the workflow into subtasks and solve each with a nested invoke.
  • Refinement — inspect a nested agent’s trajectory (the record of the code it wrote and the results it saw), improve its prompt or tools, and redo the task with feedback.
  • Context filter — hand off to a nested invoke with a filtered context and a summary when earlier REPL output is no longer needed.

These are not mutually exclusive — decomposition, search, and extra tooling can be layered together.

Per-level execution limits are hooks. Activating a hook as a with block propagates it to every nested invoke (see the two ways to pass a hook):

from jaz.hooks import IterationLimit, RecursionLimit
with RecursionLimit(max_depth=2), IterationLimit(max_iterations=20):
result = invoke(ReturnType(str), task="Complex task")

To cap total cost across the entire recursion tree, see Budgets & configuration.