Skip to content

Run agents concurrently

Each run of a task has its own sandbox, so agents run side by side, each on its own clone, without seeing each other's files, network rules or keys. Runs given the same host directory as a read-write workspace or mount share it, and agents served by one subscription of the daemon share its account. This page gives the same issue to two agents, each on its own clone, and tells which one passes the tests, its patch in hand.

docs_src/agents/several_agents.py
import asyncio
import sys
from pathlib import Path
from typing import Annotated

from pydantic import BaseModel

import fastsandbox
from fastsandbox import Context, FastSandbox, WorkspaceDir

app = FastSandbox("contest", max_concurrency=2)

Clone = Annotated[Path, WorkspaceDir(clone=True)]


class Attempt(BaseModel):
    agent: str
    passed: bool
    patch: str


async def attempt(ctx: Context, workdir: str, issue: str, command: str) -> Attempt:
    """Has the agent of the task fix the issue on its clone, then runs the tests."""
    head = await ctx.sandbox.exec(["git", "rev-parse", "HEAD"], working_dir=workdir, check=True)
    await ctx.agent.prompt(f"{issue}\n\nFix it and commit the fix.", working_dir=workdir)
    tests = await ctx.sandbox.exec(command, working_dir=workdir)
    patch = await ctx.sandbox.exec(
        ["git", "format-patch", "--stdout", f"{head.stdout.strip()}..HEAD"],
        working_dir=workdir,
        check=True,
    )
    return Attempt(agent=ctx.agent.name, passed=tests.ok, patch=patch.stdout)


@app.agent("claude", timeout="20m")
async def fix_with_claude(
    ctx: Context, repo: Clone, issue: str, command: str = "make test"
) -> Attempt:
    """Has Claude Code fix an issue."""
    return await attempt(ctx, str(repo.resolve()), issue, command)


@app.agent("codex", timeout="20m")
async def fix_with_codex(
    ctx: Context, repo: Clone, issue: str, command: str = "make test"
) -> Attempt:
    """Has Codex fix the same issue."""
    return await attempt(ctx, str(repo.resolve()), issue, command)


async def main(repo: str, issue: str) -> None:
    async with app:  # One client for every run.
        attempts = await asyncio.gather(
            fix_with_claude(repo=repo, issue=issue),
            fix_with_codex(repo=repo, issue=issue),
        )
    for result in attempts:
        print(f"{result.agent}: {'passed' if result.passed else 'failed'}")


if __name__ == "__main__":
    fastsandbox.run(main(sys.argv[1], sys.argv[2]))
  • Lines 22 to 32: the work, written once: the agent of the task fixes the issue on its clone and commits, the tests decide, and the commits leave as a patch. ctx.agent.name says which agent did it.
  • Lines 35 and 43: one task per agent, Claude Code and Codex, on the same inputs. A third agent is three more lines.
  • Line 11: max_concurrency=2 bounds how many runs of the application hold a sandbox at once; the others wait for a free slot before they create theirs.
  • Lines 52 to 56: async with app: starts the application once, so that the runs share one client; asyncio.gather runs both tasks at once, and returns their results in order.

Run it with the key of each agent in the environment, or the credential the daemon holds for it: with a Claude subscription, Claude Code needs no ANTHROPIC_API_KEY (see the quickstart):

$ export ANTHROPIC_API_KEY=sk-ant-... OPENAI_API_KEY=sk-...
$ python docs_src/agents/several_agents.py . "the parser drops the last line"
claude: passed
codex: failed

The script prints which attempt passed; each Attempt also holds its patch, for the program to keep the one that passes, or to apply it with git am as Get a patch does.

Many runs of one agent

The same pattern runs one agent on many inputs, a review of each repository of a list for instance: await asyncio.gather(*(review(repo=repo) for repo in repos)). Each run gets its own sandbox and its own clone; max_concurrency on the application, or on the task with @app.agent(..., max_concurrency=4), keeps the machine from running them all at once.

When one fails

asyncio.gather raises the first error of a run; when the program then ends, as main does under fastsandbox.run, asyncio.run cancels the runs still going, which removes their sandboxes. With return_exceptions=True, it returns the errors in place of the results instead, so that one failed agent does not hide the work of the others. Each sandbox is deleted at the end of its run, on an error or a cancellation too (see Running tasks).