-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
520 lines (433 loc) · 17.9 KB
/
Copy pathcli.py
File metadata and controls
520 lines (433 loc) · 17.9 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
"""
UdaPlay CLI interface module.
Banner, configuration wizard, help screen, and response formatting.
"""
import os
from pathlib import Path
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
from rich.markdown import Markdown
from rich.prompt import Prompt, Confirm
from rich.rule import Rule
from rich import box
from lib.localization import set_language, _
console = Console()
BANNER = r"""
_ _ _ ____ _
| | | | __| | __ _| _ \| | __ _ _ _
| | | |/ _` |/ _` | |_) | |/ _` | | | |
| |_| | (_| | (_| | __/| | (_| | |_| |
\___/ \__,_|\__,_|_| |_|\__,_|\__, |
|___/"""
PROVIDERS = {
"1": {
"key": "openai",
"label": "OpenAI",
"base_url": "https://api.openai.com/v1",
"models": ["gpt-4o-mini", "gpt-4o", "gpt-4-turbo","gpt-5", "gpt-4.1"],
"key_url": "https://platform.openai.com/api-keys",
},
"2": {
"key": "gemini",
"label": "Google Gemini",
"base_url": "https://generativelanguage.googleapis.com/v1beta/openai/",
"models": ["gemini-3-flash-preview", "gemini-2.5-flash", "gemini-2.5-pro"],
"key_url": "https://aistudio.google.com/apikey",
},
"3": {
"key": "local",
"label": "Lokal / Ollama",
"base_url": "http://localhost:11434/v1",
"models": ["llama3.2", "mistral", "codellama"],
"key_url": None,
},
}
LOG_LEVELS = ["DEBUG", "INFO", "WARNING", "ERROR"]
CONFIG_KEYS = [
{"key": "LANGUAGE", "label": "Dil / Language", "required": False, "secret": False},
{"key": "LLM_PROVIDER", "label": "Sağlayıcı", "required": True, "secret": False},
{"key": "LLM_API_KEY", "label": "API Anahtarı", "required": True, "secret": True},
{"key": "LLM_API_BASE", "label": "API Base URL", "required": False, "secret": False},
{"key": "LLM_MODEL", "label": "Model", "required": False, "secret": False},
{"key": "TAVILY_API_KEY", "label": "Tavily API Key", "required": False, "secret": True},
{"key": "LOG_LEVEL", "label": "Log Seviyesi", "required": False, "secret": False},
{"key": "LOG_FORMAT", "label": "Log Formatı", "required": False, "secret": False},
]
PLACEHOLDER_VALUES = {"your-api-key", "your-openai-api-key", "your-tavily-api-key"}
# ─────────────────────────────────────────────
# Banner & Help
# ─────────────────────────────────────────────
def print_banner():
"""Prints the application title banner."""
banner_text = Text(BANNER, style="bold cyan")
subtitle = Text("Video Game Research Agent - Ask anything about games", style="dim white")
content = Text.assemble(banner_text, "\n", subtitle)
console.print(Panel(content, border_style="cyan", padding=(0, 2)))
def print_help():
"""Prints interactive mode commands."""
table = Table(
title=_("commands_title"),
box=box.ROUNDED,
border_style="cyan",
title_style="bold cyan",
show_header=True,
header_style="bold white",
)
table.add_column(_("command_col"), style="bold yellow", min_width=12)
table.add_column(_("desc_col"), style="white")
commands = [
("/help", _("help_desc")),
("/config", _("config_desc")),
("/reset", _("reset_desc")),
("/status", _("status_desc")),
("/lang", _("lang_desc")),
("/quit", _("quit_desc")),
]
for cmd, desc in commands:
table.add_row(cmd, desc)
console.print()
console.print(table)
console.print()
def print_cli_help():
"""Prints CLI usage information."""
print_banner()
console.print()
table = Table(
title=_("usage_title"),
box=box.ROUNDED,
border_style="cyan",
title_style="bold cyan",
show_header=True,
header_style="bold white",
)
table.add_column(_("command_col"), style="bold yellow", min_width=40)
table.add_column(_("desc_col"), style="white")
rows = [
("python main.py", _("usage_interactive")),
("python main.py config", _("usage_config")),
("python main.py status", _("usage_status")),
('python main.py -q "soru"', _("usage_single")),
('python main.py --model gpt-4o -q "soru"', _("usage_single_model")),
("python main.py --env dosya.env", _("usage_env")),
("python main.py --help", _("usage_help")),
]
for cmd, desc in rows:
table.add_row(cmd, desc)
console.print(table)
console.print()
# ─────────────────────────────────────────────
# File helpers
# ─────────────────────────────────────────────
def _read_env_file(path: str) -> dict:
"""Reads an .env file and returns a key=value dict."""
values = {}
p = Path(path)
if not p.exists():
return values
for line in p.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
if "=" in line:
k, v = line.split("=", 1)
v = v.strip().strip('"').strip("'")
values[k.strip()] = v
return values
def _is_real_value(value: str) -> bool:
"""Değerin placeholder olmayan gerçek bir değer olup olmadığını kontrol et."""
return bool(value) and value.lower() not in PLACEHOLDER_VALUES
def _mask(value: str) -> str:
"""Gizli değerleri maskele."""
if len(value) <= 8:
return "****"
return value[:4] + "..." + value[-4:]
def _provider_label(key: str) -> str:
"""Provider key'inden okunabilir etiket döndür."""
for p in PROVIDERS.values():
if p["key"] == key:
return p["label"]
return key
# ─────────────────────────────────────────────
# Configuration Status
# ─────────────────────────────────────────────
def print_config_status(env_path: str = "config.env", show_secrets: bool = False):
"""Prints the current configuration status in a table."""
values = _read_env_file(env_path)
file_exists = Path(env_path).exists()
if not file_exists:
console.print()
console.print(
Panel(
_("config_not_found", env_path=env_path),
border_style="red",
title=_("warning_title"),
)
)
return False
table = Table(
title=_("config_title", env_path=env_path),
box=box.ROUNDED,
border_style="cyan",
title_style="bold cyan",
show_header=True,
header_style="bold white",
)
table.add_column(_("var_col"), style="bold", min_width=16)
table.add_column(_("status_col"), min_width=8)
table.add_column(_("val_col"), min_width=24)
table.add_column(_("req_col"), min_width=8)
all_ok = True
for item in CONFIG_KEYS:
key = item["key"]
val = values.get(key, "")
is_set = _is_real_value(val)
required_text = f"[bold red]{_('yes')}[/]" if item["required"] else f"[dim]{_('no')}[/]"
if is_set:
status = "[bold green]OK[/]"
if item["secret"]:
display_val = val if show_secrets else _mask(val)
elif key == "LLM_PROVIDER":
display_val = _provider_label(val)
else:
display_val = val
elif item["required"]:
status = f"[bold red]{_('missing')}[/]"
display_val = "[dim]-[/]"
all_ok = False
else:
status = f"[dim]{_('empty')}[/]"
display_val = f"[dim]{_('default')}[/]"
table.add_row(key, status, display_val, required_text)
console.print()
console.print(table)
console.print()
return all_ok
# ─────────────────────────────────────────────
# Configuration wizard
# ─────────────────────────────────────────────
def config_wizard(env_path: str = "config.env") -> bool:
"""Interactive configuration wizard.
Args:
env_path: Config file path to be written.
Returns:
``True`` if config was written successfully.
"""
console.print()
console.print(
Panel(
f"[bold]{_('wizard_title')}[/]\n\n{_('wizard_desc')}",
border_style="cyan",
title=_("settings_title"),
)
)
existing = _read_env_file(env_path)
if existing:
if Confirm.ask(f" {_('view_current_prompt')}", default=True):
show_secrets = Confirm.ask(f" {_('view_secrets_prompt')}", default=False)
print_config_status(env_path, show_secrets=show_secrets)
config = {}
# ── 0. Dil / Language ──
console.print(Rule(f"[bold yellow]0/5[/] {_('language_prompt')}", style="cyan"))
current_lang = existing.get("LANGUAGE", "tr")
config["LANGUAGE"] = Prompt.ask(" Seçim / Selection [tr/en]", choices=["tr", "en"], default=current_lang)
# Switch language immediately for the rest of the wizard
set_language(config["LANGUAGE"])
# ── 1. Select Provider ──
console.print()
console.print(Rule(f"[bold yellow]1/5[/] {_('provider_step')}", style="cyan"))
console.print(f" {_('provider_prompt')}\n")
for num, info in PROVIDERS.items():
models_str = ", ".join(info["models"][:2])
console.print(f" [bold yellow]{num}[/]) {info['label']:<16} [dim]{_('models_label')}: {models_str}[/]")
console.print()
current_provider = existing.get("LLM_PROVIDER", "")
default_choice = "1"
for num, info in PROVIDERS.items():
if info["key"] == current_provider:
default_choice = num
choice = Prompt.ask(f" {_('selection_prompt')}", choices=["1", "2", "3"], default=default_choice)
provider_info = PROVIDERS[choice]
config["LLM_PROVIDER"] = provider_info["key"]
# ── 2. API Anahtarı ──
console.print()
console.print(Rule(f"[bold yellow]2/5[/] {_('apikey_step')}", style="cyan"))
current_key = existing.get("LLM_API_KEY", "")
if provider_info["key"] == "local":
console.print(f" {_('local_apikey_hint')}")
if _is_real_value(current_key):
console.print(f" {_('current_val')}: [green]{_mask(current_key)}[/]")
key_input = Prompt.ask(" [bold]LLM_API_KEY[/]", default=current_key or "not-needed")
config["LLM_API_KEY"] = key_input
else:
if provider_info["key_url"]:
console.print(f" {_('get_key_hint', url=provider_info['key_url'])}")
if _is_real_value(current_key):
console.print(f" {_('current_val')}: [green]{_mask(current_key)}[/]")
if not Confirm.ask(f" {_('change_prompt')}", default=False):
config["LLM_API_KEY"] = current_key
else:
config["LLM_API_KEY"] = Prompt.ask(" [bold]LLM_API_KEY[/]")
else:
config["LLM_API_KEY"] = Prompt.ask(" [bold]LLM_API_KEY[/]")
if not config["LLM_API_KEY"]:
console.print(_("apikey_required"))
return False
# ── 3. API Base URL ──
console.print()
console.print(Rule(f"[bold yellow]3/5[/] {_('baseurl_step')}", style="cyan"))
default_base = provider_info["base_url"]
current_base = existing.get("LLM_API_BASE", "") or existing.get("OPENAI_API_BASE", "")
show_default = current_base if _is_real_value(current_base) else default_base
console.print(f" {_('default_hint', val=default_base)}")
config["LLM_API_BASE"] = Prompt.ask(" [bold]LLM_API_BASE[/]", default=show_default)
# ── 4. Model ──
console.print()
console.print(Rule(f"[bold yellow]4/5[/] {_('model_step')}", style="cyan"))
console.print(f" {_('recommended_hint', val=', '.join(provider_info['models']))}")
current_model = existing.get("LLM_MODEL", "")
default_model = current_model if _is_real_value(current_model) else provider_info["models"][0]
config["LLM_MODEL"] = Prompt.ask(" [bold]LLM_MODEL[/]", default=default_model)
# ── 5. Tavily ──
console.print()
console.print(Rule(f"[bold yellow]5/5[/] {_('extra_step')}", style="cyan"))
# Tavily
console.print(f" {_('tavily_hint')}")
current_tavily = existing.get("TAVILY_API_KEY", "")
if _is_real_value(current_tavily):
console.print(f" {_('current_val')} Tavily key: [green]{_mask(current_tavily)}[/]")
if Confirm.ask(f" {_('change_prompt')}", default=False):
config["TAVILY_API_KEY"] = Prompt.ask(" [bold]TAVILY_API_KEY[/]", default="")
else:
config["TAVILY_API_KEY"] = current_tavily
else:
config["TAVILY_API_KEY"] = Prompt.ask(" [bold]TAVILY_API_KEY[/]", default="")
# Log
console.print()
current_level = existing.get("LOG_LEVEL", "INFO")
config["LOG_LEVEL"] = Prompt.ask(
f" [bold]{_('log_level_prompt')}[/]",
choices=LOG_LEVELS,
default=current_level,
)
current_format = existing.get("LOG_FORMAT", "text")
config["LOG_FORMAT"] = Prompt.ask(
f" [bold]{_('log_format_prompt')}[/]",
choices=["text", "json"],
default=current_format,
)
# ── Kaydet ──
console.print()
_write_config(env_path, config)
console.print(
Panel(
_("config_saved", env_path=env_path),
border_style="green",
)
)
return True
def _write_config(path: str, config: dict):
"""Writes the config dict to an .env file."""
lines = [
"# UdaPlay Configuration",
"",
f"LANGUAGE={config.get('LANGUAGE', 'tr')}",
f"LLM_PROVIDER={config.get('LLM_PROVIDER', 'openai')}",
f"LLM_API_KEY={config.get('LLM_API_KEY', '')}",
f"LLM_API_BASE={config.get('LLM_API_BASE', '')}",
f"LLM_MODEL={config.get('LLM_MODEL', '')}",
]
tavily = config.get("TAVILY_API_KEY", "")
if tavily:
lines.append(f"TAVILY_API_KEY={tavily}")
lines.append(f"LOG_LEVEL={config.get('LOG_LEVEL', 'INFO')}")
lines.append(f"LOG_FORMAT={config.get('LOG_FORMAT', 'text')}")
lines.append("")
Path(path).write_text("\n".join(lines), encoding="utf-8")
# ─────────────────────────────────────────────
# Check Config
# ─────────────────────────────────────────────
def check_config(env_path: str = "config.env") -> bool:
"""Checks if the config file exists and is valid.
Returns:
``True`` if required fields (LLM_PROVIDER, LLM_API_KEY) are filled.
"""
if not Path(env_path).exists():
return False
values = _read_env_file(env_path)
has_provider = _is_real_value(values.get("LLM_PROVIDER", ""))
has_key = _is_real_value(values.get("LLM_API_KEY", ""))
return has_provider and has_key
def ensure_config(env_path: str = "config.env") -> bool:
"""If config is missing, redirects the user to the wizard.
Returns:
``True`` if config is ready.
"""
if check_config(env_path):
return True
console.print()
if not Path(env_path).exists():
console.print(
Panel(
_("config_needed_desc", env_path=env_path),
border_style="yellow",
title=_("config_needed_title"),
)
)
else:
console.print(
Panel(
_("config_missing_desc"),
border_style="yellow",
title=_("config_missing_title"),
)
)
if Confirm.ask(f"\n {_('start_wizard_prompt')}", default=True):
return config_wizard(env_path)
else:
console.print(_("exiting"))
return False
# ─────────────────────────────────────────────
# Response formatting
# ─────────────────────────────────────────────
def print_response(report: dict):
"""Prints the agent response in a formatted way."""
answer = report.get("answer", "")
confidence = report.get("confidence", 0.0)
tokens = report.get("total_tokens", 0)
sources = report.get("sources", [])
console.print()
console.print(Markdown(answer))
conf_color = "green" if confidence >= 80 else "yellow" if confidence >= 60 else "red"
meta = Text.assemble(
(f"{_('confidence')}: ", "dim"),
(f"{confidence:.0f}%", f"bold {conf_color}"),
(" | ", "dim"),
("Token: ", "dim"),
(str(tokens), "bold white"),
(" | ", "dim"),
(f"{_('source')}: ", "dim"),
(", ".join(sources) if sources else "-", "cyan"),
)
console.print(Panel(meta, border_style="dim", padding=(0, 1)))
console.print()
def print_chat_header(model_name: str):
"""Prints the chat session header."""
provider = os.getenv("LLM_PROVIDER", "")
provider_text = _provider_label(provider) if provider else ""
info_parts = []
if provider_text:
info_parts.append(f"[bold]{_('provider')}:[/] [cyan]{provider_text}[/]")
info_parts.append(f"[bold]{_('model')}:[/] [cyan]{model_name}[/]")
info_parts.append(_("help_hint"))
console.print()
console.print(
Panel(
"\n".join(info_parts),
border_style="cyan",
title="UdaPlay",
subtitle=_("quit_hint"),
)
)
console.print()