


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:
- API Integration: Works with Chat Completions, Assistants, and Batch APIs for seamless application integration.
- Structured Outputs: Returns structured data (JSON), ideal for interacting with systems needing specific data formats.
- Vision Capabilities: Accepts image inputs (though not multimodal outputs like video or audio).
- Advanced Functionalities: Simplifies complex workflows by suggesting or invoking functions in your code, automating tasks and integrating AI decision-making.
(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
Copy after login -
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}"
Copy after login -
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 } }]
Copy after login -
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
Copy after login -
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
Copy after login -
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)}"
Copy after login -
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Meta's Llama 3.2: A Leap Forward in Multimodal and Mobile AI Meta recently unveiled Llama 3.2, a significant advancement in AI featuring powerful vision capabilities and lightweight text models optimized for mobile devices. Building on the success o

Hey there, Coding ninja! What coding-related tasks do you have planned for the day? Before you dive further into this blog, I want you to think about all your coding-related woes—better list those down. Done? – Let’

This week's AI landscape: A whirlwind of advancements, ethical considerations, and regulatory debates. Major players like OpenAI, Google, Meta, and Microsoft have unleashed a torrent of updates, from groundbreaking new models to crucial shifts in le

Shopify CEO Tobi Lütke's recent memo boldly declares AI proficiency a fundamental expectation for every employee, marking a significant cultural shift within the company. This isn't a fleeting trend; it's a new operational paradigm integrated into p

Introduction Imagine walking through an art gallery, surrounded by vivid paintings and sculptures. Now, what if you could ask each piece a question and get a meaningful answer? You might ask, “What story are you telling?

Introduction OpenAI has released its new model based on the much-anticipated “strawberry” architecture. This innovative model, known as o1, enhances reasoning capabilities, allowing it to think through problems mor

SQL's ALTER TABLE Statement: Dynamically Adding Columns to Your Database In data management, SQL's adaptability is crucial. Need to adjust your database structure on the fly? The ALTER TABLE statement is your solution. This guide details adding colu

Meta's Llama 3.2: A Multimodal AI Powerhouse Meta's latest multimodal model, Llama 3.2, represents a significant advancement in AI, boasting enhanced language comprehension, improved accuracy, and superior text generation capabilities. Its ability t
