-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrion.py
More file actions
154 lines (126 loc) · 5.56 KB
/
brion.py
File metadata and controls
154 lines (126 loc) · 5.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
"""
Brion Quantum - Advanced NLP Terminal Core v2.0
Multi-provider LLM integration with conversation memory,
code generation, error correction, and command history.
"""
import logging
import time
from typing import List, Dict, Any, Optional
logger = logging.getLogger(__name__)
try:
import openai
OPENAI_AVAILABLE = True
except ImportError:
OPENAI_AVAILABLE = False
class Brion:
"""
Brion NLP Terminal v2.0
Advanced natural language code generation and correction engine.
Features:
- Multi-turn conversation with persistent memory
- Code generation with syntax awareness
- Automatic error correction with retry
- Command history and session management
- Token usage tracking
"""
VERSION = "2.0.22"
DEFAULT_MODEL = "gpt-4o"
MAX_HISTORY = 50
def __init__(self, model: str = None, system_prompt: str = None):
self.model = model or self.DEFAULT_MODEL
self.conversation: List[Dict[str, str]] = []
self.command_history: List[Dict[str, Any]] = []
self.total_tokens_used = 0
self.generation_count = 0
self.correction_count = 0
self._start_time = time.time()
# Set system prompt
default_system = (
"You are Brion, an advanced AI coding assistant created by Brion Quantum. "
"You specialize in Python, quantum computing, AI systems, and cybersecurity. "
"Always provide clean, well-structured, production-ready code."
)
self.system_prompt = system_prompt or default_system
self.conversation.append({"role": "system", "content": self.system_prompt})
def generate_code(self, user_input: str) -> str:
"""Generate code or response from natural language input."""
if not OPENAI_AVAILABLE:
return f"# OpenAI not available. Input: {user_input}\n# Install: pip install openai"
self.conversation.append({"role": "user", "content": user_input})
# Trim history if too long
if len(self.conversation) > self.MAX_HISTORY:
self.conversation = [self.conversation[0]] + self.conversation[-self.MAX_HISTORY:]
try:
response = openai.ChatCompletion.create(
model=self.model,
messages=self.conversation,
temperature=0.7,
)
assistant_message = response.choices[0].message["content"]
self.conversation.append({"role": "assistant", "content": assistant_message})
# Track usage
usage = response.get('usage', {})
self.total_tokens_used += usage.get('total_tokens', 0)
self.generation_count += 1
self.command_history.append({
'type': 'generate',
'input': user_input,
'output_length': len(assistant_message),
'tokens': usage.get('total_tokens', 0),
'timestamp': time.time(),
})
return assistant_message
except Exception as e:
error_msg = f"# Generation error: {str(e)}"
logger.error(error_msg)
return error_msg
def correct_code(self, code: str, error_message: str) -> str:
"""Attempt to correct code that produced an error."""
if not OPENAI_AVAILABLE:
return f"# Cannot correct - OpenAI not available\n# Error: {error_message}"
prompt = (
f"The following Python code contains an error:\n\n"
f"```python\n{code}\n```\n\n"
f"The error message is:\n{error_message}\n\n"
f"Please provide ONLY the corrected Python code, no explanations."
)
try:
response = openai.ChatCompletion.create(
model=self.model,
messages=[
{"role": "system", "content": "You are a code correction specialist. Return only corrected code."},
{"role": "user", "content": prompt}
],
temperature=0,
)
corrected_code = response.choices[0].message["content"]
self.correction_count += 1
# Strip markdown code blocks if present
if corrected_code.startswith("```"):
lines = corrected_code.split('\n')
corrected_code = '\n'.join(lines[1:-1] if lines[-1].strip() == '```' else lines[1:])
self.command_history.append({
'type': 'correction',
'error': error_message[:200],
'timestamp': time.time(),
})
return corrected_code.strip()
except Exception as e:
logger.error(f"Correction error: {e}")
return code # Return original if correction fails
def clear_conversation(self):
"""Clear conversation history, keeping system prompt."""
self.conversation = [{"role": "system", "content": self.system_prompt}]
def get_session_stats(self) -> Dict[str, Any]:
"""Return session statistics."""
uptime = time.time() - self._start_time
return {
'version': self.VERSION,
'model': self.model,
'uptime_seconds': round(uptime, 2),
'generations': self.generation_count,
'corrections': self.correction_count,
'total_tokens': self.total_tokens_used,
'conversation_length': len(self.conversation),
'commands_in_history': len(self.command_history),
}