Skip to main content

Swarm Agents

swarm-agents is a standalone Python package for building LLM agents with:

  • provider-agnostic model routing
  • function/tool execution
  • lifecycle hooks
  • input/output guardrails
  • streaming dialogue execution
  • autonomous batch execution

The import path is swarm.

Package Docs

Releases

Versions are derived from Git tags. A pushed vX.Y.Z tag creates:

  • a GitHub Release with generated notes and attached build artifacts
  • a PyPI publish job via Trusted Publishing

Install

Base package:

pip install swarm-agents

With optional image helpers:

pip install "swarm-agents[image]"

From Git:

pip install "swarm-agents[dev] @ git+ssh://git@github.com/logarith-ms/swarm-agents.git@vX.Y.Z"

PyPI is the primary distribution channel. Git installs remain useful for pinned previews or local validation.

Quick Start

Swarm is the beginner-facing entry point. It handles provider configuration and model-router wiring for you.

from swarm import Agent, Swarm

client = Swarm()  # loads config from environment via ConfigLoader.load()

agent = Agent(
    name="Assistant",
    model="openai/gpt-4o",
    instructions="You are a helpful assistant.",
)

async for chunk in client.run_streamed(
    agent,
    deps=your_context,
    stream_manager=your_stream_manager,
    message_store=your_message_store,
    retry_policy=your_retry_policy,
    max_turns=10,
):
    print(chunk)

Batch execution:

from swarm import Agent, Swarm

client = Swarm(
    config={
        "openai_api_key": "...",
        "openai_organization": "...",
        "openai_project": "...",
        "anthropic_api_key": "...",
        "google_api_key": "...",
        "vertex_project": "...",
        "vertex_location": "us-east1",
    }
)

agent = Agent(
    name="Planner",
    model="openai/gpt-4o",
    instructions="Work through the task step by step.",
)

result = await client.run(
    agent,
    deps=your_context,
    stream_manager=your_stream_manager,
    message_store=your_message_store,
    retry_policy=your_retry_policy,
    max_turns=5,
)
print(result.signal)

What The Facade Does

Swarm(...) removes only the provider/router wiring:

  • ConfigLoader.load()
  • ProviderFactory(config=...)
  • ModelRouter(factory=...)
  • RunContext(..., router=...)

You still provide implementations for the runtime protocols:

  • ContextProtocol
  • StreamManagerProtocol
  • MessageStoreProtocol
  • optionally RetryPolicyProtocol

Those implementations are application-specific and are intentionally not bundled as defaults in this package.

Model Fallback

Agent.model supports either:

  • a single model string
  • a list of models in fallback order

Example:

from swarm import Agent

agent = Agent(
    name="FallbackAgent",
    model=[
        "openai/gpt-4o",
        "anthropic/claude-3-5-sonnet",
        "google/gemini-2.0-flash",
    ],
    instructions="Try providers in order until one succeeds.",
)

The router will try each model in sequence until one succeeds or all fail.

Provider Configuration

ConfigLoader.load() reads these environment variables and maps them to the config keys expected by ProviderFactory:

  • OPENAI_API_KEY
  • OPENAI_ORGANIZATION
  • OPENAI_PROJECT
  • ANTHROPIC_API_KEY
  • GOOGLE_API_KEY
  • VERTEX_PROJECT_ID -> vertex_project
  • VERTEX_LOCATION -> vertex_location

Advanced / Explicit Wiring

If you want full control, keep using the manual path directly:

from swarm import Agent, ConfigLoader, Runner, ModelRouter, ProviderFactory
from swarm.context import RunContext

config = ConfigLoader.load()
router = ModelRouter(factory=ProviderFactory(config=config))

agent = Agent(
    name="Assistant",
    model="openai/gpt-4o",
    instructions="You are a helpful assistant.",
)

run_context = RunContext(
    deps=your_context,
    stream_manager=your_stream_manager,
    message_store=your_message_store,
    router=router,
    retry_policy=your_retry_policy,
)

runner = Runner()
async for chunk in runner.run_streamed(agent=agent, run_context=run_context, max_turns=10):
    print(chunk)

