NoahsKI / ai_improvements.py
noah33565's picture
Upload 221 files
8d3de43 verified
"""
COMPREHENSIVE AI SYSTEM IMPROVEMENTS & BUG FIXES
Enhances all handlers and fixes identified issues
"""
import re
import logging
from typing import Dict, List, Tuple, Optional, Any
from collections import defaultdict
import json
logger = logging.getLogger(__name__)
class AISystemImprovements:
"""Improvements and bug fixes for all AI systems"""
# ========================================================================
# CODE GENERATION IMPROVEMENTS
# ========================================================================
@staticmethod
def extract_code_intent(message: str) -> Optional[str]:
"""Better code intent extraction"""
message_lower = message.lower()
# Code keywords
code_keywords = {
'python': ['python', '.py', 'django', 'flask', 'pandas', 'numpy'],
'javascript': ['javascript', 'js', 'node', 'react', 'vue', 'typescript'],
'java': ['java', 'spring', 'maven', 'gradle'],
'cpp': ['c++', 'cpp', 'c\\+\\+'],
'rust': ['rust', 'cargo'],
'go': ['golang', 'go', 'goroutine'],
'php': ['php', 'laravel', 'symfony'],
'csharp': ['c#', 'csharp', 'dotnet', '.net'],
'sql': ['sql', 'mysql', 'postgres', 'database'],
'html_css': ['html', 'css', 'bootstrap', 'tailwind'],
}
for lang, keywords in code_keywords.items():
if any(kw in message_lower for kw in keywords):
return lang
return None
@staticmethod
def improve_code_generation(prompt: str, language: str) -> Dict:
"""Generate better code with proper structure and Python improvements"""
# Define high-quality code templates
python_templates = {
'function': '''def calculate_fibonacci(n: int) -> list[int]:
"""Generate Fibonacci sequence up to n numbers.
Args:
n: Number of Fibonacci numbers to generate
Returns:
List of Fibonacci numbers
"""
if n <= 0:
return []
elif n == 1:
return [0]
fib_sequence = [0, 1]
for i in range(2, n):
fib_sequence.append(fib_sequence[i-1] + fib_sequence[i-2])
return fib_sequence[:n]
# Usage
if __name__ == "__main__":
result = calculate_fibonacci(10)
print(f"Fibonacci sequence: {result}")''',
'class': '''class DataProcessor:
"""Process and analyze data efficiently."""
def __init__(self, name: str):
"""Initialize processor with name.
Args:
name: Name of the processor
"""
self.name = name
self.data = []
def add_data(self, values: list) -> None:
"""Add data to processor.
Args:
values: List of values to add
"""
self.data.extend(values)
def process(self) -> dict:
"""Process collected data.
Returns:
Dictionary with processing results
"""
if not self.data:
return {'error': 'No data to process'}
return {
'count': len(self.data),
'sum': sum(self.data),
'average': sum(self.data) / len(self.data),
'min': min(self.data),
'max': max(self.data)
}
# Usage
if __name__ == "__main__":
processor = DataProcessor("DataAnalyzer")
processor.add_data([10, 20, 30, 40, 50])
result = processor.process()
print(result)''',
'loop': '''def process_items(items: list, multiplier: int = 2) -> list:
"""Process items with multiplier.
Args:
items: List of items to process
multiplier: Multiplication factor
Returns:
List of processed items
"""
results = []
for item in items:
if isinstance(item, (int, float)):
results.append(item * multiplier)
else:
results.append(item)
return results
# More Pythonic with list comprehension:
def process_items_modern(items: list, multiplier: int = 2) -> list:
"""Process items using list comprehension."""
return [item * multiplier if isinstance(item, (int, float)) else item for item in items]
# Usage
items = [1, 2, 3, 4, 5]
print(process_items(items))
print(process_items_modern(items, multiplier=3))''',
'condition': '''def validate_input(value: any, min_val: int = 0, max_val: int = 100) -> tuple[bool, str]:
"""Validate if value is within range.
Args:
value: Value to validate
min_val: Minimum allowed value
max_val: Maximum allowed value
Returns:
Tuple of (is_valid, message)
"""
if not isinstance(value, (int, float)):
return False, "Value must be a number"
if value < min_val:
return False, f"Value must be >= {min_val}"
elif value > max_val:
return False, f"Value must be <= {max_val}"
else:
return True, "Value is valid"
# Usage
is_valid, message = validate_input(50)
print(f"Valid: {is_valid}, Message: {message}")''',
}
javascript_templates = {
'function': '''function calculateSum(numbers) {
/**
* Calculate sum of array numbers
* @param {number[]} numbers - Array of numbers
* @returns {number} Sum of all numbers
*/
if (!Array.isArray(numbers) || numbers.length === 0) {
return 0;
}
return numbers.reduce((acc, num) => acc + (typeof num === 'number' ? num : 0), 0);
}
// Usage
console.log(calculateSum([1, 2, 3, 4, 5])); // Output: 15''',
'class': '''class UserManager {
/**
* Manage user data and operations
*/
constructor(name) {
this.name = name;
this.users = [];
}
addUser(user) {
/**
* Add user to manager
* @param {object} user - User object
*/
if (user.id && user.name) {
this.users.push(user);
return true;
}
return false;
}
getUser(id) {
/**
* Get user by ID
* @param {number} id - User ID
* @returns {object|null} User object or null
*/
return this.users.find(u => u.id === id) || null;
}
}
// Usage
const manager = new UserManager("Admin");
manager.addUser({ id: 1, name: "John" });
console.log(manager.getUser(1));''',
}
# Templates for other languages
templates_by_lang = {
'python': python_templates,
'javascript': javascript_templates,
}
# Detect code type from prompt
prompt_lower = prompt.lower()
code_type = 'function' # Default
for ctype in ['function', 'class', 'loop', 'condition']:
if ctype in prompt_lower:
code_type = ctype
break
# Get appropriate template
lang_templates = templates_by_lang.get(language, python_templates)
code_template = lang_templates.get(code_type, lang_templates.get('function', ''))
return {
'success': True,
'type': 'code',
'language': language,
'code': code_template,
'code_type': code_type,
'quality': 'high',
'has_documentation': True,
'has_usage_example': True,
'method': 'improved_template'
}
# ========================================================================
# TRANSLATION IMPROVEMENTS
# ========================================================================
@staticmethod
def extract_language_pair(message: str, current_lang: str) -> Tuple[str, str]:
"""Extract source and target languages"""
message_lower = message.lower()
# Language names
all_languages = {
'english': ['english', 'en', 'eng', 'english'],
'german': ['german', 'de', 'deutsch'],
'french': ['french', 'fr', 'français'],
'spanish': ['spanish', 'es', 'español'],
'italian': ['italian', 'it', 'italiano'],
'portuguese': ['portuguese', 'pt', 'português'],
'russian': ['russian', 'ru', 'русский'],
'japanese': ['japanese', 'ja', 'jp', '日本語'],
'chinese': ['chinese', 'zh', 'cn', '中文'],
'korean': ['korean', 'ko', 'kr', '한국어'],
'dutch': ['dutch', 'nl'],
'polish': ['polish', 'pl'],
'swedish': ['swedish', 'sv'],
}
# Find target language
target_lang = current_lang
for lang, keywords in all_languages.items():
if any(kw in message_lower for kw in keywords):
target_lang = lang[:2] # Convert to language code
break
source_lang = current_lang
return (source_lang, target_lang)
@staticmethod
def translate_text(text: str, source_lang: str, target_lang: str) -> Dict:
"""Simple translation using pattern matching"""
# Common translation mapping
simple_translations = {
('en', 'de'): {
'hello': 'hallo',
'world': 'welt',
'good morning': 'guten morgen',
'good night': 'gute nacht',
'thank you': 'danke',
'please': 'bitte',
'yes': 'ja',
'no': 'nein',
'how are you': 'wie geht es dir',
'my name is': 'mein name ist',
'what is': 'was ist',
'where is': 'wo ist',
},
('en', 'fr'): {
'hello': 'bonjour',
'world': 'monde',
'good morning': 'bon matin',
'thank you': 'merci',
'please': 's\'il vous plaît',
'yes': 'oui',
'no': 'non',
},
('en', 'es'): {
'hello': 'hola',
'world': 'mundo',
'good morning': 'buenos días',
'thank you': 'gracias',
'please': 'por favor',
'yes': 'sí',
'no': 'no',
},
}
# Get translation mapping
pair = (source_lang, target_lang[:2])
translations = simple_translations.get(pair, {})
# Translate
result = text.lower()
for src, tgt in translations.items():
if src in result:
result = result.replace(src, tgt)
return {
'type': 'translation',
'success': True,
'original': text,
'translated': result,
'source_language': source_lang,
'target_language': target_lang,
'confidence': 0.75,
'method': 'pattern_matching'
}
# ========================================================================
# CALCULATION IMPROVEMENTS
# ========================================================================
@staticmethod
def safe_calculate(expression: str) -> Dict:
"""Safely evaluate mathematical expressions"""
try:
# Remove dangerous characters
expression = expression.replace('^', '**') # ^ to **
expression = expression.strip()
# Validate expression
allowed_chars = set('0123456789+-*/.()% sqrtsincostan logabspi e ')
if not all(c.lower() in allowed_chars for c in expression):
return {'success': False, 'error': 'Invalid characters'}
# Check for dangerous patterns
if 'import' in expression or 'exec' in expression or '__' in expression:
return {'success': False, 'error': 'Dangerous expression'}
# Math functions
import math
safe_dict = {
'sqrt': math.sqrt,
'sin': math.sin,
'cos': math.cos,
'tan': math.tan,
'log': math.log,
'log10': math.log10,
'abs': abs,
'pi': math.pi,
'e': math.e,
}
# Evaluate
result = eval(expression, {"__builtins__": {}}, safe_dict)
return {
'success': True,
'expression': expression,
'result': result,
'type': 'calculation',
'method': 'safe_eval'
}
except ZeroDivisionError:
return {'success': False, 'error': 'Division by zero'}
except Exception as e:
return {'success': False, 'error': str(e)}
# ========================================================================
# KNOWLEDGE QUERY IMPROVEMENTS
# ========================================================================
@staticmethod
def improve_knowledge_response(topic: str, search_results: List[Dict]) -> Dict:
"""Synthesize better knowledge responses"""
if not search_results:
return {
'success': False,
'error': 'No results found'
}
# Extract key information
key_info = []
for result in search_results[:3]: # Top 3 results
content = result.get('content', '')
if content:
# Get first 200 chars
key_info.append(content[:200])
# Synthesize
response = f"Based on search results about '{topic}':\n\n"
response += "\n\n".join(key_info)
return {
'success': True,
'type': 'knowledge',
'topic': topic,
'content': response,
'source': 'synthesized_search',
'quality': 0.8
}
# ========================================================================
# CONVERSATION IMPROVEMENTS
# ========================================================================
@staticmethod
def improve_conversation_response(message: str, context: List[Dict]) -> Optional[str]:
"""Generate more natural conversation responses"""
message_lower = message.lower()
# Context-aware responses
responses = {
'greeting': [
"Hello! How can I help?",
"Hi there! What can I do for you?",
"Hey! What's on your mind?",
"Welcome! How can I assist you?",
],
'greeting_de': [
"Hallo! Wie kann ich dir helfen?",
"Guten Tag! Was kann ich für dich tun?",
"Hallo! Worum geht es?",
],
'small_talk': [
"That's interesting! Tell me more.",
"I see. What else?",
"Got it. How did that make you feel?",
"Interesting perspective!",
],
'question': [
"Great question! Let me help with that.",
"That's a good point. Let me think about it.",
"I can help with that!",
],
'thank_you': [
"You're welcome!",
"Happy to help!",
"Glad I could assist!",
"Anytime!",
],
'thank_you_de': [
"Gerne geschehen!",
"Immer gerne!",
"Kein Problem!",
],
}
# Detect intent
if any(x in message_lower for x in ['hello', 'hi', 'hey', 'hallo', 'guten']):
import random
lang_key = 'greeting_de' if any(x in message_lower for x in ['hallo', 'guten']) else 'greeting'
return random.choice(responses[lang_key])
elif any(x in message_lower for x in ['thank', 'thanks', 'danke', 'danken']):
import random
lang_key = 'thank_you_de' if any(x in message_lower for x in ['danke', 'danken']) else 'thank_you'
return random.choice(responses[lang_key])
elif '?' in message:
import random
return random.choice(responses['question'])
else:
import random
return random.choice(responses['small_talk'])
# Integration function
def apply_all_improvements(handler_name: str, *args, **kwargs) -> Optional[Dict]:
"""
Apply improvements to any handler
Args:
handler_name: Name of handler to improve
args, kwargs: Handler arguments
Returns:
Improved result or None if not applicable
"""
improvements = AISystemImprovements()
if handler_name in ('code', 'code_generation'):
prompt = args[0] if args else kwargs.get('message', '')
language = args[1] if len(args) > 1 else kwargs.get('language', 'python')
# Extract language from prompt if not specified
detected_lang = improvements.extract_code_intent(prompt)
if detected_lang:
language = detected_lang
result = improvements.improve_code_generation(prompt, language)
if result.get('code'):
return {
'type': 'code',
'success': True,
'code': result['code'],
'explanation': f'Generated {result["language"]} code',
'language': result['language'],
'confidence': 0.8
}
return result
elif handler_name == 'translation':
message = args[0] if args else kwargs.get('message', '')
language = args[1] if len(args) > 1 else kwargs.get('language', 'en')
source_lang, target_lang = improvements.extract_language_pair(message, language)
# Extract text to translate
text = re.sub(r'(translate|übersetze)\s+', '', message, flags=re.IGNORECASE).strip()
text = re.sub(r'\s+(to|into|nach|zu|in)\s+\w+', '', text, flags=re.IGNORECASE).strip()
result = improvements.translate_text(text, source_lang, target_lang)
if result and result.get('translated'):
return {
'type': 'translation',
'success': True,
'content': result['translated'],
'original': result.get('original'),
'source_lang': source_lang,
'target_lang': target_lang,
'confidence': 0.75
}
return result
elif handler_name == 'calculation':
expression = args[0] if args else kwargs.get('message', '')
# Clean up expression
expression = re.sub(r'(calculate|compute|solve|what is|berechne|rechne)\s+', '', expression, flags=re.IGNORECASE)
result = improvements.safe_calculate(expression)
if result and result.get('success'):
return {
'type': 'math',
'success': True,
'expression': result['expression'],
'result': result.get('result'),
'confidence': 0.9
}
return result
elif handler_name == 'knowledge':
message = args[0] if args else kwargs.get('message', '')
search_results = args[1] if len(args) > 1 else kwargs.get('search_results', [])
if search_results:
result = improvements.improve_knowledge_response(message, search_results)
else:
# Generate basic knowledge response without search results
result = {
'success': True,
'type': 'knowledge',
'topic': message,
'content': f"Searching for information about '{message}'...",
'source': 'knowledge_initiator'
}
if result and result.get('content'):
return {
'type': 'text',
'success': True,
'content': result.get('content'),
'source': 'improved_knowledge',
'confidence': 0.8
}
return None
elif handler_name == 'conversation':
message = args[0] if args else kwargs.get('message', '')
context = args[2] if len(args) > 2 else kwargs.get('context', [])
response = improvements.improve_conversation_response(message, context)
if response:
return {
'type': 'text',
'success': True,
'content': response,
'source': 'improved_conversation'
}
return None
return None