Last active
October 8, 2022 07:59
-
-
Save cr0hn/9debed29e31e99c13d60125b039f842f to your computer and use it in GitHub Desktop.
Python OpenAI API Client WITHOUT ANY external dependency
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
This file contains code for consuming the OpenAI API without depencies | |
This code is released under MIT License. | |
""" | |
import json | |
from typing import List | |
import urllib.request as rq | |
class OpenAIError(Exception): | |
... | |
def openai_choices(resp: dict) -> List[str]: | |
try: | |
return [r.get('text') for r in resp.get("choices", [])] | |
except (AttributeError, TypeError): | |
return [] | |
def openai_ask( | |
prompt: str, | |
api_key: str, | |
model: str = "text-davinci-002", | |
temperature: int = 0, | |
max_tokens: int = 250, | |
top_p: float = 1.0, | |
frequency_penalty: float = 0.0, | |
presence_penalty: float = 0.0, | |
timeout: int = 30, | |
return_only_choices: bool = True | |
) -> dict: | |
"""This function call OpenAI API""" | |
try: | |
data = json.dumps({ | |
"prompt": prompt, | |
"model": model, | |
"temperature": temperature, | |
"max_tokens": max_tokens, | |
"top_p": top_p, | |
"frequency_penalty": frequency_penalty, | |
"presence_penalty": presence_penalty | |
}).encode() | |
resp = rq.Request( | |
url="https://api.openai.com/v1/completions", | |
method="POST", | |
headers={ | |
"Authorization": f"Bearer {api_key}", | |
"Content-Type": "application/json", | |
"User-Agent": "OpenAI/v1 PythonBindings/0.23.1" | |
} | |
) | |
with rq.urlopen(resp, data, timeout=timeout) as f: | |
return json.loads(f.read().decode("utf-8")) | |
except Exception as e: | |
raise OpenAIError(e) | |
if __name__ == '__main__': | |
# Usage example | |
# Example from: https://beta.openai.com/examples/default-parse-data | |
text = """A table summarizing the fruits from Goocrux: | |
There are many fruits that were found on the recently discovered planet Goocrux. There are neoskizzles that grow there, which are purple and taste like candy. There are also loheckles, which are a grayish blue fruit and are very tart, a little bit like a lemon. Pounits are a bright green color and are more savory than sweet. There are also plenty of loopnovas which are a neon pink flavor and taste like cotton candy. Finally, there are fruits called glowls, which have a very sour and bitter taste which is acidic and caustic, and a pale orange tinge to them. | |
| Fruit | Color | Flavor |""" | |
try: | |
response = openai_ask( | |
prompt="", | |
api_key="sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" | |
) | |
print("Raw response:") | |
print(response) | |
print("Choices:") | |
if suggestions := openai_choices(response): | |
for suggestion in suggestions: | |
print(suggestion) | |
except OpenAIError as e: | |
print(f"OpenAIError: {e}") | |
exit(1) | |
__all__ = ("openai_ask", "openai_choices", "OpenAIError") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment