forked from Niansuh/chat2api
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathchat.py
More file actions
1710 lines (1469 loc) · 69.1 KB
/
chat.py
File metadata and controls
1710 lines (1469 loc) · 69.1 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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Chat2API CLI - Professional, modern interface
"""
import sys
import json
import asyncio
import os
import secrets
import string
import webbrowser
from pathlib import Path
from typing import Optional, List, Dict
import httpx
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt, Confirm
from rich.markdown import Markdown
from rich import box
from rich.layout import Layout
from rich.text import Text
from rich.align import Align
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.syntax import Syntax
from rich.columns import Columns
from rich.rule import Rule
from rich.live import Live
from rich.status import Status
from prompt_toolkit import prompt as pt_prompt
from prompt_toolkit.completion import Completer, Completion
from prompt_toolkit.formatted_text import HTML
class Theme:
"""Retro pixelated theme for the CLI"""
# Primary colors
PRIMARY = "#8b5cf6" # Bright Purple
SECONDARY = "#10b981" # Bright Green
SUCCESS = "#10b981" # Bright Green
WARNING = "#f59e0b" # Orange
ERROR = "#ef4444" # Red
INFO = "#06b6d4" # Cyan
# Neutral colors
BACKGROUND = "#000000" # Black
SURFACE = "#1a1a1a" # Dark gray
BORDER = "#8b5cf6" # Purple border
TEXT_PRIMARY = "#ffffff" # White
TEXT_SECONDARY = "#e5e7eb" # Light gray
TEXT_MUTED = "#9ca3af" # Muted gray
# Accent colors
ACCENT_BLUE = "#10b981" # Green
ACCENT_PURPLE = "#8b5cf6" # Bright Purple
ACCENT_GREEN = "#10b981" # Bright Green
ACCENT_YELLOW = "#f59e0b"
ACCENT_RED = "#ef4444"
ACCENT_CYAN = "#06b6d4"
from rich.theme import Theme as RichTheme
rich_theme = RichTheme({
"info": Theme.INFO,
"warning": Theme.WARNING,
"error": Theme.ERROR,
"success": Theme.SUCCESS,
"primary": Theme.PRIMARY,
"secondary": Theme.SECONDARY,
})
console = Console(
color_system="truecolor",
theme=rich_theme
)
def get_data_dir():
"""Get the appropriate data directory based on execution context"""
if getattr(sys, 'frozen', False):
return Path(sys.executable).parent
else:
return Path.cwd()
def normalize_endpoint(endpoint: str) -> str:
"""Normalize endpoint URL by removing trailing slashes"""
if endpoint:
return endpoint.rstrip('/')
return endpoint
CONFIG_DIR = get_data_dir()
CONFIG_FILE = CONFIG_DIR / "config.json"
TOKENS_FILE = CONFIG_DIR / "tokens.json"
APIKEYS_FILE = CONFIG_DIR / "apikeys.json"
DATA_DIR = CONFIG_DIR / "data"
class Config:
"""CLI Configuration Manager"""
def __init__(self):
self.config_dir = CONFIG_DIR
self.config_file = CONFIG_FILE
self.tokens_file = TOKENS_FILE
self.apikeys_file = APIKEYS_FILE
self.config = self.load_config()
self.tokens = self.load_tokens()
self.apikeys = self.load_apikeys()
def load_config(self) -> dict:
"""Load configuration from file"""
if self.config_file.exists():
with open(self.config_file, 'r') as f:
config_data = json.load(f)
if "api_endpoint" in config_data:
config_data["api_endpoint"] = normalize_endpoint(config_data["api_endpoint"])
return config_data
return {
"api_endpoint": "http://localhost:5005",
"default_model": "gpt-3.5-turbo",
"active_token": None
}
def load_tokens(self) -> dict:
"""Load labeled tokens"""
if self.tokens_file.exists():
try:
with open(self.tokens_file, 'r') as f:
data = json.load(f)
if isinstance(data, dict):
return data
else:
return {}
except (json.JSONDecodeError, Exception):
return {}
return {}
def save_config(self):
"""Save configuration to file"""
self.config_dir.mkdir(parents=True, exist_ok=True)
with open(self.config_file, 'w') as f:
json.dump(self.config, f, indent=2)
def save_tokens(self):
"""Save tokens to file"""
self.config_dir.mkdir(parents=True, exist_ok=True)
with open(self.tokens_file, 'w') as f:
json.dump(self.tokens, f, indent=2)
def get(self, key: str, default=None):
return self.config.get(key, default)
def set(self, key: str, value):
if key == "api_endpoint" and value:
value = normalize_endpoint(value)
self.config[key] = value
self.save_config()
def add_token(self, name: str, token: str, sync_to_server=True):
"""Add a labeled token"""
if not isinstance(self.tokens, dict):
self.tokens = {}
self.tokens[name] = token
self.save_tokens()
DATA_DIR.mkdir(exist_ok=True)
token_file = DATA_DIR / "token.txt"
with open(token_file, 'a') as f:
f.write(f"{token}\n")
if sync_to_server:
self.sync_tokens_to_server()
def remove_token(self, name: str):
"""Remove a labeled token"""
if not isinstance(self.tokens, dict):
self.tokens = {}
if name in self.tokens:
del self.tokens[name]
self.save_tokens()
return True
return False
def use_token(self, name: str):
"""Set active token by name"""
if not isinstance(self.tokens, dict):
self.tokens = {}
if name in self.tokens:
self.config['active_token'] = name
self.save_config()
return True
return False
def get_active_token(self):
"""Get the currently active token"""
if not isinstance(self.tokens, dict):
self.tokens = {}
active = self.config.get('active_token')
if active and active in self.tokens:
return self.tokens[active]
if self.tokens:
return list(self.tokens.values())[0]
return None
def load_apikeys(self) -> dict:
"""Load generated API keys"""
if self.apikeys_file.exists():
try:
with open(self.apikeys_file, 'r') as f:
data = json.load(f)
if isinstance(data, dict):
return data
else:
return {}
except (json.JSONDecodeError, Exception):
return {}
return {}
def save_apikeys(self):
"""Save API keys to file"""
self.config_dir.mkdir(parents=True, exist_ok=True)
with open(self.apikeys_file, 'w') as f:
json.dump(self.apikeys, f, indent=2)
def generate_apikey(self, name: str, sync_to_server=True) -> str:
"""Generate a new OpenAI-compatible API key"""
if not isinstance(self.apikeys, dict):
self.apikeys = {}
random_part = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(48))
api_key = f"sk-{random_part}"
self.apikeys[name] = {
"key": api_key,
"created": __import__('datetime').datetime.now().isoformat(),
"token_name": self.config.get('active_token', 'auto')
}
self.save_apikeys()
if sync_to_server:
self.sync_apikeys_to_server()
return api_key
def remove_apikey(self, name: str):
"""Remove an API key"""
if not isinstance(self.apikeys, dict):
self.apikeys = {}
if name in self.apikeys:
del self.apikeys[name]
self.save_apikeys()
return True
return False
def sync_tokens_to_server(self):
"""Sync local tokens to server"""
endpoint = self.get("api_endpoint", "http://localhost:5005")
if endpoint == "http://localhost:5005":
return False
try:
import requests
tokens_data = {
"tokens": self.tokens,
"sync_type": "tokens"
}
response = requests.post(
f"{endpoint}/admin/sync/tokens",
json=tokens_data,
timeout=10
)
if response.status_code == 200:
console.print("[dim green]✓ Tokens synced to server[/dim green]")
return True
else:
console.print(f"[dim yellow]⚠ Sync failed: {response.status_code}[/dim yellow]")
return False
except Exception as e:
console.print(f"[dim red]✗ Sync error: {str(e)}[/dim red]")
return False
def sync_apikeys_to_server(self):
endpoint = self.get("api_endpoint", "http://localhost:5005")
if endpoint == "http://localhost:5005":
return False
try:
import requests
apikeys_data = {
"apikeys": self.apikeys,
"sync_type": "apikeys"
}
response = requests.post(
f"{endpoint}/admin/sync/apikeys",
json=apikeys_data,
timeout=10
)
if response.status_code == 200:
console.print("[dim green]✓ API keys synced to server[/dim green]")
return True
else:
console.print(f"[dim yellow]⚠ Sync failed: {response.status_code}[/dim yellow]")
return False
except Exception as e:
console.print(f"[dim red]✗ Sync error: {str(e)}[/dim red]")
return False
config = Config()
def setup_auto_config():
"""Auto-configure CLI by reading from tokens.json"""
if not config.tokens:
project_tokens_file = Path("tokens.json")
if project_tokens_file.exists():
try:
with open(project_tokens_file, 'r') as f:
project_tokens = json.load(f)
if isinstance(project_tokens, dict) and project_tokens:
for name, token in project_tokens.items():
config.add_token(name, token)
first_token_name = list(project_tokens.keys())[0]
config.use_token(first_token_name)
console.print(f"[dim]✓ Auto-configured with token '{first_token_name}' from tokens.json[/dim]")
return True
except (json.JSONDecodeError, Exception) as e:
console.print(f"[dim yellow]⚠ Could not load tokens.json: {e}[/dim yellow]")
data_token_file = Path("data/token.txt")
if data_token_file.exists():
try:
with open(data_token_file, 'r') as f:
lines = f.read().strip().split('\n')
if lines and lines[0].strip():
token = lines[-1].strip()
config.add_token("auto", token)
config.use_token("auto")
console.print("[dim]✓ Auto-configured with token from data/token.txt[/dim]")
return True
except Exception as e:
console.print(f"[dim yellow]⚠ Could not load data/token.txt: {e}[/dim yellow]")
return False
setup_auto_config()
COMMANDS = {
"/help": "Show all available commands",
"/status": "Display current settings and connection status",
"/models": "List all available AI models",
"/use": "Switch to a different model (e.g., /use gpt-4)",
"/stream": "Toggle streaming mode on/off",
"/clear": "Clear conversation history",
"/reset": "Reset all settings, tokens, and API keys to defaults",
"/token": "Manage access tokens (add/list/use/remove)",
"/token add": "Add a new access token",
"/token list": "List all saved tokens",
"/token use": "Switch to a specific token",
"/token remove": "Remove a token",
"/apikey": "Generate OpenAI-compatible API keys for external programs",
"/apikey generate": "Generate a new API key",
"/apikey list": "List all generated API keys",
"/apikey test": "Test a specific API key",
"/apikey remove": "Remove an API key",
"/endpoint": "Switch API endpoint (e.g., /endpoint https://your-server.com)",
"/web": "Open ChatGPT web interface in default browser",
"/exit": "Exit the CLI",
}
class CommandCompleter(Completer):
"""Custom completer for slash commands with descriptions"""
def get_completions(self, document, complete_event):
text = document.text
# Only show completions if text starts with /
if not text.startswith('/'):
return
# Get matching commands - iterate over items properly
for cmd, desc in sorted(COMMANDS.items()):
if cmd.lower().startswith(text.lower()):
# Simple white text for better readability
display_meta = HTML(f'<ansibrightwhite>{desc}</ansibrightwhite>')
yield Completion(
cmd,
start_position=-len(text),
display_meta=display_meta
)
def get_user_input():
"""Get user input with retro styling and command completion"""
try:
completer = CommandCompleter()
result = pt_prompt(
HTML('<ansibrightmagenta>></ansibrightmagenta> '),
completer=completer,
complete_while_typing=True,
enable_history_search=True
)
return result
except (KeyboardInterrupt, EOFError):
raise
def show_banner():
"""Show retro pixelated banner"""
# Clear screen for better presentation
os.system('cls' if os.name == 'nt' else 'clear')
# Create gradient purple effect for CHAT2API
console.print()
# Top border with gradient
console.print(Align.center("╔══════════════════════════════════════════════════════════════════════════════╗"), style="#a855f7")
console.print(Align.center("║ ║"), style="#9333ea")
# CHAT2API with gradient effect (using different purple shades)
chat2api_lines = [
" ██████╗██╗ ██╗ █████╗ ████████╗██████╗ █████╗ ██████╗ ██╗ ",
" ██╔════╝██║ ██║██╔══██╗╚══██╔══╝╚════██╗██╔══██╗██╔══██╗██║ ",
" ██║ ███████║███████║ ██║ █████╔╝███████║██████╔╝██║ ",
" ██║ ██╔══██║██╔══██║ ██║ ██╔═══╝ ██╔══██║██╔═══╝ ██║ ",
" ╚██████╗██║ ██║██║ ██║ ██║ ███████╗██║ ██║██║ ██║ ",
" ╚═════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ "
]
# Apply gradient effect to each line
gradient_colors = ["#a855f7", "#9333ea", "#7c3aed", "#6d28d9", "#5b21b6", "#4c1d95"]
for i, line in enumerate(chat2api_lines):
color = gradient_colors[i % len(gradient_colors)]
console.print(Align.center(f"║{line}║"), style=color)
console.print(Align.center("║ ║"), style="#7c3aed")
console.print(Align.center("╚══════════════════════════════════════════════════════════════════════════════╝"), style="#6d28d9")
console.print()
console.print(Align.center("[bold white]OpenAI-Compatible API Gateway[/bold white]"))
console.print(Align.center("[dim]Transform ChatGPT into powerful APIs[/dim]"))
console.print()
def show_help():
"""Show available commands with professional formatting"""
console.print()
help_content = """
[bold
[bold
[bold
[bold
[bold
[bold
[bold
[bold
[bold
[bold
[bold
[bold
[bold
[bold
[bold
[bold
[bold
[bold
[bold
[bold
[bold
[bold
[bold
[dim][bold]Quick Start:[/bold] Type normally to chat with AI. Commands start with /[/dim]
[dim][bold]Examples:[/bold] /use gpt-4, /token add, /apikey generate, /web[/dim]
"""
help_panel = Panel(
help_content,
title="[bold white]Command Reference[/bold white]",
subtitle="[dim]Professional Chat2API CLI[/dim]",
border_style="#a855f7",
padding=(1, 2),
title_align="left"
)
console.print(Align.center(help_panel))
console.print()
def open_web_interface():
"""Open the ChatGPT web interface in the default browser"""
console.print()
endpoint = config.get("api_endpoint", "http://localhost:5005")
web_url = f"{endpoint}/"
try:
webbrowser.open(web_url)
success_panel = Panel(
f"[bold green]✓ Opening ChatGPT web interface![/bold green]\n\n"
f"[bold]URL:[/bold] [underline]{web_url}[/underline]\n"
f"[dim]The web interface should open in your default browser.[/dim]\n"
f"[dim]If it doesn't open automatically, copy the URL above.[/dim]",
title="[bold]Web Interface[/bold]",
border_style=Theme.SUCCESS,
padding=(1, 2)
)
console.print(success_panel)
console.print()
except Exception as e:
error_panel = Panel(
f"[bold red]✗ Failed to open browser![/bold red]\n\n"
f"[dim]Error: {str(e)}[/dim]\n"
f"[bold]Please manually open:[/bold] [underline]{web_url}[/underline]",
title="[bold]Browser Error[/bold]",
border_style=Theme.ERROR,
padding=(1, 2)
)
console.print(error_panel)
console.print()
def switch_endpoint(new_endpoint):
"""Switch the API endpoint with validation"""
console.print()
# Validate URL format
if not new_endpoint.startswith(('http://', 'https://')):
error_panel = Panel(
"[bold red]✗ Invalid endpoint format![/bold red]\n\n"
"[bold]Endpoint must start with:[/bold]\n"
"• [bold #a855f7]http://[/bold #a855f7] (for local servers)\n"
"• [bold #a855f7]https://[/bold #a855f7] (for secure servers)\n\n"
"[bold]Examples:[/bold]\n"
"• [#a855f7]http://localhost:5005[/#a855f7]\n"
"• [#a855f7]https://your-server.com[/#a855f7]\n"
"• [#a855f7]https://api.example.com:8080[/#a855f7]",
title="[bold]Invalid Endpoint[/bold]",
border_style=Theme.ERROR,
padding=(1, 2)
)
console.print(error_panel)
console.print()
return False
# Test the new endpoint
console.print(f"[dim]Testing endpoint: {new_endpoint}...[/dim]")
try:
import requests
# Test with health endpoint first (doesn't require auth)
test_url = f"{new_endpoint}/health"
response = requests.get(test_url, timeout=5)
if response.status_code == 200:
# Health endpoint is working, endpoint is valid
config.set("api_endpoint", new_endpoint)
success_panel = Panel(
f"[bold green]✓ Endpoint switched successfully![/bold green]\n\n"
f"[bold]New Endpoint:[/bold] [yellow]{new_endpoint}[/yellow]\n"
f"[bold]Status:[/bold] [green]✓ Online and responding[/green]\n"
f"[bold]Response Time:[/bold] [dim]{response.elapsed.total_seconds():.2f}s[/dim]\n\n"
f"[dim]All future API requests will use this endpoint.[/dim]",
title="[bold]Endpoint Changed[/bold]",
border_style=Theme.SUCCESS,
padding=(1, 2)
)
console.print(success_panel)
console.print()
return True
elif response.status_code == 403:
# Try fallback test with /v1/models (403 is expected for Chat2API with RBAC)
try:
fallback_url = f"{new_endpoint}/v1/models"
fallback_response = requests.get(fallback_url, timeout=5)
if fallback_response.status_code == 403 and "RBAC" in fallback_response.text:
# This is a valid Chat2API server with RBAC enabled
config.set("api_endpoint", new_endpoint)
success_panel = Panel(
f"[bold green]✓ Chat2API server detected![/bold green]\n\n"
f"[bold]New Endpoint:[/bold] [yellow]{new_endpoint}[/yellow]\n"
f"[bold]Status:[/bold] [green]✓ Online with RBAC security[/green]\n"
f"[bold]Response Time:[/bold] [dim]{response.elapsed.total_seconds():.2f}s[/dim]\n\n"
f"[dim]Server is secured and ready for authenticated requests.[/dim]",
title="[bold]Endpoint Changed[/bold]",
border_style=Theme.SUCCESS,
padding=(1, 2)
)
console.print(success_panel)
console.print()
return True
except:
pass
# If fallback fails, show the original error
error_panel = Panel(
f"[bold yellow]⚠ Endpoint responded but with error![/bold yellow]\n\n"
f"[bold]Endpoint:[/bold] [yellow]{new_endpoint}[/yellow]\n"
f"[bold]Status Code:[/bold] [yellow]{response.status_code}[/yellow]\n"
f"[bold]Response:[/bold] [dim]{response.text[:100]}...[/dim]\n\n"
f"[dim]The endpoint is reachable but may not be a valid Chat2API server.[/dim]",
title="[bold]Endpoint Error[/bold]",
border_style=Theme.WARNING,
padding=(1, 2)
)
console.print(error_panel)
console.print()
return False
else:
# Other error codes
error_panel = Panel(
f"[bold yellow]⚠ Endpoint responded but with error![/bold yellow]\n\n"
f"[bold]Endpoint:[/bold] [yellow]{new_endpoint}[/yellow]\n"
f"[bold]Status Code:[/bold] [yellow]{response.status_code}[/yellow]\n"
f"[bold]Response:[/bold] [dim]{response.text[:100]}...[/dim]\n\n"
f"[dim]The endpoint is reachable but may not be a valid Chat2API server.[/dim]",
title="[bold]Endpoint Error[/bold]",
border_style=Theme.WARNING,
padding=(1, 2)
)
console.print(error_panel)
console.print()
return False
except requests.exceptions.Timeout:
error_panel = Panel(
f"[bold red]✗ Endpoint timeout![/bold red]\n\n"
f"[bold]Endpoint:[/bold] [yellow]{new_endpoint}[/yellow]\n"
f"[bold]Error:[/bold] [red]Connection timeout (5s)[/red]\n\n"
f"[dim]The endpoint is not responding or is too slow.[/dim]\n"
f"[dim]Please check if the server is running and accessible.[/dim]",
title="[bold]Connection Timeout[/bold]",
border_style=Theme.ERROR,
padding=(1, 2)
)
console.print(error_panel)
console.print()
return False
except requests.exceptions.ConnectionError:
error_panel = Panel(
f"[bold red]✗ Connection failed![/bold red]\n\n"
f"[bold]Endpoint:[/bold] [yellow]{new_endpoint}[/yellow]\n"
f"[bold]Error:[/bold] [red]Connection refused[/red]\n\n"
f"[dim]The endpoint is not reachable. Please check:[/dim]\n"
f"[dim]• Server is running[/dim]\n"
f"[dim]• URL is correct[/dim]\n"
f"[dim]• Network connectivity[/dim]\n"
f"[dim]• Firewall settings[/dim]",
title="[bold]Connection Failed[/bold]",
border_style=Theme.ERROR,
padding=(1, 2)
)
console.print(error_panel)
console.print()
return False
except Exception as e:
error_panel = Panel(
f"[bold red]✗ Unexpected error![/bold red]\n\n"
f"[bold]Endpoint:[/bold] [yellow]{new_endpoint}[/yellow]\n"
f"[bold]Error:[/bold] [red]{str(e)}[/red]\n\n"
f"[dim]An unexpected error occurred while testing the endpoint.[/dim]",
title="[bold]Test Error[/bold]",
border_style=Theme.ERROR,
padding=(1, 2)
)
console.print(error_panel)
console.print()
return False
def show_status(current_model, current_stream, conversation_history):
"""Show current status with retro design"""
console.print()
endpoint = config.get("api_endpoint", "http://localhost:5005")
try:
import requests
response = requests.get(f"{endpoint}/v1/models", timeout=2)
status_icon = "●"
status_text = "ONLINE"
status_color = Theme.SUCCESS
except:
status_icon = "●"
status_text = "OFFLINE"
status_color = Theme.ERROR
console.print(Align.center("╔══════════════════════════════════════════════════════════════════════════════╗"), style="#a855f7")
console.print(Align.center("║ Server Status ║"), style="#9333ea")
console.print(Align.center("╚══════════════════════════════════════════════════════════════════════════════╝"), style="#7c3aed")
console.print()
console.print(Align.center(f"● Status [{status_color}]{status_text}[/{status_color}]"))
console.print(Align.center(f"Endpoint [underline]{endpoint}[/underline]"))
console.print(Align.center(f"Model [{Theme.ACCENT_PURPLE}]{current_model}[/{Theme.ACCENT_PURPLE}]"))
console.print(Align.center(f"Streaming [{Theme.SUCCESS if current_stream else Theme.WARNING}]{'Enabled' if current_stream else 'Disabled'}[/{Theme.SUCCESS if current_stream else Theme.WARNING}]"))
console.print()
console.print(Align.center(f"Type [{Theme.ACCENT_PURPLE}]/help[/{Theme.ACCENT_PURPLE}] for commands"))
console.print()
def list_models():
"""Show available models with professional formatting"""
models = [
# GPT-3.5 Models
("gpt-3.5-turbo", "Fast & Efficient", "Best for quick questions and general use", Theme.ACCENT_GREEN),
# GPT-4 Models
("gpt-4", "Advanced Reasoning", "Best for complex tasks and analysis", Theme.ACCENT_BLUE),
("gpt-4-mobile", "Mobile Optimized", "Optimized for mobile devices", Theme.ACCENT_BLUE),
("gpt-4-gizmo", "Gizmo Integration", "GPT-4 with gizmo capabilities", Theme.ACCENT_BLUE),
# GPT-4o Models
("gpt-4o", "Latest Generation", "Most advanced capabilities", Theme.ACCENT_YELLOW),
("gpt-4o-mini", "Efficient GPT-4o", "Faster, cheaper GPT-4o variant", Theme.ACCENT_YELLOW),
("gpt-4o-canmore", "Canmore Model", "Specialized GPT-4o variant", Theme.ACCENT_CYAN),
("gpt-4.5o", "Enhanced GPT-4o", "Advanced GPT-4o variant", Theme.ACCENT_CYAN),
# GPT-5
("gpt-5", "Next Generation", "Future AI capabilities", Theme.ACCENT_CYAN),
# O1 Models
("o1-preview", "Reasoning Engine", "Advanced reasoning and problem solving", Theme.ACCENT_RED),
("o1-mini", "Lightweight Reasoning", "Efficient reasoning capabilities", Theme.ACCENT_RED),
("o1", "General Reasoning", "General purpose reasoning model", Theme.ACCENT_RED),
# Auto Selection
("auto", "Auto Selection", "Automatically select best available model", Theme.ACCENT_PURPLE)
]
console.print()
# Create models table
models_table = Table(
title="[bold white]Available AI Models[/bold white]",
show_header=True,
header_style="bold white",
box=box.ROUNDED,
border_style="#a855f7",
title_style="bold white"
)
models_table.add_column("Model", style="bold", width=20)
models_table.add_column("Description", style="default", width=25)
models_table.add_column("Best For", style="dim", width=30)
models_table.add_column("Status", style="default", width=15)
for model, desc, use_case, color in models:
models_table.add_row(
f"[{color}]{model}[/{color}]",
desc,
use_case,
f"[{Theme.SUCCESS}]Available[/{Theme.SUCCESS}]"
)
console.print(Align.left(models_table))
console.print()
# Usage instructions
usage_panel = Panel(
"[bold]Usage:[/bold] [#a855f7]/use <model-name>[/#a855f7]\n"
"[bold]Example:[/bold] [#a855f7]/use gpt-4[/#a855f7]\n"
"[dim]Models are automatically selected based on your needs[/dim]",
title="[bold]Quick Switch[/bold]",
border_style="#9333ea",
padding=(1, 2)
)
console.print(Align.left(usage_panel))
console.print()
def list_tokens():
"""List all saved tokens with professional formatting"""
if not isinstance(config.tokens, dict):
config.tokens = {}
if not config.tokens:
console.print()
empty_panel = Panel(
"[bold yellow]⚠ No access tokens configured[/bold yellow]\n\n"
"[dim]Add your first token with:[/dim] [bold #a855f7]/token add[/bold #a855f7]\n"
"[dim]Get tokens from:[/dim] [bold #a855f7]https://chatgpt.com[/bold #a855f7]",
title="[bold]No Tokens Found[/bold]",
border_style=Theme.WARNING,
padding=(1, 2)
)
console.print(empty_panel)
console.print()
return
active = config.get('active_token')
console.print()
tokens_table = Table(
title="[bold white]Access Tokens[/bold white]",
show_header=True,
header_style="bold white",
box=box.ROUNDED,
border_style="#a855f7",
title_style="bold white"
)
tokens_table.add_column("Name", style="bold", width=20)
tokens_table.add_column("Type", style="default", width=15)
tokens_table.add_column("Preview", style="dim", width=25)
tokens_table.add_column("Status", style="default", width=15)
for name, token in config.tokens.items():
if token.startswith("eyJhbGciOi"):
token_type = "JWT"
type_color = Theme.ACCENT_BLUE
elif token.startswith("fk-"):
token_type = "FakeOpen"
type_color = Theme.ACCENT_PURPLE
elif len(token) == 45:
token_type = "Refresh"
type_color = Theme.ACCENT_GREEN
else:
token_type = "Unknown"
type_color = Theme.ACCENT_YELLOW
preview = f"{token[:12]}...{token[-6:]}" if len(token) > 25 else token
if name == active:
status = f"[{Theme.SUCCESS}]Active[/{Theme.SUCCESS}]"
name_style = f"[{Theme.SUCCESS}]{name}[/{Theme.SUCCESS}]"
else:
status = "[dim]Inactive[/dim]"
name_style = name
tokens_table.add_row(
name_style,
f"[{type_color}]{token_type}[/{type_color}]",
preview,
status
)
console.print(Align.center(tokens_table))
console.print()
if active:
active_info = f"[bold green]Active Token:[/bold green] [bold]{active}[/bold]"
else:
active_info = "[bold yellow]Auto-selection enabled[/bold yellow]"
management_panel = Panel(
f"{active_info}\n\n"
"[bold]Management Commands:[/bold]\n"
"• [#a855f7]/token add[/#a855f7] - Add new token\n"
"• [#a855f7]/token use <name>[/#a855f7] - Switch token\n"
"• [#a855f7]/token remove <name>[/#a855f7] - Remove token",
title="[bold]Token Management[/bold]",
border_style="#9333ea",
padding=(1, 2)
)
console.print(Align.center(management_panel))
console.print()
def add_token_interactive():
"""Add a token with professional interactive prompts"""
console.print()
# Welcome panel
welcome_panel = Panel(
"[bold white]Add New Access Token[/bold white]\n\n"
"[dim]This will securely store your ChatGPT access token for use with the CLI.[/dim]",
title="[bold]Token Setup[/bold]",
border_style="#a855f7",
padding=(1, 2)
)
console.print(welcome_panel)
console.print()
# Ask for name
name = Prompt.ask(
"[bold #a855f7]Token Name[/bold #a855f7]",
default="default",
show_default=True
)
if not name:
console.print(f"[{Theme.ERROR}]✗ Name cannot be empty![/{Theme.ERROR}]")
return
# Ensure tokens is a dictionary
if not isinstance(config.tokens, dict):
config.tokens = {}
if name in config.tokens:
if not Confirm.ask(f"[{Theme.WARNING}]⚠ Token '{name}' already exists. Replace it?[/{Theme.WARNING}]"):
console.print("[dim]✗ Operation cancelled[/dim]")
return
# Instructions panel
instructions_panel = Panel(
"[bold]How to get your access token:[/bold]\n\n"
"1. You can find it in [bold #a855f7]@https://chatgpt.com/api/auth/session[/bold #a855f7]\n"
"2. Copy the returned token value\n\n"
"[dim]The token should start with 'eyJ' or be a long string of characters.[/dim]",
title="[bold]Instructions[/bold]",
border_style="#9333ea",
padding=(1, 2)
)
console.print(instructions_panel)
console.print()
# Ask for token
token = Prompt.ask(
"[bold #a855f7]Access Token[/bold #a855f7]"
)
if not token or len(token) < 20:
console.print(f"[{Theme.ERROR}]✗ Invalid token! Token must be at least 20 characters.[/{Theme.ERROR}]")
return
# Save token
config.add_token(name, token)
# Success panel
success_panel = Panel(
f"[bold green]✓ Token '{name}' added successfully![/bold green]\n\n"
f"[dim]Token preview:[/dim] [bold]{token[:12]}...{token[-6:]}[/bold]",
title="[bold]Success[/bold]",
border_style=Theme.SUCCESS,
padding=(1, 2)
)
console.print(success_panel)
console.print()
# Ask if they want to use it now
if Confirm.ask(f"[{Theme.ACCENT_BLUE}]🚀 Use this token now?[/{Theme.ACCENT_BLUE}]", default=True):
config.use_token(name)
console.print(f"[{Theme.SUCCESS}]✓ Now using token '{name}'[/{Theme.SUCCESS}]")
console.print()
def generate_apikey_interactive():
"""Generate a new API key for external programs with professional interface"""
console.print()
if not config.get_active_token():
error_panel = Panel(
"[bold red]✗ No ChatGPT access token configured![/bold red]\n\n"
"[dim]You need to add a ChatGPT access token first before generating API keys.[/dim]\n"
"[bold]Add one with:[/bold] [cyan]/token add[/cyan]",
title="[bold]Missing Token[/bold]",
border_style=Theme.ERROR,
padding=(1, 2)
)
console.print(error_panel)
console.print()
return
welcome_panel = Panel(
"[bold white]Generate OpenAI-Compatible API Key[/bold white]\n\n"
"[dim]This creates a secure API key that external applications can use to access your ChatGPT account.[/dim]",
title="[bold]API Key Generator[/bold]",
border_style=Theme.PRIMARY,
padding=(1, 2)
)
console.print(welcome_panel)
console.print()
name = Prompt.ask(
"[bold #a855f7]🏷️ API Key Name[/bold #a855f7]",
default="my-app",
show_default=True
)
if not name:
console.print(f"[{Theme.ERROR}]✗ Name cannot be empty![/{Theme.ERROR}]")
return
if not isinstance(config.apikeys, dict):
config.apikeys = {}
if name in config.apikeys:
if not Confirm.ask(f"[{Theme.WARNING}]⚠ API key '{name}' already exists. Replace it?[/{Theme.WARNING}]"):
console.print("[dim]✗ Operation cancelled[/dim]")
return
api_key = config.generate_apikey(name)
endpoint = config.get("api_endpoint", "http://localhost:5005")
success_panel = Panel(
f"[bold green]✓ API Key Generated Successfully![/bold green]\n\n"
f"[bold]Name:[/bold] [yellow]{name}[/yellow]\n"
f"[bold]API Key:[/bold] [#a855f7]{api_key}[/#a855f7]\n"
f"[bold]Base URL:[/bold] [magenta]{endpoint}/v1[/magenta]",
title="[bold]Success[/bold]",
border_style=Theme.SUCCESS,
padding=(1, 2)