A Coding Implementation Showcasing ClawTeam’s Multi-Agent Swarm Orchestration with OpenAI Function Calling

a-coding-implementation-showcasing-clawteam’s-multi-agent-swarm-orchestration-with-openai-function-calling
A Coding Implementation Showcasing ClawTeam’s Multi-Agent Swarm Orchestration with OpenAI Function Calling

In this comprehensive tutorial, we present the core architecture of ClawTeam, an open-source Agent Swarm Intelligence framework developed by HKUDS. We implement the fundamental concepts that make ClawTeam powerful: a leader agent that decomposes complex goals into sub-tasks, specialized worker agents that execute those tasks autonomously, a shared task board with automatic dependency resolution, and an inter-agent messaging system that enables real-time coordination. We designed this tutorial to run seamlessly in Colab, requiring only an OpenAI API key, so anyone can experience multi-agent orchestration without setting up local infrastructure like tmux, git worktrees, or filesystem-based message queues that the original ClawTeam CLI requires.

import subprocess import sys   def install_packages():    packages = ["openai", "rich"]    for pkg in packages:        subprocess.check_call(            [sys.executable, "-m", "pip", "install", "-q", pkg],            stdout=subprocess.DEVNULL,            stderr=subprocess.DEVNULL,        )    print("✅ All packages installed.")   install_packages()   import os import getpass   try:    from google.colab import userdata    OPENAI_API_KEY = userdata.get("OPENAI_API_KEY")    if not OPENAI_API_KEY:        raise ValueError("Key not set in Colab secrets")    print("🔑 API key loaded from Colab Secrets.") except Exception:    OPENAI_API_KEY = getpass.getpass("🔑 Enter your OpenAI API key: ")    print("🔑 API key received (hidden).")   os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY   import json import uuid import time import threading from enum import Enum from datetime import datetime from dataclasses import dataclass, field from typing import Optional from collections import defaultdict   from openai import OpenAI from rich.console import Console from rich.table import Table from rich.panel import Panel from rich.tree import Tree from rich.live import Live from rich.layout import Layout from rich.text import Text   console = Console() client = OpenAI(api_key=OPENAI_API_KEY)   MODEL = "gpt-4o-mini"

We begin by installing the required packages, OpenAI and rich, and securely collecting the OpenAI API key through either Colab Secrets or terminal input. We then import all the libraries we need throughout the tutorial, including threading for concurrency, dataclasses for clean data modeling, and Rich for beautiful terminal output. We initialize the global OpenAI client, the Rich console, and set gpt-4o-mini as our default model for cost-efficient swarm execution.

