-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenaiapi.py
67 lines (52 loc) · 1.76 KB
/
openaiapi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from openai import OpenAI
from openaikey import OPENAI_KEY
import requests
client = OpenAI(api_key=OPENAI_KEY)
def getCompletion(prompt, system_prompt="", messages=[]):
if system_prompt != "" and len(messages) == 0:
messages.append({"role": "system", "content": system_prompt})
messages.append({"role": "user", "content": prompt})
try:
completion = client.chat.completions.create(
model="gpt-4o",
messages=messages
)
response = completion.choices[0].message.content
messages.append({"role": "assistant", "content": response})
return response
except Exception as e:
print("OpenAI Exception" + str(e))
return None
def generateImage(prompt, resolution="1024x1024", filename="", cheap_mode=False):
model = "dall-e-3"
if cheap_mode:
model="dall-e-2"
resolution="512x512"
try:
response = client.images.generate(
model=model,
prompt=prompt,
n=1,
quality="standard",
size=resolution
)
image_url = response.data[0].url
if filename != "":
image_data = requests.get(image_url).content
with open(filename, 'wb') as file:
file.write(image_data)
return image_url
except Exception as e:
print("OpenAI Exception" + str(e))
return None
def textToSpeech(text, filename):
response = client.audio.speech.create(
model="tts-1",
voice="alloy",
input=text,
)
response.write_to_file(filename)
if __name__ == "__main__":
print(getCompletion("Bonjour"))
#print(generateImage("a black fox", "1024x1024", "black_fox.png", cheap_mode=True))
#textToSpeech("hello, I'm Vincent", "hello.mp3")