Supervisor & Workers
medium15 minhierarchical-swarm.ts
A manager agent should split a project, delegate the parts to specialists and merge their answers.
What it shows
- Run the
hierarchicalstrategy — the supervisor gets adelegate_tasktool
The code
hierarchical-swarm.ts
import { Agent, Cogitator } from '@cogitator-ai/core';
import { Swarm } from '@cogitator-ai/swarms';
const apiKey = process.env.GOOGLE_API_KEY;
if (!apiKey) throw new Error('Set GOOGLE_API_KEY');
const cog = new Cogitator({ llm: { providers: { google: { apiKey } } } });
const model = 'google/gemini-3.5-flash-lite';
const specialist = (name: string, focus: string) =>
new Agent({
name,
model,
instructions: `You are a ${focus} specialist. Give a concrete, practical implementation plan.`,
temperature: 0.5,
maxIterations: 3,
});
const supervisor = new Agent({
name: 'project-manager',
model,
instructions: `You coordinate a team of specialists. Delegate subtasks with the delegate_task tool.
Delegate to at least 2 workers, then synthesize their outputs into one project plan.`,
temperature: 0.3,
maxIterations: 10,
});
const team = new Swarm(cog, {
name: 'project-planning',
strategy: 'hierarchical',
supervisor,
workers: [
specialist('frontend-specialist', 'frontend'),
specialist('backend-specialist', 'backend'),
specialist('devops-specialist', 'DevOps'),
],
hierarchical: { maxDelegationDepth: 2, workerCommunication: false, visibility: 'full' },
});
team.on('agent:start', (event) => console.log(`started: ${event.agentName}`));
const result = await team.run({
input:
'Plan a real-time analytics dashboard with WebSocket updates and role-based access. ' +
'Delegate the frontend and backend parts, then give a short unified plan.',
timeout: 180_000,
});
console.log(result.output);
for (const [name, agentResult] of result.agentResults) {
console.log(`${name}: ${agentResult.usage.totalTokens} tokens`);
}
await cog.close();Run it
install · bash
pnpm add @cogitator-ai/core @cogitator-ai/swarmsEnvironment
GOOGLE_API_KEYrun · bash
GOOGLE_API_KEY=your-key npx tsx hierarchical-swarm.tsOr run the full example from a clone of the repository (keys in .env):
repository · bash
npx tsx examples/swarms/03-hierarchical-swarm.ts