I was feeling quite bored, so I decided to create a terminal-based chatbot. It comes with a functioning memory system, which has a default maximum capacity of 50 messages. You are free to adjust this capacity, but please note that it might affect response times.
Currently, the chatbot utilizes the g4f
library and the default GPT-3.5-TURBO
model. It doesn’t have a set provider, so it automatically selects one. However, if you’re interested, you can explore the g4f
GitHub repository to check out the available providers. Alternatively, you can refer to this list:
g4f.Provider.Ails
g4f.Provider.ChatBase
g4f.Provider.DeepAI
Please keep in mind that these providers exclusively support the GPT-3.5-TURBO
model. (Note: ChatBase does offer a GPT-4
, but it can generate religious content, so exercise caution when using it.)
Source Code:
import g4f
class Colors:
"""
A class defining ANSI escape codes for text formatting.
"""
RESET = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
BLACK = "\033[30m"
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[34m"
MAGENTA = "\033[35m"
CYAN = "\033[36m"
WHITE = "\033[37m"
BG_BLACK = "\033[40m"
BG_RED = "\033[41m"
BG_GREEN = "\033[42m"
BG_YELLOW = "\033[43m"
BG_BLUE = "\033[44m"
BG_MAGENTA = "\033[45m"
BG_CYAN = "\033[46m"
BG_WHITE = "\033[47m"
@staticmethod
def color_text(text, color_code):
"""
Apply color formatting to the provided text.
Args:
text (str): The text to be formatted.
color_code (str): The ANSI escape code for the desired color.
Returns:
str: The formatted text with the specified color.
"""
return f"{color_code}{text}{Colors.RESET}"
class ChatBotException(Exception):
"""
A custom exception class for chatbot-specific errors.
"""
pass
class Conversation:
"""
A class to manage the conversation history.
"""
def __init__(self, max_memory=50):
"""
Initialize a Conversation object.
Args:
max_memory (int): The maximum number of messages to store in the conversation history.
"""
self.messages = []
self.max_memory = max_memory
def add_message(self, role: str, content: str):
"""
Add a message to the conversation history.
Args:
role (str): The role of the message sender (e.g., 'user' or 'assistant').
content (str): The content of the message.
"""
if len(self.messages) >= self.max_memory:
self.messages.pop(0)
self.messages.append({'role': role, 'content': content})
def get_messages(self):
"""
Get the conversation history.
Returns:
list: A list of message dictionaries representing the conversation history.
"""
return self.messages
class TerminalChatBot:
"""
A class to manage the terminal-based chatbot.
"""
def __init__(self):
"""
Initialize a TerminalChatBot object.
"""
self.conversation = Conversation()
def send_message(self, content: str) -> None:
"""
Send a message to the chatbot and display the response.
Args:
content (str): The user's input message.
"""
try:
if not content.strip():
raise ChatBotException("Input is empty.")
self.conversation.add_message('user', content)
messages = [
{"role": "user", "content": content},
*self.conversation.get_messages()
]
response = g4f.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages
)
if not response:
raise ChatBotException("No response from the chat model.")
formatted_response = Colors.color_text(f"Bot: {response}", Colors.UNDERLINE)
print(formatted_response)
self.conversation.add_message('assistant', response)
except ChatBotException as e:
print(f"Error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
def start_chat(self):
"""
Start the chatbot interaction with the user.
"""
try:
while True:
user_input = input("You: ")
if user_input.lower() == "exit":
break
self.send_message(user_input)
except KeyboardInterrupt:
print("\nChat interrupted by the user.")
except Exception as e:
print(f"Unexpected error: {e}")
if __name__ == "__main__":
chatbot = TerminalChatBot()
chatbot.start_chat()