openai-decorator


Nameopenai-decorator JSON
Version 0.1.3 PyPI version JSON
download
home_pagehttps://github.com/shruti222patel/openai-decorator
SummaryThis package allows you to genrate function paramater values by integrating OpenAI's API function capabilities through signature and docstring analysis.
upload_time2023-06-18 21:03:48
maintainer
docs_urlNone
authorShruti Patel
requires_python>=3.8,<4.0
licenseMIT
keywords openai decorator functions openai-functions openai-decorator openai-api openai-api-functions openai-api-decorator openai
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # OpenAI Decorator

The OpenAI Decorator is a Python package that enriches your Python functions with the capabilities of OpenAI's API. It leverages the function's signature and docstring to generate specifications comprehensible by OpenAI's API, subsequently making a request to the API.

## Table of Contents

- [Key Features](#key-features)
- [Installation](#installation)
- [Usage Guide](#usage-guide)
  - [Basic Usage](#basic-usage)
  - [Type Annotations & Optionals](#type-annotations-optionals)
  - [Passing a Callable Prompt](#passing-callable-prompts)
  - [Using the Decorator as a Regular Function](#using-the-decorator-as-a-regular-function)
- [Contributing](#contributing)
  - [Setup](#setup)
- [Future Enhancements](#future-enhancements)
- [License](#license)

## Key Features

- Automatic generation of specs from the function's signature and docstring.
- Integration with OpenAI's API using the generated specs and a customizable prompt.
- Inference of function arguments from the OpenAI API response, negating the need for manual input.
- Handling of various edge cases related to function signatures, including default and optional values.

## Installation

Install the package using pip:

```sh
pip install openai-decorator
```
Save your OpenAI key in an environment variable named `OPENAI_API_KEY`:
```sh
export OPENAI_API_KEY=<your key>
```

## Usage Guide

### Basic Usage
Apply the `openai_func` decorator to a function with type annotations and a well-formatted Google Style docstring. Then, it will seamlessly interact with OpenAI's API to generate the parameters for your function based on the prompt.

```python
from openai_decorator import openai_func

@openai_func(prompt="Your OpenAI prompt here")
def example_function(arg1: str, arg2: int) -> str:
    """
    This is an example function.

    Args:
        arg1 (str): Description for arg1
        arg2 (int): Description for arg2

    Returns:
        str: Description for return value
    """
    return f"Your output here: {arg1} and {arg2}"

result = example_function()
print(result)
```

### Type Annotations & Optionals

The decorator efficiently handles complex function signatures:

- **Default Values:** Parameters with a default value or `Optional` type annotation are marked as optional in the JSON specification.
- **Type Annotations:** Supports primitive types (int, str, bool, float) and complex types (List, Dict, Tuple, Set, Optional, custom classes).

```python
from openai_decorator import openai_func

@openai_func(prompt="Perform mathematical operations")
def example_function(a: int, b: int, c: float = 0.0, d: List[int] = []):
    """
    This is an example function.

    Args:
        a: The first integer.
        b: The second integer.
        c: An optional float.
        d: An optional list of integers.
    """
    # Function body here
```

### Passing Callable Prompts

In addition to static strings, you can also pass a callable to the `prompt` parameter in the `openai_func` decorator to dynamically generate prompts. This callable should take no arguments and return a string. Here's an example:

```python
from openai_decorator import openai_func

def generate_prompt():
    # Dynamically generate a prompt.
    # In a real-world scenario, this could depend on various factors,
    # such as the current time or the latest trending topics.
    return "Your OpenAI prompt here"

@openai_func(prompt=generate_prompt)
def example_function(arg1: str, arg2: int) -> str:
    """
    This is an example function.

    Args:
        arg1 (str): Description for arg1
        arg2 (int): Description for arg2

    Returns:
        str: Description for return value
    """
    return f"Your output here: {arg1} and {arg2}"

result = example_function()
print(result)
```

In this example, every time `example_function` is called, `generate_prompt

### Using the Decorator as a Regular Function

`openai_func` can also be used as a regular function. First, call `openai_func` with the prompt and any other arguments to get the actual decorator. Then, apply this decorator to your function.

```python
from openai_decorator import openai_func

def example_function(arg1: str, arg2: int) -> str:
    """
    This is an example function.

    Args:
        arg1 (str): Description for arg1
        arg2 (int): Description for arg2

    Returns:
        str: Description for return value
    """
    return f"Your output here: {arg1} and {arg2}"

# Use openai_func as a regular function
prompt = "Your OpenAI prompt here"

example_func_with_generated_params = openai_func(prompt=prompt)(example_function)

result = example_func_with_generated_params()
print(result)
```
This approach gives you more flexibility in determining the prompt at runtime.

## Contributing

Contributions are welcome! Feel free to submit issues and pull requests.

### Setup

1. Install Python `3.11` and the latest version of [poetry](https://python-poetry.org/docs/#installing-with-pipx)
    - `pyenv` can help manage multiple Python versions.
2. Clone the repository: `git clone`.
3. Set your OpenAI key as an environment variable:
```shell
export OPENAI_API_KEY=<insert your openai key>
```
4. Install dependencies: `poetry install --no-root`

## Future Enhancements

- [x] Handle optional parameters.
- [x] Handle parameters with default values.
- [ ] Add test to ensure default values are used if OpenAI doesn't return parameters.
- [ ] Publish the package to PyPI.
- [ ] Expand test coverage.
- [ ] Show tests passing & coverage as github badges.
- [X] Fix CI/CD -- Address the issue where the pre-release deployment to PyPI fails due to the need for version update.
- [ ] Add docstrings.
- [ ] Generate docs (from docstrings).

## License

This project is under the MIT License. See the [LICENSE](LICENSE) file for more details.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/shruti222patel/openai-decorator",
    "name": "openai-decorator",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8,<4.0",
    "maintainer_email": "",
    "keywords": "openai,decorator,functions,openai-functions,openai-decorator,openai-api,openai-api-functions,openai-api-decorator,openai",
    "author": "Shruti Patel",
    "author_email": "shruti222patel@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/f1/da/9aa7db7476662661c4854ec047ae41b75a3bf723e95377b82bf2a4ecee9d/openai_decorator-0.1.3.tar.gz",
    "platform": null,
    "description": "# OpenAI Decorator\n\nThe OpenAI Decorator is a Python package that enriches your Python functions with the capabilities of OpenAI's API. It leverages the function's signature and docstring to generate specifications comprehensible by OpenAI's API, subsequently making a request to the API.\n\n## Table of Contents\n\n- [Key Features](#key-features)\n- [Installation](#installation)\n- [Usage Guide](#usage-guide)\n  - [Basic Usage](#basic-usage)\n  - [Type Annotations & Optionals](#type-annotations-optionals)\n  - [Passing a Callable Prompt](#passing-callable-prompts)\n  - [Using the Decorator as a Regular Function](#using-the-decorator-as-a-regular-function)\n- [Contributing](#contributing)\n  - [Setup](#setup)\n- [Future Enhancements](#future-enhancements)\n- [License](#license)\n\n## Key Features\n\n- Automatic generation of specs from the function's signature and docstring.\n- Integration with OpenAI's API using the generated specs and a customizable prompt.\n- Inference of function arguments from the OpenAI API response, negating the need for manual input.\n- Handling of various edge cases related to function signatures, including default and optional values.\n\n## Installation\n\nInstall the package using pip:\n\n```sh\npip install openai-decorator\n```\nSave your OpenAI key in an environment variable named `OPENAI_API_KEY`:\n```sh\nexport OPENAI_API_KEY=<your key>\n```\n\n## Usage Guide\n\n### Basic Usage\nApply the `openai_func` decorator to a function with type annotations and a well-formatted Google Style docstring. Then, it will seamlessly interact with OpenAI's API to generate the parameters for your function based on the prompt.\n\n```python\nfrom openai_decorator import openai_func\n\n@openai_func(prompt=\"Your OpenAI prompt here\")\ndef example_function(arg1: str, arg2: int) -> str:\n    \"\"\"\n    This is an example function.\n\n    Args:\n        arg1 (str): Description for arg1\n        arg2 (int): Description for arg2\n\n    Returns:\n        str: Description for return value\n    \"\"\"\n    return f\"Your output here: {arg1} and {arg2}\"\n\nresult = example_function()\nprint(result)\n```\n\n### Type Annotations & Optionals\n\nThe decorator efficiently handles complex function signatures:\n\n- **Default Values:** Parameters with a default value or `Optional` type annotation are marked as optional in the JSON specification.\n- **Type Annotations:** Supports primitive types (int, str, bool, float) and complex types (List, Dict, Tuple, Set, Optional, custom classes).\n\n```python\nfrom openai_decorator import openai_func\n\n@openai_func(prompt=\"Perform mathematical operations\")\ndef example_function(a: int, b: int, c: float = 0.0, d: List[int] = []):\n    \"\"\"\n    This is an example function.\n\n    Args:\n        a: The first integer.\n        b: The second integer.\n        c: An optional float.\n        d: An optional list of integers.\n    \"\"\"\n    # Function body here\n```\n\n### Passing Callable Prompts\n\nIn addition to static strings, you can also pass a callable to the `prompt` parameter in the `openai_func` decorator to dynamically generate prompts. This callable should take no arguments and return a string. Here's an example:\n\n```python\nfrom openai_decorator import openai_func\n\ndef generate_prompt():\n    # Dynamically generate a prompt.\n    # In a real-world scenario, this could depend on various factors,\n    # such as the current time or the latest trending topics.\n    return \"Your OpenAI prompt here\"\n\n@openai_func(prompt=generate_prompt)\ndef example_function(arg1: str, arg2: int) -> str:\n    \"\"\"\n    This is an example function.\n\n    Args:\n        arg1 (str): Description for arg1\n        arg2 (int): Description for arg2\n\n    Returns:\n        str: Description for return value\n    \"\"\"\n    return f\"Your output here: {arg1} and {arg2}\"\n\nresult = example_function()\nprint(result)\n```\n\nIn this example, every time `example_function` is called, `generate_prompt\n\n### Using the Decorator as a Regular Function\n\n`openai_func` can also be used as a regular function. First, call `openai_func` with the prompt and any other arguments to get the actual decorator. Then, apply this decorator to your function.\n\n```python\nfrom openai_decorator import openai_func\n\ndef example_function(arg1: str, arg2: int) -> str:\n    \"\"\"\n    This is an example function.\n\n    Args:\n        arg1 (str): Description for arg1\n        arg2 (int): Description for arg2\n\n    Returns:\n        str: Description for return value\n    \"\"\"\n    return f\"Your output here: {arg1} and {arg2}\"\n\n# Use openai_func as a regular function\nprompt = \"Your OpenAI prompt here\"\n\nexample_func_with_generated_params = openai_func(prompt=prompt)(example_function)\n\nresult = example_func_with_generated_params()\nprint(result)\n```\nThis approach gives you more flexibility in determining the prompt at runtime.\n\n## Contributing\n\nContributions are welcome! Feel free to submit issues and pull requests.\n\n### Setup\n\n1. Install Python `3.11` and the latest version of [poetry](https://python-poetry.org/docs/#installing-with-pipx)\n    - `pyenv` can help manage multiple Python versions.\n2. Clone the repository: `git clone`.\n3. Set your OpenAI key as an environment variable:\n```shell\nexport OPENAI_API_KEY=<insert your openai key>\n```\n4. Install dependencies: `poetry install --no-root`\n\n## Future Enhancements\n\n- [x] Handle optional parameters.\n- [x] Handle parameters with default values.\n- [ ] Add test to ensure default values are used if OpenAI doesn't return parameters.\n- [ ] Publish the package to PyPI.\n- [ ] Expand test coverage.\n- [ ] Show tests passing & coverage as github badges.\n- [X] Fix CI/CD -- Address the issue where the pre-release deployment to PyPI fails due to the need for version update.\n- [ ] Add docstrings.\n- [ ] Generate docs (from docstrings).\n\n## License\n\nThis project is under the MIT License. See the [LICENSE](LICENSE) file for more details.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "This package allows you to genrate function paramater values by integrating OpenAI's API function capabilities through signature and docstring analysis.",
    "version": "0.1.3",
    "project_urls": {
        "Homepage": "https://github.com/shruti222patel/openai-decorator",
        "Repository": "https://github.com/shruti222patel/openai-decorator"
    },
    "split_keywords": [
        "openai",
        "decorator",
        "functions",
        "openai-functions",
        "openai-decorator",
        "openai-api",
        "openai-api-functions",
        "openai-api-decorator",
        "openai"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "c46a4279fd650e3f6a2ba54f528f4af847381098b1dd74911888ea096044ab91",
                "md5": "7768cb2794235cc05cf1bb9b619a8e99",
                "sha256": "c2b2305c15feaf89870b57a6cb3640f85c209714dbdf27adff613094297db9b3"
            },
            "downloads": -1,
            "filename": "openai_decorator-0.1.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "7768cb2794235cc05cf1bb9b619a8e99",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8,<4.0",
            "size": 7009,
            "upload_time": "2023-06-18T21:03:47",
            "upload_time_iso_8601": "2023-06-18T21:03:47.152029Z",
            "url": "https://files.pythonhosted.org/packages/c4/6a/4279fd650e3f6a2ba54f528f4af847381098b1dd74911888ea096044ab91/openai_decorator-0.1.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "f1da9aa7db7476662661c4854ec047ae41b75a3bf723e95377b82bf2a4ecee9d",
                "md5": "50d906a61d81f2217117541c4d8c9c15",
                "sha256": "10b72404340c7cdbe7e449a4ab5c14c5839df7cf7cee661bf11d0393a5130b74"
            },
            "downloads": -1,
            "filename": "openai_decorator-0.1.3.tar.gz",
            "has_sig": false,
            "md5_digest": "50d906a61d81f2217117541c4d8c9c15",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8,<4.0",
            "size": 6271,
            "upload_time": "2023-06-18T21:03:48",
            "upload_time_iso_8601": "2023-06-18T21:03:48.922645Z",
            "url": "https://files.pythonhosted.org/packages/f1/da/9aa7db7476662661c4854ec047ae41b75a3bf723e95377b82bf2a4ecee9d/openai_decorator-0.1.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-06-18 21:03:48",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "shruti222patel",
    "github_project": "openai-decorator",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "openai-decorator"
}
        
Elapsed time: 0.08124s