4  Creating an Agent with OpenAI Agent SDK

4.1 Learning Objectives

  • Understand the OpenAI Agent SDK and its core concepts
  • Integrate our financial tools with the Agent SDK
  • Build a basic agent that can answer financial questions
  • Run and test the agent with different types of queries

Let’s start building our first agent implementation using the OpenAI Agent SDK. This high-level framework will simplify many aspects of agent development, allowing us to focus on the core functionality.

4.2 Understanding the OpenAI Agent SDK

The OpenAI Agent SDK is a framework that simplifies the development of AI agents. It provides many abstractions, among them:

  1. Tool Management: Registering, describing, and executing tools
  2. Conversation Management: Handling multi-turn conversations
  3. State Management: Maintaining context across interactions
  4. Async Operations: Efficient handling of API calls

Let’s first install the SDK:

uv add openai-agents

4.2.1 Core Concepts in the Agent SDK

Before we dive into implementation, let’s understand the key concepts in the Agent SDK:

  1. Agent: The main class that represents our assistant. It has a name, instructions, and tools.
  2. Runner: Responsible for executing the agent with user inputs and managing the conversation flow.
  3. Tools: Functions that the agent can call to perform actions or retrieve information.
  4. Context: A container for state that persists across interactions.

Now let’s implement our agent using these concepts.

Create and Test Basic Agents

If you would like to start with even simpler agents to get a better understanding of how the Agent SDK works, please refer to this section.

If you prefer developing and testing in an interactive environment (like Jupyter) for Python, we cover in this section, where we will also discuss the caveats of running the Agent SDK in an interactive environment.

4.3 Building the First Version of MarketMind

Let’s create a file for our Agent SDK implementation:

touch src/openai_agent_sdk/agent.py

Now, let’s implement a basic version of our agent:

# src/openai_agent_sdk/agent.py
from agents import Agent, Runner, function_tool
import logging
from functools import wraps
from src.common.config import SYSTEM_PROMPT, DEFAULT_MODEL
from src.common.tools_yf import (
    get_stock_price as original_get_stock_price,
    get_stock_history as original_get_stock_history,
    get_company_info as original_get_company_info,
    get_financial_metrics as original_get_financial_metrics
)

# Configure logger for the agent
logger = logging.getLogger(__name__)

# Wrap our tools to use with the Agent SDK
@function_tool
@wraps(original_get_stock_price)
def get_stock_price(ticker: str) -> str:
    return original_get_stock_price(ticker)

@function_tool
@wraps(original_get_stock_history)
def get_stock_history(ticker: str, days: int) -> str:
    return original_get_stock_history(ticker, days)

@function_tool
@wraps(original_get_company_info)
def get_company_info(ticker: str) -> str:
    return original_get_company_info(ticker)

@function_tool
@wraps(original_get_financial_metrics)
def get_financial_metrics(ticker: str) -> str:
    return original_get_financial_metrics(ticker)

class MarketMindOpenAIAgent:
    def __init__(self, model=DEFAULT_MODEL):
        """Initialize the MarketMind agent."""
        logger.info(f"Initializing MarketMindOpenAIAgent with model={model}")
        
        # Initialize the agent
        self.agent = Agent(
            name = "MarketMind",
            model = model,
            instructions = SYSTEM_PROMPT,
            tools = [                
                get_stock_price,
                get_stock_history,
                get_company_info,
                get_financial_metrics
            ],
        )
        logger.info("Agent initialization complete")

    async def process_query(self, query):
        """Process a user query using the agent."""
        logger.info(f"Processing query: {query[:50]}...")
        
        # Process the query using the agent
        logger.debug("Sending query to OpenAI agent")
        result = await Runner.run(self.agent, query)
        
        final_output = result.final_output
        logger.debug(f"Received response: {final_output[:50]}...")
        
        return final_output

Let’s break down what’s happening in this code:

  1. Tool Wrapping: We’re using @function_tool and @wraps to adapt our existing tools for use with the Agent SDK.
  2. Agent Initialization: We create an Agent object with a name, model, instructions, and tools.
  3. Query Processing: We implement an async process_query method that uses the Runner to execute the agent with a user query.
Note

@function_tool is a decorator provided by the Agent SDK to mark functions as tools that can be used by the agent. We’re adding the @wraps decorator to make sure the Agent SDK can extract the description of the original functions which helps the agent select the tools, you can refer to this section for more details.

4.4 Testing Our Basic Agent

Let’s create a simple test script to try out our agent:

# /tests/test_agent.py
import asyncio
from src.openai_agent_sdk.agent import MarketMindOpenAIAgent

async def test_agent():
    # Initialize our agent
    agent = MarketMindOpenAIAgent()
    
    # Test with a simple query
    query = "What's the current price of TSLA stock?"
    print(f"Query: {query}")
    
    response = await agent.process_query(query)
    print(f"\nResponse: {response}")

if __name__ == "__main__":
    asyncio.run(test_agent())

Run the test script:

python test_agent.py

You should see output similar to this:

Query: What's the current price of TSLA stock?
  🔍 Getting stock price for TSLA
Response: Tesla, Inc. (TSLA) is currently trading at $237.97, up 4.60% today.

Great! Our agent is working. It correctly understood the query, called the appropriate tool, and formatted a response.

4.5 Understanding How the Agent Works

Let’s take a deeper look at what’s happening when we run the agent:

  1. Query Processing: The agent receives the user’s query and analyzes it to understand the intent.
  2. Tool Selection: Based on the query, the agent decides which tool to use (in this case, get_stock_price).
  3. Tool Execution: The agent calls the selected tool with the appropriate parameters (ticker=“TSLA”).
  4. Response Generation: The agent formats a natural language response using the tool’s output.

