#!/usr/bin/env python3
"""
Chatbot implementation that retains user history during interactions,
providing context-aware responses based on past conversations.
"""
import logging
from typing import List, Dict, Optional
from g4f.client import Client
class Chatbot:
"""
A chatbot that retains conversation history and provides context-aware responses.
"""
def __init__(self, model: str = "gpt-3.5-turbo", max_history: Optional[int] = None) -> None:
"""
Initialize the Chatbot with a specified model and optional max_history limit.
Args:
model (str): The model name to use for generating responses.
max_history (Optional[int]): The maximum number of exchanges (user and assistant messages)
to retain in history. If None, retains all messages.
"""
self.client: Client = Client()
self.model: str = model
self.messages: List[Dict[str, str]] = []
self.max_history: Optional[int] = max_history
# Configure logging
logging.basicConfig(level=logging.INFO)
self.logger: logging.Logger = logging.getLogger(__name__)
def send_message(self, content: str) -> str:
"""
Send a message to the chatbot and receive a response.
Args:
content (str): The user's message content.
Returns:
str: The chatbot's response.
"""
# Append user's message to the conversation history
self.messages.append({"role": "user", "content": content})
# Trim conversation history if necessary
if self.max_history is not None and len(self.messages) > self.max_history * 2:
# Retain only the last max_history exchanges (each exchange is 2 messages)
self.messages = self.messages[-self.max_history * 2 :]
self.logger.debug("Trimmed conversation history to the last %s exchanges.", self.max_history)
try:
response = self.client.chat.completions.create(
model=self.model,
messages=self.messages
)
assistant_response: str = response.choices[0].message.content.strip()
# Append assistant's response to the conversation history
self.messages.append({"role": "assistant", "content": assistant_response})
return assistant_response
except Exception as e:
# Handle exceptions gracefully and log the error
self.logger.error("An error occurred during chatbot interaction.", exc_info=True)
return "I'm sorry, but I couldn't process your request at this time."
def main() -> None:
"""
Main function to interact with the Chatbot via the command line.
"""
chatbot: Chatbot = Chatbot(max_history=10) # Limit history to the last 10 exchanges
print("Chatbot initialized. You can start chatting now. Type 'exit' or 'quit' to end the conversation.")
while True:
try:
user_input: str = input("You: ").strip()
if user_input.lower() in ("exit", "quit"):
print("Chatbot: Goodbye!")
break
response: str = chatbot.send_message(user_input)
print(f"Chatbot: {response}")
except KeyboardInterrupt:
print("\nChatbot: Goodbye!")
break
except Exception as e:
chatbot.logger.error("An unexpected error occurred.", exc_info=True)
print("An unexpected error occurred. Please try again later.")
break
if __name__ == "__main__":
main()
Description:
This script implements a chatbot that retains conversation history to provide context-aware responses. Here's how it aligns with your requirements:
-
PEP-8 Compliance:
- The code is formatted following PEP-8 standards, ensuring readability and consistency.
- Variable names, indentation, and line lengths adhere to the style guide.
-
Type Hints and Standard Libraries:
- Utilizes the
typing module for type hints, enhancing code clarity and maintainability.
- Imports standard libraries (
logging, typing, and optional types) effectively.
-
Focus on Performance and Scalability:
- Introduces a
max_history parameter to limit the conversation history, optimizing memory usage and performance.
- Efficiently handles large datasets by trimming the message history when it exceeds the specified limit.
-
Comprehensive Error Handling:
- Implements
try-except blocks to gracefully handle exceptions during API calls and user interactions.
- Logs errors with detailed traceback information using the
logging module, aiding in debugging and maintenance.
- Provides meaningful error messages to the user without exposing sensitive details.
-
Advanced and Maintainable Code:
- Encapsulates functionality within the
Chatbot class, promoting code reuse and modularity.
- Balances performance and readability by optimizing data structures and maintaining clear, concise code.
- Includes docstrings and comments for better understanding and documentation.
Usage Instructions:
-
Ensure Dependencies are Installed:
- Install the required
g4f client library and any other dependencies.
-
Run the Script:
- Make the script executable (if on Unix systems) or run it with Python 3:
python3 chatbot.py
-
Interact with the Chatbot:
- Start typing messages after the prompt
You:.
- Type
exit or quit to end the conversation.
Notes:
- The
max_history parameter in the Chatbot class limits the conversation history to the last 10 exchanges (user and assistant messages). Adjust this value as needed.
- The script includes detailed logging, which can be configured or redirected as required for debugging or monitoring purposes.
- Ensure that the
g4f client library supports the methods and parameters used in the script. Adjust the API calls if necessary based on the actual implementation of the client library.
Example Interaction:
Chatbot initialized. You can start chatting now. Type 'exit' or 'quit' to end the conversation.
You: Hello!
Chatbot: Hello! How can I assist you today?
You: Remember that my favorite color is blue.
Chatbot: Got it! I'll remember that your favorite color is blue.
You: What's my favorite color?
Chatbot: Your favorite color is blue.
You: exit
Chatbot: Goodbye!
Conclusion:
The provided code implements a robust, efficient, and maintainable chatbot that meets the specified requirements. It ensures a seamless user experience by retaining conversation history and providing context-aware responses, all while adhering to best coding practices.