swarms
Build agents and multi-agent systems with the Swarms framework — the Agent class, tools, autonomous loops, memory, and the 15+ multi-agent architectures (SequentialWorkflow, ConcurrentWorkflow, GraphWorkflow, HierarchicalSwarm, SwarmRouter, and more). Use whenever writing, reviewing, or debugging code that imports `swarms`.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/kyegomez/swarms with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/kyegomez/swarms'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/kyegomez--swarms)HTML
<a href="/listings/kyegomez--swarms"><img src="/api/listings/kyegomez--swarms/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
# pip $ pip3 install -U swarms # uv (recommended): https://github.com/astral-sh/uv $ uv pip install swarms # poetry $ poetry add swarms
From source
# Clone the repository $ git clone https://github.com/kyegomez/swarms.git $ cd swarms $ pip install -r requirements.txt
Faster model calls and graphs with `swarms[fast]`
`swarms[fast]` adds two optional speedups:
- [RouteHub](https://github.com/The-Swarm-Corporation/RouteHub) for faster model calls through a drop-in LLM gateway. No code changes needed. To switch back to litellm, set `SWARMS_LLM_BACKEND=litellm`. - [rustworkx](https://github.com/Qiskit/rustworkx), a graph library written in Rust, for faster `GraphWorkflow` graphs. Turn it on with `GraphWorkflow(backend="rustworkx")`.
$ pip3 install -U "swarms[fast]"
Using Docker
The official image, [`swarmscorp/swarms`](https://hub.docker.com/r/swarmscorp/swarms) on Docker Hub, has swarms and its CLI installed on Python 3.13, for `linux/amd64` and `linux/arm64`.
# Pull the image $ docker pull swarmscorp/swarms:latest # Run a script from the current directory, passing your API key from the shell $ docker run --rm -e OPENAI_API_KEY -v "$PWD:/app" swarmscorp/swarms python agent.py # Open a Python shell with swarms installed $ docker run -it --rm -e OPENAI_API_KEY swarmscorp/swarms
To build the image yourself, run `docker build -t swarms .` from the repository root.
---
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
SKILL.md · Manifest · 645 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- ---
- name: swarms
- description: Build agents and multi-agent systems with the Swarms framework — the Agent class, tools, autonomous loops, memory, and the 15+ multi-agent architectures (SequentialWorkflow, ConcurrentWorkflow, GraphWorkflow, HierarchicalSwarm, SwarmRouter, and more). Use whenever writing, reviewing, or debugging code that imports `swarms`.
- ---
- # Swarms
- Swarms is a multi-agent orchestration framework. Everything is built from one primitive — `Agent` — which multi-agent structures compose. This document is verified against **swarms v14.0.0**.
- ## Live documentation
- This skill can lag the library. When a signature here disagrees with the installed version, check the current docs:
- - Docs MCP server, no key: `https://docs.swarms.world/mcp` (`claude mcp add --transport http swarms-docs https://docs.swarms.world/mcp`)
- - Marketplace MCP server, Swarms API key for calls: `https://swarms.world/mcp`
- - Plain-text docs: [llms.txt](https://docs.swarms.world/llms.txt) (index), [llms-full.txt](https://docs.swarms.world/llms-full.txt) (every page)
- ## Golden rules
- 1. **Import from the top level**: `from swarms import Agent`, never `from swarms.structs.agent import Agent`. The one common exception is `PlannerWorkerSwarm` (see below).
- 2. **Every agent needs a unique `agent_name`** — memory files and swarm routing key on it.
- 3. **Default to `max_loops=1`.** Use a specific integer for production. Use `"auto"` only for genuinely open-ended work.
- 4. **Pass `tools=None`, not `tools=[]`.** An empty list breaks schema generation.
- 5. **Check `examples/`** — 586 runnable examples live there. One is probably close to what you need.
- 6. **Never set `streaming_on=True` and `streaming_callback` together.** Pick one.
- ## Setup
- ```bash
- pip install -U swarms
- ```
- Set the key for whichever provider you use — any [LiteLLM](https://docs.litellm.ai/docs/providers) model string works:
- ```bash
- export OPENAI_API_KEY="sk-..."
- export ANTHROPIC_API_KEY="sk-ant-..."
- export GROQ_API_KEY="..."
- export WORKSPACE_DIR="agent_workspace" # where agent state and memory land
- ```
- ---
- # Part 1 — The Agent
- ```python
- from swarms import Agent
- agent = Agent(
- agent_name="Analyst",
- agent_description="Analyzes market data and produces summaries.",
- system_prompt="You are a precise financial analyst.",
- model_name="gpt-5.4",
- max_loops=1,
- )
- result = agent.run("Summarize the state of the semiconductor market.")
- ```
- `Agent.__init__` accepts 90+ parameters. These are the ones that matter:
- | Parameter | Type | Default | Purpose |
- |---|---|---|---|
- | `agent_name` | `str` | `"swarm-worker-01"` | Unique identity; keys memory + routing |
- | `agent_description` | `str` | generic | How orchestrators decide to route to it |
- | `system_prompt` | `str` | built-in | Persona and instructions |
- | `model_name` | `str` | `"gpt-5.4"` | Any LiteLLM model string |
- | `max_loops` | `int \| "auto"` | `1` | Iterations, or autonomous mode |
- | `tools` | `list[Callable]` | `None` | Python functions the agent may call |
- | `temperature` | `float` | `0.5` | Sampling temperature |
- | `max_tokens` | `int` | model max | Output cap per call |
- | `top_p` | `float` | `None` | Nucleus sampling |
- | `context_length` | `int` | `None` | Token budget; triggers compression at 90% |
- | `output_type` | `str` | `"str-all-except-first"` | Return shape — see below |
- | `streaming_on` | `bool` | `False` | Stream tokens to stdout |
- | `streaming_callback` | `Callable` | `None` | Stream tokens to your function |
- | `interactive` | `bool` | `False` | REPL — prompts the user each loop |
- | `verbose` | `bool` | `False` | Debug logging |
- | `print_on` | `bool` | `True` | Print the final output |
- | `autosave` | `bool` | `False` | Persist agent state after each run |
- | `retry_attempts` | `int` | `3` | LLM call retries |
- | `reasoning_effort` | `str` | `None` | `minimal`/`low`/`medium`/`high`/`xhigh`/`ultra`/`max`/`none` |
- | `thinking_tokens` | `int` | `1024` | Extended thinking budget (Claude) |
- | `mcp_url` / `mcp_urls` | `str` / `list[str]` | `None` | MCP servers to load tools from |
- | `handoffs` | `list[Agent]` | `None` | Agents this one may delegate to |
- | `persistent_memory` | `bool` | `False` | Read/write `MEMORY.md` across restarts |
- | `context_compression` | `bool` | `True` | Auto-summarize near the context limit |
- | `plan_enabled` | `bool` | `False` | Plan before executing |
- | `mode` | `str` | `"standard"` | `"standard"`, `"fast"`, `"interactive"` |
- | `fallback_models` | `list[str]` | `None` | Models to try if the primary fails |
- **`output_type` options**: `"str"`, `"list"`, `"dict"`, `"json"`, `"yaml"`, `"final"`, `"last"`, `"all"`, `"str-all-except-first"`, `"dict-all-except-first"`, `"dict-final"`, `"list-final"`.
- ### Running
- ```python
- agent.run(task="...") # standard
- agent.run(task="...", img="chart.png") # one image
- agent.run(task="...", imgs=["a.png", "b.png"]) # several images
- agent.run(task="...", n=3) # 3 independent samples
- await agent.arun("...") # async
- ```
- `Agent.run` signature: `run(task=None, img=None, imgs=None, streaming_callback=None, n=1, messages=None)`.
- ### Streaming
- ```python
- # To stdout
- agent = Agent(agent_name="Writer", model_name="gpt-5.4", streaming_on=True)
- agent.run("Write a haiku about distributed systems.")
- # To a callback (do NOT combine with streaming_on)
- def on_token(token: str) -> None:
- print(token, end="", flush=True)
- agent = Agent(agent_name="Writer", model_name="gpt-5.4", streaming_callback=on_token)
- agent.run("Write a haiku.")
- # Async streaming
- async for token in agent.arun_stream("Explain async/await."):
- print(token, end="", flush=True)
- ```
- ---
- # Part 2 — Tools
- Any Python function with type hints and a docstring becomes a tool. The framework generates the OpenAI function schema automatically — **the docstring is the tool description the model reads, so write it for the model.**
- ```python
- from swarms import Agent
- def get_stock_price(ticker: str) -> str:
- """Fetch the current stock price for a ticker symbol.
- Args:
- ticker: Stock ticker symbol, e.g. 'AAPL'.
- Returns:
- The current price as a formatted string.
- """
- import yfinance as yf
- return f"{ticker}: ${yf.Ticker(ticker).fast_info['last_price']:.2f}"
- agent = Agent(
- agent_name="StockAnalyst",
- model_name="gpt-5.4",
- tools=[get_stock_price],
- max_loops=3, # needs > 1 so it can act on the tool result
- )
- agent.run("What are Apple and Microsoft trading at?")
- ```
- **`max_loops` must exceed 1 for tool use** — loop 1 calls the tool, loop 2 uses the result.
- Related knobs: `tool_call_summary=True` (summarize tool output), `show_tool_execution_output=True` (print raw returns), `tool_retry_attempts` (retries on tool failure).
- ### MCP servers
- ```python
- agent = Agent(
- agent_name="MCPAgent",
- model_name="gpt-5.4",
- mcp_url="http://localhost:8000/sse",
- # or: mcp_urls=["http://localhost:8000/sse", "http://localhost:8001/sse"]
- max_loops=3,
- )
- ```
- Inspect what a server exposes before wiring it up:
- ```python
- from swarms.tools.mcp_manager import MCPManager
- mgr = MCPManager(mcp_url="http://localhost:8000/sse")
- print(mgr.list_tool_names())
- schemas = mgr.get_tools() # aget_tools() for the async form
- ```
- ### Handoffs
- Give an agent a roster it can delegate to. It receives a `handoff_task` tool automatically.
- ```python
- triage = Agent(
- agent_name="Triage",
- model_name="gpt-5.4",
- handoffs=[billing_agent, technical_agent, refunds_agent],
- max_loops=3,
- )
- triage.run("My invoice is wrong and the app won't load.")
- ```
- ---
- # Part 3 — Autonomous mode (`max_loops="auto"`)
- The agent runs plan → execute → reflect until it decides it is finished, with **16 built-in tools** available:
- | Group | Tools |
- |---|---|
- | Planning | `create_plan`, `think`, `subtask_done`, `complete_task`, `respond_to_user` |
- | Files | `create_file`, `update_file`, `read_file`, `list_directory`, `delete_file` |
- | System | `run_bash`, `grep` |
- | Delegation | `create_sub_agent`, `assign_task`, `check_sub_agent_status`, `cancel_sub_agent_tasks` |
- ```python
- agent = Agent(
- agent_name="Researcher",
- model_name="gpt-5.4",
- max_loops="auto",
- tools=[search_web], # your tools stack on top of the built-ins
- persistent_memory=True,
- context_compression=True,
- context_length=32000,
- )
- agent.run("Research the top 5 vector databases and write compare.md")
- ```
- Restrict the built-in set with `selected_tools` (default `"all"`):
- ```python
- agent = Agent(
- agent_name="ReadOnly",
- max_loops="auto",
- selected_tools=["create_plan", "think", "read_file", "grep", "complete_task"],
- )
- ```
- Inspect the full list at runtime with `agent.get_all_selected_tools()`.
- ⚠️ **`run_bash` and `delete_file` are real.** In autonomous mode the agent can modify and delete files and execute shell commands. Scope `selected_tools` and set `WORKSPACE_DIR` deliberately.
- ---
- # Part 4 — Memory and conversation
- ### Persistent memory
- `persistent_memory=True` reads `{WORKSPACE_DIR}/agents/{agent_name}/MEMORY.md` on startup and appends to it each response. It is **off by default** — set it in every process that should share the memory.
- ```python
- agent = Agent(agent_name="ProjectAssistant", model_name="gpt-5.4", persistent_memory=True)
- agent.run("My project is called Helios. Remember that.")
- # Later process, same agent_name and the flag set again → it remembers.
- ```
- ### Context compression
- `context_compression=True` (default) fires at 90% of `context_length`, summarizing history in place so long sessions never hit the wall. Leave it on for anything long-running.
- ### Conversation
- ```python
- from swarms import Conversation
- conv = Conversation(
- name="my-conversation", # note: `name`, not `agent_name`
- system_prompt="You are helpful.",
- time_enabled=True,
- token_count=True,
- )
- conv.add("user", "What is 2+2?")
- conv.add("assistant", "4.")
- conv.return_history_as_string()
- conv.search("2+2")
- conv.compact(summary="User asked arithmetic. Answer: 4.") # archives, then collapses
- conv.save_as_json("conv.json")
- ```
- ---
- # Part 5 — Multi-agent architectures
- ## Choosing one
- | Situation | Use |
- |---|---|
- | Single task | `Agent` |
- | Linear A→B→C | `SequentialWorkflow` |
- | Same task, many agents at once | `ConcurrentWorkflow` |
- | Custom mix of sequential + parallel | `AgentRearrange` |
- | Dependency graph / fan-out-fan-in | `GraphWorkflow` |
- | Many models, one synthesized answer | `MixtureOfAgents` |
- | Manager delegates to specialists | `HierarchicalSwarm` |
- | Open discussion | `GroupChat` |
- | Discrete decision by consensus | `MajorityVoting` |
- | Quality-critical evaluation | `CouncilAsAJudge` |
- | Structured adversarial debate | `DebateWithJudge` |
- | Deep multi-stage research | `HeavySwarm` |
- | Route each task to the best agent | `MultiAgentRouter` |
- | Plan then execute with workers | `PlannerWorkerSwarm` |
- | Don't know yet | `SwarmRouter(swarm_type="auto")` or `AutoSwarmBuilder` |
- ## SequentialWorkflow
- Each agent's output becomes the next agent's context.
- ```python
- from swarms import Agent, SequentialWorkflow
- pipeline = SequentialWorkflow(
- agents=[researcher, analyst, writer],
- max_loops=1,
- output_type="dict",
- )
- pipeline.run("Analyze how rate hikes affect tech stocks.")
- ```
- Options: `team_awareness=True` (agents see the roster), `multi_agent_collab_prompt=True`, `drift_detection=True`.
- ## ConcurrentWorkflow
- All agents run the same task in parallel.
- ```python
- from swarms import Agent, ConcurrentWorkflow
- workflow = ConcurrentWorkflow(
- agents=agents,
- max_workers=5,
- show_dashboard=True,
- on_error="store", # or "raise"
- )
- workflow.run("List 10 use cases for multi-agent AI.")
- ```
- ## AgentRearrange — flow DSL
- ```python
- from swarms import Agent, AgentRearrange
- pipeline = AgentRearrange(
- agents=[planner, coder, reviewer, tester],
- flow="Planner -> Coder -> Reviewer, Tester",
- max_loops=1,
- )
- pipeline.run("Build an email validator.")
- ```
- - `A -> B` — sequential, B receives A's output
- - `A, B` — concurrent, same input
- - `A -> B, C -> D` — A, then B and C in parallel, then D on their combined output
- **Every name in `flow` must match an `agent_name` in `agents`**, or it fails at run time. There is no human-in-the-loop step — split into separate `.run()` calls and insert your own `input()` between them.
- ## GraphWorkflow — DAG
- Pass agents directly to `add_node`/`add_edge`; there is no need to wrap them in `Node` objects.
- ```python
- from swarms import Agent, GraphWorkflow
- wf = GraphWorkflow(name="research-dag", max_loops=1)
- for a in (ingestion, branch_a, branch_b, merger):
- wf.add_node(a)
- wf.add_edge(ingestion, branch_a) # fan out
- wf.add_edge(ingestion, branch_b)
- wf.add_edge(branch_a, merger) # fan in
- wf.add_edge(branch_b, merger)
- wf.set_entry_points(["Ingestion"])
- wf.set_end_points(["Merger"])
- def on_done(node: str, result) -> None:
- print(f"[{node}] {len(str(result))} chars")
- results = wf.run(task="Analyze this dataset two ways and merge.", on_node_complete=on_done)
- ```
- `add_node` also accepts a nested `GraphWorkflow`. Other options: `backend="networkx"|"rustworkx"`, `max_parallel_nodes`, `checkpoint_dir`, `streaming_callback`.
- ## SwarmRouter — one entry point
- Swap architectures without rewriting orchestration.
- ```python
- from swarms import Agent, SwarmRouter
- router = SwarmRouter(agents=agents, swarm_type="SequentialWorkflow", max_loops=1)
- router.run("Write a post about transformers.")
- ```
- Valid `swarm_type` values — **exactly these 16**:
- `"AgentRearrange"`, `"MixtureOfAgents"`, `"SequentialWorkflow"`, `"ConcurrentWorkflow"`, `"GroupChat"`, `"MultiAgentRouter"`, `"HierarchicalSwarm"`, `"MajorityVoting"`, `"CouncilAsAJudge"`, `"HeavySwarm"`, `"BatchedGridWorkflow"`, `"LLMCouncil"`, `"DebateWithJudge"`, `"RoundRobin"`, `"PlannerWorkerSwarm"`, `"auto"`.
- `"AutoSwarmBuilder"` and `"SpreadSheetSwarm"` are **not** router types — use those classes directly. With `swarm_type="AgentRearrange"` you must also pass `rearrange_flow`.
- ## MixtureOfAgents
- Workers answer independently; an aggregator synthesizes. Best with diverse providers.
- ```python
- from swarms import Agent, MixtureOfAgents
- moa = MixtureOfAgents(
- agents=[worker_gpt, worker_claude, worker_llama],
- aggregator_agent=aggregator, # optional; falls back to aggregator_model_name
- layers=3,
- max_loops=1,
- )
- moa.run("Best practices for securing a Kubernetes cluster?")
- ```
- ## HierarchicalSwarm
- A director decomposes the task, delegates, and synthesizes results.
- ```python
- from swarms import Agent, HierarchicalSwarm
- swarm = HierarchicalSwarm(
- agents=[data_worker, writing_worker, review_worker],
- director=director, # optional; else built from director_model_name
- max_loops=2,
- planning_enabled=True,
- parallel_execution=True,
- director_feedback_on=True,
- )
- swarm.run("Produce a competitive analysis of the AI chip market.")
- ```
- Also: `agent_as_judge=True`, `max_agent_retries`, `max_reassignment_attempts`, `interactive=True`.
- ## GroupChat
- Asynchronous and self-selecting — no rounds, no speaker-selection function. Every agent scores how much it wants to speak (0–1); replies above `threshold` are broadcast. Ends at `max_loops` messages or when no reply clears `threshold`.
- ```python
- from swarms import Agent, GroupChat
- chat = GroupChat(
- agents=[optimist, pessimist, realist], # at least 2 required
- max_loops=10,
- threshold=0.5, # raise for a more selective room
- recency_penalty=0.3, # discourages one agent dominating
- )
- chat.run("Should we adopt AI for medical diagnosis?")
- ```
- `auto_equip=True` (default) injects the required `RESPOND_TOOL` into every agent — **you do not need to pass it yourself**. Set `auto_equip=False` only if you attach `RESPOND_TOOL` manually via `tools_list_dictionary`.
- ## MajorityVoting
- Agents answer independently; a consensus agent picks the winner.
- ```python
- from swarms import Agent, MajorityVoting
- mv = MajorityVoting(
- agents=voters,
- consensus_agent_model_name="gpt-5.4",
- max_loops=1,
- )
- mv.run("Python or Rust for a high-performance web server?")
- ```
- ## CouncilAsAJudge
- Evaluates a response across dimensions. **It builds its own council from model names — it does not take an `agents` list or a `judge` agent.**
- ```python
- from swarms import CouncilAsAJudge
- council = CouncilAsAJudge(
- model_name="gpt-5.4",
- aggregation_model_name="gpt-5.4",
- random_model_name=True,
- max_loops=1,
- )
- council.run("Should we store biometric data on-device only?")
- ```
- ## DebateWithJudge
- ```python
- from swarms import Agent, DebateWithJudge
- debate = DebateWithJudge(
- pro_agent=pro,
- con_agent=con,
- judge_agent=judge,
- max_loops=3, # rounds
- )
- debate.run("Motion: open-source LLMs will surpass closed-source by 2027.")
- ```
- `preset_agents=True` generates pro/con/judge for you from `model_name`. The kwargs are `pro_agent`/`con_agent`/`judge_agent` — **not** `agents=[...]` plus `judge=`.
- ## HeavySwarm
- Deep multi-stage analysis. **Configured by model names, not by an `agents` list.**
- ```python
- from swarms import HeavySwarm
- swarm = HeavySwarm(
- question_agent_model_name="gpt-5.4",
- worker_model_name="gpt-5.4",
- max_loops=1,
- timeout=900,
- show_dashboard=True,
- worker_tools=[search_web],
- )
- swarm.run("Analyze the implications of AGI on global labour markets.")
- ```
- ## PlannerWorkerSwarm
- A planner decomposes the task and workers execute; a judge checks completion each cycle. **Not exported at the top level:**
- ```python
- from swarms.structs.planner_worker_swarm import PlannerWorkerSwarm
- swarm = PlannerWorkerSwarm(
- agents=workers, # workers only — the planner is built internally
- planner_model_name="gpt-5.4",
- judge_model_name="gpt-5.4",
- max_planner_depth=1,
- max_loops=1,
- )
- swarm.run("Build a go-to-market strategy for a B2B SaaS product.")
- ```
- ## Others
- ```python
- from swarms import (
- MultiAgentRouter, # routes each task to the best-fit agent
- RoundRobinSwarm, # fixed rotation
- LLMCouncil, # members answer, rank peers anonymously, chairman synthesizes
- BatchedGridWorkflow, # agent i runs task i
- AutoSwarmBuilder, # generates the agents and architecture from a description
- SpreadSheetSwarm, # structured tabular processing
- AdvisorSwarm, SelfMoASeq, HybridHierarchicalClusterSwarm,
- )
- builder = AutoSwarmBuilder(name="MarketResearch", description="...", max_loops=1)
- builder.run("Research the EV market and find growth opportunities.")
- ```
- ---
- # Part 6 — Execution helpers
- ```python
- from swarms import (
- run_agents_concurrently,
- run_agents_with_different_tasks,
- run_agents_concurrently_async,
- batch_agent_execution,
- run_single_agent,
- aggregate,
- )
- run_agents_concurrently(agents=agents, task="Summarize today's news.", max_workers=8)
- run_agents_with_different_tasks([(agent_a, "task A"), (agent_b, "task B")]) # list of tuples
- batch_agent_execution(agents=agents, tasks=tasks, max_workers=10)
- aggregate(workers=agents, task="...", aggregator_model_name="gpt-5.4")
- ```
- Note `run_agents_with_different_tasks` takes a **list of `(agent, task)` tuples**, not a dict.
- ## Scheduling
- ```python
- from swarms import CronJob
- job = CronJob(agent=agent, interval="10minutes", job_id="market-check")
- job.run(task="Check for unusual market activity.")
- ```
- `interval` is `"<number><unit>"`, and the unit must be one of `second`, `seconds`, `minute`, `minutes`, `hour`, `hours`. Abbreviations like `"30s"` raise `CronJobConfigError`, as does a zero interval.
- ## Loading agents from files
- ```python
- from swarms import AgentLoader
- loader = AgentLoader(concurrent=True)
- agents = loader.load_agents_from_markdown("agents/") # also: _from_yaml, _from_csv
- agent = loader.load_agent_from_markdown("agents/researcher.md")
- ```
- ---
- # Part 7 — Pitfalls
- | Don't | Do | Why |
- |---|---|---|
- | `from swarms.structs.agent import Agent` | `from swarms import Agent` | Submodule paths move between versions |
- | `tools=[]` | `tools=None` | Empty list breaks schema generation |
- | `tools=[f]` with `max_loops=1` | `max_loops=3` | Loop 1 calls the tool; it needs loop 2 to use the result |
- | Same `agent_name` on several agents | Unique names | `MEMORY.md` is keyed on it — they corrupt each other |
- | `streaming_on=True` + `streaming_callback` | Pick one | They conflict |
- | `CouncilAsAJudge(agents=..., judge=...)` | Model-name kwargs | It takes no `agents` or `judge` argument |
- | `DebateWithJudge(agents=[p, c], judge=j)` | `pro_agent=`, `con_agent=`, `judge_agent=` | Those kwarg names don't exist |
- | `HeavySwarm(num_agents=4, model_name=...)` | `question_agent_model_name=`, `worker_model_name=` | Those kwarg names don't exist |
- | `from swarms import PlannerWorkerSwarm` | `from swarms.structs.planner_worker_swarm import ...` | Not exported at the top level |
- | `swarm_type="AutoSwarmBuilder"` | Use the class directly | Not one of the 16 router types |
- | `GraphWorkflow.add_node(Node(...))` | `add_node(agent)` | It takes the agent itself |
- | Building agents inside a loop | Build once, reuse | Construction is expensive |
- | `context_compression=False` on long runs | Leave it `True` | The run will hit the context wall |
- | Bare `max_loops="auto"` in production | Integer `max_loops` | Autonomous runs have no natural stopping point |
- ## Production configuration
- ```python
- agent = Agent(
- agent_name="ProductionAgent",
- agent_description="...",
- model_name="gpt-5.4",
- max_loops=3,
- context_length=32000,
- context_compression=True,
- persistent_memory=True,
- autosave=True,
- retry_attempts=3,
- fallback_models=["claude-sonnet-4-6"],
- verbose=False,
- )
- ```
- ## Debugging
- - `verbose=True` — full internal logging
- - `show_tool_execution_output=True` — raw tool returns
- - `output_type="all"` — the complete conversation instead of just the final message
- - `agent.get_all_selected_tools()` — the autonomous tool roster
- - `agent.short_memory.return_history_as_string()` — dump the conversation
- ---
- ## Reference
- - Docs: [docs.swarms.world](https://docs.swarms.world) · [Agent API](https://docs.swarms.world/api/agent)
- - Examples: [`examples/`](examples/) — `single_agent/`, `multi_agent/`, `tools/`, `guides/`
- - Source: `swarms/structs/` (agents + swarms), `swarms/agents/` (loops, judges, routers), `swarms/tools/`
- - Contributing: [CONTRIBUTING.md](CONTRIBUTING.md)
README.md · README · 821 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- <div align="left">
- <a href="https://swarms.world">
- <img src="https://github.com/kyegomez/swarms/blob/master/images/new_logo.png" style="margin: 15px; max-width: 350px" width="70%" alt="Logo">
- </a>
- </div>
- <p align="left">
- <!-- Main Navigation Links -->
- <a href="https://swarms.ai">Swarms Website</a>
- <span> • </span>
- <a href="https://docs.swarms.world">Documentation</a>
- <span> • </span>
- <a href="https://swarms.world">Swarms Marketplace</a>
- <span> • </span>
- <a href="./README_zh.md">中文</a>
- </p>
- <p align="left">
- <a href="https://pypi.org/project/swarms/" target="_blank">
- <picture>
- <source srcset="https://img.shields.io/pypi/v/swarms?style=for-the-badge&color=3670A0" media="(prefers-color-scheme: dark)">
- <img alt="Version" src="https://img.shields.io/pypi/v/swarms?style=for-the-badge&color=3670A0">
- </picture>
- </a>
- <a href="https://pypi.org/project/swarms/" target="_blank">
- <picture>
- <source srcset="https://img.shields.io/pypi/dm/swarms?style=for-the-badge&color=3670A0" media="(prefers-color-scheme: dark)">
- <img alt="Downloads" src="https://img.shields.io/pypi/dm/swarms?style=for-the-badge&color=3670A0">
- </picture>
- </a>
- <a href="https://twitter.com/swarms_corp/">
- <picture>
- <source srcset="https://img.shields.io/badge/Twitter-Follow-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white" media="(prefers-color-scheme: dark)">
- <img src="https://img.shields.io/badge/Twitter-Follow-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white" alt="Twitter">
- </picture>
- </a>
- <a href="https://discord.gg/EamjgSaEQf">
- <picture>
- <source srcset="https://img.shields.io/badge/Discord-Join-5865F2?style=for-the-badge&logo=discord&logoColor=white" media="(prefers-color-scheme: dark)">
- <img src="https://img.shields.io/badge/Discord-Join-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Discord">
- </picture>
- </a>
- </p>
- ## Overview
- >
- > Swarms, The Enterprise-Grade Production-Ready Multi-Agent Orchestration Framework
- Build, deploy, and scale high-performance multi-agent systems with Swarms Python, a fast, flexible, and optimized agent framework. Featuring production-ready harnesses for sequential, concurrent, and hierarchical architectures, seamless framework compatibility, and integrations with MCP, x402, and skills.
- ## Install
- ```bash
- # pip
- $ pip3 install -U swarms
- # uv (recommended): https://github.com/astral-sh/uv
- $ uv pip install swarms
- # poetry
- $ poetry add swarms
- ```
- ### From source
- ```bash
- # Clone the repository
- $ git clone https://github.com/kyegomez/swarms.git
- $ cd swarms
- $ pip install -r requirements.txt
- ```
- ### Faster model calls and graphs with `swarms[fast]`
- `swarms[fast]` adds two optional speedups:
- - [RouteHub](https://github.com/The-Swarm-Corporation/RouteHub) for faster model calls through a drop-in LLM gateway. No code changes needed. To switch back to litellm, set `SWARMS_LLM_BACKEND=litellm`.
- - [rustworkx](https://github.com/Qiskit/rustworkx), a graph library written in Rust, for faster `GraphWorkflow` graphs. Turn it on with `GraphWorkflow(backend="rustworkx")`.
- ```bash
- $ pip3 install -U "swarms[fast]"
- ```
- ### Using Docker
- The official image, [`swarmscorp/swarms`](https://hub.docker.com/r/swarmscorp/swarms) on Docker Hub, has swarms and its CLI installed on Python 3.13, for `linux/amd64` and `linux/arm64`.
- ```bash
- # Pull the image
- $ docker pull swarmscorp/swarms:latest
- # Run a script from the current directory, passing your API key from the shell
- $ docker run --rm -e OPENAI_API_KEY -v "$PWD:/app" swarmscorp/swarms python agent.py
- # Open a Python shell with swarms installed
- $ docker run -it --rm -e OPENAI_API_KEY swarmscorp/swarms
- ```
- To build the image yourself, run `docker build -t swarms .` from the repository root.
- ---
- ## Environment Configuration
- [Learn more about the environment configuration here](https://docs.swarms.world/environment-setup)
- ```
- OPENAI_API_KEY=""
- WORKSPACE_DIR="agent_workspace"
- ANTHROPIC_API_KEY=""
- GROQ_API_KEY=""
- SWARMS_TELEMETRY_ON
- ```
- ### Your First Agent
- An **Agent** is the fundamental building block of a swarm: an autonomous entity powered by an LLM + Tools + Memory. [Learn more Here](https://docs.swarms.world/api/agent)
- ```python
- from swarms import Agent
- # Initialize a new agent
- agent = Agent(
- model_name="gpt-5.4", # Specify the LLM
- max_loops="auto", # Set the number of interactions
- interactive=True, # Enable interactive mode for real-time feedback
- temperature=None,
- )
- # Run the agent with a task
- agent.run("What are the key benefits of using a multi-agent system?")
- ```
- ### Autonomous Agent with `max_loops="auto"`
- Setting `max_loops="auto"` lets the agent decide for itself when the task is complete. It keeps reasoning and acting until it reaches a stopping condition, rather than halting after a fixed number of iterations. This is the recommended mode for open-ended, multi-step tasks where the number of steps isn't known in advance.
- ```python
- from swarms import Agent
- agent = Agent(
- agent_name="Autonomous-Research-Agent",
- agent_description="An autonomous agent that conducts multi-step research independently.",
- system_prompt=(
- "You are an autonomous research agent. Break down complex tasks into steps, "
- "execute each step thoroughly, and signal completion only when the full task is done."
- ),
- model_name="gpt-5.4",
- max_loops="auto", # Agent decides when it's done; no fixed iteration cap
- autosave=True,
- verbose=True,
- )
- # The agent will keep looping (planning, executing, and reflecting) until it
- # determines the task is fully complete.
- result = agent.run(
- "Research the current state of quantum computing, identify the top three "
- "hardware approaches, and summarize the key challenges each faces."
- )
- print(result)
- ```
- Use `max_loops="auto"` for open-ended research, iterative refinement, or any task where the number of steps depends on intermediate results. Use a fixed `max_loops` value for latency- or cost-sensitive production pipelines and tasks with a well-defined number of steps.
- ## MCP Integration
- The [Model Context Protocol (MCP)](https://modelcontextprotocol.io) lets agents easily access external tools and data by pointing to an MCP server URL, which automatically provides tools to the agent as needed. Agents become MCP-enabled by setting `mcp_url` or `mcp_urls`, and can use tools from one or many servers with no manual configuration. Free and public MCP servers like [DeepWiki](https://mcp.deepwiki.com/mcp) work out of the box, offering immediate access to useful agent tools.
- ```python
- from swarms import Agent
- agent = Agent(
- agent_name="MCP-Agent",
- model_name="claude-sonnet-5",
- mcp_url="https://mcp.deepwiki.com/mcp",
- max_loops=1,
- temperature=None,
- max_tokens=16_000,
- reasoning_effort=None,
- )
- print(
- agent.run(
- "Use your tools to explain what the kyegomez/swarms repository does."
- )
- )
- ```
- ### Serve an Agent as an MCP Server
- The reverse direction works too. `MCPDeployer` turns any agent, or any swarm, into an MCP server that other agents and MCP hosts can call, with an auth layer in front of it. Each target becomes one tool; pass a list or a dict to serve several from one server. [See the MCPDeployer examples](examples/mcp/mcp_deployer/)
- ```python
- from swarms import Agent, MCPDeployer
- researcher = Agent(
- agent_name="Researcher",
- agent_description="Answers research questions with a short summary.",
- model_name="gpt-5.4",
- max_loops=1,
- )
- # Serves http://127.0.0.1:8000/mcp as the tool "researcher".
- MCPDeployer(researcher, api_keys=["sk-local-dev"], port=8000).run()
- ```
- Any other agent can then use it by pointing at the URL with the key:
- ```python
- from swarms import Agent
- from swarms.schemas.mcp_schemas import MCPConnection
- client = Agent(
- agent_name="Client",
- model_name="gpt-5.4",
- mcp_url=MCPConnection(url="http://127.0.0.1:8000/mcp", api_key="sk-local-dev"),
- max_loops=2,
- )
- client.run("Use the researcher tool to summarise the state of solid-state batteries.")
- ```
- Auth can be static API keys, your own `auth` callable that reads the request headers, or an `mcp` `TokenVerifier` with required scopes. A server with no auth configured refuses to start unless you pass `allow_anonymous=True`. Transports: streamable HTTP (default), SSE, or stdio for desktop MCP hosts.
- | Example | What it shows |
- |---|---|
- | [single_agent_api_key.py](examples/mcp/mcp_deployer/single_agent_api_key.py) | One agent behind a static key |
- | [multiple_agents_one_server.py](examples/mcp/mcp_deployer/multiple_agents_one_server.py) | Two agents, a `SequentialWorkflow` and two functions as separate tools |
- | [custom_auth_per_tenant.py](examples/mcp/mcp_deployer/custom_auth_per_tenant.py) | Your own async auth callable reading an `x-tenant` header |
- | [token_verifier_with_scopes.py](examples/mcp/mcp_deployer/token_verifier_with_scopes.py) | `TokenVerifier` with required scopes |
- | [background_server_and_client_agent.py](examples/mcp/mcp_deployer/background_server_and_client_agent.py) | Serve, call from a second agent, and stop, all in one process |
- | [All MCPDeployer examples](examples/mcp/mcp_deployer/) | Every target kind, auth mode and transport |
- ### Your First Swarm: Multi-Agent Collaboration
- A **Swarm** is multiple agents working together. This example chains a researcher and a writer to produce a blog post. [Learn More About SequentialWorkflow](https://docs.swarms.world/api/sequential-workflow)
- ```python
- from swarms import Agent, SequentialWorkflow
- # Agent 1: The Researcher
- researcher = Agent(
- agent_name="Researcher",
- system_prompt="Your job is to research the provided topic and provide a detailed summary.",
- model_name="gpt-5.4",
- )
- # Agent 2: The Writer
- writer = Agent(
- agent_name="Writer",
- system_prompt="Your job is to take the research summary and write a beautiful, engaging blog post about it.",
- model_name="gpt-5.4",
- )
- # Create a sequential workflow where the researcher's output feeds into the writer's input
- workflow = SequentialWorkflow(agents=[researcher, writer])
- # Run the workflow on a task
- final_post = workflow.run("The history and future of artificial intelligence")
- print(final_post)
- ```
- -----
- ## Available Multi-Agent Architectures
- `swarms` provides a variety of powerful, pre-built multi-agent architectures enabling you to orchestrate agents in various ways. Choose the right structure for your specific problem to build efficient and reliable production systems.
- | **Architecture** | **Description** | **Best For** |
- |---|---|---|
- | **[SequentialWorkflow](https://docs.swarms.world/api/sequential-workflow)** | Agents execute tasks in a linear chain; the output of one agent becomes the input for the next. | Step-by-step processes such as data transformation pipelines and report generation. |
- | **[ConcurrentWorkflow](https://docs.swarms.world/api/concurrent-workflow)** | Agents run tasks simultaneously for maximum efficiency. | High-throughput tasks such as batch processing and parallel data analysis. |
- | **[AgentRearrange](https://docs.swarms.world/api/agent-rearrange)** | Dynamically maps complex relationships (e.g., `a -> b, c`) between agents. | Flexible and adaptive workflows, task distribution, and dynamic routing. |
- | **[GraphWorkflow](https://docs.swarms.world/api/graph-workflow)** | Orchestrates agents as nodes in a Directed Acyclic Graph (DAG). | Complex projects with intricate dependencies, such as software builds. |
- | **[MixtureOfAgents (MoA)](https://docs.swarms.world/api/mixture-of-agents)** | Utilizes multiple expert agents in parallel and synthesizes their outputs. | Complex problem-solving and achieving state-of-the-art performance through collaboration. |
- | **[GroupChat](https://docs.swarms.world/api/group-chat)** | Agents collaborate and make decisions through a conversational interface. | Real-time collaborative decision-making, negotiations, and brainstorming. |
- | **[ForestSwarm](https://docs.swarms.world/api/forest-swarm)** | Dynamically selects the most suitable agent or tree of agents for a given task. | Task routing, optimizing for expertise, and complex decision-making trees. |
- | **[HierarchicalSwarm](https://docs.swarms.world/api/hierarchical-swarm)** | Orchestrates agents with a director who creates plans and distributes tasks to specialized worker agents. | Complex project management, team coordination, and hierarchical decision-making with feedback loops. |
- | **[HeavySwarm](https://docs.swarms.world/api/heavy-swarm)** | Implements a five-phase workflow with specialized agents (Research, Analysis, Alternatives, Verification) for comprehensive task analysis. | Complex research and analysis tasks, financial analysis, strategic planning, and comprehensive reporting. |
- | **[SwarmRouter](https://docs.swarms.world/api/swarm-router)** | A universal orchestrator that provides a single interface to run any type of swarm with dynamic selection. | Simplifying complex workflows, switching between swarm strategies, and unified multi-agent management. |
- Learn more about all of the 60+ Multi-Agent Structures we have available [here](https://docs.swarms.world)
- -----
- ### SequentialWorkflow
- A `SequentialWorkflow` runs agents in a strict order, with each agent building on the previous one's output. Use it for processes with clear, ordered steps that depend on each other.
- ```python
- from swarms import Agent, SequentialWorkflow
- researcher = Agent(
- agent_name="Researcher",
- system_prompt="Your job is to research the provided topic and provide a detailed summary.",
- model_name="gpt-5.4",
- )
- writer = Agent(
- agent_name="Writer",
- system_prompt="Your job is to take the research summary and write a beautiful, engaging blog post about it.",
- model_name="gpt-5.4",
- )
- workflow = SequentialWorkflow(agents=[researcher, writer])
- final_post = workflow.run("The history and future of artificial intelligence")
- print(final_post)
- ```
- -----
- ### ConcurrentWorkflow
- A `ConcurrentWorkflow` runs multiple agents on the same task in parallel. It cuts execution time for high-throughput work where agents don't depend on each other.
- ```python
- from swarms import Agent, ConcurrentWorkflow
- market_analyst = Agent(
- agent_name="Market-Analyst",
- system_prompt="Analyze market trends and provide insights on the given topic.",
- model_name="gpt-5.4",
- max_loops=1,
- )
- financial_analyst = Agent(
- agent_name="Financial-Analyst",
- system_prompt="Provide financial analysis and recommendations on the given topic.",
- model_name="gpt-5.4",
- max_loops=1,
- )
- risk_analyst = Agent(
- agent_name="Risk-Analyst",
- system_prompt="Assess risks and provide risk management strategies for the given topic.",
- model_name="gpt-5.4",
- max_loops=1,
- )
- concurrent_workflow = ConcurrentWorkflow(
- agents=[market_analyst, financial_analyst, risk_analyst],
- max_loops=1,
- )
- results = concurrent_workflow.run(
- "Analyze the potential impact of AI technology on the healthcare industry"
- )
- print(results)
- ```
- ---
- ### AgentRearrange
- Inspired by `einsum`, `AgentRearrange` defines relationships between agents with a simple string syntax, where `->` runs agents in sequence and `,` runs them in parallel. Use it to mix sequential and parallel steps in any combination. [Learn more](https://docs.swarms.world/api/agent-rearrange)
- ```python
- from swarms import Agent, AgentRearrange
- researcher = Agent(agent_name="researcher", model_name="gpt-5.4")
- writer = Agent(agent_name="writer", model_name="gpt-5.4")
- editor = Agent(agent_name="editor", model_name="gpt-5.4")
- flow = "researcher -> writer, editor"
- rearrange_system = AgentRearrange(
- agents=[researcher, writer, editor],
- flow=flow,
- )
- outputs = rearrange_system.run("Analyze the impact of AI on modern cinema.")
- print(outputs)
- ```
- ### GraphWorkflow
- `GraphWorkflow` runs agents as nodes in a Directed Acyclic Graph (DAG), where each edge is a dependency and independent branches run in parallel. Use it for fan-out / fan-in, diamond patterns, or any structure that isn't a simple line or parallel batch. [Learn more about GraphWorkflow](https://docs.swarms.world/api/graph-workflow)
- ```python
- from swarms import Agent, GraphWorkflow
- researcher = Agent(agent_name="Researcher", system_prompt="Research the topic and list the key findings.", model_name="gpt-5.4")
- writer = Agent(agent_name="Writer", system_prompt="Write a clear article from the research.", model_name="gpt-5.4")
- reviewer = Agent(agent_name="Reviewer", system_prompt="Review the article for accuracy and clarity.", model_name="gpt-5.4")
- workflow = GraphWorkflow()
- workflow.add_nodes([researcher, writer, reviewer])
- workflow.add_edge(researcher, writer)
- workflow.add_edge(writer, reviewer)
- print(workflow.run("Write a short article on the rise of small language models."))
- ```
- ----
- ### SwarmRouter: The Universal Swarm Orchestrator
- `SwarmRouter` gives you a single interface to run any type of swarm. Change `swarm_type` (for example to `"ConcurrentWorkflow"` or `"HierarchicalSwarm"`) to run the same agents with a different strategy. [Read the full documentation](https://docs.swarms.world/api/swarm-router)
- ```python
- from swarms import Agent, SwarmRouter
- writer = Agent(agent_name="Writer", system_prompt="You are a creative writer.", model_name="gpt-5.4")
- editor = Agent(agent_name="Editor", system_prompt="You are an expert editor for stories.", model_name="gpt-5.4")
- router = SwarmRouter(
- agents=[writer, editor],
- swarm_type="SequentialWorkflow",
- )
- print(router.run("Write a short story about a robot who discovers music."))
- ```
- -------
- ### AutoSwarmBuilder: Autonomous Agent Generation
- `AutoSwarmBuilder` generates specialized agents, their prompts, and their workflow from a description of your task. Use it for rapid prototyping or to build a team without configuring each agent by hand. [Learn more about AutoSwarmBuilder](https://docs.swarms.world/api/auto-swarm-builder)
- ```python
- from swarms import AutoSwarmBuilder
- import json
- swarm = AutoSwarmBuilder(
- name="My Swarm",
- description="A swarm of agents",
- verbose=True,
- max_loops=1,
- return_agents=True,
- model_name="gpt-5.4",
- )
- result = swarm.run(
- task="Create an accounting team to analyze crypto transactions, "
- "there must be 5 agents in the team with extremely extensive prompts. "
- "Make the prompts extremely detailed and specific and long and comprehensive. "
- "Make sure to include all the details of the task in the prompts."
- )
- print(json.dumps(result, indent=4))
- ```
- -------
- ### MixtureOfAgents (MoA)
- `MixtureOfAgents` sends a task to multiple expert agents in parallel. An aggregator agent then synthesizes their outputs into one final answer. [Learn more here](https://docs.swarms.world/examples/mixture-of-agents-example)
- ```python
- from swarms import Agent, MixtureOfAgents
- financial_analyst = Agent(agent_name="FinancialAnalyst", system_prompt="Analyze financial data.", model_name="gpt-5.4")
- market_analyst = Agent(agent_name="MarketAnalyst", system_prompt="Analyze market trends.", model_name="gpt-5.4")
- risk_analyst = Agent(agent_name="RiskAnalyst", system_prompt="Analyze investment risks.", model_name="gpt-5.4")
- aggregator = Agent(
- agent_name="InvestmentAdvisor",
- system_prompt="Synthesize the financial, market, and risk analyses to provide a final investment recommendation.",
- model_name="gpt-5.4"
- )
- moa_swarm = MixtureOfAgents(
- agents=[financial_analyst, market_analyst, risk_analyst],
- aggregator_agent=aggregator,
- )
- recommendation = moa_swarm.run("Should we invest in NVIDIA stock right now?")
- print(recommendation)
- ```
- ----
- ### GroupChat
- In `GroupChat`, every agent bids each turn with a score for how much it wants to speak, and the highest bidder above `threshold` posts its reply. The chat ends when no agent clears `threshold` or `max_loops` messages have been posted, and every agent must carry `RESPOND_TOOL` so it can bid.
- ```python
- from swarms import Agent, GroupChat, RESPOND_TOOL
- tech_optimist = Agent(
- agent_name="TechOptimist",
- system_prompt="Argue for the benefits of AI in society.",
- model_name="gpt-5.4",
- max_loops=1,
- persistent_memory=False,
- tools_list_dictionary=[RESPOND_TOOL],
- )
- tech_critic = Agent(
- agent_name="TechCritic",
- system_prompt="Argue against the unchecked advancement of AI.",
- model_name="gpt-5.4",
- max_loops=1,
- persistent_memory=False,
- tools_list_dictionary=[RESPOND_TOOL],
- )
- chat = GroupChat(
- agents=[tech_optimist, tech_critic],
- max_loops=10,
- threshold=0.5,
- )
- result = chat.run("Let's discuss the societal impact of artificial intelligence.")
- print(result)
- ```
- ----
- ### HierarchicalSwarm
- In a `HierarchicalSwarm`, a director agent creates a plan and assigns tasks to specialized worker agents. The director then reviews their results and can issue new orders over several loops.
- ```python
- from swarms import Agent, HierarchicalSwarm
- content_strategist = Agent(
- agent_name="Content-Strategist",
- system_prompt="You are a senior content strategist. Develop comprehensive content strategies, editorial calendars, and content roadmaps.",
- model_name="gpt-5.4"
- )
- creative_director = Agent(
- agent_name="Creative-Director",
- system_prompt="You are a creative director. Develop compelling advertising concepts, visual directions, and campaign creativity.",
- model_name="gpt-5.4"
- )
- seo_specialist = Agent(
- agent_name="SEO-Specialist",
- system_prompt="You are an SEO expert. Conduct keyword research, optimize content, and develop organic growth strategies.",
- model_name="gpt-5.4"
- )
- brand_strategist = Agent(
- agent_name="Brand-Strategist",
- system_prompt="You are a brand strategist. Develop brand positioning, identity systems, and market differentiation strategies.",
- model_name="gpt-5.4"
- )
- marketing_swarm = HierarchicalSwarm(
- name="Marketing-Team-Swarm",
- description="A comprehensive marketing team with specialized agents coordinated by a director",
- agents=[content_strategist, creative_director, seo_specialist, brand_strategist],
- max_loops=2,
- verbose=True
- )
- result = marketing_swarm.run(
- "Develop a comprehensive marketing strategy for a new SaaS product launch. "
- "The product is a project management tool targeting small to medium businesses. "
- "Coordinate the team to create content strategy, creative campaigns, SEO optimization, "
- "and brand positioning that work together cohesively."
- )
- print(result)
- ```
- ---
- ### HeavySwarm
- Inspired by Grok Heavy, `HeavySwarm` generates questions about a task, runs specialized research, analysis, alternatives, and verification agents in parallel, and synthesizes their findings. The example below uses `exa_search` from `swarms-tools` (`pip install swarms-tools`). [Learn more about HeavySwarm](https://docs.swarms.world/api/heavy-swarm)
- ```python
- from swarms import HeavySwarm
- from swarms_tools import exa_search
- swarm = HeavySwarm(
- name="Gold ETF Research Team",
- description="A team of agents that research the best gold ETFs",
- worker_model_name="claude-sonnet-4-20250514",
- show_dashboard=True,
- question_agent_model_name="gpt-5.4",
- loops_per_agent=1,
- agent_prints_on=False,
- worker_tools=[exa_search],
- random_loops_per_agent=True,
- )
- prompt = (
- "Find the best 3 gold ETFs. For each ETF, provide the ticker symbol, "
- "full name, current price, expense ratio, assets under management, and "
- "a brief explanation of why it is considered among the best. Present the information "
- "in a clear, structured format suitable for investors. Scrape the data from the web. "
- )
- out = swarm.run(prompt)
- print(out)
- ```
- ---
- ### Social Algorithms
- **Social Algorithms** let you define custom communication patterns between agents. You pass a callable that decides which agent talks to which, and in what order. [Learn more about Social Algorithms](https://docs.swarms.world/api/social-algorithms)
- ```python
- from swarms import Agent, SocialAlgorithms
- def research_analysis_synthesis_algorithm(agents, task, **kwargs):
- research_result = agents[0].run(f"Research: {task}")
- analysis = agents[1].run(f"Analyze this research: {research_result}")
- synthesis = agents[2].run(f"Synthesize: {research_result} + {analysis}")
- return {
- "research": research_result,
- "analysis": analysis,
- "synthesis": synthesis
- }
- researcher = Agent(
- agent_name="Researcher",
- agent_description="Expert in comprehensive research and information gathering.",
- model_name="gpt-5.4"
- )
- analyst = Agent(
- agent_name="Analyst",
- agent_description="Specialist in analyzing and interpreting data.",
- model_name="gpt-5.4"
- )
- synthesizer = Agent(
- agent_name="Synthesizer",
- agent_description="Focused on synthesizing and integrating research insights.",
- model_name="gpt-5.4"
- )
- social_alg = SocialAlgorithms(
- name="Research-Analysis-Synthesis",
- agents=[researcher, analyst, synthesizer],
- social_algorithm=research_analysis_synthesis_algorithm,
- verbose=True
- )
- result = social_alg.run("The impact of AI on healthcare")
- print(result.final_outputs)
- ```
- ---
- ## Documentation
- The full documentation lives at **[docs.swarms.world](https://docs.swarms.world)**. Below are the resources most useful when building with Swarms, both for humans and for AI coding assistants.
- | Resource | Link | What it's for |
- |---|---|---|
- | **Main documentation** | [docs.swarms.world](https://docs.swarms.world) | Guides, API reference, tutorials |
- | **`llms.txt` (LLM-ingestible docs)** | [docs.swarms.world/llms.txt](https://docs.swarms.world/llms.txt) | A single, machine-readable index of the entire documentation, formatted for LLMs and AI IDEs (Cursor, Claude Code, etc.) to consume in one fetch |
- | **Docs MCP server** | `https://docs.swarms.world/mcp` | A [Model Context Protocol](https://modelcontextprotocol.io) server that lets an assistant search and read the current docs. See [Using Swarms with AI Coding Assistants](#using-swarms-with-ai-coding-assistants) |
- | **MCP integration guide** | [docs.swarms.world/integrations/mcp](https://docs.swarms.world/integrations/mcp) | How to connect a Swarms `Agent` to any MCP server, auto-discover its tools, and call them from a swarm |
- | **API reference** | [docs.swarms.world/api](https://docs.swarms.world/api) | Per-class reference for `Agent`, `SequentialWorkflow`, `ConcurrentWorkflow`, `AgentRearrange`, `GraphWorkflow`, `SwarmRouter`, and every multi-agent architecture |
- | **Environment setup** | [docs.swarms.world/environment-setup](https://docs.swarms.world/environment-setup) | API keys, model providers, and configuration options |
- > **Tip for AI coding assistants:** point your tool (Claude Code, Cursor, Windsurf, Continue, etc.) at `https://docs.swarms.world/llms.txt`. It will pull the entire docs index in one shot and write idiomatic Swarms code without per-question lookups.
- ---
- ## Using Swarms with AI Coding Assistants
- The repo ships with [`AGENTS.md`](./AGENTS.md) and [`CLAUDE.md`](./CLAUDE.md), guides that teach AI coding assistants (Claude Code, Cursor, Codex, Copilot and others) how to build with Swarms: the `Agent` primitive, every multi-agent architecture, tools, streaming, memory and MCP.
- Copy `CLAUDE.md` (or symlink it as `AGENTS.md` / `.cursorrules`) into any project that uses `swarms`, and your assistant will write idiomatic Swarms code from the start.
- Two hosted MCP servers give an assistant live Swarms context instead of training data that may predate a rename:
- | Server | URL | Key | What it does |
- |---|---|---|---|
- | Docs | `https://docs.swarms.world/mcp` | none | Searches and reads the current documentation |
- | Marketplace | `https://swarms.world/mcp` | Swarms API key for calls | Searches, reads and publishes agents, prompts and tools on [swarms.world](https://swarms.world) |
- The whole documentation is also available as plain text at [docs.swarms.world/llms.txt](https://docs.swarms.world/llms.txt) (an index) and [docs.swarms.world/llms-full.txt](https://docs.swarms.world/llms-full.txt) (every page).
- Claude Code:
- ```bash
- claude mcp add --transport http swarms-docs https://docs.swarms.world/mcp
- claude mcp add --transport http swarms-marketplace https://swarms.world/mcp \
- --header "Authorization: Bearer $SWARMS_API_KEY"
- ```
- Cursor, in `.cursor/mcp.json`:
- ```json
- {
- "mcpServers": {
- "swarms-docs": { "url": "https://docs.swarms.world/mcp" },
- "swarms-marketplace": {
- "url": "https://swarms.world/mcp",
- "headers": { "Authorization": "Bearer ${env:SWARMS_API_KEY}" }
- }
- }
- }
- ```
- ---
- ## Features
- Swarms delivers a comprehensive, enterprise-grade multi-agent infrastructure platform designed for production-scale deployments and seamless integration with existing systems. [Learn more about the swarms feature set here](https://docs.swarms.world/community/features)
- | Category | Features | Benefits |
- |----------|----------|-----------|
- | **Enterprise Architecture** | • Production-Ready Infrastructure<br>• High Availability Systems<br>• Modular Microservices Design<br>• Comprehensive Observability<br>• Backwards Compatibility | • 99.9%+ Uptime Guarantee<br>• Reduced Operational Overhead<br>• Seamless Legacy Integration<br>• Enhanced System Monitoring<br>• Risk-Free Migration Path |
- | **Multi-Agent Orchestration** | • Hierarchical Agent Swarms<br>• Parallel Processing Pipelines<br>• Sequential Workflow Orchestration<br>• Graph-Based Agent Networks<br>• Dynamic Agent Composition<br>• Agent Registry Management | • Complex Business Process Automation<br>• Scalable Task Distribution<br>• Flexible Workflow Adaptation<br>• Optimized Resource Utilization<br>• Centralized Agent Governance<br>• Enterprise-Grade Agent Lifecycle Management |
- | **Enterprise Integration** | • Multi-Model Provider Support<br>• Custom Agent Development Framework<br>• Extensive Enterprise Tool Library<br>• Multiple Memory Systems<br>• Backwards Compatibility with LangChain, AutoGen, CrewAI<br>• Standardized API Interfaces | • Vendor-Agnostic Architecture<br>• Custom Solution Development<br>• Extended Functionality Integration<br>• Enhanced Knowledge Management<br>• Seamless Framework Migration<br>• Reduced Integration Complexity |
- | **Enterprise Scalability** | • Concurrent Multi-Agent Processing<br>• Intelligent Resource Management<br>• Load Balancing & Auto-Scaling<br>• Horizontal Scaling Capabilities<br>• Performance Optimization<br>• Capacity Planning Tools | • High-Throughput Processing<br>• Cost-Effective Resource Utilization<br>• Elastic Scaling Based On Demand<br>• Linear Performance Scaling<br>• Optimized Response Times<br>• Predictable Growth Planning |
- | **Developer Experience** | • Intuitive Enterprise API<br>• Comprehensive Documentation<br>• Active Enterprise Community<br>• CLI & SDK Tools<br>• IDE Integration Support<br>• Code Generation Templates | • Accelerated Development Cycles<br>• Reduced Learning Curve<br>• Expert Community Support<br>• Rapid Deployment Capabilities<br>• Enhanced Developer Productivity<br>• Standardized Development Patterns |
- ## Supported Protocols & Integrations
- Swarms seamlessly integrates with industry-standard protocols and open specifications, unlocking powerful capabilities for tool integration, payment processing, distributed agent orchestration, and model interoperability.
- | Protocol | Description | Documentation |
- |----------|-------------|---------------|
- | **[MCP (Model Context Protocol)](https://docs.swarms.world/integrations/mcp)** | Standardized protocol for AI agents to interact with external tools and services through MCP servers. Enables dynamic tool discovery and execution. | [MCP Integration Guide](https://docs.swarms.world/integrations/mcp) |
- | **[A2A (Agent2Agent)](https://a2a-protocol.org)** | Open protocol for agents built on different frameworks to discover and call each other. `A2AServer` serves any agent or swarm with a public agent card and a `SendMessage` endpoint, and `A2AClient` calls any remote A2A 1.0 agent. | [A2A Examples](examples/a2a/) |
- | **[X402](https://docs.swarms.world/examples/integrations/x402-payment)** | Cryptocurrency payment protocol for API endpoints. Enables monetization of agents with pay-per-use models. | [X402 Quickstart](https://docs.swarms.world/examples/integrations/x402-payment) |
- | **[Swarms Marketplace](https://swarms.world)** | Platform for discovering and sharing production-ready prompts, agents, and tools. Enables automatic prompt loading from the marketplace and publishing your own prompts directly from code. | [Marketplace Tutorial](https://docs.swarms.world/integrations/marketplace) |
- | **[Open Responses](https://www.openresponses.org/)** | Open-source specification and ecosystem for multi-provider, interoperable LLM interfaces based on the OpenAI Responses API. Provides a unified schema and tooling for calling language models, streaming results, and composing agentic workflows, independent of provider. | [Open Responses Website](https://www.openresponses.org/) |
- | **[Agent Skills](https://docs.swarms.world/agents/agent-skills)** | Lightweight, markdown-based format for defining modular, reusable agent capabilities introduced by Anthropic. Enables specialization of agents without modifying code by loading skill definitions from simple SKILL.md files. | [Agent Skills Documentation](https://docs.swarms.world/agents/agent-skills) |
- ---
- ## Examples
- Explore comprehensive examples and tutorials to learn how to use Swarms effectively [HERE](examples/README.md)
- ---
- ## Contribute to Swarms
- Swarms is an open-source, community-driven framework aiming to accelerate a fully autonomous world by providing robust infrastructure for deploying and orchestrating millions of agents. By contributing, you can help advance multi-agent AI, collaborate with passionate peers, shape the agent economy, and enhance your expertise.
- Learn more about how you can make a meaningful impact in our [Contributor's Guide](https://docs.swarms.world/community/contributing).
- ### How to Contribute
- We've made it easy to start contributing. Here's how you can help:
- 1. **Find an Issue to Tackle:** The best way to begin is by visiting our [**contributing project board**](https://github.com/users/kyegomez/projects/1). Look for issues tagged with `good first issue`; these are specifically selected for new contributors.
- 2. **Report a Bug or Request a Feature:** Have a new idea or found something that isn't working right? We'd love to hear from you. Please [**file a Bug Report or Feature Request**](https://github.com/kyegomez/swarms/issues) on our GitHub Issues page.
- 3. **Understand Our Workflow and Standards:** Before submitting your work, please review our complete [**Contribution Guidelines**](https://github.com/kyegomez/swarms/blob/master/CONTRIBUTING.md). To help maintain code quality, we also encourage you to read our guide on [**Code Cleanliness**](https://docs.swarms.world/community/contributing-to-docs).
- 4. **Join the Discussion:** To participate in roadmap discussions and connect with other developers, join our community on [**Discord**](https://discord.gg/EamjgSaEQf).
- 5. **Use WARP for Every Commit, PR and Issue:** All contributors, people and AI agents alike, must write commit messages, PR titles and issue titles in the WARP (Warp Speed Protocol) shorthand: `[TYPE][Function/FileName][Short Description]`, for example `[FIX][Agent._run][Raise AgentLLMError after retry exhaustion]`. The full spec is the [**WARP Git Message Skill**](https://swarms.world/prompt/32d1e7b4-34da-4035-bc05-d18f8e71a2f1). Issues and PRs that skip WARP are triaged after the ones that use it, so expect a delay without it.
- ### Thank You to Our Contributors
- Thank you for contributing to swarms. Your work is extremely appreciated and recognized.
- <a href="https://github.com/kyegomez/swarms/graphs/contributors">
- <img src="https://contrib.rocks/image?repo=kyegomez/swarms" />
- </a>
- ## Join Swarms
- Our mission is to advance humanity by building the infrastructure that powers the agent economy. We’re actively recruiting talented individuals across multiple roles to accelerate this vision. Join our team to help build, maintain, and scale the Swarms Python package, Swarms Marketplace, and our growing suite of products.
- - **Check Open roles:** [swarms.ai/hiring](https://swarms.ai/hiring)
- - **Get in touch:** email [kye@swarms.world](mailto:kye@swarms.world) to learn more
- ## Join the Discord
- Join thousands of agent builders and AI engineers in the **[Swarms Discord](https://discord.gg/EamjgSaEQf)** for technical support, project showcases, collaboration, and the latest swarms ecosystem updates.
- [Join the Swarms Discord →](https://discord.gg/EamjgSaEQf)
- -----
- ## Join the Swarms Community!
- Join our community of agent engineers and researchers for technical support, cutting-edge updates, and exclusive access to world-class agent engineering insights!
- | Platform | Description | Link |
- |----------|-------------|------|
- | Documentation | Official documentation and guides | [docs.swarms.world](https://docs.swarms.world) |
- | Blog | Latest updates and technical articles | [Medium](https://medium.com/@kyeg) |
- | Discord | Live chat and community support | [Join Discord](https://discord.gg/EamjgSaEQf) |
- | Twitter | Latest news and announcements | [@swarms_corp](https://twitter.com/swarms_corp) |
- | LinkedIn | Professional network and updates | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) |
- | YouTube | Tutorials and demos | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) |
- | Events | Join our community events | [Sign up here](https://lu.ma/swarms_calendar) |
- | Onboarding Session | Get onboarded with Kye Gomez, creator and lead maintainer of Swarms | [Book Session](https://cal.com/swarms/swarms-onboarding-session) |
- ------
- ## Citation
- If you use **swarms** in your research, please cite the project by referencing the metadata in [CITATION.cff](./CITATION.cff).
- ```bibtex
- @misc{SWARMS_2022,
- author = {Kye Gomez and Pliny and Zack Bradshaw and Ilumn and Harshal and the Swarms Community},
- title = {{Swarms: Production-Grade Multi-Agent Infrastructure Platform}},
- year = {2022},
- howpublished = {\url{https://github.com/kyegomez/swarms}},
- note = {Documentation available at \url{https://docs.swarms.world}},
- version = {latest}
- ```
- ---
- # License
- Swarms is licensed under the Apache License 2.0. [Learn more here](./LICENSE)
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.