This is a simple Python script to access ChatGPT and DALL-E 2 within
Jupyter Notebook.
The inspiration and core code comes from an article by Sophia Yang in Medium.
My humble additions are to loop the query, opt to do an image prompt
(see below) and to save images and/or conversations.
Its been handy to have ChatGPT on call. It is definitely an
interesting and valuable tool, though I have found it necessary to
verify responses as errors are common. I’ve had the same answer to
opposite questions and seen errors in basic arithmetic. A way I look at
ChatGPT is similar to Wikipedia, in that it can help get you started,
but you should still go the source for verification.
Similarly with coding - at times ChatGPT is a great help, and at
other times is just plain wrong. Though, sometimes the approach to a
solution can help prompt my own thinking to solve the problem at hand.
So, another way to think of ChatGPT is like a sounding board or a friend
who is really trying to help. Used in this way, I’ve found ChatGPT to be
a useful tool on a few projects to get me thinking about things in a
different way.
Getting ready
Get OpenAI Key - you’ll need to set up a developer account to create
your personal API key:
I believe the first month you get US$18 credit and then pay for
monthly usage. With light to moderate usage, my bills are $1 per month
or less
Create two folders in the same directory as the script for saving
files:
Prompts:
- ChaptGPT: default - just enter prompt
- DALL-E 2: type
image:
plus text prompt
- Save image: after image is generated, type
save
- To finish: type
exit
After you finish a chat, you will be asked if you wish to save the
conversation.
Setup
from chatgpt import Conversation
import urllib.request
import sys
import os
import openai
from IPython.display import display, HTML
from IPython.display import Image
import pandas as pd
working_directory = os.getcwd()
working_directory = "/Users/adam/data/ChatGPT/"
# Enter personal OpenAI key here - see link above
openai.api_key = "<INSERT OPENAI KEY HERE>"
Functions
A list of models
If you wish to try other models, a list can be obtained with use of
this code:
models = pd.DataFrame(openai.Model.list()["data"])
# Functions
def openai_completion(prompt):
# Send prompt/Get ChatGPT reponse
response = openai.Completion.create(
model="text-davinci-003", # this can be changed to access different models
prompt=prompt,
max_tokens=2000, # you can change this to different values for longer shorter prompts/replies
temperature=0.5 # the "straightness" of the replies
)
return response['choices'][0]['text']
def openai_image(prompt):
#Send prompt/Get DALL-E 2 response
response = openai.Image.create(
prompt=prompt,
n=1,
size="256x256" # this can be different values "256x256", "512x512", "1024x1024"
)
image_url = response['data'][0]['url']
return image_url
#
def append_strings_to_df(question, response):
# Conversation text as dataframe - ready for saving upon request (enter "save" as prompt)
global conversation
dict = {"Question": question, "Response": response}
data = pd.DataFrame(dict, index=[0])
conversation = pd.concat([conversation, data])
Main prompt loop
# Set up empty conversation df
conversation = pd.DataFrame(columns=["Question", "Response"])
# Main prompt loop
while True:
question = input(">>")
if question.lower() == "exit":
append_strings_to_df(question, "")
break
elif question[0:7].lower() == "image: ": #create image based on prompt after "image: "
image_link = openai_image(question[7:])
image_obj = Image(url=image_link)
display(image_obj)
file_name = question[7:18] + ".png" #extracts text after "image: " to create filename
append_strings_to_df(question, image_link)
elif question.lower() == "save": #to save image
file_path = working_directory + "images/" + file_name
urllib.request.urlretrieve(image_link, file_path)
else:
response = openai_completion(question) #chatGPT response
print(response)
print()
append_strings_to_df(question, response)
# After exit - option to save conversation
while True:
save_convo = input("Save the conversation (Y/N)? :").lower()
if save_convo == "y":
file_name = input("Name? :")
conversation.to_csv(working_directory + "chats/" + file_name + ".csv", index=False)
break
elif save_convo == "n":
print("No probs - thanks!")
break
Copyright © 2023 Adam Simmons, Inc. All rights reserved.