Multi-Agent Hierarchical Scheduling: An Engineering Approach to Reducing AI Team Costs

    As cross-regional AI development teams scale, relying on a single general-purpose large language model for all tasks leads to rising expenses and inefficiencies. This article explores a multi-agent hierarchical scheduling architecture designed to optimize costs. By dividing systems into scheduling, execution, and shared workspace layers, teams can leverage task-tiered routing, context trimming, caching, parallel processing, and workspace isolation. The guide details role division, cost reduction mechanisms, implementation steps, failure handling, and cost accounting methods to help engineering teams build efficient and budget-conscious AI workflows.

    1. Why a Single-Model Approach Becomes Expensive

    In the early stages, many cross-regional AI development teams adopt a single general-purpose large language model to handle all tasks. Requirements analysis, data retrieval, data processing, code generation, and report writing are all handed over to the same model. While this approach is quick to get started with, costs rise significantly as scale increases. There are four main reasons for this:

    First, task and model capability mismatch. Lightweight tasks like summarization, format conversion, and field extraction can typically be handled by low-cost models, but they are often routed to expensive general-purpose models in practice. Conversely, complex reasoning and engineering implementation require stronger capabilities, making it difficult for a single-model approach to simultaneously satisfy both cost and performance requirements.

    Second, repeated context billing. In multi-turn collaborations, background information is needed at every step: scheduling, retrieval, analysis, and coding. If every call includes the complete conversation history and all documents, input tokens will increase rapidly with the length of the task chain.

    Third, serial processing slows progress. When a single model processes subtasks sequentially, cross-timezone teams cannot split the work to advance in parallel. Wait times and retries after failures accumulate, driving up total costs.

    Fourth, lack of budget tags. If call records are not tagged by project, role, and task type, teams only see the total bill. They cannot determine which step is the most expensive or identify optimization priorities.

    Multi-agent hierarchical scheduling is an engineering solution designed to address these four issues. It reorganizes the relationships between tasks, models, context, and workspaces, ensuring that each call uses only the capabilities and information necessary to complete the task.

    2. Architecture Overview: Scheduling Layer, Execution Layer, and Shared Workspace

    A three-tier structure is recommended:

    1. Scheduling Layer: Managed by a general-purpose agent with long-context and strong planning capabilities. It is responsible for requirement clarification, task decomposition, dependency analysis, parallel allocation, result aggregation, and quality gates.
    2. Execution Layer: Composed of multiple specialized agents responsible for reasoning and computation, retrieval and scraping, multimodal parsing, and code implementation. Each execution agent only receives the inputs listed in its task ticket and outputs structured deliverables.
    3. Shared Workspace: Includes shared indexes, artifact directories, logs, and metadata. The scheduling layer maintains task state, while the execution layer reads inputs and writes outputs on demand.

    This structure allows the scheduling layer to maintain a global view while the execution layer pulls only the minimum necessary inputs. The cost reduction comes from five mechanisms: task-tiered routing, context trimming, cache reuse, parallel and timeout control, and resource recovery enabled by isolated workspaces.

    3. Role Division and Model Selection

    Roles should be divided based on task capabilities rather than specific products. The table below outlines general roles. The cost levels are relative references and should be calibrated using the actual price table of the models used.

    Role Primary Responsibilities Typical Input Output Artifact Relative Cost Level
    Scheduler Agent Decompose tasks, dispatch subtasks, aggregate results, quality gates Requirement descriptions, task status summaries Structured task tickets High (long context)
    Reasoning Agent Metric calculation, comparative analysis, rule derivation Data fragment references Computation result tables Medium to High
    Retrieval Agent Data collection, fact-checking, source organization Search terms, source scope Source lists and summaries Low to Medium
    Multimodal Agent Parsing receipts, screenshots, scans, charts Image file references Structured fields Medium
    Coder Agent Script writing, refactoring, test completion Code file paths, API specs Patches and test results Medium to High

    The number of roles does not have to be fixed at five. High-frequency tasks with clear boundaries should be independent roles. Low-frequency, long-tail tasks can be handled directly by the scheduling layer or merged into similar roles. This keeps routing rules simple and prevents coordination costs from rising due to an excess of roles.

    4. Five Mechanisms for Cost Reduction

    1. Task-Tiered Routing

    When decomposing tasks, the scheduling layer should annotate the complexity of each subtask. The criteria below are examples; thresholds should be adjusted based on your price table and quality evaluation results.

    • Lightweight tasks: Estimated input under 2,000 tokens, no tool calls required, low retry cost on failure. Route to low-cost models.
    • Standard tasks: Estimated input between 2,000 and 16,000 tokens, requires one tool call or simple reasoning. Route to balanced models.
    • Complex tasks: Estimated input over 16,000 tokens, or involves multi-step reasoning, code modifications, or high-risk conclusions. Route to strong reasoning or strong coding models.

    After the same subtask fails twice, it should be upgraded to a higher-tier model. Retries should not increase indefinitely, or the cost saved by routing will be offset by repeated calls.

    2. Context Trimming and Reference Passing

    Instead of copying full texts between execution agents, pass artifact references. References can include document chunk IDs, table row numbers, code file paths, and retrieval result summary IDs. Below is an example of a reference object:

    1. {
    2. "ref_type": "doc_chunk",
    3. "doc_id": "contract_2026_017",
    4. "chunk_id": "c-0042",
    5. "doc_version": "v3",
    6. "summary_id": "s-0042"
    7. }

    The scheduling layer only retains task status and key conclusions. When the execution layer receives a reference, it reads the corresponding fragment on demand. This reduces repeated billing and facilitates auditing, as every conclusion can be traced back to a specific fragment.

    3. Cache Keys, Versioning, and Expiration Strategies

    Caching can significantly reduce repeated calls, but stale results can cause errors. It is recommended to design caching as follows:

    • Cache Key: A hash generated from the task type, input content hash, prompt version, model version, and key parameters (e.g., temperature). Any change in these will generate a new key.
    • Expiration Time: Retrieval results should be set to 24 hours. Format conversion results can be set to 30 days. Caches related to code snippets should be bound to the commit hash of the code repository, expiring immediately when a commit changes.
    • Invalidation Triggers: Clear all caches with corresponding prefixes when source data updates, prompts update, or models are replaced.
    • Stale Result Troubleshooting: Every cached artifact should record the version info at generation time. Sample periodically, regenerate using the current version, and compare results. If the difference exceeds a preset threshold, clear the cache for that task type and record the reason.

    4. Batch Processing and Parallel Control

    Batch summarization, batch field extraction, and batch calculations should merge requests or run in parallel batches. The maximum concurrency should be set based on your budget and the service provider’s rate limits. Every call must have a timeout. Use exponential backoff for retries after failure, with a maximum of 3 retries. If exceeded, enter a degraded path or hand over to manual processing.

    5. Isolated Workspaces and Resource Recovery

    Each execution agent uses an independent working directory, while the shared area is read-only or written to with specific permissions. After a task is completed, the system recovers the temporary directories and runtime environments. This avoids hidden costs caused by repeatedly creating environments and installing dependencies.

    5. Implementation Steps

    Step 1: Unify Credentials and Budgets. Place the API credentials for various model services into a unified secret management system, isolated by project and environment. Read credentials via environment variables or a secret service; do not hardcode them in code or logs. Set daily and weekly budgets for each project and configure alerts.

    Step 2: Register Roles and Capability Tags. Define a name, model identifier, capability scope, input/output format, max concurrency, timeout, and cost level for each agent.

    Step 3: Establish the Shared Workspace. Divide it into a shared index area, artifact area, log area, and temporary area. Assign an independent working directory to each execution agent, granting only the minimum permissions required to complete the task.

    Step 4: Define Task Protocols. Each subtask must include a task ID, goal, input references, output format, acceptance criteria, and deadline. The scheduling layer only accepts structured results, not free-text deliverables, to reduce repeated clarifications.

    Step 5: Implement the Scheduler. The scheduler is responsible for decomposition, routing, parallelism, retries, aggregation, and manual escalation. The configuration below is a structural illustration only and cannot be run directly. Before actual deployment, you need to supply model identifiers, credential sources, message queue addresses, timeout parameters, file permissions, and dependency versions.

    1. # Structural illustration only, not directly runnable
    2. orchestrator:
    3. role: scheduler
    4. model: <long_context_model_id> # Read from secret service
    5. max_parallel: 4 # Adjust based on budget and rate limits
    6. timeout_seconds: 120
    7. workspace: /workspace/shared # Must set read/write permissions
    8. workers:
    9. - name: reasoner
    10. model: <reasoning_model_id>
    11. scope: ["Data reasoning", "Batch calculation"]
    12. timeout_seconds: 300
    13. - name: retriever
    14. model: <tool_calling_model_id>
    15. scope: ["Retrieval", "Scraping", "Summarization"]
    16. timeout_seconds: 60
    17. - name: multimodal
    18. model: <multimodal_model_id>
    19. scope: ["Image parsing", "Layout recognition"]
    20. timeout_seconds: 180
    21. - name: coder
    22. model: <code_model_id>
    23. scope: ["Code generation", "Script writing", "Test completion"]
    24. timeout_seconds: 300
    25. routing:
    26. - if task.type == "data_analysis": route("reasoner")
    27. - if task.type == "search": route("retriever")
    28. - if task.type == "image_parse": route("multimodal")
    29. - if task.type == "coding": route("coder")
    30. - else: route("scheduler")
    31. memory:
    32. shared_index: <vector_index_name>
    33. artifact_dir: /workspace/artifacts # Partition by sensitivity level
    34. isolation:
    35. per_agent_workdir: true
    36. shared_read_only: true

    Step 6: Write the Scheduling Prompt. The scheduler agent’s prompt needs to clarify three things: it is only responsible for decomposition and aggregation, not replacing the execution layer for subtasks; it must output structured task tickets; if a task is uncertain, it should hand it to the retrieval role for verification before dispatch. Below is a prompt example, including constraints and triggers for manual review.

    1. You are the scheduler agent. Responsibilities: Decompose tasks, assign subtasks, aggregate results, execute quality gates.
    2. The output must be in the following JSON format:
    3. {
    4. "task_id": "...",
    5. "subtasks": [
    6. {
    7. "role": "reasoner|retriever|multimodal|coder",
    8. "complexity": "light|standard|complex",
    9. "goal": "...",
    10. "input_refs": ["..."],
    11. "output_format": "...",
    12. "acceptance": "...",
    13. "deadline": "..."
    14. }
    15. ]
    16. }
    17. Constraints:
    18. 1. Do not execute subtasks yourself; delegate all substantive work to the execution layer.
    19. 2. Do not copy the full context to the execution layer; prioritize passing references.
    20. 3. Mark for manual review if any of the following occur: involves money, compliance, or personal sensitive information; two execution results contradict each other; the same subtask fails twice.

    Step 7: Monitoring and Iteration. Log the role, task type, input/output token count, duration, cache hit status, retry count, and failure reason for every call. Review weekly by project dimension, and adjust routing thresholds and cache expiration times accordingly.

    6. Failure Handling and Quality Gates

    Multi-agent systems should assume that the execution layer will fail. The scheduling layer needs to set timeout retries, degraded routing, result validation, and manual escalation.

    When retrieval fails, you can degrade to a local document library. However, this degraded path has clear boundaries. It only applies to authorized, desensitized public data or internal non-sensitive data. Read permissions for the local document library must be set per project. Data with sensitive tags must not be copied from original storage to local copies, nor should degradation bypass existing access audits.

    When code execution fails, first let the coder agent self-check and regenerate once. If it still fails, hand it over to manual review.

    Quality gates include the following checks:

    • Format Validation: Whether the artifact meets the output format specified in the task ticket.
    • Source Traceability: Whether every conclusion can be mapped to a specific reference.
    • Key Number Review: Amounts, percentages, and thresholds must be cross-checked by a second role or a human.
    • Sensitive Information Desensitization: Outputs must not contain ID numbers, phone numbers, account numbers, or similar fields.

    7. Cost Accounting and Weekly Review

    To evaluate the effectiveness of cost reduction, accounting must be done using consistent metrics. The core formulas are as follows:

    • Single Call Cost = Input Token Count × Input Unit Price + Output Token Count × Output Unit Price + Tool Call Fees
    • Weekly Cost = Sum of Single Call Costs for all calls, aggregated by project, role, and task type
    • Cache Savings = Cache Hit Count × Average Cost of Corresponding Missed Calls
    • Reduction Rate = (Baseline Weekly Cost − Post-Transformation Weekly Cost) ÷ Baseline Weekly Cost

    It is recommended to collect at least two weeks of baseline data before enabling hierarchical scheduling. After the transformation, compare using the same statistical method. During weekly reviews, record the fields in the table below.

    Field Description
    Project, Role, Task Type Used to locate cost-intensive steps
    Call Count Weekly call volume for each role
    Input Token, Output Token Distinguishes the impact of context length vs. generation length
    Cache Hit Rate Hit count divided by total request count
    Retry Count, Failure Reason Determines if the retry strategy is reasonable
    Price Version Ensures consistent comparison when prices change
    Weekly Cost Aggregated actual amount

    Budget thresholds can be set to two