Create a Python library that enables me to do the following. I want to add a decorator @openaifunc to python functions, and then call a function get_openai_funcs() that would return the following response:[{
"name": "<NAME_OF_THE_FUNCTION>",
"description": "<DESCRIPTION_OF_THE_FUNCTION>",
"parameters": {
"type": "object",
"properties": {
"": {
"type": "<PARAMETER1_TYPE>",
"description": "<DESCRIPTION_OF_PARAMETER1>",
},
"": {
"type": "<PARAMETER2_TYPE>",
"description": "<DESCRIPTION_OF_PARAMETER2>",
},
},
"required": [""],
},
}]The details in angle brackets should be automatically parsed from the function.
Assistant
The following is an implementation that might work for your scenario. This makes use of theinspectmodule in Python to extract details about the function's parameters, anddocstringsfor description. Thefunctoolsmodule is used to create the decorator without interfering with the original function's attributes.
User
what would the folder structure look like for a project that used this module? and how do I import the module to a project?
Assistant
Assuming that you'd like to put the code in a Python module namedopenai_decorator, you could structure your project like this:
The__init__.pyfile is used to indicate that a directory is a Python package, which means it can be imported as a module. In the simplest case, the__init__.pyfile can be completely empty.
However, you can use the__init__.pyfile to control what gets exposed to the outside when the package is imported. For instance, you can make theopenaifuncdecorator andget_openai_funcsfunction directly importable from theopenai_decoratorpackage, rather than from theopenai_decorator.openai_decoratormodule.
You can achieve this by adding the following lines to your__init__.py:
@openaifunc
def add_numbers(a: int, b: int):
"""
This function adds two numbers.
"""
return a + b
print(get_openai_funcs())
This makes your code cleaner and easier to use, as you don't need to import fromopenai_decorator.openai_decorator. Instead, you just import fromopenai_decorator.
User
Now the type is in the format "<class 'str'>". Could we change it to "string" like in the JSON spec?
Assistant
Yes, you can definitely do that. One way to achieve this is to map Python's types to the corresponding JSON schema types. Here's how you can modify theopenaifuncdecorator to do that:
# Get information about function parameters
params = inspect.signature(func).parameters
param_dict = dict()
for k, v in params.items():
# For simplicity, we assume all parameters are required
# In real case, we need to inspect default values to find out optional parameters
param_dict[k] = {
"type": str(v.annotation),
"description": "", # This would need to be manually added or extracted from docstring
}
openai_functions.append({
"name": func.__name__,
"description": inspect.cleandoc(func.__doc__ or ""),
"parameters": {
"type": "object",
"properties": param_dict,
"required": list(param_dict.keys()),
},
})
return wrapper
pythonCopy code@openaifunc
def add_numbers(a: int, b: int):
"""
This function adds two numbers.
"""
return a + b
@openaifunc
def say_hello(name: str):
"""
This function greets the user.
"""
return f"Hello, {name}!"
print(get_openai_funcs())
Please note that Python does not have a built-in way to obtain the description of parameters from function signatures. In the provided implementation, the description of each parameter is left empty. If you want to include this, you'll need to develop a way to encode this information, such as using a specific format in the function's docstring and parsing it.
Remember to handle the situation where the parameters don't have type annotations. The current code simply gets the annotation, which will beinspect._emptyif there is no annotation.
openai_decorator/is a package directory, containing an__init__.pyfile to signify it's a package, andopenai_decorator.pywhere the actual decorator code resides.
main.pyandother_module.pyare some Python scripts/modules in your project that use the decorator.
my_project/is the root directory of your project.
openai_decorator/is a package directory, containing an__init__.pyfile to signify it's a package, andopenai_decorator.pywhere the actual decorator code resides.
main.pyandother_module.pyare some Python scripts/modules in your project that use the decorator.
To use youropenai_decoratormodule inmain.pyorother_module.py, you'd import the decorator function andget_openai_funcsfunction like so:
@openaifunc
def add_numbers(a: int, b: int):
"""
This function adds two numbers.
"""
return a + b
@openaifunc
def say_hello(name: str):
"""
This function greets the user.
"""
return f"Hello, {name}!"
print(get_openai_funcs())
This is a simple structure. Depending on the complexity of your project, you may want to further subdivide your project into more packages or modules.
In a real project, you would also want to add more files likeREADME.md(describing the project),.gitignore(specifying files to ignore for version control),requirements.txtorPipfile(listing Python dependencies),setup.py(for packaging and distribution),tests/(containing test code), etc.
Lastly, make sure your project's root directory is in Python's path when you run your script. If you're running the script directly from the root directory, likepython main.py, it should work fine.
# Get information about function parameters
params = inspect.signature(func).parameters
param_dict = dict()
for k, v in params.items():
# Map python types to JSON schema types
param_type = type_mapping.get(v.annotation, "unknown")
param_dict[k] = {
"type": param_type,
"description": "", # This would need to be manually added or extracted from docstring
}
openai_functions.append({
"name": func.__name__,
"description": inspect.cleandoc(func.__doc__ or ""),
"parameters": {
"type": "object",
"properties": param_dict,
"required": list(param_dict.keys()),
},
})
return wrapper
def get_openai_funcs():
return openai_functions
In thetype_mappingdictionary, I have added a mapping from Python's built-in types to the JSON Schema's types. This mapping is then used to get the type of the parameters. Note that not all Python types are covered here. If a parameter's type is not in thetype_mappingdictionary, it defaults to "unknown".
This will result in the parameter type being "string" forstrparameters, "integer" forintparameters, etc. according to JSON Schema's types.