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.
import osfrom datetime import datetimefrom zoneinfo import ZoneInfofrom celery import Celeryapp = Celery("token_optimizer", broker=os.environ["CELERY_BROKER_URL"])app.conf.task_acks_late = True # Acknowledge only after success, so failed tasks get redeliveredPACIFIC = ZoneInfo("America/Los_Angeles")PEAK_START_HOUR = 5 # Pacific timePEAK_END_HOUR = 11PEAK_WEEKDAYS_ONLY = Truedef pacific_now() -> datetime:return datetime.now(ZoneInfo("UTC")).astimezone(PACIFIC)def is_peak(now: datetime) -> bool:if PEAK_WEEKDAYS_ONLY and now.weekday() >= 5:return Falsereturn PEAK_START_HOUR <= now.hour < PEAK_END_HOURdef seconds_until_off_peak(now: datetime) -> int:"""Returns seconds until the current peak window ends; 0 if already off-peak."""if not is_peak(now):return 0end = now.replace(hour=PEAK_END_HOUR, minute=0, second=0, microsecond=0)return int((end - now).total_seconds())@app.task(bind=True, autoretry_for=(Exception,), max_retries=3,retry_backoff=True, time_limit=3600)def execute_heavy_agent_task(self, task_payload: dict):# Tasks must be idempotent: track state by task_id and avoid duplicate writes on re-execution...def submit_agent_task(task_payload: dict) -> None:delay = seconds_until_off_peak(pacific_now())if delay:execute_heavy_agent_task.apply_async(args=[task_payload], countdown=delay)print(f"Peak hours detected, deferring task by {delay} seconds.")else:execute_heavy_agent_task.delay(task_payload)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:
import reERROR_LINE = re.compile(r"^(?P<file>[^\s:]+):(?P<line>\d+)(?::\d+)?:\s*"r"(?P<kind>\w*(?:Error|error)\w*|E\d{3,4}|TS\d{4})\b[:\s]*(?P<msg>.*)$")def compress_errors(log: str, max_errors: int = 10, max_chars: int = 1500) -> str:lines = log.splitlines()picked = []for line in lines:m = ERROR_LINE.match(line.strip())if m:picked.append(f"{m['file']}:{m['line']} {m['kind']} {m['msg'][:200]}")if len(picked) >= max_errors:breakif not picked:# If the format isn't recognized, keep the head and tail of the logif len(log) <= max_chars:return logreturn log[:max_chars // 2] + "\n...\n" + log[-max_chars // 2:]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.
