Skip to main content

Helper functions to generate OpenAI GPT function calling requests.

Project description

OpenAI Function Calling

GitHub Actions Build Status PyPi Package Version

Helper functions to generate JSON schema dicts for OpenAI ChatGPT function calling requests. See the official Function Calling reference for more information.

Installation

Install from PyPi with:

pip install openai-function-calling

The openai-function-calling package does come with the openai package. It must be installed separately with pip install openai

Usage

Auto-Infer the Function Definition (Beta)

Automatically infer your function name, description, and parameters given a reference to the function. A Function instance is returned which can be converted to JSON schema with .to_json_schema() and then passed to the OpenAI chat completion API:

from typing import Any, Callable
from openai_function_calling import FunctionInferrer
import openai
import json

# Define example functions.

def get_current_weather(location: str, unit: str = "fahrenheit") -> str:
    """Get the current weather and return a summary."""
    return f"It is currently sunny in {location} and 75 degrees {unit}."


def get_tomorrows_weather(location: str, unit: str = "fahrenheit") -> str:
    """Get the weather for tomorrow and return a summary."""
    return f"Tomorrow it will be rainy in {location} and 60 degrees {unit}."

# Infer the function definitions.
get_current_weather_function = FunctionInferrer.infer_from_function_reference(
    get_current_weather
)

get_tomorrows_weather_function = FunctionInferrer.infer_from_function_reference(
    get_tomorrows_weather
)

# Get the function to call from ChatGPT (you would normally have more than one).
response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo-0613",
    messages=[
        {
            "role": "user",
            "content": "What will the weather be like in Boston, MA today?",
        }
    ],
    functions=[
        # Convert the functions to JSON schema.
        get_current_weather_function.to_json_schema(),
        get_tomorrows_weather_function.to_json_schema(),
    ],
)

Define Functions with Objects

Define your function definitions using typed classes Function and Parameter which automatically convert to JSON schema with .to_json_schema methods. See an example below:

from openai_function_calling import Function, FunctionDict, Parameter, JsonSchemaType


def get_current_weather(location: str, unit: str) -> str:
    """Do some stuff in here."""


# Define the function.
get_current_weather_function = Function(
    "get_current_weather",
    "Get the current weather",
    [
        Parameter(
            name="location",
            type=JsonSchemaType.STRING,
            description="The city and state, e.g. San Francisco, CA",
        ),
        Parameter(
            name="unit",
            type=JsonSchemaType.STRING,
            description="The temperature unit to use.",
            enum=["celsius", "fahrenheit"],
        ),
    ],
)

# Convert to a JSON schema dict to send to OpenAI.
get_current_weather_function_schema = get_current_weather_function.to_json_schema()

Convert Functions to OpenAI Compatible JSON

from openai import OpenAI
from openai.types.chat import (
    ChatCompletion,
    ChatCompletionUserMessageParam,
)
from openai_function_calling.tool_helpers import ToolHelpers


# Define our functions.
def get_current_weather(location: str, unit: str) -> str:
    """Get the current weather and return a summary."""
    return f"It is currently sunny in {location} and 75 degrees {unit}."


def get_tomorrows_weather(location: str, unit: str) -> str:
    """Get tomorrow's weather and return a summary."""
    return f"It will be rainy tomorrow in {location} and around 65 degrees {unit}."


openai_client = OpenAI()

# Send the query and our function context to OpenAI.
response: ChatCompletion = openai_client.chat.completions.create(
    model="gpt-3.5-turbo-1106",
    messages=[
        ChatCompletionUserMessageParam(
            role="user", content="What's the weather in Boston MA?"
        ),
    ],
    tools=ToolHelpers.infer_from_function_refs(
        [get_current_weather, get_tomorrows_weather]
    ),
    tool_choice="auto",
)

Examples

To run the examples, set the environment variable OPENAI_API_KEY to your OpenAI API key. For example:

export OPENAI_API_KEY=SOME_KEY_VALUE

# or when running an example

OPENAI_API_KEY=SOME_KEY_VALUE python examples/weather_functions.py

Make sure to also follow all instructions in the Installation section.

See complete examples in the ./examples folder.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

openai_function_calling-2.0.0.tar.gz (8.1 kB view details)

Uploaded Source

Built Distribution

openai_function_calling-2.0.0-py3-none-any.whl (9.3 kB view details)

Uploaded Python 3

File details

Details for the file openai_function_calling-2.0.0.tar.gz.

File metadata

  • Download URL: openai_function_calling-2.0.0.tar.gz
  • Upload date:
  • Size: 8.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.6.1 CPython/3.11.5 Darwin/23.2.0

File hashes

Hashes for openai_function_calling-2.0.0.tar.gz
Algorithm Hash digest
SHA256 0679b01550891dcbbeaa5350a3e6ebad7a4694d01b8e77ee60a360c5e9ffecfa
MD5 7bac3fb7ae3d6aaf85af318fcfe4cd6b
BLAKE2b-256 73b59ec63580726f0712efee3845d95b0058cea9b53e8c4b4fa013d5e82a4fba

See more details on using hashes here.

File details

Details for the file openai_function_calling-2.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for openai_function_calling-2.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 fa4fb4aa36f67c760a76bb835f35774799977ca91e4ce964a3fbf59f4fa3c027
MD5 b680c1047fc19ff2426b08b57d6651e0
BLAKE2b-256 6fb53b804a316721ae04f56ab9b76d338670be1223becb02a11e215e95fd059e

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page