import g4f
from g4f.client import Client
import time
import sys
import json
from typing import List, Dict, Any
import random
from datetime import datetime
import tkinter as tk
from tkinter import scrolledtext, filedialog, messagebox
import threading
import multiprocessing
import spacy
from textblob import TextBlob
import requests
# Load spaCy English model
try:
nlp = spacy.load('en_core_web_sm')
except:
import subprocess
subprocess.run(['python', '-m', 'spacy', 'download', 'en_core_web_sm'])
nlp = spacy.load('en_core_web_sm')
client = Client(provider=g4f.Provider.Blackbox)
# Configuration Constants
SEARCH_API_KEY = 'YOUR_BING_SEARCH_API_KEY' # Replace with your Bing Search API Key
SEARCH_API_ENDPOINT = 'https://api.bing.microsoft.com/v7.0/search'
# Define AI Worker Base Class
class AIWorker:
def __init__(self, name: str, description: str, few_shot_examples: List[Dict[str, str]] = None):
self.name = name
self.description = description
self.few_shot_examples = few_shot_examples if few_shot_examples else []
def process(self, user_input: str, settings: Dict[str, Any]) -> str:
"""
Process the user input and return the response.
This method should be overridden by subclasses.
"""
raise NotImplementedError("Each AIWorker must implement the process method.")
# Example Worker: DataAnalysisWorker
class DataAnalysisWorker(AIWorker):
def __init__(self):
few_shot = [
{
"prompt": "Analyze the following sales data and identify trends:",
"completion": "To analyze the sales data, I'll look at monthly sales figures, identify peaks and troughs, and determine seasonal trends. For example, if sales increase in December, it might indicate a holiday season trend."
},
{
"prompt": "Explain the correlation between marketing spend and sales revenue:",
"completion": "The correlation between marketing spend and sales revenue can be assessed by calculating the correlation coefficient. A positive correlation suggests that increased marketing spend leads to higher sales revenue, while a negative correlation indicates the opposite."
}
]
super().__init__(name="DataAnalysisWorker", description="Handles data analysis queries.", few_shot_examples=few_shot)
def process(self, user_input: str, settings: Dict[str, Any]) -> str:
# Construct prompt with few-shot examples
prompt = "You are a data analysis expert.\n\n"
for example in self.few_shot_examples:
prompt += f"User: {example['prompt']}\nAssistant: {example['completion']}\n\n"
prompt += f"User: {user_input}\nAssistant:"
# Incorporate user settings
prompt += f" Respond in a {settings.get('response_style', 'informative')} manner with a verbosity level of {settings.get('verbosity', 'medium')}."
# Call AI model
try:
response = client.chat.completions.create(
model=settings.get('model', 'gpt-4o-mini'),
messages=[{"role": "system", "content": prompt}],
stream=True
)
full_response = ""
for chunk in response:
if hasattr(chunk, 'choices') and len(chunk.choices) > 0 and hasattr(chunk.choices[0].delta, 'content') and chunk.choices[0].delta.content is not None:
full_response += chunk.choices[0].delta.content
return full_response.strip()
except Exception as e:
return f"Error in DataAnalysisWorker: {str(e)}"
# Example Worker: CreativeWritingWorker
class CreativeWritingWorker(AIWorker):
def __init__(self):
few_shot = [
{
"prompt": "Write a short story about a dragon and a knight.",
"completion": "Once upon a time, in a land far away, a brave knight named Sir Cedric encountered a majestic dragon atop Mount Ember. Instead of fighting, they forged an unlikely friendship, leading their kingdom into an era of peace and prosperity."
},
{
"prompt": "Compose a poem about the ocean at sunset.",
"completion": "The ocean breathes in hues of gold,\nAs sunsets paint the sky so bold.\nWaves whisper secrets to the shore,\nIn twilight's embrace, forevermore."
}
]
super().__init__(name="CreativeWritingWorker", description="Handles creative writing and storytelling.", few_shot_examples=few_shot)
def process(self, user_input: str, settings: Dict[str, Any]) -> str:
# Construct prompt with few-shot examples
prompt = "You are a creative writing expert.\n\n"
for example in self.few_shot_examples:
prompt += f"User: {example['prompt']}\nAssistant: {example['completion']}\n\n"
prompt += f"User: {user_input}\nAssistant:"
# Incorporate user settings
prompt += f" Respond in a {settings.get('response_style', 'engaging')} manner with a verbosity level of {settings.get('verbosity', 'detailed')}."
# Call AI model
try:
response = client.chat.completions.create(
model=settings.get('model', 'gpt-4o-mini'),
messages=[{"role": "system", "content": prompt}],
stream=True
)
full_response = ""
for chunk in response:
if hasattr(chunk, 'choices') and len(chunk.choices) > 0 and hasattr(chunk.choices[0].delta, 'content') and chunk.choices[0].delta.content is not None:
full_response += chunk.choices[0].delta.content
return full_response.strip()
except Exception as e:
return f"Error in CreativeWritingWorker: {str(e)}"
# New Worker: WebSearchWorker
class WebSearchWorker(AIWorker):
def __init__(self):
few_shot = [
{
"prompt": "Find the latest news about renewable energy.",
"completion": "According to recent reports, renewable energy sources are gaining significant traction globally, with solar and wind power leading the charge. Governments are increasing investments to reduce carbon emissions and promote sustainable practices."
},
{
"prompt": "Search for current stock prices of Tesla.",
"completion": "As of today, Tesla's stock is trading at approximately $850 per share, reflecting a recent surge driven by strong quarterly earnings and positive market sentiment."
}
]
super().__init__(name="WebSearchWorker", description="Performs web searches and provides concise summaries.", few_shot_examples=few_shot)
def perform_web_search(self, query: str) -> str:
"""Performs a web search using Bing Search API and returns a concise summary."""
headers = {"Ocp-Apim-Subscription-Key": SEARCH_API_KEY}
params = {"q": query, "textDecorations": True, "textFormat": "HTML", "count": 3}
try:
response = requests.get(SEARCH_API_ENDPOINT, headers=headers, params=params)
response.raise_for_status()
search_results = response.json()
snippets = []
if 'webPages' in search_results:
for page in search_results['webPages']['value'][:3]:
# Strip HTML tags from snippet
snippet = page.get('snippet', '')
cleaned_snippet = ''.join(c for c in snippet if c.isprintable())
snippets.append(cleaned_snippet)
summary = " ".join(snippets)
# Use AI to generate a concise summary from snippets
summary_prompt = (
"Summarize the following web search snippets concisely:\n\n"
+ "\n".join(snippets)
+ "\n\nSummary:"
)
try:
summary_response = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{"role": "system", "content": summary_prompt}],
stream=True
)
full_summary = ""
for chunk in summary_response:
if hasattr(chunk, 'choices') and len(chunk.choices) > 0 and hasattr(chunk.choices[0].delta, 'content') and chunk.choices[0].delta.content is not None:
full_summary += chunk.choices[0].delta.content
return full_summary.strip()
except Exception as e:
return f"Error during summary generation: {str(e)}"
except Exception as e:
return f"Error during web search: {str(e)}"
def process(self, user_input: str, settings: Dict[str, Any]) -> str:
# Construct prompt with few-shot examples
prompt = "You are an expert web researcher.\n\n"
for example in self.few_shot_examples:
prompt += f"User: {example['prompt']}\nAssistant: {example['completion']}\n\n"
prompt += f"User: {user_input}\nAssistant:"
# Incorporate user settings
prompt += f" Respond in a {settings.get('response_style', 'informative')} manner with a verbosity level of {settings.get('verbosity', 'medium')}."
# Extract query for web search
query = user_input # In a real scenario, parse to extract the actual search intent
# Perform web search and summarize
summary = self.perform_web_search(query)
return summary
# Define a MetaLearningWorker for Advanced Meta-Learning
class MetaLearningWorker(AIWorker):
def __init__(self):
few_shot = [
{
"prompt": "Improve the assistant's ability to handle ambiguous queries.",
"completion": "To enhance the assistant's handling of ambiguous queries, it should ask clarifying questions to better understand the user's intent. Additionally, it can provide possible interpretations of the query and offer corresponding responses."
},
{
"prompt": "Adjust the response style to be more empathetic.",
"completion": "The assistant should incorporate empathetic language, acknowledge the user's emotions, and respond in a warm and understanding tone. Phrases like 'I understand how you feel' or 'I'm here to help' can make interactions more compassionate."
}
]
super().__init__(name="MetaLearningWorker", description="Learns from interactions to improve chatbot performance.", few_shot_examples=few_shot)
def process(self, reflection: str, settings: Dict[str, Any]) -> str:
"""
Process the reflection to adjust settings or behaviors.
This is a simplified example of meta-learning where reflections can be used to tweak settings.
"""
# Example: Parse reflection and adjust settings accordingly
# This would require more sophisticated NLP for real applications
if "improve" in reflection.lower() and "clarifying questions" in reflection.lower():
settings['response_style'] = 'concise'
settings['verbosity'] = 'high'
adjustment = "Adjusted response style to 'concise' and verbosity to 'high' based on reflection."
return adjustment
elif "empathetic" in reflection.lower():
settings['response_style'] = 'engaging'
adjustment = "Adjusted response style to 'engaging' to be more empathetic."
return adjustment
else:
return "No adjustments were necessary based on the reflection."
# Multi-Processing Manager
class MultiProcessingManager:
def __init__(self):
self.pool = multiprocessing.Pool(processes=4) # Adjust the number of processes as needed
def execute(self, func, args):
return self.pool.apply_async(func, args)
def close_pool(self):
self.pool.close()
self.pool.join()
# Define the AdvancedChatbot Class
class AdvancedChatbot:
def __init__(self):
self.config_file = "config.json"
self.config = self.load_config()
# Initialize Multi-Processing Manager
self.mpm = MultiProcessingManager()
# Initialize AI Workers including WebSearchWorker and MetaLearningWorker
self.workers = [DataAnalysisWorker(), CreativeWritingWorker(), WebSearchWorker()]
self.meta_worker = MetaLearningWorker()
# Initialize settings
self.settings = self.config.get('settings', {
'response_style': 'informative',
'verbosity': 'medium',
'language': 'English',
'custom_prompt': '',
'model': 'gpt-4o-mini'
})
# Initialize conversation history and reflection history
self.conversation_history: List[Dict[str, str]] = self.config.get('history', [])
self.reflection_history: List[Dict[str, str]] = self.config.get('reflection_history', [])
# Initialize GUI
self.root = tk.Tk()
self.gui = AdvancedChatbotGUI(self.root, self)
def load_config(self) -> Dict[str, Any]:
"""Load configuration from file."""
try:
with open(self.config_file, 'r') as f:
config = json.load(f)
except FileNotFoundError:
config = {
'model': 'gpt-4o-mini',
'history': [],
'reflection_history': [],
'settings': {
'response_style': 'informative',
'verbosity': 'medium',
'language': 'English',
'custom_prompt': ''
}
}
self.save_config(config)
return config
def save_config(self, config: Dict[str, Any] = None):
"""Save current configuration to file."""
if config is None:
config = {
'model': self.config.get('model', 'gpt-4o-mini'),
'history': self.conversation_history,
'reflection_history': self.reflection_history,
'settings': self.settings
}
with open(self.config_file, 'w') as f:
json.dump(config, f, indent=4)
def detect_intent(self, user_input: str) -> str:
"""Detect the intent of the user input using NLP."""
doc = nlp(user_input)
# Simple intent detection based on keywords
intents = {
'data_analysis': ['analyze', 'data', 'statistics', 'trend', 'market analysis'],
'creative_writing': ['write', 'story', 'poem', 'creative', 'compose'],
'web_search': ['search', 'find', 'lookup', 'look up', 'google', 'bing'],
# Add more intents as needed
}
for intent, keywords in intents.items():
if any(keyword in user_input.lower() for keyword in keywords):
return intent
return 'general'
def analyze_sentiment(self, user_input: str) -> str:
"""Analyze the sentiment of the user input."""
blob = TextBlob(user_input)
sentiment = blob.sentiment.polarity
if sentiment > 0.1:
return 'positive'
elif sentiment < -0.1:
return 'negative'
else:
return 'neutral'
def extract_entities(self, user_input: str) -> List[str]:
"""Extract named entities from the user input."""
doc = nlp(user_input)
return [ent.text for ent in doc.ents]
def select_worker(self, user_input: str, intent: str) -> AIWorker:
"""Selects an appropriate worker based on the user input intent."""
if intent == 'data_analysis':
return next((worker for worker in self.workers if isinstance(worker, DataAnalysisWorker)), None)
elif intent == 'creative_writing':
return next((worker for worker in self.workers if isinstance(worker, CreativeWritingWorker)), None)
elif intent == 'web_search':
return next((worker for worker in self.workers if isinstance(worker, WebSearchWorker)), None)
else:
return None # Use default AI response if no worker matches
def default_ai_response(self, user_input: str) -> str:
"""Generates a default AI response when no specific worker is selected."""
# Incorporate user settings into the prompt
prompt = f"Please respond to the following query.\n\nUser: {user_input}\nAssistant:"
# Add customization settings
prompt += f" Respond in a {self.settings.get('response_style', 'informative')} manner with a verbosity level of {self.settings.get('verbosity', 'medium')} and in {self.settings.get('language', 'English')}."
# Append custom prompt if exists
custom_prompt = self.settings.get('custom_prompt', '')
if custom_prompt:
prompt = f"{custom_prompt}\n\n{prompt}"
try:
response = client.chat.completions.create(
model=self.settings.get('model', 'gpt-4o-mini'),
messages=[{"role": "system", "content": prompt}],
stream=True
)
full_response = ""
for chunk in response:
if hasattr(chunk, 'choices') and len(chunk.choices) > 0 and hasattr(chunk.choices[0].delta, 'content') and chunk.choices[0].delta.content is not None:
full_response += chunk.choices[0].delta.content
return full_response.strip()
except Exception as e:
return f"Error: {str(e)}"
def recursive_self_reflection(self, user_input: str, assistant_response: str) -> str:
"""Performs recursive self-reflection on the assistant's response."""
# Construct reflection prompt
reflection_prompt = (
"Evaluate the following response for accuracy, coherence, and relevance.\n\n"
f"User: {user_input}\n"
f"Assistant: {assistant_response}\n\n"
"Provide a brief assessment and suggest any improvements if necessary."
)
try:
# Call AI model for reflection
reflection_response = client.chat.completions.create(
model=self.settings.get('model', 'gpt-4o-mini'),
messages=[{"role": "system", "content": reflection_prompt}],
stream=True
)
full_reflection = ""
for chunk in reflection_response:
if hasattr(chunk, 'choices') and len(chunk.choices) > 0 and hasattr(chunk.choices[0].delta, 'content') and chunk.choices[0].delta.content is not None:
full_reflection += chunk.choices[0].delta.content
return full_reflection.strip()
except Exception as e:
return f"Error during self-reflection: {str(e)}"
def perform_meta_learning(self, reflection: str):
"""Adjust settings based on reflection using MetaLearningWorker."""
adjustment = self.meta_worker.process(reflection, self.settings)
if adjustment.startswith("Adjusted"):
# Log the adjustment in conversation history
self.conversation_history.append({"role": "assistant", "content": adjustment})
self.reflection_history.append({"query": "Meta-Learning Adjustment", "response": adjustment, "reflection": ""})
# Optionally, notify the user about the adjustment
messagebox.showinfo("Meta-Learning Adjustment", adjustment)
def customize_behavior(self):
"""Allows the user to customize AI behavior."""
# Simple implementation using a popup to change settings
customize_window = tk.Toplevel(self.root)
customize_window.title("Customize AI Behavior")
customize_window.geometry("400x300")
# Response Style
tk.Label(customize_window, text="Response Style:").pack(pady=5)
response_style_var = tk.StringVar(value=self.settings.get('response_style', 'informative'))
response_style_options = ['informative', 'engaging', 'concise', 'friendly']
tk.OptionMenu(customize_window, response_style_var, *response_style_options).pack(pady=5)
# Verbosity Level
tk.Label(customize_window, text="Verbosity Level:").pack(pady=5)
verbosity_var = tk.StringVar(value=self.settings.get('verbosity', 'medium'))
verbosity_options = ['low', 'medium', 'high']
tk.OptionMenu(customize_window, verbosity_var, *verbosity_options).pack(pady=5)
# Language
tk.Label(customize_window, text="Language:").pack(pady=5)
language_var = tk.StringVar(value=self.settings.get('language', 'English'))
language_options = ['English', 'Spanish', 'French', 'German', 'Chinese']
tk.OptionMenu(customize_window, language_var, *language_options).pack(pady=5)
# Custom Prompt
tk.Label(customize_window, text="Custom Prompt:").pack(pady=5)
custom_prompt_text = tk.Text(customize_window, height=5, width=40)
custom_prompt_text.pack(pady=5)
custom_prompt_text.insert(tk.END, self.settings.get('custom_prompt', ''))
def save_customization():
self.settings['response_style'] = response_style_var.get()
self.settings['verbosity'] = verbosity_var.get()
self.settings['language'] = language_var.get()
self.settings['custom_prompt'] = custom_prompt_text.get("1.0", tk.END).strip()
self.save_config()
customize_window.destroy()
messagebox.showinfo("Customization Saved", "AI behavior has been customized successfully.")
tk.Button(customize_window, text="Save", command=save_customization).pack(pady=10)
def run(self):
"""Run the GUI."""
self.root.protocol("WM_DELETE_WINDOW", self.on_close)
self.gui.display_history()
self.root.mainloop()
def on_close(self):
"""Handle closing of the chatbot."""
self.save_config()
self.mpm.close_pool()
self.root.destroy()
# Enhanced GUI Class with Meta-Learning and Web-Search
class AdvancedChatbotGUI:
def __init__(self, master, chatbot):
self.master = master
self.chatbot = chatbot
master.title("Advanced AI Chatbot")
master.geometry("900x700")
# Initialize conversation history and reflection history
self.conversation_history: List[Dict[str, str]] = self.chatbot.conversation_history
self.reflection_history: List[Dict[str, str]] = self.chatbot.reflection_history
# Initialize AI Workers including WebSearchWorker and MetaLearningWorker
self.workers = self.chatbot.workers
# Initialize Multi-Processing Manager
self.mpm = self.chatbot.mpm # Reference to multiprocessing manager
# Initialize main frame
self.main_frame = tk.Frame(master)
self.main_frame.pack(fill=tk.BOTH, expand=True)
# Create text display area
self.chat_display = scrolledtext.ScrolledText(self.main_frame, wrap=tk.WORD, state='disabled', font=("Arial", 12))
self.chat_display.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
# Create input frame
self.input_frame = tk.Frame(self.main_frame)
self.input_frame.pack(padx=10, pady=10, fill=tk.X)
# User input entry
self.user_input = tk.Entry(self.input_frame, font=("Arial", 12))
self.user_input.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0,10))
self.user_input.bind("<Return>", self.send_message)
# Send button
self.send_button = tk.Button(self.input_frame, text="Send", command=self.send_message, font=("Arial", 12))
self.send_button.pack(side=tk.RIGHT)
# Menu bar
self.menu = tk.Menu(master)
master.config(menu=self.menu)
# File menu
self.file_menu = tk.Menu(self.menu, tearoff=0)
self.menu.add_cascade(label="File", menu=self.file_menu)
self.file_menu.add_command(label="Save Conversation", command=self.chatbot.save_config)
self.file_menu.add_command(label="Load Conversation", command=self.load_conversation)
self.file_menu.add_separator()
self.file_menu.add_command(label="Exit", command=master.quit)
# Settings menu
self.settings_menu = tk.Menu(self.menu, tearoff=0)
self.menu.add_cascade(label="Settings", menu=self.settings_menu)
self.settings_menu.add_command(label="Customize AI Behavior", command=self.chatbot.customize_behavior)
# Initialize Recursive Self-Reflection flag
self.enable_reflection = True # Can be toggled via settings
# Display existing history
self.display_history()
def display_history(self):
"""Display the loaded conversation history in the chat_display."""
self.chat_display.config(state='normal')
self.chat_display.delete(1.0, tk.END)
for message in self.conversation_history:
role = "You" if message['role'] == 'user' else "Assistant"
self.chat_display.insert(tk.END, f"{role}: {message['content']}\n\n")
# Optionally display reflections
for reflection in self.reflection_history:
reflection_content = reflection.get('reflection', reflection.get('response', ''))
if reflection_content:
self.chat_display.insert(tk.END, f"Assistant (Reflection): {reflection_content}\n\n")
self.chat_display.config(state='disabled')
def stream_response(self, response: str, role: str = "Assistant"):
"""Stream the response with a typing effect in the GUI."""
self.chat_display.config(state='normal')
self.chat_display.insert(tk.END, f"{role}: ")
self.chat_display.config(state='disabled')
def write_chars():
for char in response:
self.chat_display.config(state='normal')
self.chat_display.insert(tk.END, char)
self.chat_display.yview(tk.END)
self.chat_display.config(state='disabled')
time.sleep(random.uniform(0.005, 0.02))
self.chat_display.insert(tk.END, "\n\n")
self.chat_display.yview(tk.END)
threading.Thread(target=write_chars).start()
def send_message(self, event=None):
"""Handle sending of user messages."""
user_text = self.user_input.get().strip()
if user_text:
# Display user message
self.chat_display.config(state='normal')
self.chat_display.insert(tk.END, f"You: {user_text}\n\n")
self.chat_display.config(state='disabled')
self.chat_display.yview(tk.END)
# Append to conversation history
self.chatbot.conversation_history.append({"role": "user", "content": user_text})
# Clear input field
self.user_input.delete(0, tk.END)
# Start a new thread to process the message using multi-processing
threading.Thread(target=self.process_message, args=(user_text,)).start()
def process_message(self, user_input: str):
"""Process the user message, handle NLP, get response, and perform reflection."""
# Perform NLP enhancements
intent = self.chatbot.detect_intent(user_input)
sentiment = self.chatbot.analyze_sentiment(user_input)
entities = self.chatbot.extract_entities(user_input)
# Determine which worker to use
worker = self.chatbot.select_worker(user_input, intent)
if worker:
# Execute worker processing in a separate process
async_result = self.chatbot.mpm.execute(worker.process, (user_input, self.chatbot.settings))
response = async_result.get()
else:
# If no specific worker, use default AI response
async_result = self.chatbot.mpm.execute(self.chatbot.default_ai_response, (user_input,))
response = async_result.get()
# Append assistant response to conversation history
self.chatbot.conversation_history.append({"role": "assistant", "content": response})
# Perform self-reflection in a separate process
reflection = ""
if self.enable_reflection:
reflection_result = self.chatbot.mpm.execute(self.chatbot.recursive_self_reflection, (user_input, response))
reflection = reflection_result.get()
if reflection and not reflection.lower().startswith("error"):
# Append reflection to conversation history
self.chatbot.conversation_history.append({"role": "assistant", "content": reflection})
self.chatbot.reflection_history.append({"query": user_input, "response": response, "reflection": reflection})
# Meta-Learning: Adjust settings based on reflection
adjustment_result = self.chatbot.mpm.execute(self.chatbot.perform_meta_learning, (reflection,))
adjustment_result.get() # Handle adjustments internally
# Update configuration
self.chatbot.save_config()
# Display the assistant response
self.stream_response(response)
# Optionally display reflection
if self.enable_reflection and reflection and not reflection.lower().startswith("error"):
self.stream_response(reflection, role="Assistant (Reflection)")
def load_conversation(self):
"""Load conversation history from a file."""
filepath = filedialog.askopenfilename(title="Load Conversation", filetypes=(("JSON Files", "*.json"),))
if filepath:
try:
with open(filepath, 'r') as f:
data = json.load(f)
self.chatbot.conversation_history = data.get('history', [])
self.chatbot.reflection_history = data.get('reflection_history', [])
self.chatbot.settings = data.get('settings', self.chatbot.settings)
self.chat_display.config(state='normal')
self.chat_display.delete(1.0, tk.END)
for message in self.chatbot.conversation_history:
role = "You" if message['role'] == 'user' else "Assistant"
self.chat_display.insert(tk.END, f"{role}: {message['content']}\n\n")
for reflection in self.chatbot.reflection_history:
reflection_content = reflection.get('reflection', reflection.get('response', ''))
if reflection_content:
self.chat_display.insert(tk.END, f"Assistant (Reflection): {reflection_content}\n\n")
self.chat_display.config(state='disabled')
messagebox.showinfo("Success", "Conversation loaded successfully.")
except Exception as e:
messagebox.showerror("Error", f"Failed to load conversation: {str(e)}")
# Instantiate and run the chatbot
if __name__ == "__main__":
chatbot = AdvancedChatbot()
chatbot.run()