top of page

OpenAI Functions: A Beginner's Guide


Introduction

OpenAI Functions is a powerful new feature of the OpenAI API that allows developers to call custom functions from within their code. This can be used to perform a wide variety of tasks, such as:

  • Calculating complex mathematical expressions

  • Parsing and manipulating data

  • Making API calls to other services

  • Generating creative content

How it works

In order to use OpenAI functions we need to you json format, so you can use any programming language that support json to use the OpenAI functions. For this particular blog we going to using python and we are going to use a Yahoo Finance library to get past history of a stock using the symbol of the company.


Before we proceed with the code we need to make sure we have the required libraries for this and have also provided the commands to install

  • OpenAI

pip install openai
  • Yahoo Finance

pip install yahoo_fin
  • Other Standard Python Libraries - JSON,

Next we will import the required libraries :

import os
import openai
import json
import yahoo_fin.stock_info as si
import pandas

Now we will have to set the OpenAI API key using the following code :

openai.api_key = ''

Then we will proceed with the main function that we can use to get the historical data for any particular stock from yahoo finance :

def get_historical_data(ticker_symbol):
  """This function makes an API call to a stock market service and returns the historical data for the stock"""
  quote_table = si.get_data(ticker_symbol)
  return quote_table

Now we have to define the function for OpenAI this is format that we have to follow for more information click here. Such function will have to be within a list so that it can be passed to OpenAI models.

Each function will have to be in a json format as given in the example below, here first we have to name the functions, then provide a description for this function which is the important part as Model will read this to understand the purpose of this function. Then we define the parameters we have to extract from the input text.

  1. We extract the Company Name then we will have to define the type of data we have to expect for this variable and the description of this variable. Again the description is the key as it will read it to understand what to extract from the given user input

  2. We now extract the symbol of the company which we are going to use to query the particular API to get historical data

stock_functions = [
    {
        'name': 'extract_stock_symbol',
        'description': 'Get the stock symbol from the input text, if not provided please ask the user',
        'parameters': {
            'type': 'object',
            'properties': {
                'Company Name': {
                    'type': 'string',
                    'description': 'Name of the company'
                },
                'symbol': {
                    'type': 'string',
                    'description': 'symbol of stock'
                }
                
            }
        }
    }
]

Now that defined the function for the OpenAI, we are going to define a function to chat with the model.

messages = []

def chat_models(user_input, messages = messages):
    
    response = openai.ChatCompletion.create(
        model = 'gpt-3.5-turbo',
        messages = [{'role': 'user', 'content': user_input}],
        functions=stock_functions,
    )
    messages.append({'role': 'user', 'content': user_input})
    messages.append({"role": "assistant", "content": response['choices'][0]['message']})
    
    return response, messages

Now we will define a function to tie up all the functionalities into a single function for us to use directly and after this if we type the following user_input

complete_chat_api('Historical Data of Apple company, Stock symbol is AAPL')

We will get the following output:

As you can see we are getting a Final Output as a Pandas Dataframe which we can use directly to get historical data for any stock. This is a basic example, some of the other example you can try are :

  • A chatbot that can answer questions about the weather by calling a weather API.

  • A financial trading bot that can make trades based on the latest news by calling a news API.

  • A creative writing tool that generates poems or stories by calling a language model.

  • A website that provides real-time translation by calling a translation API.

  • A software application that helps users with their taxes by calling an accounting API.

Some of the Benefits of using OpenAI Functions are :

  • Increased flexibility: OpenAI Functions allows developers to perform a wider range of tasks than is possible with the standard OpenAI API.

  • Improved performance: OpenAI Functions can be used to improve the performance of applications by offloading computationally expensive tasks to external services.

  • Reduced development time: OpenAI Functions can save developers time by eliminating the need to write custom code for common tasks.

  • Increased reliability: OpenAI Functions can help to improve the reliability of applications by making them less dependent on a single source of data or computation.

OpenAI Functions is a powerful tool that can be used to improve the functionality and performance of applications. It is a valuable resource for developers who are looking to build more sophisticated and efficient applications.

If you need any help in developing such OpenAI functions or any other topics related to OpenAI API, ChatGPT feel free to contact us at contact@codersarts.com







bottom of page