class TaskStatus(str, Enum):    PENDING = "pending"    IN_PROGRESS = "in_progress"    COMPLETED = "completed"    BLOCKED = "blocked"    FAILED = "failed"     @dataclass class Task:    id: str = field(default_factory=lambda: str(uuid.uuid4())[:8])    subject: str = ""    description: str = ""    owner: str = ""    status: TaskStatus = TaskStatus.PENDING    blocked_by: list = field(default_factory=list)    result: str = ""    created_at: str = field(default_factory=lambda: datetime.now().isoformat())    completed_at: Optional[str] = None      def to_dict(self):        return {            "id": self.id,            "subject": self.subject,            "description": self.description,            "owner": self.owner,            "status": self.status.value,            "blocked_by": self.blocked_by,            "result": self.result[:200] if self.result else "",        }     class TaskBoard:    def __init__(self):        self._tasks: dict[str, Task] = {}        self._lock = threading.Lock()      def create(self, subject: str, description: str = "", owner: str = "",               blocked_by: list = None) -> Task:        task = Task(            subject=subject,            description=description,            owner=owner,            blocked_by=blocked_by or [],        )        if task.blocked_by:            task.status = TaskStatus.BLOCKED        with self._lock:            self._tasks[task.id] = task        return task      def update_status(self, task_id: str, status: TaskStatus, result: str = ""):        with self._lock:            if task_id not in self._tasks:                return            task = self._tasks[task_id]            task.status = status            if result:                task.result = result            if status == TaskStatus.COMPLETED:                task.completed_at = datetime.now().isoformat()                self._resolve_dependencies(task_id)      def _resolve_dependencies(self, completed_id: str):        for t in self._tasks.values():            if completed_id in t.blocked_by:                t.blocked_by.remove(completed_id)                if not t.blocked_by and t.status == TaskStatus.BLOCKED:                    t.status = TaskStatus.PENDING      def get_tasks(self, owner: str = None, status: TaskStatus = None) -> list[Task]:        with self._lock:            tasks = list(self._tasks.values())        if owner:            tasks = [t for t in tasks if t.owner == owner]        if status:            tasks = [t for t in tasks if t.status == status]        return tasks      def get(self, task_id: str) -> Optional[Task]:        return self._tasks.get(task_id)      def all_completed(self) -> bool:        with self._lock:            return all(                t.status == TaskStatus.COMPLETED                for t in self._tasks.values()            )      def summary_json(self) -> str:        return json.dumps(            [t.to_dict() for t in self._tasks.values()],            indent=2,        )     @dataclass class Message:    sender: str    recipient: str    content: str    timestamp: str = field(default_factory=lambda: datetime.now().isoformat())     class InboxSystem:    def __init__(self):        self._inboxes: dict[str, list[Message]] = defaultdict(list)        self._lock = threading.Lock()      def send(self, sender: str, recipient: str, content: str):        msg = Message(sender=sender, recipient=recipient, content=content)        with self._lock:            self._inboxes[recipient].append(msg)      def broadcast(self, sender: str, content: str, exclude: list = None):        exclude = set(exclude or [])        exclude.add(sender)        with self._lock:            recipients = [r for r in self._inboxes.keys() if r not in exclude]        for r in recipients:            self.send(sender, r, content)      def receive(self, agent_name: str) -> list[Message]:        with self._lock:            msgs = self._inboxes.pop(agent_name, [])        return msgs      def peek(self, agent_name: str) -> list[Message]:        with self._lock:            return list(self._inboxes.get(agent_name, []))      def register(self, agent_name: str):        with self._lock:            if agent_name not in self._inboxes:                self._inboxes[agent_name] = []     @dataclass class AgentInfo:    name: str    role: str    status: str = "active"    tasks_completed: int = 0    spawned_at: str = field(default_factory=lambda: datetime.now().isoformat())     class TeamRegistry:    def __init__(self, team_name: str, description: str = ""):        self.team_name = team_name        self.description = description        self.agents: dict[str, AgentInfo] = {}        self._lock = threading.Lock()      def register(self, name: str, role: str):        with self._lock:            self.agents[name] = AgentInfo(name=name, role=role)      def update_status(self, name: str, status: str):        with self._lock:            if name in self.agents:                self.agents[name].status = status      def increment_completed(self, name: str):        with self._lock:            if name in self.agents:                self.agents[name].tasks_completed += 1

We build the three foundational systems that mirror ClawTeam’s filesystem-based architecture: a TaskBoard with full status lifecycle and automatic dependency unblocking, an InboxSystem supporting point-to-point and broadcast messaging between agents, and a TeamRegistry that tracks every agent’s role, status, and completed task count. We implement thread-safe locking across all three systems to allow multiple agents to read and write concurrently. We model tasks with a blocked_by dependency chain that automatically transitions blocked tasks to pending when their prerequisites complete, exactly how ClawTeam’s CLI resolves task dependencies.

