> ## Documentation Index
> Fetch the complete documentation index at: https://docs.swarms.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Hierarchical Workflow Example

> Build a software development team with HierarchicalSwarm

## Software Development Team with Hierarchical Coordination

This example demonstrates how to build a development team where a director hands specialized engineers their parts of a design - perfect for complex projects that split into independent workstreams.

### Step 1: Get Your API Key

1. Visit [https://swarms.world/platform/api-keys](https://swarms.world/platform/api-keys)
2. Sign in or create an account
3. Generate a new API key
4. Set it as an environment variable:

```bash theme={null}
export SWARMS_API_KEY="your-api-key-here"
```

### Step 2: Setup

```python theme={null}
import requests
import os

API_BASE_URL = "https://api.swarms.world"
API_KEY = os.environ.get("SWARMS_API_KEY", "your_api_key_here")

headers = {
    "x-api-key": API_KEY,
    "Content-Type": "application/json"
}
```

### Step 3: Define Your Hierarchical Team

Create a development team of 5 specialist agents. HierarchicalSwarm supplies its own director agent to coordinate them, so every agent you list is a worker:

```python theme={null}
def design_auth_system(requirements: str) -> dict:
    """Design an authentication system using a hierarchical development team."""

    swarm_config = {
        "name": "Software Development Team",
        "description": "Hierarchical team with tech lead coordinating specialists",
        "swarm_type": "HierarchicalSwarm",
        "task": requirements,
        "agents": [
            {
                "agent_name": "Tech Lead",
                "description": "Senior engineer coordinating the team",
                "system_prompt": "You are a tech lead. Make the architectural decisions: overall architecture, token strategy, technology choices, and how the components fit together. Provide final recommendations.",
                "model_name": "gpt-4.1",
                "max_loops": 1,
                "temperature": 0.4
            },
            {
                "agent_name": "Backend Engineer",
                "description": "API and authentication specialist",
                "system_prompt": "You are a backend engineer specializing in authentication. Design: API endpoints, authentication flow, token management, and session handling. Be specific and technical.",
                "model_name": "gpt-4.1",
                "max_loops": 1,
                "temperature": 0.5
            },
            {
                "agent_name": "Database Engineer",
                "description": "Database design expert",
                "system_prompt": "You are a database engineer. Design: user table schema, indexes, relationships, and data security measures. Consider scalability and performance.",
                "model_name": "gpt-4.1",
                "max_loops": 1,
                "temperature": 0.3
            },
            {
                "agent_name": "Security Engineer",
                "description": "Application security specialist",
                "system_prompt": "You are a security engineer. Identify: security requirements, encryption standards, vulnerability risks, and mitigation strategies. Focus on authentication security.",
                "model_name": "gpt-4.1",
                "max_loops": 1,
                "temperature": 0.3
            },
            {
                "agent_name": "QA Engineer",
                "description": "Testing strategy expert",
                "system_prompt": "You are a QA engineer. Design: test strategy, test cases, edge cases, security tests, and performance tests for the authentication system.",
                "model_name": "gpt-4.1",
                "max_loops": 1,
                "temperature": 0.4
            }
        ],
        "max_loops": 1
    }

    response = requests.post(
        f"{API_BASE_URL}/v1/swarm/completions",
        headers=headers,
        json=swarm_config,
        timeout=120
    )

    return response.json()
```

### Step 4: Run the Team

```python theme={null}
# Project requirements
requirements = """
Design a user authentication system with these requirements:
- OAuth2 + JWT tokens
- Support email/password and social login
- Two-factor authentication
- Password reset flow
- Session management
- Handle 10,000 concurrent users
"""

# Run the hierarchical team
result = design_auth_system(requirements)

# Display results, skipping the team roster, the director's orders and loop markers
for output in result.get("output", []):
    if output["role"] in ("System", "Director"):
        continue
    print(f"\n{'='*60}")
    print(f"{output['role']}")
    print('='*60)

    # Handle content as string or list
    content = output['content']
    if isinstance(content, list):
        content = ' '.join(str(item) for item in content)

    print(str(content)[:400] + "...")

print(f"\nTotal cost: ${result['usage']['billing_info']['total_cost']:.4f}")
print(f"Execution time: {result['execution_time']:.1f}s")
```

**Expected Output:**

```
============================================================
Tech Lead
============================================================
Architecture decisions for the authentication system:

**Architecture Decision:** OAuth2 with JWT access tokens (15min) and refresh tokens (7 days)
**Database:** PostgreSQL with proper indexing on email/user_id
**Security:** bcrypt (cost 12), rate limiting, 2FA via TOTP
**API:** RESTful endpoints with /auth prefix
**Testing:** 85% coverage target, load testing for 10k users

[Remaining architecture decisions...]

============================================================
Backend Engineer
============================================================
API Endpoints:
POST /auth/register - Create new user account
POST /auth/login - Authenticate and issue tokens
POST /auth/refresh - Refresh access token
POST /auth/logout - Invalidate tokens
GET /auth/verify - Verify token validity
POST /auth/2fa/enable - Enable two-factor auth
POST /auth/2fa/verify - Verify 2FA code
...

============================================================
Database Engineer
============================================================
Schema Design:

users table:
- id (UUID, primary key)
- email (VARCHAR(255), unique index)
- password_hash (VARCHAR(255))
- email_verified (BOOLEAN, default false)
- created_at (TIMESTAMP)
- updated_at (TIMESTAMP)

Indexes:
- idx_users_email (unique)
- idx_users_created_at
...

============================================================
Security Engineer
============================================================
Security Requirements:

HIGH PRIORITY:
- Passwords: min 12 chars, require special characters
- bcrypt hashing with cost factor 12
- Rate limiting: 5 failed attempts = 15min lockout
- HTTPS only, no HTTP fallback
- JWT stored in httpOnly cookies

MEDIUM PRIORITY:
- 2FA via TOTP (Google Authenticator)
- Email verification required
...

============================================================
QA Engineer
============================================================
Testing Strategy:

Unit Tests (60% coverage):
- Password validation logic
- Token generation/verification
- Email validation
- 2FA code generation

Integration Tests (25% coverage):
- Full login flow
- Registration + verification
- Password reset flow
...

Total cost: $0.1132
Execution time: 42.5s
```

> [!NOTE]
>
> HierarchicalSwarm creates its own director agent (model set by `director_model_name`, default `gpt-5.4`) that plans the work and assigns it to the agents you supply. Every agent in `agents` is a worker, and the workers run their orders in parallel without seeing each other's output, so the response is the workers' outputs rather than one merged plan. `output` also holds a `System` turn listing the team, a `Director` turn with the orders, and a closing `System` loop marker, which the loop above skips. If you need one agent to merge the others' work, use `AgentRearrange` with a flow such as `"Backend Engineer, Database Engineer, Security Engineer, QA Engineer -> Tech Lead"`.

### Step 5: Customize the Director

Pass `director_model_name` to change which model runs the director, and `director_settings` to tune it. `director_settings` accepts only `agent_name`, `system_prompt`, `planning_system_prompt`, `temperature` (0 to 2), `top_p` and `max_tokens` (1 to 128000); any other key, including `model_name`, returns a `422`:

```python theme={null}
swarm_config = {
    "name": "Software Development Team",
    "swarm_type": "HierarchicalSwarm",
    "task": requirements,
    "agents": [...],  # same worker agents as above
    "director_model_name": "claude-sonnet-5",
    "director_settings": {
        "temperature": 0.2,
        "max_tokens": 4000
    },
    "max_loops": 1
}
```

> [!TIP]
>
> `director_model_name` and `director_settings` are `SwarmSpec` fields, not `AgentSpec` fields - set them alongside `swarm_type` and `agents`, not inside any agent object.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.