Skip to content

Instantly share code, notes, and snippets.

@eug
Last active October 23, 2023 00:29
Show Gist options
  • Save eug/c20409e2985988c1a4a11a05477bdcc3 to your computer and use it in GitHub Desktop.
Save eug/c20409e2985988c1a4a11a05477bdcc3 to your computer and use it in GitHub Desktop.
OpenAI Function Call Syntax Sugar
import json
import functools
class Property:
def __init__(self, name, descr_or_enum, required=False):
self.name = name
self.descr_or_enum = descr_or_enum
self.required = required
def to_dict(self):
key = "enum" if isinstance(self.descr_or_enum, list) else "description"
return {
self.name: {
"type": "string",
key: self.descr_or_enum
}
}
def _merge_dicts(a, b):
if a is None:
if b is None:
return {}
if not isinstance(b, Property):
return b.to_dict()
return b
if b is None:
if not isinstance(a, Property):
return a.to_dict()
return a
if not isinstance(a, dict):
a = a.to_dict()
if not isinstance(b, dict):
b = b.to_dict()
return {**a, **b}
class Function:
def __init__(self, name, description, parameters=[]):
self.name = name
self.description = description
self.parameters = parameters
def to_dict(self):
return {
"name": self.name,
"description": self.description,
"parameters": {
"type": "object", # is there another option?
"properties": functools.reduce(_merge_dicts, self.parameters, {}),
"required": [x.name for x in self.parameters if x.required]
}
}
def as_fc(functions):
return [fn.to_dict() for fn in functions]
if __name__ == '__main__':
#https://platform.openai.com/docs/guides/gpt/function-calling
print(json.dumps(as_fc([
Function("get_current_weather", "Get the current weather in a given location", [
Property("location", "The city and state, e.g. San Francisco, CA", required=True),
Property("unit", ["celsius", "fahrenheit"]),
])
]), indent=2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment