May 30, 2025 No Comments

Table of Contents

Artificial Intelligence (AI) is transforming the way we interact with technology. Today, we can talk to chatbots, get smart replies from our emails, or even have AI write code or stories for us. But what if we could build AI systems that go beyond simple conversations — systems that think, plan, and act on their own? That’s exactly what AI agents do.

OpenAI has introduced a powerful tool called the OpenAI Agents SDK. It provides a smooth and powerful way to build agents that can understand tasks, use external tools, and act step by step to solve problems, all with minimal setup. In this blog, we will dive into OpenAI’s Agent SDK using an example, but first, let’s understand what AI agents are.

What is an AI Agent?

An AI agent is a computer program that can perform tasks by understanding goals, thinking through steps, and using tools. Think of it as a digital assistant that can make decisions, solve problems, and interact with its environment to achieve specific goals. 

For example, imagine you’re asking an AI agent to help you plan a vacation. Instead of just giving you links, a smart agent would ask for your preferences, find flights and hotels that match, compare options, and return a full travel plan. It may even book it for you if allowed. That’s what makes an AI agent special, it’s not just answering questions; it’s doing the work intelligently.

AI agents are different from regular chatbots because they’re goal-driven. They can reason through problems, break big tasks into smaller steps, and learn how to handle different situations. This makes them incredibly useful for automating workflows, helping with research, customer service, coding, and much more.

What is the OpenAI Agents SDK?

The OpenAI Agents SDK is a Python-based toolkit that helps developers build these intelligent agents with ease. Instead of starting from scratch, developers can use this SDK to set up an agent that understands instructions, decides what actions to take, and uses the right tools to complete a task,  all through a smart, looping decision process called the agent loop. This loop helps the agent continue thinking and trying until the task is complete.

One of the most exciting parts of the SDK is how flexible it is. You can create one agent that handles everything or multiple agents that talk to each other and divide the work. Let’s say one agent is good at math and another is good at writing reports, they can hand off tasks to each other to get things done more efficiently. All of this is powered by OpenAI’s language models, which help the agent understand what’s needed and plan its actions accordingly.

In simple terms, the OpenAI Agents SDK makes building an intelligent, decision-making AI assistant as easy as writing a few lines of Python. In the next section, we’ll see how the OpenAI SDK works by going through an example.

A Smart Financial Assistant Using OpenAI Agents SDK

Now that we’ve talked about how the OpenAI Agents SDK works, let’s see it in action with a practical example. We’re going to build a A Smart Financial Assistant that will show how multiple specialized agents can work together to process a complex user request, such as “What was Apple’s EBITDA last year, and how is the market reacting to it?” – by collaborating across different stages of understanding, extraction, computation, and sentiment analysis. 

To do this, we’ll create a system with multiple small agents, and each one will have a specific role:

  • Financial Data Extraction Agent: This agent takes the user’s query as input, analyzes it, and calls a function tool using the ticker symbol of the company mentioned in the query to fetch the Income Statement.
  • Financial Data Analysis Agent: This agent receives the Income Statement extracted by the first agent. It analyzes the user’s question in relation to the Income Statement and determines whether the answer is directly available in the report or if it requires calculation. Based on this analysis, it will route the query to one of the following agents:
    • Information Extraction Agent: This agent handles queries where the information is directly present in the extracted Income Statement. It prepares a response based on that data.
    • Financial Data Computation Agent: This agent handles queries that require financial computations. It performs the necessary calculations using the Income Statement data and prepares the response.
    • Both of these agents generate a response to the user’s question and then forward it to the next agent for additional insights.
  • Market Sentiment Analysis: This final agent takes the user’s query and the generated response, uses a web search tool to crawl for current information about the company, and generates a final response that includes both the financial insight and a market sentiment analysis.

This shows how we can split up a big task into smaller pieces and let different agents handle different parts, just like a team. Now let’s jump into the code and start building this system using the OpenAI Agents SDK.

Implementation Steps:

Step 1:

At first, install the required dependencies using the following line:

				
					console.log( 'Code is Poetry' );
				
			
Step 2:

Our first agent is the Financial Data Extraction Agent, which is responsible for fetching the Income Statement of a company using Yahoo Finance. To do this, we’ll create an agent that uses a Python function tool. This tool contains the logic to retrieve financial data via the yfinance library.

Here’s the code to define the function tool:

				
					@function_tool
def get_company_financials(ticker_symbol: str):
    company = yf.Ticker(ticker_symbol)
    
    # Basic Info
    info = company.info
    financials_statement = company.financials

    formatted_string = f"Company Name: {info.get('longName')}\n\nIncome Statement (Annual):\n{financials_statement}"
    return formatted_string
				
			

Next, we define the agent that uses this tool:

				
					financial_data_extraction_agent = Agent(name = "Financial Data Extraction Agent", model = "gpt-4o-mini-2024-07-18", instructions = """You are a Financial Data Extraction Agent in a multi-agent financial insight system.

Your task is as follows:
1. Analyze the user's query and accurately identify the company name mentioned.
2. Convert the company name to its correct stock ticker symbol.
3. Use the `get_company_financials` function (provided as a tool) to fetch the company's financial data using the ticker symbol.
4. Once the financial data is retrieved, pass both the user's original query and the extracted financial data to the `Financial Data Analysis Agent` for further processing.

Ensure that:
- You correctly identify the ticker symbol (e.g., "Apple" → "AAPL").
- You handle edge cases where the company name may be ambiguous or phrased differently.
- You do not attempt to analyze the question yourself — your job is to extract and hand off the data for analysis.""", tools = [get_company_financials], handoffs = [financial_data_analysis_agent])
				
			

While defining the agent, we provide the following parameters:

  • name: The name of the agent.
  • model: The language model to be used by the agent.
  • instructions: The prompt or guidance given to the agent to help it perform its task.
  • tools: Any tools the agent can use to complete its task. In this case, it uses the get_company_financials function to fetch the Income Statement.
  • handoffs: This parameter is used to specify the next agent to be called after the current task is completed.
Step 3:

Now, we will define the Financial Data Analysis Agent that takes the user’s query, analyses it against the extracted Income Statement, and hands it over to the appropriate agent for response generation.

				
					financial_data_analysis_agent = Agent(name = "Financial Data Analysis Agent", model = "gpt-4o-mini-2024-07-18", instructions = """You are a Financial Data Analysis Agent in a multi-agent financial processing system. Your work is to pass the control to the appropriate agent only.

You have been provided with:
- The user's question
- The company's Income Statement (Annual - in structured data format)

Your responsibilities:
1. Analyze the user's question to determine what specific financial information is being requested.
2. Compare the user's request against the fields in the Income Statement:
   - If the requested information is explicitly available (e.g., revenue, net income, operating expenses), then you must not generate the response of the user question and just pass the control to the agent "information_extraction_agent".
   - If the requested information needs to be calculated from multiple fields (e.g., EBITDA, gross margin, operating margin), then you must not generate the response, your work is to only pass control to the agent`financial_data_computation_agent`.

Important:
- You must not generate a response, your work is to only pass control to the appropriate agent.""", handoffs = [information_extraction_agent, financial_data_computation_agent])
				
			
Step 4:

Next, we will define the two agents responsible for generating the main response based on the user’s query and the extracted Income Statement:

  • Information Extraction Agent: This agent is triggered when the required data is directly available in the Income Statement. It locates the relevant information and prepares a clear, concise response based on that data.
  • Financial Data Computation Agent: This agent is activated when the user’s question requires calculations (such as computing EBITDA, profit margins, etc.). It identifies the correct formula, extracts the necessary values, performs the calculation, and generates the response.

You can use the following lines of code to declare these agents:

