This is a simple conversation program based on the OpenAI GPT-3.5-Turbo model.
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 | |
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 [ | |
msg.to_dict() | |
for msg | |
in self.system_msgs + self.messages | |
] | |
def __add_message(self, message: Message) -> None: | |
if len(self.messages) >= self.max_length: | |
self.messages.pop(0) | |
self.messages.append(message) | |
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]: | |
try: | |
completion = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages=[ | |
*self.__make_messages(), | |
{ | |
"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.") | |
sys.exit(1) | |
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] | |
try: | |
while True: | |
print("You: ", end="") | |
sys.stdout.flush() | |
text = sys.stdin.readline() | |
if not text: | |
break | |
print("AI: ", session.ask(text)) | |
print() | |
except KeyboardInterrupt: | |
pass | |
except Exception as err: | |
logging.error(f"Error: {err}") | |
return False | |
print("Goodbye!") | |
return True | |
if __name__ == "__main__": | |
sys.exit(0 if main() else 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Two points to note:
export OPENAI_API_KEY=xxxxxxxx
pip3 install 'openai>=0.27.0'