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

# Group Chat Example

> Learn how to run an asynchronous, self-selecting agent groupchat for debates and multi-perspective reasoning

`GroupChat` creates an **asynchronous, self-selecting** room where every agent sees every message and independently decides whether to speak. There is no fixed speaking order — agents chime in only when their self-rated desire to respond clears a threshold. This is ideal for debates, brainstorming, and complex decision-making where you want natural, emergent dialogue rather than a rigid turn order.

<Note>
  This page reflects the current asynchronous `GroupChat`. The older turn-based design — `speaker_function`, `round-robin`/`random`/`priority` speakers, `@mention` routing, and interactive REPL sessions — has been **removed**. See the [GroupChat API reference](/api/group-chat) for the full parameter list.
</Note>

## How Group Chat Works

1. **Seed** — the task is broadcast to every agent's inbox as the first message.
2. **Self-selection** — for each message, every agent is asked (via a forced `respond(score, message)` tool call) how much it wants to speak, on a `0..1` scale.
3. **Threshold** — a reply is published only when its `score` exceeds `threshold` and the message is non-empty.
4. **Concurrent broadcast** — published replies wake every other agent's inbox at once; multiple agents can react to the same message in parallel.
5. **Stop condition** — the chat ends when `max_loops` total messages have been posted, or no new message arrives for `idle_timeout` seconds.

### Key Characteristics

* **Asynchronous**: agents listen in parallel; there is no global turn order.
* **Self-selecting**: silence is the default — agents only speak when they add value.
* **Shared context**: every agent sees the full transcript before deciding.
* **Bounded**: `max_loops` caps total messages; `idle_timeout` ends quiet chats.
* **Auto-equipped**: with `auto_equip=True` (default), the `respond` tool is injected into each agent for you.

## Key Parameters

| Parameter      | Purpose                                                                                             |
| -------------- | --------------------------------------------------------------------------------------------------- |
| `agents`       | Participating agents (**at least 2 required**).                                                     |
| `max_loops`    | Hard cap on total messages posted (the user task counts as the first). Default `20`.                |
| `threshold`    | Minimum decision score (`0..1`) to publish a reply. Default `0.5`. Raise for a more selective room. |
| `idle_timeout` | Seconds of silence before the chat stops. Default `8.0`.                                            |
| `output_type`  | History format. Default `"str-all-except-first"`. Use `"list"` or `"dict"` to iterate messages.     |
| `print_on`     | Print each broadcast as a styled panel. Default `True`.                                             |
| `auto_equip`   | Auto-inject the `respond` tool into agents that lack it. Default `True`.                            |

## Basic Example: Tech Debate

A two-sided debate about AI's societal impact. Each agent uses `max_loops=1` and `persistent_memory=False` so every speaking decision is a clean single-shot call.

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

tech_optimist = Agent(
    agent_name="TechOptimist",
    system_prompt="You argue for the benefits of AI in society.",
    model_name="gpt-5.4",
    max_loops=1,
    persistent_memory=False,
)

tech_critic = Agent(
    agent_name="TechCritic",
    system_prompt="You argue against the unchecked advancement of AI.",
    model_name="gpt-5.4",
    max_loops=1,
    persistent_memory=False,
)

chat = GroupChat(
    agents=[tech_optimist, tech_critic],
    max_loops=8,       # stop after 8 total messages
    threshold=0.5,     # publish replies scoring above 0.5
    idle_timeout=8.0,  # stop after 8s of silence
)

result = chat.run(
    "Let's discuss the societal impact of artificial intelligence."
)
print(result)
```

By default `result` is a formatted string (`output_type="str-all-except-first"`). To iterate over individual messages, set `output_type="list"`:

```python theme={null}
chat = GroupChat(
    agents=[tech_optimist, tech_critic],
    max_loops=8,
    output_type="list",
)

messages = chat.run("Discuss the societal impact of artificial intelligence.")

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

Each message dict carries `role` (the agent name, or `"User"` for the seed task) and `content`.

## Real-World Examples

### Business Strategy Discussion

Executives with distinct mandates weigh in only where they have something to add.

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

ceo = Agent(
    agent_name="CEO",
    system_prompt="Focus on long-term vision, mission, and stakeholder value.",
    model_name="gpt-5.4",
    max_loops=1,
    persistent_memory=False,
)
cfo = Agent(
    agent_name="CFO",
    system_prompt="Focus on financial viability, costs, revenue, and ROI.",
    model_name="gpt-5.4",
    max_loops=1,
    persistent_memory=False,
)
cto = Agent(
    agent_name="CTO",
    system_prompt="Focus on technical feasibility, architecture, and scalability.",
    model_name="gpt-5.4",
    max_loops=1,
    persistent_memory=False,
)
cmo = Agent(
    agent_name="CMO",
    system_prompt="Focus on market positioning, customer needs, and brand impact.",
    model_name="gpt-5.4",
    max_loops=1,
    persistent_memory=False,
)

exec_team = GroupChat(
    agents=[ceo, cfo, cto, cmo],
    max_loops=12,      # room for several rounds of contribution
    threshold=0.6,     # only fairly motivated replies get published
    idle_timeout=12.0,
)

discussion = exec_team.run(
    "Should we pivot from B2C to B2B and rebuild our product for enterprise "
    "customers? This would require 18 months and $5M investment."
)
print(discussion)
```

### Legal Contract Negotiation

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

buyer_attorney = Agent(
    agent_name="Buyer-Attorney",
    system_prompt="Represent the buyer. Negotiate favorable terms and minimize liability.",
    model_name="gpt-5.4",
    max_loops=1,
    persistent_memory=False,
)
seller_attorney = Agent(
    agent_name="Seller-Attorney",
    system_prompt="Represent the seller. Ensure fair payment and protect IP.",
    model_name="gpt-5.4",
    max_loops=1,
    persistent_memory=False,
)
mediator = Agent(
    agent_name="Mediator",
    system_prompt="Facilitate fair negotiation. Find common ground and propose compromises.",
    model_name="gpt-5.4",
    max_loops=1,
    persistent_memory=False,
)

negotiation = GroupChat(
    agents=[buyer_attorney, seller_attorney, mediator],
    max_loops=14,
    threshold=0.5,
)

contract_discussion = negotiation.run(
    "Negotiate a software licensing agreement. Key issues: payment terms "
    "(buyer wants net-60, seller wants net-30), liability cap (buyer wants $1M, "
    "seller wants $100K), and IP ownership of customizations."
)
print(contract_discussion)
```

### Medical Case Conference

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

attending = Agent(
    agent_name="Attending-Physician",
    system_prompt="Present the case and synthesize recommendations.",
    model_name="gpt-5.4",
    max_loops=1,
    persistent_memory=False,
)
cardiologist = Agent(
    agent_name="Cardiologist",
    system_prompt="Evaluate from a cardiovascular perspective.",
    model_name="gpt-5.4",
    max_loops=1,
    persistent_memory=False,
)
neurologist = Agent(
    agent_name="Neurologist",
    system_prompt="Evaluate from a neurological perspective.",
    model_name="gpt-5.4",
    max_loops=1,
    persistent_memory=False,
)
pharmacologist = Agent(
    agent_name="Pharmacologist",
    system_prompt="Evaluate drug interactions and medication recommendations.",
    model_name="gpt-5.4",
    max_loops=1,
    persistent_memory=False,
)

case_conference = GroupChat(
    agents=[attending, cardiologist, neurologist, pharmacologist],
    max_loops=12,
    threshold=0.6,  # specialists stay quiet outside their domain
)

case_discussion = case_conference.run(
    "Patient: 68-year-old male with hypertension and diabetes. Symptoms: severe "
    "headaches, dizziness, BP 180/110, slight confusion. Medications: metformin, "
    "lisinopril, aspirin. Discuss diagnosis and treatment plan."
)
print(case_discussion)
```

## Tuning the Conversation

Because there is no fixed turn order, you shape the conversation with `threshold`, `max_loops`, and `idle_timeout` rather than a speaker function.

### A livelier room

```python theme={null}
# Lower threshold → more agents chime in on each message.
brainstorm = GroupChat(
    agents=[copywriter, art_director, strategist, creative_director],
    max_loops=20,
    threshold=0.4,
    idle_timeout=10.0,
)
```

### A more selective room

```python theme={null}
# Higher threshold → only strongly-motivated, high-value replies are published.
focused = GroupChat(
    agents=[expert1, expert2, expert3],
    max_loops=10,
    threshold=0.75,
    idle_timeout=15.0,  # give agents time to deliberate
)
```

### Bounding total length

`max_loops` is the primary cost control — it caps the **total number of messages** posted (the seed task included), not the turns per agent.

```python theme={null}
# At most 6 messages total, then the chat stops.
quick = GroupChat(agents=[proponent, opponent], max_loops=6)
```

## Best Practices

### 1. Give each agent a distinct, specific role

```python theme={null}
# Good: a specific perspective the agent can defend.
agent = Agent(
    agent_name="Privacy-Advocate",
    system_prompt="You are a privacy advocate. Always weigh data protection, "
                  "consent, and privacy implications.",
    model_name="gpt-5.4",
    max_loops=1,
    persistent_memory=False,
)
```

Distinct roles make the `respond` decision meaningful — agents speak inside their lane and stay quiet outside it.

### 2. Use `max_loops=1` and `persistent_memory=False` per agent

Each participating agent should make a clean, single-shot decision per message. Stateful memory across decisions can distort the speaking score.

### 3. Tune `threshold` to the room size

* **Few agents (2–3)**: a lower threshold (`~0.4–0.5`) keeps the dialogue flowing.
* **Many agents (4+)**: raise it (`~0.6–0.75`) so the room doesn't pile on every message.

### 4. Set `idle_timeout` to match thinking time

Raise it when models need longer to reason; lower it to end quiet chats faster.

### 5. Choose the right `output_type`

* `"str-all-except-first"` (default) — a single readable transcript string.
* `"list"` / `"dict"` — structured messages you can iterate (`role`, `content`).

## When to Use Group Chat

Ideal for:

* **Debates and discussions** — exploring opposing viewpoints.
* **Collaborative decision-making** — stakeholders converging on consensus.
* **Brainstorming** — emergent ideas from parallel contributions.
* **Negotiation** — parties working toward agreement.
* **Peer review** — evaluating work from multiple angles.

## When NOT to Use Group Chat

* **Simple tasks** — the coordination overhead isn't justified (use a single `Agent`).
* **Independent analysis** — when agents shouldn't influence each other (use `ConcurrentWorkflow`).
* **Strict ordering** — when a fixed sequence is required (use `SequentialWorkflow`).
* **Hierarchical coordination** — when a director must delegate (use `HierarchicalSwarm`).

## Comparison with Other Patterns

| Pattern                | Interaction Style                     | Best For                           |
| ---------------------- | ------------------------------------- | ---------------------------------- |
| **GroupChat**          | Asynchronous, self-selecting dialogue | Debates, brainstorms, negotiations |
| **MixtureOfAgents**    | Parallel → synthesis                  | Combining expert analyses          |
| **HierarchicalSwarm**  | Director → workers                    | Project coordination               |
| **SequentialWorkflow** | Linear pipeline                       | Step-by-step processes             |
| **ConcurrentWorkflow** | Independent parallel                  | Multi-perspective analysis         |

## Related Architectures

* **[MixtureOfAgents](/examples/mixture-of-agents-example)**: parallel experts with synthesis
* **[HierarchicalSwarm](/examples/hierarchical-swarm-example)**: director-worker coordination
* **[ConcurrentWorkflow](/examples/concurrent-workflow-example)**: independent parallel execution

## Learn More

* [GroupChat API Reference](/api/group-chat)
* [Multi-Agent Architectures Overview](/architectures/overview)
