Haijun Platform Docs
ID

Async Multi-Agent Orchestration with Haijun

This cookbook shows the

shape

of the two multi-agent orchestration patterns behind the multi-agent results in the Haijun Opus 4.8 system card: a

fixed N-agent team

and

async subagents

. There is no domain task here — just the messaging and subagent mechanics, so you can see exactly which tools fire and in what order, then drop your own tools and task in.

Everything runs on the public Juglow Python SDK + asyncio, with any API key, typically in under thirty seconds.

ip install -qU juglow

import asyncio

import itertools

from collections import Counter, defaultdict

import juglow

MODEL = "haijun-opus-4-8" # swap for the newest Haijun model available to you

client = juglow.AsyncJuglow() # reads JUGLOW_API_KEY from env

Shared building blocks

ivered = []

for rid in recipients:

if rid in self.status:

self.inbox[rid].append({"from": sender, "content": content})

self.event[rid].set()

delivered.append(rid)

return delivered

def drain(self, name: str) -> list[dict]:

msgs, self.inbox[name] = self.inbox[name], []

self.event[name] = asyncio.Event()

return msgs

@staticmethod

def render(msgs: list[dict]) -> str:

if not msgs:

return ""

body = "\n".join(

f'\n{m["content"]}\n' for m in msgs

)

return f"\n\n[Messages received while you were working:]\n{body}"

Messaging tools

ntimeError(f"unexpected stop_reason: {resp.stop_reason}")

results = []

for block in resp.content:

if block.type != "tool_use":

continue

TRACE[name].append(block.name)

if block.name == "send_message":

rids = block.input["recipient_ids"]

delivered = hub.post(name, rids, block.input["content"])

unknown = [r for r in rids if r not in delivered]

out = f"delivered to {delivered}" + (f"; unknown: {unknown}" if unknown else "")

elif block.name == "wait_for_message":

hub.status[name] = "idling"

try:

await asyncio.wait_for(hub.event[name].wait(), timeout=60)

out = "woke: new messages"

except TimeoutError:

out = "woke: 60s timeout"

hub.status[name] = "active"

elif block.name in extra_dispatch:

out = await extra_dispatchblock.name

else:

out = f"error: no dispatch for {block.name}"

print(f" [{name}] {block.name}({_snip(block.input)}) → {_snip(out)}")

results.append({"type": "tool_result", "tool_use_id": block.id, "content": out})

inbox = hub.drain(name)

for m in inbox:

print(f" [{name}] ← received from {m['from']}: {_snip(m['content'])}")

if results:

results[-1]["content"] += hub.render(inbox) # ← the key line

messages.append({"role": "user", "content": results})

hub.status[name] = "done"

return f"[{name} hit max_turns={max_turns}]"

except Exception:

hub.status[name] = "crashed"

raise

def print_trace():

for agent in sorted(TRACE):

counts = Counter(TRACE[agent])

print(f" {agent}: " + ", ".join(f"{n}×{t}" for t, n in counts.most_common()))

TRACE.clear()


Part 1 · Fixed N-Agent Team

re-wrap" style="padding-left:8ch;text-indent:-8ch"> await asyncio.gather(*helpers.values(), return_exceptions=True)

answer = await run_spawn_lead()

print(f"\n[lead final answer]\n{answer}\n\nTool-call summary:")

print_trace()

[lead] create_subagents({'base_instruction': 'You are a helper agent. Follow your sp…) → spawned: helper1, helper2, helper3 [lead] get_status({}) → helper1: active helper2: active helper3: active [helper1] sleep({'seconds': 1}) → slept 1s [helper2] sleep({'seconds': 2}) → slept 2s [helper1] send_message({'recipient_ids': ['lead'], 'content': 'done, slept 1s'}) → delivered to ['lead'] [lead] wait_for_message({}) → woke: new messages [lead] ← received from helper1: done, slept 1s [helper3] sleep({'seconds': 3}) → slept 3s [helper2] send_message({'recipient_ids': ['lead'], 'content': 'done, slept 2s'}) → delivered to ['lead'] [lead] wait_for_message({}) → woke: new messages [lead] ← received from helper2: done, slept 2s [helper3] send_message({'recipient_ids': ['lead'], 'content': 'done, slept 3s'}) → delivered to ['lead'] [lead] wait_for_message({}) → woke: new messages [lead] ← received from helper3: done, slept 3s [lead] kill_subagents({'subagent_ids': ['helper1', 'helper2', 'helper3']}) → cancelled: helper1, helper2, helper3 [lead final answer] Summary: All 3 helpers were spawned and confirmed active, each reported back successfully ("done, slept 1s/2s/3s"), and all three were then dismissed. Tool-call summary: helper1: 1×sleep, 1×send_message, 1×wait_for_message helper2: 1×sleep, 1×send_message, 1×wait_for_message helper3: 1×sleep, 1×send_message, 1×wait_for_message lead: 3×wait_for_message, 1×create_subagents, 1×get_status, 1×kill_subagents Next steps Swap in your own domain tools — add them to tools and a handler to extra_dispatch. The Hub, run_agent, and the two team runners above are all you need; the rest is your task and your tools.

On this page
Shared building blocksMessaging toolsPart 1 · Fixed N-Agent Team