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

# SocialAlgorithms Guide

> Write a plain Python function that decides which agent talks to which, and get every message recorded for you

`SocialAlgorithms` runs your own Python function over a group of agents. The function, called a social algorithm, decides who speaks, in what order and with what input. It can be a pipeline, a review loop, a vote or anything else you can write in Python.

While your function runs, every agent call is recorded into one transcript, so you don't have to collect the messages yourself. `run` returns that transcript, ending with whatever your function returned.

Reference: [SocialAlgorithms](https://docs.swarms.world/api/social-algorithms.md).

## 1. Write an algorithm

A social algorithm is any callable that takes `(agents, task, **kwargs)`. It receives the agents in the order you passed them. Here a researcher gathers facts, a critic checks them and a writer turns both into a summary:

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


def agent(name: str, system_prompt: str) -> Agent:
    """Build a one-loop agent whose run returns only its reply."""
    return Agent(
        agent_name=name,
        system_prompt=f"{system_prompt} Keep it under 80 words.",
        model_name="gpt-5.4-mini",
        max_loops=1,
        output_type="final",
    )


def research_then_write(agents, task, **kwargs):
    """The researcher gathers facts, the critic checks them, the writer drafts."""
    researcher, critic, writer = agents

    facts = researcher.run(f"List the key facts about: {task}")
    review = critic.run(f"Point out anything wrong or missing:\n{facts}")
    return writer.run(
        f"Write a short summary of {task}.\nFacts:\n{facts}\nReview:\n{review}"
    )


team = SocialAlgorithms(
    name="Research-Team",
    agents=[
        agent("Researcher", "You gather facts as bullet points."),
        agent("Critic", "You check facts for errors and gaps."),
        agent("Writer", "You write clear, plain summaries."),
    ],
    social_algorithm=research_then_write,
)

messages = team.run("the history of the QWERTY keyboard")

for message in messages:
    print(f"--- {message['role']} at {message['timestamp']}")
    print(str(message["content"])[:200])
```

`output_type="final"` on each agent makes `agent.run` return only the reply. With the `Agent` default, `run` returns more of the agent's conversation, which grows each time your algorithm calls the same agent again.

The constructor raises `ValueError` if `agents` is empty or holds anything that is not an `Agent`, and `InvalidAlgorithmError` if `social_algorithm` is not callable. `run` raises `InvalidAlgorithmError` if no algorithm was set.

## 2. Read the transcript

`run` returns the transcript, formatted by `output_type`. The default is `"dict"`, a list of messages, each with `role`, `content` and an ISO `timestamp`:

| Role | Content |
| - | - |
| `User` | The task |
| An agent's `agent_name` | That agent's reply, once for every call your algorithm made |
| The algorithm's `name` | Whatever your function returned |

Every call is recorded with the agent's final reply, whatever the agent's own `output_type`. You don't need to report anything from your function.

Other `output_type` values:

* `"final"` returns the last message, which is your function's return value, as it was returned. A dict stays a dict.
* `"str"` returns the transcript as one string, one `[timestamp] role: content` line per message.
* `"list"`, `"json"` and `"yaml"` give the messages in those formats.

## 3. Pass settings to the algorithm

Anything extra your algorithm needs goes in `algorithm_args`, as a dict, or as keyword arguments to `run`. The function is called as `social_algorithm(agents, task, **algorithm_args, **kwargs)`, and a keyword argument wins when both set the same name. Here a writer and an editor refine a pitch for a set number of rounds:

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


def refine(agents, task, rounds=1, audience="engineers", **kwargs):
    """The writer drafts, then revises once per round after the editor's notes."""
    writer, editor = agents

    draft = writer.run(f"Write a two-sentence pitch for {audience}: {task}")
    for _ in range(rounds):
        notes = editor.run(f"Give two short notes to improve this pitch:\n{draft}")
        draft = writer.run(f"Revise the pitch using these notes:\n{notes}\n\nPitch:\n{draft}")

    return {"pitch": draft, "rounds": rounds}


writer = Agent(
    agent_name="Writer",
    system_prompt="You write short product pitches.",
    model_name="gpt-5.4-mini",
    max_loops=1,
    output_type="final",
)
editor = Agent(
    agent_name="Editor",
    system_prompt="You give blunt, specific editing notes.",
    model_name="gpt-5.4-mini",
    max_loops=1,
    output_type="final",
)

loop = SocialAlgorithms(
    name="Pitch-Refiner",
    agents=[writer, editor],
    social_algorithm=refine,
    output_type="final",
)

result = loop.run(
    "a tool that turns log files into incident timelines",
    algorithm_args={"rounds": 2, "audience": "managers"},
    audience="site reliability engineers",
)
print(result)
```

The pitch is written for site reliability engineers, because the keyword argument overrides `algorithm_args`. With `output_type="final"`, `result` is the dict the function returned. `algorithm_args` itself is never changed.

## 4. Agents talking to agents

`agent.talk_to(other, message)` has one agent think about a message and then send its reply to another agent. Inside a social algorithm it is recorded in three steps: the outgoing message under the sender's name, with the receiver in the message's `metadata`, then the sender's reply, then the receiver's reply.

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


def ask_the_expert(agents, task, **kwargs):
    """The junior asks the senior for help through talk_to."""
    junior, senior = agents
    return junior.talk_to(senior, task)


junior = Agent(
    agent_name="Junior",
    system_prompt="You are a junior developer. Turn the problem into one clear question.",
    model_name="gpt-5.4-mini",
    max_loops=1,
    output_type="final",
)
senior = Agent(
    agent_name="Senior",
    system_prompt="You are a senior developer. Answer in under 60 words.",
    model_name="gpt-5.4-mini",
    max_loops=1,
    output_type="final",
)

pair = SocialAlgorithms(
    name="Help-Desk",
    agents=[junior, senior],
    social_algorithm=ask_the_expert,
)
pair.run("My Python script gets slower every hour it runs.")

for message in pair.get_communication_history():
    receiver = message.get("metadata", {}).get("receiver_agent")
    arrow = f" -> {receiver}" if receiver else ""
    print(f"--- {message['role']}{arrow}")
    print(str(message["content"])[:150])
```

`get_communication_history()` returns a copy of the transcript as a list of message dicts, whatever the `output_type`.

Recording works by wrapping each agent's `run` and `talk_to` for the length of the call, and putting them back afterwards, even when the algorithm fails. Agents outside this `SocialAlgorithms` are never touched.

## 5. Reuse, clear and change the group

The transcript is kept across runs: a second `run` adds its task and messages after the first run's. Call `clear_communication_history()` to start over. `add_agent` and `remove_agent` change the group between runs, and `get_algorithm_info()` describes the setup. This continues from section 4:

```python theme={null}
pair.run("Our CI pipeline takes 40 minutes.")
print(len(pair.get_communication_history()), "messages after two runs")

pair.clear_communication_history()
print(len(pair.get_communication_history()), "messages after clearing")

pair.add_agent(
    Agent(
        agent_name="Reviewer",
        model_name="gpt-5.4-mini",
        max_loops=1,
    )
)
pair.remove_agent("Reviewer")
print(pair.get_algorithm_info())
```

`remove_agent` raises `AgentNotFoundError` for a name that is not in the group. Import it, and the other exceptions, from `swarms.structs.social_algorithms`.

## Tips

* **Handle failures in your function.** An error from your algorithm or from an agent is logged and raised from `run`. Catch it inside the algorithm if the rest of the run should go on.
* **Build in a time limit yourself.** There is no built-in timeout, so put one in your algorithm if it needs one, for example a cap on rounds.
* **Track cost** with `usage`, which sums the token counts of every agent in the group across every run.
* **Turn on logs** with `verbose=True` to log each recorded message and how long the run took.

## Next steps

* [SocialAlgorithms reference](https://docs.swarms.world/api/social-algorithms.md)
* [Social swarm patterns](https://docs.swarms.world/examples/social-swarm-patterns.md), ready-made broadcast, circular and grid patterns
* [Runnable scripts](https://github.com/kyegomez/swarms/tree/master/examples/multi_agent/social_algorithms_examples)


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