OpenAI Swarm
Experimental pattern for lightweight agent "Handoffs".
1. Philosophy
Swarm is stateless. An agent is just a set of instructions. To "Orchestrate", Agent A simply calls a function that returns Agent B. This is called a Handoff.
Technique: The Handoff
from swarm import Swarm, Agent
client = Swarm()
# 1. Define Handoff Logic
def transfer_to_spanish():
"""Transfer spanish users here."""
return spanish_agent
# 2. Define Agents
english_agent = Agent(
name="English",
instructions="You speak English.",
functions=[transfer_to_spanish] # <--- The Handoff Tool
)
spanish_agent = Agent(
name="Spanish",
instructions="Tu hablas espaƱol.",
)
# 3. Run
# If user says "Hola", agent calls 'transfer_to_spanish', and Swarm switches active agent.
response = client.run(
agent=english_agent,
messages=[{"role": "user", "content": "Hola"}]
)
print(response.messages[-1]['content'])
Technique: Context Variables
Since Swarm is stateless, you pass data manually.
def greet(context_variables):
name = context_variables.get("name", "User")
return f"Hello {name}"
agent = Agent(functions=[greet])
client.run(
agent=agent,
messages=[...],
context_variables={"name": "Alice"}
)