3 Ways to Cut Token Costs in Multi-Agent Development

    Multi-agent systems burn through tokens quickly because every agent re-reads upstream output, retries resend full context, and retrieved content often goes unfiltered. This article explains where token consumption comes from in multi-agent workflows and presents three practical optimizations: off-peak asynchronous scheduling with Celery, context pruning with sliding windows and structured task handoffs, and error log compression—with working Python examples for each.

    Why Multi-Agent Development Is So Token-Hungry

    A typical multi-agent pipeline includes planning, coding, and review roles. Each agent pulls upstream output into its own context, so the same material gets billed over and over. Token consumption comes mainly from three sources.

    Context accumulation. The planning agent’s task breakdown and file structure notes get injected into the executor agent’s prompt. The longer the task chain, the larger every subsequent input becomes.

    Error retries. When compilation or tests fail, systems often resend the full stack trace and original code to the model. Every “try, fail, fix” cycle grows the input length.

    Retrieval assembly. After wiring in vector or codebase retrieval, unfiltered recalled chunks let large amounts of irrelevant content into the context.

    Off-Peak Asynchronous Scheduling

    Batch tasks like bulk code generation, test completion, and documentation writing don’t need real-time responses. Put them in a queue and let a scheduler run them during off-peak windows, while interactive tasks stay synchronous.

    The example below assumes peak hours are 5 AM to 11 AM Pacific on weekdays. In practice, the window should follow your provider’s published pricing schedule, so it’s implemented as a configurable setting.

    1. import os
    2. from datetime import datetime
    3. from zoneinfo import ZoneInfo
    4. from celery import Celery
    5. app = Celery("token_optimizer", broker=os.environ["CELERY_BROKER_URL"])
    6. app.conf.task_acks_late = True # Acknowledge only after success, so failed tasks get redelivered
    7. PACIFIC = ZoneInfo("America/Los_Angeles")
    8. PEAK_START_HOUR = 5 # Pacific time
    9. PEAK_END_HOUR = 11
    10. PEAK_WEEKDAYS_ONLY = True
    11. def pacific_now() -> datetime:
    12. return datetime.now(ZoneInfo("UTC")).astimezone(PACIFIC)
    13. def is_peak(now: datetime) -> bool:
    14. if PEAK_WEEKDAYS_ONLY and now.weekday() >= 5:
    15. return False
    16. return PEAK_START_HOUR <= now.hour < PEAK_END_HOUR
    17. def seconds_until_off_peak(now: datetime) -> int:
    18. """Returns seconds until the current peak window ends; 0 if already off-peak."""
    19. if not is_peak(now):
    20. return 0
    21. end = now.replace(hour=PEAK_END_HOUR, minute=0, second=0, microsecond=0)
    22. return int((end - now).total_seconds())
    23. @app.task(bind=True, autoretry_for=(Exception,), max_retries=3,
    24. retry_backoff=True, time_limit=3600)
    25. def execute_heavy_agent_task(self, task_payload: dict):
    26. # Tasks must be idempotent: track state by task_id and avoid duplicate writes on re-execution
    27. ...
    28. def submit_agent_task(task_payload: dict) -> None:
    29. delay = seconds_until_off_peak(pacific_now())
    30. if delay:
    31. execute_heavy_agent_task.apply_async(args=[task_payload], countdown=delay)
    32. print(f"Peak hours detected, deferring task by {delay} seconds.")
    33. else:
    34. execute_heavy_agent_task.delay(task_payload)
    35. print("Task submitted for execution.")

    Three things to note in this code. First, the time is converted to the target timezone before checking the hour, rather than treating UTC time as local time. Second, the delay is computed as “seconds remaining until peak ends.” A fixed 4-hour delay would still land inside the peak window if submitted at 5 AM. Third, the task has a timeout and a retry cap, with exponential backoff between retries.

    Before running, set the CELERY_BROKER_URL environment variable and use Python 3.9 or later (where zoneinfo became available). When using Redis as the broker, delayed tasks longer than visibility_timeout (1 hour by default) may be delivered more than once, so tasks must be idempotent. RabbitMQ is generally a better fit for long-delayed tasks; verify the right choice in your own environment.

    How to Prune Context

    Context pruning comes down to three rules.

    Sliding window with summarization. Keep only the most recent N rounds of full conversation and compress older history into a short summary of a few hundred words.

    Structured task handoffs. Pass structured task specs between agents instead of entire files. Interface signatures, directory structure, and the list of files to modify cost far fewer tokens than full text—and they make it easier for downstream agents to focus.

    Bounded retrieval. Sort retrieval results by relevance and enforce both a result-count cap and a character cap. Drop anything beyond the limit rather than concatenating everything.

    Error log compression is the most direct token saver. The code below keeps only the file, line number, error type, and a short message:

    1. import re
    2. ERROR_LINE = re.compile(
    3. r"^(?P<file>[^\s:]+):(?P<line>\d+)(?::\d+)?:\s*"
    4. r"(?P<kind>\w*(?:Error|error)\w*|E\d{3,4}|TS\d{4})\b[:\s]*(?P<msg>.*)$"
    5. )
    6. def compress_errors(log: str, max_errors: int = 10, max_chars: int = 1500) -> str:
    7. lines = log.splitlines()
    8. picked = []
    9. for line in lines:
    10. m = ERROR_LINE.match(line.strip())
    11. if m:
    12. picked.append(f"{m['file']}:{m['line']} {m['kind']} {m['msg'][:200]}")
    13. if len(picked) >= max_errors:
    14. break
    15. if not picked:
    16. # If the format isn't recognized, keep the head and tail of the log
    17. if len(log) <= max_chars:
    18. return log
    19. return log[:max_chars // 2] + "\n...\n" + log[-max_chars // 2:]
    20. return "\n".join(picked)[:max_chars]

    Combined, these three techniques—scheduling batch work off-peak, trimming what goes into each prompt, and shrinking error payloads before retries—address the main sources of token waste in multi-agent systems without changing what your agents actually do.