OpenAI Swarm - Detailed Introduction to Multi-Agent Orchestration Framework
Project Overview
OpenAI Swarm is an educational framework for exploring ergonomic, lightweight multi-agent orchestration. Managed by the OpenAI Solutions team, this project aims to provide developers with a simple, flexible, and controllable tool for building multi-agent systems.
Important Update: Swarm has now been superseded by the OpenAI Agents SDK, which is the production-ready version of Swarm. The OpenAI team recommends migrating all production use cases to the Agents SDK.
Core Features
1. Design Philosophy
- Lightweight: Focused on simplicity and ease of use
- Highly Controllable: Provides precise agent control mechanisms
- Easy to Test: Supports simple testing and debugging processes
- Education-Oriented: Serves as an educational resource for learning multi-agent orchestration
2. Core Abstractions
Swarm achieves agent coordination through two core abstractions:
Agent
- Contains instructions and tools
- Can hand off the conversation to another agent at any point
- Supports dynamic instructions and context variables
Handoffs
- Seamless transition mechanism between agents
- Supports complex agent networks and workflows
- Maintains conversation continuity
Installation and Basic Usage
System Requirements
- Python 3.10+
Installation
pip install git+ssh://[email protected]/openai/swarm.git
# Or
pip install git+https://github.com/openai/swarm.git
Basic Example
from swarm 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",
instructions="Only speak in Haikus.",
)
response = client.run(
agent=agent_a,
messages=[{"role": "user", "content": "I want to talk to agent B."}],
)
print(response.messages[-1]["content"])
Output Example:
Hope glimmers brightly,
New paths converge gracefully,
What can I assist?
Technical Architecture
Client Execution Mechanism
Swarm's client.run() function implements the following loop:
- Get completion response from the current agent
- Execute tool calls and add results
- Switch agents if necessary
- Update context variables
- Return the result if there are no new function calls
Parameter Configuration
| Parameter | Type | Description | Default Value |
|---|---|---|---|
| agent | Agent | The (initial) agent to call | (Required) |
| messages | List | List of message objects | (Required) |
| context_variables | dict | Context variables | {} |
| max_turns | int | Maximum number of turns | float("inf") |
| model_override | str | Model override | None |
| execute_tools | bool | Whether to execute tools | True |
| stream | bool | Whether to enable streaming responses | False |
| debug | bool | Whether to enable debug logging | False |
Agent Configuration
Agent Class Fields
| Field | Type | Description | Default Value |
|---|---|---|---|
| name | str | Agent name | "Agent" |
| model | str | Model to use | "gpt-4o" |
| instructions | str or function | Agent instructions | "You are a helpful agent." |
| functions | List | List of callable functions | [] |
| tool_choice | str | Tool selection strategy | None |
Dynamic Instructions Example
def instructions(context_variables):
user_name = context_variables["user_name"]
return f"Help the user, {user_name}, do whatever they want."
agent = Agent(instructions=instructions)
response = client.run(
agent=agent,
messages=[{"role":"user", "content": "Hi!"}],
context_variables={"user_name":"John"}
)
Function Calling Mechanism
Basic Function Call
def greet(context_variables, language):
user_name = context_variables["user_name"]
greeting = "Hola" if language.lower() == "spanish" else "Hello"
print(f"{greeting}, {user_name}!")
return "Done"
agent = Agent(functions=[greet])
Agent Handoff
sales_agent = Agent(name="Sales Agent")
def transfer_to_sales():
return sales_agent
agent = Agent(functions=[transfer_to_sales])
Complex Result Return
def talk_to_sales():
print("Hello, World!")
return Result(
value="Done",
agent=sales_agent,
context_variables={"department": "sales"}
)
Example Projects
Swarm provides several example projects demonstrating different application scenarios:
1. basic - Basic Example
Demonstrates basic usage of setup, function calls, handoffs, and context variables
2. triage_agent - Triage Agent
Simple triage setup that forwards requests to the appropriate agent
3. weather_agent - Weather Agent
Simple example demonstrating function calls
4. airline - Airline Customer Service
Multi-agent setup for handling different types of customer service requests for an airline
5. support_bot - Support Bot
Includes a user interface agent and a help center agent with various tools
6. personal_shopper - Personal Shopper
Personal shopping agent that helps with sales and refund order processing
Streaming
Swarm supports streaming responses, using the same events as the Chat Completions API:
stream = client.run(agent, messages, stream=True)
for chunk in stream:
print(chunk)
New event types:
{"delim":"start"}and{"delim":"end"}- Mark the beginning and end of an agent processing a single message{"response": Response}- Returns the complete Response object at the end of the stream
Testing and Evaluation
Development Testing
Use run_demo_loop for command-line testing:
from swarm.repl import run_demo_loop
run_demo_loop(agent, stream=True)
Evaluation Recommendations
- The project encourages developers to bring their own evaluation suites
- Evaluation references are provided in the airline, weather_agent, and triage_agent examples
- Supports custom performance testing metrics
Differences from Other OpenAI Products
Comparison with Assistants API
- Assistants API: Provides fully managed threads and built-in memory management
- Swarm: Runs entirely on the client-side, with a stateless design, making it more suitable for learning and experimentation
Technical Features
- Built on the Chat Completions API
- Does not save state between calls
- Lightweight client implementation
- Focused on education and learning purposes
Suitable Scenarios
Swarm is particularly well-suited for the following situations:
- Scenarios requiring handling a large number of independent functions and instructions
- Complex tasks that are difficult to encode into a single prompt
- Learning multi-agent orchestration concepts
- Rapid prototyping and experimentation
Project Status
Note: While Swarm has been superseded by the OpenAI Agents SDK, it remains an excellent educational resource for understanding the basic concepts and implementation methods of multi-agent systems. For production environments, it is recommended to migrate to the official Agents SDK.
Summary
OpenAI Swarm provides a simple yet powerful framework for learning and developing multi-agent systems. Through the two core concepts of agents and handoffs, developers can build complex AI workflows while maintaining code readability and maintainability. Although it has been superseded by the new SDK, its design philosophy and educational value remain important.