-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
499 lines (415 loc) · 16.1 KB
/
app.py
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
from textual.app import App
from textual import events
from agents.command_parser import CommandParser
from langchain_groq import ChatGroq
from pydantic import SecretStr
from agents.graph import SimpleChat
from agents.react_graph import Splatter
import os
import asyncio
from dotenv import load_dotenv
from textual.widgets import RichLog, TextArea, Header, SelectionList
from textual.widgets.selection_list import Selection
from textual.containers import Vertical, Grid, ScrollableContainer, Container
from textual_plotext import PlotextPlot
from textual_components.token_usage_logger import TokenUsagePlot
from textual_components.terminal_widget import PtyTerminal
from textual.message import Message
from textual.widgets import Static
from textual.events import Mount
import plotext as plt
from dataclasses import dataclass
from typing import Callable, Dict
#from langchain.callbacks import BaseCallbackHandler
from pathlib import Path
import fnmatch
import asyncio
from functools import lru_cache
from textual import on
from shelly_types.types import CustomRichLog
from functools import wraps
import time
load_dotenv()
def debounce(wait):
def decorator(fn):
last_call = 0
@wraps(fn)
def debounced(*args, **kwargs):
nonlocal last_call
current_time = time.time()
if current_time - last_call >= wait:
last_call = current_time
return fn(*args, **kwargs)
return debounced
return decorator
class Shelly(App):
CSS = """
Grid#main_grid {
grid-size: 2; /* 2 columns */
grid-columns: 3fr 1fr; /* 75% - 25% split */
height: 100%;
margin: 1;
}
Vertical#left_panel {
width: 100%;
height: 100%;
margin-right: 1;
}
Vertical#right_panel {
width: 100%;
height: 100%;
}
CustomTextArea {
height: 30%;
dock: top;
border: solid $accent;
margin-bottom: 1;
}
CustomRichLog {
height: 1fr; /* Changed to 1fr to take remaining space */
border: solid $accent;
background: $surface;
overflow-y: scroll;
padding: 1;
}
#token_usage {
height: 40%;
border: solid $accent;
margin-bottom: 1;
}
#terminal_panel {
height: 60%; /* This plus token_usage should equal 100% */
border: solid $accent;
}
PtyTerminal {
height: 100%;
background: $surface;
color: $text;
border: solid $accent;
}
"""
def __init__(self):
super().__init__()
self.child_terminal = None
#self.zapper = Zap()
#self.zapper = Splatter()
self.zapper = SimpleChat()
api_key = os.getenv('GROQ_API_KEY')
if not api_key:
raise ValueError("GROQ_API_KEY environment variable is not set")
# Initialize the LLM
self.versatile_llm = ChatGroq(
model="llama-3.3-70b-versatile",
api_key= SecretStr(api_key),
temperature=0,
stop_sequences=None)
self.simple_llm = ChatGroq(
model="llama3-8b-8192",
api_key=SecretStr(api_key),
temperature=0,
stop_sequences=None
)
# token usage plot intialization
self.operation_counter = 0
self.operations = []
self.total_token_usage = 0
self.token_usage = []
@property
def state(self):
if self.zapper is None:
return None
return self.zapper.state
@state.setter
def state(self, value):
if self.zapper is not None:
self.zapper.state = value
def compose(self):
"""Create ui loadout"""
yield Header(id="header", name="Shelly", show_clock=True)
with Grid(id="main_grid"):
# Left side - 75% width
with Vertical(id="left_panel"):
yield CustomTextArea(app=self, id="user_input", theme="monokai")
yield CustomRichLog(id="output", wrap=True)
# Right side - 25% width
with Vertical(id="right_panel"):
yield TokenUsagePlot(id="token_usage")
with ScrollableContainer(id="terminal_panel"):
yield PtyTerminal(id="terminal")
#yield Terminal(command="bash", default_colors="textual", id="terminal")
#yield PlotextPlot(id="resource_usage")
def update_charts(self, token_plot: PlotextPlot, token_amount):
self.token_usage.append(token_amount)
self.total_token_usage += token_amount
self.operation_counter += 1
self.operations.append(self.operation_counter)
if len(self.token_usage) > 20:
self.token_usage.pop(0)
plt.clf()
plt.plot(self.operations, self.token_usage)
plt.title(f'Total Tokens: {self.total_token_usage}')
token_plot.refresh()
def on_key(self, event) -> None:
"""Handle key events"""
# Add any key-based controls here
if event.key == "ctrl+c":
self.state["should_end"] = True
async def on_key_pressed(self, event: events.Key) -> None:
if event.key == "c" and event.control:
self.state["should_end"] = True
async def on_shutdown(self) -> None:
"""Clean up when the application is shutting down"""
# Add any cleanup code here
if self.child_terminal:
self.child_terminal.kill_tmux_session()
@debounce(0.5)
def process_input(self, user_input: str, output_log: CustomRichLog) -> None:
"""Process input through the graph"""
total_tokens = 0
try:
# Update state with user input
self.zapper.state["messages"] = self.zapper.state["messages"] + [{
"role": "user",
"content": user_input
}]
self.zapper.state["current_input"] = user_input
self.zapper.state["should_end"] = False # Reset end flag
# Single stream iteration
for event in self.zapper.graph.stream(self.zapper.state):
if "current_messages" in event:
# Get response from LLM
response = self.zapper.llm.invoke(event["current_messages"])
# Write response
if response and hasattr(response, 'content'):
output_log.write("\nAssistant: " + str(response.content))
self.zapper.state["action_output"] = str(response.content)
output_log.write("\n") # Add final newline
except Exception as e:
import traceback
output_log.write(f"\n[red]Error: {str(e)}[/red]")
output_log.write(f"\n[dim]{traceback.format_exc()}[/dim]")
async def on_mount(self) -> None:
"""Called after the app is mounted"""
await asyncio.sleep(1) # Wait for widgets to be ready
try:
# Get output log first for debugging
output_log = self.query_one("#output", CustomRichLog)
if output_log:
# List all available widgets
all_widgets = list(self.query("*"))
self.zapper.output_log = output_log
# Try to get token usage widget
token_usage = self.query_one("#token_usage", TokenUsagePlot)
# Set up Zapper connections
if token_usage:
self.zapper.token_usage_log = token_usage
# Set up input widget
input_widget = self.query_one("#user_input", CustomTextArea)
if input_widget:
input_widget.focus()
except Exception as e:
if 'output_log' in locals():
output_log.write(f"\n[red]Error in on_mount: {str(e)}[/red]")
import traceback
output_log.write(f"\n[dim]{traceback.format_exc()}[/dim]")
@dataclass
class Command:
"""Represents a command that can be triggered"""
name: str
description: str
handler: Callable
args: list = None
# this class has to stay here because we have to pass a reference of shelly to it (preventing circular imports)
class CustomTextArea(TextArea):
"""A TextArea with custom key bindings."""
def __init__(self, app: Shelly, *args, **kwargs):
super().__init__(*args, **kwargs)
self.show_line_numbers=True
self._shelly_app = app
self.last_submitted_position = 0
'''
self.commands: Dict[str, Command] = {
"!help": Command(
name="help",
description="Show help message",
handler=self.show_help
),
"!clear": Command(
name="clear",
description="Clear output",
handler=self.clear_output
),
"!run": Command(
name="run",
description="Run code",
handler=self.run_code,
args=["filepath"]
)
}'''
@lru_cache
def get_all_files_in_cwd(self, max_files=100):
cwd = os.getcwd()
files = []
# Extensive list of directories to ignore
ignore_dirs = {
# Version Control
'.git', '.svn', '.hg', '.bzr',
# Python
'__pycache__', '.pytest_cache', '.mypy_cache', '.ruff_cache',
'venv', '.venv', 'env', '.env', '.tox',
# Node.js / JavaScript
'node_modules', 'bower_components',
'.next', '.nuxt', '.gatsby',
# Build directories
'dist', 'build', '_build', 'public/build',
'target', 'out', 'output',
'bin', 'obj',
# IDE and editors
'.idea', '.vscode', '.vs',
'.settings', '.project', '.classpath',
# Dependencies
'vendor', 'packages',
# Coverage and tests
'coverage', '.coverage', 'htmlcov',
# Mobile
'Pods', '.gradle',
# Misc
'tmp', 'temp', 'logs',
'.sass-cache', '.parcel-cache',
'.cargo', 'artifacts'
}
# Extensive list of file patterns to ignore
ignore_files = {
# Python
'*.pyc', '*.pyo', '*.pyd',
'*.so', '*.egg', '*.egg-info',
# JavaScript/Web
'*.min.js', '*.min.css',
'*.chunk.js', '*.chunk.css',
'*.bundle.js', '*.bundle.css',
'*.hot-update.*',
# Build artifacts
'*.o', '*.obj', '*.a', '*.lib',
'*.dll', '*.dylib', '*.so',
'*.exe', '*.bin',
# Logs and databases
'*.log', '*.logs',
'*.sqlite', '*.sqlite3', '*.db',
'*.mdb', '*.ldb',
# Package locks
'package-lock.json', 'yarn.lock',
'poetry.lock', 'Pipfile.lock',
'pnpm-lock.yaml', 'composer.lock',
# Environment and secrets
'.env', '.env.*', '*.env',
'.env.local', '.env.development',
'.env.test', '.env.production',
'*.pem', '*.key', '*.cert',
# Cache files
'.DS_Store', 'Thumbs.db',
'*.cache', '.eslintcache',
'*.swp', '*.swo',
# Documentation build
'*.pdf', '*.doc', '*.docx',
# Images and large media
'*.jpg', '*.jpeg', '*.png', '*.gif',
'*.ico', '*.svg', '*.woff', '*.woff2',
'*.ttf', '*.eot', '*.mp4', '*.mov',
# Archives
'*.zip', '*.tar', '*.gz', '*.rar',
# Generated sourcemaps
'*.map', '*.css.map', '*.js.map'
}
for root, dirs, filenames in os.walk(cwd, topdown=True):
# Skip ignored directories
dirs[:] = [d for d in dirs if d not in ignore_dirs]
for filename in filenames:
# Skip files matching ignore patterns
if any(fnmatch.fnmatch(filename, pattern) for pattern in ignore_files):
continue
# Get relative path
rel_path = os.path.relpath(os.path.join(root, filename), cwd)
# Skip paths that contain any of the ignored directory names
# (handles nested cases like 'something/node_modules/something')
if any(ignored_dir in rel_path.split(os.sep) for ignored_dir in ignore_dirs):
continue
files.append(rel_path)
if len(files) >= max_files:
return files
return sorted(files) # Sort for consistent ordering
@lru_cache
def get_all_dirs_in_cwd(self):
cwd = Path.cwd()
return [d.name for d in cwd.iterdir() if d.is_dir()]
async def on_text_area_changed(self) -> None:
cursor = self.cursor_location
if cursor is None:
return
current_line = self.document.get_line(cursor[0])
output_log = self._shelly_app.query_one("#output", CustomRichLog)
#output = self._shelly_app.query_one("#output", CustomRichLog)
if str("/file") in current_line and cursor[1] - (current_line.index("/file")+5) == 1:
files = [Selection(str(file), str(num)) for num, file in enumerate(self.get_all_files_in_cwd())]
#output_log.write(self.get_all_files_in_cwd())
selection_list = ContextSelectionList(*files, text_area=self, id="files")
selection_list.focus()
await self.mount(selection_list)
if str("/dir") in current_line and cursor[1] - (current_line.index("/dir")+4) == 1:
#directories = self.get_all_dirs_in_cwd()
directories = [Selection(str(dir), str(num)) for num, dir in enumerate(self.get_all_dirs_in_cwd())]
selection_list = ContextSelectionList(*directories, text_area=self, id="files")
selection_list.focus()
await self.mount(selection_list)
'''
async def on_selection_list_selected_changed(self):
"""Handle the selection event"""
output_log = self._shelly_app.query_one("#output", RichLog)
selection_list = self.query_one("#files", SelectionList)
self.insert(selection_list.selected)
output_log.write(selection_list.selected)
#output.write("fileeee")
# Optionally remove the selection list
await selection_list.remove()
'''
async def on_key(self, event):
"""Handle key press events."""
output_log = self._shelly_app.query_one("#output", CustomRichLog)
if event.key == "alt+enter" or event.key == "ctrl+enter":
content = self.text[self.last_submitted_position:].strip()
self.last_submitted_position = len(content)
if content.strip():
output_log.write(f"input: {content}")
self._shelly_app.process_input(content, output_log)
self.action_cursor_down()
else:
# Allow default key handling
await super()._on_key(event)
class ContextSelectionList(SelectionList):
def __init__(self, *items, text_area: TextArea, id: str | None = None):
super().__init__(*items, id=id)
self.text_area = text_area
def on_key(self, event) -> None:
if event.key == "enter" and self.highlighted is not None:
selected_option = self.get_option_at_index(self.highlighted)
self.text_area.insert(str(selected_option.prompt)) # use highlighted instead of selected
self.text_area.action_cursor_down()
self.remove()
elif event.key == "escape":
self.remove()
#def on_click(self) -> None:
class Alert(Message):
def __init__(self, message: str) -> None:
self.message = message
super().__init__()
class AlertWidget(Static):
def __init__(self, message: str):
super().__init__(message)
self.message = message
async def main():
try:
shelly = Shelly()
await shelly.run_async()
except Exception as e:
print(f"Application error: {str(e)}")
if __name__ == "__main__":
asyncio.run(main())