-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·2316 lines (1934 loc) · 109 KB
/
Copy pathmain.py
File metadata and controls
executable file
·2316 lines (1934 loc) · 109 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
"""
Main entry point for the AutoInterp Agent Framework.
Implements a streamlined pipeline for automated interpretability research.
"""
import os
import sys
import re
import argparse
import asyncio
import json
from pathlib import Path
from typing import Dict, List, Any, Optional, Tuple, Union
# Ensure package imports resolve when running this file directly
if __package__ is None or __package__ == "":
pkg_root = Path(__file__).resolve().parent.parent
if str(pkg_root) not in sys.path:
sys.path.insert(0, str(pkg_root))
# Load environment variables from .env file
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass # dotenv is optional
from AutoInterp.core.utils import setup_logging, load_yaml, ensure_directory, get_timestamp, load_prompts, PathResolver, log_to_comprehensive_log, clean_code_content
from AutoInterp.core.llm_interface import LLMInterface
from AutoInterp.questions.question_manager import QuestionManager
from AutoInterp.analysis.analysis_generator import AnalysisGenerator
from AutoInterp.analysis.analysis_executor import AnalysisExecutor
from AutoInterp.analysis.analysis_planner import AnalysisPlanner
from AutoInterp.analysis.evaluator import Evaluator
from AutoInterp.analysis.visualization_evaluator import VisualizationEvaluator
from AutoInterp.reporting.report_generator import ReportGenerator
def select_provider_and_model() -> Tuple[str, str]:
"""
Prompt user to select LLM provider and model for the current run.
Returns:
Tuple of (provider, model_id)
"""
# Model mappings for each provider
model_mappings = {
"anthropic": {
"Claude Sonnet 4.5": "claude-sonnet-4-5",
"Claude Opus 4.5": "claude-opus-4-5-20251101"
},
"openai": {
"GPT-5": "gpt-5-2025-08-07",
"GPT-5-mini": "gpt-5-mini-2025-08-07"
},
"openrouter": {
"Claude Sonnet 4.5": "anthropic/claude-sonnet-4.5",
"Claude Opus 4.5": "anthropic/claude-opus-4.5",
"GPT-5": "openai/gpt-5",
"GPT-5-mini": "openai/gpt-5-mini",
"Kimi K2": "moonshotai/kimi-k2-0905",
"Qwen3 235B-A22B": "qwen/qwen3-235b-a22b",
"DeepSeek V3.2": "deepseek/deepseek-v3.2"
}
}
print("\n" + "="*50)
print("Select model provider:")
print("="*50)
# Provider options - show all options regardless of API keys
provider_options = ["anthropic", "openai", "openrouter", "manual"]
print("[1] Anthropic")
print("[2] OpenAI")
print("[3] OpenRouter")
print("[4] Manual Configuration (use config.yaml)")
# Get provider selection
while True:
try:
choice = input(f"\nSelect provider [1-{len(provider_options)}]: ").strip()
provider_idx = int(choice) - 1
if 0 <= provider_idx < len(provider_options):
selected_provider = provider_options[provider_idx]
break
else:
print(f"Please enter a number between 1 and {len(provider_options)}")
except (ValueError, KeyboardInterrupt):
print(f"Please enter a valid number between 1 and {len(provider_options)}")
# If manual configuration, return None to skip overrides
if selected_provider == "manual":
print("Using manual configuration from config.yaml")
return "manual", ""
print(f"\nSelected provider: {selected_provider.upper()}")
# Model selection
print(f"\nSelect default model:")
available_models = list(model_mappings[selected_provider].keys())
for i, model_name in enumerate(available_models, 1):
print(f"[{i}] {model_name}")
# Get model selection
while True:
try:
choice = input(f"\nSelect model [1-{len(available_models)}]: ").strip()
model_idx = int(choice) - 1
if 0 <= model_idx < len(available_models):
selected_model_name = available_models[model_idx]
selected_model_id = model_mappings[selected_provider][selected_model_name]
break
else:
print(f"Please enter a number between 1 and {len(available_models)}")
except (ValueError, KeyboardInterrupt):
print(f"Please enter a valid number between 1 and {len(available_models)}")
print(f"Selected model: {selected_model_name}")
print("="*50)
return selected_provider, selected_model_id
def apply_provider_model_override(config: Dict[str, Any], provider: str, model_id: str) -> Dict[str, Any]:
"""
Apply provider and model selection to all agents in the config.
Args:
config: Configuration dictionary to modify
provider: Selected provider (anthropic, openai, openrouter)
model_id: Selected model ID
Returns:
Modified configuration dictionary
"""
if provider == "manual":
return config
# Update all agent configurations
for agent_name, agent_config in config.get("agents", {}).items():
if "llm" in agent_config:
agent_config["llm"]["provider"] = provider
agent_config["llm"]["model"] = model_id
# Also update the default LLM config if it exists
if "llm" in config:
config["llm"]["provider"] = provider
config["llm"]["model"] = model_id
return config
async def initialize_framework(
config_path: Optional[str] = None,
venv_path: Optional[str] = None,
projects_dir: Optional[Union[str, Path]] = None,
) -> Dict[str, Any]:
"""
Initialize the framework with the given configuration.
Args:
config_path: Optional path to an override configuration file
venv_path: Optional path to existing virtual environment to use
projects_dir: Optional root directory for generated projects
Returns:
Dictionary with initialized components
"""
package_root = Path(__file__).resolve().parent
# Load global configuration
config = load_yaml(Path(__file__).parent / "config.yaml")
# Load override configuration if provided
if config_path:
override_config = load_yaml(config_path)
# Merge configurations (override config takes precedence)
for key, value in override_config.items():
if isinstance(value, dict) and key in config and isinstance(config[key], dict):
# Deep merge for dictionary values
config[key] = {**config[key], **value}
else:
# Simple override for other values
config[key] = value
# Resolve the projects directory, defaulting to the package projects folder
paths_config = config.setdefault("paths", {})
configured_projects = projects_dir or paths_config.get("projects", "projects")
resolved_projects_path = Path(configured_projects).expanduser()
if not resolved_projects_path.is_absolute():
resolved_projects_path = (package_root / resolved_projects_path).resolve()
paths_config["projects"] = str(resolved_projects_path)
# Handle virtual environment path override
if venv_path:
# Enable existing venv usage and set the path
if "execution" not in config:
config["execution"] = {}
config["execution"]["use_existing_venv"] = True
config["execution"]["existing_venv_path"] = venv_path
# Disable clean venv when using existing venv
config["execution"]["force_clean_venv"] = False
print(f"[AUTOINTERP] Using existing virtual environment: {venv_path}")
# Validate execution settings for conflicts
if config.get("execution", {}).get("use_existing_venv", False):
# When using existing venv, force_clean_venv should be disabled
if config.get("execution", {}).get("force_clean_venv", False):
config["execution"]["force_clean_venv"] = False
print(f"[AUTOINTERP] Disabled force_clean_venv since using existing virtual environment")
# Validate required configuration sections and values
required_sections = {
"framework": ["version", "log_level"],
"paths": ["projects"],
"task": ["description"],
"analysis": ["max_iterations", "confidence_threshold"],
"execution": ["max_retries"],
"llm": ["provider", "model", "temperature"]
}
# Required component configurations
required_component_configs = {
"paths": {
"required_fields": ["projects", "data", "models"],
"required_settings": ["create_missing", "cleanup_old"]
},
"llm": {
"required_fields": ["provider", "model"],
"required_settings": ["temperature", "max_tokens", "timeout"]
},
"analysis": {
"required_fields": ["executor_type", "output_format"],
"required_settings": ["max_iterations", "timeout_per_analysis"]
}
}
missing_configs = []
# First validate basic required sections and fields
for section, fields in required_sections.items():
if section not in config:
missing_configs.append(f"Missing required configuration section: {section}")
continue
for field in fields:
if field not in config[section]:
missing_configs.append(f"Missing required configuration field: {section}.{field}")
elif config[section][field] is None:
missing_configs.append(f"Configuration field cannot be null: {section}.{field}")
# Then validate component-specific configurations
for component, requirements in required_component_configs.items():
if component not in config:
missing_configs.append(f"Missing required component configuration: {component}")
continue
component_config = config[component]
# Check required fields
for field in requirements["required_fields"]:
if field not in component_config:
missing_configs.append(f"Missing required field in {component} configuration: {field}")
elif component_config[field] is None:
missing_configs.append(f"Field in {component} configuration cannot be null: {field}")
# Check required settings
for setting in requirements["required_settings"]:
if setting not in component_config:
missing_configs.append(f"Missing required setting in {component} configuration: {setting}")
elif component_config[setting] is None:
missing_configs.append(f"Setting in {component} configuration cannot be null: {setting}")
if missing_configs:
error_msg = "Configuration validation failed:\n" + "\n".join(missing_configs)
print(f"[AUTOINTERP] ERROR: {error_msg}")
# Print the current configuration for debugging
print(f"[AUTOINTERP] Current configuration:")
for section, values in config.items():
print(f"[AUTOINTERP] {section}: {values}")
raise ValueError(error_msg)
# Load prompt configuration
try:
prompts_dir = Path(__file__).parent / "prompts"
prompts = load_prompts(prompts_dir)
# Add prompts to config
config["prompts"] = prompts
except Exception as e:
import traceback
full_traceback = traceback.format_exc()
print(f"ERROR: Failed to load prompts from {prompts_dir}")
print(f"Reason: {e}")
print(f"Full traceback:\n{full_traceback}")
print("Prompts are required for operation. Exiting...")
sys.exit(1)
# STEP 1: Always use a fixed working project ID at startup. Name will be updated after question selection
project_id = f"working_project_{get_timestamp('%Y%m%dT%H%M%S')}"
# Set the project_id in config so it's immediately available everywhere
config["project_id"] = project_id
# Set up logging with log file in logs directory
log_level = config["framework"]["log_level"]
log_file_name = config["framework"].get("log_file") # This one can be optional
# Initialize logger - only show warnings and errors in console, but log everything to file
logger = setup_logging(log_level=log_level, console_level="WARNING")
# Initialize the central path resolver with the config
path_resolver = PathResolver(config)
logger.info(f"Initialized path resolver with project_id: {project_id}")
# Setup project directories using the path resolver
path_resolver.ensure_path("") # Create project root directory
path_resolver.ensure_path("analysis_scripts")
path_resolver.ensure_path("analysis_plans")
path_resolver.ensure_path("reports")
path_resolver.ensure_path("evaluation_results")
path_resolver.ensure_path("questions")
path_resolver.ensure_path("logs")
path_resolver.ensure_path("data")
# Get paths for components to use
project_dir = path_resolver.get_project_dir()
# Now update the logger with the log file path if needed
if log_file_name:
logs_dir = path_resolver.get_path("logs")
log_file_path = logs_dir / log_file_name
logger = setup_logging(log_level, str(log_file_path))
logger.info(f"Log file path set to: {log_file_path}")
logger.info(f"Initializing AutoInterp Agent Framework v{config['framework']['version']}")
# Initialize LLM interface with validated config
llm_interface = LLMInterface(config, agent_name="question_generator") # Use question_generator as the default agent
logger.info(f"LLM interface initialized with provider: {config['agents']['question_generator']['llm']['provider']} and model: {config['agents']['question_generator']['llm']['model']}")
# Initialize question manager
question_manager = QuestionManager(
llm_interface=llm_interface,
config=config
)
logger.info("Question manager initialized")
# Initialize analysis components with validated config
analysis_generator = AnalysisGenerator(
llm_interface=llm_interface,
config=config
)
logger.info("Analysis generator initialized")
analysis_executor = AnalysisExecutor(config=config)
logger.info("Analysis executor initialized")
analysis_planner = AnalysisPlanner(
llm_interface=llm_interface,
path_resolver=path_resolver
)
logger.info("Analysis planner initialized")
evaluator = Evaluator(
question_manager=question_manager,
llm_interface=llm_interface,
config=config
)
logger.info("Evaluator initialized")
visualization_evaluator = VisualizationEvaluator(
llm_interface=llm_interface,
config=config
)
logger.info("Visualization Evaluator initialized")
# Initialize reporting components
report_generator = ReportGenerator(config=config, llm_interface=llm_interface)
logger.info("Report generator initialized")
# Return framework components including path resolver
return {
"config": config,
"logger": logger,
"path_resolver": path_resolver,
"llm_interface": llm_interface,
"question_manager": question_manager,
"analysis_generator": analysis_generator,
"analysis_executor": analysis_executor,
"analysis_planner": analysis_planner,
"evaluator": evaluator,
"visualization_evaluator": visualization_evaluator,
"report_generator": report_generator
}
async def generate_questions(
llm_interface: LLMInterface,
question_manager: QuestionManager,
config: Dict[str, Any],
logger: Any
) -> List[Dict[str, Any]]:
"""
Generate initial questions using the question_generator agent.
Args:
llm_interface: LLM interface for interacting with language models
question_manager: Manager for question tracking
config: Configuration dictionary
logger: Logging instance
Returns:
List of generated questions
"""
logger.info("Generating questions...")
print("[AUTOINTERP] PHASE 1/4: Question Generation")
# Get task details for questions generation
task_config = config.get("task")
if not task_config or "description" not in task_config:
error_msg = "Missing required task configuration. Task 'description' must be specified in the task config."
logger.error(error_msg)
raise ValueError(error_msg)
# Generate a task name from the description for logging
task_description = task_config["description"]
task_name = task_description[:50] + "..." if len(task_description) > 50 else task_description
task_description = task_config["description"]
if not task_description.strip():
error_msg = "Task description cannot be empty. A detailed description is required for question generation."
logger.error(error_msg)
raise ValueError(error_msg)
# Log task starting
logger.info(f"Starting task: {task_name}")
logger.info(f"Task description: {task_description}")
# Generate questions using the question_manager
# Now it just saves to a text file and returns empty list
await question_manager.generate_questions(
task_description=task_description,
count=3
)
# Read the raw questions from file and print them directly
raw_questions_path = question_manager.storage_dir / "questions.txt"
if raw_questions_path.exists():
try:
with open(raw_questions_path, 'r') as f:
raw_questions = f.read()
print("\n============= QUESTION GENERATOR OUTPUT =============")
print(raw_questions)
print("======================================================\n")
except Exception as e:
print(f"[AUTOINTERP] Error reading raw questions: {e}")
# For logging - we don't have structured questions anymore, just carry on
logger.info("Generated initial questions - see raw text output in console")
# Return empty list since we now use raw text files instead of structured questions
return []
async def prioritize_questions(
question_manager: QuestionManager,
llm_interface: LLMInterface,
config: Dict[str, Any],
logger: Any,
evaluator: Optional[Evaluator] = None
) -> Dict[str, Any]:
"""
Prioritize questions using the question_prioritizer agent.
Args:
question_manager: Manager for question tracking
llm_interface: LLM interface for interacting with language models
config: Configuration dictionary
logger: Logging instance
evaluator: Optional evaluator instance for updating after project rename
Returns:
Selected question to investigate
"""
logger.info("Prioritizing questions...")
print("[AUTOINTERP] PHASE 2/4: Question Prioritization")
# Get task details for context
# Generate a task name from the description for logging
task_description = config.get("task", {}).get("description", "")
task_name = task_description[:50] + "..." if len(task_description) > 50 else task_description or "Unnamed Task"
task_description = config.get("task", {}).get("description", "")
# Call prioritize_questions to have the question_prioritizer agent select a question
# It now saves the output to prioritized_question.txt and returns empty list
await question_manager.prioritize_questions()
# Read the prioritized question from file and print it directly
prioritized_path = question_manager.storage_dir / "prioritized_question.txt"
if not prioritized_path.exists():
logger.error("No prioritized_question.txt file was generated.")
print("\n[AUTOINTERP] No prioritized question file was generated. Using raw question text instead.\n")
# Try to use raw questions instead
raw_questions_path = question_manager.storage_dir / "questions.txt"
if raw_questions_path.exists():
# Copy the raw questions to prioritized question path
import shutil
shutil.copy(raw_questions_path, prioritized_path)
print(f"[AUTOINTERP] Copied raw questions to {prioritized_path}")
# Read and print prioritized question
if prioritized_path.exists():
try:
with open(prioritized_path, 'r') as f:
prioritized_text = f.read()
print("\n============= QUESTION PRIORITIZER OUTPUT =============")
print(prioritized_text)
print("========================================================\n")
# Extract TITLE from the prioritized text if available
import re # Make sure re is imported in this scope
title_match = re.search(r'TITLE:\s*(.*?)(?:\n|$)', prioritized_text, re.IGNORECASE)
if title_match:
extracted_title = title_match.group(1).strip()
print(f"[AUTOINTERP] Extracted title: {extracted_title}")
# Update project_id with this title immediately
if extracted_title:
# Sanitize the title for use as directory name
sanitized_title = re.sub(r'[^\w\-\.]', '_', extracted_title).lower()
sanitized_title = re.sub(r'_+', '_', sanitized_title)
# Get timestamp for uniqueness
timestamp = get_timestamp("%Y-%m-%dT%H-%M-%S")
# Create new project_id
new_project_id = f"{sanitized_title}_{timestamp}"
# Store the original title for later use
config["title"] = extracted_title
print(f"[AUTOINTERP] Setting new project ID: {new_project_id}")
# Immediately rename the project (we'll do it properly later)
old_project_id = config.get("project_id", "working_project")
config["project_id"] = new_project_id
except Exception as e:
print(f"[AUTOINTERP] Error reading prioritized question: {e}")
raise ValueError("Failed to read prioritized question")
else:
raise ValueError("No prioritized question was found")
# Pass the raw text directly as the active question
logger.info(f"Selected question")
active_question = prioritized_text
selected_hyp = prioritized_text # We still need this for compatibility with the return value
# HERE'S THE KEY CHANGE:
# Now that we've selected a question, let's rename the project with a meaningful name
# If we already have a title from the prioritized question, use that
# Otherwise, fall back to the task name
if "title" in config:
# We already set new_project_id in config when we extracted the title
new_project_id = config["project_id"]
print(f"[AUTOINTERP] Using extracted title for project ID: {new_project_id}")
else:
# Fall back to using the task name with timestamp
default_timestamp = get_timestamp("%Y-%m-%dT%H-%M-%S")
# Use a default project name when no title is extracted
task_name = "interpretability_project"
# Convert task name to a valid directory name
safe_task_name = re.sub(r'[^\w]', '_', task_name).lower().strip('_')
# Generate the new project ID
new_project_id = f"{safe_task_name}_{default_timestamp}"
print(f"[AUTOINTERP] No title found in prioritized question, using task name: {new_project_id}")
# Get the old and new project paths using the path resolver
path_resolver = PathResolver() # Get the singleton instance
old_project_dir = path_resolver.get_project_dir()
# Need this for the os.rename operation
configured_projects = config.get("paths", {}).get("projects")
if configured_projects:
projects_dir = Path(configured_projects)
else:
projects_dir = path_resolver.base_project_dir
if not projects_dir.is_absolute():
projects_dir = path_resolver.base_project_dir / projects_dir
new_project_dir = projects_dir / new_project_id
# ONLY rename if working_project exists and the new project doesn't
if old_project_dir.exists() and not new_project_dir.exists():
try:
# Log before renaming
logger.info(f"Renaming project directory from '{path_resolver.project_id}' to '{new_project_id}'")
print(f"[AUTOINTERP] Renaming project from '{path_resolver.project_id}' to '{new_project_id}'...")
# Rename the directory (this moves all files from old to new location)
import os
os.rename(old_project_dir, new_project_dir)
# Update the project_id in config
config["project_id"] = new_project_id
# Update the path resolver with the new project_id
# This ensures all future path resolutions will use the new project_id
path_resolver.update_project_id(new_project_id)
# Update the question manager's storage directory
question_manager.update_storage_dir()
# Update the evaluator's output directory if provided
if evaluator:
evaluator.output_dir = path_resolver.ensure_path("evaluation_results")
logger.info(f"Updated evaluator's output directory to: {evaluator.output_dir}")
else:
logger.warning("Evaluator not available, skipping update of evaluation_results directory")
logger.info(f"Updated question manager's storage directory")
logger.info(f"Successfully renamed project directory to '{new_project_id}'")
print(f"[AUTOINTERP] Project directory renamed to: {new_project_id}")
# Console logging was already set up at the start of the pipeline
# The rename operation moved the entire directory including console.log
except Exception as e:
import traceback
logger.error(f"Failed to rename project directory: {str(e)}")
logger.error(traceback.format_exc())
print(f"[AUTOINTERP] Warning: Could not rename project directory: {str(e)}")
else:
# Project already exists or rename didn't happen
# Console logging was already set up at the start of the pipeline
pass
# Log the decision
logger.info("Selected question using question_prioritizer - see raw text output in console")
# Return our simple dict with raw_text instead of structured question
return selected_hyp
async def analyze_question(
active_question: Union[str, Dict[str, Any]], # Can be raw text or dict
analysis_generator: AnalysisGenerator,
analysis_executor: AnalysisExecutor,
analysis_planner: AnalysisPlanner,
question_manager: QuestionManager,
config: Dict[str, Any],
logger: Any,
iteration_number: Optional[int] = None
) -> Dict[str, Any]:
"""
Analyze the active question using the analysis_planner, analysis_generator, and analysis_executor.
Args:
active_question: The question to analyze
analysis_generator: Generator for analysis code
analysis_executor: Executor for analysis code
analysis_planner: Planner for analysis strategy
question_manager: Manager for question tracking
config: Configuration dictionary
logger: Logging instance
Returns:
Analysis results
"""
logger.info("Starting analysis phase...")
print(f"[AUTOINTERP] PHASE 3/4: Analysis of Question")
print(f"[AUTOINTERP] Using raw question text for analysis\n")
# First, plan the analysis
logger.info("Planning analysis approach...")
print(f"[AUTOINTERP] Planning analysis approach...")
try:
# Generate the analysis plan
plan_path, analysis_plan = await analysis_planner.plan_analysis(
active_question=active_question,
config=config,
iteration_number=iteration_number
)
logger.info(f"Generated analysis plan at {plan_path}")
print(f"[AUTOINTERP] Generated analysis plan at {plan_path}")
# Next, generate analysis code based on the plan
logger.info("Generating analysis script from plan...")
print(f"[AUTOINTERP] Generating analysis script from plan...")
# Pass the analysis plan directly - it will be formatted in the template
script_path, analysis_code = await analysis_generator.generate_analysis(
question=active_question,
task_config=config,
analysis_plan=analysis_plan,
iteration_number=iteration_number
)
logger.info(f"Generated analysis script at {script_path}")
print(f"[AUTOINTERP] Generated analysis script at {script_path}")
# Execute the analysis with retry for script errors
logger.info("Executing analysis...")
print(f"[AUTOINTERP] Executing analysis script on question... (this may take a while)")
max_retries = config.get("execution", {}).get("max_retries", 1)
max_total_attempts = max_retries + 1 # Total attempts = initial attempt + retries
attempt_number = 1
while attempt_number <= max_total_attempts:
execution_result = await analysis_executor.execute_analysis(
script_path=script_path,
question=active_question,
parameters=config.get("analysis_parameters", {})
)
if execution_result.get("success", False):
# Script ran successfully, break the retry loop
break
error_msg = execution_result.get("error", "Unknown error")
error_traceback = execution_result.get("traceback", "")
# Log detailed error to logger
logger.error(f"Analysis execution failed (attempt {attempt_number}/{max_total_attempts}): {error_msg}")
if error_traceback:
logger.error(f"Traceback: {error_traceback}")
# Print error details to console for user visibility
print(f"[AUTOINTERP] Analysis execution failed (attempt {attempt_number}/{max_total_attempts})")
print(f"[AUTOINTERP] Error: {error_msg}")
if error_traceback:
print(f"[AUTOINTERP] Traceback:\n{error_traceback}")
if attempt_number < max_total_attempts:
# Try to regenerate the script with the error information
logger.info(f"Regenerating analysis script (attempt {attempt_number + 1}/{max_total_attempts})")
print(f"[AUTOINTERP] Regenerating script (attempt {attempt_number + 1}/{max_total_attempts})...")
# Increment the attempt counter in the analysis generator
analysis_generator.increment_attempt()
# Read stderr directly if possible
stderr_file = Path(execution_result.get("execution_dir", "")) / "stderr.txt"
stderr_content = ""
if stderr_file.exists():
try:
with open(stderr_file, 'r') as f:
stderr_content = f.read()
logger.info(f"Read stderr.txt content for error context")
except Exception as e:
logger.error(f"Error reading stderr.txt: {e}")
# Format the traceback nicely
error_traceback_formatted = ""
if stderr_content:
error_traceback_formatted = f"TRACEBACK:\n{stderr_content}"
elif error_traceback:
error_traceback_formatted = f"TRACEBACK:\n{error_traceback}"
# Capture the current script path before generating a new one
previous_script_path = script_path
# Generate a modified analysis script with error context
script_path, analysis_code = await analysis_generator.generate_analysis(
question=active_question,
task_config=config,
error_context={
"error": error_msg,
"traceback": error_traceback_formatted,
"previous_script": previous_script_path
},
iteration_number=iteration_number
)
logger.info(f"Regenerated analysis script at {script_path}")
print(f"[AUTOINTERP] Regenerated analysis script at {script_path}")
attempt_number += 1
else:
# We've exhausted our attempts
print(f"[AUTOINTERP] Analysis execution failed after {max_total_attempts} attempts.")
# Check if we should shutdown or continue
fail_on_max_retries = config.get("execution", {}).get("fail_on_max_retries", False)
if fail_on_max_retries:
# Shutdown the entire system
logger.critical(f"System shutdown due to max retries exceeded (fail_on_max_retries=true)")
print(f"[AUTOINTERP] SYSTEM SHUTDOWN: Analysis failed after {max_total_attempts} attempts (fail_on_max_retries=true)")
raise SystemExit(f"Analysis execution failed: {error_msg}\nTraceback: {error_traceback}")
else:
# Continue to next analysis (existing behavior)
logger.warning(f"Continuing to next analysis despite failures (fail_on_max_retries=false)")
print(f"[AUTOINTERP] Continuing to next analysis despite execution failures...")
# Raise error with full details for the iterative_analysis function to handle
raise ValueError(f"Analysis execution failed: {error_msg}\nTraceback: {error_traceback}")
logger.info(f"Analysis execution completed in {execution_result.get('execution_time_formatted', 'unknown time')}")
print(f"[AUTOINTERP] Analysis execution completed in {execution_result.get('execution_time_formatted', 'unknown time')}")
# We'll handle moving to the next analysis in the iterative_analysis function
# Don't call move_to_next_analysis() here
# Record success in logs
logger.info(f"Analysis completed successfully in {execution_result.get('execution_time_formatted', 'unknown time')}. Produced results of size {len(str(execution_result.get('results', {})))} characters.")
# Return both analysis results and the plan
return execution_result, analysis_plan
except Exception as e:
import traceback
full_traceback = traceback.format_exc()
# Log the full error details and also print to console
logger.error(f"Error in analysis: {str(e)}")
logger.error(full_traceback)
# Print full error details to console
print(f"[AUTOINTERP] Error in analysis: {str(e)}")
print(f"[AUTOINTERP] Full traceback:\n{full_traceback}")
# Record failure in logs
logger.error(f"Analysis attempt failed: {str(e)}")
logger.error(f"Traceback: {full_traceback}")
# Re-raise the exception for the caller to handle
raise e
async def evaluate_analysis(
active_question: Union[str, Dict[str, Any]], # Can be raw text or dict
analysis_results: Dict[str, Any],
evaluator: Evaluator,
question_manager: QuestionManager,
config: Dict[str, Any],
logger: Any,
current_confidence: float = 0.0,
iteration_number: Optional[int] = None,
attempt_number: Optional[int] = None,
analysis_plan: Optional[str] = None
) -> Dict[str, Any]:
"""
Evaluate analysis results against the question.
Args:
active_question: The question being tested
analysis_results: Results from the analysis
evaluator: Evaluator component
question_manager: Manager for question tracking
config: Configuration dictionary
logger: Logging instance
Returns:
Evaluation results
"""
logger.info("Starting evaluation phase...")
print(f"[AUTOINTERP] Evaluating analysis results against question")
# Use the evaluator to assess results
# For raw text questions, we need to generate a dummy ID
if isinstance(active_question, str):
# Create a simple dummy ID
dummy_id = "txt_question_1"
evaluation_result = await evaluator.evaluate_analysis(
analysis_results=analysis_results,
question_id=dummy_id,
current_confidence=current_confidence,
iteration_number=iteration_number,
attempt_number=attempt_number,
analysis_plan=analysis_plan
)
else:
# For dict questions, use the ID if available
evaluation_result = await evaluator.evaluate_analysis(
analysis_results=analysis_results,
question_id=active_question.get("id", "txt_question_1"),
current_confidence=current_confidence,
iteration_number=iteration_number,
attempt_number=attempt_number,
analysis_plan=analysis_plan
)
# Log the evaluation results
supports = evaluation_result.get("supports_question", None)
confidence_impact = evaluation_result.get("confidence_impact", 0.0)
explanation = evaluation_result.get("explanation", "")
# Ensure confidence_impact is a valid number for formatting
try:
confidence_impact = float(confidence_impact) if confidence_impact is not None else 0.0
except (ValueError, TypeError):
confidence_impact = 0.0
supports_text = "supports" if supports else "does not support" if supports is False else "is inconclusive regarding"
logger.info(f"Evaluation complete. Evidence {supports_text} the question. Confidence impact: {confidence_impact:+.2f}")
print(f"[AUTOINTERP] Evaluation complete")
print(f"[AUTOINTERP] Evidence {supports_text} the question")
# Print key insights
if "key_insights" in evaluation_result and evaluation_result["key_insights"]:
print(f"[AUTOINTERP] Key insights:")
for i, insight in enumerate(evaluation_result["key_insights"][:3]):
print(f"[AUTOINTERP] {i+1}. {insight}")
# Log evaluation results
logger.info(f"Evaluated analysis results against question. Evidence {supports_text} the question. Confidence {confidence_impact:+.2f}.")
if "key_insights" in evaluation_result and evaluation_result["key_insights"]:
logger.info(f"Key insight: {evaluation_result['key_insights'][0]}")
return evaluation_result
async def iterative_analysis(
active_question: Union[str, Dict[str, Any]], # Can be raw text or dict
analysis_generator: AnalysisGenerator,
analysis_executor: AnalysisExecutor,
analysis_planner: AnalysisPlanner,
evaluator: Evaluator,
question_manager: QuestionManager,
config: Dict[str, Any],
logger: Any,
max_iterations: int = 6,
confidence_threshold: float = 0.8
) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
"""
Perform iterative analysis and evaluation until confidence threshold is reached.
Args:
active_question: The question to analyze
analysis_generator: Generator for analysis code
analysis_executor: Executor for analysis code
evaluator: Evaluator for analysis results
question_manager: Manager for question tracking
config: Configuration dictionary
logger: Logging instance
max_iterations: Maximum number of analysis iterations
confidence_threshold: Confidence threshold to stop iteration
Returns:
Tuple of (all analyses, all evaluations)
"""
logger.info(f"Starting iterative analysis cycle. Max iterations: {max_iterations}, Confidence threshold: {confidence_threshold}")
print(f"[AUTOINTERP] Beginning iterative analysis cycle")
print(f"[AUTOINTERP] Will continue analyzing until confidence is ≥ {confidence_threshold}, or until {max_iterations} analyses are completed")
all_analyses = []
all_evaluations = []
# Get initial confidence - use default since we're using raw text
current_confidence = 0.0
for iteration in range(max_iterations):
print(f"\n[AUTOINTERP] === ANALYSIS CYCLE {iteration+1}/{max_iterations} ===")
print(f"[AUTOINTERP] Current confidence: {current_confidence:.2f}")
# Make sure we start a new analysis for this iteration (not a retry attempt)
# but only if this isn't the first iteration
if iteration > 0:
# Reset the analysis generator to start a new analysis
analysis_generator.move_to_next_analysis()
# Run analysis
try:
analysis_result, analysis_plan = await analyze_question(
active_question=active_question,
analysis_generator=analysis_generator,
analysis_executor=analysis_executor,
analysis_planner=analysis_planner,
question_manager=question_manager,
config=config,
logger=logger,
iteration_number=iteration + 1
)
all_analyses.append(analysis_result)
# Evaluate results
evaluation_result = await evaluate_analysis(
active_question=active_question,
analysis_results=analysis_result,
evaluator=evaluator,
question_manager=question_manager,
config=config,
logger=logger,
current_confidence=current_confidence,
iteration_number=iteration + 1,
attempt_number=analysis_generator.current_attempt,
analysis_plan=analysis_plan
)
# Check if evaluator detected failed analysis (similar to compilation failure handling)
raw_evaluation = evaluation_result.get("raw_evaluation", "")
if "ANALYSIS_FAILED" in raw_evaluation:
logger.warning(f"Evaluator detected failed analysis in iteration {iteration+1}")