{"owner":"kyegomez","repo":"swarms","hasSkills":true,"totalSkillsCount":10,"totalTokensCount":14159,"categories":["claude-rule","subagent-persona","anthropic-skill","plugin-manifest"],"hasMcp":false,"mcpConfig":null,"found":["CLAUDE.md","examples/mcp/agents/README.md","examples/single_agent/capabilities/skills/code-review/SKILL.md","examples/single_agent/capabilities/skills/data-visualization/SKILL.md","examples/single_agent/capabilities/skills/financial-analysis/SKILL.md","examples/single_agent/capabilities/tools/README.md","examples/tools/README.md","examples/tools/base_tool_examples/README.md","examples/tools/multi_tool_use/README.md","examples/tools/stagehand/README.md"],"skills":{"CLAUDE.md":"# CLAUDE.md — Swarms Framework Guide\n\nThis file teaches you how to build agents and multi-agent systems with the **Swarms** framework. Read it before writing any code in this repo.\n\n---\n\n## Installation & Setup\n\n```bash\npip install swarms\n```\n\nSet your LLM API key as an environment variable before running:\n\n```bash\nexport OPENAI_API_KEY=\"sk-...\"        # OpenAI / GPT models\nexport ANTHROPIC_API_KEY=\"sk-ant-...\" # Claude models\nexport GROQ_API_KEY=\"...\"             # Groq\n# Any provider supported by LiteLLM works\n```\n\nAll imports come from the top-level `swarms` package:\n\n```python\nfrom swarms import (\n    Agent,\n    SequentialWorkflow,\n    ConcurrentWorkflow,\n    AgentRearrange,\n    GraphWorkflow,\n    SwarmRouter,\n    MixtureOfAgents,\n    HierarchicalSwarm,\n    GroupChat,\n    MajorityVoting,\n    # ...\n)\n```\n\n---\n\n## Project Layout\n\n```\nswarms/\n├── swarms/\n│   ├── structs/         # All agent + multi-agent structures (61 files)\n│   │   ├── agent.py             # Core Agent class\n│   │   ├── conversation.py      # Conversation / memory management\n│   │   ├── sequential_workflow.py\n│   │   ├── concurrent_workflow.py\n│   │   ├── agent_rearrange.py\n│   │   ├── graph_workflow.py\n│   │   ├── swarm_router.py      # Single-entry-point router\n│   │   ├── mixture_of_agents.py\n│   │   ├── hiearchical_swarm.py\n│   │   ├── groupchat.py\n│   │   ├── majority_voting.py\n│   │   ├── council_as_judge.py\n│   │   ├── debate_with_judge.py\n│   │   ├── heavy_swarm.py\n│   │   ├── round_robin.py\n│   │   ├── planner_worker_swarm.py\n│   │   ├── auto_swarm_builder.py\n│   │   └── multi_agent_exec.py  # run_agents_concurrently + friends\n│   ├── tools/           # Tool utilities, MCP, schema conversion\n│   └── utils/           # Logging, formatting helpers\n├── examples/            # 586 runnable examples\n│   ├── single_agent/\n│   ├── multi_agent/\n│   ├── tools/\n│   └── guides/\n└── v12_examples/        # New v12 feature examples\n```\n\nLook in `examples/` first before writing new code — there is almost certainly an existing example close to what you need.\n\n---\n\n## Core Primitive: Agent\n\n`Agent` is the single building block everything else composes. All multi-agent structures wrap one or more `Agent` instances.\n\n### Minimal agent\n\n```python\nfrom swarms import Agent\n\nagent = Agent(\n    agent_name=\"Analyst\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n)\n\nresult = agent.run(\"Summarise the current state of LLM research.\")\nprint(result)\n```\n\n### Key constructor parameters\n\n| Parameter | Type | Default | Purpose |\n|---|---|---|---|\n| `agent_name` | str | `\"swarm-worker-01\"` | Unique name — used for memory file paths |\n| `agent_description` | str | generic | Shown to orchestrators for routing |\n| `system_prompt` | str | built-in | The agent's persona / instructions |\n| `model_name` | str | `\"gpt-5.4\"` | Any LiteLLM model string |\n| `max_loops` | int \\| `\"auto\"` | `1` | Loops before returning; `\"auto\"` = autonomous until done |\n| `tools` | list[Callable] | `None` | Python functions the agent can call |\n| `streaming_on` | bool | `False` | Stream tokens to stdout |\n| `interactive` | bool | `False` | REPL mode — prompt user for input each loop |\n| `context_length` | int | `None` | Token budget; triggers compression at 90 % |\n| `context_compression` | bool | `True` | Auto-summarise when near context limit (v12) |\n| `persistent_memory` | bool | `False` | Read/write MEMORY.md across restarts (v12); opt in explicitly |\n| `temperature` | float | `0.5` | Sampling temperature |\n| `max_tokens` | int | model's max output | Max tokens per LLM call. Unset resolves to the model's own output limit |\n| `reasoning_effort` | str | `None` | `\"low\"`, `\"medium\"`, `\"high\"` for reasoning models |\n| `thinking_tokens` | int | `None` | Extended thinking budget (Claude) |\n| `output_type` | str | `\"str-all-except-first\"` | How to format returned output |\n| `mcp_url` | str | `None` | MCP server URL to load tools from |\n| `handoffs` | list | `None` | Agents this agent can hand off to |\n| `plan_enabled` | bool | `False` | Generate a plan before execution |\n| `autosave` | bool | `False` | Save agent state to disk after each run |\n\n### Autonomous loop (`max_loops=\"auto\"`)\n\nWhen `max_loops=\"auto\"` the agent runs a plan→execute→reflect loop until it decides it is done. It automatically gets access to:\n- A `think` tool (disabled when `thinking_tokens` is set)\n- A `grep` tool for searching files (v12)\n- Bash / file tools if configured\n\n```python\nagent = Agent(\n    agent_name=\"Researcher\",\n    model_name=\"gpt-5.4\",\n    max_loops=\"auto\",\n    interactive=False,\n)\nresult = agent.run(\"Research the top 5 vector databases and compare them.\")\n```\n\n### Model names\n\nUse any LiteLLM-compatible string:\n\n```python\n# OpenAI\nmodel_name=\"gpt-5.4\"\nmodel_name=\"gpt-5.4-mini\"\nmodel_name=\"o3\"\n\n# Anthropic\nmodel_name=\"claude-opus-4-7-20251001\"\nmodel_name=\"claude-sonnet-4-6\"\nmodel_name=\"claude-haiku-4-5-20251001\"\n\n# Groq\nmodel_name=\"groq/llama-3.3-70b-versatile\"\n\n# Google\nmodel_name=\"gemini/gemini-2.5-pro\"\n```\n\n### Running with images\n\n```python\nresult = agent.run(\n    task=\"Describe what you see in this chart.\",\n    img=\"path/to/chart.png\",   # or base64 string or URL\n)\n```\n\n---\n\n## Memory & Persistence (v12)\n\n### `persistent_memory=True` (opt in)\n\nOn startup the agent reads `{workspace}/agents/{agent_name}/MEMORY.md` and injects it as a system preamble. On each response it appends to that file. State survives process restarts automatically.\n\n```python\nagent = Agent(\n    agent_name=\"ProjectAssistant\",\n    model_name=\"gpt-5.4\",\n    persistent_memory=True,   # off by default; opt in\n)\n# First run: agent has no prior context\nagent.run(\"My project is called Helios. Remember that.\")\n\n# New process, same agent_name → agent remembers \"Helios\".\n# persistent_memory must be set here too; it is False by default.\nagent2 = Agent(\n    agent_name=\"ProjectAssistant\",\n    model_name=\"gpt-5.4\",\n    persistent_memory=True,\n)\nagent2.run(\"What is my project called?\")\n```\n\n### `persistent_memory=False` (default)\n\nFully stateless — no disk reads or writes. Use for short, isolated tasks where carry-over would be harmful.\n\n```python\nagent = Agent(\n    agent_name=\"OneShot\",\n    model_name=\"gpt-5.4\",\n    persistent_memory=False,\n)\n```\n\n### `context_compression=True` (default)\n\n`ContextCompressor` fires automatically when token usage crosses 90 % of `context_length`. It summarises and rewrites `MEMORY.md` in place so long sessions never hit the context wall.\n\n```python\nagent = Agent(\n    agent_name=\"LongSession\",\n    model_name=\"gpt-5.4\",\n    context_length=32000,\n    context_compression=True,   # default\n)\n```\n\n### Conversation.compact()\n\nManually collapse history to a single summary; creates a timestamped archive before rewriting:\n\n```python\nfrom swarms.structs.conversation import Conversation\n\nconv = Conversation(agent_name=\"MyAgent\", system_prompt=\"You are helpful.\")\nconv.add(\"user\", \"Tell me about X\")\nconv.add(\"assistant\", \"X is ...\")\n\n# Collapse history, archive the full log\nconv.compact(summary=\"User asked about X. Assistant explained X.\")\n```\n\n---\n\n## Tools\n\n### Python functions as tools\n\nDecorate any Python function with a docstring — the framework converts it to an OpenAI function-calling schema automatically:\n\n```python\nimport yfinance as yf\nfrom swarms import Agent\n\ndef get_stock_price(ticker: str) -> str:\n    \"\"\"Fetch the current stock price for a given ticker symbol.\n\n    Args:\n        ticker: Stock ticker symbol, e.g. 'AAPL'.\n\n    Returns:\n        Current price as a formatted string.\n    \"\"\"\n    data = yf.Ticker(ticker)\n    price = data.fast_info[\"last_price\"]\n    return f\"{ticker}: ${price:.2f}\"\n\nagent = Agent(\n    agent_name=\"StockAnalyst\",\n    model_name=\"gpt-5.4\",\n    tools=[get_stock_price],\n    max_loops=3,\n)\nresult = agent.run(\"What is the current price of Apple and Microsoft?\")\n```\n\n### Multiple tools\n\n```python\nagent = Agent(\n    agent_name=\"ResearchAgent\",\n    model_name=\"gpt-5.4\",\n    tools=[search_web, get_stock_price, read_file, write_file],\n    max_loops=\"auto\",\n)\n```\n\n### Tool schema from Pydantic\n\n```python\nfrom swarms.tools.pydantic_to_json import base_model_to_openai_function\nfrom pydantic import BaseModel\n\nclass WeatherQuery(BaseModel):\n    city: str\n    units: str = \"celsius\"\n\nschema = base_model_to_openai_function(WeatherQuery)\n```\n\n---\n\n## Streaming\n\n### Stream to stdout\n\n```python\nagent = Agent(\n    agent_name=\"Writer\",\n    model_name=\"gpt-5.4\",\n    streaming_on=True,\n)\nagent.run(\"Write a short poem about distributed systems.\")\n```\n\n### Stream tokens to a callback\n\n```python\ndef handle_token(token: str) -> None:\n    print(token, end=\"\", flush=True)\n\nagent = Agent(\n    agent_name=\"Writer\",\n    model_name=\"gpt-5.4\",\n    streaming_callback=handle_token,\n)\nagent.run(\"Write a haiku.\")\n```\n\n### Async streaming (`arun_stream`)\n\n```python\nimport asyncio\nfrom swarms import Agent\n\nagent = Agent(agent_name=\"AsyncWriter\", model_name=\"gpt-5.4\", streaming_on=True)\n\nasync def main():\n    async for token in agent.arun_stream(\"Explain async/await in Python.\"):\n        print(token, end=\"\", flush=True)\n\nasyncio.run(main())\n```\n\n---\n\n## Multi-Agent Structures\n\n### Sequential Workflow\n\nAgents execute **one after another**. The output of each agent is passed as context to the next.\n\n```python\nfrom swarms import Agent, SequentialWorkflow\n\nresearcher = Agent(agent_name=\"Researcher\", model_name=\"gpt-5.4\", max_loops=1)\nanalyst   = Agent(agent_name=\"Analyst\",    model_name=\"gpt-5.4\", max_loops=1)\nwriter    = Agent(agent_name=\"Writer\",     model_name=\"gpt-5.4\", max_loops=1)\n\npipeline = SequentialWorkflow(\n    agents=[researcher, analyst, writer],\n    max_loops=1,\n)\nresult = pipeline.run(\"Analyse the impact of interest rate hikes on tech stocks.\")\n```\n\n**When to use:** Linear pipelines where each step depends on the prior step's output. Research → Analysis → Report. Extraction → Transformation → Load.\n\n---\n\n### Concurrent Workflow\n\nAll agents run **in parallel** on the same task. Results are collected and returned together.\n\n```python\nfrom swarms import Agent, ConcurrentWorkflow\n\nagents = [\n    Agent(agent_name=f\"Worker-{i}\", model_name=\"gpt-5.4\", max_loops=1)\n    for i in range(5)\n]\n\nworkflow = ConcurrentWorkflow(agents=agents)\nresults = workflow.run(\"List 10 use cases for multi-agent AI systems.\")\n```\n\n**When to use:** Independent subtasks that can run simultaneously. Analysing multiple documents. Querying multiple data sources. Generating multiple creative variants.\n\n---\n\n### AgentRearrange — Flow DSL\n\nDefine execution flow as a string using a simple DSL. Mix sequential (`->`) and parallel (`,`) execution.\n\n```python\nfrom swarms import Agent, AgentRearrange\n\nplanner  = Agent(agent_name=\"Planner\",  model_name=\"gpt-5.4\", max_loops=1)\ncoder    = Agent(agent_name=\"Coder\",    model_name=\"gpt-5.4\", max_loops=1)\nreviewer = Agent(agent_name=\"Reviewer\", model_name=\"gpt-5.4\", max_loops=1)\ntester   = Agent(agent_name=\"Tester\",   model_name=\"gpt-5.4\", max_loops=1)\n\npipeline = AgentRearrange(\n    agents=[planner, coder, reviewer, tester],\n    flow=\"Planner -> Coder -> Reviewer, Tester\",\n    #        sequential  ↑      parallel  ↑\n    max_loops=1,\n)\nresult = pipeline.run(\"Build a Python function that validates email addresses.\")\n```\n\n**Flow DSL rules:**\n- `A -> B` — A runs, then B receives A's output\n- `A, B` — A and B run concurrently with the same input\n- `A -> B, C -> D` — A runs first, then B and C run concurrently, then D receives their combined output\n\n`AgentRearrange` has no built-in human-in-the-loop step — every name in `flow` must correspond to an agent in `agents`, or the flow will fail at run time. For a human checkpoint, break the pipeline into separate `AgentRearrange`/`Agent.run()` calls and insert your own logic (e.g. `input()`) between them — see the \"Human-in-the-loop with AgentRearrange\" pattern below.\n\n**When to use:** Any workflow where you need explicit, readable control over agent execution order and parallelism.\n\n---\n\n### GraphWorkflow — DAG Execution\n\nFull directed-acyclic-graph (DAG) execution. Nodes are agents; edges are dependencies. Topological sort ensures correct order. Supports per-node callbacks and token streaming.\n\n```python\nfrom swarms import Agent, GraphWorkflow, Node, Edge, NodeType\n\n# Build agents\nanalyst  = Agent(agent_name=\"Analyst\",  model_name=\"gpt-5.4-mini\", max_loops=1)\nwriter   = Agent(agent_name=\"Writer\",   model_name=\"gpt-5.4-mini\", max_loops=1)\nreviewer = Agent(agent_name=\"Reviewer\", model_name=\"gpt-5.4-mini\", max_loops=1)\npublisher = Agent(agent_name=\"Publisher\", model_name=\"gpt-5.4-mini\", max_loops=1)\n\n# Build graph\nwf = GraphWorkflow()\nwf.add_node(Node(id=\"analyst\",   type=NodeType.AGENT, agent=analyst))\nwf.add_node(Node(id=\"writer\",    type=NodeType.AGENT, agent=writer))\nwf.add_node(Node(id=\"reviewer\",  type=NodeType.AGENT, agent=reviewer))\nwf.add_node(Node(id=\"publisher\", type=NodeType.AGENT, agent=publisher))\n\nwf.add_edge(Edge(source=\"analyst\",  target=\"writer\"))\nwf.add_edge(Edge(source=\"writer\",   target=\"reviewer\"))\nwf.add_edge(Edge(source=\"reviewer\", target=\"publisher\"))\n\nwf.set_entry_points([\"analyst\"])\nwf.set_end_points([\"publisher\"])\n\n# Run with callbacks\ndef on_done(node_name: str, result: str) -> None:\n    print(f\"[{node_name}] finished — {len(result)} chars\")\n\nresults = wf.run(\n    task=\"Produce a market report on AI chips.\",\n    on_node_complete=on_done,          # fires after each node\n    streaming_callback=lambda tok: print(tok, end=\"\", flush=True),\n)\n```\n\n**Diamond / fan-out fan-in pattern:**\n\n```python\n# analyst feeds both writer AND researcher concurrently,\n# then editor combines both outputs\nwf.add_edge(Edge(source=\"analyst\",    target=\"writer\"))\nwf.add_edge(Edge(source=\"analyst\",    target=\"researcher\"))\nwf.add_edge(Edge(source=\"writer\",     target=\"editor\"))\nwf.add_edge(Edge(source=\"researcher\", target=\"editor\"))\n```\n\n**When to use:** Complex dependency graphs, fan-out/fan-in patterns, when you need precise control over which agents depend on which.\n\n---\n\n### SwarmRouter — Single Entry Point\n\n`SwarmRouter` is the highest-level abstraction. Pass it a list of agents and a `swarm_type` — it handles the rest. Use this when you want to switch architectures without rewriting orchestration code.\n\n```python\nfrom swarms import Agent, SwarmRouter\n\nagents = [\n    Agent(agent_name=\"Analyst\",  model_name=\"gpt-5.4\", max_loops=1),\n    Agent(agent_name=\"Writer\",   model_name=\"gpt-5.4\", max_loops=1),\n    Agent(agent_name=\"Reviewer\", model_name=\"gpt-5.4\", max_loops=1),\n]\n\nrouter = SwarmRouter(\n    agents=agents,\n    swarm_type=\"SequentialWorkflow\",   # swap to any SwarmType below\n    max_loops=1,\n)\nresult = router.run(\"Write a blog post about transformer architectures.\")\n```\n\n**All `swarm_type` options:**\n\n| SwarmType | Behaviour |\n|---|---|\n| `\"SequentialWorkflow\"` | Agents run one after another |\n| `\"ConcurrentWorkflow\"` | Agents run in parallel |\n| `\"AgentRearrange\"` | Flow-DSL based execution |\n| `\"MixtureOfAgents\"` | Workers + aggregator layer |\n| `\"HierarchicalSwarm\"` | Boss delegates to workers |\n| `\"GroupChat\"` | Multi-agent round-table discussion |\n| `\"MultiAgentRouter\"` | Task routed to best-fit agent |\n| `\"MajorityVoting\"` | Agents vote; majority wins |\n| `\"CouncilAsAJudge\"` | Council deliberates; judge decides |\n| `\"DebateWithJudge\"` | Agents debate; judge rules |\n| `\"HeavySwarm\"` | Intensive multi-loop deep analysis |\n| `\"RoundRobin\"` | Round-robin task distribution |\n| `\"PlannerWorkerSwarm\"` | Planner + worker delegation |\n| `\"BatchedGridWorkflow\"` | Grid-based batch execution |\n| `\"LLMCouncil\"` | LLM-based council decisions |\n| `\"AutoSwarmBuilder\"` | Auto-configures everything |\n| `\"auto\"` | Router selects swarm_type automatically |\n\n---\n\n### MixtureOfAgents\n\nMultiple **worker** agents each respond to the task independently, then an **aggregator** agent synthesises all responses into a final answer. Repeat for multiple layers.\n\n```python\nfrom swarms import Agent, MixtureOfAgents\n\nworkers = [\n    Agent(agent_name=\"Worker-GPT\",    model_name=\"gpt-5.4\",       max_loops=1),\n    Agent(agent_name=\"Worker-Claude\", model_name=\"claude-sonnet-4-6\", max_loops=1),\n    Agent(agent_name=\"Worker-Llama\",  model_name=\"groq/llama-3.3-70b-versatile\", max_loops=1),\n]\n\naggregator = Agent(\n    agent_name=\"Aggregator\",\n    model_name=\"gpt-5.4\",\n    system_prompt=\"Synthesise the following expert responses into one coherent answer.\",\n    max_loops=1,\n)\n\nmoa = MixtureOfAgents(\n    agents=workers,\n    aggregator_agent=aggregator,\n    layers=2,        # run worker→aggregate cycle this many times\n    max_loops=1,\n)\nresult = moa.run(\"What are the best practices for securing a Kubernetes cluster?\")\n```\n\n**When to use:** High-stakes tasks where you want multiple independent perspectives merged into a consensus. Works especially well with diverse model providers.\n\n---\n\n### HierarchicalSwarm\n\nA director agent breaks the task into subtasks and delegates them to worker agents. Workers report back; director synthesises.\n\n```python\nfrom swarms import Agent, HierarchicalSwarm\n\ndirector = Agent(\n    agent_name=\"Director\",\n    agent_description=\"Breaks complex tasks into subtasks and delegates them.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n)\n\nworkers = [\n    Agent(agent_name=\"DataWorker\",    model_name=\"gpt-5.4-mini\", max_loops=1),\n    Agent(agent_name=\"WritingWorker\", model_name=\"gpt-5.4-mini\", max_loops=1),\n    Agent(agent_name=\"ReviewWorker\",  model_name=\"gpt-5.4-mini\", max_loops=1),\n]\n\nswarm = HierarchicalSwarm(\n    director=director,\n    agents=workers,\n    max_loops=2,\n)\nresult = swarm.run(\"Produce a comprehensive competitive analysis of the AI chip market.\")\n```\n\n**When to use:** Tasks naturally decomposed into subtasks where a coordinator must manage work allocation and synthesis.\n\n---\n\n### GroupChat\n\nAn asynchronous, self-selecting groupchat. There are no rounds or speaker-selection functions — every agent listens in parallel and decides on its own whether to chime in. A forced `respond(score, message)` function call asks each agent how much it wants to speak (0..1); replies above `threshold` are broadcast. The chat ends when `max_loops` messages have been posted or no message arrives for `idle_timeout` seconds.\n\n```python\nfrom swarms import Agent\nfrom swarms.structs.groupchat import GroupChat, RESPOND_TOOL\n\n# Every agent MUST carry RESPOND_TOOL so the chat can ask it whether to speak.\n# Recommended per-agent: max_loops=1, persistent_memory=False.\noptimist = Agent(\n    agent_name=\"Optimist\",\n    system_prompt=\"You argue for the benefits.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n    persistent_memory=False,\n    tools_list_dictionary=[RESPOND_TOOL],\n)\npessimist = Agent(\n    agent_name=\"Pessimist\",\n    system_prompt=\"You argue for the risks.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n    persistent_memory=False,\n    tools_list_dictionary=[RESPOND_TOOL],\n)\nrealist = Agent(\n    agent_name=\"Realist\",\n    system_prompt=\"You seek balanced analysis.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n    persistent_memory=False,\n    tools_list_dictionary=[RESPOND_TOOL],\n)\n\nchat = GroupChat(\n    agents=[optimist, pessimist, realist],\n    max_loops=10,        # hard cap on total messages posted\n    threshold=0.5,       # min decision score (0..1) to publish a reply\n    idle_timeout=8.0,    # seconds of silence before stopping\n)\nresult = chat.run(\"Should we adopt AI for medical diagnosis?\")\n```\n\n**Tuning:** raise `threshold` for a more selective room; lower it for livelier chats. Raise `idle_timeout` if agents need time to think before replying.\n\n---\n\n### MajorityVoting\n\nAll agents independently answer the task. The answer that appears in the majority of responses wins.\n\n```python\nfrom swarms import Agent, MajorityVoting\n\nvoters = [\n    Agent(agent_name=f\"Voter-{i}\", model_name=\"gpt-5.4-mini\", max_loops=1)\n    for i in range(5)\n]\n\nmv = MajorityVoting(agents=voters, max_loops=1)\nresult = mv.run(\"Is Python or Rust better for building a high-performance web server?\")\n```\n\n**When to use:** Classification, yes/no decisions, or any task with a discrete answer set where you want noise reduction through consensus.\n\n---\n\n### CouncilAsAJudge\n\nA council of agents each deliberate, then a judge agent makes the final ruling based on the council's reasoning.\n\n```python\nfrom swarms import Agent, CouncilAsAJudge\n\ncouncil = [\n    Agent(agent_name=\"Expert-Security\", model_name=\"gpt-5.4\", max_loops=1),\n    Agent(agent_name=\"Expert-Privacy\",  model_name=\"gpt-5.4\", max_loops=1),\n    Agent(agent_name=\"Expert-Legal\",    model_name=\"gpt-5.4\", max_loops=1),\n]\n\njudge = Agent(\n    agent_name=\"Judge\",\n    system_prompt=\"Given the council's analysis, deliver a final verdict.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n)\n\ncouncil_swarm = CouncilAsAJudge(\n    agents=council,\n    judge=judge,\n    max_loops=1,\n)\nresult = council_swarm.run(\"Should we store user biometric data on-device only?\")\n```\n\n---\n\n### DebateWithJudge\n\nTwo or more agents argue opposing positions for multiple rounds. A judge delivers a verdict at the end.\n\n```python\nfrom swarms import Agent, DebateWithJudge\n\npro  = Agent(agent_name=\"Pro\",  system_prompt=\"Argue strongly in favour.\",  model_name=\"gpt-5.4\", max_loops=1)\ncon  = Agent(agent_name=\"Con\",  system_prompt=\"Argue strongly against.\",    model_name=\"gpt-5.4\", max_loops=1)\n\njudge = Agent(\n    agent_name=\"Judge\",\n    system_prompt=\"Evaluate the debate and deliver an objective verdict.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n)\n\ndebate = DebateWithJudge(\n    agents=[pro, con],\n    judge=judge,\n    max_loops=3,   # 3 rounds of argument\n)\nresult = debate.run(\"Motion: Open-source LLMs will surpass closed-source models by 2027.\")\n```\n\n---\n\n### HeavySwarm\n\nIntensive multi-loop analysis. Each agent runs for many loops on the problem, producing deep reasoning. Best for research-grade analysis.\n\n```python\nfrom swarms import HeavySwarm\n\nswarm = HeavySwarm(\n    num_agents=4,\n    model_name=\"gpt-5.4\",\n    loops_per_agent=5,       # each agent reasons for 5 loops\n    show_output=True,\n)\nresult = swarm.run(\"Derive a novel approach to solving the alignment problem in AI.\")\n```\n\nOr via `SwarmRouter`:\n\n```python\nfrom swarms import Agent, SwarmRouter\n\nagents = [Agent(agent_name=f\"Deep-{i}\", model_name=\"gpt-5.4\", max_loops=5) for i in range(4)]\nrouter = SwarmRouter(agents=agents, swarm_type=\"HeavySwarm\")\nresult = router.run(\"Deep analysis: implications of AGI on global labour markets.\")\n```\n\n---\n\n### RoundRobinSwarm\n\nDistributes tasks to agents in a fixed rotation. Each agent handles every Nth task.\n\n```python\nfrom swarms import Agent, RoundRobinSwarm\n\nagents = [\n    Agent(agent_name=f\"Handler-{i}\", model_name=\"gpt-5.4-mini\", max_loops=1)\n    for i in range(3)\n]\n\nrr = RoundRobinSwarm(agents=agents, max_loops=1)\n\ntasks = [\"Task A\", \"Task B\", \"Task C\", \"Task D\", \"Task E\", \"Task F\"]\nfor task in tasks:\n    result = rr.run(task)\n```\n\n---\n\n### PlannerWorkerSwarm\n\nA planner agent generates a structured plan; worker agents execute each step.\n\n```python\nfrom swarms import Agent, PlannerWorkerSwarm\n\nplanner = Agent(\n    agent_name=\"Planner\",\n    system_prompt=\"You create detailed, step-by-step execution plans.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n)\n\nworkers = [\n    Agent(agent_name=f\"Worker-{i}\", model_name=\"gpt-5.4-mini\", max_loops=2)\n    for i in range(4)\n]\n\nswarm = PlannerWorkerSwarm(\n    planner_agent=planner,\n    worker_agents=workers,\n    max_loops=1,\n)\nresult = swarm.run(\"Build a complete go-to-market strategy for a B2B SaaS product.\")\n```\n\n---\n\n### AutoSwarmBuilder\n\nPass a high-level description of the task — the framework automatically creates the agents, assigns roles, and runs the appropriate swarm architecture.\n\n```python\nfrom swarms import AutoSwarmBuilder\n\nbuilder = AutoSwarmBuilder(\n    name=\"MarketResearchSwarm\",\n    description=\"A swarm that produces comprehensive market research reports\",\n    max_loops=2,\n)\nresult = builder.run(\"Research the electric vehicle market and identify growth opportunities.\")\n```\n\n**When to use:** Rapid prototyping, when you don't know yet which structure fits, or when you want the LLM to decide.\n\n---\n\n## Utility Execution Helpers\n\n```python\nfrom swarms.structs.multi_agent_exec import (\n    run_agents_concurrently,\n    run_agents_concurrently_async,\n    run_agents_with_different_tasks,\n    run_single_agent,\n)\n\n# Same task, all agents in parallel\nresults = run_agents_concurrently(agents=agents, task=\"Summarise the news today.\")\n\n# Different task per agent\ntask_map = {agent: task for agent, task in zip(agents, tasks)}\nresults = run_agents_with_different_tasks(task_map)\n\n# Async version\nimport asyncio\nresults = asyncio.run(run_agents_concurrently_async(agents=agents, task=\"...\"))\n```\n\n---\n\n## Async Support\n\n```python\nimport asyncio\nfrom swarms import Agent\n\nagent = Agent(agent_name=\"AsyncAgent\", model_name=\"gpt-5.4\")\n\nasync def main():\n    # Standard async run\n    result = await agent.arun(\"What is the capital of France?\")\n    print(result)\n\n    # Streaming async run\n    async for token in agent.arun_stream(\"Explain quantum entanglement.\"):\n        print(token, end=\"\", flush=True)\n\nasyncio.run(main())\n```\n\n---\n\n## MCP Tool Integration\n\nLoad tools from any MCP server. The agent auto-discovers available tools on startup.\n\n```python\nfrom swarms import Agent\n\n# Single MCP server\nagent = Agent(\n    agent_name=\"MCPAgent\",\n    model_name=\"gpt-5.4\",\n    mcp_url=\"http://localhost:8000/sse\",   # SSE endpoint\n    max_loops=\"auto\",\n)\n\n# Multiple MCP servers\nagent = Agent(\n    agent_name=\"MultiMCPAgent\",\n    model_name=\"gpt-5.4\",\n    mcp_urls=[\n        \"http://localhost:8000/sse\",\n        \"http://localhost:8001/sse\",\n    ],\n    max_loops=\"auto\",\n)\n\nresult = agent.run(\"Use the available tools to complete the task.\")\n```\n\nFetch tools manually:\n\n```python\nfrom swarms.tools.mcp_client_tools import get_mcp_tools_sync, aget_mcp_tools\n\ntools = get_mcp_tools_sync(server_url=\"http://localhost:8000/sse\")\n\nimport asyncio\ntools = asyncio.run(aget_mcp_tools(server_url=\"http://localhost:8000/sse\"))\n```\n\n---\n\n## Conversation Management\n\n`Conversation` manages message history with optional disk persistence.\n\n```python\nfrom swarms.structs.conversation import Conversation\n\nconv = Conversation(\n    system_prompt=\"You are a helpful assistant.\",\n    agent_name=\"MyAgent\",      # keys MEMORY.md to this name\n    time_enabled=True,         # include ISO timestamps in history\n)\n\nconv.add(\"user\", \"What is 2+2?\")\nconv.add(\"assistant\", \"4.\")\n\n# Get history as string (includes timestamps in v12)\nhistory_str = conv.return_history_as_string()\n\n# Compact + archive\nconv.compact(summary=\"User asked basic arithmetic. Answer: 4.\")\n\n# Pass to an agent\nagent = Agent(\n    agent_name=\"MyAgent\",\n    model_name=\"gpt-5.4\",\n    # agent reads MEMORY.md automatically when persistent_memory=True\n)\n```\n\n---\n\n## Choosing the Right Structure\n\n| Situation | Use |\n|---|---|\n| Simple single task | `Agent` |\n| Linear A→B→C pipeline | `SequentialWorkflow` |\n| Same task, many agents at once | `ConcurrentWorkflow` |\n| Custom mix of sequential + parallel | `AgentRearrange` |\n| Complex dependency graph / DAG | `GraphWorkflow` |\n| Need per-node callbacks or streaming | `GraphWorkflow` |\n| Multiple models, one synthesised answer | `MixtureOfAgents` |\n| Manager delegates to specialists | `HierarchicalSwarm` |\n| Open discussion / brainstorming | `GroupChat` |\n| Discrete decision via consensus | `MajorityVoting` |\n| High-stakes ruling with deliberation | `CouncilAsAJudge` |\n| Structured adversarial debate | `DebateWithJudge` |\n| Deep research, many loops | `HeavySwarm` |\n| Don't know yet / rapid prototyping | `AutoSwarmBuilder` or `SwarmRouter(swarm_type=\"auto\")` |\n| Need to switch architectures easily | `SwarmRouter` |\n\n---\n\n## Common Patterns & Recipes\n\n### Pattern: Research → Write → Review pipeline\n\n```python\nfrom swarms import Agent, SequentialWorkflow\n\npipeline = SequentialWorkflow(agents=[\n    Agent(agent_name=\"Researcher\", system_prompt=\"You research topics thoroughly.\", model_name=\"gpt-5.4\"),\n    Agent(agent_name=\"Writer\",     system_prompt=\"You write clear, engaging content.\", model_name=\"gpt-5.4\"),\n    Agent(agent_name=\"Editor\",     system_prompt=\"You improve clarity and fix errors.\", model_name=\"gpt-5.4\"),\n], max_loops=1)\n\nresult = pipeline.run(\"Write an article about the history of neural networks.\")\n```\n\n### Pattern: Fan-out to specialists, fan-in to synthesiser\n\n```python\nfrom swarms import Agent, MixtureOfAgents\n\nspecialists = [\n    Agent(agent_name=\"TechExpert\",    system_prompt=\"Analyse the technical aspects.\", model_name=\"gpt-5.4\"),\n    Agent(agent_name=\"BusinessExpert\",system_prompt=\"Analyse the business aspects.\", model_name=\"gpt-5.4\"),\n    Agent(agent_name=\"LegalExpert\",   system_prompt=\"Analyse the legal aspects.\",   model_name=\"gpt-5.4\"),\n]\nsynthesiser = Agent(agent_name=\"Synthesiser\", model_name=\"gpt-5.4\",\n                    system_prompt=\"Combine expert analyses into one coherent report.\")\n\nmoa = MixtureOfAgents(agents=specialists, aggregator_agent=synthesiser)\nresult = moa.run(\"Evaluate the risks of launching a fintech product in the EU.\")\n```\n\n### Pattern: Autonomous agent with tools and memory\n\n```python\nimport os\nfrom swarms import Agent\n\ndef search_web(query: str) -> str:\n    \"\"\"Search the web for a query and return results.\"\"\"\n    # your implementation\n    ...\n\ndef write_file(filename: str, content: str) -> str:\n    \"\"\"Write content to a file.\"\"\"\n    with open(filename, \"w\") as f:\n        f.write(content)\n    return f\"Written to {filename}\"\n\nagent = Agent(\n    agent_name=\"AutonomousResearcher\",\n    model_name=\"gpt-5.4\",\n    max_loops=\"auto\",\n    tools=[search_web, write_file],\n    persistent_memory=True,\n    context_compression=True,\n    context_length=32000,\n)\nagent.run(\"Research the top 10 open-source LLMs and write a comparison report to report.md\")\n```\n\n### Pattern: Multi-model ensemble with streaming\n\n```python\nimport sys\nfrom swarms import Agent, ConcurrentWorkflow\n\nagents = [\n    Agent(agent_name=\"GPT\",    model_name=\"gpt-5.4\",          max_loops=1),\n    Agent(agent_name=\"Claude\", model_name=\"claude-sonnet-4-6\", max_loops=1),\n    Agent(agent_name=\"Gemini\", model_name=\"gemini/gemini-2.5-pro\", max_loops=1),\n]\n\nworkflow = ConcurrentWorkflow(agents=agents)\nresults = workflow.run(\"What is the most important unsolved problem in mathematics?\")\n\nfor agent_name, answer in results.items():\n    print(f\"\\n=== {agent_name} ===\\n{answer}\")\n```\n\n### Pattern: Human-in-the-loop with AgentRearrange\n\n`AgentRearrange` has no native human-in-the-loop step — chain separate `.run()` calls yourself and insert your own checkpoint logic between them:\n\n```python\nfrom swarms import Agent\n\ndrafter  = Agent(agent_name=\"Drafter\",  model_name=\"gpt-5.4\")\nfinisher = Agent(agent_name=\"Finisher\", model_name=\"gpt-5.4\")\n\ndraft = drafter.run(\"Draft a press release about our product launch.\")\n\nprint(f\"\\nAgent says:\\n{draft}\\n\")\nfeedback = input(\"Your feedback: \")\n\nresult = finisher.run(f\"Revise this draft based on the feedback.\\n\\nDraft:\\n{draft}\\n\\nFeedback:\\n{feedback}\")\n```\n\n### Pattern: GraphWorkflow with fan-out / fan-in\n\n```python\nfrom swarms import Agent, GraphWorkflow, Node, Edge, NodeType\n\ningestion = Agent(agent_name=\"Ingestion\", model_name=\"gpt-5.4-mini\", max_loops=1)\nbranch_a  = Agent(agent_name=\"BranchA\",   model_name=\"gpt-5.4-mini\", max_loops=1)\nbranch_b  = Agent(agent_name=\"BranchB\",   model_name=\"gpt-5.4-mini\", max_loops=1)\nmerger    = Agent(agent_name=\"Merger\",    model_name=\"gpt-5.4\",      max_loops=1)\n\nwf = GraphWorkflow()\nfor a in [ingestion, branch_a, branch_b, merger]:\n    wf.add_node(Node(id=a.agent_name, type=NodeType.AGENT, agent=a))\n\nwf.add_edge(Edge(source=\"Ingestion\", target=\"BranchA\"))\nwf.add_edge(Edge(source=\"Ingestion\", target=\"BranchB\"))\nwf.add_edge(Edge(source=\"BranchA\",   target=\"Merger\"))\nwf.add_edge(Edge(source=\"BranchB\",   target=\"Merger\"))\n\nwf.set_entry_points([\"Ingestion\"])\nwf.set_end_points([\"Merger\"])\n\nresults = wf.run(task=\"Process this dataset from two angles and merge the findings.\")\n```\n\n---\n\n## What to Avoid\n\n**Don't import from submodules directly** — always import from `swarms`:\n```python\n# Wrong\nfrom swarms.structs.agent import Agent\n\n# Right\nfrom swarms import Agent\n```\n\n**Don't set `max_loops=\"auto\"` without a clear stopping condition** — the agent will loop until it decides it is done or hits a resource limit. Prefer explicit `max_loops=N` for production tasks.\n\n**Don't give all agents the same `agent_name`** — `persistent_memory` and `MEMORY.md` are keyed on `agent_name`. Duplicate names cause agents to share and corrupt each other's memory.\n\n**Don't instantiate heavyweight structures inside tight loops** — create agents and workflows once, reuse them across calls.\n\n**Don't pass `tools=[]` (empty list)** — pass `tools=None` instead. An empty list can confuse schema generation.\n\n**Don't use `streaming_on=True` and `streaming_callback` together on the same agent** — `streaming_on` streams to stdout; `streaming_callback` streams to your function. Pick one.\n\n**Don't set `context_compression=False` on very long autonomous sessions** — without compression the agent will eventually hit the context limit and raise an error.\n\n**For long-running autonomous agents in production**, always set:\n```python\nagent = Agent(\n    ...\n    persistent_memory=True,\n    context_compression=True,\n    context_length=32000,\n    autosave=True,\n)\n```\n","examples/mcp/agents/README.md":"# Agents + MCP\n\nGiving an agent tools from an MCP server. Set `mcp_url` (one server) or `mcp_urls`\n(several) and the agent discovers and calls the tools on its own.\n\n## Start here — numbered, in order\n\nEach runs against a real public server. The first four need **no MCP API key**.\n\n| # | File | Server | Auth |\n|---|---|---|---|\n| 01 | [`01_deepwiki_repo_qa.py`](01_deepwiki_repo_qa.py) | DeepWiki — Q&A over any public GitHub repo | none |\n| 02 | [`02_gitmcp_repo_docs.py`](02_gitmcp_repo_docs.py) | GitMCP — docs/code search for one repo | none |\n| 03 | [`03_microsoft_learn_docs.py`](03_microsoft_learn_docs.py) | Microsoft Learn — official Azure/.NET docs | none |\n| 04 | [`04_multi_server_agent.py`](04_multi_server_agent.py) | Two servers on one agent | none |\n| 05 | [`05_exa_web_search.py`](05_exa_web_search.py) | Exa — web search | free API key |\n| 07 | [`07_huggingface_model_search.py`](07_huggingface_model_search.py) | Hugging Face — find models & datasets | none (optional token) |\n| 10 | [`10_firecrawl_web_scraping.py`](10_firecrawl_web_scraping.py) | Firecrawl — scrape pages to markdown | API key (in URL path) |\n| 12 | [`12_semgrep_security_scan.py`](12_semgrep_security_scan.py) | Semgrep — static-analysis security scan | free token |\n| 13 | [`13_mcp_sequential_workflow.py`](13_mcp_sequential_workflow.py) | **Multi-agent**: MCP tools in a `SequentialWorkflow` | none |\n\nBetween them these cover all three ways a server takes a key — query parameter\n(05), Bearer token (12), and URL path segment (10) — plus the optional-auth\ncase (07), where a missing key degrades to anonymous access instead of\nfailing.\n\nSee [`FREE_MCP_SERVERS.md`](FREE_MCP_SERVERS.md) for the full catalog of public servers.\n\n## Configuration patterns\n\n| File | Shows |\n|---|---|\n| [`deepwiki_minimal.py`](deepwiki_minimal.py) | The smallest possible `mcp_url` agent |\n| [`mcp_connection_object.py`](mcp_connection_object.py) | `MCPConnection` instead of a bare URL — headers, auth, timeout |\n| [`multi_mcp_urls.py`](multi_mcp_urls.py) | `mcp_urls=[...]` for several servers at once |\n| [`multi_mcp_walkthrough.py`](multi_mcp_walkthrough.py) | Longer multi-server walkthrough with commentary |\n| [`mcp_with_local_tools.py`](mcp_with_local_tools.py) | MCP tools *plus* your own tool schemas on one agent |\n| [`tools_list_dictionary.py`](tools_list_dictionary.py) | The raw `tools_list_dictionary` schema format MCP tools are converted into |\n| [`finance_agent_mcp.py`](finance_agent_mcp.py) | A realistic finance agent backed by an MCP server |\n\n## Run one\n\n```bash\nexport OPENAI_API_KEY=\"sk-...\"\npython examples/mcp/agents/01_deepwiki_repo_qa.py\n```\n\nExamples pointing at `http://localhost:8000/mcp` need a local server — start one from\n[`../servers/`](../servers/) first.\n","examples/single_agent/capabilities/skills/code-review/SKILL.md":"---\nname: code-review\ndescription: Perform comprehensive code reviews focusing on best practices, security vulnerabilities, performance optimization, and maintainability\n---\n\n# Code Review Skill\n\nWhen reviewing code, follow this systematic approach to ensure thorough evaluation:\n\n## Review Checklist\n\n### 1. Code Quality\n- **Readability**: Is the code easy to understand?\n- **Naming**: Are variables, functions, and classes well-named?\n- **Structure**: Is the code properly organized and modular?\n- **Comments**: Are complex sections adequately documented?\n- **Complexity**: Are there overly complex functions that should be simplified?\n\n### 2. Security Analysis\nCheck for common vulnerabilities:\n- SQL injection vulnerabilities\n- XSS (Cross-Site Scripting) vulnerabilities\n- Authentication and authorization flaws\n- Insecure data handling (passwords, sensitive data)\n- Input validation and sanitization\n- OWASP Top 10 vulnerabilities\n\n### 3. Performance Considerations\n- Identify potential bottlenecks\n- Check for inefficient algorithms or data structures\n- Look for unnecessary database queries or API calls\n- Evaluate caching opportunities\n- Assess memory usage patterns\n\n### 4. Best Practices\n- **DRY Principle**: Eliminate code duplication\n- **SOLID Principles**: Verify adherence to design principles\n- **Error Handling**: Check for proper exception handling\n- **Testing**: Evaluate test coverage and quality\n- **Dependencies**: Review external dependencies and their versions\n\n### 5. Maintainability\n- Is the code easy to modify and extend?\n- Are there proper abstractions?\n- Is the architecture scalable?\n- Are there technical debt concerns?\n\n## Review Format\n\nStructure your review as follows:\n\n1. **Summary**: High-level overview of the changes\n2. **Critical Issues**: Security vulnerabilities or bugs that must be fixed\n3. **Major Concerns**: Significant issues affecting quality or performance\n4. **Suggestions**: Optional improvements and best practices\n5. **Positive Feedback**: Acknowledge good practices and improvements\n\n## Guidelines\n\n- Be constructive and respectful\n- Provide specific examples and suggestions\n- Explain the \"why\" behind recommendations\n- Prioritize issues by severity (critical, major, minor)\n- Reference documentation or standards when applicable\n- Consider the context and constraints of the project\n\n## Example Reviews\n\n**Security Issue:**\n```\nCRITICAL: SQL injection vulnerability detected at line 45\nCurrent: f\"SELECT * FROM users WHERE id = {user_id}\"\nRecommendation: Use parameterized queries to prevent SQL injection\n```\n\n**Performance Suggestion:**\n```\nSUGGESTION: Consider caching database results at line 123\nThe same query is executed multiple times in the loop. Cache the results\nto improve performance by ~80%.\n```\n","examples/single_agent/capabilities/skills/data-visualization/SKILL.md":"---\nname: data-visualization\ndescription: Create effective data visualizations using best practices for clarity, accuracy, and visual communication of insights\n---\n\n# Data Visualization Skill\n\nWhen creating data visualizations, follow these principles to ensure clear and effective communication:\n\n## Core Principles\n\n### 1. Choose the Right Chart Type\n- **Line Charts**: Trends over time, continuous data\n- **Bar Charts**: Comparing categories, discrete data\n- **Scatter Plots**: Relationships between variables, correlations\n- **Pie Charts**: Parts of a whole (use sparingly, max 5-6 segments)\n- **Heatmaps**: Patterns in large datasets, correlations\n- **Box Plots**: Distribution statistics, outlier detection\n\n### 2. Design Guidelines\n\n**Clarity**\n- Use clear, descriptive titles and labels\n- Include units of measurement\n- Add a legend when multiple series are present\n- Ensure adequate contrast and readability\n\n**Accuracy**\n- Start y-axis at zero for bar charts (unless good reason)\n- Use consistent scales across related charts\n- Avoid distorting data through inappropriate scaling\n- Label data points when precision matters\n\n**Simplicity**\n- Remove chart junk and unnecessary decorations\n- Use color purposefully, not decoratively\n- Limit the number of colors (5-7 max)\n- Ensure accessibility (colorblind-friendly palettes)\n\n### 3. Color Best Practices\n- **Sequential**: Use for ordered data (light to dark)\n- **Diverging**: Use for data with a meaningful midpoint\n- **Categorical**: Use for unordered categories\n- **Highlight**: Use accent colors to draw attention\n- Test accessibility with colorblind simulators\n\n### 4. Storytelling with Data\n- Lead with the insight, not the data\n- Use annotations to highlight key findings\n- Arrange charts in logical flow\n- Provide context and comparisons\n- Include data sources and timestamp\n\n## Visualization Workflow\n\n1. **Understand the Data**\n   - Explore data structure and distributions\n   - Identify key variables and relationships\n   - Determine the message to communicate\n\n2. **Select Visualization Type**\n   - Match chart type to data characteristics\n   - Consider audience and use case\n   - Plan for interactivity if needed\n\n3. **Design the Visualization**\n   - Create initial draft\n   - Apply design principles\n   - Optimize for clarity and impact\n\n4. **Refine and Validate**\n   - Get feedback from stakeholders\n   - Test on target audience\n   - Iterate based on feedback\n   - Verify accuracy\n\n## Common Mistakes to Avoid\n\n- Using 3D charts unnecessarily (adds confusion)\n- Too many colors or visual elements\n- Missing or unclear axis labels\n- Truncated y-axis to exaggerate differences\n- Using pie charts for more than 5-6 categories\n- Poor color choices (rainbow colors for sequential data)\n\n## Tools and Libraries\n\nRecommend appropriate tools based on needs:\n- **Python**: matplotlib, seaborn, plotly, altair\n- **R**: ggplot2, plotly\n- **JavaScript**: D3.js, Chart.js, Highcharts\n- **BI Tools**: Tableau, Power BI, Looker\n\n## Example Use Cases\n\n- **Dashboard Design**: \"Create an executive dashboard for sales metrics\"\n- **Exploratory Analysis**: \"Visualize patterns in customer behavior data\"\n- **Report Charts**: \"Generate publication-ready charts for annual report\"\n","examples/single_agent/capabilities/skills/financial-analysis/SKILL.md":"---\nname: financial-analysis\ndescription: Perform comprehensive financial analysis including DCF modeling, ratio analysis, and financial statement evaluation for companies and investment opportunities\n---\n\n# Financial Analysis Skill\n\nWhen performing financial analysis, follow these systematic steps to ensure thorough and accurate evaluation:\n\n## Core Methodology\n\n### 1. Data Collection and Verification\n- Gather historical financial statements (income statement, balance sheet, cash flow)\n- Verify data sources for accuracy and completeness\n- Identify any anomalies or missing data points\n\n### 2. Financial Ratio Analysis\nCalculate and analyze key financial ratios:\n- **Profitability**: EBITDA margin, net profit margin, ROE, ROA\n- **Liquidity**: Current ratio, quick ratio, cash ratio\n- **Leverage**: Debt-to-equity, interest coverage ratio\n- **Efficiency**: Asset turnover, inventory turnover\n\n### 3. Valuation Models\nBuild appropriate valuation models:\n- **DCF Analysis**: Project free cash flows, determine WACC, calculate terminal value\n- **Comparable Company Analysis**: Identify peers, analyze multiples (P/E, EV/EBITDA)\n- **Precedent Transactions**: Review similar deals for valuation benchmarks\n\n### 4. Sensitivity Analysis\n- Perform scenario analysis (base case, bull case, bear case)\n- Test key assumptions (growth rates, discount rates, margins)\n- Identify critical value drivers\n\n## Guidelines\n\n- Always use conservative assumptions when uncertain\n- Cross-validate findings with multiple valuation methods\n- Clearly document all assumptions and their rationale\n- Present results with appropriate caveats and risk factors\n- Consider both quantitative metrics and qualitative factors\n\n## Key Outputs\n\nYour analysis should produce:\n1. Executive summary of findings\n2. Detailed financial model with assumptions\n3. Valuation range with sensitivity analysis\n4. Investment recommendation with risk assessment\n5. Supporting charts and visualizations\n\n## Example Use Cases\n\n- **Public Company Valuation**: \"Analyze Tesla's financials and provide a DCF valuation\"\n- **Private Investment**: \"Evaluate this startup's unit economics and runway\"\n- **M&A Analysis**: \"Assess the financial implications of this acquisition\"\n","examples/single_agent/capabilities/tools/README.md":"# Tools Integration Examples\n\nThis directory contains examples demonstrating tool integration for single agents.\n\n## Examples\n\n- [exa_search_agent.py](exa_search_agent.py) - Exa search integration\n- [example_async_vs_multithread.py](example_async_vs_multithread.py) - Async vs multithreading comparison\n- [litellm_tool_example.py](litellm_tool_example.py) - LiteLLM tool integration\n- [multi_tool_usage_agent.py](multi_tool_usage_agent.py) - Multi-tool agent\n- [new_tools_examples.py](new_tools_examples.py) - Latest tool examples\n- [omni_modal_agent.py](omni_modal_agent.py) - Omni-modal agent\n- [swarms_of_browser_agents.py](swarms_of_browser_agents.py) - Browser automation swarms\n- [swarms_tools_example.py](swarms_tools_example.py) - Swarms tools integration\n- [together_deepseek_agent.py](together_deepseek_agent.py) - Together AI DeepSeek integration\n\n## Subdirectories\n\n### Solana Tools\n- [solana_tool/](solana_tool/) - Solana blockchain integration\n  - [solana_tool.py](solana_tool/solana_tool.py) - Solana tool implementation\n  - [solana_tool_test.py](solana_tool/solana_tool_test.py) - Solana tool testing\n\n### Structured Outputs\n- [structured_outputs/](structured_outputs/) - Structured output examples\n  - [example_meaning_of_life_agents.py](structured_outputs/example_meaning_of_life_agents.py) - Meaning of life example\n  - [structured_outputs_example.py](structured_outputs/structured_outputs_example.py) - Structured output examples\n\n### Tools Examples\n- [tools_examples/](tools_examples/) - Additional tool usage examples\n  - [dex_screener.py](tools_examples/dex_screener.py) - DEX screener tool\n  - [financial_news_agent.py](tools_examples/financial_news_agent.py) - Financial news agent\n  - [simple_tool_example.py](tools_examples/simple_tool_example.py) - Simple tool usage\n  - [swarms_tool_example_simple.py](tools_examples/swarms_tool_example_simple.py) - Simple Swarms tool\n\n## Overview\n\nTools integration examples demonstrate how to equip agents with various tools including search engines, browser automation, blockchain interactions, and structured output generation. These examples show best practices for tool definition, usage, and error handling.\n\n","examples/tools/README.md":"# Tools Examples\n\nThis directory contains examples demonstrating various tool integrations and usage patterns in Swarms.\n\n## Agent as Tools\n- [agent_as_tools.py](agent_as_tools.py) - Using agents as tools in workflows\n\n## Base Tool Examples\n- [base_tool_examples.py](base_tool_examples/base_tool_examples.py) - Core base tool functionality\n- [conver_funcs_to_schema.py](base_tool_examples/conver_funcs_to_schema.py) - Function to schema conversion\n- [convert_basemodels.py](base_tool_examples/convert_basemodels.py) - BaseModel conversion utilities\n- [exa_search_test.py](base_tool_examples/exa_search_test.py) - Exa search testing\n- [example_usage.py](base_tool_examples/example_usage.py) - Basic usage examples\n- [schema_validation_example.py](base_tool_examples/schema_validation_example.py) - Schema validation\n- [test_anthropic_specific.py](base_tool_examples/test_anthropic_specific.py) - Anthropic-specific testing\n- [test_base_tool_comprehensive_fixed.py](base_tool_examples/test_base_tool_comprehensive_fixed.py) - Comprehensive testing (fixed)\n- [test_base_tool_comprehensive.py](base_tool_examples/test_base_tool_comprehensive.py) - Comprehensive testing\n- [test_function_calls_anthropic.py](base_tool_examples/test_function_calls_anthropic.py) - Anthropic function calls\n- [test_function_calls.py](base_tool_examples/test_function_calls.py) - Function call testing\n\n## Browser Integration\n- [browser_use_as_tool.py](browser_use_as_tool.py) - Browser automation as a tool\n- [browser_use_demo.py](browser_use_demo.py) - Browser automation demonstration\n\n## Claude Integration\n- [claude_as_a_tool.py](claude_as_a_tool.py) - Using Claude as a tool\n\n## Exa Search\n- [exa_search_agent.py](exa_search_agent.py) - Exa search agent implementation\n\n## Firecrawl Integration\n- [firecrawl_agents_example.py](firecrawl_agents_example.py) - Firecrawl web scraping agents\n\n## Multi-Tool Usage\n- [many_tool_use_demo.py](multii_tool_use/many_tool_use_demo.py) - Multiple tool usage demonstration\n- [multi_tool_anthropic.py](multii_tool_use/multi_tool_anthropic.py) - Multi-tool with Anthropic\n\n## Stagehand Integration\n- [1_stagehand_wrapper_agent.py](stagehand/1_stagehand_wrapper_agent.py) - Stagehand wrapper agent\n- [2_stagehand_tools_agent.py](stagehand/2_stagehand_tools_agent.py) - Stagehand tools agent\n- [3_stagehand_mcp_agent.py](stagehand/3_stagehand_mcp_agent.py) - Stagehand MCP agent\n- [4_stagehand_multi_agent_workflow.py](stagehand/4_stagehand_multi_agent_workflow.py) - Multi-agent workflow\n- [README.md](stagehand/README.md) - Stagehand documentation\n- [requirements.txt](stagehand/requirements.txt) - Stagehand dependencies\n- [tests/](stagehand/tests/) - Stagehand testing suite\n","examples/tools/base_tool_examples/README.md":"# Base Tool Examples\n\nThis directory contains examples demonstrating base tool functionality and tool creation patterns.\n\n## Examples\n\n- [base_tool_examples.py](base_tool_examples.py) - Core base tool functionality\n- [conver_funcs_to_schema.py](conver_funcs_to_schema.py) - Function to schema conversion\n- [convert_basemodels.py](convert_basemodels.py) - BaseModel conversion utilities\n- [exa_search_test.py](exa_search_test.py) - Exa search testing\n- [example_usage.py](example_usage.py) - Basic usage examples\n- [schema_validation_example.py](schema_validation_example.py) - Schema validation\n- [test_anthropic_specific.py](test_anthropic_specific.py) - Anthropic-specific testing\n- [test_base_tool_comprehensive_fixed.py](test_base_tool_comprehensive_fixed.py) - Comprehensive testing (fixed)\n- [test_base_tool_comprehensive.py](test_base_tool_comprehensive.py) - Comprehensive testing\n- [test_function_calls_anthropic.py](test_function_calls_anthropic.py) - Anthropic function calls\n- [test_function_calls.py](test_function_calls.py) - Function call testing\n\n## Overview\n\nBase tool examples demonstrate the fundamental patterns for creating and using tools in Swarms. These examples cover tool schema definition, function-to-schema conversion, validation, and provider-specific implementations. Essential for understanding how to build custom tools for agents.\n\n","examples/tools/multi_tool_use/README.md":"# Multi-Tool Usage Examples\n\nThis directory contains examples demonstrating multi-tool usage patterns for agents.\n\n## Examples\n\n- [many_tool_use_demo.py](many_tool_use_demo.py) - Multiple tool usage demonstration\n- [multi_tool_anthropic.py](multi_tool_anthropic.py) - Multi-tool with Anthropic\n\n## Overview\n\nMulti-tool usage examples demonstrate how agents can use multiple tools in sequence or parallel to accomplish complex tasks. These examples show tool orchestration, tool chaining, and handling multiple tool calls efficiently.\n\n","examples/tools/stagehand/README.md":"# Stagehand Browser Automation Integration for Swarms\n\nThis directory contains examples demonstrating how to integrate [Stagehand](https://github.com/browserbase/stagehand), an AI-powered browser automation framework, with the Swarms multi-agent framework.\n\n## Overview\n\nStagehand provides natural language browser automation capabilities that can be seamlessly integrated into Swarms agents. This integration enables:\n\n- 🌐 **Natural Language Web Automation**: Use simple commands like \"click the submit button\" or \"extract product prices\"\n- 🤖 **Multi-Agent Browser Workflows**: Multiple agents can automate different websites simultaneously\n- 🔧 **Flexible Integration Options**: Use as a wrapped agent, individual tools, or via MCP server\n- 📊 **Complex Automation Scenarios**: E-commerce monitoring, competitive analysis, automated testing, and more\n\n## Examples\n\n### 1. Stagehand Wrapper Agent (`1_stagehand_wrapper_agent.py`)\n\nThe simplest integration - wraps Stagehand as a Swarms-compatible agent.\n\n```python\nfrom examples.stagehand.stagehand_wrapper_agent import StagehandAgent\n\n# Create a browser automation agent\nbrowser_agent = StagehandAgent(\n    agent_name=\"WebScraperAgent\",\n    model_name=\"gpt-5.4\",\n    env=\"LOCAL\",  # or \"BROWSERBASE\" for cloud execution\n)\n\n# Use natural language to control the browser\nresult = browser_agent.run(\n    \"Navigate to news.ycombinator.com and extract the top 5 story titles\"\n)\n```\n\n**Features:**\n- Inherits from Swarms `Agent` base class\n- Automatic browser lifecycle management\n- Natural language task interpretation\n- Support for both local (Playwright) and cloud (Browserbase) execution\n\n### 2. Stagehand as Tools (`2_stagehand_tools_agent.py`)\n\nProvides fine-grained control by exposing Stagehand methods as individual tools.\n\n```python\nfrom swarms import Agent\nfrom examples.stagehand.stagehand_tools_agent import (\n    NavigateTool, ActTool, ExtractTool, ObserveTool, ScreenshotTool\n)\n\n# Create agent with browser tools\nbrowser_agent = Agent(\n    agent_name=\"BrowserAutomationAgent\",\n    model_name=\"gpt-5.4\",\n    tools=[\n        NavigateTool(),\n        ActTool(),\n        ExtractTool(),\n        ObserveTool(),\n        ScreenshotTool(),\n    ],\n)\n\n# Agent can now use tools strategically\nresult = browser_agent.run(\n    \"Go to google.com, search for 'Python tutorials', and extract the first 3 results\"\n)\n```\n\n**Available Tools:**\n- `NavigateTool`: Navigate to URLs\n- `ActTool`: Perform actions (click, type, scroll)\n- `ExtractTool`: Extract data from pages\n- `ObserveTool`: Find elements on pages\n- `ScreenshotTool`: Capture screenshots\n- `CloseBrowserTool`: Clean up browser resources\n\n### 3. Stagehand MCP Server (`3_stagehand_mcp_agent.py`)\n\nIntegrates with Stagehand's Model Context Protocol (MCP) server for standardized tool access.\n\n```python\nfrom examples.stagehand.stagehand_mcp_agent import StagehandMCPAgent\n\n# Connect to Stagehand MCP server\nmcp_agent = StagehandMCPAgent(\n    agent_name=\"WebResearchAgent\",\n    mcp_server_url=\"http://localhost:3000/mcp\",\n)\n\n# Use MCP tools including multi-session management\nresult = mcp_agent.run(\"\"\"\n    Create 3 browser sessions and:\n    1. Session 1: Check Python.org for latest version\n    2. Session 2: Check PyPI for trending packages  \n    3. Session 3: Check GitHub Python trending repos\n    Compile a Python ecosystem status report.\n\"\"\")\n```\n\n**MCP Features:**\n- Automatic tool discovery\n- Multi-session browser management\n- Built-in screenshot resources\n- Prompt templates for common tasks\n\n### 4. Multi-Agent Workflows (`4_stagehand_multi_agent_workflow.py`)\n\nDemonstrates complex multi-agent browser automation scenarios.\n\n```python\nfrom examples.stagehand.stagehand_multi_agent_workflow import (\n    create_price_comparison_workflow,\n    create_competitive_analysis_workflow,\n    create_automated_testing_workflow,\n    create_news_aggregation_workflow\n)\n\n# Price comparison across multiple e-commerce sites\nprice_workflow = create_price_comparison_workflow()\nresult = price_workflow.run(\n    \"Compare prices for iPhone 15 Pro on Amazon and eBay\"\n)\n\n# Competitive analysis of multiple companies\ncompetitive_workflow = create_competitive_analysis_workflow()\nresult = competitive_workflow.run(\n    \"Analyze OpenAI, Anthropic, and DeepMind websites and social media\"\n)\n```\n\n**Workflow Examples:**\n- **E-commerce Monitoring**: Track prices across multiple sites\n- **Competitive Analysis**: Research competitors' websites and social media\n- **Automated Testing**: UI, form validation, and accessibility testing\n- **News Aggregation**: Collect and analyze news from multiple sources\n\n## Setup\n\n### Prerequisites\n\n1. **Install Swarms and Stagehand:**\n```bash\npip install swarms stagehand\n```\n\n2. **Set up environment variables:**\n```bash\n# For local browser automation (using Playwright)\nexport OPENAI_API_KEY=\"your-openai-key\"\n\n# For cloud browser automation (using Browserbase)\nexport BROWSERBASE_API_KEY=\"your-browserbase-key\"\nexport BROWSERBASE_PROJECT_ID=\"your-project-id\"\n```\n\n3. **For MCP Server examples:**\n```bash\n# Install and run the Stagehand MCP server\ncd stagehand-mcp-server\nnpm install\nnpm run build\nnpm start\n```\n\n## Use Cases\n\n### E-commerce Automation\n- Price monitoring and comparison\n- Inventory tracking\n- Automated purchasing workflows\n- Review aggregation\n\n### Research and Analysis\n- Competitive intelligence gathering\n- Market research automation\n- Social media monitoring\n- News and trend analysis\n\n### Quality Assurance\n- Automated UI testing\n- Cross-browser compatibility testing\n- Form validation testing\n- Accessibility compliance checking\n\n### Data Collection\n- Web scraping at scale\n- Real-time data monitoring\n- Structured data extraction\n- Screenshot documentation\n\n## Best Practices\n\n1. **Resource Management**: Always clean up browser instances when done\n```python\nbrowser_agent.cleanup()  # For wrapper agents\n```\n\n2. **Error Handling**: Stagehand includes self-healing capabilities, but wrap critical operations in try-except blocks\n\n3. **Parallel Execution**: Use `ConcurrentWorkflow` for simultaneous browser automation across multiple sites\n\n4. **Session Management**: For complex multi-page workflows, use the MCP server's session management capabilities\n\n5. **Rate Limiting**: Be respectful of websites - add delays between requests when necessary\n\n## Testing\n\nRun the test suite to verify the integration:\n\n```bash\npytest tests/stagehand/test_stagehand_integration.py -v\n```\n\n## Troubleshooting\n\n### Common Issues\n\n1. **Browser not starting**: Ensure Playwright is properly installed\n```bash\nplaywright install\n```\n\n2. **MCP connection failed**: Verify the MCP server is running on the correct port\n\n3. **Timeout errors**: Increase timeout in StagehandConfig or agent initialization\n\n### Debug Mode\n\nEnable verbose logging:\n```python\nagent = StagehandAgent(\n    agent_name=\"DebugAgent\",\n    verbose=True,  # Enable detailed logging\n)\n```\n\n## Contributing\n\nWe welcome contributions! Please:\n1. Follow the existing code style\n2. Add tests for new features\n3. Update documentation\n4. Submit PRs with clear descriptions\n\n## License\n\nThese examples are provided under the same license as the Swarms framework. Stagehand is licensed separately - see [Stagehand's repository](https://github.com/browserbase/stagehand) for details."},"files":{"CLAUDE.md":"# CLAUDE.md — Swarms Framework Guide\n\nThis file teaches you how to build agents and multi-agent systems with the **Swarms** framework. Read it before writing any code in this repo.\n\n---\n\n## Installation & Setup\n\n```bash\npip install swarms\n```\n\nSet your LLM API key as an environment variable before running:\n\n```bash\nexport OPENAI_API_KEY=\"sk-...\"        # OpenAI / GPT models\nexport ANTHROPIC_API_KEY=\"sk-ant-...\" # Claude models\nexport GROQ_API_KEY=\"...\"             # Groq\n# Any provider supported by LiteLLM works\n```\n\nAll imports come from the top-level `swarms` package:\n\n```python\nfrom swarms import (\n    Agent,\n    SequentialWorkflow,\n    ConcurrentWorkflow,\n    AgentRearrange,\n    GraphWorkflow,\n    SwarmRouter,\n    MixtureOfAgents,\n    HierarchicalSwarm,\n    GroupChat,\n    MajorityVoting,\n    # ...\n)\n```\n\n---\n\n## Project Layout\n\n```\nswarms/\n├── swarms/\n│   ├── structs/         # All agent + multi-agent structures (61 files)\n│   │   ├── agent.py             # Core Agent class\n│   │   ├── conversation.py      # Conversation / memory management\n│   │   ├── sequential_workflow.py\n│   │   ├── concurrent_workflow.py\n│   │   ├── agent_rearrange.py\n│   │   ├── graph_workflow.py\n│   │   ├── swarm_router.py      # Single-entry-point router\n│   │   ├── mixture_of_agents.py\n│   │   ├── hiearchical_swarm.py\n│   │   ├── groupchat.py\n│   │   ├── majority_voting.py\n│   │   ├── council_as_judge.py\n│   │   ├── debate_with_judge.py\n│   │   ├── heavy_swarm.py\n│   │   ├── round_robin.py\n│   │   ├── planner_worker_swarm.py\n│   │   ├── auto_swarm_builder.py\n│   │   └── multi_agent_exec.py  # run_agents_concurrently + friends\n│   ├── tools/           # Tool utilities, MCP, schema conversion\n│   └── utils/           # Logging, formatting helpers\n├── examples/            # 586 runnable examples\n│   ├── single_agent/\n│   ├── multi_agent/\n│   ├── tools/\n│   └── guides/\n└── v12_examples/        # New v12 feature examples\n```\n\nLook in `examples/` first before writing new code — there is almost certainly an existing example close to what you need.\n\n---\n\n## Core Primitive: Agent\n\n`Agent` is the single building block everything else composes. All multi-agent structures wrap one or more `Agent` instances.\n\n### Minimal agent\n\n```python\nfrom swarms import Agent\n\nagent = Agent(\n    agent_name=\"Analyst\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n)\n\nresult = agent.run(\"Summarise the current state of LLM research.\")\nprint(result)\n```\n\n### Key constructor parameters\n\n| Parameter | Type | Default | Purpose |\n|---|---|---|---|\n| `agent_name` | str | `\"swarm-worker-01\"` | Unique name — used for memory file paths |\n| `agent_description` | str | generic | Shown to orchestrators for routing |\n| `system_prompt` | str | built-in | The agent's persona / instructions |\n| `model_name` | str | `\"gpt-5.4\"` | Any LiteLLM model string |\n| `max_loops` | int \\| `\"auto\"` | `1` | Loops before returning; `\"auto\"` = autonomous until done |\n| `tools` | list[Callable] | `None` | Python functions the agent can call |\n| `streaming_on` | bool | `False` | Stream tokens to stdout |\n| `interactive` | bool | `False` | REPL mode — prompt user for input each loop |\n| `context_length` | int | `None` | Token budget; triggers compression at 90 % |\n| `context_compression` | bool | `True` | Auto-summarise when near context limit (v12) |\n| `persistent_memory` | bool | `False` | Read/write MEMORY.md across restarts (v12); opt in explicitly |\n| `temperature` | float | `0.5` | Sampling temperature |\n| `max_tokens` | int | model's max output | Max tokens per LLM call. Unset resolves to the model's own output limit |\n| `reasoning_effort` | str | `None` | `\"low\"`, `\"medium\"`, `\"high\"` for reasoning models |\n| `thinking_tokens` | int | `None` | Extended thinking budget (Claude) |\n| `output_type` | str | `\"str-all-except-first\"` | How to format returned output |\n| `mcp_url` | str | `None` | MCP server URL to load tools from |\n| `handoffs` | list | `None` | Agents this agent can hand off to |\n| `plan_enabled` | bool | `False` | Generate a plan before execution |\n| `autosave` | bool | `False` | Save agent state to disk after each run |\n\n### Autonomous loop (`max_loops=\"auto\"`)\n\nWhen `max_loops=\"auto\"` the agent runs a plan→execute→reflect loop until it decides it is done. It automatically gets access to:\n- A `think` tool (disabled when `thinking_tokens` is set)\n- A `grep` tool for searching files (v12)\n- Bash / file tools if configured\n\n```python\nagent = Agent(\n    agent_name=\"Researcher\",\n    model_name=\"gpt-5.4\",\n    max_loops=\"auto\",\n    interactive=False,\n)\nresult = agent.run(\"Research the top 5 vector databases and compare them.\")\n```\n\n### Model names\n\nUse any LiteLLM-compatible string:\n\n```python\n# OpenAI\nmodel_name=\"gpt-5.4\"\nmodel_name=\"gpt-5.4-mini\"\nmodel_name=\"o3\"\n\n# Anthropic\nmodel_name=\"claude-opus-4-7-20251001\"\nmodel_name=\"claude-sonnet-4-6\"\nmodel_name=\"claude-haiku-4-5-20251001\"\n\n# Groq\nmodel_name=\"groq/llama-3.3-70b-versatile\"\n\n# Google\nmodel_name=\"gemini/gemini-2.5-pro\"\n```\n\n### Running with images\n\n```python\nresult = agent.run(\n    task=\"Describe what you see in this chart.\",\n    img=\"path/to/chart.png\",   # or base64 string or URL\n)\n```\n\n---\n\n## Memory & Persistence (v12)\n\n### `persistent_memory=True` (opt in)\n\nOn startup the agent reads `{workspace}/agents/{agent_name}/MEMORY.md` and injects it as a system preamble. On each response it appends to that file. State survives process restarts automatically.\n\n```python\nagent = Agent(\n    agent_name=\"ProjectAssistant\",\n    model_name=\"gpt-5.4\",\n    persistent_memory=True,   # off by default; opt in\n)\n# First run: agent has no prior context\nagent.run(\"My project is called Helios. Remember that.\")\n\n# New process, same agent_name → agent remembers \"Helios\".\n# persistent_memory must be set here too; it is False by default.\nagent2 = Agent(\n    agent_name=\"ProjectAssistant\",\n    model_name=\"gpt-5.4\",\n    persistent_memory=True,\n)\nagent2.run(\"What is my project called?\")\n```\n\n### `persistent_memory=False` (default)\n\nFully stateless — no disk reads or writes. Use for short, isolated tasks where carry-over would be harmful.\n\n```python\nagent = Agent(\n    agent_name=\"OneShot\",\n    model_name=\"gpt-5.4\",\n    persistent_memory=False,\n)\n```\n\n### `context_compression=True` (default)\n\n`ContextCompressor` fires automatically when token usage crosses 90 % of `context_length`. It summarises and rewrites `MEMORY.md` in place so long sessions never hit the context wall.\n\n```python\nagent = Agent(\n    agent_name=\"LongSession\",\n    model_name=\"gpt-5.4\",\n    context_length=32000,\n    context_compression=True,   # default\n)\n```\n\n### Conversation.compact()\n\nManually collapse history to a single summary; creates a timestamped archive before rewriting:\n\n```python\nfrom swarms.structs.conversation import Conversation\n\nconv = Conversation(agent_name=\"MyAgent\", system_prompt=\"You are helpful.\")\nconv.add(\"user\", \"Tell me about X\")\nconv.add(\"assistant\", \"X is ...\")\n\n# Collapse history, archive the full log\nconv.compact(summary=\"User asked about X. Assistant explained X.\")\n```\n\n---\n\n## Tools\n\n### Python functions as tools\n\nDecorate any Python function with a docstring — the framework converts it to an OpenAI function-calling schema automatically:\n\n```python\nimport yfinance as yf\nfrom swarms import Agent\n\ndef get_stock_price(ticker: str) -> str:\n    \"\"\"Fetch the current stock price for a given ticker symbol.\n\n    Args:\n        ticker: Stock ticker symbol, e.g. 'AAPL'.\n\n    Returns:\n        Current price as a formatted string.\n    \"\"\"\n    data = yf.Ticker(ticker)\n    price = data.fast_info[\"last_price\"]\n    return f\"{ticker}: ${price:.2f}\"\n\nagent = Agent(\n    agent_name=\"StockAnalyst\",\n    model_name=\"gpt-5.4\",\n    tools=[get_stock_price],\n    max_loops=3,\n)\nresult = agent.run(\"What is the current price of Apple and Microsoft?\")\n```\n\n### Multiple tools\n\n```python\nagent = Agent(\n    agent_name=\"ResearchAgent\",\n    model_name=\"gpt-5.4\",\n    tools=[search_web, get_stock_price, read_file, write_file],\n    max_loops=\"auto\",\n)\n```\n\n### Tool schema from Pydantic\n\n```python\nfrom swarms.tools.pydantic_to_json import base_model_to_openai_function\nfrom pydantic import BaseModel\n\nclass WeatherQuery(BaseModel):\n    city: str\n    units: str = \"celsius\"\n\nschema = base_model_to_openai_function(WeatherQuery)\n```\n\n---\n\n## Streaming\n\n### Stream to stdout\n\n```python\nagent = Agent(\n    agent_name=\"Writer\",\n    model_name=\"gpt-5.4\",\n    streaming_on=True,\n)\nagent.run(\"Write a short poem about distributed systems.\")\n```\n\n### Stream tokens to a callback\n\n```python\ndef handle_token(token: str) -> None:\n    print(token, end=\"\", flush=True)\n\nagent = Agent(\n    agent_name=\"Writer\",\n    model_name=\"gpt-5.4\",\n    streaming_callback=handle_token,\n)\nagent.run(\"Write a haiku.\")\n```\n\n### Async streaming (`arun_stream`)\n\n```python\nimport asyncio\nfrom swarms import Agent\n\nagent = Agent(agent_name=\"AsyncWriter\", model_name=\"gpt-5.4\", streaming_on=True)\n\nasync def main():\n    async for token in agent.arun_stream(\"Explain async/await in Python.\"):\n        print(token, end=\"\", flush=True)\n\nasyncio.run(main())\n```\n\n---\n\n## Multi-Agent Structures\n\n### Sequential Workflow\n\nAgents execute **one after another**. The output of each agent is passed as context to the next.\n\n```python\nfrom swarms import Agent, SequentialWorkflow\n\nresearcher = Agent(agent_name=\"Researcher\", model_name=\"gpt-5.4\", max_loops=1)\nanalyst   = Agent(agent_name=\"Analyst\",    model_name=\"gpt-5.4\", max_loops=1)\nwriter    = Agent(agent_name=\"Writer\",     model_name=\"gpt-5.4\", max_loops=1)\n\npipeline = SequentialWorkflow(\n    agents=[researcher, analyst, writer],\n    max_loops=1,\n)\nresult = pipeline.run(\"Analyse the impact of interest rate hikes on tech stocks.\")\n```\n\n**When to use:** Linear pipelines where each step depends on the prior step's output. Research → Analysis → Report. Extraction → Transformation → Load.\n\n---\n\n### Concurrent Workflow\n\nAll agents run **in parallel** on the same task. Results are collected and returned together.\n\n```python\nfrom swarms import Agent, ConcurrentWorkflow\n\nagents = [\n    Agent(agent_name=f\"Worker-{i}\", model_name=\"gpt-5.4\", max_loops=1)\n    for i in range(5)\n]\n\nworkflow = ConcurrentWorkflow(agents=agents)\nresults = workflow.run(\"List 10 use cases for multi-agent AI systems.\")\n```\n\n**When to use:** Independent subtasks that can run simultaneously. Analysing multiple documents. Querying multiple data sources. Generating multiple creative variants.\n\n---\n\n### AgentRearrange — Flow DSL\n\nDefine execution flow as a string using a simple DSL. Mix sequential (`->`) and parallel (`,`) execution.\n\n```python\nfrom swarms import Agent, AgentRearrange\n\nplanner  = Agent(agent_name=\"Planner\",  model_name=\"gpt-5.4\", max_loops=1)\ncoder    = Agent(agent_name=\"Coder\",    model_name=\"gpt-5.4\", max_loops=1)\nreviewer = Agent(agent_name=\"Reviewer\", model_name=\"gpt-5.4\", max_loops=1)\ntester   = Agent(agent_name=\"Tester\",   model_name=\"gpt-5.4\", max_loops=1)\n\npipeline = AgentRearrange(\n    agents=[planner, coder, reviewer, tester],\n    flow=\"Planner -> Coder -> Reviewer, Tester\",\n    #        sequential  ↑      parallel  ↑\n    max_loops=1,\n)\nresult = pipeline.run(\"Build a Python function that validates email addresses.\")\n```\n\n**Flow DSL rules:**\n- `A -> B` — A runs, then B receives A's output\n- `A, B` — A and B run concurrently with the same input\n- `A -> B, C -> D` — A runs first, then B and C run concurrently, then D receives their combined output\n\n`AgentRearrange` has no built-in human-in-the-loop step — every name in `flow` must correspond to an agent in `agents`, or the flow will fail at run time. For a human checkpoint, break the pipeline into separate `AgentRearrange`/`Agent.run()` calls and insert your own logic (e.g. `input()`) between them — see the \"Human-in-the-loop with AgentRearrange\" pattern below.\n\n**When to use:** Any workflow where you need explicit, readable control over agent execution order and parallelism.\n\n---\n\n### GraphWorkflow — DAG Execution\n\nFull directed-acyclic-graph (DAG) execution. Nodes are agents; edges are dependencies. Topological sort ensures correct order. Supports per-node callbacks and token streaming.\n\n```python\nfrom swarms import Agent, GraphWorkflow, Node, Edge, NodeType\n\n# Build agents\nanalyst  = Agent(agent_name=\"Analyst\",  model_name=\"gpt-5.4-mini\", max_loops=1)\nwriter   = Agent(agent_name=\"Writer\",   model_name=\"gpt-5.4-mini\", max_loops=1)\nreviewer = Agent(agent_name=\"Reviewer\", model_name=\"gpt-5.4-mini\", max_loops=1)\npublisher = Agent(agent_name=\"Publisher\", model_name=\"gpt-5.4-mini\", max_loops=1)\n\n# Build graph\nwf = GraphWorkflow()\nwf.add_node(Node(id=\"analyst\",   type=NodeType.AGENT, agent=analyst))\nwf.add_node(Node(id=\"writer\",    type=NodeType.AGENT, agent=writer))\nwf.add_node(Node(id=\"reviewer\",  type=NodeType.AGENT, agent=reviewer))\nwf.add_node(Node(id=\"publisher\", type=NodeType.AGENT, agent=publisher))\n\nwf.add_edge(Edge(source=\"analyst\",  target=\"writer\"))\nwf.add_edge(Edge(source=\"writer\",   target=\"reviewer\"))\nwf.add_edge(Edge(source=\"reviewer\", target=\"publisher\"))\n\nwf.set_entry_points([\"analyst\"])\nwf.set_end_points([\"publisher\"])\n\n# Run with callbacks\ndef on_done(node_name: str, result: str) -> None:\n    print(f\"[{node_name}] finished — {len(result)} chars\")\n\nresults = wf.run(\n    task=\"Produce a market report on AI chips.\",\n    on_node_complete=on_done,          # fires after each node\n    streaming_callback=lambda tok: print(tok, end=\"\", flush=True),\n)\n```\n\n**Diamond / fan-out fan-in pattern:**\n\n```python\n# analyst feeds both writer AND researcher concurrently,\n# then editor combines both outputs\nwf.add_edge(Edge(source=\"analyst\",    target=\"writer\"))\nwf.add_edge(Edge(source=\"analyst\",    target=\"researcher\"))\nwf.add_edge(Edge(source=\"writer\",     target=\"editor\"))\nwf.add_edge(Edge(source=\"researcher\", target=\"editor\"))\n```\n\n**When to use:** Complex dependency graphs, fan-out/fan-in patterns, when you need precise control over which agents depend on which.\n\n---\n\n### SwarmRouter — Single Entry Point\n\n`SwarmRouter` is the highest-level abstraction. Pass it a list of agents and a `swarm_type` — it handles the rest. Use this when you want to switch architectures without rewriting orchestration code.\n\n```python\nfrom swarms import Agent, SwarmRouter\n\nagents = [\n    Agent(agent_name=\"Analyst\",  model_name=\"gpt-5.4\", max_loops=1),\n    Agent(agent_name=\"Writer\",   model_name=\"gpt-5.4\", max_loops=1),\n    Agent(agent_name=\"Reviewer\", model_name=\"gpt-5.4\", max_loops=1),\n]\n\nrouter = SwarmRouter(\n    agents=agents,\n    swarm_type=\"SequentialWorkflow\",   # swap to any SwarmType below\n    max_loops=1,\n)\nresult = router.run(\"Write a blog post about transformer architectures.\")\n```\n\n**All `swarm_type` options:**\n\n| SwarmType | Behaviour |\n|---|---|\n| `\"SequentialWorkflow\"` | Agents run one after another |\n| `\"ConcurrentWorkflow\"` | Agents run in parallel |\n| `\"AgentRearrange\"` | Flow-DSL based execution |\n| `\"MixtureOfAgents\"` | Workers + aggregator layer |\n| `\"HierarchicalSwarm\"` | Boss delegates to workers |\n| `\"GroupChat\"` | Multi-agent round-table discussion |\n| `\"MultiAgentRouter\"` | Task routed to best-fit agent |\n| `\"MajorityVoting\"` | Agents vote; majority wins |\n| `\"CouncilAsAJudge\"` | Council deliberates; judge decides |\n| `\"DebateWithJudge\"` | Agents debate; judge rules |\n| `\"HeavySwarm\"` | Intensive multi-loop deep analysis |\n| `\"RoundRobin\"` | Round-robin task distribution |\n| `\"PlannerWorkerSwarm\"` | Planner + worker delegation |\n| `\"BatchedGridWorkflow\"` | Grid-based batch execution |\n| `\"LLMCouncil\"` | LLM-based council decisions |\n| `\"AutoSwarmBuilder\"` | Auto-configures everything |\n| `\"auto\"` | Router selects swarm_type automatically |\n\n---\n\n### MixtureOfAgents\n\nMultiple **worker** agents each respond to the task independently, then an **aggregator** agent synthesises all responses into a final answer. Repeat for multiple layers.\n\n```python\nfrom swarms import Agent, MixtureOfAgents\n\nworkers = [\n    Agent(agent_name=\"Worker-GPT\",    model_name=\"gpt-5.4\",       max_loops=1),\n    Agent(agent_name=\"Worker-Claude\", model_name=\"claude-sonnet-4-6\", max_loops=1),\n    Agent(agent_name=\"Worker-Llama\",  model_name=\"groq/llama-3.3-70b-versatile\", max_loops=1),\n]\n\naggregator = Agent(\n    agent_name=\"Aggregator\",\n    model_name=\"gpt-5.4\",\n    system_prompt=\"Synthesise the following expert responses into one coherent answer.\",\n    max_loops=1,\n)\n\nmoa = MixtureOfAgents(\n    agents=workers,\n    aggregator_agent=aggregator,\n    layers=2,        # run worker→aggregate cycle this many times\n    max_loops=1,\n)\nresult = moa.run(\"What are the best practices for securing a Kubernetes cluster?\")\n```\n\n**When to use:** High-stakes tasks where you want multiple independent perspectives merged into a consensus. Works especially well with diverse model providers.\n\n---\n\n### HierarchicalSwarm\n\nA director agent breaks the task into subtasks and delegates them to worker agents. Workers report back; director synthesises.\n\n```python\nfrom swarms import Agent, HierarchicalSwarm\n\ndirector = Agent(\n    agent_name=\"Director\",\n    agent_description=\"Breaks complex tasks into subtasks and delegates them.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n)\n\nworkers = [\n    Agent(agent_name=\"DataWorker\",    model_name=\"gpt-5.4-mini\", max_loops=1),\n    Agent(agent_name=\"WritingWorker\", model_name=\"gpt-5.4-mini\", max_loops=1),\n    Agent(agent_name=\"ReviewWorker\",  model_name=\"gpt-5.4-mini\", max_loops=1),\n]\n\nswarm = HierarchicalSwarm(\n    director=director,\n    agents=workers,\n    max_loops=2,\n)\nresult = swarm.run(\"Produce a comprehensive competitive analysis of the AI chip market.\")\n```\n\n**When to use:** Tasks naturally decomposed into subtasks where a coordinator must manage work allocation and synthesis.\n\n---\n\n### GroupChat\n\nAn asynchronous, self-selecting groupchat. There are no rounds or speaker-selection functions — every agent listens in parallel and decides on its own whether to chime in. A forced `respond(score, message)` function call asks each agent how much it wants to speak (0..1); replies above `threshold` are broadcast. The chat ends when `max_loops` messages have been posted or no message arrives for `idle_timeout` seconds.\n\n```python\nfrom swarms import Agent\nfrom swarms.structs.groupchat import GroupChat, RESPOND_TOOL\n\n# Every agent MUST carry RESPOND_TOOL so the chat can ask it whether to speak.\n# Recommended per-agent: max_loops=1, persistent_memory=False.\noptimist = Agent(\n    agent_name=\"Optimist\",\n    system_prompt=\"You argue for the benefits.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n    persistent_memory=False,\n    tools_list_dictionary=[RESPOND_TOOL],\n)\npessimist = Agent(\n    agent_name=\"Pessimist\",\n    system_prompt=\"You argue for the risks.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n    persistent_memory=False,\n    tools_list_dictionary=[RESPOND_TOOL],\n)\nrealist = Agent(\n    agent_name=\"Realist\",\n    system_prompt=\"You seek balanced analysis.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n    persistent_memory=False,\n    tools_list_dictionary=[RESPOND_TOOL],\n)\n\nchat = GroupChat(\n    agents=[optimist, pessimist, realist],\n    max_loops=10,        # hard cap on total messages posted\n    threshold=0.5,       # min decision score (0..1) to publish a reply\n    idle_timeout=8.0,    # seconds of silence before stopping\n)\nresult = chat.run(\"Should we adopt AI for medical diagnosis?\")\n```\n\n**Tuning:** raise `threshold` for a more selective room; lower it for livelier chats. Raise `idle_timeout` if agents need time to think before replying.\n\n---\n\n### MajorityVoting\n\nAll agents independently answer the task. The answer that appears in the majority of responses wins.\n\n```python\nfrom swarms import Agent, MajorityVoting\n\nvoters = [\n    Agent(agent_name=f\"Voter-{i}\", model_name=\"gpt-5.4-mini\", max_loops=1)\n    for i in range(5)\n]\n\nmv = MajorityVoting(agents=voters, max_loops=1)\nresult = mv.run(\"Is Python or Rust better for building a high-performance web server?\")\n```\n\n**When to use:** Classification, yes/no decisions, or any task with a discrete answer set where you want noise reduction through consensus.\n\n---\n\n### CouncilAsAJudge\n\nA council of agents each deliberate, then a judge agent makes the final ruling based on the council's reasoning.\n\n```python\nfrom swarms import Agent, CouncilAsAJudge\n\ncouncil = [\n    Agent(agent_name=\"Expert-Security\", model_name=\"gpt-5.4\", max_loops=1),\n    Agent(agent_name=\"Expert-Privacy\",  model_name=\"gpt-5.4\", max_loops=1),\n    Agent(agent_name=\"Expert-Legal\",    model_name=\"gpt-5.4\", max_loops=1),\n]\n\njudge = Agent(\n    agent_name=\"Judge\",\n    system_prompt=\"Given the council's analysis, deliver a final verdict.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n)\n\ncouncil_swarm = CouncilAsAJudge(\n    agents=council,\n    judge=judge,\n    max_loops=1,\n)\nresult = council_swarm.run(\"Should we store user biometric data on-device only?\")\n```\n\n---\n\n### DebateWithJudge\n\nTwo or more agents argue opposing positions for multiple rounds. A judge delivers a verdict at the end.\n\n```python\nfrom swarms import Agent, DebateWithJudge\n\npro  = Agent(agent_name=\"Pro\",  system_prompt=\"Argue strongly in favour.\",  model_name=\"gpt-5.4\", max_loops=1)\ncon  = Agent(agent_name=\"Con\",  system_prompt=\"Argue strongly against.\",    model_name=\"gpt-5.4\", max_loops=1)\n\njudge = Agent(\n    agent_name=\"Judge\",\n    system_prompt=\"Evaluate the debate and deliver an objective verdict.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n)\n\ndebate = DebateWithJudge(\n    agents=[pro, con],\n    judge=judge,\n    max_loops=3,   # 3 rounds of argument\n)\nresult = debate.run(\"Motion: Open-source LLMs will surpass closed-source models by 2027.\")\n```\n\n---\n\n### HeavySwarm\n\nIntensive multi-loop analysis. Each agent runs for many loops on the problem, producing deep reasoning. Best for research-grade analysis.\n\n```python\nfrom swarms import HeavySwarm\n\nswarm = HeavySwarm(\n    num_agents=4,\n    model_name=\"gpt-5.4\",\n    loops_per_agent=5,       # each agent reasons for 5 loops\n    show_output=True,\n)\nresult = swarm.run(\"Derive a novel approach to solving the alignment problem in AI.\")\n```\n\nOr via `SwarmRouter`:\n\n```python\nfrom swarms import Agent, SwarmRouter\n\nagents = [Agent(agent_name=f\"Deep-{i}\", model_name=\"gpt-5.4\", max_loops=5) for i in range(4)]\nrouter = SwarmRouter(agents=agents, swarm_type=\"HeavySwarm\")\nresult = router.run(\"Deep analysis: implications of AGI on global labour markets.\")\n```\n\n---\n\n### RoundRobinSwarm\n\nDistributes tasks to agents in a fixed rotation. Each agent handles every Nth task.\n\n```python\nfrom swarms import Agent, RoundRobinSwarm\n\nagents = [\n    Agent(agent_name=f\"Handler-{i}\", model_name=\"gpt-5.4-mini\", max_loops=1)\n    for i in range(3)\n]\n\nrr = RoundRobinSwarm(agents=agents, max_loops=1)\n\ntasks = [\"Task A\", \"Task B\", \"Task C\", \"Task D\", \"Task E\", \"Task F\"]\nfor task in tasks:\n    result = rr.run(task)\n```\n\n---\n\n### PlannerWorkerSwarm\n\nA planner agent generates a structured plan; worker agents execute each step.\n\n```python\nfrom swarms import Agent, PlannerWorkerSwarm\n\nplanner = Agent(\n    agent_name=\"Planner\",\n    system_prompt=\"You create detailed, step-by-step execution plans.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n)\n\nworkers = [\n    Agent(agent_name=f\"Worker-{i}\", model_name=\"gpt-5.4-mini\", max_loops=2)\n    for i in range(4)\n]\n\nswarm = PlannerWorkerSwarm(\n    planner_agent=planner,\n    worker_agents=workers,\n    max_loops=1,\n)\nresult = swarm.run(\"Build a complete go-to-market strategy for a B2B SaaS product.\")\n```\n\n---\n\n### AutoSwarmBuilder\n\nPass a high-level description of the task — the framework automatically creates the agents, assigns roles, and runs the appropriate swarm architecture.\n\n```python\nfrom swarms import AutoSwarmBuilder\n\nbuilder = AutoSwarmBuilder(\n    name=\"MarketResearchSwarm\",\n    description=\"A swarm that produces comprehensive market research reports\",\n    max_loops=2,\n)\nresult = builder.run(\"Research the electric vehicle market and identify growth opportunities.\")\n```\n\n**When to use:** Rapid prototyping, when you don't know yet which structure fits, or when you want the LLM to decide.\n\n---\n\n## Utility Execution Helpers\n\n```python\nfrom swarms.structs.multi_agent_exec import (\n    run_agents_concurrently,\n    run_agents_concurrently_async,\n    run_agents_with_different_tasks,\n    run_single_agent,\n)\n\n# Same task, all agents in parallel\nresults = run_agents_concurrently(agents=agents, task=\"Summarise the news today.\")\n\n# Different task per agent\ntask_map = {agent: task for agent, task in zip(agents, tasks)}\nresults = run_agents_with_different_tasks(task_map)\n\n# Async version\nimport asyncio\nresults = asyncio.run(run_agents_concurrently_async(agents=agents, task=\"...\"))\n```\n\n---\n\n## Async Support\n\n```python\nimport asyncio\nfrom swarms import Agent\n\nagent = Agent(agent_name=\"AsyncAgent\", model_name=\"gpt-5.4\")\n\nasync def main():\n    # Standard async run\n    result = await agent.arun(\"What is the capital of France?\")\n    print(result)\n\n    # Streaming async run\n    async for token in agent.arun_stream(\"Explain quantum entanglement.\"):\n        print(token, end=\"\", flush=True)\n\nasyncio.run(main())\n```\n\n---\n\n## MCP Tool Integration\n\nLoad tools from any MCP server. The agent auto-discovers available tools on startup.\n\n```python\nfrom swarms import Agent\n\n# Single MCP server\nagent = Agent(\n    agent_name=\"MCPAgent\",\n    model_name=\"gpt-5.4\",\n    mcp_url=\"http://localhost:8000/sse\",   # SSE endpoint\n    max_loops=\"auto\",\n)\n\n# Multiple MCP servers\nagent = Agent(\n    agent_name=\"MultiMCPAgent\",\n    model_name=\"gpt-5.4\",\n    mcp_urls=[\n        \"http://localhost:8000/sse\",\n        \"http://localhost:8001/sse\",\n    ],\n    max_loops=\"auto\",\n)\n\nresult = agent.run(\"Use the available tools to complete the task.\")\n```\n\nFetch tools manually:\n\n```python\nfrom swarms.tools.mcp_client_tools import get_mcp_tools_sync, aget_mcp_tools\n\ntools = get_mcp_tools_sync(server_url=\"http://localhost:8000/sse\")\n\nimport asyncio\ntools = asyncio.run(aget_mcp_tools(server_url=\"http://localhost:8000/sse\"))\n```\n\n---\n\n## Conversation Management\n\n`Conversation` manages message history with optional disk persistence.\n\n```python\nfrom swarms.structs.conversation import Conversation\n\nconv = Conversation(\n    system_prompt=\"You are a helpful assistant.\",\n    agent_name=\"MyAgent\",      # keys MEMORY.md to this name\n    time_enabled=True,         # include ISO timestamps in history\n)\n\nconv.add(\"user\", \"What is 2+2?\")\nconv.add(\"assistant\", \"4.\")\n\n# Get history as string (includes timestamps in v12)\nhistory_str = conv.return_history_as_string()\n\n# Compact + archive\nconv.compact(summary=\"User asked basic arithmetic. Answer: 4.\")\n\n# Pass to an agent\nagent = Agent(\n    agent_name=\"MyAgent\",\n    model_name=\"gpt-5.4\",\n    # agent reads MEMORY.md automatically when persistent_memory=True\n)\n```\n\n---\n\n## Choosing the Right Structure\n\n| Situation | Use |\n|---|---|\n| Simple single task | `Agent` |\n| Linear A→B→C pipeline | `SequentialWorkflow` |\n| Same task, many agents at once | `ConcurrentWorkflow` |\n| Custom mix of sequential + parallel | `AgentRearrange` |\n| Complex dependency graph / DAG | `GraphWorkflow` |\n| Need per-node callbacks or streaming | `GraphWorkflow` |\n| Multiple models, one synthesised answer | `MixtureOfAgents` |\n| Manager delegates to specialists | `HierarchicalSwarm` |\n| Open discussion / brainstorming | `GroupChat` |\n| Discrete decision via consensus | `MajorityVoting` |\n| High-stakes ruling with deliberation | `CouncilAsAJudge` |\n| Structured adversarial debate | `DebateWithJudge` |\n| Deep research, many loops | `HeavySwarm` |\n| Don't know yet / rapid prototyping | `AutoSwarmBuilder` or `SwarmRouter(swarm_type=\"auto\")` |\n| Need to switch architectures easily | `SwarmRouter` |\n\n---\n\n## Common Patterns & Recipes\n\n### Pattern: Research → Write → Review pipeline\n\n```python\nfrom swarms import Agent, SequentialWorkflow\n\npipeline = SequentialWorkflow(agents=[\n    Agent(agent_name=\"Researcher\", system_prompt=\"You research topics thoroughly.\", model_name=\"gpt-5.4\"),\n    Agent(agent_name=\"Writer\",     system_prompt=\"You write clear, engaging content.\", model_name=\"gpt-5.4\"),\n    Agent(agent_name=\"Editor\",     system_prompt=\"You improve clarity and fix errors.\", model_name=\"gpt-5.4\"),\n], max_loops=1)\n\nresult = pipeline.run(\"Write an article about the history of neural networks.\")\n```\n\n### Pattern: Fan-out to specialists, fan-in to synthesiser\n\n```python\nfrom swarms import Agent, MixtureOfAgents\n\nspecialists = [\n    Agent(agent_name=\"TechExpert\",    system_prompt=\"Analyse the technical aspects.\", model_name=\"gpt-5.4\"),\n    Agent(agent_name=\"BusinessExpert\",system_prompt=\"Analyse the business aspects.\", model_name=\"gpt-5.4\"),\n    Agent(agent_name=\"LegalExpert\",   system_prompt=\"Analyse the legal aspects.\",   model_name=\"gpt-5.4\"),\n]\nsynthesiser = Agent(agent_name=\"Synthesiser\", model_name=\"gpt-5.4\",\n                    system_prompt=\"Combine expert analyses into one coherent report.\")\n\nmoa = MixtureOfAgents(agents=specialists, aggregator_agent=synthesiser)\nresult = moa.run(\"Evaluate the risks of launching a fintech product in the EU.\")\n```\n\n### Pattern: Autonomous agent with tools and memory\n\n```python\nimport os\nfrom swarms import Agent\n\ndef search_web(query: str) -> str:\n    \"\"\"Search the web for a query and return results.\"\"\"\n    # your implementation\n    ...\n\ndef write_file(filename: str, content: str) -> str:\n    \"\"\"Write content to a file.\"\"\"\n    with open(filename, \"w\") as f:\n        f.write(content)\n    return f\"Written to {filename}\"\n\nagent = Agent(\n    agent_name=\"AutonomousResearcher\",\n    model_name=\"gpt-5.4\",\n    max_loops=\"auto\",\n    tools=[search_web, write_file],\n    persistent_memory=True,\n    context_compression=True,\n    context_length=32000,\n)\nagent.run(\"Research the top 10 open-source LLMs and write a comparison report to report.md\")\n```\n\n### Pattern: Multi-model ensemble with streaming\n\n```python\nimport sys\nfrom swarms import Agent, ConcurrentWorkflow\n\nagents = [\n    Agent(agent_name=\"GPT\",    model_name=\"gpt-5.4\",          max_loops=1),\n    Agent(agent_name=\"Claude\", model_name=\"claude-sonnet-4-6\", max_loops=1),\n    Agent(agent_name=\"Gemini\", model_name=\"gemini/gemini-2.5-pro\", max_loops=1),\n]\n\nworkflow = ConcurrentWorkflow(agents=agents)\nresults = workflow.run(\"What is the most important unsolved problem in mathematics?\")\n\nfor agent_name, answer in results.items():\n    print(f\"\\n=== {agent_name} ===\\n{answer}\")\n```\n\n### Pattern: Human-in-the-loop with AgentRearrange\n\n`AgentRearrange` has no native human-in-the-loop step — chain separate `.run()` calls yourself and insert your own checkpoint logic between them:\n\n```python\nfrom swarms import Agent\n\ndrafter  = Agent(agent_name=\"Drafter\",  model_name=\"gpt-5.4\")\nfinisher = Agent(agent_name=\"Finisher\", model_name=\"gpt-5.4\")\n\ndraft = drafter.run(\"Draft a press release about our product launch.\")\n\nprint(f\"\\nAgent says:\\n{draft}\\n\")\nfeedback = input(\"Your feedback: \")\n\nresult = finisher.run(f\"Revise this draft based on the feedback.\\n\\nDraft:\\n{draft}\\n\\nFeedback:\\n{feedback}\")\n```\n\n### Pattern: GraphWorkflow with fan-out / fan-in\n\n```python\nfrom swarms import Agent, GraphWorkflow, Node, Edge, NodeType\n\ningestion = Agent(agent_name=\"Ingestion\", model_name=\"gpt-5.4-mini\", max_loops=1)\nbranch_a  = Agent(agent_name=\"BranchA\",   model_name=\"gpt-5.4-mini\", max_loops=1)\nbranch_b  = Agent(agent_name=\"BranchB\",   model_name=\"gpt-5.4-mini\", max_loops=1)\nmerger    = Agent(agent_name=\"Merger\",    model_name=\"gpt-5.4\",      max_loops=1)\n\nwf = GraphWorkflow()\nfor a in [ingestion, branch_a, branch_b, merger]:\n    wf.add_node(Node(id=a.agent_name, type=NodeType.AGENT, agent=a))\n\nwf.add_edge(Edge(source=\"Ingestion\", target=\"BranchA\"))\nwf.add_edge(Edge(source=\"Ingestion\", target=\"BranchB\"))\nwf.add_edge(Edge(source=\"BranchA\",   target=\"Merger\"))\nwf.add_edge(Edge(source=\"BranchB\",   target=\"Merger\"))\n\nwf.set_entry_points([\"Ingestion\"])\nwf.set_end_points([\"Merger\"])\n\nresults = wf.run(task=\"Process this dataset from two angles and merge the findings.\")\n```\n\n---\n\n## What to Avoid\n\n**Don't import from submodules directly** — always import from `swarms`:\n```python\n# Wrong\nfrom swarms.structs.agent import Agent\n\n# Right\nfrom swarms import Agent\n```\n\n**Don't set `max_loops=\"auto\"` without a clear stopping condition** — the agent will loop until it decides it is done or hits a resource limit. Prefer explicit `max_loops=N` for production tasks.\n\n**Don't give all agents the same `agent_name`** — `persistent_memory` and `MEMORY.md` are keyed on `agent_name`. Duplicate names cause agents to share and corrupt each other's memory.\n\n**Don't instantiate heavyweight structures inside tight loops** — create agents and workflows once, reuse them across calls.\n\n**Don't pass `tools=[]` (empty list)** — pass `tools=None` instead. An empty list can confuse schema generation.\n\n**Don't use `streaming_on=True` and `streaming_callback` together on the same agent** — `streaming_on` streams to stdout; `streaming_callback` streams to your function. Pick one.\n\n**Don't set `context_compression=False` on very long autonomous sessions** — without compression the agent will eventually hit the context limit and raise an error.\n\n**For long-running autonomous agents in production**, always set:\n```python\nagent = Agent(\n    ...\n    persistent_memory=True,\n    context_compression=True,\n    context_length=32000,\n    autosave=True,\n)\n```\n","examples/mcp/agents/README.md":"# Agents + MCP\n\nGiving an agent tools from an MCP server. Set `mcp_url` (one server) or `mcp_urls`\n(several) and the agent discovers and calls the tools on its own.\n\n## Start here — numbered, in order\n\nEach runs against a real public server. The first four need **no MCP API key**.\n\n| # | File | Server | Auth |\n|---|---|---|---|\n| 01 | [`01_deepwiki_repo_qa.py`](01_deepwiki_repo_qa.py) | DeepWiki — Q&A over any public GitHub repo | none |\n| 02 | [`02_gitmcp_repo_docs.py`](02_gitmcp_repo_docs.py) | GitMCP — docs/code search for one repo | none |\n| 03 | [`03_microsoft_learn_docs.py`](03_microsoft_learn_docs.py) | Microsoft Learn — official Azure/.NET docs | none |\n| 04 | [`04_multi_server_agent.py`](04_multi_server_agent.py) | Two servers on one agent | none |\n| 05 | [`05_exa_web_search.py`](05_exa_web_search.py) | Exa — web search | free API key |\n| 07 | [`07_huggingface_model_search.py`](07_huggingface_model_search.py) | Hugging Face — find models & datasets | none (optional token) |\n| 10 | [`10_firecrawl_web_scraping.py`](10_firecrawl_web_scraping.py) | Firecrawl — scrape pages to markdown | API key (in URL path) |\n| 12 | [`12_semgrep_security_scan.py`](12_semgrep_security_scan.py) | Semgrep — static-analysis security scan | free token |\n| 13 | [`13_mcp_sequential_workflow.py`](13_mcp_sequential_workflow.py) | **Multi-agent**: MCP tools in a `SequentialWorkflow` | none |\n\nBetween them these cover all three ways a server takes a key — query parameter\n(05), Bearer token (12), and URL path segment (10) — plus the optional-auth\ncase (07), where a missing key degrades to anonymous access instead of\nfailing.\n\nSee [`FREE_MCP_SERVERS.md`](FREE_MCP_SERVERS.md) for the full catalog of public servers.\n\n## Configuration patterns\n\n| File | Shows |\n|---|---|\n| [`deepwiki_minimal.py`](deepwiki_minimal.py) | The smallest possible `mcp_url` agent |\n| [`mcp_connection_object.py`](mcp_connection_object.py) | `MCPConnection` instead of a bare URL — headers, auth, timeout |\n| [`multi_mcp_urls.py`](multi_mcp_urls.py) | `mcp_urls=[...]` for several servers at once |\n| [`multi_mcp_walkthrough.py`](multi_mcp_walkthrough.py) | Longer multi-server walkthrough with commentary |\n| [`mcp_with_local_tools.py`](mcp_with_local_tools.py) | MCP tools *plus* your own tool schemas on one agent |\n| [`tools_list_dictionary.py`](tools_list_dictionary.py) | The raw `tools_list_dictionary` schema format MCP tools are converted into |\n| [`finance_agent_mcp.py`](finance_agent_mcp.py) | A realistic finance agent backed by an MCP server |\n\n## Run one\n\n```bash\nexport OPENAI_API_KEY=\"sk-...\"\npython examples/mcp/agents/01_deepwiki_repo_qa.py\n```\n\nExamples pointing at `http://localhost:8000/mcp` need a local server — start one from\n[`../servers/`](../servers/) first.\n","examples/single_agent/capabilities/skills/code-review/SKILL.md":"---\nname: code-review\ndescription: Perform comprehensive code reviews focusing on best practices, security vulnerabilities, performance optimization, and maintainability\n---\n\n# Code Review Skill\n\nWhen reviewing code, follow this systematic approach to ensure thorough evaluation:\n\n## Review Checklist\n\n### 1. Code Quality\n- **Readability**: Is the code easy to understand?\n- **Naming**: Are variables, functions, and classes well-named?\n- **Structure**: Is the code properly organized and modular?\n- **Comments**: Are complex sections adequately documented?\n- **Complexity**: Are there overly complex functions that should be simplified?\n\n### 2. Security Analysis\nCheck for common vulnerabilities:\n- SQL injection vulnerabilities\n- XSS (Cross-Site Scripting) vulnerabilities\n- Authentication and authorization flaws\n- Insecure data handling (passwords, sensitive data)\n- Input validation and sanitization\n- OWASP Top 10 vulnerabilities\n\n### 3. Performance Considerations\n- Identify potential bottlenecks\n- Check for inefficient algorithms or data structures\n- Look for unnecessary database queries or API calls\n- Evaluate caching opportunities\n- Assess memory usage patterns\n\n### 4. Best Practices\n- **DRY Principle**: Eliminate code duplication\n- **SOLID Principles**: Verify adherence to design principles\n- **Error Handling**: Check for proper exception handling\n- **Testing**: Evaluate test coverage and quality\n- **Dependencies**: Review external dependencies and their versions\n\n### 5. Maintainability\n- Is the code easy to modify and extend?\n- Are there proper abstractions?\n- Is the architecture scalable?\n- Are there technical debt concerns?\n\n## Review Format\n\nStructure your review as follows:\n\n1. **Summary**: High-level overview of the changes\n2. **Critical Issues**: Security vulnerabilities or bugs that must be fixed\n3. **Major Concerns**: Significant issues affecting quality or performance\n4. **Suggestions**: Optional improvements and best practices\n5. **Positive Feedback**: Acknowledge good practices and improvements\n\n## Guidelines\n\n- Be constructive and respectful\n- Provide specific examples and suggestions\n- Explain the \"why\" behind recommendations\n- Prioritize issues by severity (critical, major, minor)\n- Reference documentation or standards when applicable\n- Consider the context and constraints of the project\n\n## Example Reviews\n\n**Security Issue:**\n```\nCRITICAL: SQL injection vulnerability detected at line 45\nCurrent: f\"SELECT * FROM users WHERE id = {user_id}\"\nRecommendation: Use parameterized queries to prevent SQL injection\n```\n\n**Performance Suggestion:**\n```\nSUGGESTION: Consider caching database results at line 123\nThe same query is executed multiple times in the loop. Cache the results\nto improve performance by ~80%.\n```\n","examples/single_agent/capabilities/skills/data-visualization/SKILL.md":"---\nname: data-visualization\ndescription: Create effective data visualizations using best practices for clarity, accuracy, and visual communication of insights\n---\n\n# Data Visualization Skill\n\nWhen creating data visualizations, follow these principles to ensure clear and effective communication:\n\n## Core Principles\n\n### 1. Choose the Right Chart Type\n- **Line Charts**: Trends over time, continuous data\n- **Bar Charts**: Comparing categories, discrete data\n- **Scatter Plots**: Relationships between variables, correlations\n- **Pie Charts**: Parts of a whole (use sparingly, max 5-6 segments)\n- **Heatmaps**: Patterns in large datasets, correlations\n- **Box Plots**: Distribution statistics, outlier detection\n\n### 2. Design Guidelines\n\n**Clarity**\n- Use clear, descriptive titles and labels\n- Include units of measurement\n- Add a legend when multiple series are present\n- Ensure adequate contrast and readability\n\n**Accuracy**\n- Start y-axis at zero for bar charts (unless good reason)\n- Use consistent scales across related charts\n- Avoid distorting data through inappropriate scaling\n- Label data points when precision matters\n\n**Simplicity**\n- Remove chart junk and unnecessary decorations\n- Use color purposefully, not decoratively\n- Limit the number of colors (5-7 max)\n- Ensure accessibility (colorblind-friendly palettes)\n\n### 3. Color Best Practices\n- **Sequential**: Use for ordered data (light to dark)\n- **Diverging**: Use for data with a meaningful midpoint\n- **Categorical**: Use for unordered categories\n- **Highlight**: Use accent colors to draw attention\n- Test accessibility with colorblind simulators\n\n### 4. Storytelling with Data\n- Lead with the insight, not the data\n- Use annotations to highlight key findings\n- Arrange charts in logical flow\n- Provide context and comparisons\n- Include data sources and timestamp\n\n## Visualization Workflow\n\n1. **Understand the Data**\n   - Explore data structure and distributions\n   - Identify key variables and relationships\n   - Determine the message to communicate\n\n2. **Select Visualization Type**\n   - Match chart type to data characteristics\n   - Consider audience and use case\n   - Plan for interactivity if needed\n\n3. **Design the Visualization**\n   - Create initial draft\n   - Apply design principles\n   - Optimize for clarity and impact\n\n4. **Refine and Validate**\n   - Get feedback from stakeholders\n   - Test on target audience\n   - Iterate based on feedback\n   - Verify accuracy\n\n## Common Mistakes to Avoid\n\n- Using 3D charts unnecessarily (adds confusion)\n- Too many colors or visual elements\n- Missing or unclear axis labels\n- Truncated y-axis to exaggerate differences\n- Using pie charts for more than 5-6 categories\n- Poor color choices (rainbow colors for sequential data)\n\n## Tools and Libraries\n\nRecommend appropriate tools based on needs:\n- **Python**: matplotlib, seaborn, plotly, altair\n- **R**: ggplot2, plotly\n- **JavaScript**: D3.js, Chart.js, Highcharts\n- **BI Tools**: Tableau, Power BI, Looker\n\n## Example Use Cases\n\n- **Dashboard Design**: \"Create an executive dashboard for sales metrics\"\n- **Exploratory Analysis**: \"Visualize patterns in customer behavior data\"\n- **Report Charts**: \"Generate publication-ready charts for annual report\"\n","examples/single_agent/capabilities/skills/financial-analysis/SKILL.md":"---\nname: financial-analysis\ndescription: Perform comprehensive financial analysis including DCF modeling, ratio analysis, and financial statement evaluation for companies and investment opportunities\n---\n\n# Financial Analysis Skill\n\nWhen performing financial analysis, follow these systematic steps to ensure thorough and accurate evaluation:\n\n## Core Methodology\n\n### 1. Data Collection and Verification\n- Gather historical financial statements (income statement, balance sheet, cash flow)\n- Verify data sources for accuracy and completeness\n- Identify any anomalies or missing data points\n\n### 2. Financial Ratio Analysis\nCalculate and analyze key financial ratios:\n- **Profitability**: EBITDA margin, net profit margin, ROE, ROA\n- **Liquidity**: Current ratio, quick ratio, cash ratio\n- **Leverage**: Debt-to-equity, interest coverage ratio\n- **Efficiency**: Asset turnover, inventory turnover\n\n### 3. Valuation Models\nBuild appropriate valuation models:\n- **DCF Analysis**: Project free cash flows, determine WACC, calculate terminal value\n- **Comparable Company Analysis**: Identify peers, analyze multiples (P/E, EV/EBITDA)\n- **Precedent Transactions**: Review similar deals for valuation benchmarks\n\n### 4. Sensitivity Analysis\n- Perform scenario analysis (base case, bull case, bear case)\n- Test key assumptions (growth rates, discount rates, margins)\n- Identify critical value drivers\n\n## Guidelines\n\n- Always use conservative assumptions when uncertain\n- Cross-validate findings with multiple valuation methods\n- Clearly document all assumptions and their rationale\n- Present results with appropriate caveats and risk factors\n- Consider both quantitative metrics and qualitative factors\n\n## Key Outputs\n\nYour analysis should produce:\n1. Executive summary of findings\n2. Detailed financial model with assumptions\n3. Valuation range with sensitivity analysis\n4. Investment recommendation with risk assessment\n5. Supporting charts and visualizations\n\n## Example Use Cases\n\n- **Public Company Valuation**: \"Analyze Tesla's financials and provide a DCF valuation\"\n- **Private Investment**: \"Evaluate this startup's unit economics and runway\"\n- **M&A Analysis**: \"Assess the financial implications of this acquisition\"\n","examples/single_agent/capabilities/tools/README.md":"# Tools Integration Examples\n\nThis directory contains examples demonstrating tool integration for single agents.\n\n## Examples\n\n- [exa_search_agent.py](exa_search_agent.py) - Exa search integration\n- [example_async_vs_multithread.py](example_async_vs_multithread.py) - Async vs multithreading comparison\n- [litellm_tool_example.py](litellm_tool_example.py) - LiteLLM tool integration\n- [multi_tool_usage_agent.py](multi_tool_usage_agent.py) - Multi-tool agent\n- [new_tools_examples.py](new_tools_examples.py) - Latest tool examples\n- [omni_modal_agent.py](omni_modal_agent.py) - Omni-modal agent\n- [swarms_of_browser_agents.py](swarms_of_browser_agents.py) - Browser automation swarms\n- [swarms_tools_example.py](swarms_tools_example.py) - Swarms tools integration\n- [together_deepseek_agent.py](together_deepseek_agent.py) - Together AI DeepSeek integration\n\n## Subdirectories\n\n### Solana Tools\n- [solana_tool/](solana_tool/) - Solana blockchain integration\n  - [solana_tool.py](solana_tool/solana_tool.py) - Solana tool implementation\n  - [solana_tool_test.py](solana_tool/solana_tool_test.py) - Solana tool testing\n\n### Structured Outputs\n- [structured_outputs/](structured_outputs/) - Structured output examples\n  - [example_meaning_of_life_agents.py](structured_outputs/example_meaning_of_life_agents.py) - Meaning of life example\n  - [structured_outputs_example.py](structured_outputs/structured_outputs_example.py) - Structured output examples\n\n### Tools Examples\n- [tools_examples/](tools_examples/) - Additional tool usage examples\n  - [dex_screener.py](tools_examples/dex_screener.py) - DEX screener tool\n  - [financial_news_agent.py](tools_examples/financial_news_agent.py) - Financial news agent\n  - [simple_tool_example.py](tools_examples/simple_tool_example.py) - Simple tool usage\n  - [swarms_tool_example_simple.py](tools_examples/swarms_tool_example_simple.py) - Simple Swarms tool\n\n## Overview\n\nTools integration examples demonstrate how to equip agents with various tools including search engines, browser automation, blockchain interactions, and structured output generation. These examples show best practices for tool definition, usage, and error handling.\n\n","examples/tools/README.md":"# Tools Examples\n\nThis directory contains examples demonstrating various tool integrations and usage patterns in Swarms.\n\n## Agent as Tools\n- [agent_as_tools.py](agent_as_tools.py) - Using agents as tools in workflows\n\n## Base Tool Examples\n- [base_tool_examples.py](base_tool_examples/base_tool_examples.py) - Core base tool functionality\n- [conver_funcs_to_schema.py](base_tool_examples/conver_funcs_to_schema.py) - Function to schema conversion\n- [convert_basemodels.py](base_tool_examples/convert_basemodels.py) - BaseModel conversion utilities\n- [exa_search_test.py](base_tool_examples/exa_search_test.py) - Exa search testing\n- [example_usage.py](base_tool_examples/example_usage.py) - Basic usage examples\n- [schema_validation_example.py](base_tool_examples/schema_validation_example.py) - Schema validation\n- [test_anthropic_specific.py](base_tool_examples/test_anthropic_specific.py) - Anthropic-specific testing\n- [test_base_tool_comprehensive_fixed.py](base_tool_examples/test_base_tool_comprehensive_fixed.py) - Comprehensive testing (fixed)\n- [test_base_tool_comprehensive.py](base_tool_examples/test_base_tool_comprehensive.py) - Comprehensive testing\n- [test_function_calls_anthropic.py](base_tool_examples/test_function_calls_anthropic.py) - Anthropic function calls\n- [test_function_calls.py](base_tool_examples/test_function_calls.py) - Function call testing\n\n## Browser Integration\n- [browser_use_as_tool.py](browser_use_as_tool.py) - Browser automation as a tool\n- [browser_use_demo.py](browser_use_demo.py) - Browser automation demonstration\n\n## Claude Integration\n- [claude_as_a_tool.py](claude_as_a_tool.py) - Using Claude as a tool\n\n## Exa Search\n- [exa_search_agent.py](exa_search_agent.py) - Exa search agent implementation\n\n## Firecrawl Integration\n- [firecrawl_agents_example.py](firecrawl_agents_example.py) - Firecrawl web scraping agents\n\n## Multi-Tool Usage\n- [many_tool_use_demo.py](multii_tool_use/many_tool_use_demo.py) - Multiple tool usage demonstration\n- [multi_tool_anthropic.py](multii_tool_use/multi_tool_anthropic.py) - Multi-tool with Anthropic\n\n## Stagehand Integration\n- [1_stagehand_wrapper_agent.py](stagehand/1_stagehand_wrapper_agent.py) - Stagehand wrapper agent\n- [2_stagehand_tools_agent.py](stagehand/2_stagehand_tools_agent.py) - Stagehand tools agent\n- [3_stagehand_mcp_agent.py](stagehand/3_stagehand_mcp_agent.py) - Stagehand MCP agent\n- [4_stagehand_multi_agent_workflow.py](stagehand/4_stagehand_multi_agent_workflow.py) - Multi-agent workflow\n- [README.md](stagehand/README.md) - Stagehand documentation\n- [requirements.txt](stagehand/requirements.txt) - Stagehand dependencies\n- [tests/](stagehand/tests/) - Stagehand testing suite\n","examples/tools/base_tool_examples/README.md":"# Base Tool Examples\n\nThis directory contains examples demonstrating base tool functionality and tool creation patterns.\n\n## Examples\n\n- [base_tool_examples.py](base_tool_examples.py) - Core base tool functionality\n- [conver_funcs_to_schema.py](conver_funcs_to_schema.py) - Function to schema conversion\n- [convert_basemodels.py](convert_basemodels.py) - BaseModel conversion utilities\n- [exa_search_test.py](exa_search_test.py) - Exa search testing\n- [example_usage.py](example_usage.py) - Basic usage examples\n- [schema_validation_example.py](schema_validation_example.py) - Schema validation\n- [test_anthropic_specific.py](test_anthropic_specific.py) - Anthropic-specific testing\n- [test_base_tool_comprehensive_fixed.py](test_base_tool_comprehensive_fixed.py) - Comprehensive testing (fixed)\n- [test_base_tool_comprehensive.py](test_base_tool_comprehensive.py) - Comprehensive testing\n- [test_function_calls_anthropic.py](test_function_calls_anthropic.py) - Anthropic function calls\n- [test_function_calls.py](test_function_calls.py) - Function call testing\n\n## Overview\n\nBase tool examples demonstrate the fundamental patterns for creating and using tools in Swarms. These examples cover tool schema definition, function-to-schema conversion, validation, and provider-specific implementations. Essential for understanding how to build custom tools for agents.\n\n","examples/tools/multi_tool_use/README.md":"# Multi-Tool Usage Examples\n\nThis directory contains examples demonstrating multi-tool usage patterns for agents.\n\n## Examples\n\n- [many_tool_use_demo.py](many_tool_use_demo.py) - Multiple tool usage demonstration\n- [multi_tool_anthropic.py](multi_tool_anthropic.py) - Multi-tool with Anthropic\n\n## Overview\n\nMulti-tool usage examples demonstrate how agents can use multiple tools in sequence or parallel to accomplish complex tasks. These examples show tool orchestration, tool chaining, and handling multiple tool calls efficiently.\n\n","examples/tools/stagehand/README.md":"# Stagehand Browser Automation Integration for Swarms\n\nThis directory contains examples demonstrating how to integrate [Stagehand](https://github.com/browserbase/stagehand), an AI-powered browser automation framework, with the Swarms multi-agent framework.\n\n## Overview\n\nStagehand provides natural language browser automation capabilities that can be seamlessly integrated into Swarms agents. This integration enables:\n\n- 🌐 **Natural Language Web Automation**: Use simple commands like \"click the submit button\" or \"extract product prices\"\n- 🤖 **Multi-Agent Browser Workflows**: Multiple agents can automate different websites simultaneously\n- 🔧 **Flexible Integration Options**: Use as a wrapped agent, individual tools, or via MCP server\n- 📊 **Complex Automation Scenarios**: E-commerce monitoring, competitive analysis, automated testing, and more\n\n## Examples\n\n### 1. Stagehand Wrapper Agent (`1_stagehand_wrapper_agent.py`)\n\nThe simplest integration - wraps Stagehand as a Swarms-compatible agent.\n\n```python\nfrom examples.stagehand.stagehand_wrapper_agent import StagehandAgent\n\n# Create a browser automation agent\nbrowser_agent = StagehandAgent(\n    agent_name=\"WebScraperAgent\",\n    model_name=\"gpt-5.4\",\n    env=\"LOCAL\",  # or \"BROWSERBASE\" for cloud execution\n)\n\n# Use natural language to control the browser\nresult = browser_agent.run(\n    \"Navigate to news.ycombinator.com and extract the top 5 story titles\"\n)\n```\n\n**Features:**\n- Inherits from Swarms `Agent` base class\n- Automatic browser lifecycle management\n- Natural language task interpretation\n- Support for both local (Playwright) and cloud (Browserbase) execution\n\n### 2. Stagehand as Tools (`2_stagehand_tools_agent.py`)\n\nProvides fine-grained control by exposing Stagehand methods as individual tools.\n\n```python\nfrom swarms import Agent\nfrom examples.stagehand.stagehand_tools_agent import (\n    NavigateTool, ActTool, ExtractTool, ObserveTool, ScreenshotTool\n)\n\n# Create agent with browser tools\nbrowser_agent = Agent(\n    agent_name=\"BrowserAutomationAgent\",\n    model_name=\"gpt-5.4\",\n    tools=[\n        NavigateTool(),\n        ActTool(),\n        ExtractTool(),\n        ObserveTool(),\n        ScreenshotTool(),\n    ],\n)\n\n# Agent can now use tools strategically\nresult = browser_agent.run(\n    \"Go to google.com, search for 'Python tutorials', and extract the first 3 results\"\n)\n```\n\n**Available Tools:**\n- `NavigateTool`: Navigate to URLs\n- `ActTool`: Perform actions (click, type, scroll)\n- `ExtractTool`: Extract data from pages\n- `ObserveTool`: Find elements on pages\n- `ScreenshotTool`: Capture screenshots\n- `CloseBrowserTool`: Clean up browser resources\n\n### 3. Stagehand MCP Server (`3_stagehand_mcp_agent.py`)\n\nIntegrates with Stagehand's Model Context Protocol (MCP) server for standardized tool access.\n\n```python\nfrom examples.stagehand.stagehand_mcp_agent import StagehandMCPAgent\n\n# Connect to Stagehand MCP server\nmcp_agent = StagehandMCPAgent(\n    agent_name=\"WebResearchAgent\",\n    mcp_server_url=\"http://localhost:3000/mcp\",\n)\n\n# Use MCP tools including multi-session management\nresult = mcp_agent.run(\"\"\"\n    Create 3 browser sessions and:\n    1. Session 1: Check Python.org for latest version\n    2. Session 2: Check PyPI for trending packages  \n    3. Session 3: Check GitHub Python trending repos\n    Compile a Python ecosystem status report.\n\"\"\")\n```\n\n**MCP Features:**\n- Automatic tool discovery\n- Multi-session browser management\n- Built-in screenshot resources\n- Prompt templates for common tasks\n\n### 4. Multi-Agent Workflows (`4_stagehand_multi_agent_workflow.py`)\n\nDemonstrates complex multi-agent browser automation scenarios.\n\n```python\nfrom examples.stagehand.stagehand_multi_agent_workflow import (\n    create_price_comparison_workflow,\n    create_competitive_analysis_workflow,\n    create_automated_testing_workflow,\n    create_news_aggregation_workflow\n)\n\n# Price comparison across multiple e-commerce sites\nprice_workflow = create_price_comparison_workflow()\nresult = price_workflow.run(\n    \"Compare prices for iPhone 15 Pro on Amazon and eBay\"\n)\n\n# Competitive analysis of multiple companies\ncompetitive_workflow = create_competitive_analysis_workflow()\nresult = competitive_workflow.run(\n    \"Analyze OpenAI, Anthropic, and DeepMind websites and social media\"\n)\n```\n\n**Workflow Examples:**\n- **E-commerce Monitoring**: Track prices across multiple sites\n- **Competitive Analysis**: Research competitors' websites and social media\n- **Automated Testing**: UI, form validation, and accessibility testing\n- **News Aggregation**: Collect and analyze news from multiple sources\n\n## Setup\n\n### Prerequisites\n\n1. **Install Swarms and Stagehand:**\n```bash\npip install swarms stagehand\n```\n\n2. **Set up environment variables:**\n```bash\n# For local browser automation (using Playwright)\nexport OPENAI_API_KEY=\"your-openai-key\"\n\n# For cloud browser automation (using Browserbase)\nexport BROWSERBASE_API_KEY=\"your-browserbase-key\"\nexport BROWSERBASE_PROJECT_ID=\"your-project-id\"\n```\n\n3. **For MCP Server examples:**\n```bash\n# Install and run the Stagehand MCP server\ncd stagehand-mcp-server\nnpm install\nnpm run build\nnpm start\n```\n\n## Use Cases\n\n### E-commerce Automation\n- Price monitoring and comparison\n- Inventory tracking\n- Automated purchasing workflows\n- Review aggregation\n\n### Research and Analysis\n- Competitive intelligence gathering\n- Market research automation\n- Social media monitoring\n- News and trend analysis\n\n### Quality Assurance\n- Automated UI testing\n- Cross-browser compatibility testing\n- Form validation testing\n- Accessibility compliance checking\n\n### Data Collection\n- Web scraping at scale\n- Real-time data monitoring\n- Structured data extraction\n- Screenshot documentation\n\n## Best Practices\n\n1. **Resource Management**: Always clean up browser instances when done\n```python\nbrowser_agent.cleanup()  # For wrapper agents\n```\n\n2. **Error Handling**: Stagehand includes self-healing capabilities, but wrap critical operations in try-except blocks\n\n3. **Parallel Execution**: Use `ConcurrentWorkflow` for simultaneous browser automation across multiple sites\n\n4. **Session Management**: For complex multi-page workflows, use the MCP server's session management capabilities\n\n5. **Rate Limiting**: Be respectful of websites - add delays between requests when necessary\n\n## Testing\n\nRun the test suite to verify the integration:\n\n```bash\npytest tests/stagehand/test_stagehand_integration.py -v\n```\n\n## Troubleshooting\n\n### Common Issues\n\n1. **Browser not starting**: Ensure Playwright is properly installed\n```bash\nplaywright install\n```\n\n2. **MCP connection failed**: Verify the MCP server is running on the correct port\n\n3. **Timeout errors**: Increase timeout in StagehandConfig or agent initialization\n\n### Debug Mode\n\nEnable verbose logging:\n```python\nagent = StagehandAgent(\n    agent_name=\"DebugAgent\",\n    verbose=True,  # Enable detailed logging\n)\n```\n\n## Contributing\n\nWe welcome contributions! Please:\n1. Follow the existing code style\n2. Add tests for new features\n3. Update documentation\n4. Submit PRs with clear descriptions\n\n## License\n\nThese examples are provided under the same license as the Swarms framework. Stagehand is licensed separately - see [Stagehand's repository](https://github.com/browserbase/stagehand) for details."},"items":[{"name":"CLAUDE.md","path":"CLAUDE.md","rawUrl":"https://raw.githubusercontent.com/kyegomez/swarms/HEAD/CLAUDE.md","title":"Claude Agent Guidelines & System Prompt","category":"claude-rule","format":"markdown","content":"# CLAUDE.md — Swarms Framework Guide\n\nThis file teaches you how to build agents and multi-agent systems with the **Swarms** framework. Read it before writing any code in this repo.\n\n---\n\n## Installation & Setup\n\n```bash\npip install swarms\n```\n\nSet your LLM API key as an environment variable before running:\n\n```bash\nexport OPENAI_API_KEY=\"sk-...\"        # OpenAI / GPT models\nexport ANTHROPIC_API_KEY=\"sk-ant-...\" # Claude models\nexport GROQ_API_KEY=\"...\"             # Groq\n# Any provider supported by LiteLLM works\n```\n\nAll imports come from the top-level `swarms` package:\n\n```python\nfrom swarms import (\n    Agent,\n    SequentialWorkflow,\n    ConcurrentWorkflow,\n    AgentRearrange,\n    GraphWorkflow,\n    SwarmRouter,\n    MixtureOfAgents,\n    HierarchicalSwarm,\n    GroupChat,\n    MajorityVoting,\n    # ...\n)\n```\n\n---\n\n## Project Layout\n\n```\nswarms/\n├── swarms/\n│   ├── structs/         # All agent + multi-agent structures (61 files)\n│   │   ├── agent.py             # Core Agent class\n│   │   ├── conversation.py      # Conversation / memory management\n│   │   ├── sequential_workflow.py\n│   │   ├── concurrent_workflow.py\n│   │   ├── agent_rearrange.py\n│   │   ├── graph_workflow.py\n│   │   ├── swarm_router.py      # Single-entry-point router\n│   │   ├── mixture_of_agents.py\n│   │   ├── hiearchical_swarm.py\n│   │   ├── groupchat.py\n│   │   ├── majority_voting.py\n│   │   ├── council_as_judge.py\n│   │   ├── debate_with_judge.py\n│   │   ├── heavy_swarm.py\n│   │   ├── round_robin.py\n│   │   ├── planner_worker_swarm.py\n│   │   ├── auto_swarm_builder.py\n│   │   └── multi_agent_exec.py  # run_agents_concurrently + friends\n│   ├── tools/           # Tool utilities, MCP, schema conversion\n│   └── utils/           # Logging, formatting helpers\n├── examples/            # 586 runnable examples\n│   ├── single_agent/\n│   ├── multi_agent/\n│   ├── tools/\n│   └── guides/\n└── v12_examples/        # New v12 feature examples\n```\n\nLook in `examples/` first before writing new code — there is almost certainly an existing example close to what you need.\n\n---\n\n## Core Primitive: Agent\n\n`Agent` is the single building block everything else composes. All multi-agent structures wrap one or more `Agent` instances.\n\n### Minimal agent\n\n```python\nfrom swarms import Agent\n\nagent = Agent(\n    agent_name=\"Analyst\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n)\n\nresult = agent.run(\"Summarise the current state of LLM research.\")\nprint(result)\n```\n\n### Key constructor parameters\n\n| Parameter | Type | Default | Purpose |\n|---|---|---|---|\n| `agent_name` | str | `\"swarm-worker-01\"` | Unique name — used for memory file paths |\n| `agent_description` | str | generic | Shown to orchestrators for routing |\n| `system_prompt` | str | built-in | The agent's persona / instructions |\n| `model_name` | str | `\"gpt-5.4\"` | Any LiteLLM model string |\n| `max_loops` | int \\| `\"auto\"` | `1` | Loops before returning; `\"auto\"` = autonomous until done |\n| `tools` | list[Callable] | `None` | Python functions the agent can call |\n| `streaming_on` | bool | `False` | Stream tokens to stdout |\n| `interactive` | bool | `False` | REPL mode — prompt user for input each loop |\n| `context_length` | int | `None` | Token budget; triggers compression at 90 % |\n| `context_compression` | bool | `True` | Auto-summarise when near context limit (v12) |\n| `persistent_memory` | bool | `False` | Read/write MEMORY.md across restarts (v12); opt in explicitly |\n| `temperature` | float | `0.5` | Sampling temperature |\n| `max_tokens` | int | model's max output | Max tokens per LLM call. Unset resolves to the model's own output limit |\n| `reasoning_effort` | str | `None` | `\"low\"`, `\"medium\"`, `\"high\"` for reasoning models |\n| `thinking_tokens` | int | `None` | Extended thinking budget (Claude) |\n| `output_type` | str | `\"str-all-except-first\"` | How to format returned output |\n| `mcp_url` | str | `None` | MCP server URL to load tools from |\n| `handoffs` | list | `None` | Agents this agent can hand off to |\n| `plan_enabled` | bool | `False` | Generate a plan before execution |\n| `autosave` | bool | `False` | Save agent state to disk after each run |\n\n### Autonomous loop (`max_loops=\"auto\"`)\n\nWhen `max_loops=\"auto\"` the agent runs a plan→execute→reflect loop until it decides it is done. It automatically gets access to:\n- A `think` tool (disabled when `thinking_tokens` is set)\n- A `grep` tool for searching files (v12)\n- Bash / file tools if configured\n\n```python\nagent = Agent(\n    agent_name=\"Researcher\",\n    model_name=\"gpt-5.4\",\n    max_loops=\"auto\",\n    interactive=False,\n)\nresult = agent.run(\"Research the top 5 vector databases and compare them.\")\n```\n\n### Model names\n\nUse any LiteLLM-compatible string:\n\n```python\n# OpenAI\nmodel_name=\"gpt-5.4\"\nmodel_name=\"gpt-5.4-mini\"\nmodel_name=\"o3\"\n\n# Anthropic\nmodel_name=\"claude-opus-4-7-20251001\"\nmodel_name=\"claude-sonnet-4-6\"\nmodel_name=\"claude-haiku-4-5-20251001\"\n\n# Groq\nmodel_name=\"groq/llama-3.3-70b-versatile\"\n\n# Google\nmodel_name=\"gemini/gemini-2.5-pro\"\n```\n\n### Running with images\n\n```python\nresult = agent.run(\n    task=\"Describe what you see in this chart.\",\n    img=\"path/to/chart.png\",   # or base64 string or URL\n)\n```\n\n---\n\n## Memory & Persistence (v12)\n\n### `persistent_memory=True` (opt in)\n\nOn startup the agent reads `{workspace}/agents/{agent_name}/MEMORY.md` and injects it as a system preamble. On each response it appends to that file. State survives process restarts automatically.\n\n```python\nagent = Agent(\n    agent_name=\"ProjectAssistant\",\n    model_name=\"gpt-5.4\",\n    persistent_memory=True,   # off by default; opt in\n)\n# First run: agent has no prior context\nagent.run(\"My project is called Helios. Remember that.\")\n\n# New process, same agent_name → agent remembers \"Helios\".\n# persistent_memory must be set here too; it is False by default.\nagent2 = Agent(\n    agent_name=\"ProjectAssistant\",\n    model_name=\"gpt-5.4\",\n    persistent_memory=True,\n)\nagent2.run(\"What is my project called?\")\n```\n\n### `persistent_memory=False` (default)\n\nFully stateless — no disk reads or writes. Use for short, isolated tasks where carry-over would be harmful.\n\n```python\nagent = Agent(\n    agent_name=\"OneShot\",\n    model_name=\"gpt-5.4\",\n    persistent_memory=False,\n)\n```\n\n### `context_compression=True` (default)\n\n`ContextCompressor` fires automatically when token usage crosses 90 % of `context_length`. It summarises and rewrites `MEMORY.md` in place so long sessions never hit the context wall.\n\n```python\nagent = Agent(\n    agent_name=\"LongSession\",\n    model_name=\"gpt-5.4\",\n    context_length=32000,\n    context_compression=True,   # default\n)\n```\n\n### Conversation.compact()\n\nManually collapse history to a single summary; creates a timestamped archive before rewriting:\n\n```python\nfrom swarms.structs.conversation import Conversation\n\nconv = Conversation(agent_name=\"MyAgent\", system_prompt=\"You are helpful.\")\nconv.add(\"user\", \"Tell me about X\")\nconv.add(\"assistant\", \"X is ...\")\n\n# Collapse history, archive the full log\nconv.compact(summary=\"User asked about X. Assistant explained X.\")\n```\n\n---\n\n## Tools\n\n### Python functions as tools\n\nDecorate any Python function with a docstring — the framework converts it to an OpenAI function-calling schema automatically:\n\n```python\nimport yfinance as yf\nfrom swarms import Agent\n\ndef get_stock_price(ticker: str) -> str:\n    \"\"\"Fetch the current stock price for a given ticker symbol.\n\n    Args:\n        ticker: Stock ticker symbol, e.g. 'AAPL'.\n\n    Returns:\n        Current price as a formatted string.\n    \"\"\"\n    data = yf.Ticker(ticker)\n    price = data.fast_info[\"last_price\"]\n    return f\"{ticker}: ${price:.2f}\"\n\nagent = Agent(\n    agent_name=\"StockAnalyst\",\n    model_name=\"gpt-5.4\",\n    tools=[get_stock_price],\n    max_loops=3,\n)\nresult = agent.run(\"What is the current price of Apple and Microsoft?\")\n```\n\n### Multiple tools\n\n```python\nagent = Agent(\n    agent_name=\"ResearchAgent\",\n    model_name=\"gpt-5.4\",\n    tools=[search_web, get_stock_price, read_file, write_file],\n    max_loops=\"auto\",\n)\n```\n\n### Tool schema from Pydantic\n\n```python\nfrom swarms.tools.pydantic_to_json import base_model_to_openai_function\nfrom pydantic import BaseModel\n\nclass WeatherQuery(BaseModel):\n    city: str\n    units: str = \"celsius\"\n\nschema = base_model_to_openai_function(WeatherQuery)\n```\n\n---\n\n## Streaming\n\n### Stream to stdout\n\n```python\nagent = Agent(\n    agent_name=\"Writer\",\n    model_name=\"gpt-5.4\",\n    streaming_on=True,\n)\nagent.run(\"Write a short poem about distributed systems.\")\n```\n\n### Stream tokens to a callback\n\n```python\ndef handle_token(token: str) -> None:\n    print(token, end=\"\", flush=True)\n\nagent = Agent(\n    agent_name=\"Writer\",\n    model_name=\"gpt-5.4\",\n    streaming_callback=handle_token,\n)\nagent.run(\"Write a haiku.\")\n```\n\n### Async streaming (`arun_stream`)\n\n```python\nimport asyncio\nfrom swarms import Agent\n\nagent = Agent(agent_name=\"AsyncWriter\", model_name=\"gpt-5.4\", streaming_on=True)\n\nasync def main():\n    async for token in agent.arun_stream(\"Explain async/await in Python.\"):\n        print(token, end=\"\", flush=True)\n\nasyncio.run(main())\n```\n\n---\n\n## Multi-Agent Structures\n\n### Sequential Workflow\n\nAgents execute **one after another**. The output of each agent is passed as context to the next.\n\n```python\nfrom swarms import Agent, SequentialWorkflow\n\nresearcher = Agent(agent_name=\"Researcher\", model_name=\"gpt-5.4\", max_loops=1)\nanalyst   = Agent(agent_name=\"Analyst\",    model_name=\"gpt-5.4\", max_loops=1)\nwriter    = Agent(agent_name=\"Writer\",     model_name=\"gpt-5.4\", max_loops=1)\n\npipeline = SequentialWorkflow(\n    agents=[researcher, analyst, writer],\n    max_loops=1,\n)\nresult = pipeline.run(\"Analyse the impact of interest rate hikes on tech stocks.\")\n```\n\n**When to use:** Linear pipelines where each step depends on the prior step's output. Research → Analysis → Report. Extraction → Transformation → Load.\n\n---\n\n### Concurrent Workflow\n\nAll agents run **in parallel** on the same task. Results are collected and returned together.\n\n```python\nfrom swarms import Agent, ConcurrentWorkflow\n\nagents = [\n    Agent(agent_name=f\"Worker-{i}\", model_name=\"gpt-5.4\", max_loops=1)\n    for i in range(5)\n]\n\nworkflow = ConcurrentWorkflow(agents=agents)\nresults = workflow.run(\"List 10 use cases for multi-agent AI systems.\")\n```\n\n**When to use:** Independent subtasks that can run simultaneously. Analysing multiple documents. Querying multiple data sources. Generating multiple creative variants.\n\n---\n\n### AgentRearrange — Flow DSL\n\nDefine execution flow as a string using a simple DSL. Mix sequential (`->`) and parallel (`,`) execution.\n\n```python\nfrom swarms import Agent, AgentRearrange\n\nplanner  = Agent(agent_name=\"Planner\",  model_name=\"gpt-5.4\", max_loops=1)\ncoder    = Agent(agent_name=\"Coder\",    model_name=\"gpt-5.4\", max_loops=1)\nreviewer = Agent(agent_name=\"Reviewer\", model_name=\"gpt-5.4\", max_loops=1)\ntester   = Agent(agent_name=\"Tester\",   model_name=\"gpt-5.4\", max_loops=1)\n\npipeline = AgentRearrange(\n    agents=[planner, coder, reviewer, tester],\n    flow=\"Planner -> Coder -> Reviewer, Tester\",\n    #        sequential  ↑      parallel  ↑\n    max_loops=1,\n)\nresult = pipeline.run(\"Build a Python function that validates email addresses.\")\n```\n\n**Flow DSL rules:**\n- `A -> B` — A runs, then B receives A's output\n- `A, B` — A and B run concurrently with the same input\n- `A -> B, C -> D` — A runs first, then B and C run concurrently, then D receives their combined output\n\n`AgentRearrange` has no built-in human-in-the-loop step — every name in `flow` must correspond to an agent in `agents`, or the flow will fail at run time. For a human checkpoint, break the pipeline into separate `AgentRearrange`/`Agent.run()` calls and insert your own logic (e.g. `input()`) between them — see the \"Human-in-the-loop with AgentRearrange\" pattern below.\n\n**When to use:** Any workflow where you need explicit, readable control over agent execution order and parallelism.\n\n---\n\n### GraphWorkflow — DAG Execution\n\nFull directed-acyclic-graph (DAG) execution. Nodes are agents; edges are dependencies. Topological sort ensures correct order. Supports per-node callbacks and token streaming.\n\n```python\nfrom swarms import Agent, GraphWorkflow, Node, Edge, NodeType\n\n# Build agents\nanalyst  = Agent(agent_name=\"Analyst\",  model_name=\"gpt-5.4-mini\", max_loops=1)\nwriter   = Agent(agent_name=\"Writer\",   model_name=\"gpt-5.4-mini\", max_loops=1)\nreviewer = Agent(agent_name=\"Reviewer\", model_name=\"gpt-5.4-mini\", max_loops=1)\npublisher = Agent(agent_name=\"Publisher\", model_name=\"gpt-5.4-mini\", max_loops=1)\n\n# Build graph\nwf = GraphWorkflow()\nwf.add_node(Node(id=\"analyst\",   type=NodeType.AGENT, agent=analyst))\nwf.add_node(Node(id=\"writer\",    type=NodeType.AGENT, agent=writer))\nwf.add_node(Node(id=\"reviewer\",  type=NodeType.AGENT, agent=reviewer))\nwf.add_node(Node(id=\"publisher\", type=NodeType.AGENT, agent=publisher))\n\nwf.add_edge(Edge(source=\"analyst\",  target=\"writer\"))\nwf.add_edge(Edge(source=\"writer\",   target=\"reviewer\"))\nwf.add_edge(Edge(source=\"reviewer\", target=\"publisher\"))\n\nwf.set_entry_points([\"analyst\"])\nwf.set_end_points([\"publisher\"])\n\n# Run with callbacks\ndef on_done(node_name: str, result: str) -> None:\n    print(f\"[{node_name}] finished — {len(result)} chars\")\n\nresults = wf.run(\n    task=\"Produce a market report on AI chips.\",\n    on_node_complete=on_done,          # fires after each node\n    streaming_callback=lambda tok: print(tok, end=\"\", flush=True),\n)\n```\n\n**Diamond / fan-out fan-in pattern:**\n\n```python\n# analyst feeds both writer AND researcher concurrently,\n# then editor combines both outputs\nwf.add_edge(Edge(source=\"analyst\",    target=\"writer\"))\nwf.add_edge(Edge(source=\"analyst\",    target=\"researcher\"))\nwf.add_edge(Edge(source=\"writer\",     target=\"editor\"))\nwf.add_edge(Edge(source=\"researcher\", target=\"editor\"))\n```\n\n**When to use:** Complex dependency graphs, fan-out/fan-in patterns, when you need precise control over which agents depend on which.\n\n---\n\n### SwarmRouter — Single Entry Point\n\n`SwarmRouter` is the highest-level abstraction. Pass it a list of agents and a `swarm_type` — it handles the rest. Use this when you want to switch architectures without rewriting orchestration code.\n\n```python\nfrom swarms import Agent, SwarmRouter\n\nagents = [\n    Agent(agent_name=\"Analyst\",  model_name=\"gpt-5.4\", max_loops=1),\n    Agent(agent_name=\"Writer\",   model_name=\"gpt-5.4\", max_loops=1),\n    Agent(agent_name=\"Reviewer\", model_name=\"gpt-5.4\", max_loops=1),\n]\n\nrouter = SwarmRouter(\n    agents=agents,\n    swarm_type=\"SequentialWorkflow\",   # swap to any SwarmType below\n    max_loops=1,\n)\nresult = router.run(\"Write a blog post about transformer architectures.\")\n```\n\n**All `swarm_type` options:**\n\n| SwarmType | Behaviour |\n|---|---|\n| `\"SequentialWorkflow\"` | Agents run one after another |\n| `\"ConcurrentWorkflow\"` | Agents run in parallel |\n| `\"AgentRearrange\"` | Flow-DSL based execution |\n| `\"MixtureOfAgents\"` | Workers + aggregator layer |\n| `\"HierarchicalSwarm\"` | Boss delegates to workers |\n| `\"GroupChat\"` | Multi-agent round-table discussion |\n| `\"MultiAgentRouter\"` | Task routed to best-fit agent |\n| `\"MajorityVoting\"` | Agents vote; majority wins |\n| `\"CouncilAsAJudge\"` | Council deliberates; judge decides |\n| `\"DebateWithJudge\"` | Agents debate; judge rules |\n| `\"HeavySwarm\"` | Intensive multi-loop deep analysis |\n| `\"RoundRobin\"` | Round-robin task distribution |\n| `\"PlannerWorkerSwarm\"` | Planner + worker delegation |\n| `\"BatchedGridWorkflow\"` | Grid-based batch execution |\n| `\"LLMCouncil\"` | LLM-based council decisions |\n| `\"AutoSwarmBuilder\"` | Auto-configures everything |\n| `\"auto\"` | Router selects swarm_type automatically |\n\n---\n\n### MixtureOfAgents\n\nMultiple **worker** agents each respond to the task independently, then an **aggregator** agent synthesises all responses into a final answer. Repeat for multiple layers.\n\n```python\nfrom swarms import Agent, MixtureOfAgents\n\nworkers = [\n    Agent(agent_name=\"Worker-GPT\",    model_name=\"gpt-5.4\",       max_loops=1),\n    Agent(agent_name=\"Worker-Claude\", model_name=\"claude-sonnet-4-6\", max_loops=1),\n    Agent(agent_name=\"Worker-Llama\",  model_name=\"groq/llama-3.3-70b-versatile\", max_loops=1),\n]\n\naggregator = Agent(\n    agent_name=\"Aggregator\",\n    model_name=\"gpt-5.4\",\n    system_prompt=\"Synthesise the following expert responses into one coherent answer.\",\n    max_loops=1,\n)\n\nmoa = MixtureOfAgents(\n    agents=workers,\n    aggregator_agent=aggregator,\n    layers=2,        # run worker→aggregate cycle this many times\n    max_loops=1,\n)\nresult = moa.run(\"What are the best practices for securing a Kubernetes cluster?\")\n```\n\n**When to use:** High-stakes tasks where you want multiple independent perspectives merged into a consensus. Works especially well with diverse model providers.\n\n---\n\n### HierarchicalSwarm\n\nA director agent breaks the task into subtasks and delegates them to worker agents. Workers report back; director synthesises.\n\n```python\nfrom swarms import Agent, HierarchicalSwarm\n\ndirector = Agent(\n    agent_name=\"Director\",\n    agent_description=\"Breaks complex tasks into subtasks and delegates them.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n)\n\nworkers = [\n    Agent(agent_name=\"DataWorker\",    model_name=\"gpt-5.4-mini\", max_loops=1),\n    Agent(agent_name=\"WritingWorker\", model_name=\"gpt-5.4-mini\", max_loops=1),\n    Agent(agent_name=\"ReviewWorker\",  model_name=\"gpt-5.4-mini\", max_loops=1),\n]\n\nswarm = HierarchicalSwarm(\n    director=director,\n    agents=workers,\n    max_loops=2,\n)\nresult = swarm.run(\"Produce a comprehensive competitive analysis of the AI chip market.\")\n```\n\n**When to use:** Tasks naturally decomposed into subtasks where a coordinator must manage work allocation and synthesis.\n\n---\n\n### GroupChat\n\nAn asynchronous, self-selecting groupchat. There are no rounds or speaker-selection functions — every agent listens in parallel and decides on its own whether to chime in. A forced `respond(score, message)` function call asks each agent how much it wants to speak (0..1); replies above `threshold` are broadcast. The chat ends when `max_loops` messages have been posted or no message arrives for `idle_timeout` seconds.\n\n```python\nfrom swarms import Agent\nfrom swarms.structs.groupchat import GroupChat, RESPOND_TOOL\n\n# Every agent MUST carry RESPOND_TOOL so the chat can ask it whether to speak.\n# Recommended per-agent: max_loops=1, persistent_memory=False.\noptimist = Agent(\n    agent_name=\"Optimist\",\n    system_prompt=\"You argue for the benefits.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n    persistent_memory=False,\n    tools_list_dictionary=[RESPOND_TOOL],\n)\npessimist = Agent(\n    agent_name=\"Pessimist\",\n    system_prompt=\"You argue for the risks.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n    persistent_memory=False,\n    tools_list_dictionary=[RESPOND_TOOL],\n)\nrealist = Agent(\n    agent_name=\"Realist\",\n    system_prompt=\"You seek balanced analysis.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n    persistent_memory=False,\n    tools_list_dictionary=[RESPOND_TOOL],\n)\n\nchat = GroupChat(\n    agents=[optimist, pessimist, realist],\n    max_loops=10,        # hard cap on total messages posted\n    threshold=0.5,       # min decision score (0..1) to publish a reply\n    idle_timeout=8.0,    # seconds of silence before stopping\n)\nresult = chat.run(\"Should we adopt AI for medical diagnosis?\")\n```\n\n**Tuning:** raise `threshold` for a more selective room; lower it for livelier chats. Raise `idle_timeout` if agents need time to think before replying.\n\n---\n\n### MajorityVoting\n\nAll agents independently answer the task. The answer that appears in the majority of responses wins.\n\n```python\nfrom swarms import Agent, MajorityVoting\n\nvoters = [\n    Agent(agent_name=f\"Voter-{i}\", model_name=\"gpt-5.4-mini\", max_loops=1)\n    for i in range(5)\n]\n\nmv = MajorityVoting(agents=voters, max_loops=1)\nresult = mv.run(\"Is Python or Rust better for building a high-performance web server?\")\n```\n\n**When to use:** Classification, yes/no decisions, or any task with a discrete answer set where you want noise reduction through consensus.\n\n---\n\n### CouncilAsAJudge\n\nA council of agents each deliberate, then a judge agent makes the final ruling based on the council's reasoning.\n\n```python\nfrom swarms import Agent, CouncilAsAJudge\n\ncouncil = [\n    Agent(agent_name=\"Expert-Security\", model_name=\"gpt-5.4\", max_loops=1),\n    Agent(agent_name=\"Expert-Privacy\",  model_name=\"gpt-5.4\", max_loops=1),\n    Agent(agent_name=\"Expert-Legal\",    model_name=\"gpt-5.4\", max_loops=1),\n]\n\njudge = Agent(\n    agent_name=\"Judge\",\n    system_prompt=\"Given the council's analysis, deliver a final verdict.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n)\n\ncouncil_swarm = CouncilAsAJudge(\n    agents=council,\n    judge=judge,\n    max_loops=1,\n)\nresult = council_swarm.run(\"Should we store user biometric data on-device only?\")\n```\n\n---\n\n### DebateWithJudge\n\nTwo or more agents argue opposing positions for multiple rounds. A judge delivers a verdict at the end.\n\n```python\nfrom swarms import Agent, DebateWithJudge\n\npro  = Agent(agent_name=\"Pro\",  system_prompt=\"Argue strongly in favour.\",  model_name=\"gpt-5.4\", max_loops=1)\ncon  = Agent(agent_name=\"Con\",  system_prompt=\"Argue strongly against.\",    model_name=\"gpt-5.4\", max_loops=1)\n\njudge = Agent(\n    agent_name=\"Judge\",\n    system_prompt=\"Evaluate the debate and deliver an objective verdict.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n)\n\ndebate = DebateWithJudge(\n    agents=[pro, con],\n    judge=judge,\n    max_loops=3,   # 3 rounds of argument\n)\nresult = debate.run(\"Motion: Open-source LLMs will surpass closed-source models by 2027.\")\n```\n\n---\n\n### HeavySwarm\n\nIntensive multi-loop analysis. Each agent runs for many loops on the problem, producing deep reasoning. Best for research-grade analysis.\n\n```python\nfrom swarms import HeavySwarm\n\nswarm = HeavySwarm(\n    num_agents=4,\n    model_name=\"gpt-5.4\",\n    loops_per_agent=5,       # each agent reasons for 5 loops\n    show_output=True,\n)\nresult = swarm.run(\"Derive a novel approach to solving the alignment problem in AI.\")\n```\n\nOr via `SwarmRouter`:\n\n```python\nfrom swarms import Agent, SwarmRouter\n\nagents = [Agent(agent_name=f\"Deep-{i}\", model_name=\"gpt-5.4\", max_loops=5) for i in range(4)]\nrouter = SwarmRouter(agents=agents, swarm_type=\"HeavySwarm\")\nresult = router.run(\"Deep analysis: implications of AGI on global labour markets.\")\n```\n\n---\n\n### RoundRobinSwarm\n\nDistributes tasks to agents in a fixed rotation. Each agent handles every Nth task.\n\n```python\nfrom swarms import Agent, RoundRobinSwarm\n\nagents = [\n    Agent(agent_name=f\"Handler-{i}\", model_name=\"gpt-5.4-mini\", max_loops=1)\n    for i in range(3)\n]\n\nrr = RoundRobinSwarm(agents=agents, max_loops=1)\n\ntasks = [\"Task A\", \"Task B\", \"Task C\", \"Task D\", \"Task E\", \"Task F\"]\nfor task in tasks:\n    result = rr.run(task)\n```\n\n---\n\n### PlannerWorkerSwarm\n\nA planner agent generates a structured plan; worker agents execute each step.\n\n```python\nfrom swarms import Agent, PlannerWorkerSwarm\n\nplanner = Agent(\n    agent_name=\"Planner\",\n    system_prompt=\"You create detailed, step-by-step execution plans.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n)\n\nworkers = [\n    Agent(agent_name=f\"Worker-{i}\", model_name=\"gpt-5.4-mini\", max_loops=2)\n    for i in range(4)\n]\n\nswarm = PlannerWorkerSwarm(\n    planner_agent=planner,\n    worker_agents=workers,\n    max_loops=1,\n)\nresult = swarm.run(\"Build a complete go-to-market strategy for a B2B SaaS product.\")\n```\n\n---\n\n### AutoSwarmBuilder\n\nPass a high-level description of the task — the framework automatically creates the agents, assigns roles, and runs the appropriate swarm architecture.\n\n```python\nfrom swarms import AutoSwarmBuilder\n\nbuilder = AutoSwarmBuilder(\n    name=\"MarketResearchSwarm\",\n    description=\"A swarm that produces comprehensive market research reports\",\n    max_loops=2,\n)\nresult = builder.run(\"Research the electric vehicle market and identify growth opportunities.\")\n```\n\n**When to use:** Rapid prototyping, when you don't know yet which structure fits, or when you want the LLM to decide.\n\n---\n\n## Utility Execution Helpers\n\n```python\nfrom swarms.structs.multi_agent_exec import (\n    run_agents_concurrently,\n    run_agents_concurrently_async,\n    run_agents_with_different_tasks,\n    run_single_agent,\n)\n\n# Same task, all agents in parallel\nresults = run_agents_concurrently(agents=agents, task=\"Summarise the news today.\")\n\n# Different task per agent\ntask_map = {agent: task for agent, task in zip(agents, tasks)}\nresults = run_agents_with_different_tasks(task_map)\n\n# Async version\nimport asyncio\nresults = asyncio.run(run_agents_concurrently_async(agents=agents, task=\"...\"))\n```\n\n---\n\n## Async Support\n\n```python\nimport asyncio\nfrom swarms import Agent\n\nagent = Agent(agent_name=\"AsyncAgent\", model_name=\"gpt-5.4\")\n\nasync def main():\n    # Standard async run\n    result = await agent.arun(\"What is the capital of France?\")\n    print(result)\n\n    # Streaming async run\n    async for token in agent.arun_stream(\"Explain quantum entanglement.\"):\n        print(token, end=\"\", flush=True)\n\nasyncio.run(main())\n```\n\n---\n\n## MCP Tool Integration\n\nLoad tools from any MCP server. The agent auto-discovers available tools on startup.\n\n```python\nfrom swarms import Agent\n\n# Single MCP server\nagent = Agent(\n    agent_name=\"MCPAgent\",\n    model_name=\"gpt-5.4\",\n    mcp_url=\"http://localhost:8000/sse\",   # SSE endpoint\n    max_loops=\"auto\",\n)\n\n# Multiple MCP servers\nagent = Agent(\n    agent_name=\"MultiMCPAgent\",\n    model_name=\"gpt-5.4\",\n    mcp_urls=[\n        \"http://localhost:8000/sse\",\n        \"http://localhost:8001/sse\",\n    ],\n    max_loops=\"auto\",\n)\n\nresult = agent.run(\"Use the available tools to complete the task.\")\n```\n\nFetch tools manually:\n\n```python\nfrom swarms.tools.mcp_client_tools import get_mcp_tools_sync, aget_mcp_tools\n\ntools = get_mcp_tools_sync(server_url=\"http://localhost:8000/sse\")\n\nimport asyncio\ntools = asyncio.run(aget_mcp_tools(server_url=\"http://localhost:8000/sse\"))\n```\n\n---\n\n## Conversation Management\n\n`Conversation` manages message history with optional disk persistence.\n\n```python\nfrom swarms.structs.conversation import Conversation\n\nconv = Conversation(\n    system_prompt=\"You are a helpful assistant.\",\n    agent_name=\"MyAgent\",      # keys MEMORY.md to this name\n    time_enabled=True,         # include ISO timestamps in history\n)\n\nconv.add(\"user\", \"What is 2+2?\")\nconv.add(\"assistant\", \"4.\")\n\n# Get history as string (includes timestamps in v12)\nhistory_str = conv.return_history_as_string()\n\n# Compact + archive\nconv.compact(summary=\"User asked basic arithmetic. Answer: 4.\")\n\n# Pass to an agent\nagent = Agent(\n    agent_name=\"MyAgent\",\n    model_name=\"gpt-5.4\",\n    # agent reads MEMORY.md automatically when persistent_memory=True\n)\n```\n\n---\n\n## Choosing the Right Structure\n\n| Situation | Use |\n|---|---|\n| Simple single task | `Agent` |\n| Linear A→B→C pipeline | `SequentialWorkflow` |\n| Same task, many agents at once | `ConcurrentWorkflow` |\n| Custom mix of sequential + parallel | `AgentRearrange` |\n| Complex dependency graph / DAG | `GraphWorkflow` |\n| Need per-node callbacks or streaming | `GraphWorkflow` |\n| Multiple models, one synthesised answer | `MixtureOfAgents` |\n| Manager delegates to specialists | `HierarchicalSwarm` |\n| Open discussion / brainstorming | `GroupChat` |\n| Discrete decision via consensus | `MajorityVoting` |\n| High-stakes ruling with deliberation | `CouncilAsAJudge` |\n| Structured adversarial debate | `DebateWithJudge` |\n| Deep research, many loops | `HeavySwarm` |\n| Don't know yet / rapid prototyping | `AutoSwarmBuilder` or `SwarmRouter(swarm_type=\"auto\")` |\n| Need to switch architectures easily | `SwarmRouter` |\n\n---\n\n## Common Patterns & Recipes\n\n### Pattern: Research → Write → Review pipeline\n\n```python\nfrom swarms import Agent, SequentialWorkflow\n\npipeline = SequentialWorkflow(agents=[\n    Agent(agent_name=\"Researcher\", system_prompt=\"You research topics thoroughly.\", model_name=\"gpt-5.4\"),\n    Agent(agent_name=\"Writer\",     system_prompt=\"You write clear, engaging content.\", model_name=\"gpt-5.4\"),\n    Agent(agent_name=\"Editor\",     system_prompt=\"You improve clarity and fix errors.\", model_name=\"gpt-5.4\"),\n], max_loops=1)\n\nresult = pipeline.run(\"Write an article about the history of neural networks.\")\n```\n\n### Pattern: Fan-out to specialists, fan-in to synthesiser\n\n```python\nfrom swarms import Agent, MixtureOfAgents\n\nspecialists = [\n    Agent(agent_name=\"TechExpert\",    system_prompt=\"Analyse the technical aspects.\", model_name=\"gpt-5.4\"),\n    Agent(agent_name=\"BusinessExpert\",system_prompt=\"Analyse the business aspects.\", model_name=\"gpt-5.4\"),\n    Agent(agent_name=\"LegalExpert\",   system_prompt=\"Analyse the legal aspects.\",   model_name=\"gpt-5.4\"),\n]\nsynthesiser = Agent(agent_name=\"Synthesiser\", model_name=\"gpt-5.4\",\n                    system_prompt=\"Combine expert analyses into one coherent report.\")\n\nmoa = MixtureOfAgents(agents=specialists, aggregator_agent=synthesiser)\nresult = moa.run(\"Evaluate the risks of launching a fintech product in the EU.\")\n```\n\n### Pattern: Autonomous agent with tools and memory\n\n```python\nimport os\nfrom swarms import Agent\n\ndef search_web(query: str) -> str:\n    \"\"\"Search the web for a query and return results.\"\"\"\n    # your implementation\n    ...\n\ndef write_file(filename: str, content: str) -> str:\n    \"\"\"Write content to a file.\"\"\"\n    with open(filename, \"w\") as f:\n        f.write(content)\n    return f\"Written to {filename}\"\n\nagent = Agent(\n    agent_name=\"AutonomousResearcher\",\n    model_name=\"gpt-5.4\",\n    max_loops=\"auto\",\n    tools=[search_web, write_file],\n    persistent_memory=True,\n    context_compression=True,\n    context_length=32000,\n)\nagent.run(\"Research the top 10 open-source LLMs and write a comparison report to report.md\")\n```\n\n### Pattern: Multi-model ensemble with streaming\n\n```python\nimport sys\nfrom swarms import Agent, ConcurrentWorkflow\n\nagents = [\n    Agent(agent_name=\"GPT\",    model_name=\"gpt-5.4\",          max_loops=1),\n    Agent(agent_name=\"Claude\", model_name=\"claude-sonnet-4-6\", max_loops=1),\n    Agent(agent_name=\"Gemini\", model_name=\"gemini/gemini-2.5-pro\", max_loops=1),\n]\n\nworkflow = ConcurrentWorkflow(agents=agents)\nresults = workflow.run(\"What is the most important unsolved problem in mathematics?\")\n\nfor agent_name, answer in results.items():\n    print(f\"\\n=== {agent_name} ===\\n{answer}\")\n```\n\n### Pattern: Human-in-the-loop with AgentRearrange\n\n`AgentRearrange` has no native human-in-the-loop step — chain separate `.run()` calls yourself and insert your own checkpoint logic between them:\n\n```python\nfrom swarms import Agent\n\ndrafter  = Agent(agent_name=\"Drafter\",  model_name=\"gpt-5.4\")\nfinisher = Agent(agent_name=\"Finisher\", model_name=\"gpt-5.4\")\n\ndraft = drafter.run(\"Draft a press release about our product launch.\")\n\nprint(f\"\\nAgent says:\\n{draft}\\n\")\nfeedback = input(\"Your feedback: \")\n\nresult = finisher.run(f\"Revise this draft based on the feedback.\\n\\nDraft:\\n{draft}\\n\\nFeedback:\\n{feedback}\")\n```\n\n### Pattern: GraphWorkflow with fan-out / fan-in\n\n```python\nfrom swarms import Agent, GraphWorkflow, Node, Edge, NodeType\n\ningestion = Agent(agent_name=\"Ingestion\", model_name=\"gpt-5.4-mini\", max_loops=1)\nbranch_a  = Agent(agent_name=\"BranchA\",   model_name=\"gpt-5.4-mini\", max_loops=1)\nbranch_b  = Agent(agent_name=\"BranchB\",   model_name=\"gpt-5.4-mini\", max_loops=1)\nmerger    = Agent(agent_name=\"Merger\",    model_name=\"gpt-5.4\",      max_loops=1)\n\nwf = GraphWorkflow()\nfor a in [ingestion, branch_a, branch_b, merger]:\n    wf.add_node(Node(id=a.agent_name, type=NodeType.AGENT, agent=a))\n\nwf.add_edge(Edge(source=\"Ingestion\", target=\"BranchA\"))\nwf.add_edge(Edge(source=\"Ingestion\", target=\"BranchB\"))\nwf.add_edge(Edge(source=\"BranchA\",   target=\"Merger\"))\nwf.add_edge(Edge(source=\"BranchB\",   target=\"Merger\"))\n\nwf.set_entry_points([\"Ingestion\"])\nwf.set_end_points([\"Merger\"])\n\nresults = wf.run(task=\"Process this dataset from two angles and merge the findings.\")\n```\n\n---\n\n## What to Avoid\n\n**Don't import from submodules directly** — always import from `swarms`:\n```python\n# Wrong\nfrom swarms.structs.agent import Agent\n\n# Right\nfrom swarms import Agent\n```\n\n**Don't set `max_loops=\"auto\"` without a clear stopping condition** — the agent will loop until it decides it is done or hits a resource limit. Prefer explicit `max_loops=N` for production tasks.\n\n**Don't give all agents the same `agent_name`** — `persistent_memory` and `MEMORY.md` are keyed on `agent_name`. Duplicate names cause agents to share and corrupt each other's memory.\n\n**Don't instantiate heavyweight structures inside tight loops** — create agents and workflows once, reuse them across calls.\n\n**Don't pass `tools=[]` (empty list)** — pass `tools=None` instead. An empty list can confuse schema generation.\n\n**Don't use `streaming_on=True` and `streaming_callback` together on the same agent** — `streaming_on` streams to stdout; `streaming_callback` streams to your function. Pick one.\n\n**Don't set `context_compression=False` on very long autonomous sessions** — without compression the agent will eventually hit the context limit and raise an error.\n\n**For long-running autonomous agents in production**, always set:\n```python\nagent = Agent(\n    ...\n    persistent_memory=True,\n    context_compression=True,\n    context_length=32000,\n    autosave=True,\n)\n```\n","isInternal":false,"tokens":8600,"sizeBytes":33689},{"name":"SKILL.md","path":"examples/single_agent/capabilities/skills/code-review/SKILL.md","rawUrl":"https://raw.githubusercontent.com/kyegomez/swarms/HEAD/examples/single_agent/capabilities/skills/code-review/SKILL.md","title":"code-review","category":"anthropic-skill","format":"markdown","content":"---\nname: code-review\ndescription: Perform comprehensive code reviews focusing on best practices, security vulnerabilities, performance optimization, and maintainability\n---\n\n# Code Review Skill\n\nWhen reviewing code, follow this systematic approach to ensure thorough evaluation:\n\n## Review Checklist\n\n### 1. Code Quality\n- **Readability**: Is the code easy to understand?\n- **Naming**: Are variables, functions, and classes well-named?\n- **Structure**: Is the code properly organized and modular?\n- **Comments**: Are complex sections adequately documented?\n- **Complexity**: Are there overly complex functions that should be simplified?\n\n### 2. Security Analysis\nCheck for common vulnerabilities:\n- SQL injection vulnerabilities\n- XSS (Cross-Site Scripting) vulnerabilities\n- Authentication and authorization flaws\n- Insecure data handling (passwords, sensitive data)\n- Input validation and sanitization\n- OWASP Top 10 vulnerabilities\n\n### 3. Performance Considerations\n- Identify potential bottlenecks\n- Check for inefficient algorithms or data structures\n- Look for unnecessary database queries or API calls\n- Evaluate caching opportunities\n- Assess memory usage patterns\n\n### 4. Best Practices\n- **DRY Principle**: Eliminate code duplication\n- **SOLID Principles**: Verify adherence to design principles\n- **Error Handling**: Check for proper exception handling\n- **Testing**: Evaluate test coverage and quality\n- **Dependencies**: Review external dependencies and their versions\n\n### 5. Maintainability\n- Is the code easy to modify and extend?\n- Are there proper abstractions?\n- Is the architecture scalable?\n- Are there technical debt concerns?\n\n## Review Format\n\nStructure your review as follows:\n\n1. **Summary**: High-level overview of the changes\n2. **Critical Issues**: Security vulnerabilities or bugs that must be fixed\n3. **Major Concerns**: Significant issues affecting quality or performance\n4. **Suggestions**: Optional improvements and best practices\n5. **Positive Feedback**: Acknowledge good practices and improvements\n\n## Guidelines\n\n- Be constructive and respectful\n- Provide specific examples and suggestions\n- Explain the \"why\" behind recommendations\n- Prioritize issues by severity (critical, major, minor)\n- Reference documentation or standards when applicable\n- Consider the context and constraints of the project\n\n## Example Reviews\n\n**Security Issue:**\n```\nCRITICAL: SQL injection vulnerability detected at line 45\nCurrent: f\"SELECT * FROM users WHERE id = {user_id}\"\nRecommendation: Use parameterized queries to prevent SQL injection\n```\n\n**Performance Suggestion:**\n```\nSUGGESTION: Consider caching database results at line 123\nThe same query is executed multiple times in the loop. Cache the results\nto improve performance by ~80%.\n```\n","frontmatter":{"name":"code-review","description":"Perform comprehensive code reviews focusing on best practices, security vulnerabilities, performance optimization, and maintainability"},"isInternal":false,"tokens":556,"sizeBytes":2767},{"name":"SKILL.md","path":"examples/single_agent/capabilities/skills/data-visualization/SKILL.md","rawUrl":"https://raw.githubusercontent.com/kyegomez/swarms/HEAD/examples/single_agent/capabilities/skills/data-visualization/SKILL.md","title":"data-visualization","category":"anthropic-skill","format":"markdown","content":"---\nname: data-visualization\ndescription: Create effective data visualizations using best practices for clarity, accuracy, and visual communication of insights\n---\n\n# Data Visualization Skill\n\nWhen creating data visualizations, follow these principles to ensure clear and effective communication:\n\n## Core Principles\n\n### 1. Choose the Right Chart Type\n- **Line Charts**: Trends over time, continuous data\n- **Bar Charts**: Comparing categories, discrete data\n- **Scatter Plots**: Relationships between variables, correlations\n- **Pie Charts**: Parts of a whole (use sparingly, max 5-6 segments)\n- **Heatmaps**: Patterns in large datasets, correlations\n- **Box Plots**: Distribution statistics, outlier detection\n\n### 2. Design Guidelines\n\n**Clarity**\n- Use clear, descriptive titles and labels\n- Include units of measurement\n- Add a legend when multiple series are present\n- Ensure adequate contrast and readability\n\n**Accuracy**\n- Start y-axis at zero for bar charts (unless good reason)\n- Use consistent scales across related charts\n- Avoid distorting data through inappropriate scaling\n- Label data points when precision matters\n\n**Simplicity**\n- Remove chart junk and unnecessary decorations\n- Use color purposefully, not decoratively\n- Limit the number of colors (5-7 max)\n- Ensure accessibility (colorblind-friendly palettes)\n\n### 3. Color Best Practices\n- **Sequential**: Use for ordered data (light to dark)\n- **Diverging**: Use for data with a meaningful midpoint\n- **Categorical**: Use for unordered categories\n- **Highlight**: Use accent colors to draw attention\n- Test accessibility with colorblind simulators\n\n### 4. Storytelling with Data\n- Lead with the insight, not the data\n- Use annotations to highlight key findings\n- Arrange charts in logical flow\n- Provide context and comparisons\n- Include data sources and timestamp\n\n## Visualization Workflow\n\n1. **Understand the Data**\n   - Explore data structure and distributions\n   - Identify key variables and relationships\n   - Determine the message to communicate\n\n2. **Select Visualization Type**\n   - Match chart type to data characteristics\n   - Consider audience and use case\n   - Plan for interactivity if needed\n\n3. **Design the Visualization**\n   - Create initial draft\n   - Apply design principles\n   - Optimize for clarity and impact\n\n4. **Refine and Validate**\n   - Get feedback from stakeholders\n   - Test on target audience\n   - Iterate based on feedback\n   - Verify accuracy\n\n## Common Mistakes to Avoid\n\n- Using 3D charts unnecessarily (adds confusion)\n- Too many colors or visual elements\n- Missing or unclear axis labels\n- Truncated y-axis to exaggerate differences\n- Using pie charts for more than 5-6 categories\n- Poor color choices (rainbow colors for sequential data)\n\n## Tools and Libraries\n\nRecommend appropriate tools based on needs:\n- **Python**: matplotlib, seaborn, plotly, altair\n- **R**: ggplot2, plotly\n- **JavaScript**: D3.js, Chart.js, Highcharts\n- **BI Tools**: Tableau, Power BI, Looker\n\n## Example Use Cases\n\n- **Dashboard Design**: \"Create an executive dashboard for sales metrics\"\n- **Exploratory Analysis**: \"Visualize patterns in customer behavior data\"\n- **Report Charts**: \"Generate publication-ready charts for annual report\"\n","frontmatter":{"name":"data-visualization","description":"Create effective data visualizations using best practices for clarity, accuracy, and visual communication of insights"},"isInternal":false,"tokens":702,"sizeBytes":3232},{"name":"SKILL.md","path":"examples/single_agent/capabilities/skills/financial-analysis/SKILL.md","rawUrl":"https://raw.githubusercontent.com/kyegomez/swarms/HEAD/examples/single_agent/capabilities/skills/financial-analysis/SKILL.md","title":"financial-analysis","category":"anthropic-skill","format":"markdown","content":"---\nname: financial-analysis\ndescription: Perform comprehensive financial analysis including DCF modeling, ratio analysis, and financial statement evaluation for companies and investment opportunities\n---\n\n# Financial Analysis Skill\n\nWhen performing financial analysis, follow these systematic steps to ensure thorough and accurate evaluation:\n\n## Core Methodology\n\n### 1. Data Collection and Verification\n- Gather historical financial statements (income statement, balance sheet, cash flow)\n- Verify data sources for accuracy and completeness\n- Identify any anomalies or missing data points\n\n### 2. Financial Ratio Analysis\nCalculate and analyze key financial ratios:\n- **Profitability**: EBITDA margin, net profit margin, ROE, ROA\n- **Liquidity**: Current ratio, quick ratio, cash ratio\n- **Leverage**: Debt-to-equity, interest coverage ratio\n- **Efficiency**: Asset turnover, inventory turnover\n\n### 3. Valuation Models\nBuild appropriate valuation models:\n- **DCF Analysis**: Project free cash flows, determine WACC, calculate terminal value\n- **Comparable Company Analysis**: Identify peers, analyze multiples (P/E, EV/EBITDA)\n- **Precedent Transactions**: Review similar deals for valuation benchmarks\n\n### 4. Sensitivity Analysis\n- Perform scenario analysis (base case, bull case, bear case)\n- Test key assumptions (growth rates, discount rates, margins)\n- Identify critical value drivers\n\n## Guidelines\n\n- Always use conservative assumptions when uncertain\n- Cross-validate findings with multiple valuation methods\n- Clearly document all assumptions and their rationale\n- Present results with appropriate caveats and risk factors\n- Consider both quantitative metrics and qualitative factors\n\n## Key Outputs\n\nYour analysis should produce:\n1. Executive summary of findings\n2. Detailed financial model with assumptions\n3. Valuation range with sensitivity analysis\n4. Investment recommendation with risk assessment\n5. Supporting charts and visualizations\n\n## Example Use Cases\n\n- **Public Company Valuation**: \"Analyze Tesla's financials and provide a DCF valuation\"\n- **Private Investment**: \"Evaluate this startup's unit economics and runway\"\n- **M&A Analysis**: \"Assess the financial implications of this acquisition\"\n","frontmatter":{"name":"financial-analysis","description":"Perform comprehensive financial analysis including DCF modeling, ratio analysis, and financial statement evaluation for companies and investment opportunities"},"isInternal":false,"tokens":437,"sizeBytes":2224},{"name":"README.md","path":"examples/mcp/agents/README.md","rawUrl":"https://raw.githubusercontent.com/kyegomez/swarms/HEAD/examples/mcp/agents/README.md","title":"Subagent: readme","category":"subagent-persona","format":"markdown","content":"# Agents + MCP\n\nGiving an agent tools from an MCP server. Set `mcp_url` (one server) or `mcp_urls`\n(several) and the agent discovers and calls the tools on its own.\n\n## Start here — numbered, in order\n\nEach runs against a real public server. The first four need **no MCP API key**.\n\n| # | File | Server | Auth |\n|---|---|---|---|\n| 01 | [`01_deepwiki_repo_qa.py`](01_deepwiki_repo_qa.py) | DeepWiki — Q&A over any public GitHub repo | none |\n| 02 | [`02_gitmcp_repo_docs.py`](02_gitmcp_repo_docs.py) | GitMCP — docs/code search for one repo | none |\n| 03 | [`03_microsoft_learn_docs.py`](03_microsoft_learn_docs.py) | Microsoft Learn — official Azure/.NET docs | none |\n| 04 | [`04_multi_server_agent.py`](04_multi_server_agent.py) | Two servers on one agent | none |\n| 05 | [`05_exa_web_search.py`](05_exa_web_search.py) | Exa — web search | free API key |\n| 07 | [`07_huggingface_model_search.py`](07_huggingface_model_search.py) | Hugging Face — find models & datasets | none (optional token) |\n| 10 | [`10_firecrawl_web_scraping.py`](10_firecrawl_web_scraping.py) | Firecrawl — scrape pages to markdown | API key (in URL path) |\n| 12 | [`12_semgrep_security_scan.py`](12_semgrep_security_scan.py) | Semgrep — static-analysis security scan | free token |\n| 13 | [`13_mcp_sequential_workflow.py`](13_mcp_sequential_workflow.py) | **Multi-agent**: MCP tools in a `SequentialWorkflow` | none |\n\nBetween them these cover all three ways a server takes a key — query parameter\n(05), Bearer token (12), and URL path segment (10) — plus the optional-auth\ncase (07), where a missing key degrades to anonymous access instead of\nfailing.\n\nSee [`FREE_MCP_SERVERS.md`](FREE_MCP_SERVERS.md) for the full catalog of public servers.\n\n## Configuration patterns\n\n| File | Shows |\n|---|---|\n| [`deepwiki_minimal.py`](deepwiki_minimal.py) | The smallest possible `mcp_url` agent |\n| [`mcp_connection_object.py`](mcp_connection_object.py) | `MCPConnection` instead of a bare URL — headers, auth, timeout |\n| [`multi_mcp_urls.py`](multi_mcp_urls.py) | `mcp_urls=[...]` for several servers at once |\n| [`multi_mcp_walkthrough.py`](multi_mcp_walkthrough.py) | Longer multi-server walkthrough with commentary |\n| [`mcp_with_local_tools.py`](mcp_with_local_tools.py) | MCP tools *plus* your own tool schemas on one agent |\n| [`tools_list_dictionary.py`](tools_list_dictionary.py) | The raw `tools_list_dictionary` schema format MCP tools are converted into |\n| [`finance_agent_mcp.py`](finance_agent_mcp.py) | A realistic finance agent backed by an MCP server |\n\n## Run one\n\n```bash\nexport OPENAI_API_KEY=\"sk-...\"\npython examples/mcp/agents/01_deepwiki_repo_qa.py\n```\n\nExamples pointing at `http://localhost:8000/mcp` need a local server — start one from\n[`../servers/`](../servers/) first.\n","isInternal":false,"tokens":747,"sizeBytes":2792},{"name":"README.md","path":"examples/single_agent/capabilities/tools/README.md","rawUrl":"https://raw.githubusercontent.com/kyegomez/swarms/HEAD/examples/single_agent/capabilities/tools/README.md","title":"tools Documentation","category":"plugin-manifest","format":"markdown","content":"# Tools Integration Examples\n\nThis directory contains examples demonstrating tool integration for single agents.\n\n## Examples\n\n- [exa_search_agent.py](exa_search_agent.py) - Exa search integration\n- [example_async_vs_multithread.py](example_async_vs_multithread.py) - Async vs multithreading comparison\n- [litellm_tool_example.py](litellm_tool_example.py) - LiteLLM tool integration\n- [multi_tool_usage_agent.py](multi_tool_usage_agent.py) - Multi-tool agent\n- [new_tools_examples.py](new_tools_examples.py) - Latest tool examples\n- [omni_modal_agent.py](omni_modal_agent.py) - Omni-modal agent\n- [swarms_of_browser_agents.py](swarms_of_browser_agents.py) - Browser automation swarms\n- [swarms_tools_example.py](swarms_tools_example.py) - Swarms tools integration\n- [together_deepseek_agent.py](together_deepseek_agent.py) - Together AI DeepSeek integration\n\n## Subdirectories\n\n### Solana Tools\n- [solana_tool/](solana_tool/) - Solana blockchain integration\n  - [solana_tool.py](solana_tool/solana_tool.py) - Solana tool implementation\n  - [solana_tool_test.py](solana_tool/solana_tool_test.py) - Solana tool testing\n\n### Structured Outputs\n- [structured_outputs/](structured_outputs/) - Structured output examples\n  - [example_meaning_of_life_agents.py](structured_outputs/example_meaning_of_life_agents.py) - Meaning of life example\n  - [structured_outputs_example.py](structured_outputs/structured_outputs_example.py) - Structured output examples\n\n### Tools Examples\n- [tools_examples/](tools_examples/) - Additional tool usage examples\n  - [dex_screener.py](tools_examples/dex_screener.py) - DEX screener tool\n  - [financial_news_agent.py](tools_examples/financial_news_agent.py) - Financial news agent\n  - [simple_tool_example.py](tools_examples/simple_tool_example.py) - Simple tool usage\n  - [swarms_tool_example_simple.py](tools_examples/swarms_tool_example_simple.py) - Simple Swarms tool\n\n## Overview\n\nTools integration examples demonstrate how to equip agents with various tools including search engines, browser automation, blockchain interactions, and structured output generation. These examples show best practices for tool definition, usage, and error handling.\n\n","isInternal":false,"tokens":505,"sizeBytes":2179},{"name":"README.md","path":"examples/tools/base_tool_examples/README.md","rawUrl":"https://raw.githubusercontent.com/kyegomez/swarms/HEAD/examples/tools/base_tool_examples/README.md","title":"base_tool_examples Documentation","category":"plugin-manifest","format":"markdown","content":"# Base Tool Examples\n\nThis directory contains examples demonstrating base tool functionality and tool creation patterns.\n\n## Examples\n\n- [base_tool_examples.py](base_tool_examples.py) - Core base tool functionality\n- [conver_funcs_to_schema.py](conver_funcs_to_schema.py) - Function to schema conversion\n- [convert_basemodels.py](convert_basemodels.py) - BaseModel conversion utilities\n- [exa_search_test.py](exa_search_test.py) - Exa search testing\n- [example_usage.py](example_usage.py) - Basic usage examples\n- [schema_validation_example.py](schema_validation_example.py) - Schema validation\n- [test_anthropic_specific.py](test_anthropic_specific.py) - Anthropic-specific testing\n- [test_base_tool_comprehensive_fixed.py](test_base_tool_comprehensive_fixed.py) - Comprehensive testing (fixed)\n- [test_base_tool_comprehensive.py](test_base_tool_comprehensive.py) - Comprehensive testing\n- [test_function_calls_anthropic.py](test_function_calls_anthropic.py) - Anthropic function calls\n- [test_function_calls.py](test_function_calls.py) - Function call testing\n\n## Overview\n\nBase tool examples demonstrate the fundamental patterns for creating and using tools in Swarms. These examples cover tool schema definition, function-to-schema conversion, validation, and provider-specific implementations. Essential for understanding how to build custom tools for agents.\n\n","isInternal":false,"tokens":289,"sizeBytes":1366},{"name":"README.md","path":"examples/tools/multi_tool_use/README.md","rawUrl":"https://raw.githubusercontent.com/kyegomez/swarms/HEAD/examples/tools/multi_tool_use/README.md","title":"multi_tool_use Documentation","category":"plugin-manifest","format":"markdown","content":"# Multi-Tool Usage Examples\n\nThis directory contains examples demonstrating multi-tool usage patterns for agents.\n\n## Examples\n\n- [many_tool_use_demo.py](many_tool_use_demo.py) - Multiple tool usage demonstration\n- [multi_tool_anthropic.py](multi_tool_anthropic.py) - Multi-tool with Anthropic\n\n## Overview\n\nMulti-tool usage examples demonstrate how agents can use multiple tools in sequence or parallel to accomplish complex tasks. These examples show tool orchestration, tool chaining, and handling multiple tool calls efficiently.\n\n","isInternal":false,"tokens":105,"sizeBytes":535},{"name":"README.md","path":"examples/tools/README.md","rawUrl":"https://raw.githubusercontent.com/kyegomez/swarms/HEAD/examples/tools/README.md","title":"tools Documentation","category":"plugin-manifest","format":"markdown","content":"# Tools Examples\n\nThis directory contains examples demonstrating various tool integrations and usage patterns in Swarms.\n\n## Agent as Tools\n- [agent_as_tools.py](agent_as_tools.py) - Using agents as tools in workflows\n\n## Base Tool Examples\n- [base_tool_examples.py](base_tool_examples/base_tool_examples.py) - Core base tool functionality\n- [conver_funcs_to_schema.py](base_tool_examples/conver_funcs_to_schema.py) - Function to schema conversion\n- [convert_basemodels.py](base_tool_examples/convert_basemodels.py) - BaseModel conversion utilities\n- [exa_search_test.py](base_tool_examples/exa_search_test.py) - Exa search testing\n- [example_usage.py](base_tool_examples/example_usage.py) - Basic usage examples\n- [schema_validation_example.py](base_tool_examples/schema_validation_example.py) - Schema validation\n- [test_anthropic_specific.py](base_tool_examples/test_anthropic_specific.py) - Anthropic-specific testing\n- [test_base_tool_comprehensive_fixed.py](base_tool_examples/test_base_tool_comprehensive_fixed.py) - Comprehensive testing (fixed)\n- [test_base_tool_comprehensive.py](base_tool_examples/test_base_tool_comprehensive.py) - Comprehensive testing\n- [test_function_calls_anthropic.py](base_tool_examples/test_function_calls_anthropic.py) - Anthropic function calls\n- [test_function_calls.py](base_tool_examples/test_function_calls.py) - Function call testing\n\n## Browser Integration\n- [browser_use_as_tool.py](browser_use_as_tool.py) - Browser automation as a tool\n- [browser_use_demo.py](browser_use_demo.py) - Browser automation demonstration\n\n## Claude Integration\n- [claude_as_a_tool.py](claude_as_a_tool.py) - Using Claude as a tool\n\n## Exa Search\n- [exa_search_agent.py](exa_search_agent.py) - Exa search agent implementation\n\n## Firecrawl Integration\n- [firecrawl_agents_example.py](firecrawl_agents_example.py) - Firecrawl web scraping agents\n\n## Multi-Tool Usage\n- [many_tool_use_demo.py](multii_tool_use/many_tool_use_demo.py) - Multiple tool usage demonstration\n- [multi_tool_anthropic.py](multii_tool_use/multi_tool_anthropic.py) - Multi-tool with Anthropic\n\n## Stagehand Integration\n- [1_stagehand_wrapper_agent.py](stagehand/1_stagehand_wrapper_agent.py) - Stagehand wrapper agent\n- [2_stagehand_tools_agent.py](stagehand/2_stagehand_tools_agent.py) - Stagehand tools agent\n- [3_stagehand_mcp_agent.py](stagehand/3_stagehand_mcp_agent.py) - Stagehand MCP agent\n- [4_stagehand_multi_agent_workflow.py](stagehand/4_stagehand_multi_agent_workflow.py) - Multi-agent workflow\n- [README.md](stagehand/README.md) - Stagehand documentation\n- [requirements.txt](stagehand/requirements.txt) - Stagehand dependencies\n- [tests/](stagehand/tests/) - Stagehand testing suite\n","isInternal":false,"tokens":638,"sizeBytes":2693},{"name":"README.md","path":"examples/tools/stagehand/README.md","rawUrl":"https://raw.githubusercontent.com/kyegomez/swarms/HEAD/examples/tools/stagehand/README.md","title":"stagehand Documentation","category":"plugin-manifest","format":"markdown","content":"# Stagehand Browser Automation Integration for Swarms\n\nThis directory contains examples demonstrating how to integrate [Stagehand](https://github.com/browserbase/stagehand), an AI-powered browser automation framework, with the Swarms multi-agent framework.\n\n## Overview\n\nStagehand provides natural language browser automation capabilities that can be seamlessly integrated into Swarms agents. This integration enables:\n\n- 🌐 **Natural Language Web Automation**: Use simple commands like \"click the submit button\" or \"extract product prices\"\n- 🤖 **Multi-Agent Browser Workflows**: Multiple agents can automate different websites simultaneously\n- 🔧 **Flexible Integration Options**: Use as a wrapped agent, individual tools, or via MCP server\n- 📊 **Complex Automation Scenarios**: E-commerce monitoring, competitive analysis, automated testing, and more\n\n## Examples\n\n### 1. Stagehand Wrapper Agent (`1_stagehand_wrapper_agent.py`)\n\nThe simplest integration - wraps Stagehand as a Swarms-compatible agent.\n\n```python\nfrom examples.stagehand.stagehand_wrapper_agent import StagehandAgent\n\n# Create a browser automation agent\nbrowser_agent = StagehandAgent(\n    agent_name=\"WebScraperAgent\",\n    model_name=\"gpt-5.4\",\n    env=\"LOCAL\",  # or \"BROWSERBASE\" for cloud execution\n)\n\n# Use natural language to control the browser\nresult = browser_agent.run(\n    \"Navigate to news.ycombinator.com and extract the top 5 story titles\"\n)\n```\n\n**Features:**\n- Inherits from Swarms `Agent` base class\n- Automatic browser lifecycle management\n- Natural language task interpretation\n- Support for both local (Playwright) and cloud (Browserbase) execution\n\n### 2. Stagehand as Tools (`2_stagehand_tools_agent.py`)\n\nProvides fine-grained control by exposing Stagehand methods as individual tools.\n\n```python\nfrom swarms import Agent\nfrom examples.stagehand.stagehand_tools_agent import (\n    NavigateTool, ActTool, ExtractTool, ObserveTool, ScreenshotTool\n)\n\n# Create agent with browser tools\nbrowser_agent = Agent(\n    agent_name=\"BrowserAutomationAgent\",\n    model_name=\"gpt-5.4\",\n    tools=[\n        NavigateTool(),\n        ActTool(),\n        ExtractTool(),\n        ObserveTool(),\n        ScreenshotTool(),\n    ],\n)\n\n# Agent can now use tools strategically\nresult = browser_agent.run(\n    \"Go to google.com, search for 'Python tutorials', and extract the first 3 results\"\n)\n```\n\n**Available Tools:**\n- `NavigateTool`: Navigate to URLs\n- `ActTool`: Perform actions (click, type, scroll)\n- `ExtractTool`: Extract data from pages\n- `ObserveTool`: Find elements on pages\n- `ScreenshotTool`: Capture screenshots\n- `CloseBrowserTool`: Clean up browser resources\n\n### 3. Stagehand MCP Server (`3_stagehand_mcp_agent.py`)\n\nIntegrates with Stagehand's Model Context Protocol (MCP) server for standardized tool access.\n\n```python\nfrom examples.stagehand.stagehand_mcp_agent import StagehandMCPAgent\n\n# Connect to Stagehand MCP server\nmcp_agent = StagehandMCPAgent(\n    agent_name=\"WebResearchAgent\",\n    mcp_server_url=\"http://localhost:3000/mcp\",\n)\n\n# Use MCP tools including multi-session management\nresult = mcp_agent.run(\"\"\"\n    Create 3 browser sessions and:\n    1. Session 1: Check Python.org for latest version\n    2. Session 2: Check PyPI for trending packages  \n    3. Session 3: Check GitHub Python trending repos\n    Compile a Python ecosystem status report.\n\"\"\")\n```\n\n**MCP Features:**\n- Automatic tool discovery\n- Multi-session browser management\n- Built-in screenshot resources\n- Prompt templates for common tasks\n\n### 4. Multi-Agent Workflows (`4_stagehand_multi_agent_workflow.py`)\n\nDemonstrates complex multi-agent browser automation scenarios.\n\n```python\nfrom examples.stagehand.stagehand_multi_agent_workflow import (\n    create_price_comparison_workflow,\n    create_competitive_analysis_workflow,\n    create_automated_testing_workflow,\n    create_news_aggregation_workflow\n)\n\n# Price comparison across multiple e-commerce sites\nprice_workflow = create_price_comparison_workflow()\nresult = price_workflow.run(\n    \"Compare prices for iPhone 15 Pro on Amazon and eBay\"\n)\n\n# Competitive analysis of multiple companies\ncompetitive_workflow = create_competitive_analysis_workflow()\nresult = competitive_workflow.run(\n    \"Analyze OpenAI, Anthropic, and DeepMind websites and social media\"\n)\n```\n\n**Workflow Examples:**\n- **E-commerce Monitoring**: Track prices across multiple sites\n- **Competitive Analysis**: Research competitors' websites and social media\n- **Automated Testing**: UI, form validation, and accessibility testing\n- **News Aggregation**: Collect and analyze news from multiple sources\n\n## Setup\n\n### Prerequisites\n\n1. **Install Swarms and Stagehand:**\n```bash\npip install swarms stagehand\n```\n\n2. **Set up environment variables:**\n```bash\n# For local browser automation (using Playwright)\nexport OPENAI_API_KEY=\"your-openai-key\"\n\n# For cloud browser automation (using Browserbase)\nexport BROWSERBASE_API_KEY=\"your-browserbase-key\"\nexport BROWSERBASE_PROJECT_ID=\"your-project-id\"\n```\n\n3. **For MCP Server examples:**\n```bash\n# Install and run the Stagehand MCP server\ncd stagehand-mcp-server\nnpm install\nnpm run build\nnpm start\n```\n\n## Use Cases\n\n### E-commerce Automation\n- Price monitoring and comparison\n- Inventory tracking\n- Automated purchasing workflows\n- Review aggregation\n\n### Research and Analysis\n- Competitive intelligence gathering\n- Market research automation\n- Social media monitoring\n- News and trend analysis\n\n### Quality Assurance\n- Automated UI testing\n- Cross-browser compatibility testing\n- Form validation testing\n- Accessibility compliance checking\n\n### Data Collection\n- Web scraping at scale\n- Real-time data monitoring\n- Structured data extraction\n- Screenshot documentation\n\n## Best Practices\n\n1. **Resource Management**: Always clean up browser instances when done\n```python\nbrowser_agent.cleanup()  # For wrapper agents\n```\n\n2. **Error Handling**: Stagehand includes self-healing capabilities, but wrap critical operations in try-except blocks\n\n3. **Parallel Execution**: Use `ConcurrentWorkflow` for simultaneous browser automation across multiple sites\n\n4. **Session Management**: For complex multi-page workflows, use the MCP server's session management capabilities\n\n5. **Rate Limiting**: Be respectful of websites - add delays between requests when necessary\n\n## Testing\n\nRun the test suite to verify the integration:\n\n```bash\npytest tests/stagehand/test_stagehand_integration.py -v\n```\n\n## Troubleshooting\n\n### Common Issues\n\n1. **Browser not starting**: Ensure Playwright is properly installed\n```bash\nplaywright install\n```\n\n2. **MCP connection failed**: Verify the MCP server is running on the correct port\n\n3. **Timeout errors**: Increase timeout in StagehandConfig or agent initialization\n\n### Debug Mode\n\nEnable verbose logging:\n```python\nagent = StagehandAgent(\n    agent_name=\"DebugAgent\",\n    verbose=True,  # Enable detailed logging\n)\n```\n\n## Contributing\n\nWe welcome contributions! Please:\n1. Follow the existing code style\n2. Add tests for new features\n3. Update documentation\n4. Submit PRs with clear descriptions\n\n## License\n\nThese examples are provided under the same license as the Swarms framework. Stagehand is licensed separately - see [Stagehand's repository](https://github.com/browserbase/stagehand) for details.","isInternal":false,"tokens":1580,"sizeBytes":7285}],"systemPromptSnippet":"<agent_rules repository=\"kyegomez/swarms\">\n\n<!-- Skill/Rule: Claude Agent Guidelines & System Prompt (CLAUDE.md) -->\n# CLAUDE.md — Swarms Framework Guide\n\nThis file teaches you how to build agents and multi-agent systems with the **Swarms** framework. Read it before writing any code in this repo.\n\n---\n\n## Installation & Setup\n\n```bash\npip install swarms\n```\n\nSet your LLM API key as an environment variable before running:\n\n```bash\nexport OPENAI_API_KEY=\"sk-...\"        # OpenAI / GPT models\nexport ANTHROPIC_API_KEY=\"sk-ant-...\" # Claude models\nexport GROQ_API_KEY=\"...\"             # Groq\n# Any provider supported by LiteLLM works\n```\n\nAll imports come from the top-level `swarms` package:\n\n```python\nfrom swarms import (\n    Agent,\n    SequentialWorkflow,\n    ConcurrentWorkflow,\n    AgentRearrange,\n    GraphWorkflow,\n    SwarmRouter,\n    MixtureOfAgents,\n    HierarchicalSwarm,\n    GroupChat,\n    MajorityVoting,\n    # ...\n)\n```\n\n---\n\n## Project Layout\n\n```\nswarms/\n├── swarms/\n│   ├── structs/         # All agent + multi-agent structures (61 files)\n│   │   ├── agent.py             # Core Agent class\n│   │   ├── conversation.py      # Conversation / memory management\n│   │   ├── sequential_workflow.py\n│   │   ├── concurrent_workflow.py\n│   │   ├── agent_rearrange.py\n│   │   ├── graph_workflow.py\n│   │   ├── swarm_router.py      # Single-entry-point router\n│   │   ├── mixture_of_agents.py\n│   │   ├── hiearchical_swarm.py\n│   │   ├── groupchat.py\n│   │   ├── majority_voting.py\n│   │   ├── council_as_judge.py\n│   │   ├── debate_with_judge.py\n│   │   ├── heavy_swarm.py\n│   │   ├── round_robin.py\n│   │   ├── planner_worker_swarm.py\n│   │   ├── auto_swarm_builder.py\n│   │   └── multi_agent_exec.py  # run_agents_concurrently + friends\n│   ├── tools/           # Tool utilities, MCP, schema conversion\n│   └── utils/           # Logging, formatting helpers\n├── examples/            # 586 runnable examples\n│   ├── single_agent/\n│   ├── multi_agent/\n│   ├── tools/\n│   └── guides/\n└── v12_examples/        # New v12 feature examples\n```\n\nLook in `examples/` first before writing new code — there is almost certainly an existing example close to what you need.\n\n---\n\n## Core Primitive: Agent\n\n`Agent` is the single building block everything else composes. All multi-agent structures wrap one or more `Agent` instances.\n\n### Minimal agent\n\n```python\nfrom swarms import Agent\n\nagent = Agent(\n    agent_name=\"Analyst\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n)\n\nresult = agent.run(\"Summarise the current state of LLM research.\")\nprint(result)\n```\n\n### Key constructor parameters\n\n| Parameter | Type | Default | Purpose |\n|---|---|---|---|\n| `agent_name` | str | `\"swarm-worker-01\"` | Unique name — used for memory file paths |\n| `agent_description` | str | generic | Shown to orchestrators for routing |\n| `system_prompt` | str | built-in | The agent's persona / instructions |\n| `model_name` | str | `\"gpt-5.4\"` | Any LiteLLM model string |\n| `max_loops` | int \\| `\"auto\"` | `1` | Loops before returning; `\"auto\"` = autonomous until done |\n| `tools` | list[Callable] | `None` | Python functions the agent can call |\n| `streaming_on` | bool | `False` | Stream tokens to stdout |\n| `interactive` | bool | `False` | REPL mode — prompt user for input each loop |\n| `context_length` | int | `None` | Token budget; triggers compression at 90 % |\n| `context_compression` | bool | `True` | Auto-summarise when near context limit (v12) |\n| `persistent_memory` | bool | `False` | Read/write MEMORY.md across restarts (v12); opt in explicitly |\n| `temperature` | float | `0.5` | Sampling temperature |\n| `max_tokens` | int | model's max output | Max tokens per LLM call. Unset resolves to the model's own output limit |\n| `reasoning_effort` | str | `None` | `\"low\"`, `\"medium\"`, `\"high\"` for reasoning models |\n| `thinking_tokens` | int | `None` | Extended thinking budget (Claude) |\n| `output_type` | str | `\"str-all-except-first\"` | How to format returned output |\n| `mcp_url` | str | `None` | MCP server URL to load tools from |\n| `handoffs` | list | `None` | Agents this agent can hand off to |\n| `plan_enabled` | bool | `False` | Generate a plan before execution |\n| `autosave` | bool | `False` | Save agent state to disk after each run |\n\n### Autonomous loop (`max_loops=\"auto\"`)\n\nWhen `max_loops=\"auto\"` the agent runs a plan→execute→reflect loop until it decides it is done. It automatically gets access to:\n- A `think` tool (disabled when `thinking_tokens` is set)\n- A `grep` tool for searching files (v12)\n- Bash / file tools if configured\n\n```python\nagent = Agent(\n    agent_name=\"Researcher\",\n    model_name=\"gpt-5.4\",\n    max_loops=\"auto\",\n    interactive=False,\n)\nresult = agent.run(\"Research the top 5 vector databases and compare them.\")\n```\n\n### Model names\n\nUse any LiteLLM-compatible string:\n\n```python\n# OpenAI\nmodel_name=\"gpt-5.4\"\nmodel_name=\"gpt-5.4-mini\"\nmodel_name=\"o3\"\n\n# Anthropic\nmodel_name=\"claude-opus-4-7-20251001\"\nmodel_name=\"claude-sonnet-4-6\"\nmodel_name=\"claude-haiku-4-5-20251001\"\n\n# Groq\nmodel_name=\"groq/llama-3.3-70b-versatile\"\n\n# Google\nmodel_name=\"gemini/gemini-2.5-pro\"\n```\n\n### Running with images\n\n```python\nresult = agent.run(\n    task=\"Describe what you see in this chart.\",\n    img=\"path/to/chart.png\",   # or base64 string or URL\n)\n```\n\n---\n\n## Memory & Persistence (v12)\n\n### `persistent_memory=True` (opt in)\n\nOn startup the agent reads `{workspace}/agents/{agent_name}/MEMORY.md` and injects it as a system preamble. On each response it appends to that file. State survives process restarts automatically.\n\n```python\nagent = Agent(\n    agent_name=\"ProjectAssistant\",\n    model_name=\"gpt-5.4\",\n    persistent_memory=True,   # off by default; opt in\n)\n# First run: agent has no prior context\nagent.run(\"My project is called Helios. Remember that.\")\n\n# New process, same agent_name → agent remembers \"Helios\".\n# persistent_memory must be set here too; it is False by default.\nagent2 = Agent(\n    agent_name=\"ProjectAssistant\",\n    model_name=\"gpt-5.4\",\n    persistent_memory=True,\n)\nagent2.run(\"What is my project called?\")\n```\n\n### `persistent_memory=False` (default)\n\nFully stateless — no disk reads or writes. Use for short, isolated tasks where carry-over would be harmful.\n\n```python\nagent = Agent(\n    agent_name=\"OneShot\",\n    model_name=\"gpt-5.4\",\n    persistent_memory=False,\n)\n```\n\n### `context_compression=True` (default)\n\n`ContextCompressor` fires automatically when token usage crosses 90 % of `context_length`. It summarises and rewrites `MEMORY.md` in place so long sessions never hit the context wall.\n\n```python\nagent = Agent(\n    agent_name=\"LongSession\",\n    model_name=\"gpt-5.4\",\n    context_length=32000,\n    context_compression=True,   # default\n)\n```\n\n### Conversation.compact()\n\nManually collapse history to a single summary; creates a timestamped archive before rewriting:\n\n```python\nfrom swarms.structs.conversation import Conversation\n\nconv = Conversation(agent_name=\"MyAgent\", system_prompt=\"You are helpful.\")\nconv.add(\"user\", \"Tell me about X\")\nconv.add(\"assistant\", \"X is ...\")\n\n# Collapse history, archive the full log\nconv.compact(summary=\"User asked about X. Assistant explained X.\")\n```\n\n---\n\n## Tools\n\n### Python functions as tools\n\nDecorate any Python function with a docstring — the framework converts it to an OpenAI function-calling schema automatically:\n\n```python\nimport yfinance as yf\nfrom swarms import Agent\n\ndef get_stock_price(ticker: str) -> str:\n    \"\"\"Fetch the current stock price for a given ticker symbol.\n\n    Args:\n        ticker: Stock ticker symbol, e.g. 'AAPL'.\n\n    Returns:\n        Current price as a formatted string.\n    \"\"\"\n    data = yf.Ticker(ticker)\n    price = data.fast_info[\"last_price\"]\n    return f\"{ticker}: ${price:.2f}\"\n\nagent = Agent(\n    agent_name=\"StockAnalyst\",\n    model_name=\"gpt-5.4\",\n    tools=[get_stock_price],\n    max_loops=3,\n)\nresult = agent.run(\"What is the current price of Apple and Microsoft?\")\n```\n\n### Multiple tools\n\n```python\nagent = Agent(\n    agent_name=\"ResearchAgent\",\n    model_name=\"gpt-5.4\",\n    tools=[search_web, get_stock_price, read_file, write_file],\n    max_loops=\"auto\",\n)\n```\n\n### Tool schema from Pydantic\n\n```python\nfrom swarms.tools.pydantic_to_json import base_model_to_openai_function\nfrom pydantic import BaseModel\n\nclass WeatherQuery(BaseModel):\n    city: str\n    units: str = \"celsius\"\n\nschema = base_model_to_openai_function(WeatherQuery)\n```\n\n---\n\n## Streaming\n\n### Stream to stdout\n\n```python\nagent = Agent(\n    agent_name=\"Writer\",\n    model_name=\"gpt-5.4\",\n    streaming_on=True,\n)\nagent.run(\"Write a short poem about distributed systems.\")\n```\n\n### Stream tokens to a callback\n\n```python\ndef handle_token(token: str) -> None:\n    print(token, end=\"\", flush=True)\n\nagent = Agent(\n    agent_name=\"Writer\",\n    model_name=\"gpt-5.4\",\n    streaming_callback=handle_token,\n)\nagent.run(\"Write a haiku.\")\n```\n\n### Async streaming (`arun_stream`)\n\n```python\nimport asyncio\nfrom swarms import Agent\n\nagent = Agent(agent_name=\"AsyncWriter\", model_name=\"gpt-5.4\", streaming_on=True)\n\nasync def main():\n    async for token in agent.arun_stream(\"Explain async/await in Python.\"):\n        print(token, end=\"\", flush=True)\n\nasyncio.run(main())\n```\n\n---\n\n## Multi-Agent Structures\n\n### Sequential Workflow\n\nAgents execute **one after another**. The output of each agent is passed as context to the next.\n\n```python\nfrom swarms import Agent, SequentialWorkflow\n\nresearcher = Agent(agent_name=\"Researcher\", model_name=\"gpt-5.4\", max_loops=1)\nanalyst   = Agent(agent_name=\"Analyst\",    model_name=\"gpt-5.4\", max_loops=1)\nwriter    = Agent(agent_name=\"Writer\",     model_name=\"gpt-5.4\", max_loops=1)\n\npipeline = SequentialWorkflow(\n    agents=[researcher, analyst, writer],\n    max_loops=1,\n)\nresult = pipeline.run(\"Analyse the impact of interest rate hikes on tech stocks.\")\n```\n\n**When to use:** Linear pipelines where each step depends on the prior step's output. Research → Analysis → Report. Extraction → Transformation → Load.\n\n---\n\n### Concurrent Workflow\n\nAll agents run **in parallel** on the same task. Results are collected and returned together.\n\n```python\nfrom swarms import Agent, ConcurrentWorkflow\n\nagents = [\n    Agent(agent_name=f\"Worker-{i}\", model_name=\"gpt-5.4\", max_loops=1)\n    for i in range(5)\n]\n\nworkflow = ConcurrentWorkflow(agents=agents)\nresults = workflow.run(\"List 10 use cases for multi-agent AI systems.\")\n```\n\n**When to use:** Independent subtasks that can run simultaneously. Analysing multiple documents. Querying multiple data sources. Generating multiple creative variants.\n\n---\n\n### AgentRearrange — Flow DSL\n\nDefine execution flow as a string using a simple DSL. Mix sequential (`->`) and parallel (`,`) execution.\n\n```python\nfrom swarms import Agent, AgentRearrange\n\nplanner  = Agent(agent_name=\"Planner\",  model_name=\"gpt-5.4\", max_loops=1)\ncoder    = Agent(agent_name=\"Coder\",    model_name=\"gpt-5.4\", max_loops=1)\nreviewer = Agent(agent_name=\"Reviewer\", model_name=\"gpt-5.4\", max_loops=1)\ntester   = Agent(agent_name=\"Tester\",   model_name=\"gpt-5.4\", max_loops=1)\n\npipeline = AgentRearrange(\n    agents=[planner, coder, reviewer, tester],\n    flow=\"Planner -> Coder -> Reviewer, Tester\",\n    #        sequential  ↑      parallel  ↑\n    max_loops=1,\n)\nresult = pipeline.run(\"Build a Python function that validates email addresses.\")\n```\n\n**Flow DSL rules:**\n- `A -> B` — A runs, then B receives A's output\n- `A, B` — A and B run concurrently with the same input\n- `A -> B, C -> D` — A runs first, then B and C run concurrently, then D receives their combined output\n\n`AgentRearrange` has no built-in human-in-the-loop step — every name in `flow` must correspond to an agent in `agents`, or the flow will fail at run time. For a human checkpoint, break the pipeline into separate `AgentRearrange`/`Agent.run()` calls and insert your own logic (e.g. `input()`) between them — see the \"Human-in-the-loop with AgentRearrange\" pattern below.\n\n**When to use:** Any workflow where you need explicit, readable control over agent execution order and parallelism.\n\n---\n\n### GraphWorkflow — DAG Execution\n\nFull directed-acyclic-graph (DAG) execution. Nodes are agents; edges are dependencies. Topological sort ensures correct order. Supports per-node callbacks and token streaming.\n\n```python\nfrom swarms import Agent, GraphWorkflow, Node, Edge, NodeType\n\n# Build agents\nanalyst  = Agent(agent_name=\"Analyst\",  model_name=\"gpt-5.4-mini\", max_loops=1)\nwriter   = Agent(agent_name=\"Writer\",   model_name=\"gpt-5.4-mini\", max_loops=1)\nreviewer = Agent(agent_name=\"Reviewer\", model_name=\"gpt-5.4-mini\", max_loops=1)\npublisher = Agent(agent_name=\"Publisher\", model_name=\"gpt-5.4-mini\", max_loops=1)\n\n# Build graph\nwf = GraphWorkflow()\nwf.add_node(Node(id=\"analyst\",   type=NodeType.AGENT, agent=analyst))\nwf.add_node(Node(id=\"writer\",    type=NodeType.AGENT, agent=writer))\nwf.add_node(Node(id=\"reviewer\",  type=NodeType.AGENT, agent=reviewer))\nwf.add_node(Node(id=\"publisher\", type=NodeType.AGENT, agent=publisher))\n\nwf.add_edge(Edge(source=\"analyst\",  target=\"writer\"))\nwf.add_edge(Edge(source=\"writer\",   target=\"reviewer\"))\nwf.add_edge(Edge(source=\"reviewer\", target=\"publisher\"))\n\nwf.set_entry_points([\"analyst\"])\nwf.set_end_points([\"publisher\"])\n\n# Run with callbacks\ndef on_done(node_name: str, result: str) -> None:\n    print(f\"[{node_name}] finished — {len(result)} chars\")\n\nresults = wf.run(\n    task=\"Produce a market report on AI chips.\",\n    on_node_complete=on_done,          # fires after each node\n    streaming_callback=lambda tok: print(tok, end=\"\", flush=True),\n)\n```\n\n**Diamond / fan-out fan-in pattern:**\n\n```python\n# analyst feeds both writer AND researcher concurrently,\n# then editor combines both outputs\nwf.add_edge(Edge(source=\"analyst\",    target=\"writer\"))\nwf.add_edge(Edge(source=\"analyst\",    target=\"researcher\"))\nwf.add_edge(Edge(source=\"writer\",     target=\"editor\"))\nwf.add_edge(Edge(source=\"researcher\", target=\"editor\"))\n```\n\n**When to use:** Complex dependency graphs, fan-out/fan-in patterns, when you need precise control over which agents depend on which.\n\n---\n\n### SwarmRouter — Single Entry Point\n\n`SwarmRouter` is the highest-level abstraction. Pass it a list of agents and a `swarm_type` — it handles the rest. Use this when you want to switch architectures without rewriting orchestration code.\n\n```python\nfrom swarms import Agent, SwarmRouter\n\nagents = [\n    Agent(agent_name=\"Analyst\",  model_name=\"gpt-5.4\", max_loops=1),\n    Agent(agent_name=\"Writer\",   model_name=\"gpt-5.4\", max_loops=1),\n    Agent(agent_name=\"Reviewer\", model_name=\"gpt-5.4\", max_loops=1),\n]\n\nrouter = SwarmRouter(\n    agents=agents,\n    swarm_type=\"SequentialWorkflow\",   # swap to any SwarmType below\n    max_loops=1,\n)\nresult = router.run(\"Write a blog post about transformer architectures.\")\n```\n\n**All `swarm_type` options:**\n\n| SwarmType | Behaviour |\n|---|---|\n| `\"SequentialWorkflow\"` | Agents run one after another |\n| `\"ConcurrentWorkflow\"` | Agents run in parallel |\n| `\"AgentRearrange\"` | Flow-DSL based execution |\n| `\"MixtureOfAgents\"` | Workers + aggregator layer |\n| `\"HierarchicalSwarm\"` | Boss delegates to workers |\n| `\"GroupChat\"` | Multi-agent round-table discussion |\n| `\"MultiAgentRouter\"` | Task routed to best-fit agent |\n| `\"MajorityVoting\"` | Agents vote; majority wins |\n| `\"CouncilAsAJudge\"` | Council deliberates; judge decides |\n| `\"DebateWithJudge\"` | Agents debate; judge rules |\n| `\"HeavySwarm\"` | Intensive multi-loop deep analysis |\n| `\"RoundRobin\"` | Round-robin task distribution |\n| `\"PlannerWorkerSwarm\"` | Planner + worker delegation |\n| `\"BatchedGridWorkflow\"` | Grid-based batch execution |\n| `\"LLMCouncil\"` | LLM-based council decisions |\n| `\"AutoSwarmBuilder\"` | Auto-configures everything |\n| `\"auto\"` | Router selects swarm_type automatically |\n\n---\n\n### MixtureOfAgents\n\nMultiple **worker** agents each respond to the task independently, then an **aggregator** agent synthesises all responses into a final answer. Repeat for multiple layers.\n\n```python\nfrom swarms import Agent, MixtureOfAgents\n\nworkers = [\n    Agent(agent_name=\"Worker-GPT\",    model_name=\"gpt-5.4\",       max_loops=1),\n    Agent(agent_name=\"Worker-Claude\", model_name=\"claude-sonnet-4-6\", max_loops=1),\n    Agent(agent_name=\"Worker-Llama\",  model_name=\"groq/llama-3.3-70b-versatile\", max_loops=1),\n]\n\naggregator = Agent(\n    agent_name=\"Aggregator\",\n    model_name=\"gpt-5.4\",\n    system_prompt=\"Synthesise the following expert responses into one coherent answer.\",\n    max_loops=1,\n)\n\nmoa = MixtureOfAgents(\n    agents=workers,\n    aggregator_agent=aggregator,\n    layers=2,        # run worker→aggregate cycle this many times\n    max_loops=1,\n)\nresult = moa.run(\"What are the best practices for securing a Kubernetes cluster?\")\n```\n\n**When to use:** High-stakes tasks where you want multiple independent perspectives merged into a consensus. Works especially well with diverse model providers.\n\n---\n\n### HierarchicalSwarm\n\nA director agent breaks the task into subtasks and delegates them to worker agents. Workers report back; director synthesises.\n\n```python\nfrom swarms import Agent, HierarchicalSwarm\n\ndirector = Agent(\n    agent_name=\"Director\",\n    agent_description=\"Breaks complex tasks into subtasks and delegates them.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n)\n\nworkers = [\n    Agent(agent_name=\"DataWorker\",    model_name=\"gpt-5.4-mini\", max_loops=1),\n    Agent(agent_name=\"WritingWorker\", model_name=\"gpt-5.4-mini\", max_loops=1),\n    Agent(agent_name=\"ReviewWorker\",  model_name=\"gpt-5.4-mini\", max_loops=1),\n]\n\nswarm = HierarchicalSwarm(\n    director=director,\n    agents=workers,\n    max_loops=2,\n)\nresult = swarm.run(\"Produce a comprehensive competitive analysis of the AI chip market.\")\n```\n\n**When to use:** Tasks naturally decomposed into subtasks where a coordinator must manage work allocation and synthesis.\n\n---\n\n### GroupChat\n\nAn asynchronous, self-selecting groupchat. There are no rounds or speaker-selection functions — every agent listens in parallel and decides on its own whether to chime in. A forced `respond(score, message)` function call asks each agent how much it wants to speak (0..1); replies above `threshold` are broadcast. The chat ends when `max_loops` messages have been posted or no message arrives for `idle_timeout` seconds.\n\n```python\nfrom swarms import Agent\nfrom swarms.structs.groupchat import GroupChat, RESPOND_TOOL\n\n# Every agent MUST carry RESPOND_TOOL so the chat can ask it whether to speak.\n# Recommended per-agent: max_loops=1, persistent_memory=False.\noptimist = Agent(\n    agent_name=\"Optimist\",\n    system_prompt=\"You argue for the benefits.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n    persistent_memory=False,\n    tools_list_dictionary=[RESPOND_TOOL],\n)\npessimist = Agent(\n    agent_name=\"Pessimist\",\n    system_prompt=\"You argue for the risks.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n    persistent_memory=False,\n    tools_list_dictionary=[RESPOND_TOOL],\n)\nrealist = Agent(\n    agent_name=\"Realist\",\n    system_prompt=\"You seek balanced analysis.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n    persistent_memory=False,\n    tools_list_dictionary=[RESPOND_TOOL],\n)\n\nchat = GroupChat(\n    agents=[optimist, pessimist, realist],\n    max_loops=10,        # hard cap on total messages posted\n    threshold=0.5,       # min decision score (0..1) to publish a reply\n    idle_timeout=8.0,    # seconds of silence before stopping\n)\nresult = chat.run(\"Should we adopt AI for medical diagnosis?\")\n```\n\n**Tuning:** raise `threshold` for a more selective room; lower it for livelier chats. Raise `idle_timeout` if agents need time to think before replying.\n\n---\n\n### MajorityVoting\n\nAll agents independently answer the task. The answer that appears in the majority of responses wins.\n\n```python\nfrom swarms import Agent, MajorityVoting\n\nvoters = [\n    Agent(agent_name=f\"Voter-{i}\", model_name=\"gpt-5.4-mini\", max_loops=1)\n    for i in range(5)\n]\n\nmv = MajorityVoting(agents=voters, max_loops=1)\nresult = mv.run(\"Is Python or Rust better for building a high-performance web server?\")\n```\n\n**When to use:** Classification, yes/no decisions, or any task with a discrete answer set where you want noise reduction through consensus.\n\n---\n\n### CouncilAsAJudge\n\nA council of agents each deliberate, then a judge agent makes the final ruling based on the council's reasoning.\n\n```python\nfrom swarms import Agent, CouncilAsAJudge\n\ncouncil = [\n    Agent(agent_name=\"Expert-Security\", model_name=\"gpt-5.4\", max_loops=1),\n    Agent(agent_name=\"Expert-Privacy\",  model_name=\"gpt-5.4\", max_loops=1),\n    Agent(agent_name=\"Expert-Legal\",    model_name=\"gpt-5.4\", max_loops=1),\n]\n\njudge = Agent(\n    agent_name=\"Judge\",\n    system_prompt=\"Given the council's analysis, deliver a final verdict.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n)\n\ncouncil_swarm = CouncilAsAJudge(\n    agents=council,\n    judge=judge,\n    max_loops=1,\n)\nresult = council_swarm.run(\"Should we store user biometric data on-device only?\")\n```\n\n---\n\n### DebateWithJudge\n\nTwo or more agents argue opposing positions for multiple rounds. A judge delivers a verdict at the end.\n\n```python\nfrom swarms import Agent, DebateWithJudge\n\npro  = Agent(agent_name=\"Pro\",  system_prompt=\"Argue strongly in favour.\",  model_name=\"gpt-5.4\", max_loops=1)\ncon  = Agent(agent_name=\"Con\",  system_prompt=\"Argue strongly against.\",    model_name=\"gpt-5.4\", max_loops=1)\n\njudge = Agent(\n    agent_name=\"Judge\",\n    system_prompt=\"Evaluate the debate and deliver an objective verdict.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n)\n\ndebate = DebateWithJudge(\n    agents=[pro, con],\n    judge=judge,\n    max_loops=3,   # 3 rounds of argument\n)\nresult = debate.run(\"Motion: Open-source LLMs will surpass closed-source models by 2027.\")\n```\n\n---\n\n### HeavySwarm\n\nIntensive multi-loop analysis. Each agent runs for many loops on the problem, producing deep reasoning. Best for research-grade analysis.\n\n```python\nfrom swarms import HeavySwarm\n\nswarm = HeavySwarm(\n    num_agents=4,\n    model_name=\"gpt-5.4\",\n    loops_per_agent=5,       # each agent reasons for 5 loops\n    show_output=True,\n)\nresult = swarm.run(\"Derive a novel approach to solving the alignment problem in AI.\")\n```\n\nOr via `SwarmRouter`:\n\n```python\nfrom swarms import Agent, SwarmRouter\n\nagents = [Agent(agent_name=f\"Deep-{i}\", model_name=\"gpt-5.4\", max_loops=5) for i in range(4)]\nrouter = SwarmRouter(agents=agents, swarm_type=\"HeavySwarm\")\nresult = router.run(\"Deep analysis: implications of AGI on global labour markets.\")\n```\n\n---\n\n### RoundRobinSwarm\n\nDistributes tasks to agents in a fixed rotation. Each agent handles every Nth task.\n\n```python\nfrom swarms import Agent, RoundRobinSwarm\n\nagents = [\n    Agent(agent_name=f\"Handler-{i}\", model_name=\"gpt-5.4-mini\", max_loops=1)\n    for i in range(3)\n]\n\nrr = RoundRobinSwarm(agents=agents, max_loops=1)\n\ntasks = [\"Task A\", \"Task B\", \"Task C\", \"Task D\", \"Task E\", \"Task F\"]\nfor task in tasks:\n    result = rr.run(task)\n```\n\n---\n\n### PlannerWorkerSwarm\n\nA planner agent generates a structured plan; worker agents execute each step.\n\n```python\nfrom swarms import Agent, PlannerWorkerSwarm\n\nplanner = Agent(\n    agent_name=\"Planner\",\n    system_prompt=\"You create detailed, step-by-step execution plans.\",\n    model_name=\"gpt-5.4\",\n    max_loops=1,\n)\n\nworkers = [\n    Agent(agent_name=f\"Worker-{i}\", model_name=\"gpt-5.4-mini\", max_loops=2)\n    for i in range(4)\n]\n\nswarm = PlannerWorkerSwarm(\n    planner_agent=planner,\n    worker_agents=workers,\n    max_loops=1,\n)\nresult = swarm.run(\"Build a complete go-to-market strategy for a B2B SaaS product.\")\n```\n\n---\n\n### AutoSwarmBuilder\n\nPass a high-level description of the task — the framework automatically creates the agents, assigns roles, and runs the appropriate swarm architecture.\n\n```python\nfrom swarms import AutoSwarmBuilder\n\nbuilder = AutoSwarmBuilder(\n    name=\"MarketResearchSwarm\",\n    description=\"A swarm that produces comprehensive market research reports\",\n    max_loops=2,\n)\nresult = builder.run(\"Research the electric vehicle market and identify growth opportunities.\")\n```\n\n**When to use:** Rapid prototyping, when you don't know yet which structure fits, or when you want the LLM to decide.\n\n---\n\n## Utility Execution Helpers\n\n```python\nfrom swarms.structs.multi_agent_exec import (\n    run_agents_concurrently,\n    run_agents_concurrently_async,\n    run_agents_with_different_tasks,\n    run_single_agent,\n)\n\n# Same task, all agents in parallel\nresults = run_agents_concurrently(agents=agents, task=\"Summarise the news today.\")\n\n# Different task per agent\ntask_map = {agent: task for agent, task in zip(agents, tasks)}\nresults = run_agents_with_different_tasks(task_map)\n\n# Async version\nimport asyncio\nresults = asyncio.run(run_agents_concurrently_async(agents=agents, task=\"...\"))\n```\n\n---\n\n## Async Support\n\n```python\nimport asyncio\nfrom swarms import Agent\n\nagent = Agent(agent_name=\"AsyncAgent\", model_name=\"gpt-5.4\")\n\nasync def main():\n    # Standard async run\n    result = await agent.arun(\"What is the capital of France?\")\n    print(result)\n\n    # Streaming async run\n    async for token in agent.arun_stream(\"Explain quantum entanglement.\"):\n        print(token, end=\"\", flush=True)\n\nasyncio.run(main())\n```\n\n---\n\n## MCP Tool Integration\n\nLoad tools from any MCP server. The agent auto-discovers available tools on startup.\n\n```python\nfrom swarms import Agent\n\n# Single MCP server\nagent = Agent(\n    agent_name=\"MCPAgent\",\n    model_name=\"gpt-5.4\",\n    mcp_url=\"http://localhost:8000/sse\",   # SSE endpoint\n    max_loops=\"auto\",\n)\n\n# Multiple MCP servers\nagent = Agent(\n    agent_name=\"MultiMCPAgent\",\n    model_name=\"gpt-5.4\",\n    mcp_urls=[\n        \"http://localhost:8000/sse\",\n        \"http://localhost:8001/sse\",\n    ],\n    max_loops=\"auto\",\n)\n\nresult = agent.run(\"Use the available tools to complete the task.\")\n```\n\nFetch tools manually:\n\n```python\nfrom swarms.tools.mcp_client_tools import get_mcp_tools_sync, aget_mcp_tools\n\ntools = get_mcp_tools_sync(server_url=\"http://localhost:8000/sse\")\n\nimport asyncio\ntools = asyncio.run(aget_mcp_tools(server_url=\"http://localhost:8000/sse\"))\n```\n\n---\n\n## Conversation Management\n\n`Conversation` manages message history with optional disk persistence.\n\n```python\nfrom swarms.structs.conversation import Conversation\n\nconv = Conversation(\n    system_prompt=\"You are a helpful assistant.\",\n    agent_name=\"MyAgent\",      # keys MEMORY.md to this name\n    time_enabled=True,         # include ISO timestamps in history\n)\n\nconv.add(\"user\", \"What is 2+2?\")\nconv.add(\"assistant\", \"4.\")\n\n# Get history as string (includes timestamps in v12)\nhistory_str = conv.return_history_as_string()\n\n# Compact + archive\nconv.compact(summary=\"User asked basic arithmetic. Answer: 4.\")\n\n# Pass to an agent\nagent = Agent(\n    agent_name=\"MyAgent\",\n    model_name=\"gpt-5.4\",\n    # agent reads MEMORY.md automatically when persistent_memory=True\n)\n```\n\n---\n\n## Choosing the Right Structure\n\n| Situation | Use |\n|---|---|\n| Simple single task | `Agent` |\n| Linear A→B→C pipeline | `SequentialWorkflow` |\n| Same task, many agents at once | `ConcurrentWorkflow` |\n| Custom mix of sequential + parallel | `AgentRearrange` |\n| Complex dependency graph / DAG | `GraphWorkflow` |\n| Need per-node callbacks or streaming | `GraphWorkflow` |\n| Multiple models, one synthesised answer | `MixtureOfAgents` |\n| Manager delegates to specialists | `HierarchicalSwarm` |\n| Open discussion / brainstorming | `GroupChat` |\n| Discrete decision via consensus | `MajorityVoting` |\n| High-stakes ruling with deliberation | `CouncilAsAJudge` |\n| Structured adversarial debate | `DebateWithJudge` |\n| Deep research, many loops | `HeavySwarm` |\n| Don't know yet / rapid prototyping | `AutoSwarmBuilder` or `SwarmRouter(swarm_type=\"auto\")` |\n| Need to switch architectures easily | `SwarmRouter` |\n\n---\n\n## Common Patterns & Recipes\n\n### Pattern: Research → Write → Review pipeline\n\n```python\nfrom swarms import Agent, SequentialWorkflow\n\npipeline = SequentialWorkflow(agents=[\n    Agent(agent_name=\"Researcher\", system_prompt=\"You research topics thoroughly.\", model_name=\"gpt-5.4\"),\n    Agent(agent_name=\"Writer\",     system_prompt=\"You write clear, engaging content.\", model_name=\"gpt-5.4\"),\n    Agent(agent_name=\"Editor\",     system_prompt=\"You improve clarity and fix errors.\", model_name=\"gpt-5.4\"),\n], max_loops=1)\n\nresult = pipeline.run(\"Write an article about the history of neural networks.\")\n```\n\n### Pattern: Fan-out to specialists, fan-in to synthesiser\n\n```python\nfrom swarms import Agent, MixtureOfAgents\n\nspecialists = [\n    Agent(agent_name=\"TechExpert\",    system_prompt=\"Analyse the technical aspects.\", model_name=\"gpt-5.4\"),\n    Agent(agent_name=\"BusinessExpert\",system_prompt=\"Analyse the business aspects.\", model_name=\"gpt-5.4\"),\n    Agent(agent_name=\"LegalExpert\",   system_prompt=\"Analyse the legal aspects.\",   model_name=\"gpt-5.4\"),\n]\nsynthesiser = Agent(agent_name=\"Synthesiser\", model_name=\"gpt-5.4\",\n                    system_prompt=\"Combine expert analyses into one coherent report.\")\n\nmoa = MixtureOfAgents(agents=specialists, aggregator_agent=synthesiser)\nresult = moa.run(\"Evaluate the risks of launching a fintech product in the EU.\")\n```\n\n### Pattern: Autonomous agent with tools and memory\n\n```python\nimport os\nfrom swarms import Agent\n\ndef search_web(query: str) -> str:\n    \"\"\"Search the web for a query and return results.\"\"\"\n    # your implementation\n    ...\n\ndef write_file(filename: str, content: str) -> str:\n    \"\"\"Write content to a file.\"\"\"\n    with open(filename, \"w\") as f:\n        f.write(content)\n    return f\"Written to {filename}\"\n\nagent = Agent(\n    agent_name=\"AutonomousResearcher\",\n    model_name=\"gpt-5.4\",\n    max_loops=\"auto\",\n    tools=[search_web, write_file],\n    persistent_memory=True,\n    context_compression=True,\n    context_length=32000,\n)\nagent.run(\"Research the top 10 open-source LLMs and write a comparison report to report.md\")\n```\n\n### Pattern: Multi-model ensemble with streaming\n\n```python\nimport sys\nfrom swarms import Agent, ConcurrentWorkflow\n\nagents = [\n    Agent(agent_name=\"GPT\",    model_name=\"gpt-5.4\",          max_loops=1),\n    Agent(agent_name=\"Claude\", model_name=\"claude-sonnet-4-6\", max_loops=1),\n    Agent(agent_name=\"Gemini\", model_name=\"gemini/gemini-2.5-pro\", max_loops=1),\n]\n\nworkflow = ConcurrentWorkflow(agents=agents)\nresults = workflow.run(\"What is the most important unsolved problem in mathematics?\")\n\nfor agent_name, answer in results.items():\n    print(f\"\\n=== {agent_name} ===\\n{answer}\")\n```\n\n### Pattern: Human-in-the-loop with AgentRearrange\n\n`AgentRearrange` has no native human-in-the-loop step — chain separate `.run()` calls yourself and insert your own checkpoint logic between them:\n\n```python\nfrom swarms import Agent\n\ndrafter  = Agent(agent_name=\"Drafter\",  model_name=\"gpt-5.4\")\nfinisher = Agent(agent_name=\"Finisher\", model_name=\"gpt-5.4\")\n\ndraft = drafter.run(\"Draft a press release about our product launch.\")\n\nprint(f\"\\nAgent says:\\n{draft}\\n\")\nfeedback = input(\"Your feedback: \")\n\nresult = finisher.run(f\"Revise this draft based on the feedback.\\n\\nDraft:\\n{draft}\\n\\nFeedback:\\n{feedback}\")\n```\n\n### Pattern: GraphWorkflow with fan-out / fan-in\n\n```python\nfrom swarms import Agent, GraphWorkflow, Node, Edge, NodeType\n\ningestion = Agent(agent_name=\"Ingestion\", model_name=\"gpt-5.4-mini\", max_loops=1)\nbranch_a  = Agent(agent_name=\"BranchA\",   model_name=\"gpt-5.4-mini\", max_loops=1)\nbranch_b  = Agent(agent_name=\"BranchB\",   model_name=\"gpt-5.4-mini\", max_loops=1)\nmerger    = Agent(agent_name=\"Merger\",    model_name=\"gpt-5.4\",      max_loops=1)\n\nwf = GraphWorkflow()\nfor a in [ingestion, branch_a, branch_b, merger]:\n    wf.add_node(Node(id=a.agent_name, type=NodeType.AGENT, agent=a))\n\nwf.add_edge(Edge(source=\"Ingestion\", target=\"BranchA\"))\nwf.add_edge(Edge(source=\"Ingestion\", target=\"BranchB\"))\nwf.add_edge(Edge(source=\"BranchA\",   target=\"Merger\"))\nwf.add_edge(Edge(source=\"BranchB\",   target=\"Merger\"))\n\nwf.set_entry_points([\"Ingestion\"])\nwf.set_end_points([\"Merger\"])\n\nresults = wf.run(task=\"Process this dataset from two angles and merge the findings.\")\n```\n\n---\n\n## What to Avoid\n\n**Don't import from submodules directly** — always import from `swarms`:\n```python\n# Wrong\nfrom swarms.structs.agent import Agent\n\n# Right\nfrom swarms import Agent\n```\n\n**Don't set `max_loops=\"auto\"` without a clear stopping condition** — the agent will loop until it decides it is done or hits a resource limit. Prefer explicit `max_loops=N` for production tasks.\n\n**Don't give all agents the same `agent_name`** — `persistent_memory` and `MEMORY.md` are keyed on `agent_name`. Duplicate names cause agents to share and corrupt each other's memory.\n\n**Don't instantiate heavyweight structures inside tight loops** — create agents and workflows once, reuse them across calls.\n\n**Don't pass `tools=[]` (empty list)** — pass `tools=None` instead. An empty list can confuse schema generation.\n\n**Don't use `streaming_on=True` and `streaming_callback` together on the same agent** — `streaming_on` streams to stdout; `streaming_callback` streams to your function. Pick one.\n\n**Don't set `context_compression=False` on very long autonomous sessions** — without compression the agent will eventually hit the context limit and raise an error.\n\n**For long-running autonomous agents in production**, always set:\n```python\nagent = Agent(\n    ...\n    persistent_memory=True,\n    context_compression=True,\n    context_length=32000,\n    autosave=True,\n)\n```\n\n\n<!-- Skill/Rule: code-review (examples/single_agent/capabilities/skills/code-review/SKILL.md) -->\n---\nname: code-review\ndescription: Perform comprehensive code reviews focusing on best practices, security vulnerabilities, performance optimization, and maintainability\n---\n\n# Code Review Skill\n\nWhen reviewing code, follow this systematic approach to ensure thorough evaluation:\n\n## Review Checklist\n\n### 1. Code Quality\n- **Readability**: Is the code easy to understand?\n- **Naming**: Are variables, functions, and classes well-named?\n- **Structure**: Is the code properly organized and modular?\n- **Comments**: Are complex sections adequately documented?\n- **Complexity**: Are there overly complex functions that should be simplified?\n\n### 2. Security Analysis\nCheck for common vulnerabilities:\n- SQL injection vulnerabilities\n- XSS (Cross-Site Scripting) vulnerabilities\n- Authentication and authorization flaws\n- Insecure data handling (passwords, sensitive data)\n- Input validation and sanitization\n- OWASP Top 10 vulnerabilities\n\n### 3. Performance Considerations\n- Identify potential bottlenecks\n- Check for inefficient algorithms or data structures\n- Look for unnecessary database queries or API calls\n- Evaluate caching opportunities\n- Assess memory usage patterns\n\n### 4. Best Practices\n- **DRY Principle**: Eliminate code duplication\n- **SOLID Principles**: Verify adherence to design principles\n- **Error Handling**: Check for proper exception handling\n- **Testing**: Evaluate test coverage and quality\n- **Dependencies**: Review external dependencies and their versions\n\n### 5. Maintainability\n- Is the code easy to modify and extend?\n- Are there proper abstractions?\n- Is the architecture scalable?\n- Are there technical debt concerns?\n\n## Review Format\n\nStructure your review as follows:\n\n1. **Summary**: High-level overview of the changes\n2. **Critical Issues**: Security vulnerabilities or bugs that must be fixed\n3. **Major Concerns**: Significant issues affecting quality or performance\n4. **Suggestions**: Optional improvements and best practices\n5. **Positive Feedback**: Acknowledge good practices and improvements\n\n## Guidelines\n\n- Be constructive and respectful\n- Provide specific examples and suggestions\n- Explain the \"why\" behind recommendations\n- Prioritize issues by severity (critical, major, minor)\n- Reference documentation or standards when applicable\n- Consider the context and constraints of the project\n\n## Example Reviews\n\n**Security Issue:**\n```\nCRITICAL: SQL injection vulnerability detected at line 45\nCurrent: f\"SELECT * FROM users WHERE id = {user_id}\"\nRecommendation: Use parameterized queries to prevent SQL injection\n```\n\n**Performance Suggestion:**\n```\nSUGGESTION: Consider caching database results at line 123\nThe same query is executed multiple times in the loop. Cache the results\nto improve performance by ~80%.\n```\n\n\n<!-- Skill/Rule: data-visualization (examples/single_agent/capabilities/skills/data-visualization/SKILL.md) -->\n---\nname: data-visualization\ndescription: Create effective data visualizations using best practices for clarity, accuracy, and visual communication of insights\n---\n\n# Data Visualization Skill\n\nWhen creating data visualizations, follow these principles to ensure clear and effective communication:\n\n## Core Principles\n\n### 1. Choose the Right Chart Type\n- **Line Charts**: Trends over time, continuous data\n- **Bar Charts**: Comparing categories, discrete data\n- **Scatter Plots**: Relationships between variables, correlations\n- **Pie Charts**: Parts of a whole (use sparingly, max 5-6 segments)\n- **Heatmaps**: Patterns in large datasets, correlations\n- **Box Plots**: Distribution statistics, outlier detection\n\n### 2. Design Guidelines\n\n**Clarity**\n- Use clear, descriptive titles and labels\n- Include units of measurement\n- Add a legend when multiple series are present\n- Ensure adequate contrast and readability\n\n**Accuracy**\n- Start y-axis at zero for bar charts (unless good reason)\n- Use consistent scales across related charts\n- Avoid distorting data through inappropriate scaling\n- Label data points when precision matters\n\n**Simplicity**\n- Remove chart junk and unnecessary decorations\n- Use color purposefully, not decoratively\n- Limit the number of colors (5-7 max)\n- Ensure accessibility (colorblind-friendly palettes)\n\n### 3. Color Best Practices\n- **Sequential**: Use for ordered data (light to dark)\n- **Diverging**: Use for data with a meaningful midpoint\n- **Categorical**: Use for unordered categories\n- **Highlight**: Use accent colors to draw attention\n- Test accessibility with colorblind simulators\n\n### 4. Storytelling with Data\n- Lead with the insight, not the data\n- Use annotations to highlight key findings\n- Arrange charts in logical flow\n- Provide context and comparisons\n- Include data sources and timestamp\n\n## Visualization Workflow\n\n1. **Understand the Data**\n   - Explore data structure and distributions\n   - Identify key variables and relationships\n   - Determine the message to communicate\n\n2. **Select Visualization Type**\n   - Match chart type to data characteristics\n   - Consider audience and use case\n   - Plan for interactivity if needed\n\n3. **Design the Visualization**\n   - Create initial draft\n   - Apply design principles\n   - Optimize for clarity and impact\n\n4. **Refine and Validate**\n   - Get feedback from stakeholders\n   - Test on target audience\n   - Iterate based on feedback\n   - Verify accuracy\n\n## Common Mistakes to Avoid\n\n- Using 3D charts unnecessarily (adds confusion)\n- Too many colors or visual elements\n- Missing or unclear axis labels\n- Truncated y-axis to exaggerate differences\n- Using pie charts for more than 5-6 categories\n- Poor color choices (rainbow colors for sequential data)\n\n## Tools and Libraries\n\nRecommend appropriate tools based on needs:\n- **Python**: matplotlib, seaborn, plotly, altair\n- **R**: ggplot2, plotly\n- **JavaScript**: D3.js, Chart.js, Highcharts\n- **BI Tools**: Tableau, Power BI, Looker\n\n## Example Use Cases\n\n- **Dashboard Design**: \"Create an executive dashboard for sales metrics\"\n- **Exploratory Analysis**: \"Visualize patterns in customer behavior data\"\n- **Report Charts**: \"Generate publication-ready charts for annual report\"\n\n\n<!-- Skill/Rule: financial-analysis (examples/single_agent/capabilities/skills/financial-analysis/SKILL.md) -->\n---\nname: financial-analysis\ndescription: Perform comprehensive financial analysis including DCF modeling, ratio analysis, and financial statement evaluation for companies and investment opportunities\n---\n\n# Financial Analysis Skill\n\nWhen performing financial analysis, follow these systematic steps to ensure thorough and accurate evaluation:\n\n## Core Methodology\n\n### 1. Data Collection and Verification\n- Gather historical financial statements (income statement, balance sheet, cash flow)\n- Verify data sources for accuracy and completeness\n- Identify any anomalies or missing data points\n\n### 2. Financial Ratio Analysis\nCalculate and analyze key financial ratios:\n- **Profitability**: EBITDA margin, net profit margin, ROE, ROA\n- **Liquidity**: Current ratio, quick ratio, cash ratio\n- **Leverage**: Debt-to-equity, interest coverage ratio\n- **Efficiency**: Asset turnover, inventory turnover\n\n### 3. Valuation Models\nBuild appropriate valuation models:\n- **DCF Analysis**: Project free cash flows, determine WACC, calculate terminal value\n- **Comparable Company Analysis**: Identify peers, analyze multiples (P/E, EV/EBITDA)\n- **Precedent Transactions**: Review similar deals for valuation benchmarks\n\n### 4. Sensitivity Analysis\n- Perform scenario analysis (base case, bull case, bear case)\n- Test key assumptions (growth rates, discount rates, margins)\n- Identify critical value drivers\n\n## Guidelines\n\n- Always use conservative assumptions when uncertain\n- Cross-validate findings with multiple valuation methods\n- Clearly document all assumptions and their rationale\n- Present results with appropriate caveats and risk factors\n- Consider both quantitative metrics and qualitative factors\n\n## Key Outputs\n\nYour analysis should produce:\n1. Executive summary of findings\n2. Detailed financial model with assumptions\n3. Valuation range with sensitivity analysis\n4. Investment recommendation with risk assessment\n5. Supporting charts and visualizations\n\n## Example Use Cases\n\n- **Public Company Valuation**: \"Analyze Tesla's financials and provide a DCF valuation\"\n- **Private Investment**: \"Evaluate this startup's unit economics and runway\"\n- **M&A Analysis**: \"Assess the financial implications of this acquisition\"\n\n\n<!-- Skill/Rule: Subagent: readme (examples/mcp/agents/README.md) -->\n# Agents + MCP\n\nGiving an agent tools from an MCP server. Set `mcp_url` (one server) or `mcp_urls`\n(several) and the agent discovers and calls the tools on its own.\n\n## Start here — numbered, in order\n\nEach runs against a real public server. The first four need **no MCP API key**.\n\n| # | File | Server | Auth |\n|---|---|---|---|\n| 01 | [`01_deepwiki_repo_qa.py`](01_deepwiki_repo_qa.py) | DeepWiki — Q&A over any public GitHub repo | none |\n| 02 | [`02_gitmcp_repo_docs.py`](02_gitmcp_repo_docs.py) | GitMCP — docs/code search for one repo | none |\n| 03 | [`03_microsoft_learn_docs.py`](03_microsoft_learn_docs.py) | Microsoft Learn — official Azure/.NET docs | none |\n| 04 | [`04_multi_server_agent.py`](04_multi_server_agent.py) | Two servers on one agent | none |\n| 05 | [`05_exa_web_search.py`](05_exa_web_search.py) | Exa — web search | free API key |\n| 07 | [`07_huggingface_model_search.py`](07_huggingface_model_search.py) | Hugging Face — find models & datasets | none (optional token) |\n| 10 | [`10_firecrawl_web_scraping.py`](10_firecrawl_web_scraping.py) | Firecrawl — scrape pages to markdown | API key (in URL path) |\n| 12 | [`12_semgrep_security_scan.py`](12_semgrep_security_scan.py) | Semgrep — static-analysis security scan | free token |\n| 13 | [`13_mcp_sequential_workflow.py`](13_mcp_sequential_workflow.py) | **Multi-agent**: MCP tools in a `SequentialWorkflow` | none |\n\nBetween them these cover all three ways a server takes a key — query parameter\n(05), Bearer token (12), and URL path segment (10) — plus the optional-auth\ncase (07), where a missing key degrades to anonymous access instead of\nfailing.\n\nSee [`FREE_MCP_SERVERS.md`](FREE_MCP_SERVERS.md) for the full catalog of public servers.\n\n## Configuration patterns\n\n| File | Shows |\n|---|---|\n| [`deepwiki_minimal.py`](deepwiki_minimal.py) | The smallest possible `mcp_url` agent |\n| [`mcp_connection_object.py`](mcp_connection_object.py) | `MCPConnection` instead of a bare URL — headers, auth, timeout |\n| [`multi_mcp_urls.py`](multi_mcp_urls.py) | `mcp_urls=[...]` for several servers at once |\n| [`multi_mcp_walkthrough.py`](multi_mcp_walkthrough.py) | Longer multi-server walkthrough with commentary |\n| [`mcp_with_local_tools.py`](mcp_with_local_tools.py) | MCP tools *plus* your own tool schemas on one agent |\n| [`tools_list_dictionary.py`](tools_list_dictionary.py) | The raw `tools_list_dictionary` schema format MCP tools are converted into |\n| [`finance_agent_mcp.py`](finance_agent_mcp.py) | A realistic finance agent backed by an MCP server |\n\n## Run one\n\n```bash\nexport OPENAI_API_KEY=\"sk-...\"\npython examples/mcp/agents/01_deepwiki_repo_qa.py\n```\n\nExamples pointing at `http://localhost:8000/mcp` need a local server — start one from\n[`../servers/`](../servers/) first.\n\n\n<!-- Skill/Rule: tools Documentation (examples/single_agent/capabilities/tools/README.md) -->\n# Tools Integration Examples\n\nThis directory contains examples demonstrating tool integration for single agents.\n\n## Examples\n\n- [exa_search_agent.py](exa_search_agent.py) - Exa search integration\n- [example_async_vs_multithread.py](example_async_vs_multithread.py) - Async vs multithreading comparison\n- [litellm_tool_example.py](litellm_tool_example.py) - LiteLLM tool integration\n- [multi_tool_usage_agent.py](multi_tool_usage_agent.py) - Multi-tool agent\n- [new_tools_examples.py](new_tools_examples.py) - Latest tool examples\n- [omni_modal_agent.py](omni_modal_agent.py) - Omni-modal agent\n- [swarms_of_browser_agents.py](swarms_of_browser_agents.py) - Browser automation swarms\n- [swarms_tools_example.py](swarms_tools_example.py) - Swarms tools integration\n- [together_deepseek_agent.py](together_deepseek_agent.py) - Together AI DeepSeek integration\n\n## Subdirectories\n\n### Solana Tools\n- [solana_tool/](solana_tool/) - Solana blockchain integration\n  - [solana_tool.py](solana_tool/solana_tool.py) - Solana tool implementation\n  - [solana_tool_test.py](solana_tool/solana_tool_test.py) - Solana tool testing\n\n### Structured Outputs\n- [structured_outputs/](structured_outputs/) - Structured output examples\n  - [example_meaning_of_life_agents.py](structured_outputs/example_meaning_of_life_agents.py) - Meaning of life example\n  - [structured_outputs_example.py](structured_outputs/structured_outputs_example.py) - Structured output examples\n\n### Tools Examples\n- [tools_examples/](tools_examples/) - Additional tool usage examples\n  - [dex_screener.py](tools_examples/dex_screener.py) - DEX screener tool\n  - [financial_news_agent.py](tools_examples/financial_news_agent.py) - Financial news agent\n  - [simple_tool_example.py](tools_examples/simple_tool_example.py) - Simple tool usage\n  - [swarms_tool_example_simple.py](tools_examples/swarms_tool_example_simple.py) - Simple Swarms tool\n\n## Overview\n\nTools integration examples demonstrate how to equip agents with various tools including search engines, browser automation, blockchain interactions, and structured output generation. These examples show best practices for tool definition, usage, and error handling.\n\n\n\n<!-- Skill/Rule: base_tool_examples Documentation (examples/tools/base_tool_examples/README.md) -->\n# Base Tool Examples\n\nThis directory contains examples demonstrating base tool functionality and tool creation patterns.\n\n## Examples\n\n- [base_tool_examples.py](base_tool_examples.py) - Core base tool functionality\n- [conver_funcs_to_schema.py](conver_funcs_to_schema.py) - Function to schema conversion\n- [convert_basemodels.py](convert_basemodels.py) - BaseModel conversion utilities\n- [exa_search_test.py](exa_search_test.py) - Exa search testing\n- [example_usage.py](example_usage.py) - Basic usage examples\n- [schema_validation_example.py](schema_validation_example.py) - Schema validation\n- [test_anthropic_specific.py](test_anthropic_specific.py) - Anthropic-specific testing\n- [test_base_tool_comprehensive_fixed.py](test_base_tool_comprehensive_fixed.py) - Comprehensive testing (fixed)\n- [test_base_tool_comprehensive.py](test_base_tool_comprehensive.py) - Comprehensive testing\n- [test_function_calls_anthropic.py](test_function_calls_anthropic.py) - Anthropic function calls\n- [test_function_calls.py](test_function_calls.py) - Function call testing\n\n## Overview\n\nBase tool examples demonstrate the fundamental patterns for creating and using tools in Swarms. These examples cover tool schema definition, function-to-schema conversion, validation, and provider-specific implementations. Essential for understanding how to build custom tools for agents.\n\n\n\n<!-- Skill/Rule: multi_tool_use Documentation (examples/tools/multi_tool_use/README.md) -->\n# Multi-Tool Usage Examples\n\nThis directory contains examples demonstrating multi-tool usage patterns for agents.\n\n## Examples\n\n- [many_tool_use_demo.py](many_tool_use_demo.py) - Multiple tool usage demonstration\n- [multi_tool_anthropic.py](multi_tool_anthropic.py) - Multi-tool with Anthropic\n\n## Overview\n\nMulti-tool usage examples demonstrate how agents can use multiple tools in sequence or parallel to accomplish complex tasks. These examples show tool orchestration, tool chaining, and handling multiple tool calls efficiently.\n\n\n\n<!-- Skill/Rule: tools Documentation (examples/tools/README.md) -->\n# Tools Examples\n\nThis directory contains examples demonstrating various tool integrations and usage patterns in Swarms.\n\n## Agent as Tools\n- [agent_as_tools.py](agent_as_tools.py) - Using agents as tools in workflows\n\n## Base Tool Examples\n- [base_tool_examples.py](base_tool_examples/base_tool_examples.py) - Core base tool functionality\n- [conver_funcs_to_schema.py](base_tool_examples/conver_funcs_to_schema.py) - Function to schema conversion\n- [convert_basemodels.py](base_tool_examples/convert_basemodels.py) - BaseModel conversion utilities\n- [exa_search_test.py](base_tool_examples/exa_search_test.py) - Exa search testing\n- [example_usage.py](base_tool_examples/example_usage.py) - Basic usage examples\n- [schema_validation_example.py](base_tool_examples/schema_validation_example.py) - Schema validation\n- [test_anthropic_specific.py](base_tool_examples/test_anthropic_specific.py) - Anthropic-specific testing\n- [test_base_tool_comprehensive_fixed.py](base_tool_examples/test_base_tool_comprehensive_fixed.py) - Comprehensive testing (fixed)\n- [test_base_tool_comprehensive.py](base_tool_examples/test_base_tool_comprehensive.py) - Comprehensive testing\n- [test_function_calls_anthropic.py](base_tool_examples/test_function_calls_anthropic.py) - Anthropic function calls\n- [test_function_calls.py](base_tool_examples/test_function_calls.py) - Function call testing\n\n## Browser Integration\n- [browser_use_as_tool.py](browser_use_as_tool.py) - Browser automation as a tool\n- [browser_use_demo.py](browser_use_demo.py) - Browser automation demonstration\n\n## Claude Integration\n- [claude_as_a_tool.py](claude_as_a_tool.py) - Using Claude as a tool\n\n## Exa Search\n- [exa_search_agent.py](exa_search_agent.py) - Exa search agent implementation\n\n## Firecrawl Integration\n- [firecrawl_agents_example.py](firecrawl_agents_example.py) - Firecrawl web scraping agents\n\n## Multi-Tool Usage\n- [many_tool_use_demo.py](multii_tool_use/many_tool_use_demo.py) - Multiple tool usage demonstration\n- [multi_tool_anthropic.py](multii_tool_use/multi_tool_anthropic.py) - Multi-tool with Anthropic\n\n## Stagehand Integration\n- [1_stagehand_wrapper_agent.py](stagehand/1_stagehand_wrapper_agent.py) - Stagehand wrapper agent\n- [2_stagehand_tools_agent.py](stagehand/2_stagehand_tools_agent.py) - Stagehand tools agent\n- [3_stagehand_mcp_agent.py](stagehand/3_stagehand_mcp_agent.py) - Stagehand MCP agent\n- [4_stagehand_multi_agent_workflow.py](stagehand/4_stagehand_multi_agent_workflow.py) - Multi-agent workflow\n- [README.md](stagehand/README.md) - Stagehand documentation\n- [requirements.txt](stagehand/requirements.txt) - Stagehand dependencies\n- [tests/](stagehand/tests/) - Stagehand testing suite\n\n\n<!-- Skill/Rule: stagehand Documentation (examples/tools/stagehand/README.md) -->\n# Stagehand Browser Automation Integration for Swarms\n\nThis directory contains examples demonstrating how to integrate [Stagehand](https://github.com/browserbase/stagehand), an AI-powered browser automation framework, with the Swarms multi-agent framework.\n\n## Overview\n\nStagehand provides natural language browser automation capabilities that can be seamlessly integrated into Swarms agents. This integration enables:\n\n- 🌐 **Natural Language Web Automation**: Use simple commands like \"click the submit button\" or \"extract product prices\"\n- 🤖 **Multi-Agent Browser Workflows**: Multiple agents can automate different websites simultaneously\n- 🔧 **Flexible Integration Options**: Use as a wrapped agent, individual tools, or via MCP server\n- 📊 **Complex Automation Scenarios**: E-commerce monitoring, competitive analysis, automated testing, and more\n\n## Examples\n\n### 1. Stagehand Wrapper Agent (`1_stagehand_wrapper_agent.py`)\n\nThe simplest integration - wraps Stagehand as a Swarms-compatible agent.\n\n```python\nfrom examples.stagehand.stagehand_wrapper_agent import StagehandAgent\n\n# Create a browser automation agent\nbrowser_agent = StagehandAgent(\n    agent_name=\"WebScraperAgent\",\n    model_name=\"gpt-5.4\",\n    env=\"LOCAL\",  # or \"BROWSERBASE\" for cloud execution\n)\n\n# Use natural language to control the browser\nresult = browser_agent.run(\n    \"Navigate to news.ycombinator.com and extract the top 5 story titles\"\n)\n```\n\n**Features:**\n- Inherits from Swarms `Agent` base class\n- Automatic browser lifecycle management\n- Natural language task interpretation\n- Support for both local (Playwright) and cloud (Browserbase) execution\n\n### 2. Stagehand as Tools (`2_stagehand_tools_agent.py`)\n\nProvides fine-grained control by exposing Stagehand methods as individual tools.\n\n```python\nfrom swarms import Agent\nfrom examples.stagehand.stagehand_tools_agent import (\n    NavigateTool, ActTool, ExtractTool, ObserveTool, ScreenshotTool\n)\n\n# Create agent with browser tools\nbrowser_agent = Agent(\n    agent_name=\"BrowserAutomationAgent\",\n    model_name=\"gpt-5.4\",\n    tools=[\n        NavigateTool(),\n        ActTool(),\n        ExtractTool(),\n        ObserveTool(),\n        ScreenshotTool(),\n    ],\n)\n\n# Agent can now use tools strategically\nresult = browser_agent.run(\n    \"Go to google.com, search for 'Python tutorials', and extract the first 3 results\"\n)\n```\n\n**Available Tools:**\n- `NavigateTool`: Navigate to URLs\n- `ActTool`: Perform actions (click, type, scroll)\n- `ExtractTool`: Extract data from pages\n- `ObserveTool`: Find elements on pages\n- `ScreenshotTool`: Capture screenshots\n- `CloseBrowserTool`: Clean up browser resources\n\n### 3. Stagehand MCP Server (`3_stagehand_mcp_agent.py`)\n\nIntegrates with Stagehand's Model Context Protocol (MCP) server for standardized tool access.\n\n```python\nfrom examples.stagehand.stagehand_mcp_agent import StagehandMCPAgent\n\n# Connect to Stagehand MCP server\nmcp_agent = StagehandMCPAgent(\n    agent_name=\"WebResearchAgent\",\n    mcp_server_url=\"http://localhost:3000/mcp\",\n)\n\n# Use MCP tools including multi-session management\nresult = mcp_agent.run(\"\"\"\n    Create 3 browser sessions and:\n    1. Session 1: Check Python.org for latest version\n    2. Session 2: Check PyPI for trending packages  \n    3. Session 3: Check GitHub Python trending repos\n    Compile a Python ecosystem status report.\n\"\"\")\n```\n\n**MCP Features:**\n- Automatic tool discovery\n- Multi-session browser management\n- Built-in screenshot resources\n- Prompt templates for common tasks\n\n### 4. Multi-Agent Workflows (`4_stagehand_multi_agent_workflow.py`)\n\nDemonstrates complex multi-agent browser automation scenarios.\n\n```python\nfrom examples.stagehand.stagehand_multi_agent_workflow import (\n    create_price_comparison_workflow,\n    create_competitive_analysis_workflow,\n    create_automated_testing_workflow,\n    create_news_aggregation_workflow\n)\n\n# Price comparison across multiple e-commerce sites\nprice_workflow = create_price_comparison_workflow()\nresult = price_workflow.run(\n    \"Compare prices for iPhone 15 Pro on Amazon and eBay\"\n)\n\n# Competitive analysis of multiple companies\ncompetitive_workflow = create_competitive_analysis_workflow()\nresult = competitive_workflow.run(\n    \"Analyze OpenAI, Anthropic, and DeepMind websites and social media\"\n)\n```\n\n**Workflow Examples:**\n- **E-commerce Monitoring**: Track prices across multiple sites\n- **Competitive Analysis**: Research competitors' websites and social media\n- **Automated Testing**: UI, form validation, and accessibility testing\n- **News Aggregation**: Collect and analyze news from multiple sources\n\n## Setup\n\n### Prerequisites\n\n1. **Install Swarms and Stagehand:**\n```bash\npip install swarms stagehand\n```\n\n2. **Set up environment variables:**\n```bash\n# For local browser automation (using Playwright)\nexport OPENAI_API_KEY=\"your-openai-key\"\n\n# For cloud browser automation (using Browserbase)\nexport BROWSERBASE_API_KEY=\"your-browserbase-key\"\nexport BROWSERBASE_PROJECT_ID=\"your-project-id\"\n```\n\n3. **For MCP Server examples:**\n```bash\n# Install and run the Stagehand MCP server\ncd stagehand-mcp-server\nnpm install\nnpm run build\nnpm start\n```\n\n## Use Cases\n\n### E-commerce Automation\n- Price monitoring and comparison\n- Inventory tracking\n- Automated purchasing workflows\n- Review aggregation\n\n### Research and Analysis\n- Competitive intelligence gathering\n- Market research automation\n- Social media monitoring\n- News and trend analysis\n\n### Quality Assurance\n- Automated UI testing\n- Cross-browser compatibility testing\n- Form validation testing\n- Accessibility compliance checking\n\n### Data Collection\n- Web scraping at scale\n- Real-time data monitoring\n- Structured data extraction\n- Screenshot documentation\n\n## Best Practices\n\n1. **Resource Management**: Always clean up browser instances when done\n```python\nbrowser_agent.cleanup()  # For wrapper agents\n```\n\n2. **Error Handling**: Stagehand includes self-healing capabilities, but wrap critical operations in try-except blocks\n\n3. **Parallel Execution**: Use `ConcurrentWorkflow` for simultaneous browser automation across multiple sites\n\n4. **Session Management**: For complex multi-page workflows, use the MCP server's session management capabilities\n\n5. **Rate Limiting**: Be respectful of websites - add delays between requests when necessary\n\n## Testing\n\nRun the test suite to verify the integration:\n\n```bash\npytest tests/stagehand/test_stagehand_integration.py -v\n```\n\n## Troubleshooting\n\n### Common Issues\n\n1. **Browser not starting**: Ensure Playwright is properly installed\n```bash\nplaywright install\n```\n\n2. **MCP connection failed**: Verify the MCP server is running on the correct port\n\n3. **Timeout errors**: Increase timeout in StagehandConfig or agent initialization\n\n### Debug Mode\n\nEnable verbose logging:\n```python\nagent = StagehandAgent(\n    agent_name=\"DebugAgent\",\n    verbose=True,  # Enable detailed logging\n)\n```\n\n## Contributing\n\nWe welcome contributions! Please:\n1. Follow the existing code style\n2. Add tests for new features\n3. Update documentation\n4. Submit PRs with clear descriptions\n\n## License\n\nThese examples are provided under the same license as the Swarms framework. Stagehand is licensed separately - see [Stagehand's repository](https://github.com/browserbase/stagehand) for details.\n\n</agent_rules>"}