Home Technology peripherals AI GPT-4.5 Function Calling Tutorial: Extract Stock Prices & News With AI

GPT-4.5 Function Calling Tutorial: Extract Stock Prices & News With AI

Mar 13, 2025 am 11:38 AM

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.

GPT-4.5 Function Calling Tutorial: Extract Stock Prices & News With AI

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:

  1. API Integration: Works with Chat Completions, Assistants, and Batch APIs for seamless application integration.
  2. Structured Outputs: Returns structured data (JSON), ideal for interacting with systems needing specific data formats.
  3. Vision Capabilities: Accepts image inputs (though not multimodal outputs like video or audio).
  4. 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.

  1. Install Libraries:

    !pip install openai yahooquery -q
    Copy after login
  2. 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
  3. 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
  4. 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
  5. 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.

  1. Install feedparser:

    !pip install feedparser -q
    Copy after login
  2. 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}&region=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
  3. Define Multiple Tools: We update the tools list to include both functions.

  4. 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.

  5. 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1253
29
C# Tutorial
1227
24
Getting Started With Meta Llama 3.2 - Analytics Vidhya Getting Started With Meta Llama 3.2 - Analytics Vidhya Apr 11, 2025 pm 12:04 PM

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

10 Generative AI Coding Extensions in VS Code You Must Explore 10 Generative AI Coding Extensions in VS Code You Must Explore Apr 13, 2025 am 01:14 AM

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&#8217

AV Bytes: Meta's Llama 3.2, Google's Gemini 1.5, and More AV Bytes: Meta's Llama 3.2, Google's Gemini 1.5, and More Apr 11, 2025 pm 12:01 PM

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

Selling AI Strategy To Employees: Shopify CEO's Manifesto Selling AI Strategy To Employees: Shopify CEO's Manifesto Apr 10, 2025 am 11:19 AM

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

A Comprehensive Guide to Vision Language Models (VLMs) A Comprehensive Guide to Vision Language Models (VLMs) Apr 12, 2025 am 11:58 AM

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?

GPT-4o vs OpenAI o1: Is the New OpenAI Model Worth the Hype? GPT-4o vs OpenAI o1: Is the New OpenAI Model Worth the Hype? Apr 13, 2025 am 10:18 AM

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

How to Add a Column in SQL? - Analytics Vidhya How to Add a Column in SQL? - Analytics Vidhya Apr 17, 2025 am 11:43 AM

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

3 Methods to Run Llama 3.2 - Analytics Vidhya 3 Methods to Run Llama 3.2 - Analytics Vidhya Apr 11, 2025 am 11:56 AM

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

See all articles