course
GPT-4.5 Function Calling Tutorial: Extract Stock Prices and News With AI
Large language models (LLMs) often struggle to consistently generate structured outputs, such as JSON, even when using advanced prompt engineering techniques. While prompt engineering can improve results, it is not foolproof—errors can still occur during testing, leading to occasional failures. So, how can you ensure accurate and reliable structured outputs every time?
Function calling in LLMs refers to the ability of these models to produce structured data responses, typically in the form of JSON objects. This feature enables LLMs to go beyond simple text generation and interact with external systems, APIs, and tools. By leveraging function calling, LLMs can perform more complex, context-driven tasks while maintaining the required structure and accuracy.
In this tutorial, we will learn how to use GPT-4.5, the most accurate and factual model, to create a function-calling script. First, we will implement a single function to extract stock prices from the internet. Then, we will add another function, enabling the LLM to choose between multiple tools and select the most appropriate one based on the user prompt.
By the end of this tutorial, you will learn how to build your own intelligent application that can provide stock prices for any company and also deliver news feeds.
Image from author
GPT-4.5's Function Calling Capabilities
GPT-4.5, the latest model from OpenAI, introduces several advanced features, including enhanced function calling capabilities. These capabilities are designed to improve the model's ability to interact with external systems and perform complex tasks by invoking specific functions based on user inputs.
Source: Model - OpenAI API
Here are key features of GPT-4.5's Function Calling:
1. Integration with APIs
GPT-4.5 supports function calling through the Chat Completions API, Assistants API, and Batch API. This allows developers to seamlessly integrate the model into their applications, enabling it to perform tasks such as data retrieval, processing, and even executing commands within a software environment.
2. Structured outputs
The model can return structured outputs, such as JSON, which is particularly useful for developers who need the model to interact with other systems or tools that require specific data formats.
3. Vision capabilities
While GPT-4.5 does not support multimodal outputs like voice or video, it does support vision capabilities through image inputs. This allows the model to process and analyze visual data, which can be combined with function calling to perform tasks that involve both text and image data.
4. Advanced functionalities
The function calling feature in GPT-4.5 is designed to simplify complex workflows by allowing the model to suggest or invoke functions written in your code. This can be particularly useful for automating repetitive tasks or integrating AI-driven decision-making into existing software systems.
Discover all the details about the new OpenAI model by reading the blog GPT 4.5: Features, Access, GPT-4o Comparison & More.
GPT-4.5 Single Function Calling
We will now build a simple function-calling system using the GPT-4.5 model and the Yahooquery library. The Yahooquery library will help us extract any stock-related data from Yahoo Finance.
Our solution will allow users to ask questions about stock prices, triggering a specific function that retrieves the stock price from the internet and generates a response. It's that simple.
We will start by installing the openai
and yahooquery
libraries using the PIP command.
!pip install openai yahooquery -q
Creating a stock price function
Create a Python function that takes a ticker (e.g., AAPL) and returns the price of that ticker. It uses yahooquery
in the backend to extract relevant data.
from openai import OpenAI
import json
from yahooquery import Ticker
def get_stock_price(ticker):
try:
# Create a Ticker object for the provided ticker symbol
t = Ticker(ticker)
# Retrieve the price data
price_data = t.price
# Check if we received valid data for the ticker
if ticker in price_data and price_data[ticker].get("regularMarketPrice") is not None:
price = price_data[ticker]["regularMarketPrice"]
else:
return f"Price information for {ticker} is unavailable."
except Exception as e:
return f"Failed to retrieve data for {ticker}: {str(e)}"
return f"{ticker} is currently trading at ${price:.2f}"
Defining the tools using the function
The OpenAI client doesn't understand the Python function, so we will need to create a tool using the list of dictionaries. We must provide the necessary name, description, and output type.
Whenever this function is invoked, it will extract the ticker name from the prompt and return it in a structured format.
tools = [{
"type": "function",
"function": {
"name": "get_stock_price",
"description": "Get current stock price for a provided ticker symbol from Yahoo Finance using the yahooquery Python library.",
"parameters": {
"type": "object",
"properties": {
"ticker": {"type": "string"}
},
"required": ["ticker"],
"additionalProperties": False
},
"strict": True
}
}]
Let the model decide if it should call the function
Let’s test our recently created OpenAI function. Provide the chat completion with the user message, model name, and the tools.
client = OpenAI()
messages = [{"role": "user", "content": "What's the current price of Meta stock?"}]
completion = client.chat.completions.create(
model="gpt-4.5-preview",
messages=messages,
tools=tools,
)
print(completion.choices[0].message.tool_calls)
As we can see, GPT-4.5 accurately invoked the get_stock_price
and returned the correct ticker (META).
[ChatCompletionMessageToolCall(id='call_uVGbahRiMnn4AkOJYbv8gfIV', function=Function(arguments='{"ticker":"META"}', name='get_stock_price'), type='function')]
Execute the function with the provided ticker
We can now provide this ticker to our get_stock_price
Python function.
tool_call = completion.choices[0].message.tool_calls[0]
args = json.loads(tool_call.function.arguments)
result = get_stock_price(args["ticker"])
print(result)
As a result, you receive a response that includes the ticker name and its corresponding price.
META is currently trading at $640.00
You can stop here, but to provide a proper answer in natural language, you have to pass the results to the chat completion again.
Appending the function call and tool result
We will append the generated response from the previous conversation and also include tool calling with tool ID and tool results.
messages.append(completion.choices[0].message) # Model's function call message
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": str(result)
})
Send the updated conversation back to the model
Run the chat completion again with the message that includes tools calling content.
completion_2 = client.chat.completions.create(
model="gpt-4.5-preview",
messages=messages,
tools=tools,
)
# The final model response incorporating the stock price information
print(completion_2.choices[0].message.content)
As you can see, we got the proper result.
The current price of Meta stock (META) is $640.00.
You might think this is a useless step, but when you have a complex output, this step will help you understand the results in plain English instead of JSON format results.
If you are confused about the OpenAI API and want to learn more, consider taking the OpenAI Fundamentals career track to learn how to use the OpenAI API for prompting OpenAI's GPT and Whisper models.
GPT4.5 Multiple Function Calling
Now, we will learn how to add another function to our AI system so that GPT-4.5 can automatically decide which function to invoke based on the user prompt. We are adding a new feed function that will return the top 3 news articles along with the links for the specified ticker.
Start by installing the feedparser
library using the pip command. We will use this library to extract the headlines for the specified ticker.
!pip install feedparser -q
Define the stock news function
Create the get_stock_news
Python function that will take the ticker as input and return the top three news headlines with their links.
import feedparser
def get_stock_news(ticker):
# Construct the RSS feed URL for the given ticker.
rss_url = f"https://feeds.finance.yahoo.com/rss/2.0/headline?s={ticker}®ion=US&lang=en-US"
try:
feed = feedparser.parse(rss_url)
if not feed.entries:
return f"No news found for {ticker}."
# Extract the top 3 news items (title and link)
news_items = []
for entry in feed.entries[:3]:
title = entry.get("title", "No Title")
link = entry.get("link", "No Link")
news_items.append(f"{title} ({link})")
news_str = "\n".join(news_items)
except Exception as e:
return f"Failed to retrieve news for {ticker}: {str(e)}"
return f"Latest news for {ticker}:\n{news_str}"
get_stock_news("AAPL")
We gathered the top three headlines about Apple with appropriate links.
'Latest news for AAPL:\nNvidia AI Server Maker Hon Hai Posts 25% Jump in Two-Month Sales
(https://finance.yahoo.com/news/nvidia-ai-server-maker-hon-075011863.html?.tsrc=rss)\nFoxconn says February revenue rose 56.43% y/y
(https://finance.yahoo.com/news/foxconn-says-february-revenue-rose-074433615.html?.tsrc=rss)\nApple Inc. (AAPL): Among the Best Stocks To Invest In According to Billionaires
(https://finance.yahoo.com/news/apple-inc-aapl-among-best-051548210.html?.tsrc=rss)'
Define multiple tools for stock price and news
We now need to add another OpenAI function called get_stock_news
with the proper description and output.
tools = [
{
"type": "function",
"function": {
"name": "get_stock_price",
"description": "Get current stock price for a provided ticker symbol using yahooquery.",
"parameters": {
"type": "object",
"properties": {
"ticker": {"type": "string"}
},
"required": ["ticker"],
"additionalProperties": False
},
"strict": True
}
},
{
"type": "function",
"function": {
"name": "get_stock_news",
"description": "Get the latest news for a provided ticker symbol by parsing the Yahoo Finance RSS feed using feedparser.",
"parameters": {
"type": "object",
"properties": {
"ticker": {"type": "string"}
},
"required": ["ticker"],
"additionalProperties": False
},
"strict": True
}
}
]
Let the model decide if it should call one or both functions
Let’s try to test out the function by asking GPT-4.5 about Google stocks and the latest news about Google.
messages = [{
"role": "user",
"content": "What's the current price of Google stock and can you show me the latest news about it?"
}]
completion = client.chat.completions.create(
model="gpt-4.5-preview",
messages=messages,
tools=tools,
)
completion.choices[0].message.tool_calls
As we can see, it has invoked both functions for stock prices and the latest news.
[ChatCompletionMessageToolCall(id='call_zfcRJ4EcIUUqHCcN8SErjeoi', function=Function(arguments='{"ticker": "GOOGL"}', name='get_stock_price'), type='function'),
ChatCompletionMessageToolCall(id='call_jBv8TlSPOyFKcRWHwByxLMb4', function=Function(arguments='{"ticker": "GOOGL"}', name='get_stock_news'), type='function')]
Saving the function call result
The problem is that both functions return the ticker as a result. We have to come up with an if-else statement to determine which function is invoked. We will store the results of the function in the dictionary.
# The model returns function call requests.
tool_calls = completion.choices[0].message.tool_calls
# Execute each function call based on the tool the model requested
tool_results = {}
for tool_call in tool_calls:
func_name = tool_call.function.name
args = json.loads(tool_call.function.arguments)
if func_name == "get_stock_price":
tool_results["price"] = get_stock_price(args["ticker"])
elif func_name == "get_stock_news":
tool_results["news"] = get_stock_news(args["ticker"])
Appending the function call and tool results
We will now append the previously generated results and the function result with the tool ID.
messages.append(completion.choices[0].message) # Append the model's function call message
for tool_call in tool_calls:
func_name = tool_call.function.name
result_content = tool_results.get("price") if func_name == "get_stock_price" else tool_results.get("news")
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": result_content
})
Send the updated conversation back to the model
When we pass the resulting message to the GPT-4.5, it has generated amazing results that are perfectly reasonable.
from IPython.display import display, Markdown
completion_2 = client.chat.completions.create(
model="gpt-4.5-preview",
messages=messages,
tools=tools,
)
# The final model response incorporates both stock price and news.
Markdown(completion_2.choices[0].message.content)
We obtained the Google stock price and links to the top news about Google.
The source code and outputs are available in the DataLab Workspace. All you have to do is add your own OpenAI API key to the environment variable, and you can run everything on your own.
Conclusion
We have forced large language models to generate structured output and then pass it to an API or another Python function to execute a specific task. Advanced AI, like GPT-4.5, can use multiple services or APIs to generate highly integrated responses.
In the future, we will use function calling and agents to control everything around us; simply send a voice command to your AI, and it will invoke the necessary tools based on your command and make changes to the system.
We have GPT-4.5, but many AI experts are waiting for GPT-5, which is expected to be closer to AGI. You can learn all about the upcoming model by reading the blog Everything We Know About GPT-5 .

As a certified data scientist, I am passionate about leveraging cutting-edge technology to create innovative machine learning applications. With a strong background in speech recognition, data analysis and reporting, MLOps, conversational AI, and NLP, I have honed my skills in developing intelligent systems that can make a real impact. In addition to my technical expertise, I am also a skilled communicator with a talent for distilling complex concepts into clear and concise language. As a result, I have become a sought-after blogger on data science, sharing my insights and experiences with a growing community of fellow data professionals. Currently, I am focusing on content creation and editing, working with large language models to develop powerful and engaging content that can help businesses and individuals alike make the most of their data.
Top DataCamp Courses
course
Working with the OpenAI API
course
Introduction to Embeddings with the OpenAI API

blog
GPT-4o Guide: How it Works, Use Cases, Pricing, Benchmarks
tutorial
GPT-4 Vision: A Comprehensive Guide for Beginners
tutorial
GPT-4.5 API Tutorial: Getting Started With OpenAI's API

François Aubry
8 min
tutorial
OpenAI Function Calling Tutorial
code-along
Natural Language Interfaces to Software with GPT-4o Function Calling
code-along