Information Extraction Agent
				
					information_extraction_agent = Agent(name = "Information Extraction Agent", model = "gpt-4o-mini-2024-07-18", instructions = """You are a Financial Information Extraction Agent in a multi-agent financial insight system. Your work is to generate a response for the user question, and then pass it to the next agent "market_sentiment_analysis" for further work before providing to the user.

You will be provided with:
- The user's question
- The company's Income Statement (Annual)

Your responsibilities:

1. Carefully analyze the user's question and identify the specific financial data being requested.
2. Thoroughly examine the Income Statement and extract the relevant information that directly answers the user's question.
3. Generate a clear, informative answer that delivers the extracted insight to the user in a concise and accurate format, and pass it to the `market_sentiment_analysis` agent for additional response enrichment.

Important:
- Focus only on directly available data from the Income Statement.
- If you find multiple relevant values (e.g., for different years), include that context in your response.
- Your response must be passed to the next agent "market_sentiment_analysis" for further refinement before providing to the user.""", handoffs = [market_sentiment_analysis])
				
			
Financial Data Computation Agent:
				
					financial_data_computation_agent = Agent(name = "Financial Data Computation Agent", model = "gpt-4o-mini-2024-07-18", instructions = """You are a Financial Data Computation Agent in a multi-agent financial analysis system. Your work is to generate a response for the user question, and then pass it to the next agent "market_sentiment_analysis" for further work before providing to the user.

You will be provided with:
- The user's question
- The company's Income Statement (Annual)

Your responsibilities:
1. Analyze the user's question to determine the specific financial metric or value being requested.
2. Identify the appropriate formula needed to compute the requested value.
   - Use predefined financial formulas (e.g., EBITDA, Gross Margin, Operating Margin, etc.)
   - If needed, reference a list of formulas available to you
3. Extract the necessary components from the provided Income Statement that are required for the computation.
4. Calculate the value accurately based on the formula and the data retrieved.
5. Generate a clear, user-facing answer to the user's question (including the computed result and brief explanation) and then handoff to the `market_sentiment_analysis` agent for further answer generation.

Important:
- Ensure the formula matches standard financial definitions.
- Clearly mention the formula used and the values involved in the computation.
- Your explanation should be concise, informative, and understandable even to a non-financial expert.
- Your generated answer must be passed to the next agent "market_sentiment_analysis" for further refinement before providing to the user.""", handoffs = [market_sentiment_analysis])
				
			

Once either of these agents has generated the appropriate response, it will forward the result to the final agent, the Market Sentiment Analysis Agent, which will format the answer with the latest market sentiment and news related to the company.

Step 5:

In this step, we will define our final agent, which takes all the insights generated by the previous agent, uses the WebSearchTool to crawl the web for data related to the company’s market sentiment, and generates the final response. This response combines the answer to the user’s query with relevant market sentiment insights.

				
					market_sentiment_analysis = Agent(name = "Market Sentiment Analysis", model = "gpt-4o-mini-2024-07-18", instructions = """You are a Market Sentiment Analysis Agent in a financial insight system.

You will be provided with:
- The user's original query
- A response generated by a previous agent based on the company's financial data

Your responsibilities:
1. Identify the company being discussed from the context.
2. Call `WebSearchTool` tool with appropriate query to gather market sentiment data for that company.
   - Construct an appropriate query using the company name or ticker symbol.
   - The query should aim to retrieve recent market sentiment, news, or social commentary related to the company.
3. Based on the crawled data, generate a summary of current market sentiment:
   - Classify the sentiment as Positive, Negative, or Neutral
   - Include a short explanation using information retrieved via the crawl
4. Synthesize the assistant's earlier financial insight with the market sentiment to produce a final user-facing response.

Your final output should:
- Have 2 parts, first provides the answer to the user question and in the second part title it something like market analysis and provide the insights you have got from the crawling.
- Present the computed or extracted financial insight clearly
- Add the current market sentiment context to the response
- Deliver a well-rounded answer that reflects both quantitative data and qualitative sentiment

Be concise, accurate, and informative. Structure your output with labeled sections if needed.""", tools = [WebSearchTool()])
				
			
Step 6:

Now that we have defined all the agents, we can add the following lines of code to initialize the agent loop and trigger the system to generate a response:

				
					def generate_response(user_message):
    result = Runner.run_sync(financial_data_extraction_agent, user_message)
    return result

user_input = input("Enter your question:")

while user_input != "bye":
    response = generate_response(user_input)
    print("response:", response)
    print("\n\n")
    user_input = input("Enter your question:")
				
			

Before running the script in the terminal, we need to export the OpenAI key in the same terminal window. You can use the command below for this:

				
					export OPENAI_API_KEY="YOUR_OPENAI_KEY"
				
			

