> ## 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.

# MajorityVoting Guide

> Ask several agents the same question at once, then have a consensus agent compare their answers and give the final verdict

`MajorityVoting` sends one task to a panel of agents at the same time. Each agent answers on its own. A consensus agent, which the swarm builds for you, then reads every answer, compares them, ranks them and writes the final answer. With more than one loop, the voters see the last consensus and can change their minds before the consensus agent decides again.

The swarm does not count votes in code. The consensus agent reads the answers and decides, so you control how it judges through its prompt.

Reference: [MajorityVoting](https://docs.swarms.world/api/majority-voting.md).

## 1. Run a vote

Give each voter its own `Agent` and a unique `agent_name`. Votes are stored by name, so the constructor raises `ValueError` if two voters share one. It also raises `ValueError` for an empty `agents` list or a `max_loops` below 1.

The consensus agent runs on `gpt-5.4` unless you set `consensus_agent_model_name`.

```python theme={null}
from swarms import Agent, MajorityVoting

voters = [
    Agent(
        agent_name="Backend-Engineer",
        system_prompt="You are a backend engineer. Answer in three sentences.",
        model_name="gpt-5.4-mini",
        max_loops=1,
    ),
    Agent(
        agent_name="SRE",
        system_prompt="You are a site reliability engineer. Answer in three sentences.",
        model_name="gpt-5.4-mini",
        max_loops=1,
    ),
    Agent(
        agent_name="Security-Engineer",
        system_prompt="You are a security engineer. Answer in three sentences.",
        model_name="gpt-5.4-mini",
        max_loops=1,
    ),
]

vote = MajorityVoting(
    name="Database-Vote",
    agents=voters,
    consensus_agent_model_name="gpt-5.4-mini",
)

messages = vote.run(
    "Should a 10-person startup use PostgreSQL or MongoDB for its "
    "first product? Pick one."
)

for message in messages:
    print(f"--- {message['role']}")
    print(message["content"][:300])
```

The voters run in parallel. Each one records only its final answer, not its whole conversation.

## 2. Read the output

`run` returns the vote's conversation, formatted by `output_type`. The default is `"dict"`, a list of `{"role", "content"}` messages in this order:

| Role | Content |
| - | - |
| `user` | The task |
| Each voter's `agent_name` | That voter's answer |
| `Consensus-Agent` | The evaluation of each answer, a ranked list and the final recommendation |

With more loops, the voter and consensus messages repeat once per loop. The role of the consensus message is `consensus_agent_name`, which defaults to `Consensus-Agent`.

Other useful values:

* `"final"` returns only the last consensus answer, as a string.
* `"str"` returns the whole conversation as one string, one `role: content` block per message.
* `"list"` and `"json"` give the same messages as a list or a JSON string.

Each `run` starts a fresh conversation, so reusing a `MajorityVoting` never mixes two tasks.

## 3. Let the panel revise its answers

Set `max_loops` above 1 to run more rounds. In each later round, every voter sees the task, its own earlier answers, the other voters' answers and the last consensus, each labelled with the speaker's name. The consensus agent then decides again. Here `output_type="final"` returns only the last decision.

```python theme={null}
from swarms import Agent, MajorityVoting

voters = [
    Agent(
        agent_name=f"Reviewer-{i}",
        system_prompt="You review product names. Answer with one name and one sentence why.",
        model_name="gpt-5.4-mini",
        max_loops=1,
    )
    for i in range(3)
]

vote = MajorityVoting(
    agents=voters,
    max_loops=2,
    output_type="final",
    consensus_agent_model_name="gpt-5.4-mini",
)

consensus = vote.run(
    "Pick the best name for a budgeting app for students: "
    "PennyWise, CampusCash or Stashly."
)
print(consensus)
```

A run makes `max_loops * (len(agents) + 1)` agent calls: every voter plus the consensus agent, once per loop.

## 4. Change how the consensus is reached

The default consensus prompt asks for an evaluation of each answer, a comparison, a ranked list and a final recommendation. For a strict tally, give the consensus agent your own prompt. The constructor also takes `consensus_agent_name`, `consensus_agent_description` and `additional_consensus_agent_kwargs`, which go to the consensus agent's `Agent` constructor.

Pass `streaming_callback` to `run` to stream the consensus agent's answer as it is written. The callback receives `(agent_name, chunk, is_final)`. Only the consensus agent streams; the voters do not, and `is_final` is always `False`.

```python theme={null}
from swarms import Agent, MajorityVoting

JUDGE_PROMPT = """
You count votes. Each panelist answers YES or NO.
Reply on one line with the tally and the majority answer,
for example: 2 YES, 1 NO. Majority: YES.
Do not add your own opinion.
"""

voters = [
    Agent(
        agent_name=name,
        system_prompt=f"You are a {name}. Start your answer with YES or NO, then give one sentence.",
        model_name="gpt-5.4-mini",
        max_loops=1,
    )
    for name in ["Product-Manager", "Data-Scientist", "Privacy-Lawyer"]
]


def on_chunk(agent_name: str, chunk: str, is_final: bool) -> None:
    print(chunk, end="", flush=True)


vote = MajorityVoting(
    agents=voters,
    output_type="final",
    consensus_agent_name="Tally-Agent",
    consensus_agent_prompt=JUDGE_PROMPT,
    consensus_agent_model_name="gpt-5.4-mini",
    additional_consensus_agent_kwargs={"max_tokens": 500},
)

vote.run(
    "Should we log full user prompts to improve our chatbot?",
    streaming_callback=on_chunk,
)
print()
```

> [!NOTE]
>
> Chunks that are only whitespace, such as a lone space or line break, are not passed to the callback, so a printed stream can miss some spaces and line breaks. The answer that `run` returns is complete.

## 5. Vote on an image

`run` takes `img`, which is sent to every voter with the task. Use a model that accepts images. The consensus agent reads only the voters' answers, not the image.

```python theme={null}
from swarms import Agent, MajorityVoting

LOGO_URL = "https://raw.githubusercontent.com/kyegomez/swarms/master/images/new_logo.png"

voters = [
    Agent(
        agent_name=f"Designer-{i}",
        system_prompt="You are a brand designer. Answer in two sentences.",
        model_name="gpt-5.4-mini",
        max_loops=1,
    )
    for i in range(3)
]

vote = MajorityVoting(
    agents=voters,
    output_type="final",
    consensus_agent_model_name="gpt-5.4-mini",
)

print(vote.run("Would this logo still read well at 16 pixels wide?", img=LOGO_URL))
```

## 6. Many tasks, async runs and token usage

`batch_run(tasks)` runs one vote per task, one after another, and returns a list of results in task order. `arun` is the async form of `run`: it awaits each voter's `arun` on the event loop, and `max_concurrency` caps how many voters call the model at once. It takes no `streaming_callback` or `img`.

`usage` sums the provider token counts of every voter and the consensus agent, across every run.

```python theme={null}
import asyncio

from swarms import Agent, MajorityVoting

voters = [
    Agent(
        agent_name=f"Classifier-{i}",
        system_prompt="Classify the ticket as BUG, BILLING or FEATURE. Reply with the label only.",
        model_name="gpt-5.4-mini",
        max_loops=1,
    )
    for i in range(3)
]

vote = MajorityVoting(
    agents=voters,
    output_type="final",
    consensus_agent_prompt="Reply with the label most panelists chose, and nothing else.",
    consensus_agent_model_name="gpt-5.4-mini",
)

tickets = [
    "I was charged twice this month.",
    "The export button does nothing on Safari.",
]

# One run per ticket, one after another
for ticket, label in zip(tickets, vote.batch_run(tickets)):
    print(f"{label:10} {ticket}")

# The async form, with at most two voters calling the model at once
label = asyncio.run(
    vote.arun("Please add a dark mode.", max_concurrency=2)
)
print(label)

print(vote.usage)
```

`usage` is a dict with `input_tokens`, `output_tokens`, `cached_tokens`, `reasoning_tokens` and `total_tokens`. See [Token usage](https://docs.swarms.world/agents/token-usage.md).

## Tips

* **Short, structured answers vote best.** Ask voters to start with a label such as `YES`, `NO` or a category, and tell the consensus agent to pick the most common one.
* **Mix models or prompts.** Voters with the same model and prompt tend to give the same answer. Different system prompts or models make the vote worth more.
* **Run one task at a time per panel.** Voters keep each run's turns in their own memory, so don't run two tasks on the same agents at once. For parallel tasks, build one `MajorityVoting` with its own agents per task.
* **Save the transcript.** With `autosave=True`, each run writes the conversation to a workspace folder, and `vote.swarm_workspace_dir` holds its path.

## Next steps

* [MajorityVoting reference](https://docs.swarms.world/api/majority-voting.md)
* [CouncilAsAJudge guide](https://docs.swarms.world/examples/multi-agent/council-as-a-judge-example.md), to grade one answer on several dimensions
* [LLMCouncil guide](https://docs.swarms.world/examples/multi-agent/llm-council-example.md), where members rank each other's answers
* [Runnable scripts](https://github.com/kyegomez/swarms/tree/master/examples/multi_agent/majority_voting)


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