Skip to content

Instantly share code, notes, and snippets.

@Darkflib
Created March 5, 2023 14:50
Show Gist options
  • Save Darkflib/f1c63164397a50aef8ccf7d8c2a142e0 to your computer and use it in GitHub Desktop.
Save Darkflib/f1c63164397a50aef8ccf7d8c2a142e0 to your computer and use it in GitHub Desktop.
import os
import sys
from dotenv import load_dotenv
import openai # pip install openai
import re
# Load the API key from the .env file
load_dotenv()
# Get the API key from the environment variable
api_key = os.environ.get("OPENAI_API_KEY")
org_id = os.environ.get("OPENAI_ORG_ID")
model_engine = os.getenv("MODEL_ENGINE")
# bail if no API key, org or model engine
#if api_key is None or org_id is None or model_engine is None:
# print("Please set the environment variables OPENAI_API_KEY, OPENAI_ORG_ID and MODEL_ENGINE")
# sys.exit()
openai.api_key = api_key
openai.organization = org_id
messages = []
system_msg = input("\n\033[33mWhat type of chatbot would you like to create?\033[0m \n\n> ")
messages.append({"role": "system", "content": system_msg})
print("\n")
#print("Say hello to your new assistant!\n")
user_input = ""
chat_history = "System: " + system_msg
while user_input != "!endchat":
user_input = input("\033[31mYou: \033[0m")
if user_input == "!endchat":
break
messages.append({"role": "user", "content": user_input})
response = openai.ChatCompletion.create(
model=model_engine,
messages=messages)
reply = response["choices"][0]["message"]["content"]
messages.append({"role": "assistant", "content": reply})
chat_history += f"\nUser: {user_input}\nChatGPT: {reply}\n"
print("\n\033[31m" + "Bot:\033[0m " + reply + "\n")
chat_log = input("\n\nPlease enter a filename to save the chat log to (without the .log extension): ")
with open(f"{chat_log}.log", "w") as f:
f.write(re.sub("\033\[\d+m", "", chat_history))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment