Skip to content
Back to search

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.

Checked today

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
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/kyegomez--swarms/badge.svg)](/listings/kyegomez--swarms)

HTML

<a href="/listings/kyegomez--swarms"><img src="/api/listings/kyegomez--swarms/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

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.

  1. ---
  2. name: swarms
  3. 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`.
  4. ---
  5. # Swarms
  6. 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**.
  7. ## Live documentation
  8. This skill can lag the library. When a signature here disagrees with the installed version, check the current docs:
  9. - Docs MCP server, no key: `https://docs.swarms.world/mcp` (`claude mcp add --transport http swarms-docs https://docs.swarms.world/mcp`)
  10. - Marketplace MCP server, Swarms API key for calls: `https://swarms.world/mcp`
  11. - Plain-text docs: [llms.txt](https://docs.swarms.world/llms.txt) (index), [llms-full.txt](https://docs.swarms.world/llms-full.txt) (every page)
  12. ## Golden rules
  13. 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).
  14. 2. **Every agent needs a unique `agent_name`** — memory files and swarm routing key on it.
  15. 3. **Default to `max_loops=1`.** Use a specific integer for production. Use `"auto"` only for genuinely open-ended work.
  16. 4. **Pass `tools=None`, not `tools=[]`.** An empty list breaks schema generation.
  17. 5. **Check `examples/`** — 586 runnable examples live there. One is probably close to what you need.
  18. 6. **Never set `streaming_on=True` and `streaming_callback` together.** Pick one.
  19. ## Setup
  20. ```bash
  21. pip install -U swarms
  22. ```
  23. Set the key for whichever provider you use — any [LiteLLM](https://docs.litellm.ai/docs/providers) model string works:
  24. ```bash
  25. export OPENAI_API_KEY="sk-..."
  26. export ANTHROPIC_API_KEY="sk-ant-..."
  27. export GROQ_API_KEY="..."
  28. export WORKSPACE_DIR="agent_workspace" # where agent state and memory land
  29. ```
  30. ---
  31. # Part 1 — The Agent
  32. ```python
  33. from swarms import Agent
  34. agent = Agent(
  35. agent_name="Analyst",
  36. agent_description="Analyzes market data and produces summaries.",
  37. system_prompt="You are a precise financial analyst.",
  38. model_name="gpt-5.4",
  39. max_loops=1,
  40. )
  41. result = agent.run("Summarize the state of the semiconductor market.")
  42. ```
  43. `Agent.__init__` accepts 90+ parameters. These are the ones that matter:
  44. | Parameter | Type | Default | Purpose |
  45. |---|---|---|---|
  46. | `agent_name` | `str` | `"swarm-worker-01"` | Unique identity; keys memory + routing |
  47. | `agent_description` | `str` | generic | How orchestrators decide to route to it |
  48. | `system_prompt` | `str` | built-in | Persona and instructions |
  49. | `model_name` | `str` | `"gpt-5.4"` | Any LiteLLM model string |
  50. | `max_loops` | `int \| "auto"` | `1` | Iterations, or autonomous mode |
  51. | `tools` | `list[Callable]` | `None` | Python functions the agent may call |
  52. | `temperature` | `float` | `0.5` | Sampling temperature |
  53. | `max_tokens` | `int` | model max | Output cap per call |
  54. | `top_p` | `float` | `None` | Nucleus sampling |
  55. | `context_length` | `int` | `None` | Token budget; triggers compression at 90% |
  56. | `output_type` | `str` | `"str-all-except-first"` | Return shape — see below |
  57. | `streaming_on` | `bool` | `False` | Stream tokens to stdout |
  58. | `streaming_callback` | `Callable` | `None` | Stream tokens to your function |
  59. | `interactive` | `bool` | `False` | REPL — prompts the user each loop |
  60. | `verbose` | `bool` | `False` | Debug logging |
  61. | `print_on` | `bool` | `True` | Print the final output |
  62. | `autosave` | `bool` | `False` | Persist agent state after each run |
  63. | `retry_attempts` | `int` | `3` | LLM call retries |
  64. | `reasoning_effort` | `str` | `None` | `minimal`/`low`/`medium`/`high`/`xhigh`/`ultra`/`max`/`none` |
  65. | `thinking_tokens` | `int` | `1024` | Extended thinking budget (Claude) |
  66. | `mcp_url` / `mcp_urls` | `str` / `list[str]` | `None` | MCP servers to load tools from |
  67. | `handoffs` | `list[Agent]` | `None` | Agents this one may delegate to |
  68. | `persistent_memory` | `bool` | `False` | Read/write `MEMORY.md` across restarts |
  69. | `context_compression` | `bool` | `True` | Auto-summarize near the context limit |
  70. | `plan_enabled` | `bool` | `False` | Plan before executing |
  71. | `mode` | `str` | `"standard"` | `"standard"`, `"fast"`, `"interactive"` |
  72. | `fallback_models` | `list[str]` | `None` | Models to try if the primary fails |
  73. **`output_type` options**: `"str"`, `"list"`, `"dict"`, `"json"`, `"yaml"`, `"final"`, `"last"`, `"all"`, `"str-all-except-first"`, `"dict-all-except-first"`, `"dict-final"`, `"list-final"`.
  74. ### Running
  75. ```python
  76. agent.run(task="...") # standard
  77. agent.run(task="...", img="chart.png") # one image
  78. agent.run(task="...", imgs=["a.png", "b.png"]) # several images
  79. agent.run(task="...", n=3) # 3 independent samples
  80. await agent.arun("...") # async
  81. ```
  82. `Agent.run` signature: `run(task=None, img=None, imgs=None, streaming_callback=None, n=1, messages=None)`.
  83. ### Streaming
  84. ```python
  85. # To stdout
  86. agent = Agent(agent_name="Writer", model_name="gpt-5.4", streaming_on=True)
  87. agent.run("Write a haiku about distributed systems.")
  88. # To a callback (do NOT combine with streaming_on)
  89. def on_token(token: str) -> None:
  90. print(token, end="", flush=True)
  91. agent = Agent(agent_name="Writer", model_name="gpt-5.4", streaming_callback=on_token)
  92. agent.run("Write a haiku.")
  93. # Async streaming
  94. async for token in agent.arun_stream("Explain async/await."):
  95. print(token, end="", flush=True)
  96. ```
  97. ---
  98. # Part 2 — Tools
  99. 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.**
  100. ```python
  101. from swarms import Agent
  102. def get_stock_price(ticker: str) -> str:
  103. """Fetch the current stock price for a ticker symbol.
  104. Args:
  105. ticker: Stock ticker symbol, e.g. 'AAPL'.
  106. Returns:
  107. The current price as a formatted string.
  108. """
  109. import yfinance as yf
  110. return f"{ticker}: ${yf.Ticker(ticker).fast_info['last_price']:.2f}"
  111. agent = Agent(
  112. agent_name="StockAnalyst",
  113. model_name="gpt-5.4",
  114. tools=[get_stock_price],
  115. max_loops=3, # needs > 1 so it can act on the tool result
  116. )
  117. agent.run("What are Apple and Microsoft trading at?")
  118. ```
  119. **`max_loops` must exceed 1 for tool use** — loop 1 calls the tool, loop 2 uses the result.
  120. Related knobs: `tool_call_summary=True` (summarize tool output), `show_tool_execution_output=True` (print raw returns), `tool_retry_attempts` (retries on tool failure).
  121. ### MCP servers
  122. ```python
  123. agent = Agent(
  124. agent_name="MCPAgent",
  125. model_name="gpt-5.4",
  126. mcp_url="http://localhost:8000/sse",
  127. # or: mcp_urls=["http://localhost:8000/sse", "http://localhost:8001/sse"]
  128. max_loops=3,
  129. )
  130. ```
  131. Inspect what a server exposes before wiring it up:
  132. ```python
  133. from swarms.tools.mcp_manager import MCPManager
  134. mgr = MCPManager(mcp_url="http://localhost:8000/sse")
  135. print(mgr.list_tool_names())
  136. schemas = mgr.get_tools() # aget_tools() for the async form
  137. ```
  138. ### Handoffs
  139. Give an agent a roster it can delegate to. It receives a `handoff_task` tool automatically.
  140. ```python
  141. triage = Agent(
  142. agent_name="Triage",
  143. model_name="gpt-5.4",
  144. handoffs=[billing_agent, technical_agent, refunds_agent],
  145. max_loops=3,
  146. )
  147. triage.run("My invoice is wrong and the app won't load.")
  148. ```
  149. ---
  150. # Part 3 — Autonomous mode (`max_loops="auto"`)
  151. The agent runs plan → execute → reflect until it decides it is finished, with **16 built-in tools** available:
  152. | Group | Tools |
  153. |---|---|
  154. | Planning | `create_plan`, `think`, `subtask_done`, `complete_task`, `respond_to_user` |
  155. | Files | `create_file`, `update_file`, `read_file`, `list_directory`, `delete_file` |
  156. | System | `run_bash`, `grep` |
  157. | Delegation | `create_sub_agent`, `assign_task`, `check_sub_agent_status`, `cancel_sub_agent_tasks` |
  158. ```python
  159. agent = Agent(
  160. agent_name="Researcher",
  161. model_name="gpt-5.4",
  162. max_loops="auto",
  163. tools=[search_web], # your tools stack on top of the built-ins
  164. persistent_memory=True,
  165. context_compression=True,
  166. context_length=32000,
  167. )
  168. agent.run("Research the top 5 vector databases and write compare.md")
  169. ```
  170. Restrict the built-in set with `selected_tools` (default `"all"`):
  171. ```python
  172. agent = Agent(
  173. agent_name="ReadOnly",
  174. max_loops="auto",
  175. selected_tools=["create_plan", "think", "read_file", "grep", "complete_task"],
  176. )
  177. ```
  178. Inspect the full list at runtime with `agent.get_all_selected_tools()`.
  179. ⚠️ **`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.
  180. ---
  181. # Part 4 — Memory and conversation
  182. ### Persistent memory
  183. `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.
  184. ```python
  185. agent = Agent(agent_name="ProjectAssistant", model_name="gpt-5.4", persistent_memory=True)
  186. agent.run("My project is called Helios. Remember that.")
  187. # Later process, same agent_name and the flag set again → it remembers.
  188. ```
  189. ### Context compression
  190. `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.
  191. ### Conversation
  192. ```python
  193. from swarms import Conversation
  194. conv = Conversation(
  195. name="my-conversation", # note: `name`, not `agent_name`
  196. system_prompt="You are helpful.",
  197. time_enabled=True,
  198. token_count=True,
  199. )
  200. conv.add("user", "What is 2+2?")
  201. conv.add("assistant", "4.")
  202. conv.return_history_as_string()
  203. conv.search("2+2")
  204. conv.compact(summary="User asked arithmetic. Answer: 4.") # archives, then collapses
  205. conv.save_as_json("conv.json")
  206. ```
  207. ---
  208. # Part 5 — Multi-agent architectures
  209. ## Choosing one
  210. | Situation | Use |
  211. |---|---|
  212. | Single task | `Agent` |
  213. | Linear A→B→C | `SequentialWorkflow` |
  214. | Same task, many agents at once | `ConcurrentWorkflow` |
  215. | Custom mix of sequential + parallel | `AgentRearrange` |
  216. | Dependency graph / fan-out-fan-in | `GraphWorkflow` |
  217. | Many models, one synthesized answer | `MixtureOfAgents` |
  218. | Manager delegates to specialists | `HierarchicalSwarm` |
  219. | Open discussion | `GroupChat` |
  220. | Discrete decision by consensus | `MajorityVoting` |
  221. | Quality-critical evaluation | `CouncilAsAJudge` |
  222. | Structured adversarial debate | `DebateWithJudge` |
  223. | Deep multi-stage research | `HeavySwarm` |
  224. | Route each task to the best agent | `MultiAgentRouter` |
  225. | Plan then execute with workers | `PlannerWorkerSwarm` |
  226. | Don't know yet | `SwarmRouter(swarm_type="auto")` or `AutoSwarmBuilder` |
  227. ## SequentialWorkflow
  228. Each agent's output becomes the next agent's context.
  229. ```python
  230. from swarms import Agent, SequentialWorkflow
  231. pipeline = SequentialWorkflow(
  232. agents=[researcher, analyst, writer],
  233. max_loops=1,
  234. output_type="dict",
  235. )
  236. pipeline.run("Analyze how rate hikes affect tech stocks.")
  237. ```
  238. Options: `team_awareness=True` (agents see the roster), `multi_agent_collab_prompt=True`, `drift_detection=True`.
  239. ## ConcurrentWorkflow
  240. All agents run the same task in parallel.
  241. ```python
  242. from swarms import Agent, ConcurrentWorkflow
  243. workflow = ConcurrentWorkflow(
  244. agents=agents,
  245. max_workers=5,
  246. show_dashboard=True,
  247. on_error="store", # or "raise"
  248. )
  249. workflow.run("List 10 use cases for multi-agent AI.")
  250. ```
  251. ## AgentRearrange — flow DSL
  252. ```python
  253. from swarms import Agent, AgentRearrange
  254. pipeline = AgentRearrange(
  255. agents=[planner, coder, reviewer, tester],
  256. flow="Planner -> Coder -> Reviewer, Tester",
  257. max_loops=1,
  258. )
  259. pipeline.run("Build an email validator.")
  260. ```
  261. - `A -> B` — sequential, B receives A's output
  262. - `A, B` — concurrent, same input
  263. - `A -> B, C -> D` — A, then B and C in parallel, then D on their combined output
  264. **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.
  265. ## GraphWorkflow — DAG
  266. Pass agents directly to `add_node`/`add_edge`; there is no need to wrap them in `Node` objects.
  267. ```python
  268. from swarms import Agent, GraphWorkflow
  269. wf = GraphWorkflow(name="research-dag", max_loops=1)
  270. for a in (ingestion, branch_a, branch_b, merger):
  271. wf.add_node(a)
  272. wf.add_edge(ingestion, branch_a) # fan out
  273. wf.add_edge(ingestion, branch_b)
  274. wf.add_edge(branch_a, merger) # fan in
  275. wf.add_edge(branch_b, merger)
  276. wf.set_entry_points(["Ingestion"])
  277. wf.set_end_points(["Merger"])
  278. def on_done(node: str, result) -> None:
  279. print(f"[{node}] {len(str(result))} chars")
  280. results = wf.run(task="Analyze this dataset two ways and merge.", on_node_complete=on_done)
  281. ```
  282. `add_node` also accepts a nested `GraphWorkflow`. Other options: `backend="networkx"|"rustworkx"`, `max_parallel_nodes`, `checkpoint_dir`, `streaming_callback`.
  283. ## SwarmRouter — one entry point
  284. Swap architectures without rewriting orchestration.
  285. ```python
  286. from swarms import Agent, SwarmRouter
  287. router = SwarmRouter(agents=agents, swarm_type="SequentialWorkflow", max_loops=1)
  288. router.run("Write a post about transformers.")
  289. ```
  290. Valid `swarm_type` values — **exactly these 16**:
  291. `"AgentRearrange"`, `"MixtureOfAgents"`, `"SequentialWorkflow"`, `"ConcurrentWorkflow"`, `"GroupChat"`, `"MultiAgentRouter"`, `"HierarchicalSwarm"`, `"MajorityVoting"`, `"CouncilAsAJudge"`, `"HeavySwarm"`, `"BatchedGridWorkflow"`, `"LLMCouncil"`, `"DebateWithJudge"`, `"RoundRobin"`, `"PlannerWorkerSwarm"`, `"auto"`.
  292. `"AutoSwarmBuilder"` and `"SpreadSheetSwarm"` are **not** router types — use those classes directly. With `swarm_type="AgentRearrange"` you must also pass `rearrange_flow`.
  293. ## MixtureOfAgents
  294. Workers answer independently; an aggregator synthesizes. Best with diverse providers.
  295. ```python
  296. from swarms import Agent, MixtureOfAgents
  297. moa = MixtureOfAgents(
  298. agents=[worker_gpt, worker_claude, worker_llama],
  299. aggregator_agent=aggregator, # optional; falls back to aggregator_model_name
  300. layers=3,
  301. max_loops=1,
  302. )
  303. moa.run("Best practices for securing a Kubernetes cluster?")
  304. ```
  305. ## HierarchicalSwarm
  306. A director decomposes the task, delegates, and synthesizes results.
  307. ```python
  308. from swarms import Agent, HierarchicalSwarm
  309. swarm = HierarchicalSwarm(
  310. agents=[data_worker, writing_worker, review_worker],
  311. director=director, # optional; else built from director_model_name
  312. max_loops=2,
  313. planning_enabled=True,
  314. parallel_execution=True,
  315. director_feedback_on=True,
  316. )
  317. swarm.run("Produce a competitive analysis of the AI chip market.")
  318. ```
  319. Also: `agent_as_judge=True`, `max_agent_retries`, `max_reassignment_attempts`, `interactive=True`.
  320. ## GroupChat
  321. 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`.
  322. ```python
  323. from swarms import Agent, GroupChat
  324. chat = GroupChat(
  325. agents=[optimist, pessimist, realist], # at least 2 required
  326. max_loops=10,
  327. threshold=0.5, # raise for a more selective room
  328. recency_penalty=0.3, # discourages one agent dominating
  329. )
  330. chat.run("Should we adopt AI for medical diagnosis?")
  331. ```
  332. `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`.
  333. ## MajorityVoting
  334. Agents answer independently; a consensus agent picks the winner.
  335. ```python
  336. from swarms import Agent, MajorityVoting
  337. mv = MajorityVoting(
  338. agents=voters,
  339. consensus_agent_model_name="gpt-5.4",
  340. max_loops=1,
  341. )
  342. mv.run("Python or Rust for a high-performance web server?")
  343. ```
  344. ## CouncilAsAJudge
  345. Evaluates a response across dimensions. **It builds its own council from model names — it does not take an `agents` list or a `judge` agent.**
  346. ```python
  347. from swarms import CouncilAsAJudge
  348. council = CouncilAsAJudge(
  349. model_name="gpt-5.4",
  350. aggregation_model_name="gpt-5.4",
  351. random_model_name=True,
  352. max_loops=1,
  353. )
  354. council.run("Should we store biometric data on-device only?")
  355. ```
  356. ## DebateWithJudge
  357. ```python
  358. from swarms import Agent, DebateWithJudge
  359. debate = DebateWithJudge(
  360. pro_agent=pro,
  361. con_agent=con,
  362. judge_agent=judge,
  363. max_loops=3, # rounds
  364. )
  365. debate.run("Motion: open-source LLMs will surpass closed-source by 2027.")
  366. ```
  367. `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=`.
  368. ## HeavySwarm
  369. Deep multi-stage analysis. **Configured by model names, not by an `agents` list.**
  370. ```python
  371. from swarms import HeavySwarm
  372. swarm = HeavySwarm(
  373. question_agent_model_name="gpt-5.4",
  374. worker_model_name="gpt-5.4",
  375. max_loops=1,
  376. timeout=900,
  377. show_dashboard=True,
  378. worker_tools=[search_web],
  379. )
  380. swarm.run("Analyze the implications of AGI on global labour markets.")
  381. ```
  382. ## PlannerWorkerSwarm
  383. A planner decomposes the task and workers execute; a judge checks completion each cycle. **Not exported at the top level:**
  384. ```python
  385. from swarms.structs.planner_worker_swarm import PlannerWorkerSwarm
  386. swarm = PlannerWorkerSwarm(
  387. agents=workers, # workers only — the planner is built internally
  388. planner_model_name="gpt-5.4",
  389. judge_model_name="gpt-5.4",
  390. max_planner_depth=1,
  391. max_loops=1,
  392. )
  393. swarm.run("Build a go-to-market strategy for a B2B SaaS product.")
  394. ```
  395. ## Others
  396. ```python
  397. from swarms import (
  398. MultiAgentRouter, # routes each task to the best-fit agent
  399. RoundRobinSwarm, # fixed rotation
  400. LLMCouncil, # members answer, rank peers anonymously, chairman synthesizes
  401. BatchedGridWorkflow, # agent i runs task i
  402. AutoSwarmBuilder, # generates the agents and architecture from a description
  403. SpreadSheetSwarm, # structured tabular processing
  404. AdvisorSwarm, SelfMoASeq, HybridHierarchicalClusterSwarm,
  405. )
  406. builder = AutoSwarmBuilder(name="MarketResearch", description="...", max_loops=1)
  407. builder.run("Research the EV market and find growth opportunities.")
  408. ```
  409. ---
  410. # Part 6 — Execution helpers
  411. ```python
  412. from swarms import (
  413. run_agents_concurrently,
  414. run_agents_with_different_tasks,
  415. run_agents_concurrently_async,
  416. batch_agent_execution,
  417. run_single_agent,
  418. aggregate,
  419. )
  420. run_agents_concurrently(agents=agents, task="Summarize today's news.", max_workers=8)
  421. run_agents_with_different_tasks([(agent_a, "task A"), (agent_b, "task B")]) # list of tuples
  422. batch_agent_execution(agents=agents, tasks=tasks, max_workers=10)
  423. aggregate(workers=agents, task="...", aggregator_model_name="gpt-5.4")
  424. ```
  425. Note `run_agents_with_different_tasks` takes a **list of `(agent, task)` tuples**, not a dict.
  426. ## Scheduling
  427. ```python
  428. from swarms import CronJob
  429. job = CronJob(agent=agent, interval="10minutes", job_id="market-check")
  430. job.run(task="Check for unusual market activity.")
  431. ```
  432. `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.
  433. ## Loading agents from files
  434. ```python
  435. from swarms import AgentLoader
  436. loader = AgentLoader(concurrent=True)
  437. agents = loader.load_agents_from_markdown("agents/") # also: _from_yaml, _from_csv
  438. agent = loader.load_agent_from_markdown("agents/researcher.md")
  439. ```
  440. ---
  441. # Part 7 — Pitfalls
  442. | Don't | Do | Why |
  443. |---|---|---|
  444. | `from swarms.structs.agent import Agent` | `from swarms import Agent` | Submodule paths move between versions |
  445. | `tools=[]` | `tools=None` | Empty list breaks schema generation |
  446. | `tools=[f]` with `max_loops=1` | `max_loops=3` | Loop 1 calls the tool; it needs loop 2 to use the result |
  447. | Same `agent_name` on several agents | Unique names | `MEMORY.md` is keyed on it — they corrupt each other |
  448. | `streaming_on=True` + `streaming_callback` | Pick one | They conflict |
  449. | `CouncilAsAJudge(agents=..., judge=...)` | Model-name kwargs | It takes no `agents` or `judge` argument |
  450. | `DebateWithJudge(agents=[p, c], judge=j)` | `pro_agent=`, `con_agent=`, `judge_agent=` | Those kwarg names don't exist |
  451. | `HeavySwarm(num_agents=4, model_name=...)` | `question_agent_model_name=`, `worker_model_name=` | Those kwarg names don't exist |
  452. | `from swarms import PlannerWorkerSwarm` | `from swarms.structs.planner_worker_swarm import ...` | Not exported at the top level |
  453. | `swarm_type="AutoSwarmBuilder"` | Use the class directly | Not one of the 16 router types |
  454. | `GraphWorkflow.add_node(Node(...))` | `add_node(agent)` | It takes the agent itself |
  455. | Building agents inside a loop | Build once, reuse | Construction is expensive |
  456. | `context_compression=False` on long runs | Leave it `True` | The run will hit the context wall |
  457. | Bare `max_loops="auto"` in production | Integer `max_loops` | Autonomous runs have no natural stopping point |
  458. ## Production configuration
  459. ```python
  460. agent = Agent(
  461. agent_name="ProductionAgent",
  462. agent_description="...",
  463. model_name="gpt-5.4",
  464. max_loops=3,
  465. context_length=32000,
  466. context_compression=True,
  467. persistent_memory=True,
  468. autosave=True,
  469. retry_attempts=3,
  470. fallback_models=["claude-sonnet-4-6"],
  471. verbose=False,
  472. )
  473. ```
  474. ## Debugging
  475. - `verbose=True` — full internal logging
  476. - `show_tool_execution_output=True` — raw tool returns
  477. - `output_type="all"` — the complete conversation instead of just the final message
  478. - `agent.get_all_selected_tools()` — the autonomous tool roster
  479. - `agent.short_memory.return_history_as_string()` — dump the conversation
  480. ---
  481. ## Reference
  482. - Docs: [docs.swarms.world](https://docs.swarms.world) · [Agent API](https://docs.swarms.world/api/agent)
  483. - Examples: [`examples/`](examples/) — `single_agent/`, `multi_agent/`, `tools/`, `guides/`
  484. - Source: `swarms/structs/` (agents + swarms), `swarms/agents/` (loops, judges, routers), `swarms/tools/`
  485. - 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.

  1. <div align="left">
  2. <a href="https://swarms.world">
  3. <img src="https://github.com/kyegomez/swarms/blob/master/images/new_logo.png" style="margin: 15px; max-width: 350px" width="70%" alt="Logo">
  4. </a>
  5. </div>
  6. <p align="left">
  7. <!-- Main Navigation Links -->
  8. <a href="https://swarms.ai">Swarms Website</a>
  9. <span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
  10. <a href="https://docs.swarms.world">Documentation</a>
  11. <span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
  12. <a href="https://swarms.world">Swarms Marketplace</a>
  13. <span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
  14. <a href="./README_zh.md">中文</a>
  15. </p>
  16. <p align="left">
  17. <a href="https://pypi.org/project/swarms/" target="_blank">
  18. <picture>
  19. <source srcset="https://img.shields.io/pypi/v/swarms?style=for-the-badge&color=3670A0" media="(prefers-color-scheme: dark)">
  20. <img alt="Version" src="https://img.shields.io/pypi/v/swarms?style=for-the-badge&color=3670A0">
  21. </picture>
  22. </a>
  23. <a href="https://pypi.org/project/swarms/" target="_blank">
  24. <picture>
  25. <source srcset="https://img.shields.io/pypi/dm/swarms?style=for-the-badge&color=3670A0" media="(prefers-color-scheme: dark)">
  26. <img alt="Downloads" src="https://img.shields.io/pypi/dm/swarms?style=for-the-badge&color=3670A0">
  27. </picture>
  28. </a>
  29. <a href="https://twitter.com/swarms_corp/">
  30. <picture>
  31. <source srcset="https://img.shields.io/badge/Twitter-Follow-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white" media="(prefers-color-scheme: dark)">
  32. <img src="https://img.shields.io/badge/Twitter-Follow-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white" alt="Twitter">
  33. </picture>
  34. </a>
  35. <a href="https://discord.gg/EamjgSaEQf">
  36. <picture>
  37. <source srcset="https://img.shields.io/badge/Discord-Join-5865F2?style=for-the-badge&logo=discord&logoColor=white" media="(prefers-color-scheme: dark)">
  38. <img src="https://img.shields.io/badge/Discord-Join-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Discord">
  39. </picture>
  40. </a>
  41. </p>
  42. ## Overview
  43. >
  44. > Swarms, The Enterprise-Grade Production-Ready Multi-Agent Orchestration Framework
  45. 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.
  46. ## Install
  47. ```bash
  48. # pip
  49. $ pip3 install -U swarms
  50. # uv (recommended): https://github.com/astral-sh/uv
  51. $ uv pip install swarms
  52. # poetry
  53. $ poetry add swarms
  54. ```
  55. ### From source
  56. ```bash
  57. # Clone the repository
  58. $ git clone https://github.com/kyegomez/swarms.git
  59. $ cd swarms
  60. $ pip install -r requirements.txt
  61. ```
  62. ### Faster model calls and graphs with `swarms[fast]`
  63. `swarms[fast]` adds two optional speedups:
  64. - [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`.
  65. - [rustworkx](https://github.com/Qiskit/rustworkx), a graph library written in Rust, for faster `GraphWorkflow` graphs. Turn it on with `GraphWorkflow(backend="rustworkx")`.
  66. ```bash
  67. $ pip3 install -U "swarms[fast]"
  68. ```
  69. ### Using Docker
  70. 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`.
  71. ```bash
  72. # Pull the image
  73. $ docker pull swarmscorp/swarms:latest
  74. # Run a script from the current directory, passing your API key from the shell
  75. $ docker run --rm -e OPENAI_API_KEY -v "$PWD:/app" swarmscorp/swarms python agent.py
  76. # Open a Python shell with swarms installed
  77. $ docker run -it --rm -e OPENAI_API_KEY swarmscorp/swarms
  78. ```
  79. To build the image yourself, run `docker build -t swarms .` from the repository root.
  80. ---
  81. ## Environment Configuration
  82. [Learn more about the environment configuration here](https://docs.swarms.world/environment-setup)
  83. ```
  84. OPENAI_API_KEY=""
  85. WORKSPACE_DIR="agent_workspace"
  86. ANTHROPIC_API_KEY=""
  87. GROQ_API_KEY=""
  88. SWARMS_TELEMETRY_ON
  89. ```
  90. ### Your First Agent
  91. 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)
  92. ```python
  93. from swarms import Agent
  94. # Initialize a new agent
  95. agent = Agent(
  96. model_name="gpt-5.4", # Specify the LLM
  97. max_loops="auto", # Set the number of interactions
  98. interactive=True, # Enable interactive mode for real-time feedback
  99. temperature=None,
  100. )
  101. # Run the agent with a task
  102. agent.run("What are the key benefits of using a multi-agent system?")
  103. ```
  104. ### Autonomous Agent with `max_loops="auto"`
  105. 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.
  106. ```python
  107. from swarms import Agent
  108. agent = Agent(
  109. agent_name="Autonomous-Research-Agent",
  110. agent_description="An autonomous agent that conducts multi-step research independently.",
  111. system_prompt=(
  112. "You are an autonomous research agent. Break down complex tasks into steps, "
  113. "execute each step thoroughly, and signal completion only when the full task is done."
  114. ),
  115. model_name="gpt-5.4",
  116. max_loops="auto", # Agent decides when it's done; no fixed iteration cap
  117. autosave=True,
  118. verbose=True,
  119. )
  120. # The agent will keep looping (planning, executing, and reflecting) until it
  121. # determines the task is fully complete.
  122. result = agent.run(
  123. "Research the current state of quantum computing, identify the top three "
  124. "hardware approaches, and summarize the key challenges each faces."
  125. )
  126. print(result)
  127. ```
  128. 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.
  129. ## MCP Integration
  130. 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.
  131. ```python
  132. from swarms import Agent
  133. agent = Agent(
  134. agent_name="MCP-Agent",
  135. model_name="claude-sonnet-5",
  136. mcp_url="https://mcp.deepwiki.com/mcp",
  137. max_loops=1,
  138. temperature=None,
  139. max_tokens=16_000,
  140. reasoning_effort=None,
  141. )
  142. print(
  143. agent.run(
  144. "Use your tools to explain what the kyegomez/swarms repository does."
  145. )
  146. )
  147. ```
  148. ### Serve an Agent as an MCP Server
  149. 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/)
  150. ```python
  151. from swarms import Agent, MCPDeployer
  152. researcher = Agent(
  153. agent_name="Researcher",
  154. agent_description="Answers research questions with a short summary.",
  155. model_name="gpt-5.4",
  156. max_loops=1,
  157. )
  158. # Serves http://127.0.0.1:8000/mcp as the tool "researcher".
  159. MCPDeployer(researcher, api_keys=["sk-local-dev"], port=8000).run()
  160. ```
  161. Any other agent can then use it by pointing at the URL with the key:
  162. ```python
  163. from swarms import Agent
  164. from swarms.schemas.mcp_schemas import MCPConnection
  165. client = Agent(
  166. agent_name="Client",
  167. model_name="gpt-5.4",
  168. mcp_url=MCPConnection(url="http://127.0.0.1:8000/mcp", api_key="sk-local-dev"),
  169. max_loops=2,
  170. )
  171. client.run("Use the researcher tool to summarise the state of solid-state batteries.")
  172. ```
  173. 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.
  174. | Example | What it shows |
  175. |---|---|
  176. | [single_agent_api_key.py](examples/mcp/mcp_deployer/single_agent_api_key.py) | One agent behind a static key |
  177. | [multiple_agents_one_server.py](examples/mcp/mcp_deployer/multiple_agents_one_server.py) | Two agents, a `SequentialWorkflow` and two functions as separate tools |
  178. | [custom_auth_per_tenant.py](examples/mcp/mcp_deployer/custom_auth_per_tenant.py) | Your own async auth callable reading an `x-tenant` header |
  179. | [token_verifier_with_scopes.py](examples/mcp/mcp_deployer/token_verifier_with_scopes.py) | `TokenVerifier` with required scopes |
  180. | [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 |
  181. | [All MCPDeployer examples](examples/mcp/mcp_deployer/) | Every target kind, auth mode and transport |
  182. ### Your First Swarm: Multi-Agent Collaboration
  183. 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)
  184. ```python
  185. from swarms import Agent, SequentialWorkflow
  186. # Agent 1: The Researcher
  187. researcher = Agent(
  188. agent_name="Researcher",
  189. system_prompt="Your job is to research the provided topic and provide a detailed summary.",
  190. model_name="gpt-5.4",
  191. )
  192. # Agent 2: The Writer
  193. writer = Agent(
  194. agent_name="Writer",
  195. system_prompt="Your job is to take the research summary and write a beautiful, engaging blog post about it.",
  196. model_name="gpt-5.4",
  197. )
  198. # Create a sequential workflow where the researcher's output feeds into the writer's input
  199. workflow = SequentialWorkflow(agents=[researcher, writer])
  200. # Run the workflow on a task
  201. final_post = workflow.run("The history and future of artificial intelligence")
  202. print(final_post)
  203. ```
  204. -----
  205. ## Available Multi-Agent Architectures
  206. `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.
  207. | **Architecture** | **Description** | **Best For** |
  208. |---|---|---|
  209. | **[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. |
  210. | **[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. |
  211. | **[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. |
  212. | **[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. |
  213. | **[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. |
  214. | **[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. |
  215. | **[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. |
  216. | **[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. |
  217. | **[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. |
  218. | **[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. |
  219. Learn more about all of the 60+ Multi-Agent Structures we have available [here](https://docs.swarms.world)
  220. -----
  221. ### SequentialWorkflow
  222. 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.
  223. ```python
  224. from swarms import Agent, SequentialWorkflow
  225. researcher = Agent(
  226. agent_name="Researcher",
  227. system_prompt="Your job is to research the provided topic and provide a detailed summary.",
  228. model_name="gpt-5.4",
  229. )
  230. writer = Agent(
  231. agent_name="Writer",
  232. system_prompt="Your job is to take the research summary and write a beautiful, engaging blog post about it.",
  233. model_name="gpt-5.4",
  234. )
  235. workflow = SequentialWorkflow(agents=[researcher, writer])
  236. final_post = workflow.run("The history and future of artificial intelligence")
  237. print(final_post)
  238. ```
  239. -----
  240. ### ConcurrentWorkflow
  241. 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.
  242. ```python
  243. from swarms import Agent, ConcurrentWorkflow
  244. market_analyst = Agent(
  245. agent_name="Market-Analyst",
  246. system_prompt="Analyze market trends and provide insights on the given topic.",
  247. model_name="gpt-5.4",
  248. max_loops=1,
  249. )
  250. financial_analyst = Agent(
  251. agent_name="Financial-Analyst",
  252. system_prompt="Provide financial analysis and recommendations on the given topic.",
  253. model_name="gpt-5.4",
  254. max_loops=1,
  255. )
  256. risk_analyst = Agent(
  257. agent_name="Risk-Analyst",
  258. system_prompt="Assess risks and provide risk management strategies for the given topic.",
  259. model_name="gpt-5.4",
  260. max_loops=1,
  261. )
  262. concurrent_workflow = ConcurrentWorkflow(
  263. agents=[market_analyst, financial_analyst, risk_analyst],
  264. max_loops=1,
  265. )
  266. results = concurrent_workflow.run(
  267. "Analyze the potential impact of AI technology on the healthcare industry"
  268. )
  269. print(results)
  270. ```
  271. ---
  272. ### AgentRearrange
  273. 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)
  274. ```python
  275. from swarms import Agent, AgentRearrange
  276. researcher = Agent(agent_name="researcher", model_name="gpt-5.4")
  277. writer = Agent(agent_name="writer", model_name="gpt-5.4")
  278. editor = Agent(agent_name="editor", model_name="gpt-5.4")
  279. flow = "researcher -> writer, editor"
  280. rearrange_system = AgentRearrange(
  281. agents=[researcher, writer, editor],
  282. flow=flow,
  283. )
  284. outputs = rearrange_system.run("Analyze the impact of AI on modern cinema.")
  285. print(outputs)
  286. ```
  287. ### GraphWorkflow
  288. `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)
  289. ```python
  290. from swarms import Agent, GraphWorkflow
  291. researcher = Agent(agent_name="Researcher", system_prompt="Research the topic and list the key findings.", model_name="gpt-5.4")
  292. writer = Agent(agent_name="Writer", system_prompt="Write a clear article from the research.", model_name="gpt-5.4")
  293. reviewer = Agent(agent_name="Reviewer", system_prompt="Review the article for accuracy and clarity.", model_name="gpt-5.4")
  294. workflow = GraphWorkflow()
  295. workflow.add_nodes([researcher, writer, reviewer])
  296. workflow.add_edge(researcher, writer)
  297. workflow.add_edge(writer, reviewer)
  298. print(workflow.run("Write a short article on the rise of small language models."))
  299. ```
  300. ----
  301. ### SwarmRouter: The Universal Swarm Orchestrator
  302. `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)
  303. ```python
  304. from swarms import Agent, SwarmRouter
  305. writer = Agent(agent_name="Writer", system_prompt="You are a creative writer.", model_name="gpt-5.4")
  306. editor = Agent(agent_name="Editor", system_prompt="You are an expert editor for stories.", model_name="gpt-5.4")
  307. router = SwarmRouter(
  308. agents=[writer, editor],
  309. swarm_type="SequentialWorkflow",
  310. )
  311. print(router.run("Write a short story about a robot who discovers music."))
  312. ```
  313. -------
  314. ### AutoSwarmBuilder: Autonomous Agent Generation
  315. `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)
  316. ```python
  317. from swarms import AutoSwarmBuilder
  318. import json
  319. swarm = AutoSwarmBuilder(
  320. name="My Swarm",
  321. description="A swarm of agents",
  322. verbose=True,
  323. max_loops=1,
  324. return_agents=True,
  325. model_name="gpt-5.4",
  326. )
  327. result = swarm.run(
  328. task="Create an accounting team to analyze crypto transactions, "
  329. "there must be 5 agents in the team with extremely extensive prompts. "
  330. "Make the prompts extremely detailed and specific and long and comprehensive. "
  331. "Make sure to include all the details of the task in the prompts."
  332. )
  333. print(json.dumps(result, indent=4))
  334. ```
  335. -------
  336. ### MixtureOfAgents (MoA)
  337. `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)
  338. ```python
  339. from swarms import Agent, MixtureOfAgents
  340. financial_analyst = Agent(agent_name="FinancialAnalyst", system_prompt="Analyze financial data.", model_name="gpt-5.4")
  341. market_analyst = Agent(agent_name="MarketAnalyst", system_prompt="Analyze market trends.", model_name="gpt-5.4")
  342. risk_analyst = Agent(agent_name="RiskAnalyst", system_prompt="Analyze investment risks.", model_name="gpt-5.4")
  343. aggregator = Agent(
  344. agent_name="InvestmentAdvisor",
  345. system_prompt="Synthesize the financial, market, and risk analyses to provide a final investment recommendation.",
  346. model_name="gpt-5.4"
  347. )
  348. moa_swarm = MixtureOfAgents(
  349. agents=[financial_analyst, market_analyst, risk_analyst],
  350. aggregator_agent=aggregator,
  351. )
  352. recommendation = moa_swarm.run("Should we invest in NVIDIA stock right now?")
  353. print(recommendation)
  354. ```
  355. ----
  356. ### GroupChat
  357. 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.
  358. ```python
  359. from swarms import Agent, GroupChat, RESPOND_TOOL
  360. tech_optimist = Agent(
  361. agent_name="TechOptimist",
  362. system_prompt="Argue for the benefits of AI in society.",
  363. model_name="gpt-5.4",
  364. max_loops=1,
  365. persistent_memory=False,
  366. tools_list_dictionary=[RESPOND_TOOL],
  367. )
  368. tech_critic = Agent(
  369. agent_name="TechCritic",
  370. system_prompt="Argue against the unchecked advancement of AI.",
  371. model_name="gpt-5.4",
  372. max_loops=1,
  373. persistent_memory=False,
  374. tools_list_dictionary=[RESPOND_TOOL],
  375. )
  376. chat = GroupChat(
  377. agents=[tech_optimist, tech_critic],
  378. max_loops=10,
  379. threshold=0.5,
  380. )
  381. result = chat.run("Let's discuss the societal impact of artificial intelligence.")
  382. print(result)
  383. ```
  384. ----
  385. ### HierarchicalSwarm
  386. 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.
  387. ```python
  388. from swarms import Agent, HierarchicalSwarm
  389. content_strategist = Agent(
  390. agent_name="Content-Strategist",
  391. system_prompt="You are a senior content strategist. Develop comprehensive content strategies, editorial calendars, and content roadmaps.",
  392. model_name="gpt-5.4"
  393. )
  394. creative_director = Agent(
  395. agent_name="Creative-Director",
  396. system_prompt="You are a creative director. Develop compelling advertising concepts, visual directions, and campaign creativity.",
  397. model_name="gpt-5.4"
  398. )
  399. seo_specialist = Agent(
  400. agent_name="SEO-Specialist",
  401. system_prompt="You are an SEO expert. Conduct keyword research, optimize content, and develop organic growth strategies.",
  402. model_name="gpt-5.4"
  403. )
  404. brand_strategist = Agent(
  405. agent_name="Brand-Strategist",
  406. system_prompt="You are a brand strategist. Develop brand positioning, identity systems, and market differentiation strategies.",
  407. model_name="gpt-5.4"
  408. )
  409. marketing_swarm = HierarchicalSwarm(
  410. name="Marketing-Team-Swarm",
  411. description="A comprehensive marketing team with specialized agents coordinated by a director",
  412. agents=[content_strategist, creative_director, seo_specialist, brand_strategist],
  413. max_loops=2,
  414. verbose=True
  415. )
  416. result = marketing_swarm.run(
  417. "Develop a comprehensive marketing strategy for a new SaaS product launch. "
  418. "The product is a project management tool targeting small to medium businesses. "
  419. "Coordinate the team to create content strategy, creative campaigns, SEO optimization, "
  420. "and brand positioning that work together cohesively."
  421. )
  422. print(result)
  423. ```
  424. ---
  425. ### HeavySwarm
  426. 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)
  427. ```python
  428. from swarms import HeavySwarm
  429. from swarms_tools import exa_search
  430. swarm = HeavySwarm(
  431. name="Gold ETF Research Team",
  432. description="A team of agents that research the best gold ETFs",
  433. worker_model_name="claude-sonnet-4-20250514",
  434. show_dashboard=True,
  435. question_agent_model_name="gpt-5.4",
  436. loops_per_agent=1,
  437. agent_prints_on=False,
  438. worker_tools=[exa_search],
  439. random_loops_per_agent=True,
  440. )
  441. prompt = (
  442. "Find the best 3 gold ETFs. For each ETF, provide the ticker symbol, "
  443. "full name, current price, expense ratio, assets under management, and "
  444. "a brief explanation of why it is considered among the best. Present the information "
  445. "in a clear, structured format suitable for investors. Scrape the data from the web. "
  446. )
  447. out = swarm.run(prompt)
  448. print(out)
  449. ```
  450. ---
  451. ### Social Algorithms
  452. **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)
  453. ```python
  454. from swarms import Agent, SocialAlgorithms
  455. def research_analysis_synthesis_algorithm(agents, task, **kwargs):
  456. research_result = agents[0].run(f"Research: {task}")
  457. analysis = agents[1].run(f"Analyze this research: {research_result}")
  458. synthesis = agents[2].run(f"Synthesize: {research_result} + {analysis}")
  459. return {
  460. "research": research_result,
  461. "analysis": analysis,
  462. "synthesis": synthesis
  463. }
  464. researcher = Agent(
  465. agent_name="Researcher",
  466. agent_description="Expert in comprehensive research and information gathering.",
  467. model_name="gpt-5.4"
  468. )
  469. analyst = Agent(
  470. agent_name="Analyst",
  471. agent_description="Specialist in analyzing and interpreting data.",
  472. model_name="gpt-5.4"
  473. )
  474. synthesizer = Agent(
  475. agent_name="Synthesizer",
  476. agent_description="Focused on synthesizing and integrating research insights.",
  477. model_name="gpt-5.4"
  478. )
  479. social_alg = SocialAlgorithms(
  480. name="Research-Analysis-Synthesis",
  481. agents=[researcher, analyst, synthesizer],
  482. social_algorithm=research_analysis_synthesis_algorithm,
  483. verbose=True
  484. )
  485. result = social_alg.run("The impact of AI on healthcare")
  486. print(result.final_outputs)
  487. ```
  488. ---
  489. ## Documentation
  490. 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.
  491. | Resource | Link | What it's for |
  492. |---|---|---|
  493. | **Main documentation** | [docs.swarms.world](https://docs.swarms.world) | Guides, API reference, tutorials |
  494. | **`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 |
  495. | **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) |
  496. | **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 |
  497. | **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 |
  498. | **Environment setup** | [docs.swarms.world/environment-setup](https://docs.swarms.world/environment-setup) | API keys, model providers, and configuration options |
  499. > **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.
  500. ---
  501. ## Using Swarms with AI Coding Assistants
  502. 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.
  503. 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.
  504. Two hosted MCP servers give an assistant live Swarms context instead of training data that may predate a rename:
  505. | Server | URL | Key | What it does |
  506. |---|---|---|---|
  507. | Docs | `https://docs.swarms.world/mcp` | none | Searches and reads the current documentation |
  508. | Marketplace | `https://swarms.world/mcp` | Swarms API key for calls | Searches, reads and publishes agents, prompts and tools on [swarms.world](https://swarms.world) |
  509. 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).
  510. Claude Code:
  511. ```bash
  512. claude mcp add --transport http swarms-docs https://docs.swarms.world/mcp
  513. claude mcp add --transport http swarms-marketplace https://swarms.world/mcp \
  514. --header "Authorization: Bearer $SWARMS_API_KEY"
  515. ```
  516. Cursor, in `.cursor/mcp.json`:
  517. ```json
  518. {
  519. "mcpServers": {
  520. "swarms-docs": { "url": "https://docs.swarms.world/mcp" },
  521. "swarms-marketplace": {
  522. "url": "https://swarms.world/mcp",
  523. "headers": { "Authorization": "Bearer ${env:SWARMS_API_KEY}" }
  524. }
  525. }
  526. }
  527. ```
  528. ---
  529. ## Features
  530. 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)
  531. | Category | Features | Benefits |
  532. |----------|----------|-----------|
  533. | **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 |
  534. | **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 |
  535. | **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 |
  536. | **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 |
  537. | **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 |
  538. ## Supported Protocols & Integrations
  539. Swarms seamlessly integrates with industry-standard protocols and open specifications, unlocking powerful capabilities for tool integration, payment processing, distributed agent orchestration, and model interoperability.
  540. | Protocol | Description | Documentation |
  541. |----------|-------------|---------------|
  542. | **[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) |
  543. | **[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/) |
  544. | **[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) |
  545. | **[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) |
  546. | **[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/) |
  547. | **[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) |
  548. ---
  549. ## Examples
  550. Explore comprehensive examples and tutorials to learn how to use Swarms effectively [HERE](examples/README.md)
  551. ---
  552. ## Contribute to Swarms
  553. 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.
  554. Learn more about how you can make a meaningful impact in our [Contributor's Guide](https://docs.swarms.world/community/contributing).
  555. ### How to Contribute
  556. We've made it easy to start contributing. Here's how you can help:
  557. 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.
  558. 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.
  559. 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).
  560. 4. **Join the Discussion:** To participate in roadmap discussions and connect with other developers, join our community on [**Discord**](https://discord.gg/EamjgSaEQf).
  561. 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.
  562. ### Thank You to Our Contributors
  563. Thank you for contributing to swarms. Your work is extremely appreciated and recognized.
  564. <a href="https://github.com/kyegomez/swarms/graphs/contributors">
  565. <img src="https://contrib.rocks/image?repo=kyegomez/swarms" />
  566. </a>
  567. ## Join Swarms
  568. 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.
  569. - **Check Open roles:** [swarms.ai/hiring](https://swarms.ai/hiring)
  570. - **Get in touch:** email [kye@swarms.world](mailto:kye@swarms.world) to learn more
  571. ## Join the Discord
  572. 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.
  573. [Join the Swarms Discord →](https://discord.gg/EamjgSaEQf)
  574. -----
  575. ## Join the Swarms Community!
  576. Join our community of agent engineers and researchers for technical support, cutting-edge updates, and exclusive access to world-class agent engineering insights!
  577. | Platform | Description | Link |
  578. |----------|-------------|------|
  579. | Documentation | Official documentation and guides | [docs.swarms.world](https://docs.swarms.world) |
  580. | Blog | Latest updates and technical articles | [Medium](https://medium.com/@kyeg) |
  581. | Discord | Live chat and community support | [Join Discord](https://discord.gg/EamjgSaEQf) |
  582. | Twitter | Latest news and announcements | [@swarms_corp](https://twitter.com/swarms_corp) |
  583. | LinkedIn | Professional network and updates | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) |
  584. | YouTube | Tutorials and demos | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) |
  585. | Events | Join our community events | [Sign up here](https://lu.ma/swarms_calendar) |
  586. | Onboarding Session | Get onboarded with Kye Gomez, creator and lead maintainer of Swarms | [Book Session](https://cal.com/swarms/swarms-onboarding-session) |
  587. ------
  588. ## Citation
  589. If you use **swarms** in your research, please cite the project by referencing the metadata in [CITATION.cff](./CITATION.cff).
  590. ```bibtex
  591. @misc{SWARMS_2022,
  592. author = {Kye Gomez and Pliny and Zack Bradshaw and Ilumn and Harshal and the Swarms Community},
  593. title = {{Swarms: Production-Grade Multi-Agent Infrastructure Platform}},
  594. year = {2022},
  595. howpublished = {\url{https://github.com/kyegomez/swarms}},
  596. note = {Documentation available at \url{https://docs.swarms.world}},
  597. version = {latest}
  598. ```
  599. ---
  600. # License
  601. Swarms is licensed under the Apache License 2.0. [Learn more here](./LICENSE)

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.