How to Build Low-Cost AI Multi-Agent Workflows: The Chief Agent + Isolated Sub-Agent Pattern

    Sharing one conversation history and one memory pool across multiple agents looks convenient at first, but it quickly produces goal drift, priority conflicts, context pollution, and runaway token costs. This guide walks through a more durable design—a Chief Agent that owns decomposition, scheduling, synthesis, and long-term memory, plus stateless Sub-Agents that load only the context their current task needs. It covers pain points and their root causes, role boundaries, memory isolation, input/output schemas, task orchestration, deployment choices, a runnable Python skeleton, token cost control, and security and compliance practices you can actually apply.

    1. Why Multi-Agent Collaboration Breaks Down

    Three problems account for most failures in multi-agent setups, whether you are building an “AI-driven one-person company” or a small team of agents.

    1.1 Mixed memory dilutes strategy

    When several agents share a single long-term memory, each one keeps reasoning on top of the others’ earlier output, and the original objective gradually erodes. A product agent, a growth agent, and a research agent that all read the full history may treat a temporary experiment as the final strategy, which produces conflicting priorities.

    Useful indicators to watch:

    • Goal drift rate: the share of a task that departs from the original objective;
    • Priority conflict count: the number of times two subtasks reach contradictory conclusions in the same task;
    • Memory retrieval hit rate: whether the historical fragments a later task retrieves are relevant to the current task.

    Example log entry:

    1. {
    2. "task_id": "task-20250612-001",
    3. "agent": "growth",
    4. "retrieved_memory": ["memory-001", "memory-007"],
    5. "conflict_flag": true,
    6. "conflict_reason": "Historical goal is inconsistent with the current task"
    7. }

    1.2 Context pollution causes out-of-scope work

    Context pollution happens when a Sub-Agent pulls unrelated material into its reasoning: another agent’s chain of thought, temporary intermediate results, or conclusions that are already stale. The execution path then drifts away from the original intent, and in the worst case the agent makes decisions it was never supposed to make.

    Useful indicators to watch:

    • Pollution rate: the proportion of non-essential fragments in the current task context;
    • Rework rate: the share of tasks that need human correction or full re-execution;
    • Context hit rate: how closely retrieved fragments match the current task objective.

    1.3 Token consumption climbs fast

    If every Sub-Agent loads the entire conversation history, token usage grows quickly with both task count and role count. Multi-turn, multi-step tasks are the worst case, because every subtask re-carries context it does not need.

    Three baseline numbers are worth recording:

    • Tokens per task = input tokens + output tokens + tool-call tokens;
    • Token growth rate = optimized tokens per task / baseline tokens per task;
    • Task success rate, latency, and quality score, to confirm that cost reduction is not quietly degrading results.

    The root cause is not the number of agents. It is the missing separation between a single decision center and fully isolated execution. State consistency is hard to guarantee when every agent holds long-term memory write access.

    2. The Core Logic: Chief Agent + Isolated Sub-Agents

    The architecture splits agents into two classes: the Chief Agent, which decides and remembers, and the Sub-Agents, which execute and return structured results.

    2.1 Chief Agent: the single decision center

    The Chief Agent is responsible for:

    1. Receiving the user instruction;
    2. Classifying the task type and priority;
    3. Decomposing it into executable subtasks;
    4. Dispatching the appropriate Sub-Agents;
    5. Synthesizing the subtask results;
    6. Writing the one long-term memory;
    7. Recording observability metrics and exception logs.

    The critical rule: long-term memory write access must be exclusive. If several agents can write memory, they will act on different versions of it and reach conflicting decisions.

    2.2 Sub-Agent: an isolated execution unit without long-term memory

    Sub-Agents keep no cross-task memory and do not share the full conversation history. Each one receives only what the current task requires:

    • The task goal;
    • Input material;
    • Constraints;
    • A whitelist of callable tools;
    • An output schema;
    • Timeout and retry policy.

    Sub-Agents should return structured JSON so the Chief Agent can parse and merge results:

    1. {
    2. "task_id": "task-001",
    3. "status": "ok",
    4. "result": "Competitor analysis summary completed",
    5. "tool_calls": [],
    6. "confidence": 0.86
    7. }

    2.3 Implementation checklist

    Five design decisions come first.

    Task decomposition granularity. A subtask should be independently completable, produce a verifiable result, stay loosely coupled, finish quickly in a single run, and require no shared history from other agents. If a task genuinely needs several agents’ live reasoning chains, the decomposition is either too coarse or the task is not suitable for full isolation.

    Sub-Agent input and output schemas. A practical input schema:

    1. {
    2. "task_id": "string",
    3. "role": "coding|growth|product|finance|research",
    4. "goal": "string",
    5. "constraints": ["string"],
    6. "allowed_tools": ["string"],
    7. "context_items": ["string"],
    8. "output_schema": "string"
    9. }

    A practical output schema:

    1. {
    2. "task_id": "string",
    3. "status": "ok|partial|error",
    4. "result": "string",
    5. "tool_calls": [],
    6. "error": "string",
    7. "confidence": 0.0
    8. }

    Retries and timeouts. Configure every Sub-Agent with a per-call timeout (for example 30 seconds), a maximum retry count (for example 2), a backoff schedule (1s, 2s, 4s), and a standardized error structure returned on failure rather than a natural-language explanation.

    Memory compression rules. The Chief Agent should not persist full reasoning chains. Instead:

    • Compress to summaries that keep the goal, decision, result, and exception;
    • Index key fragments by storing a summary plus the original document ID, not the full text;
    • Apply a time window, for example 7 or 30 days;
    • Layer permissions, encrypting sensitive memory separately.

    Observability metrics. At minimum, record task success rate, average latency, tokens per task, context pollution rate, manual rework rate, and tool-call success rate.

    2.4 Role capability matrix

    Split roles by business domain and define tool permissions explicitly for each one.

    Role Allowed tools Input fields Output fields Prohibited actions
    Coding Code search, test execution, code generation goal, repo_context, constraints code_patch, test_result Modifying production config, deleting data
    Growth Content generation, channel analysis, experiment logging campaign_goal, audience copy, channel_plan Publishing ads directly, changing budget
    Product Requirement organization, user feedback analysis user_feedback, feature_context prd_summary, priority Shipping features to production
    Finance Report reading, expense classification ledger_id, period expense_summary Transferring funds, changing account permissions
    Research Document retrieval, material summarization research_question, sources findings, citations Accessing unauthorized external data

    The value of isolation is that each Sub-Agent only knows what it needs to know, which reduces both pollution and misoperation.

    3. Cloud or Local Deployment: How to Choose

    Whether cloud deployment makes sense depends on more than cost. Data sensitivity, concurrency, operations capability, and availability requirements all matter.

    Dimension Cloud deployment Local deployment
    Runtime Stable 24/7 operation Depends on local devices being online
    Access Remote access from multiple devices Local network only
    Scaling Containerized elastic scaling Limited by local hardware
    Data privacy Requires encryption and access control configuration Stronger local control
    Ops complexity Needs platform, logging, and monitoring skills Depends on your own operations
    Best fit Long-running, concurrent multi-task workloads Sensitive data, short-term validation

    Deployment checklist:

    1. Data sensitivity: does the workload touch personal, financial, or customer data?
    2. Concurrency: do multiple Sub-Agents need to run at the same time?
    3. Operations capability: do you have containers, logging, monitoring, and alerting?
    4. Budget: can you absorb elastic compute and API call costs?
    5. Availability requirement: is 24/7 availability required?
    6. Compliance requirement: do you need auditing, masking, and data retention policies?

    Choose cloud deployment when the workload needs to run continuously, handle concurrent tasks, and be reachable remotely. Choose local deployment for sensitive data processing, fast prototype validation, or offline environments.

    4. Core Code Example: A Runnable Architecture Skeleton

    The minimal skeleton below depends only on Python 3.10+ and httpx. In real use you would replace the model endpoint, API key, the decomposition function, and the tool implementations.

    1. # requirements: httpx>=0.27
    2. import os
    3. import json
    4. import time
    5. from dataclasses import dataclass
    6. from concurrent.futures import ThreadPoolExecutor
    7. import httpx
    8. MODEL_BASE_URL = os.getenv("MODEL_BASE_URL", "http://localhost:8000")
    9. MODEL_API_KEY = os.getenv("MODEL_API_KEY", "")
    10. class ModelClient:
    11. def __init__(self, base_url, api_key, timeout=30):
    12. self.client = httpx.Client(
    13. base_url=base_url,
    14. headers={"Authorization": f"Bearer {api_key}"},
    15. timeout=timeout
    16. )
    17. def call(self, messages):
    18. resp = self.client.post(
    19. "/chat/completions",
    20. json={
    21. "model": "general",
    22. "messages": messages,
    23. "temperature": 0.2
    24. }
    25. )
    26. resp.raise_for_status()
    27. return resp.json()["choices"][0]["message"]["content"]
    28. @dataclass
    29. class Task:
    30. task_id: str
    31. role: str
    32. goal: str
    33. constraints: list
    34. allowed_tools: list
    35. context_items: list
    36. timeout_s: int = 30
    37. max_retry: int = 2
    38. def build_task_context(task):
    39. # Build task-level context: never pass full history, only the
    40. # fragments the current task needs
    41. return {
    42. "task_id": task.task_id,
    43. "role": task.role,
    44. "goal": task.goal,
    45. "constraints": task.constraints,
    46. "allowed_tools": task.allowed_tools,
    47. "context_items": task.context_items,
    48. "output_schema": {
    49. "status": "ok|partial|error",
    50. "result": "string",
    51. "tool_calls": "array"
    52. }
    53. }
    54. class SubAgent:
    55. def __init__(self, model, system_prompt):
    56. self.model = model
    57. self.system_prompt = system_prompt
    58. self.tools = {}
    59. def execute(self, task):
    60. context = build_task_context(task)
    61. messages = [
    62. {"role": "system", "content": self.system_prompt},
    63. {"role": "user", "content": json.dumps(context, ensure_ascii=False)}
    64. ]
    65. last_error = None
    66. for _ in range(task.max_retry + 1):
    67. try:
    68. raw = self.model.call(messages)
    69. data = json.loads(raw)
    70. return {
    71. "task_id": task.task_id,
    72. "status": data.get("status", "ok"),
    73. "result": data.get("result", ""),
    74. "tool_calls": data.get("tool_calls", []),
    75. "error": data.get("error", "")
    76. }
    77. except Exception as e:
    78. last_error = str(e)
    79. time.sleep(1)
    80. return {
    81. "task_id": task.task_id,
    82. "status": "error",
    83. "result": "",
    84. "tool_calls": [],
    85. "error": last_error
    86. }
    87. def safe_tool_call(agent, call):
    88. name = call.get("name", "")
    89. arguments = call.get("arguments", {})
    90. if name not in agent.tools:
    91. return {"status": "error", "error": f"tool not allowed: {name}"}
    92. try:
    93. return {"status": "ok", "result": agent.tools[name](**arguments)}
    94. except Exception as e:
    95. return {"status": "error", "error": str(e)}
    96. class ChiefAgent:
    97. def __init__(self):
    98. self.memory = []
    99. model = ModelClient(MODEL_BASE_URL, MODEL_API_KEY)
    100. self.agents = {
    101. "coding": SubAgent(model, "You are a coding agent."),
    102. "growth": SubAgent(model, "You are a growth agent."),
    103. "research": SubAgent(model, "You are a research agent.")
    104. }
    105. def decompose(self, user_input):
    106. # In a real project, the Chief Agent calls the model
    107. # to generate the task list
    108. return []
    109. def handle_task(self, user_input):
    110. task_items = self.decompose(user_input)
    111. tasks = [
    112. Task(
    113. task_id=item["task_id"],
    114. role=item["role"],
    115. goal=item["goal"],
    116. constraints=item.get("constraints", []),
    117. allowed_tools=item.get("allowed_tools", []),
    118. context_items=item.get("context_items", [])
    119. )
    120. for item in task_items
    121. if item["role"] in self.agents
    122. ]
    123. results = []
    124. with ThreadPoolExecutor(max_workers=3) as executor:
    125. futures = [
    126. executor.submit(self.agents[task.role].execute, task)
    127. for task in tasks
    128. ]
    129. for future in futures:
    130. results.append(future.result(timeout=120))
    131. final_output = {"results": results}
    132. self.memory.append({
    133. "input": user_input,
    134. "output": final_output
    135. })
    136. return final_output

    The skeleton demonstrates six principles:

    1. Sub-Agents hold no long-term memory;
    2. Each task builds minimal context through build_task_context;
    3. Output is structured JSON;
    4. Retries and timeouts are in place;
    5. The Chief Agent dispatches multiple Sub-Agents through a thread pool;
    6. Tool calls require whitelist validation.

    In production you should also add model call logging, token accounting, task duration, error classification, context hashing, pollution detection, and audit logs.

    5. Token Cost Control and Performance Optimization

    Token optimization is not about shortening a single prompt. It is about the cost structure of the whole task chain. Establish a baseline first, then compare.

    5.1 Minimize context

    Pass only what the current task needs, and shape the context per task type:

    • Coding tasks: code snippets, relevant issues, test requirements;
    • Growth tasks: audience, channels, summaries of past experiments;
    • Research tasks: the question, the source list, summaries;
    • Finance tasks: reporting period, accounts, report fields.

    Never send the full chat history to a Sub-Agent.

    5.2 Constrain output to a schema

    Requiring a fixed schema cuts natural-language padding and makes downstream parsing trivial. Ask for only:

    1. {
    2. "status": "ok",
    3. "result": "...",
    4. "tool_calls": []
    5. }

    5.3 Batch tasks

    Several small, low-risk, mergeable tasks can go into one call—for example, generating five headlines in a single request instead of five model calls. Be careful that batching does not let the tasks contaminate each other.

    5.4 Compress memory

    The Chief Agent should summarize historical memory down to:

    • The original goal;
    • Key decisions;
    • Final results;
    • Exceptions;
    • Necessary reference IDs.

    5.5 Cache and reuse

    Cache answers that repeat, such as the same product description, the same policy summary, the same code template, or the same competitor material. The cache key should include the task type, a digest of the input, and a version number.

    5.6 Cost measurement template

    Metric Baseline After optimization Change
    Input tokens per task
    Output tokens per task
    Total tokens per task
    Task success rate
    Average latency
    Manual rework rate
    Quality score

    In controlled samples, context minimization and structured output usually reduce token consumption noticeably, but the exact reduction must be measured against your own task set, model, prompts, and baseline. Avoid claiming a fixed percentage without a defined measurement method.

    6. Cloud Deployment, Security, and Compliance

    For cloud deployment, a typical component mix looks like this:

    • Container platform: hosts the Chief Agent and Sub-Agent instances with elastic scaling;
    • Object storage: holds agent memory, task logs, and model inputs and outputs;
    • Message queue: schedules Sub-Agent tasks asynchronously and decouples the execution chain;
    • Logging, monitoring, and alerting: tracks token consumption, task duration, error rate, and abnormal states;
    • API gateway and key management: centralizes authentication, rate limiting, and auditing.

    For example, Baidu AI Cloud provides general-purpose capabilities such as containers, object storage, message queues, and logging and monitoring that can be integrated through APIs to reduce self-managed operations overhead. Region availability and specifics vary, so check the relevant official documentation.

    Cloud deployment is not only an availability decision. Security and compliance matter just as much.

    6.1 Object storage access control

    • Apply least-privilege policies;
    • Separate buckets for public read, private read-write, and audit logs;
    • Never make a bucket containing user data publicly accessible;
    • Enable access logging and operation auditing.

    6.2 Encryption policy

    • Use TLS in transit;
    • Enable server-side encryption at rest;
    • Encrypt sensitive fields with KMS or a dedicated key management service;
    • Manage keys separately from business code.

    6.3 Log masking

    Do not log full sensitive values. Phone numbers, email addresses, ID numbers, and payment details should be masked:

    1. {
    2. "user": "138****5678",
    3. "task_id": "task-001",
    4. "status": "ok"
    5. }

    6.4 Memory retention period

    Set a retention period for long-term memory:

    • Normal task memory: 7 or 30 days;
    • Sensitive task memory: a shorter period, or summary only;
    • Audit logs: retained according to compliance requirements;
    • Expired data deleted automatically.

    6.5 Least privilege

    • Give each Sub-Agent its own service account;
    • Authorize tool calls per role;
    • Prohibit Sub-Agents from accessing production databases directly;
    • Require human confirmation for high-risk operations.

    6.6 Sensitive data masking

    Mask data before it enters the model context:

    • Replace personal identifiers;
    • Hide account and payment information;
    • Set access levels for internal material;
    • Classify data before sending it to external model calls.

    7. Summary and Outlook

    The “Chief Agent + isolated Sub-Agent” architecture is not a universal solution, but it usually relieves memory confusion, context pollution, and token cost problems when the following hold:

    • Tasks decompose cleanly;
    • Subtasks are loosely coupled;
    • Each Sub-Agent loads only task-level context;
    • Long-term memory write access stays with the Chief Agent;
    • Timeouts, retries, observability, and auditing are in place.

    If tasks require heavily shared context, long and complex reasoning chains, real-time negotiation between several agents, or strict conversational continuity, full isolation may reduce collaboration efficiency. A hybrid architecture fits better in that case: the Chief Agent still owns core decisions and memory, Sub-Agents handle local execution, and sharing is limited to summaries, structured messages, and controlled context.

    For individual founders, freelancers, and small teams, the value of this pattern is an AI system that is easier to maintain, easier to extend, and easier to keep within budget. As agent frameworks, model services, and observability tooling standardize, “Chief Agent + Sub-Agent” is likely to become a common default pattern for lightweight AI workflows.