Building a Multi-Agent Collaboration System with LLMs: Architecture and Implementation
This article explains why single-conversation LLM calls struggle with long, multi-stage workflows and how to build a multi-agent system that decomposes work across specialized agents. It covers the overall architecture, role and prompt design, context isolation, message passing, task orchestration, tool execution, a full competitor price-monitoring case study, and practical guidance on model selection, reliability, cost control, observability, and phased rollout.
Building a Multi-Agent Collaboration System with LLMs: Architecture and Implementation
1. Why Multi-Agent Systems Are Needed
A single conversational model call works well for short, question-and-answer tasks such as answering a question, writing a code snippet, or summarizing a document. Real engineering scenarios, however, often involve long workflows. A request to “build a competitor price-monitoring dashboard” includes market research, product design, architecture design, coding, testing, deployment, and delivery. Each stage has its own inputs, outputs, and specialized knowledge requirements.
Packing every stage into one conversation context exposes three typical problems:
- Context bloat leads to forgetting: The longer the task chain and the more historical messages there are, the more the model’s ability to follow early constraints degrades.
- Mixed responsibilities reduce quality: Asking the same “role” to do research and write code produces worse output than having specialized agents focus on single responsibilities.
- No parallelism or autonomy: A single agent executes serially, cannot fully use available compute, and cannot support unattended continuous operation.
The core idea of a multi-agent system is to split a complex task into multiple agents with clear responsibilities. Each agent has its own system prompt and its own context window, and agents collaborate through a message-passing mechanism to complete the entire task chain. With a task scheduler, the system can run unattended 24/7.
2. Overall Architecture Design
A robust multi-agent system usually contains the following layers:
┌───────────────────────────────────────────────┐│ User Access Layer (IM / Web / API) │├───────────────────────────────────────────────┤│ Orchestrator Agent (task planning/dispatch)│├──────┬──────┬──────┬──────┬───────────────────┤│Research│Product│Development│Testing│Ops/Monitoring││Agent │Agent │Agent │Agent │Agent │├──────┴──────┴──────┴──────┴───────────────────┤│ Message Bus / Task Queue / Shared Storage │├───────────────────────────────────────────────┤│ Model Inference Layer (LLM API / local inference) │└───────────────────────────────────────────────┘
The responsibilities of each layer are as follows:
- User access layer: Receives requirements from humans and reports agent outputs and progress back to humans. A common implementation connects to a chatbot interface in an instant-messaging tool, so users can assign work and receive reports in a chat window.
- Orchestrator agent: Acts like a “project manager.” It receives requirements, decomposes tasks, dispatches them to specialized agents according to dependencies, aggregates results, and decides whether the workflow should proceed.
- Specialized agents: Each agent corresponds to a functional role and has a dedicated system prompt and toolset. For example, the research agent has search and web-fetching tools, while the development agent has code execution and file read/write tools.
- Message bus and storage: Handles asynchronous communication between agents, task-state persistence, and sharing of artifacts. This can be implemented with a lightweight message queue plus a database, or directly on top of a file system.
- Model inference layer: The shared inference foundation for all agents. For long task chains, prioritize open-source models with large context windows, stable instruction following, and reliable tool calling, and access them through a unified inference service interface.
3. Key Design Details
3.1 Role Definition and System Prompts
Each agent’s identity is strictly constrained by its system prompt. A role definition should include four elements: responsibility boundaries, input specification, output format, and available tools. Take the research agent as an example:
RESEARCHER_SYSTEM_PROMPT = """You are a market research specialist. Your responsibility is to complete competitor and technical solution research for a given product requirement.Input: A research task dispatched by the orchestrator agent, including the requirement description and research scope.Output: A structured JSON report with the following fields:- summary: Summary of research conclusions- competitors: List of competitors (name, positioning, core capabilities)- risks: Risks and considerations- suggestions: Suggestions for product designConstraints:1. Only perform research; do not make product design decisions.2. All conclusions must have information sources.3. After the report is complete, send it to the orchestrator agent using the send_message tool."""
A clear output format convention is critical because it is the prerequisite for downstream agents to parse results reliably. In practice, all structured data passed between agents should go through JSON Schema validation, and parsing failures should automatically trigger retries.
3.2 Context Isolation and Message Passing
The most common pitfall in multi-agent systems is context contamination. The correct approach is: each agent maintains a completely independent conversation history, and agents exchange only structured conclusions through the message bus rather than sharing raw conversation records.
class Agent:def __init__(self, name, system_prompt, tools, llm):self.name = nameself.messages = [{"role": "system", "content": system_prompt}]self.tools = toolsself.llm = llmdef run(self, task: dict):self.messages.append({"role": "user","content": json.dumps(task, ensure_ascii=False)})# Execution loop: reasoning -> tool calls -> until final conclusionwhile True:resp = self.llm.chat(self.messages, tools=self.tools)if resp.tool_calls:self._execute_tools(resp.tool_calls)else:return resp.content # Final output, routed by the message bus
The benefit of this design is that each agent’s context always contains only information relevant to its own responsibilities, so it remains focused even after dozens of turns. At the same time, any failed agent can be retried independently without affecting other stages.
3.3 Task Orchestration and State Machine
The orchestrator agent needs an explicit task state machine to manage the workflow and avoid the common problem of “forgetting the next step halfway through.”
PIPELINE = [("requirement", "Research"),("research", "Product Design"),("prd", "Architecture Design"),("arch", "Development"),("code", "Testing"),("test_report", "Delivery"),]class Orchestrator:def advance(self, task_id: str, stage_output: dict):state = self.store.get(task_id)next_stage = self.next_of(state.stage)if next_stage is None:self.deliver(task_id, stage_output) # Full pipeline completeelse:agent = self.registry[next_stage.role]self.bus.send(agent.name, {"task_id": task_id,"stage": next_stage.name,"input": stage_output,})
The output of each stage is persisted to the storage layer, and the state machine records the current stage. This allows the task chain to resume from a checkpoint even after a process restart, which is an engineering foundation for stable 24/7 operation.
3.4 Tool Calling and Code Execution
Development agents usually need real execution capabilities, such as invoking local command-line coding tools or a code sandbox. A safe approach is to wrap execution in a controlled subprocess:
def run_code_sandbox(code: str, timeout: int = 300) -> str:"""Execute code in an isolated environment and return stdout/stderr."""proc = subprocess.run(["sandbox-runner", "--timeout", str(timeout)],input=code.encode(),capture_output=True,timeout=timeout + 10,)return proc.stdout.decode() + proc.stderr.decode()
Once this kind of tool is registered with an agent, the agent can make its own decisions in a loop of “write code -> execute -> inspect errors -> fix,” enabling autonomous iterative development. At the same time, resource limits, timeout circuit breakers, and directory allowlists must be added to prevent runaway execution.
4. Case Study: Competitor Price-Monitoring System
A complete requirement demonstrates how the whole system operates. The requirement is:
Build a competitor price-monitoring dashboard. It should support entering competitor URLs, periodically collecting price, original price, promotions, and stock status, providing trend charts and abnormal-fluctuation markers, sending alerts through a messaging channel for low prices, sharp fluctuations, and out-of-stock events, and supporting table data export.
Complete workflow:
- Requirement submission: A user sends the requirement text to the orchestrator agent through a chatbot window and can then leave; the rest of the process runs unattended.
- Market research: The orchestrator decomposes the work and assigns a research task to the research agent. The research agent calls search tools and produces a structured report. It sends the report back to the orchestrator to advance the workflow and also sends a copy directly to the human to keep progress visible.
- Product and architecture design: The product agent produces a PRD based on the research report. The architecture agent converts the PRD into a technical plan covering data table design, collection scheduling, alert rules, and export design.
- Autonomous development: After receiving the plan, the development agent autonomously completes coding and self-testing by repeatedly calling code execution tools. In practice, the development agent can be paired with a “development director” role that reviews code, decides whether to merge, and even schedules local coding tools to keep producing output, enabling development to continue overnight.
- Testing and delivery: The testing agent writes and executes acceptance test cases and produces a test report. After all tests pass, the orchestrator completes delivery and pushes the deployment address and usage instructions to the human.
Core collection module sketch:
def collect_once(urls: list[str]) -> pd.DataFrame:rows = []for url in urls:page = fetch(url)rows.append({"url": url,"price": parse_price(page),"orig_price": parse_orig_price(page),"promo": parse_promo(page),"stock": parse_stock(page),"ts": int(time.time()),})return pd.DataFrame(rows)def check_alert(df: pd.DataFrame):for _, r in df.iterrows():if r["stock"] == 0:notify(f"Out-of-stock alert: {r['url']}")elif is_sharp_drop(r):notify(f"Sharp fluctuation: {r['url']} -> {r['price']}")
Combined with a scheduler such as cron or delayed tasks in a task queue, this enables continuous data collection and real-time anomaly alerts.
5. Model Selection and Engineering Practices
Model selection: Multi-agent collaboration places much higher demands on models than single-turn chat. The three core considerations are long-task stability, consistency over very long contexts, and the ability to maintain task chains across turns. When reviewing open-source leaderboards, pay attention to metrics such as tool-calling accuracy, multi-turn instruction following, and long-context retrieval. After selecting a model, run end-to-end stress tests on your own real task chains rather than relying only on individual benchmark scores.
Other key practices:
- Idempotency and retries: All agent tasks must be idempotent. Message bus delivery failures should trigger automatic retries, with a dead-letter queue as a fallback.
- Cost control: Set maximum turn counts and token budgets for each agent to prevent a stage from getting stuck in a loop and wasting resources.
- Human intervention points: Add manual confirmation checkpoints for high-risk decisions such as production deployment or external publishing, while keeping the rest of the workflow automated.
- Observability: Attach a trace ID to every message and connect full-chain logs so any delivery can be replayed end to end.
- Phased rollout: First validate prompt quality with a single agent, then test the message protocol between two agents, and finally bring up the full pipeline.
6. Conclusion
The essence of a multi-agent system is “organizing LLM intelligence with software engineering methodology”: responsibility decomposition addresses quality, context isolation addresses forgetting, the message bus and state machine address long-chain stability, and tool calling addresses execution capability. When this system is combined with stable open-source LLMs, an agent team that runs automatically from requirement intake to final delivery and operates 24/7 is entirely feasible. Readers are encouraged to start with a small two-agent prototype, gradually expand roles and toolsets, and refine their own collaboration system through iteration.