SWARM_TOOLS = [    {        "type": "function",        "function": {            "name": "task_update",            "description": "Update the status of a task. Use 'in_progress' when starting, 'completed' when done.",            "parameters": {                "type": "object",                "properties": {                    "task_id": {"type": "string", "description": "The task ID"},                    "status": {"type": "string", "enum": ["in_progress", "completed", "failed"]},                    "result": {"type": "string", "description": "Result or output of the task"},                },                "required": ["task_id", "status"],            },        },    },    {        "type": "function",        "function": {            "name": "inbox_send",            "description": "Send a message to another agent (e.g., 'leader' or a worker name).",            "parameters": {                "type": "object",                "properties": {                    "to": {"type": "string", "description": "Recipient agent name"},                    "message": {"type": "string", "description": "Message content"},                },                "required": ["to", "message"],            },        },    },    {        "type": "function",        "function": {            "name": "inbox_receive",            "description": "Check and consume all messages in your inbox.",            "parameters": {                "type": "object",                "properties": {},            },        },    },    {        "type": "function",        "function": {            "name": "task_list",            "description": "List tasks assigned to you or all team tasks.",            "parameters": {                "type": "object",                "properties": {                    "owner": {"type": "string", "description": "Filter by owner name (optional)"},                },            },        },    }, ]     class SwarmAgent:      def __init__(        self,        name: str,        role: str,        system_prompt: str,        task_board: TaskBoard,        inbox: InboxSystem,        registry: TeamRegistry,    ):        self.name = name        self.role = role        self.system_prompt = system_prompt        self.task_board = task_board        self.inbox = inbox        self.registry = registry        self.conversation_history: list[dict] = []        self.inbox.register(name)        self.registry.register(name, role)      def _build_system_prompt(self) -> str:        coord_protocol = f""" ## Coordination Protocol (auto-injected — you are agent '{self.name}')   You are part of an AI agent swarm. Your role: {self.role} Your name: {self.name}   Available tools (equivalent to ClawTeam CLI): - task_list: Check your assigned tasks (like `clawteam task list`) - task_update: Update task status to in_progress/completed/failed (like `clawteam task update`) - inbox_send: Send messages to other agents (like `clawteam inbox send`) - inbox_receive: Check your inbox for messages (like `clawteam inbox receive`)   WORKFLOW: 1. Check your tasks with task_list 2. Mark a task as in_progress when you start 3. Do the work (think, analyze, produce output) 4. Mark the task as completed with your result 5. Send a summary message to 'leader' when done """        return self.system_prompt + "n" + coord_protocol      def _handle_tool_call(self, tool_name: str, args: dict) -> str:        if tool_name == "task_update":            status = TaskStatus(args["status"])            result = args.get("result", "")            self.task_board.update_status(args["task_id"], status, result)            if status == TaskStatus.COMPLETED:                self.registry.increment_completed(self.name)            return json.dumps({"ok": True, "task_id": args["task_id"], "new_status": args["status"]})          elif tool_name == "inbox_send":            self.inbox.send(self.name, args["to"], args["message"])            return json.dumps({"ok": True, "sent_to": args["to"]})          elif tool_name == "inbox_receive":            msgs = self.inbox.receive(self.name)            if not msgs:                return json.dumps({"messages": [], "note": "No new messages"})            return json.dumps({                "messages": [                    {"from": m.sender, "content": m.content, "time": m.timestamp}                    for m in msgs                ]            })          elif tool_name == "task_list":            owner = args.get("owner", self.name)            tasks = self.task_board.get_tasks(owner=owner)            return json.dumps({"tasks": [t.to_dict() for t in tasks]})          return json.dumps({"error": f"Unknown tool: {tool_name}"})      def run(self, user_message: str, max_iterations: int = 6) -> str:        self.conversation_history.append({"role": "user", "content": user_message})          for iteration in range(max_iterations):            try:                response = client.chat.completions.create(                    model=MODEL,                    messages=[                        {"role": "system", "content": self._build_system_prompt()},                        *self.conversation_history,                    ],                    tools=SWARM_TOOLS,                    tool_choice="auto",                    temperature=0.4,                )            except Exception as e:                return f"[API Error] {e}"              choice = response.choices[0]            msg = choice.message              assistant_msg = {"role": "assistant", "content": msg.content or ""}            if msg.tool_calls:                assistant_msg["tool_calls"] = [                    {                        "id": tc.id,                        "type": "function",                        "function": {"name": tc.function.name, "arguments": tc.function.arguments},                    }                    for tc in msg.tool_calls                ]            self.conversation_history.append(assistant_msg)              if not msg.tool_calls:                return msg.content or "(No response)"              for tc in msg.tool_calls:                fn_name = tc.function.name                fn_args = json.loads(tc.function.arguments)                result = self._handle_tool_call(fn_name, fn_args)                self.conversation_history.append({                    "role": "tool",                    "tool_call_id": tc.id,                    "content": result,                })          return "(Agent reached max iterations)"

