Building a multi agent system with OpenAI’s swarm framework
In the fast-paced world of finance, the ability to quickly analyze earnings reports and extract actionable insights can provide a significant competitive advantage. Imagine automating the labor-intensive process of dissecting earnings reports, uncovering crucial insights, and generating informed recommendations — all with minimal effort.
Recently, OpenAI introduced Swarm, an open-source, lightweight, experimental framework designed for simplicity and ease of use. Its primary goal is to demonstrate how routines and handoffs can effectively orchestrate multiple agents. Swarm enables the coordination of various AI agents, each tasked with specific functions, allowing them to collaborate seamlessly.
In this article, we will go through the fundamentals of OpenAI’s Swarm framework and guide you through the creation of a multi-agent system utilizing OpenAI’s Swarm framework.
Getting Started
Table of contents
- What is OpenAI’s Swarm framework
- Components of Swarm
- Agents
- Handoffs
- Building a multi agent system for earnings report analysis
- Installing dependencies
- Setting up environment
- Implementing agents
- Running the app
What is OpenAI’s Swarm framework
OpenAI’s Swarm is an open-source multi-agent orchestration framework designed to help users build and manage multi-agent systems through the concepts of routines and handoffs. This holistic approach enables more effective collaboration among agents, each tasked with specific functions, rather than relying on independent capabilities that are challenging to encode into a single prompt.
Powered by OpenAI’s Chat Completions API, Swarm operates stateless between calls. Users instantiate a Swarm client, which utilizes the run()
function to process messages, similar to the chat.completions.create()
function in the OpenAI API. The run()
function orchestrates a loop that retrieves completions from the current agent, executes tool calls, switches agents as needed, updates context variables, and returns the response.
Key features of the Swarm framework include:
- Multi-Agent Coordination: Allows multiple agents to collaborate on complex tasks by distributing responsibilities, enhancing modularity and flexibility.
- Task-Specific Agents: Enables agents to handle diverse functions like summarization, sentiment analysis, and decision-making, promoting targeted information processing.
- Versatile Use Cases: Applicable across various domains such as finance, healthcare, and customer service, enabling tasks like summarizing earnings reports and generating trading recommendations.
- Scalability and Flexibility: Supports the addition of new agents or modification of existing ones without requiring a complete system redesign.
- API Integration: Allows for integration with APIs, enhancing agent capabilities for complex analyses and generating human-like responses.
Components of Swarm
Swarm simplifies agent coordination and execution using two primary abstractions: Agents and Handoffs.
Agents
An Agent encapsulates a set of instructions along with functions and possesses the ability to hand off execution to another Agent. While it may be tempting to view an Agent as “someone who does X”. It can also represent specific workflows or steps defined by a combination of instructions and functions such as a series of steps, a complex retrieval, or a single data transformation. This flexibility allows Agents to form a network of agents, workflows and tasks, all represented through the same primitive structure.
Each Agent consists of instructions that are directly converted into the system prompt of a conversation (as the first message). Only the instructions of the currently active Agent are present at any given time, meaning that if an Agent hands off control, the system prompt changes while the chat history remains intact.
A basic example of how to define an Agent:
agent = Agent(
instructions="You are a helpful agent."
)
The instructions can be a regular string or a function that returns a string. This function can optionally accept a context_variables
parameter, populated by the context variables passed into client.run()
.
The key agent fields of Swarm are listed below:
Handoffs
Lets explore how agents can transfer control using the handoff mechanism. Here’s a demonstration involving mathematical and weather-related queries:
client = Swarm()
messages = [{"role": "user", "content": "What is 2 + 2?"}]
handoff_response = client.run(agent=weather_agent, messages=messages)
print(handoff_response.messages[-1]["content"])
In this example, we deliberately pose a math question to the weather_agent
. Recognizing the question is outside its expertise, the weather_agent
hands off control to the math_agent
, which then provides the correct answer.
Building a multi agent system for earnings report analysis
In this section, you will learn to set up and orchestrate three specialized agents: one for summarizing earnings reports, another for sentiment analysis and a third one for generating actionable recommendations. By the end of this tutorial, you will have a scalable and modular solution that enhances financial analysis, with potential applications extending well beyond earnings reports.
Installing dependencies
- Create and activate a virtual environment by executing the following command.
Ensure that you have Python 3.10 or a later version installed on your system.
python -m venv venv
source venv/bin/activate #for ubuntu
venv/Scripts/activate #for windows
- Install
swarm
,openai
andpython-dotenv
libraries using pip.
pip install git+https://github.com/openai/swarm.git openai python-dotenv
Setting up environment
- Begin by creating a new folder for your project. Choose a name that reflects the purpose of your project.
- Inside your new project folder, create two subfolders named
agents
andutils
. - Create a file named
.env
. This file will store your environment variables, including the OpenAI key. - Open the
.env
file and add the following code to specify your OpenAI API key:
OPENAI_API_KEY=sk-proj-7XyPjkdaG_gDl0_...
Implementing agents
In this part, you will develop three distinct agents: one dedicated to summarizing the earnings report, another focused on sentiment analysis, and a third tasked with generating actionable recommendations based on the sentiment findings.
1. Summary agent
The Summary Agent is designed to extract the initial 1000 characters of the earnings report to serve as a concise summary.
- Create a file named
summary_agent.py
insideagents
folder and add the following code to it.
from swarm import Agent
def summarize_report(context_variables):
report_text = context_variables["report_text"]
return f"Summary: {report_text[:1000]}..."
summary_agent = Agent(
name="Summary Agent",
instructions="Summarize the key points of the earnings report.",
functions=[summarize_report]
)
2. Sentiment agent
This agent will analyze the report to see if the word “profit” is present, which it will use to assess whether the sentiment is positive.
- Create a file named
sentiment_agent.py
insideagents
folder and add the following code to it.
from swarm import Agent
def analyze_sentiment(context_variables):
report_text = context_variables["report_text"]
sentiment = "positive" if "profit" in report_text else "negative"
return f"The sentiment of the report is: {sentiment}"
sentiment_agent = Agent(
name="Sentiment Agent",
instructions="Analyze the sentiment of the report.",
functions=[analyze_sentiment]
)
3. Recommendation agent
Depending on the sentiment analysis, this agent will provide a recommendation of either “Buy” or “Hold.”
- Create a file named
recommendation_agent.py
insideagents
folder and add the following code to it.
from swarm import Agent
def generate_recommendation(context_variables):
sentiment = context_variables["sentiment"]
recommendation = "Buy" if sentiment == "positive" else "Hold"
return f"My recommendation is: {recommendation}"
recommendation_agent = Agent(
name="Recommendation Agent",
instructions="Recommend actions based on the sentiment analysis.",
functions=[generate_recommendation]
)
Creating helper functions
Create a helper function to load the earnings report file for your agents.
- Create a file named
helpers.py
insideutils
folder and add the following code to it.
def load_earnings_report(filepath):
with open(filepath, "r") as file:
return file.read()
Putting everything together
The agents have been created. Now, create a main script that orchestrates the agents, enabling them to collaborate seamlessly to analyze the earnings report and deliver valuable insights.
- Create a file named
app.py
in the main folder and add the following code to it.
from swarm import Swarm
from agents.summary_agent import summary_agent
from agents.sentiment_agent import sentiment_agent
from agents.recommendation_agent import recommendation_agent
from utils.helpers import load_earnings_report
import os
from dotenv import load_dotenv
# Load environment variables from the .env file
load_dotenv()
# Set the OpenAI API key from the environment variable
os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY')
# Initialize Swarm client
client = Swarm()
# Load earnings report
report_text = load_earnings_report("sample_earnings.txt")
# Run summary agent
response = client.run(
agent=summary_agent,
messages=[{"role": "user", "content": "Summarize the report"}],
context_variables={"report_text": report_text}
)
print(response.messages[-1]["content"])
# Pass summary to sentiment agent
response = client.run(
agent=sentiment_agent,
messages=[{"role": "user", "content": "Analyze the sentiment"}],
context_variables={"report_text": report_text}
)
print(response.messages[-1]["content"])
# Extract sentiment and run recommendation agent
sentiment = response.messages[-1]["content"].split(": ")[-1].strip()
response = client.run(
agent=recommendation_agent,
messages=[{"role": "user", "content": "Give a recommendation"}],
context_variables={"sentiment": sentiment}
)
print(response.messages[-1]["content"])
Running the app
We haven’t added any earnings report content yet. Create a file named sample_earnings.txt
in the main folder and include some content such as the one given below:
Company XYZ has reported strong financial results for Q3 of the fiscal year. The company saw a 20% increase in profits compared to the previous quarter, driven by a 15% increase in sales. Operating income also rose by 18%, while costs remained relatively stable.
Highlights from the report include:
- Revenue: $1.5 billion, up 15% year-over-year.
- Net profit: $300 million, up from $250 million in Q2.
- Earnings per share (EPS): $1.50, exceeding analyst expectations.
In addition, the company has invested in new technology to enhance product offerings and customer experience, with expected gains in market share in the upcoming fiscal year. Management has expressed optimism about future growth and is considering expansion into new regions.
The company anticipates a continuation of these positive trends, with projected revenue growth of 10-12% for the next fiscal quarter.
Lets run the app using the following code.
python app.py
The code output is as follows,
You can also try fetching content from the MarketWatch site and add it to the file to better understand stock recommendations. If you integrate Yahoo Finance features with this agent, it can retrieve stock details from the internet and provide recommendations based on that information.
The following is the output based on the content from the site regarding Intel stock.
If you’re looking to create AI agents and assistants without any coding, Runbear makes it super easy by offering a no-code platform that integrates seamlessly with Slack, MS Teams, HubSpot, and Zendesk, allowing you to set up custom AI assistants for your workspace in just minutes.
Thanks for reading this article !!
Thanks Gowri M Bhatt for reviewing the content.
If you enjoyed this article, please click on the clap button 👏 and share to help others find it!
The full source code for this tutorial can be found here,