Skip to content

Instantly share code, notes, and snippets.

@jetnew
Created August 9, 2023 02:17
Show Gist options
  • Save jetnew/557f3b333f80acad138ff6d2da1136bb to your computer and use it in GitHub Desktop.
Save jetnew/557f3b333f80acad138ff6d2da1136bb to your computer and use it in GitHub Desktop.
Convert function to OpenAI function calling API format.
import json
import openai
from inspect import signature, Parameter
openai.api_key = "sk-"
def func2tool(func):
"""Convert a function into OpenAI function calling API format."""
assert func.__doc__, f"Function {func.__name__} must have a docstring."
return {
"name": func.__name__,
"description": func.__doc__,
"parameters": {
"type": "object",
"properties": {
p.name: {
"type": "number" if p.annotation == int else "string",
} for p in signature(func).parameters.values()
},
"required": [p.name for p in signature(func).parameters.values() if p.default == Parameter.empty]
}
}
def call(message, functions):
"""Call OpenAI function calling API."""
fns = {fn.__name__: fn for fn in functions}
function = openai.ChatCompletion.create(
model="gpt-4",
messages=[{"role": "system", "content": "Only use the functions you have been provided with."},
{"role": "user", "content": message}],
functions=[func2tool(fn) for fn in functions],
function_call="auto",
temperature=0
)["choices"][0]["message"]["function_call"]
fn = function["name"]
args = json.loads(function["arguments"])
return fns[fn], args
def add(x: int, y: int, z: int = 0):
"Adds x, y and optionally z"
return x + y + z
print(func2tool(add))
# {'name': 'add',
# 'description': 'Adds x, y and optionally z',
# 'parameters': {'type': 'object',
# 'properties': {'x': {'type': 'number'},
# 'y': {'type': 'number'},
# 'z': {'type': 'number'}},
# 'required': ['x', 'y']}}
fn, args = call("What's 3 plus 4?", [add])
print(fn, args)
# <function add at 0x78228d876b00> {'x': 3, 'y': 4}
print(fn(**args))
# 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment