-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.py
More file actions
2153 lines (1767 loc) · 82.8 KB
/
Copy pathmain.py
File metadata and controls
2153 lines (1767 loc) · 82.8 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
"""CrawlLama - Local AI Search and Answer Agent
A fully local AI system that intelligently answers user queries by combining:
- Ollama (local LLM) for text understanding
- Autonomous web research with structured tool calls
- RAG (Retrieval-Augmented Generation) for context-based answers
"""
import argparse
import io
import json
import os
import re
import sys
from pathlib import Path
from dotenv import load_dotenv
from rich.console import Console
from rich.markdown import Markdown
from rich.panel import Panel
from rich.prompt import Prompt
# Add project root to path
sys.path.insert(0, str(Path(__file__).parent))
from _version import __version__ as VERSION
from core.agent import SearchAgent
from core.agent.constants import QUICK_RESULT_REFERENCE_PATTERN, has_osint_operators
from core.langgraph_agent import MultiHopReasoningAgent, create_multihop_agent
from utils.cli_input import read_user_input
from utils.logger import Logger
# Force UTF-8 encoding for stdout/stderr to handle Unicode characters
if sys.platform == "win32":
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')
console = Console()
class CrawllamaException(Exception):
"""Custom exception for Crawllama application errors."""
def __init__(self, message: str, exit_code: int = 1):
super().__init__(message)
self.exit_code = exit_code
self.message = message
class InputValidator:
"""Input validation helper for settings."""
@staticmethod
def validate_float(value: str, min_val: float = None, max_val: float = None) -> float | None:
"""Validate and convert string to float within bounds."""
try:
float_val = float(value)
if min_val is not None and float_val < min_val:
return None
if max_val is not None and float_val > max_val:
return None
return float_val
except ValueError:
return None
@staticmethod
def validate_int(value: str, min_val: int = None, max_val: int = None) -> int | None:
"""Validate and convert string to int within bounds."""
try:
int_val = int(value)
if min_val is not None and int_val < min_val:
return None
if max_val is not None and int_val > max_val:
return None
return int_val
except ValueError:
return None
@staticmethod
def validate_url(value: str) -> bool:
"""Validate URL format."""
url_pattern = re.compile(
r'^https?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
return bool(url_pattern.match(value))
@staticmethod
def validate_model_name(value: str) -> bool:
"""Validate LLM model name format."""
if not value or len(value) < 2:
return False
# Allow alphanumeric, dots, colons, hyphens, underscores
pattern = re.compile(r'^[a-zA-Z0-9._:-]+$')
return bool(pattern.match(value))
# ---------------------------------------------------------------------------
# Configuration helpers
# ---------------------------------------------------------------------------
def fetch_local_ollama_models(config: dict) -> tuple[list[str], str]:
"""Fetch locally downloaded Ollama models from Ollama API."""
llm_config = config.get("llm", {})
base_url = llm_config.get("base_url", "http://127.0.0.1:11434").rstrip("/")
try:
import requests
response = requests.get(f"{base_url}/api/tags", timeout=3)
response.raise_for_status()
payload = response.json() if response.content else {}
models = payload.get("models", [])
names = []
for model in models:
name = str(model.get("name", "")).strip()
if name:
names.append(name)
# Deduplicate while preserving order
deduped = list(dict.fromkeys(names))
return deduped, ""
except Exception as e:
return [], str(e)
def load_config(config_path: str = "config.json") -> dict:
"""Load configuration from JSON file."""
try:
with open(config_path, encoding="utf-8") as f:
return json.load(f)
except FileNotFoundError:
raise CrawllamaException(f"Config file not found: {config_path}", 1) from None
except json.JSONDecodeError as e:
raise CrawllamaException(f"Invalid JSON in config file: {e}", 1) from e
def adjust_config_for_provider(config: dict) -> dict:
"""
Automatically adjust token limits based on LLM provider.
Local models (Ollama): High limits (16000+ tokens, large context)
Cloud APIs (OpenAI, Anthropic, Groq): Lower limits (4096 tokens, smaller context)
Note: Adjusts if max_tokens doesn't match the provider's expected default.
Args:
config: Configuration dictionary
Returns:
Modified config with adjusted limits
"""
provider = config.get("llm", {}).get("provider", "ollama")
current_max_tokens = config.get("llm", {}).get("max_tokens")
# Default values for each provider
DEFAULT_OLLAMA_TOKENS = 16000
DEFAULT_CLOUD_TOKENS = 2048
# Determine if we need to adjust based on provider
if provider == "ollama":
# For Ollama, if max_tokens is too low (cloud default), adjust it
if current_max_tokens is None or current_max_tokens <= DEFAULT_CLOUD_TOKENS:
config["llm"]["max_tokens"] = DEFAULT_OLLAMA_TOKENS
config["security"]["max_context_length"] = 16000
config["context_limits"] = {
"small": 4000,
"medium": 6000,
"large": 8000,
"xlarge": 12000,
"max_storage": 8000
}
else:
# For cloud providers, if max_tokens is too high (ollama default), adjust it
if current_max_tokens is None or current_max_tokens >= DEFAULT_OLLAMA_TOKENS:
config["llm"]["max_tokens"] = DEFAULT_CLOUD_TOKENS
config["security"]["max_context_length"] = 6000
config["context_limits"] = {
"small": 1500,
"medium": 2500,
"large": 3500,
"xlarge": 5000,
"max_storage": 3000
}
return config
def save_config(config: dict, config_path: str = "config.json"):
"""
Save configuration to JSON file.
Args:
config: Configuration dictionary
config_path: Path to config file
"""
try:
# Atomic write (tmp + rename): a crash mid-write cannot truncate the
# existing config file.
tmp_path = f"{config_path}.tmp"
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(config, f, indent=2, ensure_ascii=False)
os.replace(tmp_path, config_path)
console.print(f"[green][OK] Configuration saved: {config_path}[/green]")
return True
except Exception as e:
console.print(f"[red][X] Error saving: {e}[/red]")
return False
# ---------------------------------------------------------------------------
# Startup checks
# ---------------------------------------------------------------------------
def _check_ollama_connection(llm_config: dict) -> dict:
"""Check Ollama connection with a quick check (2 attempts, 5 second timeout)."""
import time
import requests
base_url = llm_config.get("base_url", "http://127.0.0.1:11434")
last_error = None
# Try twice with a short delay between attempts
for attempt in range(2):
try:
response = requests.get(f"{base_url}/api/tags", timeout=5)
response.raise_for_status()
console.print("[green][OK] Ollama connection successful[/green]")
return {"status": True, "error_msg": ""}
except Exception as e:
last_error = e
if attempt == 0:
# Wait a bit before second attempt
time.sleep(1)
msg = "Ollama is not running or not accessible"
console.print(f"[yellow][!] {msg}[/yellow]")
console.print(f"[dim]Attempted URL: {base_url}/api/tags[/dim]")
if last_error:
console.print(f"[dim]Error: {type(last_error).__name__}: {str(last_error)[:100]}[/dim]")
return {"status": False, "error_msg": msg}
def _check_cloud_api_key(provider: str) -> dict:
"""For cloud providers, just check if the API key is set."""
import os
key_name = f"{provider.upper()}_API_KEY"
if os.getenv(key_name):
console.print(f"[green][OK] {provider.title()} API key configured[/green]")
return {"status": True, "error_msg": ""}
msg = f"{provider.title()} API key not found. Please set {key_name} in .env file"
console.print(f"[yellow][!] {msg}[/yellow]")
return {"status": False, "error_msg": msg}
def _check_directories(config: dict) -> dict:
"""Create the data directories from config and report failures."""
paths_config = config.get("paths", {})
directories = [
paths_config.get("cache_dir", "data/cache"),
paths_config.get("embeddings_dir", "data/embeddings"),
paths_config.get("logs_dir", "logs")
]
dir_errors = []
for directory in directories:
try:
Path(directory).mkdir(parents=True, exist_ok=True)
except Exception as e:
dir_errors.append(f"{directory}: {e}")
if dir_errors:
console.print(f"[red][X] Directory initialization failed: {dir_errors}[/red]")
return {"status": False, "error_msg": "; ".join(dir_errors)}
console.print("[green][OK] Directories initialized[/green]")
return {"status": True, "error_msg": ""}
def _check_proxies() -> dict:
"""Validate proxies if configured."""
from utils.proxy_validator import ProxyValidator
from utils.tor_mode import get_tor_config, is_tor_enabled
if is_tor_enabled():
# Tor mode already verified the circuit on startup; the regular proxy
# validation would only report its own SOCKS settings back.
console.print(f"[green][OK] Tor mode active ({get_tor_config().proxy_url})[/green]")
return {"status": True, "error_msg": ""}
proxy_validator = ProxyValidator.load_from_env()
if not proxy_validator.is_configured():
console.print("[dim]No proxy configured (direct connection)[/dim]")
return {"status": True, "error_msg": ""}
console.print("[cyan]Validating proxy configuration...[/cyan]")
proxy_results = proxy_validator.validate_proxies()
if all(proxy_results.values()):
console.print("[green][OK] Proxy configuration valid[/green]")
return {"status": True, "error_msg": ""}
msg = "Some proxies failed validation (will proceed without proxy)"
console.print(f"[yellow]⚠ {msg}[/yellow]")
return {"status": False, "error_msg": msg}
def _initialize_tor_mode_or_exit(config: dict) -> None:
"""Activate and verify Tor mode if enabled; abort startup on failure."""
from utils.tor_mode import TorError, initialize_tor_mode
try:
tor_config = initialize_tor_mode(config)
except TorError as e:
raise CrawllamaException(f"Tor mode startup failed: {e}", 1) from e
if tor_config.enabled:
console.print(
f"[green][OK] Tor mode active — all web traffic is routed via {tor_config.proxy_url}[/green]"
)
def startup_check(config: dict) -> dict:
"""
Perform startup health checks.
Args:
config: Configuration dictionary
Returns:
Dict with component status and error messages
"""
console.print("[cyan]Performing startup checks...[/cyan]")
results = {}
# Check LLM connection based on provider
llm_config = config.get("llm", {})
provider = llm_config.get("provider", "ollama")
if provider == "ollama":
results["ollama"] = _check_ollama_connection(llm_config)
else:
results[provider] = _check_cloud_api_key(provider)
results["directories"] = _check_directories(config)
results["proxy"] = _check_proxies()
return results
# ---------------------------------------------------------------------------
# Context status display
# ---------------------------------------------------------------------------
def _count_session_tokens(agent: SearchAgent) -> tuple[int, int]:
"""Count tokens used by the conversation history and saved search results."""
conversation_tokens = 0
for entry in agent.session.conversation_history:
conversation_tokens += agent.context_manager.estimate_tokens(entry.get("query", ""))
conversation_tokens += agent.context_manager.estimate_tokens(entry.get("response", ""))
search_results_tokens = 0
for result in agent.session.last_search_results:
if isinstance(result, dict):
search_results_tokens += agent.context_manager.estimate_tokens(
result.get("title", "") + " " + result.get("snippet", "")
)
return conversation_tokens, search_results_tokens
def _build_context_table(conversation_tokens: int, search_results_tokens: int,
total_used: int, available_tokens: int,
max_tokens: int, usage_percent: float):
"""Build the context usage table."""
from rich.table import Table
table = Table(title="Context Usage Tracker", show_header=True, header_style="bold cyan")
table.add_column("Source", style="cyan", width=20)
table.add_column("Tokens", style="yellow", justify="right", width=12)
table.add_column("Share", style="dim", justify="right", width=12)
table.add_row(
"Conversation",
f"{conversation_tokens:,}",
f"{(conversation_tokens/max_tokens*100):.1f}%" if max_tokens > 0 else "0%"
)
table.add_row(
"Search Results",
f"{search_results_tokens:,}",
f"{(search_results_tokens/max_tokens*100):.1f}%" if max_tokens > 0 else "0%"
)
table.add_row(
"[bold]Total Used[/bold]",
f"[bold]{total_used:,}[/bold]",
f"[bold]{usage_percent:.1f}%[/bold]"
)
table.add_row(
"[green]Available[/green]",
f"[green]{available_tokens:,}[/green]",
f"[green]{(available_tokens/max_tokens*100):.1f}%[/green]"
)
table.add_row(
"[dim]Maximum[/dim]",
f"[dim]{max_tokens:,}[/dim]",
"[dim]100%[/dim]"
)
return table
def _print_usage_bar(usage_percent: float) -> None:
"""Print a colored visual progress bar for the context usage."""
# Determine color based on usage
if usage_percent < 50:
color = "green"
elif usage_percent < 80:
color = "yellow"
else:
color = "red"
console.print("\n[bold]Context Usage:[/bold]")
console.print(f"[{color}]{'█' * int(usage_percent / 2)}[/{color}]{'░' * int((100 - usage_percent) / 2)} {usage_percent:.1f}%")
def _print_session_info(agent: SearchAgent) -> None:
"""Print conversation and search result counts for the current session."""
console.print("\n[dim]Session Info:[/dim]")
console.print(
f" • Conversation Entries: {len(agent.session.conversation_history)}/{agent.session.max_history}"
)
console.print(f" • Saved Search Results: {len(agent.session.last_search_results)}")
if agent.session.last_search_query:
console.print(f" • Last Search: '{agent.session.last_search_query[:50]}...'")
def _print_memory_summary() -> None:
"""Print a summary of the memory store contents."""
try:
from core.memory_store import get_memory_store
memory = get_memory_store()
summary = memory.get_summary()
console.print("\n[bold cyan]💾 Memory Store:[/bold cyan]")
console.print(f" 📧 Emails: {summary['emails']:,}")
console.print(f" 📱 Phones: {summary['phones']:,}")
console.print(f" 🌐 IPs: {summary['ips']:,}")
console.print(f" 👤 Usernames: {summary['usernames']:,}")
console.print(f" 🔗 Domains: {summary['domains']:,}")
console.print(f" 📝 Notes: {summary['notes']:,}")
console.print(f" [bold]Total: {summary['total_entries']:,}[/bold]")
except Exception as e:
console.print(f"\n[dim]Memory Store: Not available ({e})[/dim]")
def show_context_status(agent: SearchAgent):
"""
Display current context usage and available tokens.
Args:
agent: SearchAgent instance
"""
# Use prompt budget (actual context budget) instead of response max_tokens
max_tokens = max(1, agent.context_manager.prompt_budget)
conversation_tokens, search_results_tokens = _count_session_tokens(agent)
total_used = conversation_tokens + search_results_tokens
available_tokens = max_tokens - total_used
usage_percent = (total_used / max_tokens * 100) if max_tokens > 0 else 0
console.print("\n")
console.print(_build_context_table(
conversation_tokens, search_results_tokens,
total_used, available_tokens, max_tokens, usage_percent
))
_print_usage_bar(usage_percent)
_print_session_info(agent)
_print_memory_summary()
console.print()
# ---------------------------------------------------------------------------
# Settings display and editor
# ---------------------------------------------------------------------------
def show_settings(config: dict):
"""
Display current settings in a formatted way.
Args:
config: Configuration dictionary
"""
from rich.table import Table
table = Table(title="CrawlLama Settings", show_header=True, header_style="bold cyan")
table.add_column("Category", style="cyan")
table.add_column("Setting", style="yellow")
table.add_column("Value", style="green")
# LLM Settings
llm_config = config.get("llm", {})
provider = llm_config.get("provider", "ollama")
table.add_row("LLM", "Provider", provider)
table.add_row("", "Model", llm_config.get("model", "N/A"))
table.add_row("", "Temperature", str(llm_config.get("temperature", "N/A")))
table.add_row("", "Max Tokens", str(llm_config.get("max_tokens", "N/A")))
table.add_row("", "Stream", str(llm_config.get("stream", "N/A")))
# Search Settings
search_config = config.get("search", {})
table.add_row("Search", "Provider", search_config.get("provider", "N/A"))
table.add_row("", "Max Results", str(search_config.get("max_results", "N/A")))
table.add_row("", "Region", search_config.get("region", "N/A"))
# RAG Settings
rag_config = config.get("rag", {})
table.add_row("RAG", "Enabled", str(rag_config.get("enabled", "N/A")))
table.add_row("", "Embedding Model", rag_config.get("embedding_model", "N/A"))
table.add_row("", "Top K", str(rag_config.get("top_k", "N/A")))
# Cache Settings
cache_config = config.get("cache", {})
table.add_row("Cache", "Enabled", str(cache_config.get("enabled", "N/A")))
table.add_row("", "TTL Hours", str(cache_config.get("ttl_hours", "N/A")))
# OSINT Settings
osint_config = config.get("osint", {})
table.add_row("OSINT", "Max Results", str(osint_config.get("max_results", "N/A")))
table.add_row("", "Email Search Limit", str(osint_config.get("email_search_limit", "N/A")))
table.add_row("", "Phone Search Limit", str(osint_config.get("phone_search_limit", "N/A")))
table.add_row("", "General OSINT Limit", str(osint_config.get("general_osint_limit", "N/A")))
table.add_row("", "Safesearch", str(osint_config.get("safesearch", "N/A")))
# Memory Store Settings
memory_config = config.get("memory", {})
table.add_row("Memory", "Enabled", str(memory_config.get("enabled", "N/A")))
table.add_row("", "Auto Clear on Clear", str(memory_config.get("auto_clear_on_clear", "N/A")))
table.add_row("", "Max Entries", str(memory_config.get("max_entries", "N/A")))
table.add_row("", "Max File Size (MB)", str(memory_config.get("max_file_size_mb", "N/A")))
table.add_row("", "File Path", str(memory_config.get("file_path", "N/A")))
# Hallucination Detection Settings
hallu_config = config.get("hallucination_detection", {})
table.add_row("Hallucination", "Enabled", str(hallu_config.get("enabled", "N/A")))
table.add_row("", "Detection Level", str(hallu_config.get("detection_level", "N/A")))
table.add_row("", "Warning Mode", str(hallu_config.get("warning_mode", "N/A")))
table.add_row("", "Threshold", str(hallu_config.get("hallucination_threshold", "N/A")))
table.add_row("", "Context Alignment", str(hallu_config.get("context_alignment_threshold", "N/A")))
table.add_row("", "Fact Checking", str(hallu_config.get("fact_checking_enabled", "N/A")))
table.add_row("", "Max Processing Time", str(hallu_config.get("max_processing_time", "N/A")))
# UI Display Settings
ui_config = config.get("ui", {})
table.add_row("UI Display", "Show Adaptive Report", str(ui_config.get("show_adaptive_report", "N/A")))
console.print("\n")
console.print(table)
console.print("\n")
def _ask_int_setting(section: dict, key: str, prompt_label: str, current: int,
change_label: str, min_val: int | None = None,
max_val: int | None = None, unit: str = "") -> None:
"""Prompt for an integer setting and store it on change.
Warns on non-numeric input; silently keeps the old value when the input
is out of range or unchanged.
"""
raw = Prompt.ask(f"[cyan]{prompt_label}[/cyan]", default=str(current))
try:
value = int(raw)
except ValueError:
console.print("[yellow]Invalid value, skipping...[/yellow]")
return
if min_val is not None and value < min_val:
return
if max_val is not None and value > max_val:
return
if value == current:
return
section[key] = value
console.print(f"[green][OK] {change_label} changed: {value}{unit}[/green]")
def _ask_bool_setting(section: dict, key: str, prompt_label: str, current: bool,
change_label: str) -> None:
"""Prompt for a true/false setting and report when it changes."""
answer = Prompt.ask(
f"[cyan]{prompt_label}[/cyan]",
choices=["true", "false"],
default=str(current).lower()
)
if answer != str(current).lower():
section[key] = (answer == "true")
console.print(f"[green][OK] {change_label} changed: {answer}[/green]")
def _ask_float_or_keep(section: dict, key: str, prompt_label: str, current: float) -> None:
"""Prompt for a float; keep the existing value if user provides invalid input."""
raw = Prompt.ask(f"[cyan]{prompt_label}[/cyan]", default=str(current))
try:
section[key] = float(raw)
except ValueError:
pass # Keep existing value if user provides invalid input
def _edit_llm_provider(config: dict) -> None:
"""Prompt for the LLM provider."""
current_provider = config.get("llm", {}).get("provider", "ollama")
console.print("\n[dim]Available Providers:[/dim]")
console.print("[dim] • ollama - Local models (free)[/dim]")
console.print("[dim] • openai - GPT-3.5, GPT-4 (API key required)[/dim]")
console.print("[dim] • anthropic - Claude 3 (API key required)[/dim]")
console.print("[dim] • groq - Mixtral, LLaMA (free with Free Tier)[/dim]")
new_provider = Prompt.ask(
"[cyan]LLM Provider[/cyan]",
choices=["ollama", "openai", "anthropic", "groq"],
default=current_provider
)
if new_provider == current_provider:
return
config["llm"]["provider"] = new_provider
console.print(f"[green][OK] Provider changed: {new_provider}[/green]")
# Show API key requirements for cloud providers
if new_provider in ["openai", "anthropic", "groq"]:
key_name = f"{new_provider.upper()}_API_KEY"
console.print(f"[yellow]⚠️ {new_provider.title()} requires an API key![/yellow]")
console.print(f"[dim]Set {key_name} in .env file[/dim]")
def _print_settings_model_suggestions(provider: str, config: dict) -> None:
"""Print provider-specific model suggestions for the settings editor."""
console.print()
_suggest_default_model(provider, config)
def _edit_llm_model(config: dict) -> None:
"""Prompt for the LLM model (with provider-specific suggestions)."""
current_model = config.get("llm", {}).get("model", "qwen2.5:3b")
provider = config.get("llm", {}).get("provider", "ollama")
_print_settings_model_suggestions(provider, config)
new_model = Prompt.ask("[cyan]LLM Model[/cyan]", default=current_model)
if not new_model or new_model == current_model:
return
if InputValidator.validate_model_name(new_model):
config["llm"]["model"] = new_model
console.print(f"[green][OK] Model changed: {new_model}[/green]")
else:
console.print("[red]❌ Invalid model name! Allowed: Letters, numbers, '.', ':', '-', '_'[/red]")
def _edit_llm_temperature(config: dict) -> None:
"""Prompt for the LLM temperature."""
current_temp = config.get("llm", {}).get("temperature", 0.7)
new_temp = Prompt.ask(
"[cyan]Temperature (0.0-1.0)[/cyan]",
default=str(current_temp)
)
temp_value = InputValidator.validate_float(new_temp, 0.0, 1.0)
if temp_value is not None and temp_value != current_temp:
config["llm"]["temperature"] = temp_value
console.print(f"[green][OK] Temperature changed: {temp_value}[/green]")
elif temp_value is None:
console.print("[red]❌ Invalid value! Temperature must be between 0.0 and 1.0.[/red]")
def _edit_llm_max_tokens(config: dict) -> None:
"""Prompt for the max tokens / context size."""
current_tokens = config.get("llm", {}).get("max_tokens", 10000)
new_tokens = Prompt.ask(
"[cyan]Max Tokens / Context Size (1000-32000)[/cyan]",
default=str(current_tokens)
)
tokens_value = InputValidator.validate_int(new_tokens, 1000, 32000)
if tokens_value is not None and tokens_value != current_tokens:
config["llm"]["max_tokens"] = tokens_value
console.print(f"[green][OK] Max Tokens changed: {tokens_value}[/green]")
console.print("[dim]Recommendation: RTX 3080+ → 10k-16k, RTX 3060/70 → 6k-8k, CPU → 2k-4k[/dim]")
elif tokens_value is None:
console.print("[red]❌ Invalid value! Max Tokens must be between 1000 and 32000.[/red]")
def _edit_llm_settings(config: dict) -> None:
"""Edit all LLM settings interactively."""
console.print("\n[bold cyan]=== LLM Settings ===[/bold cyan]")
_edit_llm_provider(config)
_edit_llm_model(config)
_edit_llm_temperature(config)
_edit_llm_max_tokens(config)
def _edit_search_settings(config: dict) -> None:
"""Edit search settings interactively."""
console.print("\n[bold cyan]=== Search Settings ===[/bold cyan]")
# Max Results
current_max = config.get("search", {}).get("max_results", 10)
new_max = Prompt.ask(
"[cyan]Max Search Results (1-100)[/cyan]",
default=str(current_max)
)
max_value = InputValidator.validate_int(new_max, 1, 100)
if max_value is not None and max_value != current_max:
config["search"]["max_results"] = max_value
console.print(f"[green][OK] Max Results changed: {max_value}[/green]")
elif max_value is None:
console.print("[red]❌ Invalid value! Max Results must be between 1 and 100.[/red]")
# Region
current_region = config.get("search", {}).get("region", "de-de")
new_region = Prompt.ask(
"[cyan]Search Region[/cyan]",
choices=["de-de", "us-en", "wt-wt", "gb-en", "fr-fr"],
default=current_region
)
if new_region and new_region != current_region:
config["search"]["region"] = new_region
console.print(f"[green][OK] Region changed: {new_region}[/green]")
def _edit_rag_settings(config: dict) -> None:
"""Edit RAG settings interactively."""
console.print("\n[bold cyan]=== RAG Settings ===[/bold cyan]")
# Ensure rag config exists
if "rag" not in config:
config["rag"] = {
"enabled": True,
"embedding_model": "nomic-embed-text",
"top_k": 5
}
# RAG Enabled
current_rag = config.get("rag", {}).get("enabled", True)
rag_choice = Prompt.ask(
"[cyan]Enable RAG? (y/n)[/cyan]",
default="y" if current_rag else "n",
choices=["y", "n"]
)
new_rag = rag_choice.lower() == "y"
if new_rag != current_rag:
config["rag"]["enabled"] = new_rag
console.print(f"[green][OK] RAG {'enabled' if new_rag else 'disabled'}[/green]")
# Embedding Model
current_model = config.get("rag", {}).get("embedding_model", "nomic-embed-text")
new_model = Prompt.ask(
"[cyan]Embedding Model[/cyan]",
default=current_model
)
if new_model != current_model:
config["rag"]["embedding_model"] = new_model
console.print(f"[green][OK] Embedding Model changed: {new_model}[/green]")
# Top K
current_topk = config.get("rag", {}).get("top_k", 5)
new_topk = Prompt.ask(
"[cyan]Top K (Number of RAG documents, 1-20)[/cyan]",
default=str(current_topk)
)
topk_value = InputValidator.validate_int(new_topk, 1, 20)
if topk_value is not None and topk_value != current_topk:
config["rag"]["top_k"] = topk_value
console.print(f"[green][OK] Top K changed: {topk_value}[/green]")
elif topk_value is None:
console.print("[red]❌ Invalid value! Top K must be between 1 and 20.[/red]")
def _edit_cache_settings(config: dict) -> None:
"""Edit cache settings interactively."""
console.print("\n[bold cyan]=== Cache Settings ===[/bold cyan]")
# Cache Enabled
current_cache = config.get("cache", {}).get("enabled", True)
cache_choice = Prompt.ask(
"[cyan]Enable cache? (y/n)[/cyan]",
default="y" if current_cache else "n",
choices=["y", "n"]
)
new_cache = cache_choice.lower() == "y"
if new_cache != current_cache:
config["cache"]["enabled"] = new_cache
console.print(f"[green][OK] Cache {'enabled' if new_cache else 'disabled'}[/green]")
def _edit_osint_settings(config: dict) -> None:
"""Edit OSINT settings interactively."""
console.print("\n[bold cyan]=== OSINT Settings ===[/bold cyan]")
# Ensure osint config exists
if "osint" not in config:
config["osint"] = {
"max_results": 20,
"email_search_limit": 50,
"phone_search_limit": 50,
"general_osint_limit": 100
}
osint = config["osint"]
_ask_int_setting(osint, "max_results", "OSINT Max Results (1-50)",
osint.get("max_results", 20), "OSINT Max Results",
min_val=1, max_val=50)
_ask_int_setting(osint, "email_search_limit", "Email Search Limit per hour",
osint.get("email_search_limit", 50), "Email Search Limit")
_ask_int_setting(osint, "phone_search_limit", "Phone Search Limit per hour",
osint.get("phone_search_limit", 50), "Phone Search Limit")
_ask_int_setting(osint, "general_osint_limit", "General OSINT Limit per hour",
osint.get("general_osint_limit", 100), "General OSINT Limit")
# Safesearch Mode
current_safesearch = osint.get("safesearch", "strict")
console.print("\n[dim]Safesearch improves search result quality for OSINT investigations[/dim]")
console.print("[dim] • off: No filtering[/dim]")
console.print("[dim] • moderate: Moderate filtering (default DuckDuckGo)[/dim]")
console.print("[dim] • strict: Strict filtering (recommended for best quality)[/dim]")
new_safesearch = Prompt.ask(
"[cyan]Safesearch Mode[/cyan]",
choices=["off", "moderate", "strict"],
default=current_safesearch
)
if new_safesearch and new_safesearch != current_safesearch:
osint["safesearch"] = new_safesearch
console.print(f"[green][OK] Safesearch Mode changed: {new_safesearch}[/green]")
def _edit_memory_settings(config: dict) -> None:
"""Edit memory store settings interactively."""
console.print("\n[bold cyan]=== Memory Store Settings ===[/bold cyan]")
# Ensure memory config exists
if "memory" not in config:
config["memory"] = {
"enabled": True,
"auto_clear_on_clear": False,
"max_entries": 1000,
"max_file_size_mb": 10,
"file_path": "data/memory.json"
}
memory = config["memory"]
_ask_bool_setting(memory, "enabled", "Memory Store Enabled (true/false)",
memory.get("enabled", True), "Memory Store Enabled")
console.print("\n[dim]Auto Clear on Clear: Clears Memory Store on 'clear' command[/dim]")
console.print("[dim] • false: Memory persists (recommended for persistent data)[/dim]")
console.print("[dim] • true: Memory is cleared[/dim]")
_ask_bool_setting(memory, "auto_clear_on_clear", "Auto Clear on Clear (true/false)",
memory.get("auto_clear_on_clear", False), "Auto Clear on Clear")
_ask_int_setting(memory, "max_entries", "Max Entries (100-10000)",
memory.get("max_entries", 1000), "Max Entries",
min_val=100, max_val=10000)
_ask_int_setting(memory, "max_file_size_mb", "Max File Size in MB (1-100)",
memory.get("max_file_size_mb", 10), "Max File Size",
min_val=1, max_val=100, unit=" MB")
def _edit_hallucination_settings(config: dict) -> None:
"""Edit hallucination detection settings interactively."""
console.print("\n[bold cyan]=== Hallucination Detection Settings ===[/bold cyan]")
hallu_config = config.get("hallucination_detection", {})
# Enabled
new_enabled = Prompt.ask(
"[cyan]Detection Enabled (true/false)[/cyan]",
choices=["true", "false"],
default=str(hallu_config.get("enabled", False)).lower()
)
hallu_config["enabled"] = (new_enabled == "true")
# Detection Level
hallu_config["detection_level"] = Prompt.ask(
"[cyan]Detection Level (low/medium/high)[/cyan]",
choices=["low", "medium", "high"],
default=hallu_config.get("detection_level", "medium")
)
# Warning Mode
hallu_config["warning_mode"] = Prompt.ask(
"[cyan]Warning Mode (silent/log/flag_response/block)[/cyan]",
choices=["silent", "log", "flag_response", "block"],
default=hallu_config.get("warning_mode", "flag_response")
)
# Thresholds
_ask_float_or_keep(hallu_config, "hallucination_threshold",
"Hallucination Threshold (0.0-1.0)",
hallu_config.get("hallucination_threshold", 0.7))
_ask_float_or_keep(hallu_config, "context_alignment_threshold",
"Context Alignment Threshold (0.0-1.0)",
hallu_config.get("context_alignment_threshold", 0.4))
# Fact Checking
new_fact = Prompt.ask(
"[cyan]Fact Checking Enabled (true/false)[/cyan]",
choices=["true", "false"],
default=str(hallu_config.get("fact_checking_enabled", True)).lower()
)
hallu_config["fact_checking_enabled"] = (new_fact == "true")
# Max Processing Time
_ask_float_or_keep(hallu_config, "max_processing_time",
"Max Processing Time (seconds)",
hallu_config.get("max_processing_time", 10.0))
config["hallucination_detection"] = hallu_config
def _edit_ui_settings(config: dict) -> None:
"""Edit UI display settings interactively."""
console.print("\n[bold cyan]=== UI Display Settings ===[/bold cyan]")
# Ensure UI config exists
if "ui" not in config:
config["ui"] = {
"show_adaptive_report": True
}
# Show Adaptive Report
current_show_report = config.get("ui", {}).get("show_adaptive_report", True)
console.print("\n[dim]Adaptive Intelligence Report: Shows details after each query[/dim]")
console.print("[dim] • Complexity level (LOW/MID/HIGH)[/dim]")
console.print("[dim] • Selected Agent (SearchAgent/MultiHopReasoningAgent)[/dim]")
console.print("[dim] • Reasoning for agent selection[/dim]")
console.print("[dim] • Confidence score[/dim]")
console.print("[dim] • Processing time and attempts[/dim]")
new_show_report = Prompt.ask(
"[cyan]Show Adaptive Intelligence Report (y/n)[/cyan]",
choices=["y", "n"],
default="y" if current_show_report else "n"
)
if new_show_report != ("y" if current_show_report else "n"):
config["ui"]["show_adaptive_report"] = (new_show_report == "y")
console.print(f"[green][OK] Adaptive Report {'enabled' if new_show_report == 'y' else 'disabled'}[/green]")
def edit_settings(config: dict) -> dict:
"""
Interactive settings editor.
Args:
config: Current configuration dictionary
Returns:
Updated configuration dictionary
"""
console.print("\n[bold cyan]Settings Editor[/bold cyan]")
console.print("[dim]Select the category you want to change[/dim]\n")
all_categories = ["llm", "search", "rag", "cache", "osint", "memory", "hallucination", "ui"]
# Category selection
category_choice = Prompt.ask(
"[cyan]Which category do you want to change?[/cyan]",
choices=all_categories + ["all"],
default="all"
)
categories = all_categories if category_choice == "all" else [category_choice]
editors = {
"llm": _edit_llm_settings,
"search": _edit_search_settings,
"rag": _edit_rag_settings,
"cache": _edit_cache_settings,
"osint": _edit_osint_settings,
"memory": _edit_memory_settings,
"hallucination": _edit_hallucination_settings,
"ui": _edit_ui_settings,
}
for category in categories:
editors[category](config)
return config
# ---------------------------------------------------------------------------
# Query routing helpers (shared by interactive and direct query mode)
# ---------------------------------------------------------------------------
def _is_osint_query(agent: SearchAgent, query: str) -> bool:
"""Check whether the query uses OSINT operators or has OSINT intent."""
return has_osint_operators(query) or agent.tools_flow.check_company_osint_intent(query)
def _is_result_reference(query: str) -> bool:
"""Check whether the query references a numbered search result."""
return bool(QUICK_RESULT_REFERENCE_PATTERN.search(query.lower()))
def _direct_search_result(answer: str, complexity: str, reasoning: str) -> dict:
"""Build a result dict for queries that bypassed adaptive routing."""
return {
"answer": answer,