gptfunctionutil


Namegptfunctionutil JSON
Version 0.3.7.2 PyPI version JSON
download
home_page
SummaryA simple package for the purpose of providing a set of utilities that make it easier to invoke python functions and coroutines using OpenAI's GPT models.
upload_time2024-02-25 15:59:10
maintainer
docs_urlNone
author
requires_python>=3.10
licenseMIT License Copyright (c) 2023 CrosswaveOmega Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords openai function calling api gpt asyncio
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # GPT Function Calling Utility

The GPT Function Calling Utility is a Python package designed to streamline the process of calling Python methods using OpenAI's Function Calling API, without wrapping around the OpenAI library.

Please note that GPT Function Calling Utility does not directly make calls to OpenAI's API, but rather helps with function modeling and invocation when given a function_call field.

## Installation
```
python -m pip install -U gptfunctionutil

```
## Key Features

- **Simplified Function Modeling Via Inheritance**: This package utilizes subclasses decended from the `GPTFunctionLibrary` class that allows you to define sets of callable methods to be sent to OpenAI's Chat Completion endpoint.  `GPTFunctionLibrary` contains methods to create a json schema describing your functions, and to invoke said functions using the Function Call field returned with a call to chat/completions.

- **Decorate Invokable Functions, and Coroutines**: OpenAI's Function Calling Feature needs JSON schema to outline the name, description, and parameters of each invokable function.  This utility uses two decorators, (`@AILibFunction`) and (`@LibParam`), as well as type annotation to create this schema for functions you want to use with the API.
  + set a display name and description with (`@AILibFunction`).  You can also specify required parameters with this decorator, but it's not required.
  + apply small descriptions to arguments with (`@LibParam`), to inform the API on what it does.
  + (`@LibParamSpec`) can apply additional keywords depending on the type. (see https://json-schema.org/understanding-json-schema/index.html for details.)
  + You can decorate coroutines as well.


- **Parameter Typing and Descriptions:** To ensure clarity and facilitate proper function formatting, GPT Function Calling Utility requires that all parameters intended to be passed into the AI have an applied type;  strings, integers, floats, and bools.  The library utilizes a collection of converter objects to generate schema for each parameter based on type annotations.

- **Convert into complex types:** The utility is capable of converting some more complex data types into a json schema, such as datetimes and Literals.
   + Define Custom Converters to automatically use response arguments to initalize objects.
     +  (see examples/custom_converters.py for an example.)


- **Schema Generation for API Calls**: Before making a call to the OpenAI chat/completion endpoint, the utility has a `get_schema()` method to extract the formatted functions as a list of dictionaries. This schema is then passed as the `functions` field in the ChatCompletion call. If the AI determines that it should invoke a function call, you can pass the returned `function_call` field into the `call_by_dict(function_call)`(or `call_by_dict_async` if you're trying to call a decorated coroutine) method to call the corresponding function with the provided arguments.
   + The method also checks if there is a function by that name, falling back to a default response if something goes wrong.
   + Schema can also validate and convert responses returned from the chat/completions endpoint.

- **Integration with Discord.py**: This utility was intended to be used with life as a discord.py utility, and can be easily integrated with discord.py bots.
   + Simply import `gptfunctionutil` into your Discord bot project, and decorate your commands with `@LibParam` and `@AILibFunction`.  After passing the Commands into a GPTFunctionLibrary subclass with  `add_in_commands(your_bot_object_here)`, your bot commands will become invokable in the same way as a decorated GPTFunctionLibrary coroutine, provided you use the `call_by_dict_ctx` method.
     + (see examples/discord_bot.py for an example.)


## Usage Example

Using GPT Function Calling Utility with OpenAI to get the current time:

```python

from gptfunctionutil import GPTFunctionLibrary, AILibFunction, LibParam, LibParamSpec
from datetime import datetime
import openai
class MyLib(GPTFunctionLibrary):
    #Define methods here.
    @AILibFunction(name='get_time', description='Get the current time and day in UTC.')
    @LibParam(comment='An interesting, amusing remark.')
    def get_time(self, comment: str):
        # get the current time, with a small remark.
        return f"{comment}\n{str(datetime.now())}"

# Initialize the subclass somewhere in your code
mylib = MyLib()
client = openai.Client()

completion = client.chat.completions.create(
    model="gpt-3.5-turbo-1106",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        #This message will invoke get_time
        {"role": "user", "content": "Hello, get me the current time in UTC."}
    ],
    "tools"=: mylib.get_tool_schema(),
    "tool_choice"= 'auto',
)
message=completion.choices[0]['message']
if message.tool_calls:
    for tool in message.tool_calls:
        output = mylib.call_by_tool(tool)
        print(tool.name,output)
else:
    print(completion.choices[0].message.content)
```


            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "gptfunctionutil",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": "",
    "keywords": "OpenAI,Function Calling API,GPT,asyncio",
    "author": "",
    "author_email": "Crosswave Omega <xtream2pro@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/73/c1/d41765e35619a82acdf2d00765cbf6a18d7f629c457fc3c93163e1463e09/gptfunctionutil-0.3.7.2.tar.gz",
    "platform": null,
    "description": "# GPT Function Calling Utility\n\nThe GPT Function Calling Utility is a Python package designed to streamline the process of calling Python methods using OpenAI's Function Calling API, without wrapping around the OpenAI library.\n\nPlease note that GPT Function Calling Utility does not directly make calls to OpenAI's API, but rather helps with function modeling and invocation when given a function_call field.\n\n## Installation\n```\npython -m pip install -U gptfunctionutil\n\n```\n## Key Features\n\n- **Simplified Function Modeling Via Inheritance**: This package utilizes subclasses decended from the `GPTFunctionLibrary` class that allows you to define sets of callable methods to be sent to OpenAI's Chat Completion endpoint.  `GPTFunctionLibrary` contains methods to create a json schema describing your functions, and to invoke said functions using the Function Call field returned with a call to chat/completions.\n\n- **Decorate Invokable Functions, and Coroutines**: OpenAI's Function Calling Feature needs JSON schema to outline the name, description, and parameters of each invokable function.  This utility uses two decorators, (`@AILibFunction`) and (`@LibParam`), as well as type annotation to create this schema for functions you want to use with the API.\n  + set a display name and description with (`@AILibFunction`).  You can also specify required parameters with this decorator, but it's not required.\n  + apply small descriptions to arguments with (`@LibParam`), to inform the API on what it does.\n  + (`@LibParamSpec`) can apply additional keywords depending on the type. (see https://json-schema.org/understanding-json-schema/index.html for details.)\n  + You can decorate coroutines as well.\n\n\n- **Parameter Typing and Descriptions:** To ensure clarity and facilitate proper function formatting, GPT Function Calling Utility requires that all parameters intended to be passed into the AI have an applied type;  strings, integers, floats, and bools.  The library utilizes a collection of converter objects to generate schema for each parameter based on type annotations.\n\n- **Convert into complex types:** The utility is capable of converting some more complex data types into a json schema, such as datetimes and Literals.\n   + Define Custom Converters to automatically use response arguments to initalize objects.\n     +  (see examples/custom_converters.py for an example.)\n\n\n- **Schema Generation for API Calls**: Before making a call to the OpenAI chat/completion endpoint, the utility has a `get_schema()` method to extract the formatted functions as a list of dictionaries. This schema is then passed as the `functions` field in the ChatCompletion call. If the AI determines that it should invoke a function call, you can pass the returned `function_call` field into the `call_by_dict(function_call)`(or `call_by_dict_async` if you're trying to call a decorated coroutine) method to call the corresponding function with the provided arguments.\n   + The method also checks if there is a function by that name, falling back to a default response if something goes wrong.\n   + Schema can also validate and convert responses returned from the chat/completions endpoint.\n\n- **Integration with Discord.py**: This utility was intended to be used with life as a discord.py utility, and can be easily integrated with discord.py bots.\n   + Simply import `gptfunctionutil` into your Discord bot project, and decorate your commands with `@LibParam` and `@AILibFunction`.  After passing the Commands into a GPTFunctionLibrary subclass with  `add_in_commands(your_bot_object_here)`, your bot commands will become invokable in the same way as a decorated GPTFunctionLibrary coroutine, provided you use the `call_by_dict_ctx` method.\n     + (see examples/discord_bot.py for an example.)\n\n\n## Usage Example\n\nUsing GPT Function Calling Utility with OpenAI to get the current time:\n\n```python\n\nfrom gptfunctionutil import GPTFunctionLibrary, AILibFunction, LibParam, LibParamSpec\nfrom datetime import datetime\nimport openai\nclass MyLib(GPTFunctionLibrary):\n    #Define methods here.\n    @AILibFunction(name='get_time', description='Get the current time and day in UTC.')\n    @LibParam(comment='An interesting, amusing remark.')\n    def get_time(self, comment: str):\n        # get the current time, with a small remark.\n        return f\"{comment}\\n{str(datetime.now())}\"\n\n# Initialize the subclass somewhere in your code\nmylib = MyLib()\nclient = openai.Client()\n\ncompletion = client.chat.completions.create(\n    model=\"gpt-3.5-turbo-1106\",\n    messages=[\n        {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n        #This message will invoke get_time\n        {\"role\": \"user\", \"content\": \"Hello, get me the current time in UTC.\"}\n    ],\n    \"tools\"=: mylib.get_tool_schema(),\n    \"tool_choice\"= 'auto',\n)\nmessage=completion.choices[0]['message']\nif message.tool_calls:\n    for tool in message.tool_calls:\n        output = mylib.call_by_tool(tool)\n        print(tool.name,output)\nelse:\n    print(completion.choices[0].message.content)\n```\n\n",
    "bugtrack_url": null,
    "license": "MIT License  Copyright (c) 2023 CrosswaveOmega  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ",
    "summary": "A simple package for the purpose of providing a set of utilities that make it easier to invoke python functions and coroutines using OpenAI's GPT models.",
    "version": "0.3.7.2",
    "project_urls": {
        "Homepage": "https://github.com/CrosswaveOmega/GPT-Function-Calling-Utility"
    },
    "split_keywords": [
        "openai",
        "function calling api",
        "gpt",
        "asyncio"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "9d3f041f762ad82e64645013578c40e1e959e2d2b9ae3107d69f262aa45502c5",
                "md5": "7007157350a9081fed34a5c78505c584",
                "sha256": "3bbc3e2d6acfbd88296c5275ca418e5e56cdf4f96de7cf61017b3a41d51f55b4"
            },
            "downloads": -1,
            "filename": "gptfunctionutil-0.3.7.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "7007157350a9081fed34a5c78505c584",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 23611,
            "upload_time": "2024-02-25T15:59:09",
            "upload_time_iso_8601": "2024-02-25T15:59:09.308912Z",
            "url": "https://files.pythonhosted.org/packages/9d/3f/041f762ad82e64645013578c40e1e959e2d2b9ae3107d69f262aa45502c5/gptfunctionutil-0.3.7.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "73c1d41765e35619a82acdf2d00765cbf6a18d7f629c457fc3c93163e1463e09",
                "md5": "0f4ebfa2a747d45a0229b1306c6c2b40",
                "sha256": "61b8dd5b2ae3536b026a435a01f8ccfe9d5c63c207313f41fdbe0a30fc18e87d"
            },
            "downloads": -1,
            "filename": "gptfunctionutil-0.3.7.2.tar.gz",
            "has_sig": false,
            "md5_digest": "0f4ebfa2a747d45a0229b1306c6c2b40",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 28770,
            "upload_time": "2024-02-25T15:59:10",
            "upload_time_iso_8601": "2024-02-25T15:59:10.998912Z",
            "url": "https://files.pythonhosted.org/packages/73/c1/d41765e35619a82acdf2d00765cbf6a18d7f629c457fc3c93163e1463e09/gptfunctionutil-0.3.7.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-02-25 15:59:10",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "CrosswaveOmega",
    "github_project": "GPT-Function-Calling-Utility",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "gptfunctionutil"
}
        
Elapsed time: 0.18803s