Skip to content

Commit

Permalink
Updates for openailib 1.2.4
Browse files Browse the repository at this point in the history
  • Loading branch information
draupner1 committed Nov 14, 2023
1 parent 1aa900d commit 5f2e9b8
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 65 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,20 @@ If you have added the script to your path, you can run it from anywhere:
![image](https://user-images.githubusercontent.com/3023775/232043124-5bcdc240-4b86-4397-9355-ff0a8dc2f3fe.png)
![image](https://user-images.githubusercontent.com/3023775/232043119-d25b1e93-c99b-48e6-b9c6-ccbc1270a800.png)

New openAI lib v 1.2
--------------------
On new installs after Nov6-23 we get the new python lib v 1.2.

This breaks some calls and responce types.

OAI v.0.6.1 is adapted to the new lib!

Also, providing new shortcuts for -s size when generating Images.
Use '1:1', '16:9', '9:16' as shorthand for '1024x1024' and...

Also-2, when generating images, printing the returned eventually altered prompt.


Image Generation
----------------
Available from v.0.6.0
Expand Down
28 changes: 15 additions & 13 deletions oai.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ def put_session(messages):
to_unicode = unicode
except NameError:
to_unicode = str
# print(messages)
with open(_session_file_, 'w', encoding='utf8') as outfile:
str_ = json.dumps(messages,
indent=4, sort_keys=True,
Expand Down Expand Up @@ -124,9 +125,10 @@ def get_fun_def(func):
def print_url_list(heading, responce):
console.print(heading)
row = 1
for url in responce.data:
console.print(Markdown(" [url " + str(row) + "](" + url["url"] + ")"))

for img in responce.data:
console.print(Markdown(" [url " + str(row) + "](" + img.url + ") " + img.revised_prompt))
# console.print(img.url)
# print(responce)

def main():
desc = "This tool sends a query to OpenAIs Chat API from the command line.\n\n"\
Expand Down Expand Up @@ -248,57 +250,57 @@ def main():
messages=[askDict]

if args.create:
if args.size not in ["1024x1024", "1792x1024", "1024x1792"]:
if args.size not in ["1:1", "1024x1024", "16:9", "1792x1024", "9:16", "1024x1792"]:
print('DALL-E3 only supports, "1024x1024", "1792x1024", "1024x1792"')
print("size: " + args.size)
exit()
if args.size == "1:1":
args.size = "1024x1024"
if args.size == "16:9":
args.size = "1792x1024"
if args.size == "9:16":
args.size = "1024x1792"
with console.status(f"Phoning a friend... ", spinner="pong"):
print('Doing an image')
openai_response = get_image(prompt, numb, args.size)
# print(openai_response)
print_url_list("Created links:", openai_response)
exit()

if args.variant:
with console.status(f"Phoning a friend... ", spinner="pong"):
print('Variant of an image: ' + prompt)
openai_response = get_variant(prompt, numb)
# print(openai_response)
print_url_list("Variant links:", openai_response)
exit()

if args.edit:
with console.status(f"Phoning a friend... ", spinner="pong"):
print('Edit of an image: ' + prompt)
openai_response = get_edit(prompt, numb)
# print(openai_response)
print_url_list("Edited links:", openai_response)
exit()

with console.status(f"Phoning a friend... ", spinner="pong"):
openai_response = get_chat(messages, func)
if openai_response.get("function_call"):
function_name = openai_response["function_call"]["name"]
if openai_response.function_call != None:
function_name = openai_response.function_call.name
if function_name in available_functions:
fuction_to_call = available_functions[function_name]
else:
print('Bad returned function name from OpenAI API')
print(openai_response)
messages.append(openai_response)
messages.append({"role": "function", "name": function_name, "content": func})
function_args = json.loads(openai_response["function_call"]["arguments"].strip())
console.print(Markdown(function_args.get("content").strip()))
put_session(messages)
exit()

#print(openai_response["function_call"]["arguments"].strip())
function_args = json.loads(openai_response["function_call"]["arguments"].strip())
function_args = json.loads(openai_response.function_call.arguments.strip())
#print("Function arguments")
#print(function_args)
function_response = fuction_to_call(
**function_args
)
messages.append(openai_response)
messages.append({"role": "function", "name": function_name, "content": function_response})

if function_response != 'stop':
Expand Down
4 changes: 2 additions & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
openai==0.26.4
openai==1.2.4
appdirs==1.4.4
rich==13.3.1
rich==13.3.2
94 changes: 44 additions & 50 deletions resources/conduit.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import sys

import openai

from openai import OpenAI
from resources import config

client = OpenAI(api_key=config.get_api_key())



def get_completion(prompt):
openai.api_key = config.get_api_key()

engine = config.get_model()

if prompt is None:
Expand All @@ -18,15 +22,13 @@ def get_completion(prompt):
# print(f"Max tokens: {max_tokens}")
# print(f"Tokens in prompt: {tokens_prompt}")
try:
response = openai.Completion.create(
engine=engine,
prompt=prompt,
max_tokens=max_tokens,
n=1,
stop=None,
temperature=0.7,
).choices[0].text
except openai.error.APIError as e:
response = client.completions.create(engine=engine,
prompt=prompt,
max_tokens=max_tokens,
n=1,
stop=None,
temperature=0.7).choices[0].text
except openai.APIError as e:
# Handle API error here, e.g. retry or log
print(f"OpenAI API returned an API Error: {e}")
sys.exit()
Expand All @@ -44,25 +46,22 @@ def get_completion(prompt):
return response

def get_chat(messages, func = ""):
openai.api_key = config.get_api_key()

engine = config.get_model()

if len(messages) == 0:
print("Prompt is empty. Please enter a prompt.")

try:
if func == "":
response = openai.ChatCompletion.create(
model=engine,
messages=messages
).choices[0].message
response = client.chat.completions.create(model=engine,
messages=messages).choices[0].message
else:
response = openai.ChatCompletion.create(
model=engine,
messages=messages,
functions=[func]
).choices[0].message
except openai.error.APIError as e:
response = client.chat.completions.create(model=engine,
messages=messages,
functions=[func]).choices[0].message
print(response)
except openai.APIError as e:
# Handle API error here, e.g. retry or log
print(f"OpenAI API returned an API Error: {e}")
sys.exit()
Expand All @@ -77,16 +76,16 @@ def get_chat(messages, func = ""):
except openai.error.OpenAIError as e:
print(f"OpenAI API returned an error: {e}")
sys.exit()

return response

def get_models():
openai.api_key = config.get_api_key()

# engine = config.get_model()

try:
response = openai.Model.list(
).data
except openai.error.APIError as e:
response = client.models.list().data
except openai.APIError as e:
# Handle API error here, e.g. retry or log
print(f"OpenAI API returned an API Error: {e}")
sys.exit()
Expand All @@ -107,15 +106,13 @@ def get_image(prompt, num, size):
if num<1 or num>10:
print("Number of variants to generate must be between 1 to 10")
exit()
openai.api_key = config.get_api_key()

try:
response = openai.Image.create(
prompt = prompt,
n = num,
size=size,
model="dall-e-3"
)
except openai.error.APIError as e:
response = client.images.generate(prompt = prompt,
n = num,
size=size,
model="dall-e-3")
except openai.APIError as e:
# Handle API error here, e.g. retry or log
print(f"OpenAI API returned an API Error: {e}")
sys.exit()
Expand All @@ -130,6 +127,7 @@ def get_image(prompt, num, size):
except openai.error.OpenAIError as e:
print(f"OpenAI API returned an error: {e}")
sys.exit()
print(response)
return response


Expand All @@ -142,14 +140,12 @@ def get_variant(prompt, num):
except OSError:
print("Missing Imagefile in this directory")
exit()
openai.api_key = config.get_api_key()

try:
response = openai.Image.create_variation(
image = open(prompt, "rb"),
n = num,
size="1024x1024"
)
except openai.error.APIError as e:
response = client.images.generate(image = open(prompt, "rb"),
n = num,
size="1024x1024")
except openai.APIError as e:
# Handle API error here, e.g. retry or log
print(f"OpenAI API returned an API Error: {e}")
sys.exit()
Expand Down Expand Up @@ -184,22 +180,20 @@ def get_edit(prompt, num):
except OSError:
print("Missing Maskfile in this directory")
exit()
openai.api_key = config.get_api_key()

img = pl[0]
msk = pl[1]
prt = ' '.join(pl[2:])
# print( img )
# print( msk )
# print( prt )
try:
response = openai.Image.create_edit(
image = open(img, "rb"),
mask = open(msk, "rb"),
prompt = prt,
n = num,
size="1024x1024"
)
except openai.error.APIError as e:
response = client.images.generate(image = open(img, "rb"),
mask = open(msk, "rb"),
prompt = prt,
n = num,
size="1024x1024")
except openai.APIError as e:
# Handle API error here, e.g. retry or log
print(f"OpenAI API returned an API Error: {e}")
sys.exit()
Expand Down

0 comments on commit 5f2e9b8

Please sign in to comment.