Skip to main content

SwarmX (forked from OpenAI's Swarm)

PyPI version Python Version License: MIT Downloads GitHub stars GitHub forks GitHub issues Ruff

An extreme simple framework exploring ergonomic, lightweight multi-agent orchestration.

Highlights

  1. SwarmX is both Agent and Workflow
  2. MCP servers support
  3. OpenAI-compatible streaming-server
  4. Workflow import/export in JSON format

asciicast

Star History

Star History Chart

Quick start

SwarmX automatically loads environment variables from a .env file if present. You can either:

  1. Use a .env file (recommended):

    # Create a .env file in your project directory
    echo "OPENAI_API_KEY=your-api-key" > .env
    echo "OPENAI_BASE_URL=http://localhost:11434/v1" >> .env  # optional
    uvx swarmx  # Start interactive REPL
    
  2. Set environment variables manually:

    export OPENAI_API_KEY="your-api-key"
    # export OPENAI_BASE_URL="http://localhost:11434/v1"  # optional
    uvx swarmx  # Start interactive REPL
    

API Server

You can also start SwarmX as an OpenAI-compatible API server:

uvx swarmx serve --host 0.0.0.0 --port 8000

This provides OpenAI-compatible endpoints:

  • POST /chat/completions - Chat completions with streaming support
  • GET /models - List available models

Use it with any OpenAI-compatible client:

import openai

client = openai.OpenAI(
    base_url="http://localhost:8000",
    api_key="dummy"  # SwarmX doesn't require authentication
)

response = client.chat.completions.create(
    model="agent-created-by-yourself",
    messages=[{"role": "user", "content": "Hello!"}]
)

Installation

Requires Python 3.11+

$ pip install swarmx # or `uv tool install swarmx`

Usage

import asyncio
from swarmx import Swarm, Agent

client = Swarm()

def transfer_to_agent_b():
    return agent_b


agent_a = Agent(
    name="Agent A",
    instructions="You are a helpful agent.",
    functions=[transfer_to_agent_b],
)

agent_b = Agent(
    name="Agent B",
    model="deepseek-r1:7b",
    instructions="你只能说中文。",  # You can only speak Chinese.
)


async def main():
    response = await client.run(
        agent=agent_a,
        messages=[{"role": "user", "content": "I want to talk to agent B."}],
    )

    print(response.messages[-1]["content"])


asyncio.run(main())

Context Variables

SwarmX supports special context variables that control agent behavior:

background

Provides additional context for the agent. This can be used for:

  • Adding external knowledge (web search results, database queries)
  • Compressing previous conversation history into summaries
  • Isolating context for sub-agents who don't need full conversation history

Example:

context = {
    "background": "Recent news: AI conference announced for next month. User is interested in AI developments."
}

message_slice

Controls which messages are sent to the LLM using Python slice syntax. This enables:

  • Context compression by sending only recent messages
  • LLM-driven filtering decisions
  • Memory management for long conversations

Slice patterns:

  • ":10" - First 10 messages
  • "-5:" - Last 5 messages
  • ":0" - No messages (useful with background for context compression)
  • "2:8" - Messages from index 2 to 7

Example:

context = {
    "message_slice": "-10:"  # Send only last 10 messages
}

tools

Dynamically selects which tools are available for the current completion. This allows:

  • Context-aware tool selection
  • Reducing tool overload by showing only relevant tools
  • Dynamic tool routing based on conversation context

Example:

context = {
    "tools": [
        {
            "type": "function",
            "function": {
                "name": "search_web",
                "description": "Search the web for information",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "query": {"type": "string"}
                    },
                    "required": ["query"]
                }
            }
        },
        {
            "type": "function", 
            "function": {
                "name": "get_weather",
                "description": "Get weather information for a location",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {"type": "string"}
                    },
                    "required": ["location"]
                }
            }
        }
    ]
}

Advanced Usage Examples

Context Compression:

# Compress history into background and send no previous messages
context = {
    "background": "Previous conversation summary: User asked about weather, then travel plans.",
    "message_slice": ":0"  # No previous messages
}

RAG Pattern:

# Add web search results to background, send all messages for comprehensive context
context = {
    "background": "Web search results: Latest AI developments from yesterday's conference...",
    # No slice means all message might pass to LLM
}

Dynamic Tool Selection:

# Based on conversation topic, show only relevant tools
if "weather" in user_message:
    context = {"tools": [{"type": "function", "function": {"name": "get_weather", "description": "Get weather", "parameters": {"type": "object", "properties": {"location": {"type": "string"}}, "required": ["location"]}}}]}
elif "search" in user_message:
    context = {"tools": [{"type": "function", "function": {"name": "search_web", "description": "Search web", "parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}}}]}

Architecture

graph TD
   classDef QA fill:#ffffff;
   classDef agent fill:#ffd8ac;
   classDef tool fill:#d3ecee;
   classDef result fill:#b4f2be;
   func1("transfer_to_weather_assistant()"):::tool
   Weather["Weather Assistant"]:::agent
   func2("get_weather('New York')"):::tool
   temp(64):::result
   A["It's 64 degrees in New York."]:::QA
   Q["What's the weather in ny?"]:::QA --> 
   Triage["Triage Agent"]:::agent --> Weather --> A
   Triage --> func1 --> Weather
   Weather --> func2 --> temp --> A

Metadata

Release files for swarmx 0.7.0

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

Source distribution (sdist)

Source distribution for swarmx 0.7.0
File Size Uploaded Provenance
swarmx-0.7.0.tar.gz 26.2 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for swarmx 0.7.0
File Interpreter ABI Platform
swarmx-0.7.0-py3-none-any.whl Python 3 none any Details

Total release size: 57.0 kB

Release files / swarmx-0.7.0.tar.gz

Download URL swarmx-0.7.0.tar.gz
Size 26.2 kB
Tags Source
SHA-256 checksum
How to use checksums
247f745cfbc5375f716d455a8fdd634c90df01a142ca6bacf44174d12a30be85
BLAKE2b-256 checksum
How to use checksums
ec119b2c87b4e42f6092444647c6c45712fd8b254fda9a41aebae7a02e92f1b6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.4

Release files / swarmx-0.7.0-py3-none-any.whl

Download URL swarmx-0.7.0-py3-none-any.whl
Size 30.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
667c3e6eb6b82f665732e56086fe2b4be47199c51579d427c6f063784ea62d3e
BLAKE2b-256 checksum
How to use checksums
35be4363a357730ea11f025bb86c2dea1dcf55db1c392912404b37bede5c37d5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.4

Security for swarmx 0.7.0

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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.

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