swarm-intelligence
БесплатноБез исполняемых скриптовНе проверенBuild swarm intelligence systems where multiple AI agents collaborate to make predictions and solve complex problems. Use when: implementing ensemble AI…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
Swarm Intelligence
Overview
Build systems where multiple AI agents independently analyze a problem, then converge on predictions through voting, debate, or weighted aggregation. The idea comes from ensemble methods: independent answers that err in different directions can cancel out. With LLMs the gain is not guaranteed. Results across studies are mixed, and sampling one strong model several times and taking the majority answer (self-consistency) often does as well as a swarm at the same cost. Measure on your own questions before relying on it.
Core Patterns
- Prediction Swarm (Vote & Aggregate) — Each agent analyzes independently with a different persona, then votes are aggregated
- Debate Swarm (Argue & Converge) — Agents see each other's reasoning and update positions over multiple rounds
- Specialist Swarm (Divide & Conquer) — Each agent handles a different domain aspect, then a synthesizer combines results
Instructions
When a user asks to build a swarm intelligence system, prediction ensemble, or multi-agent decision system:
- Identify the pattern — Is it prediction (vote), debate (converge), or specialist (divide)?
- Define agents — Each agent needs a unique persona/perspective and clear role
- Choose aggregation — Weighted voting, median, debate rounds, or synthesis
- Implement with LangGraph — Use parallel nodes for agents, then aggregation node
Prediction Swarm Implementation
Each agent returns a validated Vote (structured output), not free text that has to be parsed with json.loads. The fan-in edge add_edge([...], "aggregator") makes the aggregator wait for every agent.
"""Prediction swarm: N agents vote independently, aggregator combines."""
import operator, os
from typing import Annotated, Literal, TypedDict
from pydantic import BaseModel, Field
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, START, END
MODEL = os.environ["SWARM_MODEL"] # a current chat model id that supports structured output (gpt-4o-mini is deprecated, removal 2027-01-14)
class Vote(BaseModel):
prediction: Literal["yes", "no"]
confidence: float = Field(ge=0, le=1)
reasoning: str
class SwarmState(TypedDict):
question: str
votes: Annotated[list[dict], operator.add] # reducer merges parallel writes
final_answer: str
AGENT_PERSONAS = [
{"name": "Optimist", "prompt": "You see opportunities and upside potential."},
{"name": "Skeptic", "prompt": "You question assumptions and look for flaws."},
{"name": "Analyst", "prompt": "You focus on data and historical patterns."},
{"name": "Contrarian", "prompt": "You challenge consensus. Look for what others miss."},
{"name": "Pragmatist", "prompt": "You focus on practical, real-world constraints."},
]
def make_agent_node(persona: dict):
llm = ChatOpenAI(model=MODEL).with_structured_output(Vote)
def agent_fn(state: SwarmState) -> dict:
vote = llm.invoke(
f"You are the {persona['name']}. {persona['prompt']}\n\n"
f"Question (answer yes or no): {state['question']}"
)
return {"votes": [{**vote.model_dump(), "agent": persona["name"]}]}
return agent_fn
def aggregator(state: SwarmState) -> dict:
tally: dict[str, float] = {}
lines = []
for v in state["votes"]:
tally[v["prediction"]] = tally.get(v["prediction"], 0) + v["confidence"]
lines.append(f"- {v['agent']} ({v['confidence']:.0%} {v['prediction']}): {v['reasoning']}")
winner = max(tally, key=tally.get)
share = tally[winner] / sum(tally.values())
return {"final_answer": f"**Prediction:** {winner}\n**Weighted share:** {share:.0%}\n" + "\n".join(lines)}
builder = StateGraph(SwarmState)
for persona in AGENT_PERSONAS:
builder.add_node(persona["name"], make_agent_node(persona))
builder.add_edge(START, persona["name"])
builder.add_node("aggregator", aggregator)
builder.add_edge([p["name"] for p in AGENT_PERSONAS], "aggregator")
builder.add_edge("aggregator", END)
swarm = builder.compile()
Debate Swarm (Multi-Round Convergence)
Agents see the previous round's positions, including their confidence, and may change their mind.
"""Debate swarm: agents see each other's reasoning and update positions."""
from pydantic import BaseModel, Field
import os
from langchain_openai import ChatOpenAI
MODEL = os.environ["SWARM_MODEL"] # same variable as above
class Position(BaseModel):
position: str = Field(description="One-sentence stance")
confidence: float = Field(ge=0, le=1)
reasoning: str
llm = ChatOpenAI(model=MODEL)
debater = llm.with_structured_output(Position)
DEBATE_AGENTS = [
{"name": "Bull", "bias": "optimistic"},
{"name": "Bear", "bias": "pessimistic"},
{"name": "Quant", "bias": "data-driven"},
]
def run_debate(question: str, rounds: int = 3) -> dict:
history: list[list[dict]] = []
for round_num in range(1, rounds + 1):
context
Установить swarm-intelligence в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл swarm-intelligence?
Build swarm intelligence systems where multiple AI agents collaborate to make predictions and solve complex problems. Use when: implementing ensemble AI predictions, building consensus-based decision systems, creating multi-agent prediction markets.
Как установить скилл swarm-intelligence?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл swarm-intelligence запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic