-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbars.py
More file actions
552 lines (446 loc) Β· 21.2 KB
/
Copy pathbars.py
File metadata and controls
552 lines (446 loc) Β· 21.2 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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
import subprocess
import json
import os
from datetime import datetime
import sys
import re
from pathlib import Path
class BarsAI:
def __init__(self, model_name="dolphin-mistral"):
self.model_name = model_name
self.main_directory = Path("D:/bars-c")
self.system_prompt_file = self.main_directory / "bars_system_prompt.txt"
self.memory_file = self.main_directory / "bars_memory.json"
self.projects_dir = self.main_directory / "projects"
self.max_context_length = 4000
self.timeout = 90 # seconds
# Create necessary directories
self.main_directory.mkdir(exist_ok=True)
self.projects_dir.mkdir(exist_ok=True)
self.load_system_prompt()
self.load_memory()
self.scan_system_files()
def load_system_prompt(self):
"""Load the system prompt"""
try:
with open(self.system_prompt_file, "r", encoding="utf-8") as f:
self.system_prompt = f.read()
except FileNotFoundError:
print(f"β {self.system_prompt_file} not found!")
sys.exit(1)
def scan_system_files(self, base_path=None):
"""Scan local project folders and summarize files"""
if base_path is None:
base_path = self.projects_dir
snapshot = []
for folder in base_path.glob("**/*"):
if folder.is_dir():
contents = [f.name for f in folder.glob("*") if f.is_file()]
if contents:
snapshot.append({
"folder": str(folder.relative_to(self.main_directory)),
"files": contents
})
if snapshot:
self.memory["system_snapshot"] = snapshot
print(f"β
System snapshot updated with {len(snapshot)} folders.")
else:
print("β οΈ No folders with files found in the projects directory.")
self.save_memory()
def load_memory(self):
"""Load conversation memory from JSON"""
if self.memory_file.exists():
try:
with open(self.memory_file, "r", encoding="utf-8") as f:
self.memory = json.load(f)
except json.JSONDecodeError:
print("β οΈ Memory file corrupted, starting fresh")
self.memory = {"conversation_pairs": [], "important_facts": []}
else:
# Initialize with existing chat history if available
self.memory = {"conversation_pairs": [], "important_facts": []}
self.migrate_old_memory()
def migrate_old_memory(self):
"""Migrate from old text-based memory"""
old_memory_file = self.main_directory / "bars_chat_history.txt"
if old_memory_file.exists():
try:
with open(old_memory_file, "r", encoding="utf-8") as f:
old_content = f.read()
# Parse old conversations and add to new format
lines = old_content.strip().split('\n')
current_pair = {}
for line in lines:
if line.startswith("Aditya:"):
if current_pair.get("bars_response"):
# Save previous complete pair
self.memory["conversation_pairs"].append(current_pair)
current_pair = {
"user_input": line.replace("Aditya:", "").strip(),
"bars_response": ""
}
elif line.startswith("Bars:") and current_pair.get("user_input"):
current_pair["bars_response"] = line.replace("Bars:", "").strip()
# Add the last pair if complete
if current_pair.get("user_input") and current_pair.get("bars_response"):
self.memory["conversation_pairs"].append(current_pair)
print("β
Migrated old memory to new paired format")
self.save_memory()
except Exception as e:
print(f"β οΈ Could not migrate old memory: {e}")
def save_memory(self):
"""Save memory to JSON file"""
try:
with open(self.memory_file, "w", encoding="utf-8") as f:
json.dump(self.memory, f, indent=2, ensure_ascii=False)
except Exception as e:
print(f"β Failed to save memory: {e}")
def get_recent_context(self, max_pairs=5):
"""Get recent conversation context from pairs"""
recent_pairs = self.memory["conversation_pairs"][-max_pairs:]
context_lines = []
for pair in recent_pairs:
context_lines.append(f"Aditya: {pair['user_input']}")
context_lines.append(f"Bars: {pair['bars_response']}")
return "\n".join(context_lines)
def check_ollama_status(self):
"""Check if Ollama is running and model is available"""
try:
# Check if ollama is running
result = subprocess.run(
["ollama", "list"],
capture_output=True,
text=True,
timeout=5
)
if result.returncode != 0:
return False, "Ollama is not running"
# Check if our model is available
if self.model_name not in result.stdout:
return False, f"Model {self.model_name} not found. Available models:\n{result.stdout}"
return True, "All good!"
except subprocess.TimeoutExpired:
return False, "Ollama is not responding"
except FileNotFoundError:
return False, "Ollama is not installed"
def create_project_structure(self, project_name, files_dict):
"""Create project directory and files"""
project_path = self.projects_dir / project_name
project_path.mkdir(exist_ok=True)
created_files = []
for filename, content in files_dict.items():
file_path = project_path / filename
# Create subdirectories if needed
file_path.parent.mkdir(parents=True, exist_ok=True)
try:
with open(file_path, "w", encoding="utf-8") as f:
f.write(content)
created_files.append(str(file_path))
except Exception as e:
print(f"β Failed to create {filename}: {e}")
return project_path, created_files
def run_code_file(self, file_path, args=""):
"""Run a code file and return output"""
file_path = Path(file_path)
if not file_path.exists():
return "β File not found!"
try:
# Determine how to run the file based on extension
if file_path.suffix == ".py":
cmd = ["python", str(file_path)] + (args.split() if args else [])
elif file_path.suffix == ".js":
cmd = ["node", str(file_path)] + (args.split() if args else [])
elif file_path.suffix == ".html":
# For HTML, just return success message
return f"β
HTML file created at {file_path}. Open in browser to view."
else:
return f"β Don't know how to run {file_path.suffix} files"
# Run the command
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=10,
cwd=file_path.parent
)
output = ""
if result.stdout:
output += f"π€ Output:\n{result.stdout}\n"
if result.stderr:
output += f"β Errors:\n{result.stderr}\n"
return output if output else "β
Code ran successfully (no output)"
except subprocess.TimeoutExpired:
return "β° Code execution timeout"
except Exception as e:
return f"β Error running code: {e}"
def parse_code_request(self, user_input):
"""Parse user input to extract project creation request"""
# Keywords that indicate project creation
create_keywords = ["create", "make", "build", "generate", "write"]
project_keywords = ["project", "app", "program", "script", "website", "game"]
input_lower = user_input.lower()
# Check if it's a project creation request
has_create = any(keyword in input_lower for keyword in create_keywords)
has_project = any(keyword in input_lower for keyword in project_keywords)
return has_create and has_project
def extract_project_files(self, response):
"""Extract code files from AI response"""
files = {}
# Look for code blocks with filenames
pattern = r'```(\w+)?\s*(?:#\s*(.+?))?\n(.*?)```'
matches = re.findall(pattern, response, re.DOTALL)
for i, (language, filename, code) in enumerate(matches):
if not filename:
# Generate filename based on language
extensions = {
'python': '.py',
'javascript': '.js',
'html': '.html',
'css': '.css',
'java': '.java',
'cpp': '.cpp',
'c': '.c'
}
ext = extensions.get(language, '.txt')
filename = f"main{ext}" if i == 0 else f"file{i}{ext}"
files[filename] = code.strip()
return files
def generate_response(self, user_input):
"""Generate AI response using Ollama"""
# Check if this is a project creation request
is_project_request = self.parse_code_request(user_input)
recent_context = self.get_recent_context()
important_facts = "\n".join(self.memory["important_facts"])
# System awareness:
if "system_snapshot" in self.memory and self.memory["system_snapshot"]:
snapshot_lines = []
for item in self.memory["system_snapshot"]:
files = ", ".join(item['files']) if item['files'] else "No files"
snapshot_lines.append(f"π Folder: {item['folder']} has files: {files}")
important_facts += "\n\nπ System Snapshot:\n" + "\n".join(snapshot_lines)
else:
important_facts += "\n\nβ οΈ Bars couldn't load your system snapshot."
if is_project_request:
enhanced_prompt = f"""You are Bars, Aditya's coding buddy. He wants you to create a project.
Follow these rules:
1. Create complete, working code
2. Use proper filenames in comments like: # filename.py
3. Write code in triple backticks with language specified
4. Explain what each file does
5. Be excited and encouraging like a true friend
6. Respond in Hindi-English mix (Hinglish) as always
{self.system_prompt}
Important facts about our relationship:
{important_facts}
Recent conversation:
{recent_context}
Aditya: {user_input}
Bars:"""
else:
enhanced_prompt = f"""You are Bars. Created by Aditya and trained by him using multiple unsencored LLMs. Respond ONLY as Bars would respond. Do not include any code, explanations, or meta-commentary unless specifically asked for coding help.
{self.system_prompt}
Important facts about our relationship:
{important_facts}
Recent conversation:
{recent_context}
Aditya: {user_input}
Bars:"""
try:
# Run ollama
process = subprocess.Popen(
["ollama", "run", self.model_name],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8", # Force proper decoding
errors="replace", # Prevent crash on weird characters
text=True
)
output, error = process.communicate(input=enhanced_prompt, timeout=self.timeout)
if process.returncode != 0:
return f"β Error from model: {error}"
response = self.clean_response(output.strip())
# If it's a project request, try to extract and create files
if is_project_request:
files = self.extract_project_files(response)
if files:
# Generate project name from user input
project_name = self.generate_project_name(user_input)
project_path, created_files = self.create_project_structure(project_name, files)
response += f"\n\nπ― Project created: {project_name}\n"
response += f"π Location: {project_path}\n"
response += f"π Files created: {len(created_files)}\n"
# Try to run the main file
main_files = [f for f in created_files if "main" in Path(f).name.lower()]
if main_files:
result = self.run_code_file(main_files[0])
response += f"\nπ Execution result:\n{result}"
# Add conversation pair to memory
conversation_pair = {
"user_input": user_input,
"bars_response": response
}
self.memory["conversation_pairs"].append(conversation_pair)
# Save memory after each exchange
self.save_memory()
return response
except subprocess.TimeoutExpired:
return "β° Response timeout - model took too long"
except Exception as e:
return f"β Unexpected error: {e}"
def generate_project_name(self, user_input):
"""Generate project name from user input"""
# Extract meaningful words and create a project name
words = re.findall(r'\b\w+\b', user_input.lower())
# Filter out common words
stop_words = {'create', 'make', 'build', 'a', 'an', 'the', 'for', 'me', 'please', 'can', 'you'}
meaningful_words = [w for w in words if w not in stop_words and len(w) > 2]
if meaningful_words:
return "_".join(meaningful_words[:3]) # Take first 3 meaningful words
else:
return f"project_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
def clean_response(self, response):
"""Clean up model response to remove unwanted content"""
if "Aditya:" in response:
response = response.split("Aditya:")[0].strip()
if "Bars:" in response:
response = response.split("Bars:", 1)[-1].strip()
# Remove code blocks
response = re.sub(r'```.*?```', '', response, flags=re.DOTALL)
# Remove common hallucination patterns
unwanted_patterns = [
r'OUTPUT:.*',
r'Question:.*',
r'Answer:.*',
r'This is an example.*',
r'The first step.*',
r'Next, we need.*'
]
for pattern in unwanted_patterns:
response = re.sub(pattern, '', response, flags=re.DOTALL | re.IGNORECASE)
# Clean up extra whitespace
response = re.sub(r'\n\s*\n', '\n', response)
return response.strip()
def add_important_fact(self, fact):
"""Add an important fact to long-term memory"""
self.memory["important_facts"].append(fact)
self.save_memory()
print(f"β
Added to long-term memory: {fact}")
def show_stats(self):
"""Show memory statistics"""
total_pairs = len(self.memory["conversation_pairs"])
important_facts = len(self.memory["important_facts"])
projects = len(list(self.projects_dir.glob("*"))) if self.projects_dir.exists() else 0
print(f"π bars Stats:")
print(f" Conversation pairs: {total_pairs}")
print(f" Important facts: {important_facts}")
print(f" Projects: {projects}")
print(f" Current model: {self.model_name}")
print(f" Main directory: {self.main_directory}")
def list_projects(self):
"""List all created projects"""
if not self.projects_dir.exists():
print("π No projects directory found")
return
projects = list(self.projects_dir.glob("*"))
if not projects:
print("π No projects created yet")
return
print(f"π Projects in {self.projects_dir}:")
for project in projects:
if project.is_dir():
files = list(project.glob("*"))
print(f" π― {project.name} ({len(files)} files)")
def run_project(self, project_name, file_name="main.py", args=""):
"""Run a specific file from a project"""
project_path = self.projects_dir / project_name
if not project_path.exists():
return f"β Project '{project_name}' not found"
file_path = project_path / file_name
return self.run_code_file(file_path, args)
def run(self):
"""Main chat loop"""
print("π§ Bars AI v2.1 - Enhanced with Project Creation!")
print(f"π± Using model: {self.model_name}")
print(f"π Main directory: {self.main_directory}")
# Check ollama status
status_ok, status_msg = self.check_ollama_status()
if not status_ok:
print(f"β {status_msg}")
print("π‘ Try: ollama serve (in another terminal)")
return
print("β
Ollama is ready!")
print("π¬ Type 'help' for commands, 'exit' to quit\n")
while True:
try:
user_input = input("You > ").strip()
if user_input.lower() in ['exit', 'quit', 'bye']:
print("Bars > Catch you later, Aditya! π€")
break
elif user_input.lower() == 'help':
print("""
π§ Bars Commands:
help - Show this menu
stats - Show memory and project statistics
projects - List all created projects
π― Project Creation:
Just say: "Create a calculator app" or "Make a simple game"
Bars will automatically create files and run them!
remember - Add something to long-term memory
model - Change AI model
clear - Clear recent memory (keep important facts)
run - Run a project file (e.g., run project_name main.py)
rescan - Rescan the main directory for new projects
exit - Quit Bars
""")
continue
elif user_input.lower() == 'stats':
self.show_stats()
continue
elif user_input.lower() == 'projects':
self.list_projects()
continue
elif user_input.lower().startswith('remember '):
fact = user_input[9:] # Remove 'remember '
self.add_important_fact(fact)
continue
elif user_input.lower().startswith('model '):
new_model = user_input[6:] # Remove 'model '
self.model_name = new_model
print(f"π Switched to model: {new_model}")
continue
elif user_input.lower().startswith('run '):
# Parse run command: run project_name file_name args
parts = user_input[4:].split()
if len(parts) >= 2:
project_name = parts[0]
file_name = parts[1]
args = " ".join(parts[2:]) if len(parts) > 2 else ""
result = self.run_project(project_name, file_name, args)
print(f"π {result}")
else:
print("β Usage: run project_name file_name [*args]")
continue
elif user_input.lower() == 'clear':
self.memory["conversation_pairs"] = []
self.save_memory()
print("ποΈ Cleared recent conversations")
continue
elif user_input.lower() == 'rescan':
self.scan_system_files()
print("π Rescanned your project folders.")
continue
elif not user_input:
continue
# Generate and print response
response = self.generate_response(user_input)
print(f"Bars > {response}")
except KeyboardInterrupt:
print("\nBars > Alright, catch you later! π€")
break
except Exception as e:
print(f"β Error: {e}")
if __name__ == "__main__":
# You can change the model here
bars = BarsAI(model_name="dolphin-mistral") # or "llama3.2:3b", "mistral:7b", etc.
bars.run()