Delving into the Abyss: OpenAI API's Renaissance of Function Calling within the ChatGPT Realm

Delving into the Abyss: OpenAI API's Renaissance of Function Calling within the ChatGPT Realm
Photo by Wilhelm Gunkel / Unsplash

In the mesmerizing tapestry of technological evolution, OpenAI’s API emerges as a phoenix reborn, with its dazzling array of capabilities, one of which - function calling within ChatGPT - is the pièce de résistance. This article seeks to be your torchbearer as we delve into the labyrinthine depths of these recent augmentations.

Behold the Gateway:

OpenAI heralds a symphony of enhancements to its API, akin to a maestro’s grand opus. Among these, the function calling capability unfurls like a golden scroll, bridging the ethereal wisdom of ChatGPT with the tangible craft of external tools through well-orchestrated JSON objects.

The Heart of Function Calling

Imagine the ability to whisper to ChatGPT in the arcane language of JSON Schema, and summon functions at will. This alchemy enables developers to make ChatGPT conjure up JSON that resonates with the signature of the functions described.

Realms of Possibility:

  1. Chatbots as Sorcerers: Craft chatbots that channel external tools to answer queries. Ponder upon a chatbot that conjures weather forecasts through an incantation to an external weather API.
  2. Linguistic Alchemy: ChatGPT can transmute natural language into API calls or database queries, morphing “What tapestry does the sky weave today in Boston?” into get_current_weather(location: string, unit: 'celsius' | 'fahrenheit').
  3. Extracting Elixirs from Text: Envisage extracting structured data from a text’s sea, akin to distilling precious potions, using a function like extract_people_data(people: [{name: string, birthday: string, location: string}]).

Example

Below is an example of how function calling can be used to get the current weather in Boston:

import openai
import json
import os 

#use of an environment variable is safer than hard coding
openai.api_key = os.environ["OPENAI_API_KEY"] 

# Example dummy function hard coded to return the same weather
# In production, this could be your backend API or an external API
def get_current_weather(location, unit="fahrenheit"):
    """Get the current weather in a given location"""
    weather_info = {
        "location": location,
        "temperature": "72",
        "unit": unit,
        "forecast": ["sunny", "windy"],
    }
    return json.dumps(weather_info)


def run_conversation():
    # Step 1: send the conversation and available functions to GPT
    messages = [{"role": "user", "content": "What's the weather like in Boston?"}]
    functions = [
        {
            "name": "get_current_weather",
            "description": "Get the current weather in a given location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA",
                    },
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                },
                "required": ["location"],
            },
        }
    ]
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo-0613",
        messages=messages,
        functions=functions,
        function_call="auto",  # auto is default, but we'll be explicit
    )
    response_message = response["choices"][0]["message"]

    # Step 2: check if GPT wanted to call a function
    if response_message.get("function_call"):
        # Step 3: call the function
        # Note: the JSON response may not always be valid; be sure to handle errors
        available_functions = {
            "get_current_weather": get_current_weather,
        }  # only one function in this example, but you can have multiple
        function_name = response_message["function_call"]["name"]
        fuction_to_call = available_functions[function_name]
        function_args = json.loads(response_message["function_call"]["arguments"])
        function_response = fuction_to_call(
            location=function_args.get("location"),
            unit=function_args.get("unit"),
        )

        # Step 4: send the info on the function call and function response to GPT
        messages.append(response_message)  # extend conversation with assistant's reply
        messages.append(
            {
                "role": "function",
                "name": function_name,
                "content": function_response,
            }
        )  # extend conversation with function response
        second_response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo-0613",
            messages=messages,
        )  # get a new response from GPT where it can see the function response
        return second_response


print(run_conversation())

Chronicles of the Recent:

On the sun-kissed day of June 13, 2023, OpenAI unshackled new avatars of gpt-3.5-turbo and gpt-4, endowed with more potent function calling spells. Furthermore, the 16k context version of gpt-3.5-turbo emerged, with an embrace that stretches beyond the 4k version, coupled with price reductions akin to bounteous treasures.

The Guardrails of Safety:

With great power, comes the imperative for vigilance. The interplay between ChatGPT and external tools is a dance on a double-edged sword. It is crucial to be wary of the whispers from untrusted sources and to safeguard the sanctity of the applications.

In Parting:

This renaissance in OpenAI’s API, with the jewel of function calling in ChatGPT’s crown, heralds a new era. The harmonious symphony between ChatGPT and external tools is a gateway to realms uncharted, a tapestry woven with threads of imagination and ingenuity.

In the Scroll:

  1. Function Calling and Other API Updates - OpenAI Blog
  2. OpenAI API Adds Function Calling Support to ChatGPT - InfoQ News
  3. Function Calling Guide - OpenAI Platform Documentation

Note: Pythonic incantations, whispered in hushed tones, serve as illustrative examples of the spellbinding function calling within ChatGPT.