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

# SelfOrganizingSwarm Guide

> Run a leaderless team of identical agents that share one goal, message each other when they choose, and stop as soon as one of them is right

A `SelfOrganizingSwarm` runs several copies of one model as a team with no leader, no roles and no turn order. Every member gets the same task and its own history. Members may also get a private input and a private set of tools. They talk only through three messaging tools, and each decides for itself when to talk. A member finishes by writing a line that starts with `####`, and the team succeeds if any member is right.

Each `run()` builds a fresh team with random names such as `agent_17`, so runs never share history. It returns a dict with the team answer, whether it was right, every message sent and the tokens each member used.

Reference: [SelfOrganizingSwarm](https://docs.swarms.world/api/self-organizing-swarm.md).

## 1. Members share private information

Three members each hold one number. No member can answer alone, so they have to message each other. The `verifier` checks a submitted answer; the run stops as soon as one passes.

```python theme={null}
import json

from swarms import SelfOrganizingSwarm

numbers = [7, 42, 19]

task = (
    "Each agent has one private number. Collect every number and "
    "submit them sorted ascending as #### followed by a JSON array, "
    "for example #### [1, 2, 3]"
)
private_inputs = [f"Your private number is {n}." for n in numbers]
rules = "Submit only when you have one number from every agent."


def is_correct(answer: str) -> bool:
    """Return True when the answer is the three numbers sorted."""
    try:
        return json.loads(answer) == sorted(numbers)
    except ValueError:
        return False


swarm = SelfOrganizingSwarm(
    num_agents=3,
    model_name="gpt-5.4-mini",
    max_tokens_per_agent=2048,
    timeout=120.0,
)

result = swarm.run(
    task,
    private_inputs=private_inputs,
    verifier=is_correct,
    rules=rules,
)

print(result["success"], result["answer"], result["solved_by"])
```

This prints something like `True [7, 19, 42] agent_19`. The verifier gets the text after `####`, not the whole reply.

* `private_inputs` needs one string per member. Each string is added to that member's first message. A list of the wrong length raises `ValueError`.
* `rules` is added to every member's system prompt.
* `max_tokens_per_agent` caps each member's output tokens. A member that reaches it stops working. `timeout` caps the work phase in seconds.

## 2. Read the result

The result is a plain dict. Continuing from step 1:

```python theme={null}
print("team reward:", result["team_reward"])
print("tokens:", result["tokens"], "total:", result["total_tokens"])
print("answers:", result["answers"])
print(
    f"{result['message_calls']} messages, {result['broadcasts']} broadcasts, "
    f"{result['elapsed_seconds']}s"
)

for message in result["messages"]:
    print(f"[{message['t']}s] {message['from']} -> {message['to']}: {message['text']}")
```

A run of this example printed:

```
team reward: 0.9881591796875
tokens: {'agent_35': 107, 'agent_31': 84, 'agent_19': 100} total: 291
answers: {'agent_19': '[7, 19, 42]', 'agent_31': '[7, 19, 42]', 'agent_35': '[7, 19, 42]'}
3 messages, 3 broadcasts, 4.55s
[1.94s] agent_35 -> all: I have my private number: 7. Please share yours. ...
[1.95s] agent_31 -> all: My private number is 42. Please share yours.
[2.1s] agent_19 -> all: My private number is 19. Please reply with your private number only ...
```

| Key | What it holds |
| - | - |
| `answer` | The first answer that passed the verifier. Without one, the most common submitted answer, or `None` |
| `success` | `True` or `False` when there is a verifier or a tool called `solve()`, otherwise `None` |
| `solved_by` | The member whose answer passed, or whose tool called `solve()` |
| `answers` | Each member's first submitted answer. Members that never answered are missing |
| `team_reward` | 1 on success, minus a token cost of up to `token_cost` (default 0.25). 0 on failure, `None` when ungraded |
| `tokens`, `total_tokens` | Output tokens per member and in total |
| `message_calls`, `broadcasts`, `messages` | How many messages were sent, how many went to `"all"`, and the full log with `t` in seconds since the start |
| `agents`, `communication`, `elapsed_seconds` | The member names, the `communication` setting and the wall-clock time |

The cost part of `team_reward` is `token_cost * min(1, total_tokens / (num_agents * max_tokens_per_agent))`. Here 291 tokens out of an allowance of 3 x 2048 cost about 1 percent.

## 3. Compare with a best-of-N baseline

`communication=False` gives the members no messaging tools and a solo prompt, so the run is N independent attempts. Run the same task both ways to see whether talking helps. Continuing from step 1:

```python theme={null}
solo = SelfOrganizingSwarm(
    num_agents=3,
    model_name="gpt-5.4-mini",
    communication=False,
    max_tokens_per_agent=2048,
    timeout=120.0,
)

solo_result = solo.run(
    task,
    private_inputs=private_inputs,
    verifier=is_correct,
    rules=rules,
)

print("swarm:", result["success"], result["team_reward"])
print("solo: ", solo_result["success"], solo_result["team_reward"])
print("solo answers:", solo_result["answers"])
```

Output from one run:

```
swarm: True 0.9881591796875
solo:  False 0.0
solo answers: {'agent_21': '[42]', 'agent_34': '[19]', 'agent_1': '[7]'}
```

Each solo member only knew its own number, so each submitted a list with one number in it.

## 4. Give members private tools that end the run

`task_tools` is a factory. The swarm calls it once per member as `task_tools(agent_name, solve)`, and it returns that member's own list of tools. When a tool calls `solve(answer)`, the team is marked solved and every member stops. No verifier is needed.

Here each member knows one digit of a lock code and has its own copy of the lock:

```python theme={null}
from typing import Callable, List

from swarms import SelfOrganizingSwarm

CODE = "583"


def lock_tools(agent_name: str, solve: Callable[..., None]) -> List[Callable]:
    """Build one member's private copy of the lock."""

    def try_code(code: str) -> str:
        """Try a three-digit code on the lock.

        Args:
            code: The three digits to try, for example "123".

        Returns:
            Whether the lock opened.
        """
        if code.strip() == CODE:
            solve(f"{code} opened by {agent_name}")
            return "The lock opened."
        return "Wrong code."

    return [try_code]


swarm = SelfOrganizingSwarm(
    num_agents=3,
    model_name="gpt-5.4-mini",
    max_tokens_per_agent=2048,
    timeout=120.0,
)

result = swarm.run(
    "The team must open a lock with a three-digit code. Each agent knows "
    "one digit. Share what you know, then open the lock with try_code.",
    private_inputs=[f"Digit {i + 1} of the code is {d}." for i, d in enumerate(CODE)],
    task_tools=lock_tools,
)

print(result["success"], result["solved_by"], result["answer"])
```

This prints something like `True agent_55 583 opened by agent_55`. The string passed to `solve()` becomes `answer`.

> [!NOTE]
>
> A tool that raises returns its error to the model as text. This stops the agent's tool retry from running the whole turn again and sending a message twice.

## 5. Run without a verifier

With no verifier and no `solve()` call, the run ends when every member is idle or finished. `success` and `team_reward` are `None`, and `answer` is the answer submitted most often.

```python theme={null}
from swarms import SelfOrganizingSwarm

swarm = SelfOrganizingSwarm(
    num_agents=3,
    model_name="gpt-5.4-mini",
    max_tokens_per_agent=2048,
    timeout=120.0,
)

result = swarm.run(
    "Name the largest planet in the solar system. Answer with one word."
)

print(result["success"], result["team_reward"])
print(result["answers"], "->", result["answer"])
```

Output:

```
None None
{'agent_59': 'Jupiter', 'agent_31': 'Jupiter', 'agent_60': 'Jupiter'} -> Jupiter
```

## How a run ends

The work phase ends when:

* an answer passes the verifier (with `stop_on_success=True`, the default),
* a task tool calls `solve()`,
* every member is idle or finished, or
* `timeout` runs out.

Members without an answer are then asked once for a final one. In that last step the final non-empty line of a reply counts as the answer if it has no `####` line. Pass `final_prompt=None` to skip it.

## Tips

* **Pick a tool-calling model.** Messaging and task tools are function calls.
* **Spell out the answer format in the task.** Members finish with `####`, and the verifier sees only the text after it.
* **Use `seed`** to make the member names and teammate order repeatable.
* **Pass agent settings through `agent_kwargs`.** Members are built with `print_on=False`, `reasoning_prompt_on=False`, `persistent_memory=False` and `tool_retry_attempts=1`; values you pass override these.
* **Use `verbose=True`** to log every message as it is sent.

## Next steps

* [SelfOrganizingSwarm reference](https://docs.swarms.world/api/self-organizing-swarm.md)
* [HierarchicalSwarm](https://docs.swarms.world/api/hierarchical-swarm.md), when you want a director to assign the work
* [MajorityVoting](https://docs.swarms.world/api/majority-voting.md), when members don't need each other's information


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