Skip to content
GPT-4.5 Function Calling
Creating Single Tool Calling
Defining get_stock_price
Python Function
get_stock_price
Python Function!pip install yahooquery -q
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}"
Define the tool with the get_stock_price
function
get_stock_price
functiontools = [{
"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 get_stock_price function
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)
Execute the get_stock_price function with the provided ticker
tool_call = completion.choices[0].message.tool_calls[0]
args = json.loads(tool_call.function.arguments)
result = get_stock_price(args["ticker"])
print(result)
Append both the model's function call and our tool result to the conversation
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 so it can incorporate the tool result
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)
Creating the Multiple Tool Calling