Last active
March 8, 2023 12:03
-
-
Save vincefav/00588839e21cc0284d982be61618cb9b to your computer and use it in GitHub Desktop.
ChatGPT sample code
This file contains 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
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( | |
model="gpt-3.5-turbo", | |
messages=self.messages | |
) | |
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: | |
print(i) | |
# 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." | |
chat.add_user_message(human_reply) | |
gpt_reply = "Understood! 👍🏻 I'll use lots of emojis. 😀" | |
chat.add_assistant_message(gpt_reply) | |
# And from there, you can just continue adding to the conversation like this: | |
human_reply = "(Your message here)" | |
chat.add_user_message(human_reply) | |
gpt_reply = chat.get_chatgpt_reply() | |
chat.add_assistant_message(gpt_reply) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment