Skip to main content

openai-functools

openai-functools is a Python library designed to enhance the functionality of OpenAI's supported models for function calling, ref. the OpenAI official docs. This library focuses on generating the function metadata JSON automatically by wrapping existing Python functions in our decorator, or by registering them with our orchestrator. This removes the need for you to manually create and manage the JSON structures required for function calling in these models.

Why openai-functools

The image below illustrates the reduction of code which needs to be manually written. The snippets in green are interchangeable with use of our library.

example

?... So what is OpenAI Function Calling?

OpenAI function calling provides a powerful mechanism to extend the capabilities of AI models, like gpt-3.5-turbo-0613 and gpt-4-0613. In an API call, these models can understand a set of functions described to them and generate JSON outputs that adhere to the defined function signatures.

These models don't actually perform the function calls - they merely generate the JSON data that you can use in your code to call these functions. This ability allows for a wide range of applications, such as creating chatbots that call external APIs, converting natural language into API calls, and extracting structured data from text.

Typical openai functions flow:

openai-functions-flow

ref. the OpenAI official docs.

Installation

This package is hosted on PyPI and can be installed with pip:

pip install openai-functools

Alternatively, you can clone this repository and install with Poetry:

git clone https://github.com/Jakob-98/openai-functools.git
cd openai-functools
poetry install

Ensure your environment variable OPENAI_API_KEY is set.

Usage

This library is designed to streamline the usage of OpenAI's language models by simplifying the function metadata creation process. The following sections will walk you through a basic usage of openai-functools, including a traditional manual approach and our enhanced automatic approach using the openai_function decorator.

Manual Approach

Traditionally, you'd define a function, like get_current_weather, and then manually create a JSON structure that describes this function. The structure includes the function name, description, and parameters it takes, as well as the types of these parameters.

def get_current_weather(location, unit="fahrenheit"):
    weather_info = {
        "location": location,
        "temperature": "72",
        "unit": unit,
        "forecast": ["sunny", "windy"],
    }
    return json.dumps(weather_info)

def run_conversation():
    messages = [{"role": "user", "content": "What's the weather like in London?"}]
    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"],
            },
        }
    ]
    # Proceed with calling openai, invoking the function using the response, etc..

Automated Approach using openai-functools

The openai-functools library simplifies the process by automatically generating the necessary JSON structure. You just need to import our package and wrap your function with the openai_function decorator. Here's how it works:

import json
from openai_functools import openai_function

@openai_function
def get_current_weather(location, unit="fahrenheit"):
    weather_info = {
        "location": location,
        "temperature": "72",
        "unit": unit,
        "forecast": ["sunny", "windy"],
    }
    return json.dumps(weather_info)

def run_conversation():
    messages = [{"role": "user", "content": "What's the weather like in London?"}]
    functions = [
        get_current_weather.openai_metadata
    ]

As you can see, our openai_function decorator allows you to focus more on the logic of your function, while the tedious task of preparing function metadata is taken care of automatically.

Using the Orchestrator

The orchestrator in openai-functools simplifies the task of managing multiple registered functions and/or methods and automates the generation of OpenAI function descriptions. Below is a guide on how to use it.

from openai_functools import FunctionsOrchestrator

def get_current_weather(location, unit="fahrenheit"):
    """Get the current weather forecast in a given location"""
    # ... Implementation here

def get_weather_next_day(location, unit="fahrenheit"):
    """Get the weather forecast for the next day in a given location"""
    # ... Implementation here

orchestrator = FunctionsOrchestrator()
orchestrator.register_all([get_current_weather, get_weather_next_day])
# ...

Registering Functions

Functions can be registered using the register_all or register method as shown in the code snippet above. register_all accepts a list of functions, while register is used to register a single function.

Registering Instances

All methods of an instance can be registered using the register_instances_all or register_instance method and individual methods can be registered using regular function registration. An example of instance registration can be seen below.

from openai_functools import FunctionsOrchestrator

class WeatherService:
    def get_current_weather(location, unit="fahrenheit"):
        """Get the current weather forecast in a given location"""
        # ... Implementation here

weatherService = WeatherService()
orchestrator = FunctionsOrchestrator()

# Register all methods of the class
orchestrator.register_instance(weatherService)

# Register individual methods of the class
orchestrator.register_all([weatherService.get_current_weather])
# ...

Parallel function calling

Parallel function calling is a feature supported in certain models. Calling parallel functions is supported with the orchestrator. For this, use orchestrator.generate_tools_descriptions(). See the orchestrator parallel example for more details.

Creating and Using Function Descriptions

Function descriptions are automatically created based on the registered functions using create_function_descriptions method. These descriptions can then be passed to the OpenAI ChatCompletion.create method.

response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo-0613",
    messages=[{"role": "user", "content": "What's the weather like in Boston?"}],
    functions=orchestrator.create_function_descriptions(),
    function_call="auto",
)

Calling Functions Based on the OpenAI Response

The call_function method is used to call a function based on the OpenAI response. It fetches the function call data from the response, finds the matching function from the registered functions, and calls it with the provided arguments.

function_results = orchestrator.call_function(response)

This process can be repeated for subsequent interactions with the OpenAI model, allowing easy use of multiple functions in a conversational context.

response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo-0613",
    messages=[{"role": "user", "content": "What's the weather like in Boston tomorrow?"}],
    functions=orchestrator.create_function_descriptions(),
    function_call="auto",
)
function_results = orchestrator.call_function(response)

Using docstrings to enhance metadata

By using docstrings in your functions, we are able to extract more information to fill in the descriptions of the function and its properties. This will automatically be added to the openai function metadata, and will help the model better understand the functions and parameters.

Currently, only "reStructuredText" (reST) is supported by default, although this can be extended in the future (feel free to contribute!). Under the hood we make use of docstring parser to enable this.

Examples

Several examples can be found in the examples directory of this repository.

  1. The Maintenance app usecase is the recommended example to analyse, it shows the power of the library in a (spoofed) real-world setting.
  2. The Naive approach example shows how to call openai-functions without use of the library.
  3. The Simple example is similar to the naive approach, but makes use our decorator.
  4. The Orchestrator example shows how one can use the orchestrator class.

Contributing

We welcome contributions to openai-functools! Please see our contributing guide for more details.

Support

For support with openai-functools, please open an issue on this GitHub repository. We will do our best to assist you.

License

openai-functools is licensed under the MIT license. See the LICENSE file for details.

Metadata

Release files for openai_functools 1.1.131

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for openai_functools 1.1.131
File Size Uploaded
openai_functools-1.1.131.tar.gz 10.9 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for openai_functools 1.1.131
File Interpreter ABI Platform
openai_functools-1.1.131-py3-none-any.whl Python 3 none any Details

Total release size: 20.9 kB

Release files / openai_functools-1.1.131.tar.gz

Download URL openai_functools-1.1.131.tar.gz
Size 10.9 kB
Tags Source
SHA-256 checksum
How to use checksums
7c280b3d445d525bff081da4dbe6e40ec7065ee3cbf93f316527328bb03cbe7b
BLAKE2b-256 checksum
How to use checksums
76c41b010006ccc4151b78c9c147809a1ab6ce0d1b3b53eaca48f3d008fcec8f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.7.1 CPython/3.9.18 Linux/6.2.0-1018-azure

Release files / openai_functools-1.1.131-py3-none-any.whl

Download URL openai_functools-1.1.131-py3-none-any.whl
Size 10.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
387f07ba7e68e11d10088265cfd31ca20ea66747637f1514e5c3ee167f6c9f50
BLAKE2b-256 checksum
How to use checksums
66b3cff7823ead159613e9e4452c56175aa9e1309134616f80e09421a127d9a5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.7.1 CPython/3.9.18 Linux/6.2.0-1018-azure

Release history Release notifications | RSS feed

This release

1.1.131 This release

2 release files

1.0.82

2 release files

1.0.81

2 release files

1.0.80

2 release files

0.2.33

2 release files

0.2.30

2 release files

0.2.29

2 release files

0.2.28

2 release files

0.2.27

2 release files

0.2.26

2 release files

0.2.25

2 release files

0.2.24

2 release files

0.2.23

2 release files

0.2.20

2 release files

0.2.19

2 release files

0.2.18

2 release files

0.2.17

2 release files

0.2.14

2 release files

0.2.13

2 release files

0.2.12

2 release files

0.2.11

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page