Managing Token Costs and Rate Limits in Multi-Agent Programming

    This article explains where token costs accumulate in multi-agent pipelines, how to estimate and control them, and how to handle platform rate limits during peak hours. It covers token calculation formulas, cost tables, off-peak scheduling, retry with exponential backoff, context compression strategies, model tiering, and budget monitoring thresholds. The provided code, parameters, and budget checkpoints can be used as starting points for your own projects.

    Where Token Costs Come From

    1. Context Accumulates with Each Turn

    In a code refactoring workflow, an architecture agent passes a task to a coding agent, and the result is reviewed by a review agent. If the review fails, the task goes back to the coding agent. With every “plan, execute, observe, reflect” cycle, the stored history grows.

    Assume a base context of 10,000 tokens, with each turn adding about 5,000 tokens of execution records, running 8 turns in a row:

    • Without compression, the input at turn k is approximately 10,000 + 5,000k tokens, totaling about 260,000 tokens over 8 turns.
    • If history is compressed into a summary of about 15,000 tokens each turn before passing it in, the total is about 120,000 tokens over 8 turns.

    The total input difference is more than double, and the gap widens with more turns. These numbers only illustrate the trend; actual values depend on the task and the model.

    2. Define Metrics Before Measuring

    The same task can produce very different token counts depending on how you measure. Before measuring, clarify three points:

    • Data source: Prefer the usage field returned by the platform, which gives input and output tokens separately. Do not replace it with word-count estimates.
    • Whether output tokens are included: Output tokens are usually priced higher; counting only input underestimates cost.
    • Turn definition: Record each model call as a call, and a full “plan, execute, observe, reflect” cycle as a turn. State this clearly in reports.

    The table below can track each call, allowing you to aggregate by role and turn:

    Field Meaning Example
    Task ID Unique identifier for a requirement T-0412
    Role Planner, coder, reviewer, or fixer Coder
    Turn Turn number within the task 3
    Input tokens Input amount returned by the platform 18000
    Output tokens Output amount returned by the platform 2200
    Unit price Current input or output unit price Per platform pricing
    Cost Computed from the above Per formula

    Measuring Token Costs

    1. Formula and Variables

    Annual token cost = Daily token usage (in millions) × Unit price (per million tokens) × Working days per year

    Variable Meaning Measurement
    Daily token usage Average tokens consumed per working day In millions; 2 million = 2,000,000 tokens
    Unit price Price per million tokens Use current platform pricing; if input and output differ, calculate separately
    Working days per year Number of days with actual model calls Usually 250

    2. Example and Unit Check

    Assume a daily usage of 2 million tokens, a unit price of 10 yuan per million tokens (example value, not real pricing), and 250 working days per year:

    Annual token cost = 2 × 10 × 250 = 5,000 yuan

    If input and output unit prices differ, calculate separately:

    Annual cost = (Daily input tokens in millions × Input unit price + Daily output tokens in millions × Output unit price) × 250

    Unit check notes:

    • Usage is already expressed in millions of tokens; do not multiply or divide by 1,000.
    • If the unit price is given per thousand tokens, convert it to per million tokens first; otherwise the result will differ by 1,000×.

    When comparing to labor costs, include engineering hours, otherwise the conclusion will favor automation.

    3. Review Frequency

    Model prices and usage will change. Review the formula variables monthly using actual bills, and check consumption trends weekly. Prices and rate limit policies may change at any time; revisit your budget weekly. Compression and model tiering will also change usage, so recalculate after each adjustment.

    Why Rate Limits Appear During Peak Hours

    1. Common Rate Limit Forms

    • RPM (Requests Per Minute): requests allowed per minute.
    • TPM (Tokens Per Minute): tokens processed per minute. This usually hits first when agents run in parallel.
    • Concurrency limit: maximum simultaneous requests.
    • Daily or monthly quota: total token or cost cap over a window.
    • Queueing: the platform queues requests and processes them later, increasing latency.

    During peak hours, many users make requests simultaneously, so the platform tightens these limits. The same code may perform very differently at 2 AM versus in the afternoon.

    2. What Triggers 429 and How to Respond

    When a limit is exceeded, the API usually returns HTTP 429 (Too Many Requests). Some platforms include a Retry-After header indicating suggested seconds to wait.

    The only principle is to comply with the platform’s terms of service and rate limit rules. Do not circumvent limits by switching accounts, rotating keys, or spoofing request sources. These practices violate most platform terms and may lead to account suspension.

    Off-Peak Scheduling and Retry

    1. Off-Peak Scheduling Steps

    1. Prioritize tasks. Tasks that block the main flow (review, fix) run first; batch refactoring, documentation, and test generation can be deferred to off-peak hours.
    2. Calculate send rate from TPM. For example, if TPM is 300,000 and each call consumes 20,000 tokens on average, you can make at most 300,000 ÷ 20,000 = 15 calls per minute. Keep 20% headroom, so send 12 calls per minute.
    3. Schedule batch tasks during low-load periods and write results to a queue to avoid concentrated retries during peak hours.

    2. Retry Strategy

    When you encounter 429 or 5xx errors, use exponential backoff with jitter, set a maximum retry count, and a backoff cap. Errors like 400, 401, and 403 indicate the request itself is invalid; retrying them is useless, so report them immediately.

    1. import random
    2. import time
    3. MAX_RETRIES = 5 # Maximum retries
    4. BASE_DELAY = 2 # First wait in seconds
    5. MAX_DELAY = 60 # Maximum single wait in seconds
    6. RETRYABLE = {429, 500, 502, 503, 504}
    7. def call_with_backoff(send_request, downgrade_model, enqueue_for_later):
    8. for attempt in range(MAX_RETRIES + 1):
    9. resp = send_request()
    10. if resp.status_code not in RETRYABLE:
    11. return resp # Success, or a non-retryable error
    12. if attempt == MAX_RETRIES:
    13. break
    14. delay = min(MAX_DELAY, BASE_DELAY * 2 ** attempt)
    15. retry_after = resp.headers.get("Retry-After") # Assume seconds
    16. if retry_after:
    17. delay = max(delay, float(retry_after))
    18. time.sleep(delay + random.uniform(0, 1))
    19. # After exceeding retry limit: degrade first, then enqueue
    20. resp = downgrade_model()
    21. if resp is not None and resp.status_code == 200:
    22. return resp
    23. enqueue_for_later()
    24. return None

    With the above parameters, backoff times are 2, 4, 8, 16, 32 seconds, then fixed at 60 seconds. Tasks that exceed the limit go to a pending queue and notify the responsible person. Do not retry indefinitely; it will consume quota continuously and make it harder for other tasks in the same time window to complete.

    Context Compression and Model Tiering

    1. Compression Method Comparison

    Method Input per turn (example) Information loss risk Use case
    No compression Grows linearly, ~260k over 8 turns Low Few turns, short tasks
    Summarization ~15k, ~120k over 8 turns Medium; summaries may miss constraints Long flows where conclusions matter more than process
    Retrieval-based Only relevant snippets, depends on retrieval Medium to high; possible misses Large codebase where original text must be referenced

    2. Compression Execution Steps

    1. Each turn passes only necessary fields: task goal, interface constraints, open issues, and the most recent failure reason. Full logs are stored for later retrieval.
    2. Set trigger thresholds. For example, if a single input exceeds 80,000 tokens, or three turns have passed since the last summary, generate a summary targeting about 15,000 tokens.
    3. Keep hard constraints in a fixed block, e.g., “Do not modify the public interface” or “Must be compatible with Python 3.8.” These clauses are preserved verbatim during summarization and are not rewritten by the model.
    4. Build an index for code and logs. When a coding agent needs a function, retrieve it by name instead of passing the entire file.

    3. Model Tiering

    Task type Recommended tier Reasoning
    Log extraction, format conversion, field normalization Small model Rules are clear, low cost of errors
    Routine code generation, unit tests Mid-tier model Balanced quality and cost
    Architecture decisions, complex code review High-end model High cost of mistakes

    The following parameters are starting points; adjust them for your tasks:

    • max_tokens: Set per task. For normal code generation, 4096 is typical; for summary, 2048. Prevents runaway output.
    • temperature: For code generation, around 0.2 to reduce randomness and rework.
    • Context cap: If any agent’s input exceeds 80,000 tokens, compress before sending.

    Budget Monitoring

    1. Metrics and Alert Thresholds

    Record task ID, role, input tokens, output tokens, and cost for every call. Assuming a daily budget of 2 million tokens and 10 yuan per million tokens, a daily budget is about 20 yuan. Set three thresholds:

    • At 70% (1.4M tokens): Send a reminder, check which role consumes the most.
    • At 90% (1.8M tokens): Pause low-priority tasks, keep only review and fix.
    • At 100% (2M tokens): Stop new tasks, wait until the next day or manual confirmation.

    Two more signals are worth monitoring. Alert if a single task’s token count exceeds 3× the historical median, which often means loop calls or runaway context. If more than 5% of requests in an hour return 429, reduce concurrency.

    2. Weekly Review Checklist

    • Check the latest platform pricing and rate limit documentation; update unit prices and TPM/RPM limits.
    • Calculate token share by role to find the largest cost center.
    • Count retries and 429 ratios to assess concurrency settings.
    • Spot-check tasks after compression to confirm hard constraints are intact, and measure rework rate.
    • Adjust daily budget and alert thresholds based on actual usage.

    Common Mistakes

    • All agents share one oversized context, paying for irrelevant history.
    • No budget alerts; cost overruns only noticed after the fact.
    • Using the strongest model for all steps, paying high prices for easy tasks.
    • Violent retries on rate limits, without backoff, caps, or degradation.
    • After compression, key constraints are not verified, causing later turns to violate original requirements.