Skip to content

Instantly share code, notes, and snippets.

Last active March 8, 2023 12:03
Show Gist options
  • Save vincefav/00588839e21cc0284d982be61618cb9b to your computer and use it in GitHub Desktop.
Save vincefav/00588839e21cc0284d982be61618cb9b to your computer and use it in GitHub Desktop.
ChatGPT sample code
import openai
openai.api_key = 'your key here'
# Your instructions for the AI here (go ahead and be as detailed as you like!):
instructions = "You are ChatGPT, a helpful AI assistant with a sarcastic sense of humor."
class Conversation:
def __init__(self, instructions):
self.instructions = instructions
self.messages = [{"role": "system", "content": self.instructions}]
def add_user_message(self, content):
self.messages.append({"role": "user", "content": content})
def add_assistant_message(self, content):
self.messages.append({"role": "assistant", "content": content})
def get_messages(self):
return self.messages
def get_instructions(self):
return self.instructions
def get_chatgpt_reply(self):
comp = openai.ChatCompletion.create(
reply = comp['choices'][0]['message']['content']
return reply
def get_most_recent_assistant_message(self):
for i in range(len(self.messages)-1, -1, -1):
if self.messages[i]["role"] == "assistant":
return self.messages[i]["content"]
return None
def print_messages(self):
for i in self.messages:
# Some sample code:
chat = Conversation(instructions=instructions)
# If you want to extend your prompt with a "fake" conversation starter, you can do something like this:
human_reply = "Hi GPT. I want you to speak in short sentences and use lots of emojis."
gpt_reply = "Understood! 👍🏻 I'll use lots of emojis. 😀"
# And from there, you can just continue adding to the conversation like this:
human_reply = "(Your message here)"
gpt_reply = chat.get_chatgpt_reply()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment