Skip to content

Instantly share code, notes, and snippets.

Last active March 3, 2023 08:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save Thoxvi/bcd7d7242f59bd1cc1d7b92499ec671b to your computer and use it in GitHub Desktop.
Save Thoxvi/bcd7d7242f59bd1cc1d7b92499ec671b to your computer and use it in GitHub Desktop.
This is a simple conversation program based on the OpenAI GPT-3.5-Turbo model.
import openai
import sys
import random
import string
import os
import logging
from typing import Optional
from openai.error import OpenAIError
class Message:
def __init__(self, role, content):
self.role = role
self.content = content
def to_dict(self) -> dict:
return {"role": self.role, "content": self.content}
class Session:
def __make_messages(self) -> list[dict]:
return [
for msg
in self.system_msgs + self.messages
def __add_message(self, message: Message) -> None:
if len(self.messages) >= self.max_length:
def __init__(self, max_length=20):
self.system_msgs = [
Message("system", "You are a mischievous artificial assistant."),
self.messages = []
self.max_length = max_length
def ask(self, new_question) -> Optional[str]:
completion = openai.ChatCompletion.create(
"role": "user",
"content": new_question
msg = completion.choices[0].message
self.__add_message(Message("user", new_question))
self.__add_message(Message(msg["role"], msg["content"]))
return msg["content"].strip()
except OpenAIError as err:
logging.error(f"Error while asking AI: {err}")
return None
def get_random_string(length) -> str:
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(length))
def main() -> bool:
api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
logging.error("Please set the OPENAI_API_KEY environment variable.")
openai.api_key = api_key
session_map = {}
user = get_random_string(10)
if user not in session_map:
session_map[user] = Session()
session = session_map[user]
while True:
print("You: ", end="")
text = sys.stdin.readline()
if not text:
print("AI: ", session.ask(text))
except KeyboardInterrupt:
except Exception as err:
logging.error(f"Error: {err}")
return False
return True
if __name__ == "__main__":
sys.exit(0 if main() else 1)
Copy link

Thoxvi commented Mar 3, 2023

Two points to note:

  1. You need to configure the OPENAI_API_KEY in the environment variable in advance: export OPENAI_API_KEY=xxxxxxxx
  2. You need to install the official OpenAI Python library to >= 0.27.0: pip3 install 'openai>=0.27.0'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment