-
Notifications
You must be signed in to change notification settings - Fork 243
/
research_manager.py
1481 lines (1220 loc) · 58.2 KB
/
research_manager.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
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
import os
import sys
import threading
import time
import re
import json
import logging
import curses
import signal
from typing import List, Dict, Set, Optional, Tuple, Union
from dataclasses import dataclass
from queue import Queue
from datetime import datetime
from io import StringIO
from colorama import init, Fore, Style
import select
import termios
import tty
from threading import Event
from urllib.parse import urlparse
from pathlib import Path
# Initialize colorama for cross-platform color support
if os.name == 'nt': # Windows-specific initialization
init(convert=True, strip=False, wrap=True)
else:
init()
# Set up logging
log_directory = 'logs'
if not os.path.exists(log_directory):
os.makedirs(log_directory)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
log_file = os.path.join(log_directory, 'research_llm.log')
file_handler = logging.FileHandler(log_file)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
logger.handlers = []
logger.addHandler(file_handler)
logger.propagate = False
# Suppress other loggers
for name in logging.root.manager.loggerDict:
if name != __name__:
logging.getLogger(name).disabled = True
@dataclass
class ResearchFocus:
"""Represents a specific area of research focus"""
area: str
priority: int
source_query: str = ""
timestamp: str = ""
search_queries: List[str] = None
def __post_init__(self):
if not self.timestamp:
self.timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if self.search_queries is None:
self.search_queries = []
@dataclass
class AnalysisResult:
"""Contains the complete analysis result"""
original_question: str
focus_areas: List[ResearchFocus]
raw_response: str
timestamp: str = ""
def __post_init__(self):
if not self.timestamp:
self.timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
class StrategicAnalysisParser:
def __init__(self, llm=None):
self.llm = llm
self.logger = logging.getLogger(__name__)
# Simplify patterns to match exactly what we expect
self.patterns = {
'priority': [
r"Priority:\s*(\d+)", # Match exactly what's in our prompt
]
}
def strategic_analysis(self, original_query: str) -> Optional[AnalysisResult]:
"""Generate and process research areas with retries until success"""
max_retries = 3
try:
self.logger.info("Starting strategic analysis...")
prompt = f"""
You must select exactly 5 areas to investigate in order to explore and gather information to answer the research question:
"{original_query}"
You MUST provide exactly 5 areas numbered 1-5. Each must have a priority, YOU MUST ensure that you only assign one priority per area.
Assign priority based on the likelihood of a focus area being investigated to provide information that directly will allow you to respond to "{original_query}" with 5 being most likely and 1 being least.
Follow this EXACT format without any deviations or additional text:
1. [First research topic]
Priority: [number 1-5]
2. [Second research topic]
Priority: [number 1-5]
3. [Third research topic]
Priority: [number 1-5]
4. [Fourth research topic]
Priority: [number 1-5]
5. [Fifth research topic]
Priority: [number 1-5]
"""
for attempt in range(max_retries):
response = self.llm.generate(prompt, max_tokens=1000)
focus_areas = self._extract_research_areas(response)
if focus_areas: # If we got any valid areas
# Sort by priority (highest first)
focus_areas.sort(key=lambda x: x.priority, reverse=True)
return AnalysisResult(
original_question=original_query,
focus_areas=focus_areas,
raw_response=response,
timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
)
else:
self.logger.warning(f"Attempt {attempt + 1}: No valid areas generated, retrying...")
print(f"\nRetrying research area generation (Attempt {attempt + 1}/{max_retries})...")
# If all retries failed, try one final time with a stronger prompt
prompt += "\n\nIMPORTANT: You MUST provide exactly 5 research areas with priorities. This is crucial."
response = self.llm.generate(prompt, max_tokens=1000)
focus_areas = self._extract_research_areas(response)
if focus_areas:
focus_areas.sort(key=lambda x: x.priority, reverse=True)
return AnalysisResult(
original_question=original_query,
focus_areas=focus_areas,
raw_response=response,
timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
)
self.logger.error("Failed to generate any valid research areas after all attempts")
return None
except Exception as e:
self.logger.error(f"Error in strategic analysis: {str(e)}")
return None
def _extract_research_areas(self, text: str) -> List[ResearchFocus]:
"""Extract research areas with enhanced parsing to handle priorities in various formats."""
areas = []
lines = text.strip().split('\n')
current_area = None
current_priority = None
for i in range(len(lines)):
line = lines[i].strip()
if not line:
continue
# Check for numbered items (e.g., '1. Area Name')
number_match = re.match(r'^(\d+)\.\s*(.*)', line)
if number_match:
# If we have a previous area, add it to our list
if current_area is not None:
areas.append(ResearchFocus(
area=current_area.strip(' -:'),
priority=current_priority or 3,
))
# Start a new area
area_line = number_match.group(2)
# Search for 'priority' followed by a number, anywhere in the area_line
priority_inline_match = re.search(
r'(?i)\bpriority\b\s*(?:[:=]?\s*)?(\d+)', area_line)
if priority_inline_match:
# Extract and set the priority
try:
current_priority = int(priority_inline_match.group(1))
current_priority = max(1, min(5, current_priority))
except ValueError:
current_priority = 3 # Default priority if parsing fails
# Remove the 'priority' portion from area_line
area_line = area_line[:priority_inline_match.start()] + area_line[priority_inline_match.end():]
area_line = area_line.strip(' -:')
else:
current_priority = None # Priority might be on the next line
current_area = area_line.strip()
elif re.match(r'(?i)^priority\s*(?:[:=]?\s*)?(\d+)', line):
# Extract priority from the line following the area
try:
priority_match = re.match(r'(?i)^priority\s*(?:[:=]?\s*)?(\d+)', line)
current_priority = int(priority_match.group(1))
current_priority = max(1, min(5, current_priority))
except (ValueError, IndexError):
current_priority = 3 # Default priority if parsing fails
# Check if this is the last line or the next line is a new area
next_line_is_new_area = (i + 1 < len(lines)) and re.match(r'^\d+\.', lines[i + 1].strip())
if next_line_is_new_area or i + 1 == len(lines):
if current_area is not None:
# Append the current area and priority to the list
areas.append(ResearchFocus(
area=current_area.strip(' -:'),
priority=current_priority or 3,
))
current_area = None
current_priority = None
return areas
def _clean_text(self, text: str) -> str:
"""Clean and normalize text"""
text = re.sub(r'\s+', ' ', text)
text = re.sub(r'(\d+\))', r'\1.', text)
text = re.sub(r'(?i)priority:', 'P:', text)
return text.strip()
def _add_area(self, areas: List[ResearchFocus], area: str, priority: Optional[int]):
"""Add area with basic validation"""
if not area or len(area.split()) < 3: # Basic validation
return
areas.append(ResearchFocus(
area=area,
priority=priority or 3,
timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
search_queries=[]
))
def _normalize_focus_areas(self, areas: List[ResearchFocus]) -> List[ResearchFocus]:
"""Normalize and prepare final list of areas"""
if not areas:
return []
# Sort by priority
areas.sort(key=lambda x: x.priority, reverse=True)
# Ensure priorities are properly spread
for i, area in enumerate(areas):
area.priority = max(1, min(5, area.priority))
return areas[:5]
def format_analysis_result(self, result: AnalysisResult) -> str:
"""Format the results for display"""
if not result:
return "No valid analysis result generated."
formatted = [
f"\nResearch Areas for: {result.original_question}\n"
]
for i, focus in enumerate(result.focus_areas, 1):
formatted.extend([
f"\n{i}. {focus.area}",
f" Priority: {focus.priority}"
])
return "\n".join(formatted)
class OutputRedirector:
"""Redirects stdout and stderr to a string buffer"""
def __init__(self, stream=None):
self.stream = stream or StringIO()
self.original_stdout = sys.stdout
self.original_stderr = sys.stderr
def __enter__(self):
sys.stdout = self.stream
sys.stderr = self.stream
return self.stream
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout = self.original_stdout
sys.stderr = self.original_stderr
class TerminalUI:
"""Manages terminal display with fixed input area at bottom"""
def __init__(self):
self.stdscr = None
self.input_win = None
self.output_win = None
self.status_win = None
self.max_y = 0
self.max_x = 0
self.input_buffer = ""
self.is_setup = False
self.old_terminal_settings = None
self.should_terminate = Event()
self.shutdown_event = Event()
self.research_thread = None
self.last_display_height = 0 # Track display height for corruption fix
def setup(self):
"""Initialize the terminal UI"""
if self.is_setup:
return
# Save terminal settings
if not os.name == 'nt': # Unix-like systems
self.old_terminal_settings = termios.tcgetattr(sys.stdin.fileno())
self.stdscr = curses.initscr()
curses.start_color()
curses.noecho()
curses.cbreak()
self.stdscr.keypad(True)
# Enable only scroll wheel events, not all mouse events
# curses.mousemask(curses.BUTTON4_PRESSED | curses.BUTTON5_PRESSED)
# Remove this line that was causing the spam
# print('\033[?1003h') # We don't want mouse movement events
# Get terminal dimensions
self.max_y, self.max_x = self.stdscr.getmaxyx()
# Create windows
self.output_win = curses.newwin(self.max_y - 4, self.max_x, 0, 0)
self.status_win = curses.newwin(1, self.max_x, self.max_y - 4, 0)
self.input_win = curses.newwin(3, self.max_x, self.max_y - 3, 0)
# Setup colors
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)
# Enable scrolling
self.output_win.scrollok(True)
self.output_win.idlok(True)
self.input_win.scrollok(True)
self.is_setup = True
self._refresh_input_prompt()
def cleanup(self):
"""Public cleanup method with enhanced terminal restoration"""
if not self.is_setup:
return
try:
# Ensure all windows are properly closed
for win in [self.input_win, self.output_win, self.status_win]:
if win:
win.clear()
win.refresh()
# Restore terminal state
if self.stdscr:
self.stdscr.keypad(False)
curses.nocbreak()
curses.echo()
curses.endwin()
# Restore original terminal settings
if self.old_terminal_settings and not os.name == 'nt':
termios.tcsetattr(
sys.stdin.fileno(),
termios.TCSADRAIN,
self.old_terminal_settings
)
except Exception as e:
logger.error(f"Error during terminal cleanup: {str(e)}")
finally:
self.is_setup = False
self.stdscr = None
self.input_win = None
self.output_win = None
self.status_win = None
def _cleanup(self):
"""Enhanced resource cleanup with better process handling"""
self.should_terminate.set()
# Handle research thread with improved termination
if self.research_thread and self.research_thread.is_alive():
try:
self.research_thread.join(timeout=1.0)
if self.research_thread.is_alive():
import ctypes
ctypes.pythonapi.PyThreadState_SetAsyncExc(
ctypes.c_long(self.research_thread.ident),
ctypes.py_object(SystemExit))
time.sleep(0.1) # Give thread time to exit
if self.research_thread.is_alive(): # Double-check
ctypes.pythonapi.PyThreadState_SetAsyncExc(
ctypes.c_long(self.research_thread.ident),
0) # Reset exception
except Exception as e:
logger.error(f"Error terminating research thread: {str(e)}")
# Clean up LLM with improved error handling
if hasattr(self, 'llm') and hasattr(self.llm, '_cleanup'):
try:
self.llm.cleanup()
except Exception as e:
logger.error(f"Error cleaning up LLM: {str(e)}")
# Ensure terminal is restored
try:
curses.endwin()
except:
pass
# Final cleanup of UI
self.cleanup()
def _refresh_input_prompt(self, prompt="Enter command: "):
"""Refresh the fixed input prompt at bottom with display fix"""
if not self.is_setup:
return
try:
# Clear the entire input window first
self.input_win.clear()
# Calculate proper cursor position
cursor_y = 0
cursor_x = len(prompt) + len(self.input_buffer)
# Add the prompt and buffer
self.input_win.addstr(0, 0, f"{prompt}{self.input_buffer}", curses.color_pair(1))
# Position cursor correctly
try:
self.input_win.move(cursor_y, cursor_x)
except curses.error:
pass # Ignore if cursor would be off-screen
self.input_win.refresh()
except curses.error:
pass
def update_output(self, text: str):
"""Update output window with display corruption fix"""
if not self.is_setup:
return
try:
# Clean ANSI escape codes
clean_text = re.sub(r'\x1b\[[0-9;]*[mK]', '', text)
# Store current position
current_y, _ = self.output_win.getyx()
# Clear any potential corruption
if current_y > self.last_display_height:
self.output_win.clear()
self.output_win.addstr(clean_text + "\n", curses.color_pair(2))
new_y, _ = self.output_win.getyx()
self.last_display_height = new_y
self.output_win.refresh()
self._refresh_input_prompt()
except curses.error:
pass
def update_status(self, text: str):
"""Update the status line above input area"""
if not self.is_setup:
return
try:
self.status_win.clear()
self.status_win.addstr(0, 0, text, curses.color_pair(3))
self.status_win.refresh()
self._refresh_input_prompt() # Ensure prompt is refreshed after status update
except curses.error:
pass
def get_input(self, prompt: Optional[str] = None) -> Optional[str]:
"""Enhanced input handling with mouse scroll support"""
try:
if prompt:
self.update_status(prompt)
if not self.is_setup:
self.setup()
self.input_buffer = ""
self._refresh_input_prompt()
while True:
if self.should_terminate.is_set():
return None
try:
ch = self.input_win.getch()
if ch == curses.KEY_MOUSE:
try:
mouse_event = curses.getmouse()
# Ignore mouse events entirely for now
continue
except curses.error:
continue
if ch == 4: # Ctrl+D
result = self.input_buffer.strip()
self.input_buffer = ""
if not result:
self.cleanup()
return "@quit"
return result
elif ch == 3: # Ctrl+C
self.should_terminate.set()
self.cleanup()
return "@quit"
elif ch == ord('\n'): # Enter
result = self.input_buffer.strip()
if result:
self.input_buffer = ""
return result
continue
elif ch == curses.KEY_BACKSPACE or ch == 127: # Backspace
if self.input_buffer:
self.input_buffer = self.input_buffer[:-1]
self._refresh_input_prompt()
elif 32 <= ch <= 126: # Printable characters
self.input_buffer += chr(ch)
self._refresh_input_prompt()
except KeyboardInterrupt:
self.should_terminate.set()
self.cleanup()
return "@quit"
except curses.error:
self._refresh_input_prompt()
except Exception as e:
logger.error(f"Error in get_input: {str(e)}")
self.should_terminate.set()
self.cleanup()
return "@quit"
def force_exit(self):
"""Force immediate exit with enhanced cleanup"""
try:
self.should_terminate.set()
self.shutdown_event.set()
self._cleanup() # Call private cleanup first
self.cleanup() # Then public cleanup
curses.endwin() # Final attempt to restore terminal
except:
pass
finally:
os._exit(0) # Ensure exit
class NonBlockingInput:
"""Handles non-blocking keyboard input for Unix-like systems"""
def __init__(self):
self.old_settings = None
def __enter__(self):
if os.name == 'nt': # Windows
return self
self.old_settings = termios.tcgetattr(sys.stdin)
tty.setcbreak(sys.stdin.fileno())
return self
def __exit__(self, type, value, traceback):
if os.name != 'nt': # Unix-like
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings)
def check_input(self, timeout=0.1):
"""Check for input without blocking, cross-platform"""
if os.name == 'nt': # Windows
import msvcrt
if msvcrt.kbhit():
return msvcrt.getch().decode('utf-8')
return None
else: # Unix-like
ready_to_read, _, _ = select.select([sys.stdin], [], [], timeout)
if ready_to_read:
return sys.stdin.read(1)
return None
class ResearchManager:
"""Manages the research process including analysis, search, and documentation"""
def __init__(self, llm_wrapper, parser, search_engine, max_searches_per_cycle: int = 5):
self.llm = llm_wrapper
self.parser = parser
self.search_engine = search_engine
self.max_searches = max_searches_per_cycle
self.should_terminate = threading.Event()
self.shutdown_event = Event()
self.research_started = threading.Event()
self.research_thread = None
self.thinking = False
self.stop_words = {
'the', 'be', 'to', 'of', 'and', 'a', 'in', 'that', 'have', 'i',
'it', 'for', 'not', 'on', 'with', 'he', 'as', 'you', 'do', 'at'
}
# State tracking
self.searched_urls: Set[str] = set()
self.current_focus: Optional[ResearchFocus] = None
self.original_query: str = ""
self.focus_areas: List[ResearchFocus] = []
self.is_running = False
# New conversation mode attributes
self.research_complete = False
self.research_summary = ""
self.conversation_active = False
self.research_content = ""
# Initialize document paths
self.document_path = None
self.session_files = []
# Initialize UI and parser
self.ui = TerminalUI()
self.strategic_parser = StrategicAnalysisParser(llm=self.llm)
# Initialize new flags for pausing and assessment
self.research_paused = False
self.awaiting_user_decision = False
# Setup signal handlers
signal.signal(signal.SIGINT, self._signal_handler)
signal.signal(signal.SIGTERM, self._signal_handler)
def _signal_handler(self, signum, frame):
"""Handle interrupt signals"""
self.shutdown_event.set()
self.should_terminate.set()
self._cleanup()
def print_thinking(self):
"""Display thinking indicator to user"""
self.ui.update_output("🧠 Thinking...")
@staticmethod
def get_initial_input() -> str:
"""Get the initial research query from user"""
print(f"{Fore.GREEN}📝 Enter your message (Press CTRL+D to submit):{Style.RESET_ALL}")
lines = []
try:
while True:
line = input()
if line: # Only add non-empty lines
lines.append(line)
if not line: # Empty line (just Enter pressed)
break
except EOFError: # Ctrl+D pressed
pass
except KeyboardInterrupt: # Ctrl+C pressed
print("\nOperation cancelled")
sys.exit(0)
return " ".join(lines).strip()
def formulate_search_queries(self, focus_area: ResearchFocus) -> List[str]:
"""Generate search queries for a focus area"""
try:
self.print_thinking()
prompt = f"""
In order to research this query/topic:
Context: {self.original_query}
Base a search query to investigate the following research focus, which is related to the original query/topic:
Area: {focus_area.area}
Create a search query that will yield specific, search results thare are directly relevant to your focus area.
Format your response EXACTLY like this:
Search query: [Your 2-5 word query]
Time range: [d/w/m/y/none]
Do not provide any additional information or explanation, note that the time range allows you to see results within a time range (d is within the last day, w is within the last week, m is within the last month, y is within the last year, and none is results from anytime, only select one, using only the corresponding letter for whichever of these options you select as indicated in the response format) use your judgement as many searches will not require a time range and some may depending on what the research focus is.
"""
response_text = self.llm.generate(prompt, max_tokens=50, stop=None)
query, time_range = self.parse_query_response(response_text)
if not query:
self.ui.update_output(f"{Fore.RED}Error: Empty search query. Using focus area as query...{Style.RESET_ALL}")
return [focus_area.area]
self.ui.update_output(f"{Fore.YELLOW}Original focus: {focus_area.area}{Style.RESET_ALL}")
self.ui.update_output(f"{Fore.YELLOW}Formulated query: {query}{Style.RESET_ALL}")
self.ui.update_output(f"{Fore.YELLOW}Time range: {time_range}{Style.RESET_ALL}")
return [query]
except Exception as e:
logger.error(f"Error formulating query: {str(e)}")
return [focus_area.area]
def parse_search_query(self, query_response: str) -> Dict[str, str]:
"""Parse search query formulation response with improved time range detection"""
try:
lines = query_response.strip().split('\n')
result = {
'query': '',
'time_range': 'none'
}
# First try to find standard format
for line in lines:
if ':' in line:
key, value = line.split(':', 1)
key = key.strip().lower()
value = value.strip()
if 'query' in key:
result['query'] = self._clean_query(value)
elif ('time' in key or 'range' in key) and value.strip().lower() in ['d', 'w', 'm', 'y', 'none']:
result['time_range'] = value.strip().lower()
# If no time range found, look for individual characters
if result['time_range'] == 'none':
# Get all text except the query itself
full_text = query_response.lower()
if result['query']:
full_text = full_text.replace(result['query'].lower(), '')
# Look for isolated d, w, m, or y characters
time_chars = set()
for char in ['d', 'w', 'm', 'y']:
# Check if char exists by itself (not part of another word)
matches = re.finditer(r'\b' + char + r'\b', full_text)
for match in matches:
# Verify it's not part of a word
start, end = match.span()
if (start == 0 or not full_text[start-1].isalpha()) and \
(end == len(full_text) or not full_text[end].isalpha()):
time_chars.add(char)
# If exactly one time char found, use it
if len(time_chars) == 1:
result['time_range'] = time_chars.pop()
return result
except Exception as e:
logger.error(f"Error parsing search query: {str(e)}")
return {'query': '', 'time_range': 'none'}
def _cleanup(self):
"""Enhanced cleanup to handle conversation mode"""
self.conversation_active = False
self.should_terminate.set()
if self.research_thread and self.research_thread.is_alive():
try:
self.research_thread.join(timeout=1.0)
if self.research_thread.is_alive():
import ctypes
ctypes.pythonapi.PyThreadState_SetAsyncExc(
ctypes.c_long(self.research_thread.ident),
ctypes.py_object(SystemExit)
)
except Exception as e:
logger.error(f"Error terminating research thread: {str(e)}")
if hasattr(self.llm, 'cleanup'):
try:
self.llm.cleanup()
except Exception as e:
logger.error(f"Error cleaning up LLM: {str(e)}")
if hasattr(self.ui, 'cleanup'):
self.ui.cleanup()
def _initialize_document(self):
"""Initialize research session document"""
try:
# Get all existing research session files
self.session_files = []
for file in os.listdir():
if file.startswith("research_session_") and file.endswith(".txt"):
try:
num = int(file.split("_")[2].split(".")[0])
self.session_files.append(num)
except ValueError:
continue
# Determine next session number
next_session = 1 if not self.session_files else max(self.session_files) + 1
self.document_path = f"research_session_{next_session}.txt"
# Initialize the new document
with open(self.document_path, 'w', encoding='utf-8') as f:
f.write(f"Research Session {next_session}\n")
f.write(f"Topic: {self.original_query}\n")
f.write(f"Started: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write("="*80 + "\n\n")
f.flush()
except Exception as e:
logger.error(f"Error initializing document: {str(e)}")
self.document_path = "research_findings.txt"
with open(self.document_path, 'w', encoding='utf-8') as f:
f.write("Research Findings:\n\n")
f.flush()
def add_to_document(self, content: str, source_url: str, focus_area: str):
"""Add research findings to current session document"""
try:
with open(self.document_path, 'a', encoding='utf-8') as f:
if source_url not in self.searched_urls:
f.write(f"\n{'='*80}\n")
f.write(f"Research Focus: {focus_area}\n")
f.write(f"Source: {source_url}\n")
f.write(f"Content:\n{content}\n")
f.write(f"{'='*80}\n")
f.flush()
self.searched_urls.add(source_url)
self.ui.update_output(f"Added content from: {source_url}")
except Exception as e:
logger.error(f"Error adding to document: {str(e)}")
self.ui.update_output(f"Error saving content: {str(e)}")
def _process_search_results(self, results: Dict[str, str], focus_area: str):
"""Process and store search results"""
if not results:
return
for url, content in results.items():
if url not in self.searched_urls:
self.add_to_document(content, url, focus_area)
def _research_loop(self):
"""Main research loop with comprehensive functionality"""
self.is_running = True
try:
self.research_started.set()
while not self.should_terminate.is_set() and not self.shutdown_event.is_set():
# Check if research is paused
if self.research_paused:
time.sleep(1)
continue
self.ui.update_output("\nAnalyzing research progress...")
# Generate focus areas
self.ui.update_output("\nGenerating research focus areas...")
analysis_result = self.strategic_parser.strategic_analysis(self.original_query)
if not analysis_result:
self.ui.update_output("\nFailed to generate analysis result. Retrying...")
continue
focus_areas = analysis_result.focus_areas
if not focus_areas:
self.ui.update_output("\nNo valid focus areas generated. Retrying...")
continue
self.ui.update_output(f"\nGenerated {len(focus_areas)} research areas:")
for i, focus in enumerate(focus_areas, 1):
self.ui.update_output(f"\nArea {i}: {focus.area}")
self.ui.update_output(f"Priority: {focus.priority}")
# Process each focus area in priority order
for focus_area in focus_areas:
if self.should_terminate.is_set():
break
# Check if research is paused
while self.research_paused and not self.should_terminate.is_set():
time.sleep(1)
if self.should_terminate.is_set():
break
self.current_focus = focus_area
self.ui.update_output(f"\nInvestigating: {focus_area.area}")
queries = self.formulate_search_queries(focus_area)
if not queries:
continue
for query in queries:
if self.should_terminate.is_set():
break
# Check if research is paused
while self.research_paused and not self.should_terminate.is_set():
time.sleep(1)
if self.should_terminate.is_set():
break
try:
self.ui.update_output(f"\nSearching: {query}")
results = self.search_engine.perform_search(query, time_range='none')
if results:
# self.search_engine.display_search_results(results)
selected_urls = self.search_engine.select_relevant_pages(results, query)
if selected_urls:
self.ui.update_output("\n⚙️ Scraping selected pages...")
scraped_content = self.search_engine.scrape_content(selected_urls)
if scraped_content:
for url, content in scraped_content.items():
if url not in self.searched_urls:
self.add_to_document(content, url, focus_area.area)
except Exception as e:
logger.error(f"Error in search: {str(e)}")
self.ui.update_output(f"Error during search: {str(e)}")
if self.check_document_size():
self.ui.update_output("\nDocument size limit reached. Finalizing research.")
return
# After processing all areas, cycle back to generate new ones
self.ui.update_output("\nAll current focus areas investigated. Generating new areas...")
except Exception as e:
logger.error(f"Error in research loop: {str(e)}")
self.ui.update_output(f"Error in research process: {str(e)}")
finally:
self.is_running = False
def start_research(self, topic: str):
"""Start research with new session document"""
try:
self.ui.setup()
self.original_query = topic
self._initialize_document()
self.ui.update_output(f"Starting research on: {topic}")
self.ui.update_output(f"Session document: {self.document_path}")
self.ui.update_output("\nCommands available during research:")
self.ui.update_output("'s' = Show status")
self.ui.update_output("'f' = Show current focus")
self.ui.update_output("'p' = Pause and assess the research progress") # New command
self.ui.update_output("'q' = Quit research\n")
# Reset events
self.should_terminate.clear()
self.research_started.clear()
self.research_paused = False # Ensure research is not paused at the start
self.awaiting_user_decision = False
# Start research thread
self.research_thread = threading.Thread(target=self._research_loop, daemon=True)
self.research_thread.start()
# Wait for research to actually start
if not self.research_started.wait(timeout=10):
self.ui.update_output("Error: Research failed to start within timeout period")
self.should_terminate.set()
return
while not self.should_terminate.is_set():
cmd = self.ui.get_input("Enter command: ")
if cmd is None or self.shutdown_event.is_set():
if self.should_terminate.is_set() and not self.research_complete:
self.ui.update_output("\nGenerating research summary... please wait...")
summary = self.terminate_research()
self.ui.update_output("\nFinal Research Summary:")
self.ui.update_output(summary)
break
if cmd:
self._handle_command(cmd)
except Exception as e:
logger.error(f"Error in research process: {str(e)}")
finally:
self._cleanup()
def check_document_size(self) -> bool:
"""Check if document size is approaching context limit"""
try:
with open(self.document_path, 'r', encoding='utf-8') as f:
content = f.read()
estimated_tokens = len(content.split()) * 1.3
max_tokens = self.llm.llm_config.get('n_ctx', 2048)
current_ratio = estimated_tokens / max_tokens
if current_ratio > 0.8:
logger.warning(f"Document size at {current_ratio*100:.1f}% of context limit")
self.ui.update_output(f"Warning: Document size at {current_ratio*100:.1f}% of context limit")
return current_ratio > 0.9
except Exception as e:
logger.error(f"Error checking document size: {str(e)}")
return True
def _handle_command(self, cmd: str):
"""Handle user commands during research"""