This process is handled automatically by the Agent SDK, which uses the language model to make decisions about tool selection and response generation.

4.6 Testing with Different Query Types

Let’s expand our test to try different types of queries:

# test_agent_comprehensive.py
import asyncio
from src.openai_agent_sdk.agent import MarketMindOpenAIAgent

async def test_agent_with_queries():
    # Initialize our agent
    agent = MarketMindOpenAIAgent()
    
    # List of test queries
    queries = [
        "What's the current price of TSLA?",
        "What was Amazon's stock price over the past week?",
        "Tell me about Apple as a company",
        "Show me Microsoft's financial metrics",
    ]
    
    # Run each query
    for query in queries:
        print(f"\n\n{'='*50}")
        print(f"QUERY: {query}")
        print(f"{'='*50}")
        
        response = await agent.process_query(query)
        print(f"\nRESPONSE:\n{response}")

if __name__ == "__main__":
    asyncio.run(test_agent_with_queries())

Run this comprehensive test:

python test_agent_comprehensive.py

You should see the agent handling different types of queries, using the appropriate tool for each one.

 python tests/test_agent_comprehensive.py


==================================================
QUERY: What's the current price of TSLA?
==================================================
  🔍 Getting stock price for TSLA

RESPONSE:
The current price of Tesla (TSLA) is $284.95.


==================================================
QUERY: What was Amazon's stock price over the past week?
==================================================
Getting 7 days of stock history for AMZN

RESPONSE:
Over the past week, Amazon's stock price has fluctuated and is currently around $188.99.


==================================================
QUERY: Tell me about Apple as a company
==================================================
  🏢 Getting company info for AAPL

RESPONSE:
Apple Inc. is a leading technology company based in Cupertino, California. It designs, manufactures, and markets smartphones (iPhone), personal computers (Mac), tablets (iPad), wearables, and accessories worldwide. The company also offers various digital services including Apple Music, Apple TV+, iCloud, Apple Pay, and the App Store. Apple serves consumers, businesses, educational institutions, and government markets globally. It was founded in 1976 and is known for its innovative products and services.


==================================================
QUERY: Show me Microsoft's financial metrics
==================================================
  💰 Getting financial metrics for MSFT

RESPONSE:
Microsoft's key financial metrics include a market cap of approximately $2.91 trillion, a P/E ratio of 31.55, and a dividend yield of 85.00%. The company's revenue is around $261.8 billion, with a profit margin of 35.43% and a return on equity of 34.29%.


==================================================
QUERY: What are the companies we've looked at so far?
==================================================

RESPONSE:
So far, we've looked at the following companies:
- Tesla (TSLA)
- Amazon (AMZN)
- Apple (AAPL)
- Microsoft (MSFT)
 python tests/test_agent_comprehensive.py


==================================================
QUERY: What's the current price of TSLA?
==================================================
  🔍 Getting stock price for TSLA

RESPONSE:
Tesla, Inc. (TSLA) is currently trading at $284.95.


==================================================
QUERY: What was Amazon's stock price over the past week?
==================================================
Getting 7 days of stock history for AMZN
  🏢 Getting company info for AMZN

RESPONSE:
Over the past week, Amazon's stock price has fluctuated as follows:
- April 17, 2025: $172.61
- April 21, 2025: $167.32
- April 22, 2025: $173.18
- April 23, 2025: $180.60
- April 24, 2025: $186.54
- April 25, 2025: $188.99

Would you like more detailed analysis or additional information?


==================================================
QUERY: Tell me about Apple as a company
==================================================
  🏢 Getting company info for AAPL
  💰 Getting financial metrics for AAPL

RESPONSE:
Apple Inc. (AAPL) is a leading technology company based in Cupertino, California. It operates in the consumer electronics sector, designing, manufacturing, and marketing products such as iPhones, Mac computers, iPads, and wearables like Apple Watch and AirPods. The company also provides various digital services including the App Store, Apple Music, iCloud, and Apple TV+. 

As of the latest data, Apple has a market capitalization of approximately $3.15 trillion, making it one of the most valuable companies in the world. It has a P/E ratio of 33.22 and a dividend yield of 48.00%. The company reported revenues of about $396 billion, with a profit margin of 24.3% and an impressive return on equity of 136.52%.


==================================================
QUERY: Show me Microsoft's financial metrics
==================================================
  💰 Getting financial metrics for MSFT

RESPONSE:
Here are Microsoft's key financial metrics:
- Market Cap: $2.913 trillion
- P/E Ratio: 31.55
- Dividend Yield: 85.00%
- 52-Week Range: $344.79 - $468.35
- Revenue: $261.80 billion
- Profit Margin: 35.43%
- Return on Equity: 34.29%

Let me know if you'd like more details or information on another company!


==================================================
QUERY: What are the companies we've looked at so far?
==================================================

RESPONSE:
We haven't looked at any specific companies yet. If you have certain companies in mind, please let me know, and I can provide information about them!

But wait! What about the last query? Why does it say “We haven’t looked at any specific companies yet”? Ah, because it does not have memory (YET)! Let’s fix that in the next chapter.

4.7 Key Takeaways

In this chapter, we’ve:

  • Installed and set up the OpenAI Agent SDK
  • Adapted our financial tools for use with the SDK
  • Created a basic agent that can answer financial questions
  • Tested the agent with different types of queries

This implementation represents the “Brain” and “Action” component of our ABC Framework. The Agent SDK provides a powerful reasoning engine that can understand user queries, select appropriate tools, and generate natural language responses.

In the next chapter, we’ll enhance our agent with “Context” by adding memory capabilities, allowing it to maintain context across multiple interactions.