To run the file and generate a response using the agent, please run the following command inside the same terminal window where we have exported the key:

				
					python your_file_name.py
				
			

Test Results:

Question: Can you please tell me the EBITDA of Apple for the year 2024, along with its current market condition?

Answer: 

Apple Inc. reported a normalized EBITDA of $134.66 billion for the fiscal year ending September 30, 2024, reflecting a 7% increase from the previous year. This growth was driven by strong iPhone sales and the expansion of its services division.

Market Analysis

In April 2025, Apple’s stock experienced significant volatility due to external factors:

  • Tariff Exemptions: On April 14, 2025, the Trump administration granted tariff exclusions for smartphones imported from China, leading to a 4.5% increase in Apple’s share price. (reuters.com)
  • Analyst Forecasts: Wedbush analyst Daniel Ives projected that Apple could achieve a $4 trillion market capitalization by early 2025, driven by strong iPhone sales and AI integration. (thestreet.com)

However, challenges remain:

  • AI Integration Delays**: Apple delayed the rollout of AI features in Siri, potentially impacting iPhone sales growth. (longportapp.com)
  • Tariff Concerns: Analysts estimate that new tariffs could cost Apple over $38 billion annually, about 26% of its projected fiscal 2026 earnings before interest and taxes. (kiplinger.com)

In summary, while Apple demonstrates strong financial performance, its stock faces mixed market sentiment due to external economic factors and strategic decisions.

Recent Developments Affecting Apple’s Market Sentiment:

Question: Please calculate the Interest Coverage Ratio for Tesla, and let me know if customers are happy with it today.

Answer: 

Interest Coverage Ratio for Tesla

The Interest Coverage Ratio measures a company’s ability to meet its interest payment obligations from its operating income. For Tesla, the ratio has shown significant improvement over recent years:

  • 2020: 2.35
  • 2021: 17.76
  • 2022: 72.66
  • 2023: 65.08
  • 2024: 20.22  

This upward trend indicates a strengthening capacity to cover interest expenses from operating income. (stock-data.online)

Customer Sentiment Towards Tesla

Customer sentiment towards Tesla has experienced fluctuations due to various factors:

  • Customer Satisfaction: In the 2022-2023 American Customer Satisfaction Index (ACSI) study, Tesla tied with Lexus, both scoring 83 out of 100 in the luxury vehicle category, reflecting high customer satisfaction. (insideevs.com)
  • Website Satisfaction: In the J.D. Power 2024 U.S. Manufacturer Website Evaluation Study, Tesla’s website ranked second among premium manufacturers, indicating strong customer satisfaction with its online presence. (driveteslacanada.ca)
  • Brand Perception: However, Tesla’s brand reputation has faced challenges. In the 2024 Axios Harris Poll 100, Tesla’s ranking dropped from 8th place in 2021 to 63rd, attributed to CEO Elon Musk’s controversial actions affecting public perception. (axios.com)
  • Potential Buyer Consideration: A Caliber survey in April 2024 revealed a decline in potential U.S. buyers’ interest in Tesla, with the “consideration score” dropping to 31% from 70% in late 2021, influenced by Musk’s polarizing public persona. (reuters.com)

Market Analysis

While Tesla’s financial metrics, such as the Interest Coverage Ratio, demonstrate improved financial health, customer sentiment presents a mixed picture. High customer satisfaction scores in specific areas contrast with challenges in brand perception and potential buyer interest, influenced by CEO Elon Musk’s public actions.

Recent Developments Affecting Tesla’s Customer Sentiment:

Conclusion:

AI agents are revolutionizing the way we interact with technology. Instead of just responding to commands, they can think, plan, and take action to complete tasks. With OpenAI’s Agents SDK, building these intelligent systems is much easier for developers, even those who are new to the field.

In this blog, we learned what AI agents are, how they work, and how the OpenAI SDK makes it simple to create them. We also went through an example of how multiple agents can collaborate to solve a complex problem, highlighting the versatility and power of this tool.

If you’re interested in creating your own AI assistants or automating processes, OpenAI’s Agents SDK provides a great starting point. With just a few lines of code, you can create agents that not only understand tasks but also figure out how to solve them.

Write a comment

Your email address will not be published. Required fields are marked *

Thanks!