Home >Technology peripherals >AI >GPT-4.5 Function Calling Tutorial: Extract Stock Prices & News With AI
Large language models (LLMs) often struggle to reliably produce structured outputs like JSON, even with advanced prompting. While prompt engineering helps, it's not perfect, leading to occasional errors. This tutorial demonstrates how function calling in LLMs ensures accurate, consistent structured data.
Function calling lets LLMs generate structured data (usually JSON) and interact with external systems, APIs, and tools, enabling complex, context-aware tasks while maintaining accuracy. We'll use GPT-4.5, known for its accuracy, to build a function-calling script. First, we'll create a function to fetch stock prices; then, we'll add another to let the LLM choose between multiple tools based on the prompt. The final application will provide stock prices and news feeds.
Image from author
GPT-4.5's Function Calling Advantages:
GPT-4.5 enhances function calling, improving interaction with external systems and complex task handling. Key features include:
(See the blog "GPT 4.5: Features, Access, GPT-4o Comparison & More" for details on the OpenAI model.)
Single Function Calling (Stock Price):
We'll build a simple system using GPT-4.5 and the yahooquery
library (for Yahoo Finance data). Users ask about stock prices, triggering a function to retrieve and respond with the price.
Install Libraries:
!pip install openai yahooquery -q
Stock Price Function: This Python function takes a ticker symbol (e.g., AAPL) and returns its price.
from openai import OpenAI import json from yahooquery import Ticker def get_stock_price(ticker): try: t = Ticker(ticker) price_data = t.price 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: We create a tool definition (list of dictionaries) for OpenAI, specifying the function's name, description, and output type.
tools = [{ "type": "function", "function": { "name": "get_stock_price", "description": "Get current stock price from Yahoo Finance.", "parameters": { "type": "object", "properties": { "ticker": {"type": "string"} }, "required": ["ticker"], "additionalProperties": False }, "strict": True } }]
Invoke the Function: We send a user message to GPT-4.5, specifying the model and 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) # Shows function invocation
Execute and Return: We extract the ticker, run get_stock_price
, and print the result. Then, we refine the response by sending it back to the model for natural language formatting.
Multiple Function Calling (Stock Price and News):
We add a function to retrieve stock news using the feedparser
library.
Install feedparser
:
!pip install feedparser -q
Stock News Function: This function fetches the top three news headlines for a given ticker.
import feedparser def get_stock_news(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}." news_items = [f"{entry.title} ({entry.link})" for entry in feed.entries[:3]] return f"Latest news for {ticker}:\n{chr(10).join(news_items)}" except Exception as e: return f"Failed to retrieve news for {ticker}: {str(e)}"
Define Multiple Tools: We update the tools
list to include both functions.
Model Selection: We ask GPT-4.5 a question requiring both functions (e.g., "Google stock price and news"). GPT-4.5 will automatically choose and invoke the appropriate functions.
Result Handling: We handle the results from both functions, potentially using conditional logic based on the function names returned by the LLM. The results are then passed back to the LLM for a final, human-readable response.
Conclusion:
This tutorial demonstrates how function calling empowers LLMs to generate structured outputs and interact with external resources. This approach improves the reliability and accuracy of LLM-driven applications, paving the way for more sophisticated AI systems. Future advancements, like GPT-5, promise even greater capabilities in this area. The provided code snippets can be combined and expanded upon to create more complex and powerful applications.
The above is the detailed content of GPT-4.5 Function Calling Tutorial: Extract Stock Prices & News With AI. For more information, please follow other related articles on the PHP Chinese website!