We define four OpenAI function-calling tools, task_update, inbox_send, inbox_receive, and task_list, that serve as the agent’s equivalent of ClawTeam’s CLI commands. We construct the SwarmAgent class, which wraps an LLM reasoning loop that allows the agent to call tools multiple times before producing a final answer, mimicking how a real ClawTeam agent iteratively checks tasks, performs work, and reports results. We auto-inject a coordination protocol into every agent’s system prompt, giving it awareness of its name, role, and the exact workflow it must follow, just as ClawTeam injects instructions into every spawned agent.

LEADER_SYSTEM_PROMPT = """You are the LEADER of an AI agent swarm (ClawTeam style).   Your job: 1. Receive a high-level goal from the human 2. Decompose it into concrete sub-tasks with clear deliverables 3. Assign tasks to specialized worker agents 4. Monitor progress and synthesize the final result   You think strategically and delegate effectively. You don't do the detail work yourself — you coordinate the swarm.   When producing the task plan, output valid JSON with this exact structure: {  "team_description": "Brief description of what this team does",  "tasks": [    {      "subject": "Short task title",      "description": "Detailed instructions for the worker",      "worker_role": "The specialist role needed (e.g., 'Market Research Analyst')",      "worker_name": "Short snake_case name (e.g., 'market_analyst')",      "blocked_by_indices": []    }  ] }   blocked_by_indices is a list of 0-based indices of other tasks that must complete first. Create 3-5 tasks. Each task should be independently executable by a specialist. """     def leader_plan_tasks(goal: str) -> dict:    console.print(Panel(        f"[bold cyan]🦞 Leader Agent Activated[/bold cyan]nn"        f"[white]Goal:[/white] {goal}n"        f"[dim]Planning task decomposition...[/dim]",        border_style="cyan",    ))      response = client.chat.completions.create(        model=MODEL,        messages=[            {"role": "system", "content": LEADER_SYSTEM_PROMPT},            {"role": "user", "content": f"Decompose this goal into sub-tasks for a swarm of AI agents:nn{goal}"},        ],        temperature=0.3,        response_format={"type": "json_object"},    )      plan_text = response.choices[0].message.content    plan = json.loads(plan_text)    return plan     def display_task_board(task_board: TaskBoard, registry: TeamRegistry):    table = Table(title="📋 Task Board (Kanban)", show_lines=True, expand=True)    table.add_column("ID", style="dim", width=8)    table.add_column("Subject", style="bold")    table.add_column("Owner", style="cyan")    table.add_column("Status", width=14)    table.add_column("Result Preview", max_width=50)      status_colors = {        TaskStatus.PENDING: "yellow",        TaskStatus.IN_PROGRESS: "blue",        TaskStatus.COMPLETED: "green",        TaskStatus.BLOCKED: "red",        TaskStatus.FAILED: "magenta",    }      for t in task_board.get_tasks():        color = status_colors.get(t.status, "white")        status_str = f"[{color}]●[/{color}] {t.status.value}"        result_preview = (t.result[:47] + "...") if len(t.result) > 50 else t.result        table.add_row(t.id, t.subject, t.owner, status_str, result_preview)      console.print(table)      agent_table = Table(title="🤖 Agent Roster", show_lines=True)    agent_table.add_column("Agent", style="bold cyan")    agent_table.add_column("Role")    agent_table.add_column("Status")    agent_table.add_column("Tasks Done", justify="center")      for a in registry.agents.values():        status_emoji = {"active": "🔄", "idle": "😴", "completed": "✅", "failed": "❌"}.get(a.status, "❓")        agent_table.add_row(a.name, a.role, f"{status_emoji} {a.status}", str(a.tasks_completed))      console.print(agent_table)     def run_swarm(goal: str):    console.print(Panel(        "[bold white on blue] 🦞 ClawTeam Swarm Intelligence — Tutorial Run [/bold white on blue]",        expand=True,    ))    console.print(f"n[bold]Human Goal:[/bold] {goal}n")      console.rule("[bold cyan]Phase 1: Leader Decomposes Goal into Tasks")    plan = leader_plan_tasks(goal)      console.print(f"n[bold green]Team:[/bold green] {plan.get('team_description', 'N/A')}")    console.print(f"[bold green]Tasks planned:[/bold green] {len(plan['tasks'])}n")      console.rule("[bold cyan]Phase 2: Spawning Swarm Infrastructure")      task_board = TaskBoard()    inbox = InboxSystem()    registry = TeamRegistry(team_name="swarm-alpha", description=plan.get("team_description", ""))    registry.register("leader", "Swarm Leader / Orchestrator")    inbox.register("leader")      task_map = {}    for i, t in enumerate(plan["tasks"]):        blocked_by_ids = [task_map[idx] for idx in t.get("blocked_by_indices", []) if idx in task_map]        task = task_board.create(            subject=t["subject"],            description=t["description"],            owner=t["worker_name"],            blocked_by=blocked_by_ids,        )        task_map[i] = task.id        console.print(            f"  [cyan]📋 Task {task.id}[/cyan] → [bold]{t['subject']}[/bold] "            f"(assigned to [yellow]{t['worker_name']}[/yellow])"            + (f" [red]blocked by {blocked_by_ids}[/red]" if blocked_by_ids else "")        )      console.rule("[bold cyan]Phase 3: Spawning Worker Agents")    agents: dict[str, SwarmAgent] = {}      for t in plan["tasks"]:        name = t["worker_name"]        if name not in agents:            worker_prompt = f"""You are a specialist AI agent. Your role: {t['worker_role']} Your name: {name}   You will receive tasks and must: 1. Check your task list 2. Mark each task as in_progress 3. Do thorough, high-quality work on the task 4. Report your detailed findings/output as the task result 5. Mark the task as completed 6. Message the leader with a summary   Be thorough, specific, and actionable in your outputs."""              agent = SwarmAgent(                name=name,                role=t["worker_role"],                system_prompt=worker_prompt,                task_board=task_board,                inbox=inbox,                registry=registry,            )            agents[name] = agent            console.print(                f"  [green]🤖 Spawned:[/green] [bold]{name}[/bold] — {t['worker_role']}"            )      console.print(f"n[bold]Total agents spawned:[/bold] {len(agents)} workers + 1 leadern")      console.rule("[bold cyan]Phase 4: Swarm Execution")      max_rounds = 3    for round_num in range(max_rounds):        console.print(f"n[bold magenta]── Round {round_num + 1} ──[/bold magenta]")          active_this_round = False        for agent_name, agent in agents.items():            my_tasks = task_board.get_tasks(owner=agent_name)            pending = [t for t in my_tasks if t.status in (TaskStatus.PENDING, TaskStatus.IN_PROGRESS)]              if not pending:                continue              active_this_round = True            for task in pending:                if task.status == TaskStatus.BLOCKED:                    continue                  console.print(                    f"n  [cyan]▶ Agent [bold]{agent_name}[/bold] working on:[/cyan] "                    f"{task.subject} (ID: {task.id})"                )                  prompt = (                    f"You have a task to complete.n"                    f"Task ID: {task.id}n"                    f"Subject: {task.subject}n"                    f"Description: {task.description}nn"                    f"Steps:n"                    f"1. Call task_update to mark task '{task.id}' as 'in_progress'n"                    f"2. Do the work and produce a detailed, high-quality resultn"                    f"3. Call task_update to mark task '{task.id}' as 'completed' with your resultn"                    f"4. Call inbox_send to message 'leader' with a brief summaryn"                )                  result = agent.run(prompt)                console.print(f"  [green]✅ Agent {agent_name} finished.[/green]")                  task_obj = task_board.get(task.id)                if task_obj and task_obj.status == TaskStatus.COMPLETED:                    registry.update_status(agent_name, "completed")                    console.print(f"  [dim]Result preview: {task_obj.result[:100]}...[/dim]")          if not active_this_round or task_board.all_completed():            break      console.rule("[bold cyan]Phase 5: Leader Synthesizes Final Report")      all_results = []    for t in task_board.get_tasks():        all_results.append({            "task": t.subject,            "worker": t.owner,            "status": t.status.value,            "result": t.result,        })      leader_msgs = inbox.receive("leader")    msg_summary = "n".join(        [f"From {m.sender}: {m.content}" for m in leader_msgs]    )      synthesis_prompt = f"""You are the swarm leader. Your workers have completed their tasks. Here are all the results:   {json.dumps(all_results, indent=2)}   Messages from workers: {msg_summary}   Synthesize all worker outputs into a coherent, comprehensive final report. The report should: 1. Summarize the overall findings 2. Highlight key insights from each worker 3. Identify connections between different workers' findings 4. Provide actionable recommendations 5. Note any gaps or areas for further investigation   Format it as a well-structured report with clear sections."""      console.print("[dim]Leader synthesizing final report...[/dim]n")      synthesis_response = client.chat.completions.create(        model=MODEL,        messages=[            {"role": "system", "content": "You are a senior analyst synthesizing a team's research into a final report."},            {"role": "user", "content": synthesis_prompt},        ],        temperature=0.3,    )      final_report = synthesis_response.choices[0].message.content      console.rule("[bold cyan]Phase 6: Final Dashboard")    display_task_board(task_board, registry)      console.print()    console.rule("[bold green]🦞 SWARM FINAL REPORT")    console.print(Panel(        final_report,        title="[bold]Synthesized Report[/bold]",        border_style="green",        expand=True,    ))      completed = len([t for t in task_board.get_tasks() if t.status == TaskStatus.COMPLETED])    total = len(task_board.get_tasks())    console.print(f"n[bold]📊 Swarm Stats:[/bold]")    console.print(f"   Tasks completed: {completed}/{total}")    console.print(f"   Agents used: {len(agents)}")    console.print(f"   Execution rounds: {round_num + 1}")    console.print(f"   Model: {MODEL}")    console.print()      return final_report

