A gentle introduction to OpenAI Swarm Library

Rohit Raj
5 min readNov 3, 2024

--

A few days back OpenAI management conducted an AMA session on Reddit. Sam Altman said in that session that the use of agents will be a major use case for LLMs in 2025.

In this article I explain how to create agents using OpenAI library.

LLMs are already quite capable. Major companies are working to make them more reliable as an agent. If you want to implement an Agent by yourself, you can use Structured output and Function Calling features in OpenAI API. To make it easier to implement agents using these features, OpenAI launched Swarm library.

Swarm Libary makes heavy use of Function Calling feature in OpenAI API. So before reading up Swarm library I will recommend reading up on OpenAI Function Calling feature.

https://platform.openai.com/docs/guides/function-calling

Despite its name, function calling does not directly invoke any function itself. Instead, you provide a list of available tools (functions) within a chat completion request through the OpenAI Chat API. This setup includes passing function definitions alongside the user prompt. If the language model determines that a response to the user’s prompt requires using one of these tools, its reply will include a function call along with the necessary arguments

Now OpenAI Swarm library takes it a step further. It introduces the concept of agent. Each agent can have its own custom prompt, message history, context variables and available tools.

When the Swarm agent’s run method is called, it performs the following steps:

  1. It makes an API request to the OpenAI chat completion endpoint, including the agent’s tools (Python functions), message history, and the user’s prompt.
  2. If the OpenAI API returns text output, this output is sent back to the user and added to the message history.
  3. The agent’s tools must be Python functions. If a function has arguments beyond context variables, the API will return a function call with the necessary argument values. If an argument’s value can’t be inferred from the user input, the language model will prompt for the missing information.
  4. The Swarm agent executes any function calls returned by the language model. If a function only uses context variables, those are the only arguments passed.
  5. The function’s return type determines the next steps:
    • If the function returns a Result object (from the Swarm library), the Result.value is added to the message history. The Result.context_variables contain the updated context, which is then set as the new context variables. After handling all function calls, the OpenAI chat completion endpoint is called again.
    • If the function returns an Agent, the message history is passed to that agent, and the OpenAI chat completion endpoint is called again with the new agent’s instructions and tools.
  6. Finally, the agent provides a response object containing the agent’s response and any updated context variables.

Stock Price Agent

I have used the library to implement an Agent for analysis of stock price data.

  1. First import necessary libraries and helper function
import pandas as pd
import matplotlib.pyplot as plt
import requests
from swarm import Swarm
from swarm.types import Result
import json
from swarm import Agent

def pretty_print_messages(messages) -> None:
for message in messages:
if message["role"] != "assistant":
continue

# print agent name in blue
print(f"\033[94m{message['sender']}\033[0m:", end=" ")

# print response, if any
if message["content"]:
print(message["content"])

# print tool calls in purple, if any
tool_calls = message.get("tool_calls") or []
if len(tool_calls) > 1:
print()
for tool_call in tool_calls:
f = tool_call["function"]
name, args = f["name"], f["arguments"]
arg_str = json.dumps(json.loads(args)).replace(":", "=")
print(f"\033[95m{name}\033[0m({arg_str[1:-1]})")

2. Define context variables and helper functions

context_variables ={"ISIN":"","data":""}
def plotopenprice(ISIN,todate,fromdate):
url = f'https://api.upstox.com/v2/historical-candle/NSE_EQ%7C{ISIN}/day/{todate}/{fromdate}'
headers = {
'Accept': 'application/json'
}

response = requests.get(url, headers=headers)
data= response.json()
df = data['data']['candles']
df = pd.DataFrame(df,columns=['Date','Open','High','Low','Close','Volume','OpenInterest'])
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)
df['Open'].plot()
plt.xlabel("Date")
plt.ylabel("Open")
plt.show()
return Result(value=str(df["Open"][-1]),context_variables={'ISIN':ISIN,'data':df})

def averageprice(context_variables):
return context_variables['data']['Open'].mean()

def miniumumprice(context_variables):
return context_variables['data']['Open'].min()

def maximumprice(context_variables):
return context_variables['data']['Open'].max()

def returnisin(context_variables):
return context_variables["ISIN"]

3. Insantiate our Agent

upstox_agent = Agent(
name="Upstox Agent",
instructions="You are a helpful agent.",
functions=[plotopenprice, averageprice, miniumumprice, maximumprice, returnisin],
context_variables=context_variables,
)

4 Run event loop

client = Swarm()
print("Starting Swarm CLI 🐝")

messages = []
agent = upstox_agent
stream = False

while True:
user_input = input("\033[90mUser\033[0m: ")
messages.append({"role": "user", "content": user_input})

response = client.run(
agent=agent,
messages=messages,
context_variables=context_variables or {},
stream=stream,
debug=False,
)

if stream:
response = process_and_print_streaming_response(response)
else:
pretty_print_messages(response.messages)

messages.extend(response.messages)
agent = response.agent
context_variables= response.context_variables
print(context_variables)

Swarm library has run_demo_loop function for running an agent in a loop. But it has a bug. It does not update context variables after each loop. So I wrote a modified agent loop as above.

a. Running the agent , I can fetch stock price data using chat

b. The tools of agent have access to context variables as seen from the following call

c. Stock price data is plotted in part a. I can do operations on it using the tools of agents

One thing to note is that context variables are not passed to OpenAI API. So you can use agents to do complicated operations on big data without triggering significant API costs.

d. This stock price agent can be further worked upon. We can let know for which stock price data is available. So agent will download stock price data only if it is not available. We can refactor context variables to hold data for multiple stocks so that we can do even more complicated operations across multiple scrips etc.

This straightforward example demonstrates how to create agents using the OpenAI library. In the future, a company’s competitive edge may hinge on the quality of its AI agents.

If you liked the article please clap and subscribe.

--

--

Rohit Raj
Rohit Raj

Written by Rohit Raj

Studied at IIT Madras and IIM Indore. Love Data Science

No responses yet