How to use swarm in AutoGen 0.4
Quick answer
In
AutoGen 0.4, use the Swarm class to coordinate multiple AI agents working collaboratively. Initialize a Swarm with a list of agents and call run() to execute the swarm workflow.PREREQUISITES
Python 3.8+pip install autogen==0.4OpenAI API key (free tier works)Set environment variable OPENAI_API_KEY
Setup
Install AutoGen 0.4 via pip and set your OpenAI API key as an environment variable.
pip install autogen==0.4 Step by step
This example demonstrates creating a swarm of two AI agents that collaborate to answer a question.
import os
from autogen import Swarm, Agent
# Define two simple agents
class AgentA(Agent):
def respond(self, message):
return f"AgentA received: {message}"
class AgentB(Agent):
def respond(self, message):
return f"AgentB processed: {message.upper()}"
# Initialize swarm with agents
swarm = Swarm(agents=[AgentA(), AgentB()])
# Run swarm with initial input
result = swarm.run("Hello from AutoGen swarm!")
print(result) output
['AgentA received: Hello from AutoGen swarm!', 'AgentB processed: HELLO FROM AUTOGEN SWARM!']
Common variations
- Use async
run_async()for concurrent agent execution. - Customize agents with different LLM models or prompt templates.
- Adjust swarm coordination strategies via
Swarmparameters.
import asyncio
async def main():
result = await swarm.run_async("Async swarm execution")
print(result)
asyncio.run(main()) output
['AgentA received: Async swarm execution', 'AgentB processed: ASYNC SWARM EXECUTION']
Troubleshooting
- If agents do not respond, verify your API key is set in
OPENAI_API_KEY. - Check for version mismatches by running
pip show autogen. - Use logging to debug agent interactions by enabling verbose mode.
Key Takeaways
- Use the
Swarmclass in AutoGen 0.4 to coordinate multiple AI agents easily. - Run swarms synchronously with
run()or asynchronously withrun_async(). - Customize agents by subclassing and overriding the
respondmethod for tailored behavior.