opaw


Nameopaw JSON
Version 0.4.5 PyPI version JSON
download
home_pagehttps://github.com/hiimanget/openai-pw
SummaryUnofficial python wrapper of OpenAI API.
upload_time2023-08-16 16:47:47
maintainer
docs_urlNone
authorhiimanget
requires_python
licenseMIT
keywords openai python api wrapper
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            [![PyPi](https://img.shields.io/pypi/v/opaw)](https://pypi.org/project/opaw/)


# openai-pw
Unofficial python wrapper of [OpenAI](https://openai.com/) API.


# Features
- Wrapped models (chat, audio, image, embeddings ...)
- History(requests and responses) save and load to/from a file
- Audio bot supports also [whisper](https://github.com/openai/whisper) and [whisper_timestamped](https://github.com/linto-ai/whisper-timestamped)(word-level timestamps)



# Quick start
You can also play with in **[this colab](https://colab.research.google.com/drive/1nJ1-YwLMSxSVx092uBVoarvuVUyt65xC?usp=drive_link)**. Or

1. Download `openai` using pip.
```cmd
pip install opaw
```
2. Create a `open-api-key.txt` file and insert [your api key](https://platform.openai.com/account/api-keys) into the file. Or set an environment variable with the name `OPENAI_API_KEY`.
3. Write a demo code and play with ChatGPT.
```py
from opaw.examples.basic import loop_chat 
from opaw import util

util.setup() # api key setup
loop_chat() # start chat
```

# Usage
**All usage codes need to setup API key using `util.setup()` before running**

- [chat](#chat)
- [image](#image)
- [audio](#audio)
- [completion](#completion)
- [embedding](#embedding)
- [moderation](#moderation)
- [file](#file)
- [finetune](#finetune)
- [edit](#edit)
- [function_call](#function_call)
- [load_chat](#load_chat)
- [save_history](#save_history)


### Chat
```py
from opaw.model.chat import ChatBot
from opaw import util

util.setup() # api key setup
bot = ChatBot()
bot.add_message("You are a helpful assistant.", role="system")
response = bot.create("What is openai?")
print("Bot:", bot.grab(response))
```

### Image
```py
from opaw.model.image import ImageBot
from opaw import util

util.setup() # api key setup
bot = ImageBot()
prompt = "A black cat sitting on a frozen lake like a emoticon style"
response = bot.create(prompt, task="create", size="256x256")
bot.save_img(response, "cat.png")
```


### Audio
```py
from opaw.model.audio import AudioBot
from opaw import util

util.setup() # api key setup

# download a mp3 file from here: https://github.com/hiimanget/openai-pw/blob/main/opaw/examples/radio_short.mp3
bot = AudioBot()
file = 'radio_short.mp3'

# official api
response = bot.create(file, lib="api", task="stt")
print(f"official api: {response['text']}")

# whisper (https://github.com/openai/whisper)
response = bot.create(file, lib="whisper", name="tiny")
print(f"whisper: {response}")

# whisper_timestamped: supports word-timestamping (https://github.com/linto-ai/whisper-timestamped)
response = bot.create(file, lib="whisper_t", name="tiny", device="cpu")
print(f"whisper_timestamped: {util.pprints(response)}")
```


### Completion
```py
from opaw import util
from opaw.model.completion import CompletionBot

util.setup() # api key setup
bot = CompletionBot()
prompt = "Tell some lies"
response = bot.create(prompt, max_tokens=50)
print(bot.grab(response))
```

### Embedding
```py
from opaw import util
from opaw.model.embedding import EmbeddingBot 

util.setup() # api key setup
bot = EmbeddingBot()
prompt = "Cheese is melting on my laptop"
response = bot.create(prompt)
print(f"embeddings: {bot.grab(response)}")
```

### Moderation
```py
from opaw import util
from opaw.model.moderation import ModerationBot

util.setup() # api key setup
bot = ModerationBot()
prompt = "I want to kill them!!"
response = bot.create(prompt)
print(response)

# show results that are flagged
print(f"flags: {bot.grab(response)}")
```

### File
```py
from opaw import util
from opaw.model.file import FileBot

util.setup() # api key setup

# download a file from here: https://github.com/hiimanget/openai-pw/blob/main/opaw/examples/file-upload.jsonl
bot = FileBot()
# file upload
response = bot.create(task="upload", file="file-upload.jsonl", purpose="fine-tune")
print(f"file-upload response: {response}")
id = response["id"]

# retrieve a file
response = bot.create(task="retrieve", id=id)
print(f"list response: {response}")

# download file
response = bot.create(task="download", id=id)
print(f"download response: {response}")
```

### Finetune
```py
from opaw import util
from opaw.model.finetune import FinetuneBot

util.setup() # api key setup
bot = FinetuneBot()
response = bot.create(task="create", training_file="...")  # input your file id in "training_file"
print(f"finetune create: {response}")

# finetune list
response = bot.create(task="list")
print(f"finetune list: {response}")
```

### Edit
**Deprecated**
```py
from opaw import util
from opaw.model.edit import EditBot

util.setup() # api key setup
bot = EditBot()
prompt = "Hey, this was my filst car!!"  # filst -> first
instruction = "Fix the spelling mistakes"
response = bot.create(prompt, instruction=instruction)
print(f"text: {bot.grab(response)}")
```

### Function_call
```py
from opaw import util
from opaw.model.chat import ChatBot
from opaw.util import func_meta

util.setup() # api key setup

# prepare a function that will be called
def stock_price(company):
    if company == "APPL":
        return 100
    elif company == "AMZN":
        return 150

funcs_meta = [
    func_meta("stock_price",  # name
              "Get the stock price of a given company",  # desc
              ["company", "string", "The company stock name, e.g. APPL"],  # properties
              ["company"])  # required
]
funcs = {"stock_price": stock_price}

# ask a question to gpt
bot = ChatBot("gpt-3.5-turbo-0613", funcs_meta=funcs_meta, funcs=funcs)  # must use "gpt-3.5-turbo-0613" to use function call
bot.add_message("You are a helpful assistant that can send function json when need.", role="system")
response = bot.create(f"What is the amazon's stock price?", call_fn=True)

# if function_call exists (not guaranteed 100%)
if bot.get_fn_call(response):
    fn_result = bot.call_function(response)
    print(f"amazon stock price: {fn_result}")
else:
    print("no function call")
```

### Load_chat
```py
from opaw import util
from opaw.model.chat import ChatBot

util.setup() # api key setup

# download a chat history file from here: https://github.com/hiimanget/openai-pw/blob/main/opaw/examples/history/chat-hist.json
bot = ChatBot()
bot.load_msgs("chat-hist.json")  # load history (former conversation)

response = bot.create("Then, has the company's stock been listed?")  # bot sould know meaning of "there" if history loaded successfully
print(f"response: {bot.grab(response)}")
```

### Save_history
```py
from opaw import util
from opaw.model.chat import ChatBot

util.setup() # api key setup
bot = ChatBot()
bot.add_message("You are a helpful assistant.", role="system")
response = bot.create("Do you like cheese?")
print("resopnse:", bot.grab(response))

# save history
bot.save_history("history/chat-hist.json")  # check out the file in the history directory
```

# More examples
Try to run something in [examples](opaw/examples) after downloaded this repo. (needed to run `pip install -r requirements.txt` before running examples)


# OpenAI links
- [API](https://platform.openai.com/docs/api-reference/introduction)
- [Guide](https://platform.openai.com/docs/guides/gpt)
- [model list](https://platform.openai.com/docs/models)
- [community](https://community.openai.com/)
- [usage](https://platform.openai.com/account/usage)
- [api key](https://platform.openai.com/account/api-keys)


# License
MIT

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/hiimanget/openai-pw",
    "name": "opaw",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "openai,python,api,wrapper",
    "author": "hiimanget",
    "author_email": "hiimanget@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/4d/b5/97ac7694a21df47f390cb31298d4aa80ba1c7eafc7e2ef63ecd014cac7b5/opaw-0.4.5.tar.gz",
    "platform": null,
    "description": "[![PyPi](https://img.shields.io/pypi/v/opaw)](https://pypi.org/project/opaw/)\r\n\r\n\r\n# openai-pw\r\nUnofficial python wrapper of [OpenAI](https://openai.com/) API.\r\n\r\n\r\n# Features\r\n- Wrapped models (chat, audio, image, embeddings ...)\r\n- History(requests and responses) save and load to/from a file\r\n- Audio bot supports also [whisper](https://github.com/openai/whisper) and [whisper_timestamped](https://github.com/linto-ai/whisper-timestamped)(word-level timestamps)\r\n\r\n\r\n\r\n# Quick start\r\nYou can also play with in **[this colab](https://colab.research.google.com/drive/1nJ1-YwLMSxSVx092uBVoarvuVUyt65xC?usp=drive_link)**. Or\r\n\r\n1. Download `openai` using pip.\r\n```cmd\r\npip install opaw\r\n```\r\n2. Create a `open-api-key.txt` file and insert [your api key](https://platform.openai.com/account/api-keys) into the file. Or set an environment variable with the name `OPENAI_API_KEY`.\r\n3. Write a demo code and play with ChatGPT.\r\n```py\r\nfrom opaw.examples.basic import loop_chat \r\nfrom opaw import util\r\n\r\nutil.setup() # api key setup\r\nloop_chat() # start chat\r\n```\r\n\r\n# Usage\r\n**All usage codes need to setup API key using `util.setup()` before running**\r\n\r\n- [chat](#chat)\r\n- [image](#image)\r\n- [audio](#audio)\r\n- [completion](#completion)\r\n- [embedding](#embedding)\r\n- [moderation](#moderation)\r\n- [file](#file)\r\n- [finetune](#finetune)\r\n- [edit](#edit)\r\n- [function_call](#function_call)\r\n- [load_chat](#load_chat)\r\n- [save_history](#save_history)\r\n\r\n\r\n### Chat\r\n```py\r\nfrom opaw.model.chat import ChatBot\r\nfrom opaw import util\r\n\r\nutil.setup() # api key setup\r\nbot = ChatBot()\r\nbot.add_message(\"You are a helpful assistant.\", role=\"system\")\r\nresponse = bot.create(\"What is openai?\")\r\nprint(\"Bot:\", bot.grab(response))\r\n```\r\n\r\n### Image\r\n```py\r\nfrom opaw.model.image import ImageBot\r\nfrom opaw import util\r\n\r\nutil.setup() # api key setup\r\nbot = ImageBot()\r\nprompt = \"A black cat sitting on a frozen lake like a emoticon style\"\r\nresponse = bot.create(prompt, task=\"create\", size=\"256x256\")\r\nbot.save_img(response, \"cat.png\")\r\n```\r\n\r\n\r\n### Audio\r\n```py\r\nfrom opaw.model.audio import AudioBot\r\nfrom opaw import util\r\n\r\nutil.setup() # api key setup\r\n\r\n# download a mp3 file from here: https://github.com/hiimanget/openai-pw/blob/main/opaw/examples/radio_short.mp3\r\nbot = AudioBot()\r\nfile = 'radio_short.mp3'\r\n\r\n# official api\r\nresponse = bot.create(file, lib=\"api\", task=\"stt\")\r\nprint(f\"official api: {response['text']}\")\r\n\r\n# whisper (https://github.com/openai/whisper)\r\nresponse = bot.create(file, lib=\"whisper\", name=\"tiny\")\r\nprint(f\"whisper: {response}\")\r\n\r\n# whisper_timestamped: supports word-timestamping (https://github.com/linto-ai/whisper-timestamped)\r\nresponse = bot.create(file, lib=\"whisper_t\", name=\"tiny\", device=\"cpu\")\r\nprint(f\"whisper_timestamped: {util.pprints(response)}\")\r\n```\r\n\r\n\r\n### Completion\r\n```py\r\nfrom opaw import util\r\nfrom opaw.model.completion import CompletionBot\r\n\r\nutil.setup() # api key setup\r\nbot = CompletionBot()\r\nprompt = \"Tell some lies\"\r\nresponse = bot.create(prompt, max_tokens=50)\r\nprint(bot.grab(response))\r\n```\r\n\r\n### Embedding\r\n```py\r\nfrom opaw import util\r\nfrom opaw.model.embedding import EmbeddingBot \r\n\r\nutil.setup() # api key setup\r\nbot = EmbeddingBot()\r\nprompt = \"Cheese is melting on my laptop\"\r\nresponse = bot.create(prompt)\r\nprint(f\"embeddings: {bot.grab(response)}\")\r\n```\r\n\r\n### Moderation\r\n```py\r\nfrom opaw import util\r\nfrom opaw.model.moderation import ModerationBot\r\n\r\nutil.setup() # api key setup\r\nbot = ModerationBot()\r\nprompt = \"I want to kill them!!\"\r\nresponse = bot.create(prompt)\r\nprint(response)\r\n\r\n# show results that are flagged\r\nprint(f\"flags: {bot.grab(response)}\")\r\n```\r\n\r\n### File\r\n```py\r\nfrom opaw import util\r\nfrom opaw.model.file import FileBot\r\n\r\nutil.setup() # api key setup\r\n\r\n# download a file from here: https://github.com/hiimanget/openai-pw/blob/main/opaw/examples/file-upload.jsonl\r\nbot = FileBot()\r\n# file upload\r\nresponse = bot.create(task=\"upload\", file=\"file-upload.jsonl\", purpose=\"fine-tune\")\r\nprint(f\"file-upload response: {response}\")\r\nid = response[\"id\"]\r\n\r\n# retrieve a file\r\nresponse = bot.create(task=\"retrieve\", id=id)\r\nprint(f\"list response: {response}\")\r\n\r\n# download file\r\nresponse = bot.create(task=\"download\", id=id)\r\nprint(f\"download response: {response}\")\r\n```\r\n\r\n### Finetune\r\n```py\r\nfrom opaw import util\r\nfrom opaw.model.finetune import FinetuneBot\r\n\r\nutil.setup() # api key setup\r\nbot = FinetuneBot()\r\nresponse = bot.create(task=\"create\", training_file=\"...\")  # input your file id in \"training_file\"\r\nprint(f\"finetune create: {response}\")\r\n\r\n# finetune list\r\nresponse = bot.create(task=\"list\")\r\nprint(f\"finetune list: {response}\")\r\n```\r\n\r\n### Edit\r\n**Deprecated**\r\n```py\r\nfrom opaw import util\r\nfrom opaw.model.edit import EditBot\r\n\r\nutil.setup() # api key setup\r\nbot = EditBot()\r\nprompt = \"Hey, this was my filst car!!\"  # filst -> first\r\ninstruction = \"Fix the spelling mistakes\"\r\nresponse = bot.create(prompt, instruction=instruction)\r\nprint(f\"text: {bot.grab(response)}\")\r\n```\r\n\r\n### Function_call\r\n```py\r\nfrom opaw import util\r\nfrom opaw.model.chat import ChatBot\r\nfrom opaw.util import func_meta\r\n\r\nutil.setup() # api key setup\r\n\r\n# prepare a function that will be called\r\ndef stock_price(company):\r\n    if company == \"APPL\":\r\n        return 100\r\n    elif company == \"AMZN\":\r\n        return 150\r\n\r\nfuncs_meta = [\r\n    func_meta(\"stock_price\",  # name\r\n              \"Get the stock price of a given company\",  # desc\r\n              [\"company\", \"string\", \"The company stock name, e.g. APPL\"],  # properties\r\n              [\"company\"])  # required\r\n]\r\nfuncs = {\"stock_price\": stock_price}\r\n\r\n# ask a question to gpt\r\nbot = ChatBot(\"gpt-3.5-turbo-0613\", funcs_meta=funcs_meta, funcs=funcs)  # must use \"gpt-3.5-turbo-0613\" to use function call\r\nbot.add_message(\"You are a helpful assistant that can send function json when need.\", role=\"system\")\r\nresponse = bot.create(f\"What is the amazon's stock price?\", call_fn=True)\r\n\r\n# if function_call exists (not guaranteed 100%)\r\nif bot.get_fn_call(response):\r\n    fn_result = bot.call_function(response)\r\n    print(f\"amazon stock price: {fn_result}\")\r\nelse:\r\n    print(\"no function call\")\r\n```\r\n\r\n### Load_chat\r\n```py\r\nfrom opaw import util\r\nfrom opaw.model.chat import ChatBot\r\n\r\nutil.setup() # api key setup\r\n\r\n# download a chat history file from here: https://github.com/hiimanget/openai-pw/blob/main/opaw/examples/history/chat-hist.json\r\nbot = ChatBot()\r\nbot.load_msgs(\"chat-hist.json\")  # load history (former conversation)\r\n\r\nresponse = bot.create(\"Then, has the company's stock been listed?\")  # bot sould know meaning of \"there\" if history loaded successfully\r\nprint(f\"response: {bot.grab(response)}\")\r\n```\r\n\r\n### Save_history\r\n```py\r\nfrom opaw import util\r\nfrom opaw.model.chat import ChatBot\r\n\r\nutil.setup() # api key setup\r\nbot = ChatBot()\r\nbot.add_message(\"You are a helpful assistant.\", role=\"system\")\r\nresponse = bot.create(\"Do you like cheese?\")\r\nprint(\"resopnse:\", bot.grab(response))\r\n\r\n# save history\r\nbot.save_history(\"history/chat-hist.json\")  # check out the file in the history directory\r\n```\r\n\r\n# More examples\r\nTry to run something in [examples](opaw/examples) after downloaded this repo. (needed to run `pip install -r requirements.txt` before running examples)\r\n\r\n\r\n# OpenAI links\r\n- [API](https://platform.openai.com/docs/api-reference/introduction)\r\n- [Guide](https://platform.openai.com/docs/guides/gpt)\r\n- [model list](https://platform.openai.com/docs/models)\r\n- [community](https://community.openai.com/)\r\n- [usage](https://platform.openai.com/account/usage)\r\n- [api key](https://platform.openai.com/account/api-keys)\r\n\r\n\r\n# License\r\nMIT\r\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Unofficial python wrapper of OpenAI API.",
    "version": "0.4.5",
    "project_urls": {
        "Homepage": "https://github.com/hiimanget/openai-pw"
    },
    "split_keywords": [
        "openai",
        "python",
        "api",
        "wrapper"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "95fb27f021788c040f5e58c18dfd6e36fd56d7cfad44ffee75470ee2f7ea8851",
                "md5": "fb379202f743fad5b7e9185c3ad65138",
                "sha256": "1f75adf26c5845da630b81b3e05ea4749e7a421ff84976d707b1e10afd4416e4"
            },
            "downloads": -1,
            "filename": "opaw-0.4.5-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "fb379202f743fad5b7e9185c3ad65138",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 26653,
            "upload_time": "2023-08-16T16:47:45",
            "upload_time_iso_8601": "2023-08-16T16:47:45.443967Z",
            "url": "https://files.pythonhosted.org/packages/95/fb/27f021788c040f5e58c18dfd6e36fd56d7cfad44ffee75470ee2f7ea8851/opaw-0.4.5-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "4db597ac7694a21df47f390cb31298d4aa80ba1c7eafc7e2ef63ecd014cac7b5",
                "md5": "0cc4c82f357657ae96673682cea96896",
                "sha256": "4fce31786579accbed0c7bae05605c3545e2f146c566cc602c3cba823f7f2e79"
            },
            "downloads": -1,
            "filename": "opaw-0.4.5.tar.gz",
            "has_sig": false,
            "md5_digest": "0cc4c82f357657ae96673682cea96896",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 19611,
            "upload_time": "2023-08-16T16:47:47",
            "upload_time_iso_8601": "2023-08-16T16:47:47.422176Z",
            "url": "https://files.pythonhosted.org/packages/4d/b5/97ac7694a21df47f390cb31298d4aa80ba1c7eafc7e2ef63ecd014cac7b5/opaw-0.4.5.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-08-16 16:47:47",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "hiimanget",
    "github_project": "openai-pw",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "requirements": [],
    "lcname": "opaw"
}
        
Elapsed time: 0.10096s