Model Prompt Context

RunContext.model_context optionally projects the merged context used in the system prompt. Its signature is Callable[[dict[str, Any]], Mapping[str, Any]] | None, defaulting to None.

from collections.abc import Mapping
from typing import Any

def project_context(full_context: dict[str, Any]) -> Mapping[str, Any]:
    return {"phase": full_context.get("phase", "ready")}

run_context = RunContext(
    deps=your_context,
    stream_manager=your_stream_manager,
    message_store=your_message_store,
    router=router,
    model_context=project_context,
)

run_context.model_context_variables returns a fresh dict. The callback receives a deep copy of deps.current_context_variables merged with run_context_variables (run-local values win). An empty mapping omits the context block; invalid return types and callback errors propagate without falling back to full context. Without a callback, the full merged context is rendered as before.

Both runner modes refresh the prompt between continuing tool turns; streaming handoffs also use the projection. Tools, hooks, guardrails, run/replay persistence, budgets, and checkpoints keep their existing full-state behavior. This hook only controls the rendered context block, not agent instruction callbacks, history, or tool output. Context, overlays, and agent instructions retain their existing order.

Optional Image Support

swarm.util.image_to_base64(...) is available behind the image extra.

If you call it without installing the extra, it raises an ImportError with the install command:

pip install "swarm-agents[image]"

Hooks And Guardrails

  • Hooks are observational and never alter execution flow.
  • Input guardrails run before the first LLM call.
  • Output guardrails are blocking in Runner and advisory in Runner.

See:

  • swarm.hooks
  • swarm.guardrails
  • swarm.runners.runner
  • swarm.runners.runner

Development

pip install -e ".[dev]"
ruff format --check .
ruff check .
mypy swarm
pytest tests -q
python -m build

Maintainer Release Flow

  1. Merge conventional commits to main.
  2. Wait for CI to verify that the merged Git tree matches the successful PR validation, then for Auto Tag to create the next semantic vX.Y.Z tag. Tests, formatting, lint and type checks run only on PRs, across all three supported Python versions; main does not repeat them.
  3. The pushed tag triggers Publish PyPI, which requires successful main CI for that exact commit, builds the wheel/sdist once, and shares those artifacts with the GitHub Release and Trusted Publishing jobs. The pypi environment and Trusted Publisher workflow identity are unchanged.
  4. Verify the new version on:
    • https://github.com/logarith-ms/swarm-agents/releases
    • https://pypi.org/project/swarm-agents/

Notes

  • swarm_task/ is intentionally not part of this package.
  • swarm/ERROR_HANDLING.md is intentionally not promoted into the package root.

Metadata

Release files for swarm-agents 0.6.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for swarm-agents 0.6.3
File Size Uploaded Provenance Actions
swarm_agents-0.6.3.tar.gz 194.3 kB With provenance Details for swarm_agents-0.6.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for swarm-agents 0.6.3
File Interpreter ABI Platform Actions
swarm_agents-0.6.3-py3-none-any.whl Python 3 none any Details for swarm_agents-0.6.3-py3-none-any.whl

Total release size: 320.7 kB

Release files / swarm_agents-0.6.3.tar.gz

Download URL swarm_agents-0.6.3.tar.gz
Size 194.3 kB
Tags Source
SHA-256 checksum
How to use checksums
3beb0223dad032123498fdec68de0dcc46e8e9a05aa33d5f11b95c80cb084a60
BLAKE2b-256 checksum
How to use checksums
3a033315166680780558f65607cc56f675af88f030dfb5658603b947103a310d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 5, 2026.

Transparency log

Release files / swarm_agents-0.6.3-py3-none-any.whl

Download URL swarm_agents-0.6.3-py3-none-any.whl
Size 126.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6214a769413890c4066cb5042cc60a1fc6eb9ee71fc1271f1385b3aa4785e603
BLAKE2b-256 checksum
How to use checksums
4b7f154d465a528a0e102850cc12088ca04c71311f5ba96c0d0c31e956187842
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 5, 2026.

Transparency log

Security for swarm-agents 0.6.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for swarm_agents-0.6.3.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 5, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.6.3 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page