Further enhance and make it explicitly compute complex tasks with a more enhanced…
- User
Further enhance and make it explicitly compute complex tasks with a more enhanced chain-of-thought.
code - Assistant
Further enhance and make it explicitly compute complex tasks with a more enhanced chain-of-thought.
import g4f
from g4f.client import Client
import json
import re
import logging
import spacy
# Initialize spaCy English model
nlp = spacy.load('en_core_web_sm')
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class AdvancedChatbot:
def __init__(self, provider=g4f.Provider.AmigoChat, model="gpt-4o-2024-11-20"):
"""
Initialize the chatbot with a specific provider and model
"""
self.client = Client(provider=provider)
self.model = model
self.conversation_history = []
self.system_context = {
"personality": "You are a highly intelligent AI assistant capable of solving complex problems.",
"tone": "Professional and analytical",
"interests": ["advanced mathematics", "complex problem-solving", "logical reasoning"],
"reasoning_method": "Deep Analytical Thinking"
}
self.max_recursion_depth = 3 # Prevent infinite recursion
self.user_profile = {} # Store user-specific data
def format_system_message(self):
"""
Create a dynamic system message based on the context
"""
return f"""
{self.system_context['personality']}
Conversation Tone: {self.system_context['tone']}
Key Interests: {', '.join(self.system_context['interests'])}
Reasoning Method:
- Utilize Deep Analytical Thinking to solve complex queries.
- Break down problems into sub-components and analyze each thoroughly.
- Perform internal multi-step reasoning before providing an answer.
Guidelines:
- Provide clear and detailed explanations.
- Keep internal reasoning (chain-of-thought) hidden from the user.
- Ensure logical consistency and accuracy in responses.
- Handle advanced mathematical problems and complex tasks effectively.
- Personalize responses based on user preferences when applicable.
"""
def add_to_history(self, role, content):
"""
Add messages to conversation history with a max limit
"""
self.conversation_history.append({"role": role, "content": content})
# Limit history to manage token usage
if len(self.conversation_history) > 15:
self.summarize_history()
def summarize_history(self):
"""
Summarize older conversation history to maintain context within token limits
"""
logger.info("Summarizing conversation history to maintain token limits.")
# Combine messages except the last few
old_messages = self.conversation_history[:-10]
recent_messages = self.conversation_history[-10:]
# Create a summary prompt
summary_prompt = [
{"role": "system", "content": "Please summarize the following conversation history briefly to maintain context:\n"},
{"role": "user", "content": "\n".join([f"{msg['role']}: {msg['content']}" for msg in old_messages])}
]
try:
# Call the language model to summarize
response = self.client.chat.completions.create(
model=self.model,
messages=summary_prompt
)
summary = response.choices[0].message.content.strip()
# Replace old messages with the summary
self.conversation_history = [{"role": "system", "content": summary}] + recent_messages
logger.info("Conversation history summarized successfully.")
except Exception as e:
logger.error(f"Error summarizing history: {e}")
# If summarization fails, keep recent messages
self.conversation_history = recent_messages
def generate_response(self, user_message, current_depth=0):
"""
Generate a response using the chatbot's context and history
Incorporate deep analytical thinking with controlled recursion depth
"""
if current_depth > self.max_recursion_depth:
logger.warning("Maximum recursion depth reached.")
return "I'm finding it challenging to delve deeper into this topic right now. Could you please clarify or narrow down your question?"
# Prepare messages with system context and conversation history
messages = [
{"role": "system", "content": self.format_system_message()}
] + self.conversation_history + [
{"role": "user", "content": user_message}
]
# Add assistant's hidden reasoning prompt
hidden_reasoning_prompt = {
"role": "system",
"content": (
"Note: Before responding, take time to think through the problem step-by-step internally. "
"Perform any necessary calculations or logical reasoning. Do not reveal your internal thought process. "
"Only provide the final answer and explanation to the user."
)
}
messages.append(hidden_reasoning_prompt)
try:
# Create response using the client
response = self.client.chat.completions.create(
model=self.model,
messages=messages
)
assistant_message = response.choices[0].message.content.strip()
# Remove any hidden chain-of-thought if leaked
visible_response = self.filter_hidden_thoughts(assistant_message)
self.add_to_history("assistant", visible_response)
# Handle cases where deep reasoning is needed
if self.requires_further_breakdown(assistant_message) and current_depth < self.max_recursion_depth:
# Extract sub-questions
sub_questions = self.extract_sub_questions(user_message)
if sub_questions:
sub_responses = []
for sub_q in sub_questions:
# Recursive call with incremented depth
sub_resp = self.generate_response(sub_q, current_depth=current_depth+1)
sub_responses.append(sub_resp)
# Combine the assistant's main response with sub-responses
combined_response = visible_response + "\n\n" + "\n\n".join(sub_responses)
return combined_response
return visible_response
except Exception as e:
logger.error(f"Error generating response: {e}")
return "I'm having trouble generating a response right now."
def filter_hidden_thoughts(self, assistant_message):
"""
Remove any hidden chain-of-thought from the assistant's response
"""
# Remove text that might indicate internal reasoning
patterns = [
r'Thought Process:.*?(?=Final Answer:)', # Remove between 'Thought Process:' and 'Final Answer:'
r'\[\[\[.*?\]\]\]', # Remove text between '[[[' and ']]]'
r'Internal Reasoning:.*' # Remove lines starting with 'Internal Reasoning:'
]
for pattern in patterns:
assistant_message = re.sub(pattern, '', assistant_message, flags=re.DOTALL).strip()
logger.debug(f"Filtered assistant message: {assistant_message}")
return assistant_message
def requires_further_breakdown(self, assistant_message):
"""
Determine if the assistant's response indicates a need for further breakdown
"""
keywords = ["Let's break this down", "To solve this", "Firstly,", "First,"]
requires_breakdown = any(kw in assistant_message for kw in keywords)
logger.debug(f"Requires further breakdown: {requires_breakdown}")
return requires_breakdown
def extract_sub_questions(self, user_message):
"""
Extract sub-questions from the user's message using spaCy
"""
logger.info("Extracting sub-questions from user's message.")
doc = nlp(user_message)
sub_questions = []
# Identify sentences and clauses
for sent in doc.sents:
sub_questions.append(sent.text.strip())
# Check for conjunctions within sentences to further split
refined_sub_questions = []
for question in sub_questions:
sub_doc = nlp(question)
clauses = []
for token in sub_doc:
if token.dep_ == 'conj':
clause = sub_doc[token.left_edge.i:token.right_edge.i+1].text
clauses.append(clause.strip())
if clauses:
refined_sub_questions.extend(clauses)
else:
refined_sub_questions.append(question)
# Clean up and remove duplicates
refined_sub_questions = list(set(refined_sub_questions))
logger.debug(f"Extracted sub-questions: {refined_sub_questions}")
if len(refined_sub_questions) > 1:
return refined_sub_questions
else:
return None
def interact(self):
"""
Interactive chat loop
"""
print("🤖 Advanced Chatbot: Hello! I'm ready to assist you with complex problems. Type 'exit' to end the conversation.")
while True:
try:
user_input = input("You: ")
if user_input.lower() == 'exit':
print("🤖 Goodbye! Thanks for chatting.")
break
# Add user message to history
self.add_to_history("user", user_input)
print("🤖 ", end="")
bot_response = self.generate_response(user_input)
print(bot_response)
except KeyboardInterrupt:
print("\n🤖 Chat interrupted. Type 'exit' to quit.")
except Exception as e:
logger.error(f"An unexpected error occurred: {e}")
print("An unexpected error occurred. Please try again later.")
def change_context(self, **kwargs):
"""
Dynamically update the chatbot's system context
"""
for key, value in kwargs.items():
if key in self.system_context:
self.system_context[key] = value
print("🤖 Chatbot context updated!")
def update_user_profile(self, **kwargs):
"""
Update user-specific preferences
"""
self.user_profile.update(kwargs)
print("🤖 User profile updated!")
def main():
# Create an advanced chatbot instance
chatbot = AdvancedChatbot()
# Optional: Change context before starting
chatbot.change_context(
personality="You are an analytical AI assistant specializing in solving complex mathematical and logical problems.",
interests=["mathematics", "physics", "engineering", "complex problem-solving"]
)
# Optional: Update user profile
chatbot.update_user_profile(
preferred_style="detailed explanations",
level_of_detail="high"
)
# Start interactive chat
chatbot.interact()
if __name__ == "__main__":
main()
Certainly! To enhance the AdvancedChatbot for explicitly handling complex tasks with a more robust and sophisticated chain-of-thought (CoT) mechanism, we can implement several improvements:
Enhanced Chain-of-Thought Management:
Improved Recursive Processing:
Contextual Awareness and Personalization:
Performance and Efficiency Optimizations:
Below is the enhanced version of your AdvancedChatbot incorporating these improvements:
import g4f
from g4f.client import Client
import json
import re
import logging
import spacy
from typing import List, Optional
import asyncio
# Initialize spaCy English model
nlp = spacy.load('en_core_web_sm')
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class AdvancedChatbot:
def __init__(self, provider=g4f.Provider.AmigoChat, model="gpt-4o-2024-11-20"):
"""
Initialize the chatbot with a specific provider and model
"""
self.client = Client(provider=provider)
self.model = model
self.conversation_history = []
self.system_context = {
"personality": "You are a highly intelligent AI assistant capable of solving complex problems.",
"tone": "Professional and analytical",
"interests": ["advanced mathematics", "complex problem-solving", "logical reasoning"],
"reasoning_method": "Deep Analytical Thinking"
}
self.max_recursion_depth = 5 # Increased for more complex tasks
self.user_profile = {} # Store user-specific data
self.cot_log = [] # Internal Chain-of-Thought log
def format_system_message(self) -> str:
"""
Create a dynamic system message based on the context
"""
interests = ', '.join(self.system_context['interests'])
return (
f"{self.system_context['personality']}\n"
f"Conversation Tone: {self.system_context['tone']}\n"
f"Key Interests: {interests}\n\n"
"Reasoning Method:\n"
"- Utilize Deep Analytical Thinking to solve complex queries.\n"
"- Break down problems into sub-components and analyze each thoroughly.\n"
"- Perform internal multi-step reasoning before providing an answer.\n\n"
"Guidelines:\n"
"- Provide clear and detailed explanations.\n"
"- Keep internal reasoning (chain-of-thought) hidden from the user.\n"
"- Ensure logical consistency and accuracy in responses.\n"
"- Handle advanced mathematical problems and complex tasks effectively.\n"
"- Personalize responses based on user preferences when applicable."
)
def add_to_history(self, role: str, content: str):
"""
Add messages to conversation history with a max limit
"""
self.conversation_history.append({"role": role, "content": content})
# Limit history to manage token usage
if len(self.conversation_history) > 30:
self.summarize_history()
def summarize_history(self):
"""
Summarize older conversation history to maintain context within token limits
"""
logger.info("Summarizing conversation history to maintain token limits.")
# Combine messages except the last few
old_messages = self.conversation_history[:-15]
recent_messages = self.conversation_history[-15:]
# Create a summary prompt
summary_prompt = [
{"role": "system", "content": "Please summarize the following conversation briefly to maintain context:"},
{"role": "user", "content": "\n".join([f"{msg['role']}: {msg['content']}" for msg in old_messages])}
]
try:
# Call the language model to summarize
response = self.client.chat.completions.create(
model=self.model,
messages=summary_prompt
)
summary = response.choices[0].message.content.strip()
# Replace old messages with the summary
self.conversation_history = [{"role": "system", "content": summary}] + recent_messages
logger.info("Conversation history summarized successfully.")
except Exception as e:
logger.error(f"Error summarizing history: {e}")
# If summarization fails, keep recent messages
self.conversation_history = recent_messages
async def generate_response(self, user_message: str, current_depth: int = 0) -> str:
"""
Generate a response using the chatbot's context and history
Incorporate deep analytical thinking with controlled recursion depth
"""
if current_depth > self.max_recursion_depth:
logger.warning("Maximum recursion depth reached.")
return "I'm finding it challenging to delve deeper into this topic right now. Could you please clarify or narrow down your question?"
# Prepare messages with system context and conversation history
messages = [
{"role": "system", "content": self.format_system_message()}
] + self.conversation_history + [
{"role": "user", "content": user_message}
]
# Add assistant's hidden reasoning prompt
hidden_reasoning_prompt = {
"role": "system",
"content": (
"Note: Before responding, take time to think through the problem step-by-step internally. "
"Perform any necessary calculations or logical reasoning. Do not reveal your internal thought process. "
"Only provide the final answer and explanation to the user."
)
}
messages.append(hidden_reasoning_prompt)
# Append user profile preferences if any
if self.user_profile:
profile_info = "\n".join([f"{key}: {value}" for key, value in self.user_profile.items()])
messages.append({"role": "system", "content": f"User Preferences:\n{profile_info}"})
try:
# Create response using the client
response = await self.async_create_completion(messages)
assistant_message = response.choices[0].message.content.strip()
# Log the hidden chain-of-thought internally
self.log_chain_of_thought(response, assistant_message)
# Remove any hidden chain-of-thought if leaked
visible_response = self.filter_hidden_thoughts(assistant_message)
self.add_to_history("assistant", visible_response)
# Handle cases where deep reasoning is needed
if self.requires_further_breakdown(assistant_message) and current_depth < self.max_recursion_depth:
# Extract sub-questions
sub_questions = self.extract_sub_questions(user_message)
if sub_questions:
sub_responses = []
for sub_q in sub_questions:
# Recursive call with incremented depth
sub_resp = await self.generate_response(sub_q, current_depth=current_depth+1)
sub_responses.append(sub_resp)
# Combine the assistant's main response with sub-responses
combined_response = visible_response + "\n\n" + "\n\n".join(sub_responses)
return combined_response
return visible_response
except Exception as e:
logger.error(f"Error generating response: {e}")
return "I'm having trouble generating a response right now."
def log_chain_of_thought(self, response, assistant_message):
"""
Log the internal chain-of-thought for debugging and improvement purposes.
This remains hidden from the user.
"""
cogt = response.choices[0].message.get('cogt', None) # Assuming 'cogt' contains the chain-of-thought
if cogt:
self.cot_log.append({
"assistant_message": assistant_message,
"chain_of_thought": cogt
})
logger.debug(f"Logged chain-of-thought: {cogt}")
else:
logger.debug("No chain-of-thought found in the response.")
def filter_hidden_thoughts(self, assistant_message: str) -> str:
"""
Remove any hidden chain-of-thought from the assistant's response
"""
# Remove text that might indicate internal reasoning
patterns = [
r'Thought Process:.*?(?=Final Answer:)', # Remove between 'Thought Process:' and 'Final Answer:'
r'\[\[\[.*?\]\]\]', # Remove text between '[[[' and ']]]'
r'Internal Reasoning:.*', # Remove lines starting with 'Internal Reasoning:'
r'(?i)step-by-step explanation:.*' # Remove step-by-step explanations
]
for pattern in patterns:
assistant_message = re.sub(pattern, '', assistant_message, flags=re.DOTALL | re.IGNORECASE).strip()
logger.debug(f"Filtered assistant message: {assistant_message}")
return assistant_message
def requires_further_breakdown(self, assistant_message: str) -> bool:
"""
Determine if the assistant's response indicates a need for further breakdown
"""
keywords = ["let's break this down", "to solve this", "firstly,", "first,"]
requires_breakdown = any(kw.lower() in assistant_message.lower() for kw in keywords)
logger.debug(f"Requires further breakdown: {requires_breakdown}")
return requires_breakdown
def extract_sub_questions(self, user_message: str) -> Optional[List[str]]:
"""
Extract sub-questions from the user's message using spaCy
"""
logger.info("Extracting sub-questions from user's message.")
doc = nlp(user_message)
sub_questions = []
# Identify sentences
for sent in doc.sents:
sub_questions.append(sent.text.strip())
# Further split sentences with conjunctions
refined_sub_questions = []
for question in sub_questions:
sub_doc = nlp(question)
clauses = []
for token in sub_doc:
if token.dep_ == 'conj' and token.pos_ == 'CCONJ':
clause = sub_doc[token.left_edge.i:token.right_edge.i+1].text
clauses.append(clause.strip())
if clauses:
refined_sub_questions.extend(clauses)
else:
refined_sub_questions.append(question)
# Clean up and remove duplicates
refined_sub_questions = [q for q in refined_sub_questions if q]
refined_sub_questions = list(set(refined_sub_questions))
logger.debug(f"Extracted sub-questions: {refined_sub_questions}")
if len(refined_sub_questions) > 1:
return refined_sub_questions
else:
return None
async def async_create_completion(self, messages: List[dict]) -> dict:
"""
Asynchronous wrapper for the client's chat completion
"""
loop = asyncio.get_event_loop()
return await loop.run_in_executor(None, lambda: self.client.chat.completions.create(
model=self.model,
messages=messages
))
def interact(self):
"""
Interactive chat loop using asyncio for asynchronous operations
"""
print("🤖 Advanced Chatbot: Hello! I'm ready to assist you with complex problems. Type 'exit' to end the conversation.")
loop = asyncio.get_event_loop()
loop.run_until_complete(self.async_interact())
async def async_interact(self):
"""
Asynchronous interactive chat loop
"""
while True:
try:
user_input = await asyncio.get_event_loop().run_in_executor(None, input, "You: ")
if user_input.lower() == 'exit':
print("🤖 Goodbye! Thanks for chatting.")
break
# Add user message to history
self.add_to_history("user", user_input)
print("🤖 ", end="")
bot_response = await self.generate_response(user_input)
print(bot_response)
except KeyboardInterrupt:
print("\n🤖 Chat interrupted. Type 'exit' to quit.")
except Exception as e:
logger.error(f"An unexpected error occurred: {e}")
print("An unexpected error occurred. Please try again later.")
def change_context(self, **kwargs):
"""
Dynamically update the chatbot's system context
"""
for key, value in kwargs.items():
if key in self.system_context:
self.system_context[key] = value
print("🤖 Chatbot context updated!")
def update_user_profile(self, **kwargs):
"""
Update user-specific preferences
"""
self.user_profile.update(kwargs)
print("🤖 User profile updated!")
def get_cot_log(self) -> List[dict]:
"""
Retrieve the internal Chain-of-Thought log for review or analysis
"""
return self.cot_log
def main():
# Create an advanced chatbot instance
chatbot = AdvancedChatbot()
# Optional: Change context before starting
chatbot.change_context(
personality="You are an analytical AI assistant specializing in solving complex mathematical and logical problems.",
interests=["mathematics", "physics", "engineering", "complex problem-solving"]
)
# Optional: Update user profile
chatbot.update_user_profile(
preferred_style="detailed explanations",
level_of_detail="high",
preferred_language="English"
)
# Start interactive chat
chatbot.interact()
if __name__ == "__main__":
main()
Asynchronous Processing:
asyncio Integration: The chatbot now uses Python's asyncio library to handle asynchronous operations, allowing it to handle multiple tasks concurrently without blocking the main thread. This is particularly beneficial for scalability and responsiveness.async_create_completion Method: An asynchronous wrapper around the client's completion method ensures that API calls do not block the interaction loop.Enhanced Chain-of-Thought (CoT) Management:
cot_log): Introduced a mechanism to log the internal chain-of-thought separately. This log can be used for debugging and improving the reasoning processes without exposing it to the user.log_chain_of_thought Method: Captures and stores the CoT from the assistant's response. This assumes that the API provides access to the CoT, which may require specific configurations or support from the provider.Improved Recursive Processing:
max_recursion_depth: Increased from 3 to 5 to allow deeper recursive calls for more complex tasks.Advanced Sub-question Extraction:
Contextual Awareness and Personalization:
user_profile to tailor responses. Preferences like preferred_style, level_of_detail, and preferred_language can influence the assistant's responses.Error Handling Enhancements: While the current implementation includes basic error handling, consider implementing more granular exception handling to manage specific error types effectively.
Unit Testing: Implement unit tests for each method to ensure reliability and ease of maintenance. This can help in verifying that each component functions as expected, especially after making significant changes.
Security Considerations: Ensure that sensitive user data stored in user_profile is handled securely, adhering to best practices for data privacy and protection.
API Rate Limiting: Implement mechanisms to respect API rate limits, preventing potential service disruptions due to excessive requests.
Scalability: For deployments expecting high traffic, consider scaling strategies such as load balancing and distributed processing to maintain performance.
By incorporating these enhancements, the AdvancedChatbot becomes more capable of handling complex tasks with a sophisticated and efficient chain-of-thought mechanism, providing users with detailed, accurate, and personalized responses.
Not yet included in a published release.
Robust Filtering of Hidden Thoughts:
Performance Optimizations:
Utility Methods:
get_cot_log Method: Provides access to the internal CoT log for potential analysis or debugging, aiding in the continuous improvement of the chatbot's reasoning capabilities.