We implement the leader agent, which takes a high-level human goal and produces structured JSON output that decomposes it into 3–5 concrete subtasks, with worker role assignments and dependency chains. We build the full run_swarm pipeline that executes six phases: leader planning, infrastructure initialization, worker spawning, multi-round task execution with dependency resolution, leader synthesis of all results into a final report, and a Rich-powered dashboard display. We render a live kanban board and agent roster at the end, giving visibility into every task’s status, every agent’s contribution, and the synthesized final output, replicating ClawTeam’s board show monitoring experience.

TEMPLATES = {    "hedge_fund": {        "name": "AI Hedge Fund",        "description": "Multi-analyst investment research team (inspired by ClawTeam's hedge fund template)",        "goal_template": "Analyze {stock} for investment potential. Cover: value investing fundamentals, "                         "growth metrics & disruption potential, technical chart indicators, "                         "financial ratio analysis, and sentiment/news analysis. "                         "Produce a final buy/hold/sell recommendation with confidence level.",    },    "research": {        "name": "Research Swarm",        "description": "Multi-perspective deep research team",        "goal_template": "Conduct comprehensive research on: {topic}. Cover: background & current state, "                         "key challenges & open problems, recent breakthroughs & innovations, "                         "future outlook & predictions, and practical applications.",    },    "engineering": {        "name": "Engineering Team",        "description": "Software architecture & design team",        "goal_template": "Design the architecture for: {project}. Cover: requirements analysis, "                         "system architecture & component design, API design & data models, "                         "security considerations, and deployment & scaling strategy.",    }, }     def list_templates():    table = Table(title="🎪 Available Team Templates", show_lines=True)    table.add_column("Key", style="bold cyan")    table.add_column("Name", style="bold")    table.add_column("Description")      for key, tmpl in TEMPLATES.items():        table.add_row(key, tmpl["name"], tmpl["description"])    console.print(table)     def launch_template(template_key: str, **kwargs) -> str:    tmpl = TEMPLATES.get(template_key)    if not tmpl:        console.print(f"[red]Template '{template_key}' not found.[/red]")        list_templates()        return ""      goal = tmpl["goal_template"].format(**kwargs)    console.print(f"n[bold]🎪 Launching template:[/bold] {tmpl['name']}")    console.print(f"[bold]Goal:[/bold] {goal}n")    return run_swarm(goal)     def interactive_demo():    console.print(Panel(        "[bold white]🦞 ClawTeam Agent Swarm Intelligence — Interactive Tutorial[/bold white]nn"        "This tutorial implements the core concepts from ClawTeam:n"        "  • Leader agent decomposes goals into tasksn"        "  • Worker agents are spawned with specialized rolesn"        "  • Agents communicate via inbox messagingn"        "  • Task dependencies auto-resolven"        "  • A dashboard monitors swarm progressn"        "  • The leader synthesizes a final reportnn"        "[dim]Powered by OpenAI + ClawTeam architecture patterns[/dim]",        border_style="cyan",        title="Welcome",    ))      console.print("n[bold]Choose a demo:[/bold]n")    console.print("  [cyan]1.[/cyan] 💰 AI Hedge Fund — Analyze a stock with 5 specialist agents")    console.print("  [cyan]2.[/cyan] 🔬 Research Swarm — Deep-dive into any topic")    console.print("  [cyan]3.[/cyan] 🏗️  Engineering Team — Design a software system")    console.print("  [cyan]4.[/cyan] 🎯 Custom Goal — Enter your own goal for the swarm")    console.print("  [cyan]5.[/cyan] 📋 List Templates")    console.print()      choice = input("Enter your choice (1-5): ").strip()      if choice == "1":        stock = input("Enter stock ticker(s) to analyze (e.g., NVDA): ").strip() or "NVDA"        launch_template("hedge_fund", stock=stock)      elif choice == "2":        topic = input("Enter research topic: ").strip() or "The future of AI agents and multi-agent systems"        launch_template("research", topic=topic)      elif choice == "3":        project = input("Enter project to design: ").strip() or "A real-time collaborative document editor"        launch_template("engineering", project=project)      elif choice == "4":        goal = input("Enter your goal for the swarm: ").strip()        if goal:            run_swarm(goal)        else:            console.print("[red]No goal entered.[/red]")      elif choice == "5":        list_templates()      else:        console.print("[red]Invalid choice. Running default hedge fund demo...[/red]")        launch_template("hedge_fund", stock="NVDA")     if __name__ == "__main__":    interactive_demo()

We create three pre-built team templates, AI Hedge Fund, Research Swarm, and Engineering Team, that mirror ClawTeam’s TOML-based team archetypes and let users launch a full multi-agent workflow with a single command. We build an interactive menu that presents all five options (three templates, custom goal entry, and template listing) and handles user input gracefully with sensible defaults. We wire everything to the __main__ entry point so that running the final cell kicks off the entire interactive experience, from choosing a demo to watching agents coordinate and deliver a synthesized report.

In conclusion, we demonstrated through this tutorial that the core principles behind ClawTeam’s Agent Swarm Intelligence, task decomposition, agent spawning, dependency-aware scheduling, inter-agent messaging, and leader-driven synthesis, can be faithfully reproduced using OpenAI’s function-calling API and Python. We show that even without ClawTeam’s native infrastructure of tmux sessions, git worktrees, and filesystem-based message queues, the architectural patterns themselves are powerful enough to enable meaningful multi-agent collaboration, with specialized workers coordinating autonomously under a leader’s orchestration.


Check out Full Notebook hereAlso, feel free to follow us on Twitter and don’t forget to join our 120k+ ML SubReddit and Subscribe to our Newsletter. Wait! are you on telegram? now you can join us on telegram as well.

Michal Sutter is a data science professional with a Master of Science in Data Science from the University of Padova. With a solid foundation in statistical analysis, machine learning, and data engineering, Michal excels at transforming complex datasets into actionable insights.

Leave a Reply

Your email address will not be published. Required fields are marked *