Directory structure:
└── scilink/
    ├── __init__.py
    ├── auth.py
    ├── agents/
    │   ├── __init__.py
    │   ├── __pycache__/
    │   ├── exp_agents/
    │   │   ├── __init__.py
    │   │   ├── atomistic_microscopy_agent.py
    │   │   ├── base_agent.py
    │   │   ├── human_feedback.py
    │   │   ├── instruct.py
    │   │   ├── llama_wrapper.py
    │   │   ├── microscopy_agent.py
    │   │   ├── orchestrator_agent.py
    │   │   ├── recommendation_agent.py
    │   │   ├── sam_microscopy_agent.py
    │   │   ├── spectroscopy_agent.py
    │   │   ├── utils.py
    │   │   └── __pycache__/
    │   ├── lit_agents/
    │   │   ├── __init__.py
    │   │   ├── instruct.py
    │   │   ├── literature_agent.py
    │   │   ├── novelty_scorer.py
    │   │   └── __pycache__/
    │   └── sim_agents/
    │       ├── __init__.py
    │       ├── executors.py
    │       ├── instruct.py
    │       ├── llm_client.py
    │       ├── structure_agent.py
    │       ├── tools.py
    │       ├── utils.py
    │       ├── val_agent.py
    │       ├── vasp_agent.py
    │       ├── __pycache__/
    │       └── docs/
    ├── cli/
    │   ├── __init__.py
    │   ├── workflows.py
    │   └── __pycache__/
    └── workflows/
        ├── __init__.py
        ├── analyzers.py
        ├── dft_recommendation_workflow.py
        ├── dft_workflow.py
        ├── experiment2dft.py
        ├── experiment_novelty_workflow.py
        └── __pycache__/

================================================
File: __init__.py
================================================
from .auth import set_api_key, show_api_status

def configure(service: str, api_key: str):
    """Configure API key for a service
    
    Args:
        service: 'google', 'futurehouse', or 'materials_project'
        api_key: The API key
        
    Examples:
        import scilinkllm
        scilinkllm.configure('google', 'your-google-api-key')
        scilinkllm.configure('futurehouse', 'your-futurehouse-key')
    """
    set_api_key(service, api_key)

def configure_from_dict(config: dict):
    """Configure multiple API keys at once
    
    Args:
        config: Dictionary with service names as keys
        
    Example:
        scilinkllm.configure_from_dict({
            'google': 'your-google-key',
            'futurehouse': 'your-futurehouse-key'
        })
    """
    for service, key in config.items():
        set_api_key(service, key)

def show_config():
    """Show current API key configuration status"""
    show_api_status()

from .workflows import ExperimentNoveltyAssessment
from .workflows.dft_workflow import DFTWorkflow
from .workflows.dft_recommendation_workflow import DFTRecommendationsWorkflow
from .workflows.experiment2dft import Experimental2DFT

__all__ = [
    'configure', 
    'configure_from_dict', 
    'show_config',
    'MicroscopyNoveltyAssessmentWorkflow',
    'DFTWorkflow', 
    'SpectroscopyNoveltyAssessmentWorkflow',
    'DFTRecommendationsWorkflow',
    'Experimental2DFT'
    'ExperimentNoveltyAssessment'
]


================================================
File: auth.py
================================================
# scilinkllm/auth.py

import os
from typing import Optional, Dict

class APIKeyManager:
    """Simple API key management with environment variable auto-discovery"""
    
    def __init__(self):
        self._keys: Dict[str, str] = {}
    
    def get_key(self, service: str) -> Optional[str]:
        """Get API key for a service"""
        # First check if explicitly set
        if service in self._keys:
            return self._keys[service]
        
        # Then check environment variables
        env_vars = {
            'google': ['GOOGLE_API_KEY'],
            'futurehouse': ['FUTUREHOUSE_API_KEY'],
            'materials_project': ['MP_API_KEY', 'MATERIALS_PROJECT_API_KEY']
        }
        
        for var_name in env_vars.get(service, []):
            key = os.getenv(var_name)
            if key:
                return key
        
        return None
    
    def set_key(self, service: str, api_key: str):
        """Set API key for a service"""
        self._keys[service] = api_key
    
    def clear_key(self, service: str):
        """Clear API key for a service"""
        self._keys.pop(service, None)
    
    def show_status(self):
        """Show current API key status"""
        services = ['google', 'futurehouse', 'materials_project']
        print("API Key Status:")
        for service in services:
            key = self.get_key(service)
            status = "✓ Found" if key else "✗ Not found"
            source = ""
            if key:
                if service in self._keys:
                    source = "(configured)"
                else:
                    source = "(environment)"
            print(f"  {service}: {status} {source}")

# Global instance
_api_manager = APIKeyManager()

def get_api_key(service: str) -> Optional[str]:
    """Get API key for a service"""
    return _api_manager.get_key(service)

def set_api_key(service: str, api_key: str):
    """Set API key for a service"""
    _api_manager.set_key(service, api_key)

def clear_api_key(service: str):
    """Clear API key for a service"""
    _api_manager.clear_key(service)

def show_api_status():
    """Show current API key status"""
    _api_manager.show_status()

class APIKeyNotFoundError(Exception):
    """Raised when a required API key is not found"""
    
    def __init__(self, service: str):
        suggestions = {
            'google': [
                "Set environment variable: export GOOGLE_API_KEY='your-key'",
                "Configure in code: scilinkllm.configure('google', 'your-key')",
                "Get API key at: https://aistudio.google.com/apikey"
            ],
            'futurehouse': [
                "Set environment variable: export FUTUREHOUSE_API_KEY='your-key'",
                "Configure in code: scilinkllm.configure('futurehouse', 'your-key')",
                "Contact FutureHouse for API access"
            ],
            'materials_project': [
                "Set environment variable: export MP_API_KEY='your-key'",
                "Configure in code: scilinkllm.configure('materials_project', 'your-key')",
                "Get API key at: https://next-gen.materialsproject.org/api"
            ]
        }
        
        msg = f"API key for '{service}' not found.\n\nTry one of these options:\n"
        for suggestion in suggestions.get(service, []):
            msg += f"  • {suggestion}\n"
        
        super().__init__(msg)


================================================
File: agents/__init__.py
================================================




================================================
File: agents/exp_agents/__init__.py
================================================
from .microscopy_agent import MicroscopyAnalysisAgent
from .spectroscopy_agent import SpectroscopyAnalysisAgent
from .sam_microscopy_agent import SAMMicroscopyAnalysisAgent
from .orchestrator_agent import OrchestratorAgent, AGENT_MAP
from .atomistic_microscopy_agent import AtomisticMicroscopyAnalysisAgent


================================================
File: agents/exp_agents/atomistic_microscopy_agent.py
================================================
import os
import numpy as np
from io import BytesIO
import cv2
import matplotlib.pyplot as plt
import glob
from sklearn.mixture import GaussianMixture

from google.generativeai.types import GenerationConfig

from .base_agent import BaseAnalysisAgent
from .recommendation_agent import RecommendationAgent

from .instruct import (
    ATOMISTIC_MICROSCOPY_ANALYSIS_INSTRUCTIONS,
    ATOMISTIC_MICROSCOPY_CLAIMS_INSTRUCTIONS,
    INTENSITY_GMM_COMPONENT_SELECTION_INSTRUCTIONS,
    LOCAL_ENV_COMPONENT_SELECTION_INSTRUCTIONS,
    ATOMISTIC_MEASUREMENT_RECOMMENDATIONS_INSTRUCTIONS
)

from .utils import (
    load_image, preprocess_image, convert_numpy_to_jpeg_bytes, 
    predict_with_ensemble, analyze_nearest_neighbor_distances, 
    rescale_for_model, download_file_with_gdown, unzip_file,
    extract_atomic_intensities, create_intensity_histogram_plot
)

from .human_feedback import SimpleFeedbackMixin

import atomai as aoi


class AtomisticMicroscopyAnalysisAgent(SimpleFeedbackMixin, BaseAnalysisAgent):
    """
    Agent for analyzing atomistic microscopy images
    """

    def __init__(self, google_api_key: str | None = None, model_name: str = "gemini-2.5-pro-preview-06-05",
                 local_model: str = None,
                 atomistic_analysis_settings: dict | None = None, enable_human_feedback: bool = True):
        super().__init__(google_api_key, model_name, local_model, enable_human_feedback=enable_human_feedback)
        
        self.atomistic_analysis_settings = atomistic_analysis_settings if atomistic_analysis_settings else {}
        
        # Model download configuration
        self.DCNN_MODEL_GDRIVE_ID = '16LFMIEADO3XI8uNqiUoKKlrzWlc1_Q-p'
        self.DEFAULT_MODEL_DIR = "dcnn_trained"
        
        # Analysis settings
        self.save_visualizations = self.atomistic_analysis_settings.get('save_visualizations', True)
        self.refine_positions = self.atomistic_analysis_settings.get('refine_positions', False)
        self.max_refinement_shift = self.atomistic_analysis_settings.get('max_refinement_shift', 1.5)
        self.intensity_box_size = self.atomistic_analysis_settings.get('intensity_box_size', 2)  # 2x2 pixel box
        
        self.original_preprocessed_image = None
        self._recommendation_agent = None

    def _get_intensity_gmm_components_from_llm(self, image_blob, intensity_hist_blob, 
                                             system_info) -> tuple[int | None, str | None]:
        """
        Ask LLM to determine number of components for 1D intensity GMM.
        """
        self.logger.info("\n\n🤖 -------------------- ANALYSIS AGENT STEP: INTENSITY GMM COMPONENT SELECTION -------------------- 🤖\n")
        
        prompt_parts = [INTENSITY_GMM_COMPONENT_SELECTION_INSTRUCTIONS]
        prompt_parts.append("\nOriginal microscopy image:")
        prompt_parts.append(image_blob)
        prompt_parts.append("\nIntensity histogram of detected atoms:")
        prompt_parts.append(intensity_hist_blob)
        
        if system_info:
            system_info_section = self._build_system_info_prompt_section(system_info)
            if system_info_section:
                prompt_parts.append(system_info_section)
        
        prompt_parts.append("\nBased on the intensity histogram and material context, determine the optimal number of GMM components.")
        
        param_gen_config = GenerationConfig(response_mime_type="application/json")
        try:
            response = self.model.generate_content(
                contents=prompt_parts,
                generation_config=param_gen_config,
                safety_settings=self.safety_settings,
            )
            
            result_json, error_dict = self._parse_llm_response(response)
            
            if error_dict:
                self.logger.error(f"LLM intensity GMM component selection failed: {error_dict}")
                return None, None
            
            n_components = result_json.get("n_components")
            reasoning = result_json.get("reasoning", "No reasoning provided.")
            
            if isinstance(n_components, int) and 1 <= n_components <= 8:
                self.logger.info(f"LLM suggested {n_components} components for intensity GMM")
                self.logger.info(f"Reasoning: {reasoning}")
                return n_components, reasoning
            else:
                self.logger.warning(f"Invalid component number from LLM: {n_components}")
                return None, reasoning
                
        except Exception as e:
            self.logger.error(f"LLM intensity component selection failed: {e}", exc_info=True)
            return None, None

    def _perform_1d_intensity_gmm(self, intensities: np.ndarray, coordinates: np.ndarray, 
                                image_shape: tuple, n_components: int) -> tuple[np.ndarray, np.ndarray]:
        """
        Perform 1D GMM on intensities and create spatial maps.
        
        Returns:
            tuple: (gmm_labels, spatial_maps)
                gmm_labels: 1D array of cluster assignments for each atom
                spatial_maps: 3D array (h, w, n_components) showing spatial distribution
        """
        # Fit 1D GMM
        gmm = GaussianMixture(n_components=n_components, random_state=42)
        intensities_reshaped = intensities.reshape(-1, 1)
        gmm_labels = gmm.fit_predict(intensities_reshaped)
        
        # Create spatial maps
        h, w = image_shape
        spatial_maps = np.zeros((h, w, n_components))
        
        for i, (y, x) in enumerate(coordinates[:, :2].astype(int)):
            if 0 <= y < h and 0 <= x < w:
                component = gmm_labels[i]
                spatial_maps[y, x, component] = 1.0
        
        # Apply Gaussian smoothing to make maps more visible
        for c in range(n_components):
            spatial_maps[:, :, c] = cv2.GaussianBlur(spatial_maps[:, :, c], (15, 15), 3)
        
        return gmm_labels, spatial_maps

    def _create_intensity_gmm_visualization(self, intensities: np.ndarray, gmm_labels: np.ndarray,
                                          spatial_maps: np.ndarray, coordinates: np.ndarray,
                                          original_image: np.ndarray) -> list[dict]:
        """Create visualizations for 1D intensity GMM results."""
        visualizations = []
        n_components = spatial_maps.shape[2]
        
        # Intensity histogram with GMM components colored
        fig, ax = plt.subplots(figsize=(12, 4))
        
        # Use high-contrast colors that are visible on grayscale
        if n_components <= 2:
            colors = ['red', 'cyan']
        elif n_components <= 4:
            colors = ['red', 'cyan', 'lime', 'yellow']
        else:
            colors = ['red', 'cyan', 'lime', 'yellow', 'magenta', 'orange', 'white', 'lightblue']
        
        for c in range(n_components):
            component_intensities = intensities[gmm_labels == c]
            if len(component_intensities) > 0:
                ax.hist(component_intensities, bins=30, alpha=0.7, 
                       color=colors[c % len(colors)], edgecolor='black', linewidth=0.5,
                       label=f'Cluster {c+1} ({len(component_intensities)} atoms)')
        
        ax.set_xlabel('Intensity')
        ax.set_ylabel('Number of Atoms')
        ax.set_title('Intensity Distribution by GMM Component')
        ax.legend()
        ax.grid(True, alpha=0.3)
        
        buf = BytesIO()
        plt.savefig(buf, format='jpeg', dpi=150, bbox_inches='tight')
        buf.seek(0)
        visualizations.append({'label': 'Intensity GMM Histogram', 'bytes': buf.getvalue()})
        plt.close()
                
        # Atoms on original image colored by intensity component with better colors
        fig, ax = plt.subplots(figsize=(10, 10))
        ax.imshow(original_image, cmap='gray')
        
        for c in range(n_components):
            component_coords = coordinates[gmm_labels == c]
            if len(component_coords) > 0:
                ax.scatter(component_coords[:, 1], component_coords[:, 0], 
                          color=colors[c % len(colors)], s=20, alpha=0.9, 
                          edgecolors='black', linewidth=0.3,
                          label=f'Intensity Cluster {c+1} ({len(component_coords)} atoms)')
        
        ax.legend(loc='upper right', frameon=True, fancybox=True, shadow=True)
        ax.set_title('Intensity-Based Atomic Clustering')
        ax.axis('off')
        
        buf = BytesIO()
        plt.savefig(buf, format='jpeg', dpi=150, bbox_inches='tight')
        buf.seek(0)
        visualizations.append({'label': 'Intensity-Based Atomic Clustering', 'bytes': buf.getvalue()})
        plt.close()
        
        return visualizations

    def _get_local_env_components_from_llm(self, image_blob, intensity_visualizations,
                                         system_info) -> tuple[int | None, str | None]:
        """
        Ask LLM to determine number of components for local environment GMM.
        """
        self.logger.info("\n\n🤖 -------------------- ANALYSIS AGENT STEP: LOCAL ENVIRONMENT COMPONENT SELECTION -------------------- 🤖\n")
        
        prompt_parts = [LOCAL_ENV_COMPONENT_SELECTION_INSTRUCTIONS]
        prompt_parts.append("\nOriginal microscopy image:")
        prompt_parts.append(image_blob)
        
        prompt_parts.append("\nIntensity analysis results:")
        for viz in intensity_visualizations:
            prompt_parts.append(f"\n{viz['label']}:")
            prompt_parts.append({"mime_type": "image/jpeg", "data": viz['bytes']})
        
        if system_info:
            system_info_section = self._build_system_info_prompt_section(system_info)
            if system_info_section:
                prompt_parts.append(system_info_section)
        
        prompt_parts.append("\nBased on the intensity analysis and material context, determine the optimal number of components for local environment GMM.")
        
        param_gen_config = GenerationConfig(response_mime_type="application/json")
        try:
            response = self.model.generate_content(
                contents=prompt_parts,
                generation_config=param_gen_config,
                safety_settings=self.safety_settings,
            )
            
            result_json, error_dict = self._parse_llm_response(response)
            
            if error_dict:
                self.logger.error(f"LLM local environment component selection failed: {error_dict}")
                return None, None
            
            n_components = result_json.get("n_components")
            reasoning = result_json.get("reasoning", "No reasoning provided.")
            
            if isinstance(n_components, int) and 1 <= n_components <= 8:
                self.logger.info(f"LLM suggested {n_components} components for local environment GMM")
                self.logger.info(f"Reasoning: {reasoning}")
                return n_components, reasoning
            else:
                self.logger.warning(f"Invalid component number from LLM: {n_components}")
                return None, reasoning
                
        except Exception as e:
            self.logger.error(f"LLM local environment component selection failed: {e}", exc_info=True)
            return None, None

    def _run_atomistic_analysis(self, image_array: np.ndarray, model_dir_path: str, 
                                       image_blob, system_info) -> dict:
        """
        Run the complete atomistic analysis workflow.
        """
        results = {}
        
        # Step 1: Run NN ensemble to find atoms
        self.logger.info("\n\n🤖 -------------------- ANALYSIS AGENT STEP: NEURAL NETWORK ATOM DETECTION -------------------- 🤖\n")
        
        nn_output, coordinates = predict_with_ensemble(
            model_dir_path,
            image_array,
            refine=self.refine_positions,
            max_refinement_shift=self.max_refinement_shift
        )
        print()
        if coordinates is None or len(coordinates) == 0:
            self.logger.warning("No atoms detected by NN ensemble")
            return {"error": "No atoms detected"}
        
        self.logger.info(f"Detected {len(coordinates)} atomic coordinates")
        results['nn_output'] = nn_output
        results['coordinates'] = coordinates
        
        # Step 2: Analyze intensities
        self.logger.info("\n\n🤖 -------------------- ANALYSIS AGENT STEP: INTENSITY ANALYSIS -------------------- 🤖\n")
        
        intensities = extract_atomic_intensities(
            image_array, coordinates, self.intensity_box_size
        )
        intensity_hist_bytes = create_intensity_histogram_plot(intensities)
        intensity_hist_blob = {"mime_type": "image/jpeg", "data": intensity_hist_bytes}
        
        self.logger.info(f"Extracted intensities from {len(intensities)} atoms using {self.intensity_box_size}x{self.intensity_box_size} pixel boxes")
        self.logger.info(f"Intensity statistics: mean={np.mean(intensities):.3f}, std={np.std(intensities):.3f}, range=[{np.min(intensities):.3f}, {np.max(intensities):.3f}]")
        
        results['intensities'] = intensities
        results['intensity_histogram'] = intensity_hist_bytes
        
        # Step 3: LLM selects number of GMM components for intensity
        intensity_gmm_components, intensity_reasoning = self._get_intensity_gmm_components_from_llm(
            image_blob, intensity_hist_blob, system_info
        )
        
        if intensity_gmm_components is None:
            intensity_gmm_components = 3  # Default fallback
            self.logger.warning("Using default 3 components for intensity GMM")
        
        # Step 4: Do 1D GMM and plot spatial maps
        self.logger.info("\n\n🤖 -------------------- ANALYSIS AGENT STEP: 1D INTENSITY GMM ANALYSIS -------------------- 🤖\n")
        
        gmm_labels, spatial_maps = self._perform_1d_intensity_gmm(
            intensities, coordinates, image_array.shape, intensity_gmm_components
        )
        
        # Log component statistics
        for c in range(intensity_gmm_components):
            n_atoms_in_component = np.sum(gmm_labels == c)
            component_intensities = intensities[gmm_labels == c]
            if len(component_intensities) > 0:
                self.logger.info(f"Intensity component {c}: {n_atoms_in_component} atoms, mean intensity={np.mean(component_intensities):.3f}")
        
        intensity_visualizations = self._create_intensity_gmm_visualization(
            intensities, gmm_labels, spatial_maps, coordinates, image_array
        )
        
        results['intensity_gmm_labels'] = gmm_labels
        results['intensity_spatial_maps'] = spatial_maps
        results['intensity_visualizations'] = intensity_visualizations
        
        # Step 5: LLM selects components for local environment analysis
        local_env_components, local_env_reasoning = self._get_local_env_components_from_llm(
            image_blob, intensity_visualizations, system_info
        )
        
        if local_env_components is None:
            local_env_components = 4  # Default fallback
            self.logger.warning("Using default 4 components for local environment GMM")
        
        # Step 6: Local environment analysis (same as before)
        self.logger.info("\n\n🤖 -------------------- ANALYSIS AGENT STEP: LOCAL ENVIRONMENT GMM ANALYSIS -------------------- 🤖\n")
        
        # Calculate window size for local environment analysis
        window_size = self.atomistic_analysis_settings.get('window_size', 32)
        self.logger.info(f"Starting local environment analysis with {local_env_components} components and window size {window_size}px")
        
        try:
            # Use atomai's imlocal for local environment analysis
            if image_array.ndim == 2:
                expdata_reshaped = image_array[None, ..., None]
            else:
                expdata_reshaped = image_array
            
            coordinates_for_imlocal = {0: coordinates}
            self.logger.info(f"Extracting local patches around {len(coordinates)} atoms...")
            imstack = aoi.stat.imlocal(expdata_reshaped, coordinates_for_imlocal, window_size=window_size)
            
            self.logger.info(f"Running GMM clustering with {local_env_components} components...")
            centroids, _, local_env_coords_and_class = imstack.gmm(local_env_components)
            
            if local_env_coords_and_class is not None:
                local_env_coords_and_class[:, 2] = local_env_coords_and_class[:, 2] - 1  # Make 0-indexed
                
                # Log local environment statistics
                for c in range(local_env_components):
                    n_atoms_in_env = np.sum(local_env_coords_and_class[:, 2] == c)
                    self.logger.info(f"Local environment {c}: {n_atoms_in_env} atoms")
                
                self.logger.info(f"Local environment analysis completed successfully. Processed {len(local_env_coords_and_class)} atoms (out of {len(coordinates)} detected)")
            else:
                self.logger.warning("Local environment GMM returned no results")
            
            results['local_env_centroids'] = centroids
            results['local_env_coords_class'] = local_env_coords_and_class
            
        except Exception as e:
            self.logger.error(f"Local environment analysis failed: {e}")
            results['local_env_centroids'] = None
            results['local_env_coords_class'] = None
        
        # Step 7: Nearest neighbor distance analysis
        self.logger.info("\n\n🤖 -------------------- ANALYSIS AGENT STEP: NEAREST NEIGHBOR ANALYSIS -------------------- 🤖\n")
        
        if len(coordinates) > 1:
            final_coordinates_2d = coordinates[:, :2]
            nn_distances = analyze_nearest_neighbor_distances(final_coordinates_2d, pixel_scale=1.0)
            self.logger.info(f"Computed nearest neighbor distances for {len(coordinates)} atoms")
            self.logger.info(f"NN distance statistics: mean={np.mean(nn_distances):.3f}, std={np.std(nn_distances):.3f}, range=[{np.min(nn_distances):.3f}, {np.max(nn_distances):.3f}] pixels")
            results['nn_distances'] = nn_distances
        else:
            self.logger.warning("Insufficient atoms for nearest neighbor analysis (need >1 atom)")
            results['nn_distances'] = None
        
        return results

    def _create_comprehensive_visualization(self, analysis_results: dict, original_image: np.ndarray,
                                          nm_per_pixel: float = None) -> list[dict]:
        """Create comprehensive visualizations for the final LLM analysis."""
        all_visualizations = []
        
        # Add intensity analysis visualizations
        if 'intensity_visualizations' in analysis_results:
            all_visualizations.extend(analysis_results['intensity_visualizations'])
        
        # Add local environment visualizations (if available)
        if analysis_results.get('local_env_centroids') is not None:
            local_env_viz = self._create_local_env_visualization(
                original_image, 
                analysis_results['local_env_centroids'],
                analysis_results['local_env_coords_class']
            )
            all_visualizations.extend(local_env_viz)
        
        # Add nearest neighbor visualizations (if available)
        if analysis_results.get('nn_distances') is not None:
            nn_viz = self._create_nn_distance_visualization(
                original_image,
                analysis_results['coordinates'],
                analysis_results['nn_distances'],
                nm_per_pixel
            )
            all_visualizations.extend(nn_viz)
        
        return all_visualizations

    def _create_local_env_visualization(self, original_image: np.ndarray, centroids: np.ndarray,
                                      coords_class: np.ndarray) -> list[dict]:
        """Create visualizations for local environment GMM results."""
        visualizations = []
        n_components = centroids.shape[0]
        
        # 1. GMM Centroids - only show non-empty components
        actual_components = []
        component_counts = []
        
        # Check which components actually have atoms assigned
        for i in range(n_components):
            count = np.sum(coords_class[:, 2] == i)
            if count > 0:
                actual_components.append(i)
                component_counts.append(count)
        
        if len(actual_components) == 0:
            self.logger.warning("No atoms assigned to any local environment component")
            return visualizations
        
        # Create subplot grid for actual components only
        n_actual = len(actual_components)
        n_cols = min(4, n_actual)
        n_rows = (n_actual + n_cols - 1) // n_cols
        
        fig, axes = plt.subplots(n_rows, n_cols, figsize=(n_cols * 2.5, n_rows * 2.5))
        if n_actual == 1:
            axes = np.array([axes])
        elif n_rows == 1:
            axes = axes.reshape(1, -1)
        axes = axes.flatten()
        
        # Calculate global normalization for consistent scaling
        global_min = np.min(centroids[actual_components])
        global_max = np.max(centroids[actual_components])
        
        for idx, comp_idx in enumerate(actual_components):
            axes[idx].imshow(centroids[comp_idx, :, :, 0], cmap='viridis', 
                           vmin=global_min, vmax=global_max)
            axes[idx].set_title(f'Local Env Class {comp_idx}\n({component_counts[idx]} atoms)')
            axes[idx].axis('off')
        
        # Hide unused subplots
        for idx in range(n_actual, len(axes)):
            axes[idx].axis('off')
        
        fig.suptitle("Local Environment GMM Centroids")
        plt.tight_layout()
        
        buf = BytesIO()
        plt.savefig(buf, format='jpeg', dpi=150, bbox_inches='tight')
        buf.seek(0)
        visualizations.append({'label': 'Local Environment Centroids', 'bytes': buf.getvalue()})
        plt.close()
        
        # 2. Classified atom map - use high contrast colors
        fig, ax = plt.subplots(figsize=(10, 10))
        ax.imshow(original_image, cmap='gray')
        
        # Use distinct, high-contrast colors
        colors = ['red', 'cyan', 'lime', 'yellow', 'magenta', 'orange', 'white', 'lightblue']
        
        for idx, comp_idx in enumerate(actual_components):
            class_coords = coords_class[coords_class[:, 2] == comp_idx]
            if len(class_coords) > 0:
                color = colors[idx % len(colors)]
                ax.scatter(class_coords[:, 1], class_coords[:, 0], 
                          color=color, s=20, alpha=0.9, edgecolors='black', linewidth=0.3,
                          label=f'Local Env {comp_idx} ({len(class_coords)} atoms)')
        
        ax.legend(loc='upper right', frameon=True, fancybox=True, shadow=True)
        ax.set_title("Local Environment Classification")
        ax.axis('off')
        
        buf = BytesIO()
        plt.savefig(buf, format='jpeg', dpi=150, bbox_inches='tight')
        buf.seek(0)
        visualizations.append({'label': 'Local Environment Classification Map', 'bytes': buf.getvalue()})
        plt.close()
        
        return visualizations

    def _create_nn_distance_visualization(self, original_image: np.ndarray, coordinates: np.ndarray,
                                        nn_distances: np.ndarray, nm_per_pixel: float = None) -> list[dict]:
        """Create nearest neighbor distance visualizations."""
        visualizations = []
        
        # Distance units
        units = "nm" if nm_per_pixel else "pixels"
        scale = nm_per_pixel if nm_per_pixel else 1.0
        scaled_distances = nn_distances * scale
        
        # 1. Distance map
        fig, ax = plt.subplots(figsize=(8, 8))
        ax.imshow(original_image, cmap='gray')
        
        scatter = ax.scatter(coordinates[:, 1], coordinates[:, 0], 
                           c=scaled_distances, cmap='inferno', s=10, alpha=0.9)
        cbar = fig.colorbar(scatter, ax=ax, fraction=0.046, pad=0.04)
        cbar.set_label(f'Nearest-Neighbor Distance ({units})')
        
        ax.set_title("Nearest-Neighbor Distance Map")
        ax.axis('off')
        
        buf = BytesIO()
        plt.savefig(buf, format='jpeg', dpi=150, bbox_inches='tight')
        buf.seek(0)
        visualizations.append({'label': 'NN Distance Map', 'bytes': buf.getvalue()})
        plt.close()
        
        # 2. Distance histogram
        fig, ax = plt.subplots(figsize=(12, 4))
        ax.hist(scaled_distances, bins='auto', color='skyblue', edgecolor='black')
        ax.set_xlabel(f"Distance ({units})")
        ax.set_ylabel("Frequency")
        ax.set_title("Nearest-Neighbor Distance Distribution")
        
        buf = BytesIO()
        plt.savefig(buf, format='jpeg', dpi=150, bbox_inches='tight')
        buf.seek(0)
        visualizations.append({'label': 'NN Distance Histogram', 'bytes': buf.getvalue()})
        plt.close()
        
        return visualizations

    def _save_visualization_to_disk(self, image_bytes: bytes, label: str):
        """Save visualization to disk."""
        if self.save_visualizations:
            try:
                from datetime import datetime
                output_dir = "atomistic_analysis_visualizations"
                os.makedirs(output_dir, exist_ok=True)
                
                timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
                filename = f"{label.replace(' ', '_').replace('(', '').replace(')', '')}_{timestamp}.jpeg"
                filepath = os.path.join(output_dir, filename)
                
                with open(filepath, 'wb') as f:
                    f.write(image_bytes)
                
                self.logger.info(f"📸 Saved visualization: {filepath}")
            except Exception as e:
                self.logger.error(f"Failed to save visualization: {e}")

    def _analyze_image_base(self, image_path: str, system_info: dict | str | None,
                          instruction_prompt: str, 
                          additional_top_level_context: str | None = None) -> tuple[dict | None, dict | None]:
        """
        Analysis workflow
        """
        try:
            # Clear any previous stored images
            self._clear_stored_images()
            # Use base class methods for common operations
            system_info = self._handle_system_info(system_info)
            loaded_image = load_image(image_path)
            nm_per_pixel, fov_in_nm = self._calculate_spatial_scale(system_info, loaded_image.shape)

            # Rescale image for optimal NN performance
            image_for_analysis = loaded_image
            if fov_in_nm is not None:
                rescaled_image, _, final_pixel_size_A = rescale_for_model(image_for_analysis, fov_in_nm)
                image_for_analysis = rescaled_image
                nm_per_pixel = final_pixel_size_A / 10.0
                self.logger.info(f"Image rescaled for optimal NN performance. New pixel size: {nm_per_pixel*10:.3f} Å/px.")
            else:
                self.logger.warning("Field of view not provided. Skipping image rescaling.")

            # Preprocess the image
            preprocessed_img_array, _ = preprocess_image(image_for_analysis)
            self.original_preprocessed_image = preprocessed_img_array

            # Create image blob for LLM
            image_bytes = convert_numpy_to_jpeg_bytes(preprocessed_img_array)
            image_blob = {"mime_type": "image/jpeg", "data": image_bytes}

            # Get model path
            model_dir_path = self._get_or_download_model_path()
            if not model_dir_path:
                return None, {"error": "DCNN model directory not available"}

            # Run the atomistic analysis workflow
            self.logger.info(f"Using DCNN models from: {model_dir_path}")
            analysis_results = self._run_atomistic_analysis(
                preprocessed_img_array, model_dir_path, image_blob, system_info
            )

            if "error" in analysis_results:
                return None, analysis_results

            # Create comprehensive visualizations for final LLM analysis
            self.logger.info("\n\n🤖 -------------------- ANALYSIS AGENT STEP: CREATING COMPREHENSIVE VISUALIZATIONS -------------------- 🤖\n")
            
            all_visualizations = self._create_comprehensive_visualization(
                analysis_results, preprocessed_img_array, nm_per_pixel
            )

            # Save visualizations to disk if enabled
            for viz in all_visualizations:
                self._save_visualization_to_disk(viz['bytes'], viz['label'])

            analysis_images = []
            for viz in all_visualizations:
                analysis_images.append({
                    "label": viz['label'],
                    "data": viz['bytes']
                })

            analysis_metadata = {
                "image_path": image_path,
                "system_info": system_info,
                "atoms_detected": len(analysis_results.get('coordinates', [])),
                "num_visualizations": len(all_visualizations),
                "num_stored_images": len(analysis_images)
            }
            self._store_analysis_images(analysis_images, analysis_metadata)

            # Build prompt for final LLM analysis
            prompt_parts = [instruction_prompt]
            
            if additional_top_level_context:
                prompt_parts.append("\n\n## Special Considerations for This Analysis (Based on Prior Review):\n")
                prompt_parts.append(additional_top_level_context)
                prompt_parts.append("\nPlease ensure your analysis specifically addresses these considerations.\n")
            
            # Add original image
            analysis_request_text = "\nPlease analyze the following atomic-resolution microscopy image"
            if system_info: 
                analysis_request_text += " using the additional context provided."
            analysis_request_text += "\n\nPrimary Microscopy Image:\n"
            prompt_parts.append(analysis_request_text)
            prompt_parts.append(image_blob)

            # Add comprehensive analysis results
            prompt_parts.append("\n\nComprehensive Atomistic Analysis Results:")
            
            # Add analysis summary
            summary_text = f"""
Analysis Summary:
- Total atoms detected: {len(analysis_results.get('coordinates', []))}
- Intensity analysis: {len(analysis_results.get('intensities', []))} intensity values extracted
- Intensity GMM components: {analysis_results['intensity_spatial_maps'].shape[2] if 'intensity_spatial_maps' in analysis_results else 'N/A'}
- Local environment GMM components: {analysis_results['local_env_centroids'].shape[0] if analysis_results.get('local_env_centroids') is not None else 'N/A'}
- Nearest neighbor analysis: {'Completed' if analysis_results.get('nn_distances') is not None else 'Skipped (insufficient atoms)'}
"""
            prompt_parts.append(summary_text)

            # Add all visualizations
            for viz in all_visualizations:
                prompt_parts.append(f"\n{viz['label']}:")
                prompt_parts.append({"mime_type": "image/jpeg", "data": viz['bytes']})

            # Add system info
            system_info_section = self._build_system_info_prompt_section(system_info)
            if system_info_section:
                prompt_parts.append(system_info_section)
            
            prompt_parts.append("\n\nProvide your analysis strictly in the requested JSON format.")
            
            # Final LLM analysis
            self.logger.info("\n\n🤖 -------------------- ANALYSIS AGENT STEP: FINAL COMPREHENSIVE ANALYSIS -------------------- 🤖\n")
            response = self.model.generate_content(
                contents=prompt_parts,
                generation_config=self.generation_config,
                safety_settings=self.safety_settings,
            )
            
            return self._parse_llm_response(response)

        except FileNotFoundError:
            self._clear_stored_images()
            self.logger.error(f"Image file not found: {image_path}")
            return None, {"error": "Image file not found", "details": f"Path: {image_path}"}
        except Exception as e:
            self._clear_stored_images()
            self.logger.exception(f"Atomistic analysis failed: {e}")
            return None, {"error": "Atomistic analysis failed", "details": str(e)}

    # Keep the existing methods for getting/downloading model path
    def _get_or_download_model_path(self) -> str | None:
        """
        Manages finding or downloading the DCNN models.
        """
        user_provided_path = self.atomistic_analysis_settings.get('model_dir_path')

        if user_provided_path:
            if not os.path.isdir(user_provided_path):
                self.logger.error(f"The provided 'model_dir_path' ('{user_provided_path}') does not exist.")
                return None
            self.logger.info(f"Using user-provided model path: {user_provided_path}")
            return user_provided_path
        
        default_path = self.DEFAULT_MODEL_DIR

        if not os.path.isdir(default_path):
            self.logger.warning(f"Default model directory '{default_path}' not found. Downloading...")
            zip_filename = f"{self.DEFAULT_MODEL_DIR}.zip"
            
            downloaded_zip_path = download_file_with_gdown(self.DCNN_MODEL_GDRIVE_ID, zip_filename)
            
            if not downloaded_zip_path or not os.path.exists(downloaded_zip_path):
                self.logger.error("Failed to download the model.")
                return None

            unzip_success = unzip_file(downloaded_zip_path, default_path)
            
            try:
                os.remove(downloaded_zip_path)
                self.logger.info(f"Cleaned up downloaded zip file: {downloaded_zip_path}")
            except OSError as e:
                self.logger.warning(f"Could not remove zip file {downloaded_zip_path}: {e}")

            if not unzip_success:
                self.logger.error(f"Failed to unzip model from '{downloaded_zip_path}'.")
                return None
        
        try:
            if glob.glob(os.path.join(default_path, 'atomnet3*.tar')):
                return default_path
            
            for item in os.listdir(default_path):
                sub_path = os.path.join(default_path, item)
                if os.path.isdir(sub_path) and glob.glob(os.path.join(sub_path, 'atomnet3*.tar')):
                    self.logger.info(f"Found models in nested directory: {sub_path}")
                    return sub_path
        except FileNotFoundError:
            self.logger.error(f"The model directory '{default_path}' does not exist.")
        
        self.logger.error(f"Could not find model files in '{default_path}' or subdirectories.")
        return None

    # Keep existing public interface methods but update them to use the new workflow
    def analyze_microscopy_image_for_claims(self, image_path: str, system_info: dict | str | None = None):
        """
        Analyze microscopy image to generate scientific claims
        """
        result_json, error_dict = self._analyze_image_base(
            image_path, system_info, ATOMISTIC_MICROSCOPY_CLAIMS_INSTRUCTIONS
        )

        if error_dict:
            return error_dict
        if result_json is None:
            return {"error": "Atomistic analysis for claims failed unexpectedly."}

        detailed_analysis = result_json.get("detailed_analysis", "Analysis not provided by LLM.")
        scientific_claims = result_json.get("scientific_claims", [])
        
        valid_claims = self._validate_scientific_claims(scientific_claims)

        if not valid_claims and not detailed_analysis == "Analysis not provided by LLM.":
            self.logger.warning("Analysis successful but no valid claims found.")
        elif not valid_claims:
            self.logger.warning("LLM did not yield valid claims or analysis text.")

        initial_result = {"detailed_analysis": detailed_analysis, "scientific_claims": valid_claims}
        return self._apply_feedback_if_enabled(
            initial_result,
            image_path=image_path,
            system_info=system_info
        )
    
    def analyze_microscopy_image_for_structure_recommendations(
            self,
            image_path: str | None = None,
            system_info: dict | str | None = None,
            additional_prompt_context: str | None = None,
            cached_detailed_analysis: str | None = None
    ):
        """
        Analyze atomistic microscopy image for DFT structure recommendations.
        """
        result_json, error_dict = None, None
        output_analysis_key = "detailed_analysis"

        # Text-Only path (delegate to RecommendationAgent)
        if cached_detailed_analysis and additional_prompt_context:
            self.logger.info("Delegating DFT recommendations to RecommendationAgent.")

            if not self._recommendation_agent:
                self._recommendation_agent = RecommendationAgent(self.google_api_key, self.model_name)
            
            return self._recommendation_agent.generate_dft_recommendations_from_text(
                cached_detailed_analysis=cached_detailed_analysis,
                additional_prompt_context=additional_prompt_context,
                system_info=system_info
            )
        
        # Image-Based path
        elif image_path:
            self.logger.info("Generating DFT recommendations from atomistic analysis.")
            result_json, error_dict = self._analyze_image_base(
                image_path, system_info, ATOMISTIC_MICROSCOPY_ANALYSIS_INSTRUCTIONS, 
                additional_top_level_context=additional_prompt_context
            )
        else:
            return {"error": "Either image_path or (cached_detailed_analysis AND additional_prompt_context) must be provided."}

        if error_dict:
            return error_dict
        if result_json is None:
            return {"error": "Atomistic analysis failed unexpectedly."}

        analysis_output_text = result_json.get(output_analysis_key, "Analysis not provided by LLM.")
        recommendations = result_json.get("structure_recommendations", [])
        
        sorted_recommendations = self._validate_structure_recommendations(recommendations)

        if not sorted_recommendations and not analysis_output_text == "Analysis not provided by LLM.":
            self.logger.warning("Analysis successful but no valid recommendations found.")
        elif not sorted_recommendations:
            self.logger.warning("LLM did not yield valid recommendations or analysis text.")

        return {"analysis_summary_or_reasoning": analysis_output_text, "recommendations": sorted_recommendations}
    
    def _get_claims_instruction_prompt(self) -> str:
        return ATOMISTIC_MICROSCOPY_CLAIMS_INSTRUCTIONS
    
    def _get_measurement_recommendations_prompt(self) -> str:
        return ATOMISTIC_MEASUREMENT_RECOMMENDATIONS_INSTRUCTIONS


================================================
File: agents/exp_agents/base_agent.py
================================================
import json
import logging

import google.generativeai as genai
from google.generativeai.types import GenerationConfig, HarmCategory, HarmBlockThreshold

from ...auth import get_api_key, APIKeyNotFoundError


class BaseAnalysisAgent:
    """
    Base class for analysis agents
    """
    
    def __init__(self, google_api_key: str | None = None, model_name: str = "gemini-2.5-pro-preview-06-05", local_model: str = None):
        if local_model is not None:
            logging.info(f"💻 Using local agent as the analysis agent.")
            from .llama_wrapper import LocalLlamaModel
            self.model = LocalLlamaModel(local_model)
            self.generation_config = None
            self.safety_settings = None
            self.model_name = local_model
        else:
            logging.info(f"☁️ Using cloud agent as the analysis agent.")
            # Auto-discover API key
            if google_api_key is None:
                google_api_key = get_api_key('google')
                if not google_api_key:
                    raise APIKeyNotFoundError('google')
            genai.configure(api_key=google_api_key)
        
            self.model = genai.GenerativeModel(model_name)
            self.generation_config = GenerationConfig(response_mime_type="application/json")
            self.safety_settings = {
                HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
            }
            self.model_name = model_name
            
        self.logger = logging.getLogger(__name__)
        self.google_api_key = google_api_key 
        
        self._stored_analysis_images = []
        self._stored_analysis_metadata = {}

    def _parse_llm_response(self, response) -> tuple[dict | None, dict | None]:
        """
        Parses the LLM response, expecting JSON.
        Shared implementation used by all agents.
        """
        result_json = None
        error_dict = None
        raw_text = None
        json_string = None

        try:
            raw_text = response.text
            first_brace_index = raw_text.find('{')
            last_brace_index = raw_text.rfind('}')
            if first_brace_index != -1 and last_brace_index != -1 and last_brace_index > first_brace_index:
                json_string = raw_text[first_brace_index : last_brace_index + 1]
                result_json = json.loads(json_string)
            else:
                raise ValueError("Could not find valid JSON object delimiters '{' and '}' in the response text.")

        except (json.JSONDecodeError, AttributeError, IndexError, ValueError) as e:
            error_details = str(e)
            error_raw_response = raw_text if raw_text is not None else getattr(response, 'text', 'N/A')
            self.logger.error(f"Error parsing LLM JSON response: {e}")
            parsed_substring_for_log = json_string if json_string else 'N/A'
            self.logger.debug(f"Attempted to parse substring: {parsed_substring_for_log[:500]}...")
            self.logger.debug(f"Original Raw response text: {error_raw_response[:500]}...")

            if hasattr(response, 'prompt_feedback') and response.prompt_feedback.block_reason:
                block_reason = response.prompt_feedback.block_reason
                self.logger.error(f"Request blocked due to: {block_reason}")
                error_dict = {"error": f"Content blocked by safety filters", "details": f"Reason: {block_reason}"}
            elif response.candidates and response.candidates[0].finish_reason != 1: # 1 == Stop
                finish_reason = response.candidates[0].finish_reason
                self.logger.error(f"Generation finished unexpectedly: {finish_reason}")
                error_dict = {"error": f"Generation finished unexpectedly: {finish_reason}", "details": error_details, "raw_response": error_raw_response}
            else:
                error_dict = {"error": "Failed to parse valid JSON from LLM response", "details": error_details, "raw_response": error_raw_response}
        except Exception as e:
            self.logger.exception(f"Unexpected error processing response: {e}")
            error_dict = {"error": "Unexpected error processing LLM response", "details": str(e)}
        
        return result_json, error_dict

    def _generate_json_from_text_parts(self, prompt_parts: list) -> tuple[dict | None, dict | None]:
        """
        Internal helper to generate JSON from a list of textual prompt parts.
        Shared implementation used by multiple agents.
        """
        try:
            self.logger.debug(f"Sending text-only prompt to LLM. Total parts: {len(prompt_parts)}")
            response = self.model.generate_content(
                contents=prompt_parts,
                generation_config=self.generation_config,
                safety_settings=self.safety_settings,
            )
            return self._parse_llm_response(response)
        except Exception as e:
            self.logger.exception(f"An unexpected error occurred during text-based LLM call: {e}")
            return None, {"error": "An unexpected error occurred during text-based LLM call", "details": str(e)}

    def _handle_system_info(self, system_info: dict | str | None) -> dict:
        """
        Handle system_info input (can be dict, file path, or None).
        Converts to dict format for consistent processing.
        """
        if isinstance(system_info, str):
            try:
                with open(system_info, 'r') as f:
                    system_info = json.load(f)
            except (FileNotFoundError, json.JSONDecodeError) as e:
                self.logger.error(f"Error loading system_info from {system_info}: {e}")
                system_info = {} # Proceed without system info if loading fails
        elif system_info is None:
            system_info = {} # Ensure it's a dict for easier access later
        
        return system_info

    def _find_spatial_info(self, data: dict) -> dict | None:
        """
        Recursively search for spatial_info in a nested dictionary structure.
        
        Args:
            data: Dictionary to search through
            
        Returns:
            The spatial_info dictionary if found, None otherwise
        """
        if not isinstance(data, dict):
            return None
        
        # Check if spatial_info exists at current level
        if 'spatial_info' in data and isinstance(data['spatial_info'], dict):
            return data['spatial_info']
        
        # Recursively search through all nested dictionaries
        for key, value in data.items():
            if isinstance(value, dict):
                result = self._find_spatial_info(value)
                if result is not None:
                    return result
        
        return None

    def _calculate_spatial_scale(self, system_info: dict, image_shape: tuple) -> tuple[float | None, float | None]:
        """
        Calculate nm/pixel and field of view from system metadata.
        
        Args:
            system_info: Dictionary containing spatial metadata (can be nested anywhere)
            image_shape: (height, width) of the loaded image
            
        Returns:
            tuple: (nm_per_pixel, fov_in_nm) or (None, None) if calculation fails
        """
        # Determine physical scale (nm/pixel) from metadata, mirroring spectroscopy agent's approach
        nm_per_pixel = None
        fov_in_nm = None
        
        # Search for spatial_info anywhere in the nested structure
        spatial = self._find_spatial_info(system_info)
        
        if spatial is not None:
            fov_x = spatial.get("field_of_view_x")
            units = spatial.get("field_of_view_units", "nm")  # Default to nm

            if fov_x is not None and isinstance(fov_x, (int, float)) and fov_x > 0:
                h, w = image_shape[:2]
                
                # Convert provided units to nm for consistent calculations
                scale_to_nm = 1.0
                if units.lower() in ['um', 'micrometer', 'micrometers']:
                    scale_to_nm = 1000.0
                elif units.lower() in ['a', 'angstrom', 'angstroms']:
                    scale_to_nm = 0.1
                
                fov_in_nm = fov_x * scale_to_nm
                
                if w > 0:
                    nm_per_pixel = fov_in_nm / w
                    self.logger.info(f"Found spatial_info and calculated nm/pixel: {fov_x} {units} / {w} px = {nm_per_pixel:.4f} nm/pixel")
                else:
                    self.logger.warning("Cannot calculate scale from FOV because image width is 0.")
            else:
                self.logger.warning(f"Invalid or missing 'field_of_view_x' in spatial_info: {fov_x}. Physical scale not applied.")
        else:
            self.logger.info("No spatial_info found in system metadata. Physical scale not applied.")
        
        return nm_per_pixel, fov_in_nm

    def _validate_scientific_claims(self, scientific_claims: list) -> list:
        """
        Validate scientific claims structure and content.
        Shared validation logic used by all agents that generate claims.
        """
        valid_claims = []

        if not isinstance(scientific_claims, list):
            self.logger.warning(f"'scientific_claims' from LLM was not a list: {scientific_claims}")
            return valid_claims

        for claim in scientific_claims:
            if isinstance(claim, dict) and all(k in claim for k in ["claim", "scientific_impact", "has_anyone_question", "keywords"]):
                if isinstance(claim.get("keywords"), list):
                    valid_claims.append(claim)
                else:
                    self.logger.warning(f"Claim skipped due to 'keywords' not being a list: {claim}")
            else:
                self.logger.warning(f"Claim skipped due to missing keys or incorrect dict format: {claim}")
        
        return valid_claims

    def _validate_structure_recommendations(self, recommendations: list) -> list:
        """
        Validate and sort structure recommendations.
        Shared validation logic used by all agents that generate recommendations.
        """
        valid_recommendations = []
        
        if not isinstance(recommendations, list):
            self.logger.warning(f"'structure_recommendations' from LLM was not a list: {recommendations}")
            return valid_recommendations

        for rec in recommendations:
            if isinstance(rec, dict) and all(k in rec for k in ["description", "scientific_interest", "priority"]):
                if isinstance(rec.get("priority"), int):
                    valid_recommendations.append(rec)
                else:
                    self.logger.warning(f"Recommendation skipped due to invalid priority type (expected int): {rec.get('priority')}. Recommendation: {rec}")
            else:
                self.logger.warning(f"Recommendation skipped due to missing keys or incorrect dict format: {rec}")
        
        # Sort by priority (1 = highest priority)
        sorted_recommendations = sorted(valid_recommendations, key=lambda x: x.get("priority", 99))
        return sorted_recommendations

    def _build_system_info_prompt_section(self, system_info: dict) -> str:
        """
        Build the system information section for LLM prompts.
        """
        if not system_info:
            return ""
            
        system_info_text = "\n\nAdditional System Information (Metadata):\n"
        if isinstance(system_info, dict):
            system_info_text += json.dumps(system_info, indent=2)
        else:
            system_info_text += str(system_info)
        
        return system_info_text
    
    def _store_analysis_images(self, images: list, metadata: dict = None):
        """Store analysis images for potential reuse in refinement."""
        self._stored_analysis_images = images.copy() if images else []
        self._stored_analysis_metadata = metadata or {}
        self.logger.debug(f"Stored {len(self._stored_analysis_images)} analysis images for potential refinement")
    
    def _get_stored_analysis_images(self) -> list:
        """Retrieve stored analysis images."""
        return self._stored_analysis_images.copy()
    
    def _clear_stored_images(self):
        """Clear stored images to free memory."""
        self._stored_analysis_images = []
        self._stored_analysis_metadata = {}

    def _refine_analysis_with_feedback(self, original_analysis: str, 
                                     original_claims: list, 
                                     user_feedback: str,
                                     instruction_prompt: str,
                                     stored_images: list = None,
                                     system_info: dict = None) -> dict:
        """Use LLM to refine analysis and claims based on user feedback."""
        try:
            # Create refinement prompt
            refinement_prompt = f"""
    {instruction_prompt}

    ## REFINEMENT TASK
    You previously generated this analysis and claims:

    ORIGINAL DETAILED ANALYSIS:
    {original_analysis}

    ORIGINAL CLAIMS:
    {json.dumps(original_claims, indent=2)}

    A human expert provided this feedback:
    "{user_feedback}"

    Use this feedback *thoughtfully* to refine both the detailed analysis and scientific claims. 
    Maintain the same JSON output format with "detailed_analysis" and "scientific_claims" keys.
    """
            
            prompt_parts = [refinement_prompt]
            
            # Add stored images
            if stored_images:
                for img_data in stored_images:
                    if isinstance(img_data, dict) and 'label' in img_data and 'data' in img_data:
                        prompt_parts.append(f"\n{img_data['label']}:")
                        prompt_parts.append({"mime_type": "image/jpeg", "data": img_data['data']})
                    elif isinstance(img_data, dict) and img_data.get("mime_type") == "image/jpeg":
                        prompt_parts.append("\nAnalysis image:")
                        prompt_parts.append(img_data)
            
            # Add system info
            if system_info:
                system_info_section = self._build_system_info_prompt_section(system_info)
                if system_info_section:
                    prompt_parts.append(system_info_section)
            
            prompt_parts.append("\nProvide the refined analysis in JSON format.")
            
            # Query LLM for refinement
            self.logger.info("🔄 Refining analysis using stored images...")
            response = self.model.generate_content(
                contents=prompt_parts,
                generation_config=self.generation_config,
                safety_settings=self.safety_settings,
            )
            
            result_json, error_dict = self._parse_llm_response(response)
            
            if error_dict:
                return {"error": "Refinement failed", "details": error_dict}
            
            # Validate refined claims
            refined_claims = result_json.get("scientific_claims", [])
            validated_claims = self._validate_scientific_claims(refined_claims)
            
            self.logger.info(f"Refinement complete: {len(validated_claims)} validated claims")
            
            return {
                "detailed_analysis": result_json.get("detailed_analysis", original_analysis),
                "scientific_claims": validated_claims
            }
            
        except Exception as e:
            self.logger.error(f"Analysis refinement failed: {e}")
            return {"error": "Refinement failed", "details": str(e)}
        
    def _validate_measurement_recommendations(self, recommendations: list) -> list:
        """Simple validation of measurement recommendations."""
        valid_recommendations = []
        
        if not isinstance(recommendations, list):
            return valid_recommendations
        
        required_keys = ["description", "scientific_justification", "priority"]
        
        for rec in recommendations:
            if isinstance(rec, dict) and all(k in rec for k in required_keys):
                # Simple validation
                if isinstance(rec.get("priority"), int) and 1 <= rec.get("priority") <= 5:
                    valid_recommendations.append(rec)
        
        # Sort by priority
        return sorted(valid_recommendations, key=lambda x: x.get("priority", 5))
    
    def generate_measurement_recommendations(self, analysis_result: dict, 
                                           system_info: dict = None,
                                           novelty_context: str = None) -> dict:
        """
        Generate measurement recommendations using existing analysis results and stored images.
        """
        if "error" in analysis_result:
            return {"error": "Cannot generate recommendations from failed analysis"}
        
        try:
            # Get agent-specific prompt
            instruction_prompt = self._get_measurement_recommendations_prompt()
            
            # Build simple prompt using existing data
            prompt_parts = [instruction_prompt]
            
            # Add analysis results (what's already available)
            prompt_parts.append("\n\n--- Analysis Results ---")
            
            if "detailed_analysis" in analysis_result:
                prompt_parts.append(f"Detailed Analysis:\n{analysis_result['detailed_analysis']}")
            
            if "scientific_claims" in analysis_result:
                prompt_parts.append(f"\nScientific Claims:")
                for i, claim in enumerate(analysis_result["scientific_claims"], 1):
                    prompt_parts.append(f"{i}. {claim.get('claim', 'N/A')}")
            
            # Add stored images (what's already available from the analysis)
            stored_images = self._get_stored_analysis_images()
            if stored_images:
                prompt_parts.append(f"\n\nAnalysis Images:")
                for img_data in stored_images[:3]:  # Limit to 3 images
                    if isinstance(img_data, dict) and 'label' in img_data and 'data' in img_data:
                        prompt_parts.append(f"\n{img_data['label']}:")
                        prompt_parts.append({"mime_type": "image/jpeg", "data": img_data['data']})
            
            # Add optional context
            if novelty_context:
                prompt_parts.append(f"\n\nNovelty Context: {novelty_context}")
            
            if system_info:
                system_info_section = self._build_system_info_prompt_section(system_info)
                if system_info_section:
                    prompt_parts.append(system_info_section)
            
            prompt_parts.append("\n\nProvide measurement recommendations in JSON format.")
            
            # Query LLM
            response = self.model.generate_content(
                contents=prompt_parts,
                generation_config=self.generation_config,
                safety_settings=self.safety_settings,
            )
            
            result_json, error_dict = self._parse_llm_response(response)
            
            if error_dict:
                return {"error": "Recommendation generation failed", "details": error_dict}
            
            # Validate recommendations
            recommendations = result_json.get("measurement_recommendations", [])
            valid_recommendations = self._validate_measurement_recommendations(recommendations)
            
            return {
                "analysis_integration": result_json.get("analysis_integration", ""),
                "measurement_recommendations": valid_recommendations,
                "total_recommendations": len(valid_recommendations)
            }
            
        except Exception as e:
            self.logger.error(f"Recommendation generation failed: {e}")
            return {"error": "Recommendation generation failed", "details": str(e)}

    def _get_measurement_recommendations_prompt(self) -> str:
        """Must be implemented by each agent."""
        raise NotImplementedError("Each agent must implement this method")


================================================
File: agents/exp_agents/human_feedback.py
================================================
# exp_agents/human_feedback.py
import json
import logging
from typing import Dict, List, Any, Optional
from datetime import datetime


class SimpleFeedbackCollector:
    """Simple feedback collector for refining analysis results"""
    
    def __init__(self, logger: Optional[logging.Logger] = None):
        self.logger = logger or logging.getLogger(__name__)
    
    def collect_optional_feedback(self, analysis_result: Dict[str, Any]) -> Optional[str]:
        """Intuitive feedback collection that handles natural user behavior."""
        detailed_analysis = analysis_result.get("detailed_analysis", "No analysis provided")
        claims = analysis_result.get("scientific_claims", [])
        
        print("\n" + "="*80)
        print("🔬 ANALYSIS RESULTS")
        print("="*80)
        
        # Display detailed analysis
        print("\n📋 DETAILED ANALYSIS:")
        print("-" * 40)
        print(detailed_analysis)
        
        # Display claims
        print(f"\n🎯 SCIENTIFIC CLAIMS ({len(claims)} generated):")
        print("-" * 40)
        
        if not claims:
            print("❌ No claims were generated.")
        else:
            for i, claim in enumerate(claims, 1):
                print(f"\nCLAIM {i}:")
                print(f"  Statement: {claim.get('claim', 'N/A')}")
                print(f"  Impact: {claim.get('scientific_impact', 'N/A')}")
                print(f"  Research Question: {claim.get('has_anyone_question', 'N/A')}")
                print(f"  Keywords: {', '.join(claim.get('keywords', []))}")
        
        print("\n" + "="*80)
        
        try:
            # Single, clear prompt that accepts feedback directly
            feedback_text = input("\n🤔 Your feedback (or press Enter to use analysis as-is): ").strip()
            
            if not feedback_text:
                print("✅ No feedback provided. Using analysis as-is.")
                return None
            
            print(f"\n✅ Feedback collected ({len(feedback_text)} characters)")
            return feedback_text
            
        except KeyboardInterrupt:
            print("\n\n⚠️  Interrupted. Using original analysis.")
            return None
        except Exception as e:
            self.logger.error(f"Error collecting feedback: {e}")
            return None
    
    def save_feedback_log(self, original_result: Dict[str, Any], 
                         feedback: str, 
                         refined_result: Dict[str, Any] = None,
                         output_dir: str = "feedback_logs") -> str:
        """Save feedback session for audit trail."""
        import os
        
        os.makedirs(output_dir, exist_ok=True)
        
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        log_file = os.path.join(output_dir, f"feedback_log_{timestamp}.json")
        
        log_data = {
            "timestamp": datetime.now().isoformat(),
            "original_result": original_result,
            "user_feedback": feedback,
            "refined_result": refined_result,
            "session_summary": {
                "feedback_provided": feedback is not None,
                "feedback_length": len(feedback) if feedback else 0,
                "original_claims_count": len(original_result.get("scientific_claims", [])),
                "refined_claims_count": len(refined_result.get("scientific_claims", [])) if refined_result else 0
            }
        }
        
        with open(log_file, 'w') as f:
            json.dump(log_data, f, indent=2)
        
        self.logger.info(f"Feedback log saved: {log_file}")
        return log_file


class SimpleFeedbackMixin:
    """Mixin to add feedback capabilities to existing analysis agents."""
    
    def __init__(self, *args, enable_human_feedback: bool = False, **kwargs):
        super().__init__(*args, **kwargs)
        self.enable_human_feedback = enable_human_feedback
        self._feedback_collector = None
    
    def _get_feedback_collector(self) -> SimpleFeedbackCollector:
        """Lazy initialization of feedback collector."""
        if self._feedback_collector is None:
            self._feedback_collector = SimpleFeedbackCollector(self.logger)
        return self._feedback_collector
    
    def _apply_feedback_if_enabled(self, claims_result: Dict[str, Any], 
                                  **refinement_kwargs) -> Dict[str, Any]:
        """Apply human feedback to refine analysis if enabled."""
        if not self.enable_human_feedback:
            return claims_result
        
        if "error" in claims_result:
            return claims_result
        
        try:
            feedback_collector = self._get_feedback_collector()
            
            # Collect optional feedback
            user_feedback = feedback_collector.collect_optional_feedback(claims_result)
            
            if not user_feedback:
                return claims_result
            
            self.logger.info("🔄 Refining analysis based on user feedback...")
            
            # Use the common refinement method
            refined_result = self._refine_with_feedback(
                claims_result, user_feedback, **refinement_kwargs
            )
            
            if "error" in refined_result:
                self.logger.error("Refinement failed, using original analysis")
                return claims_result
            
            # Add feedback metadata
            refined_result["human_feedback"] = {
                "feedback_provided": True,
                "user_feedback": user_feedback,
                "refinement_applied": True
            }
            
            # Save feedback log
            feedback_collector.save_feedback_log(
                claims_result, user_feedback, refined_result
            )
            
            print("✅ Analysis refined based on your feedback!")
            return refined_result
            
        except Exception as e:
            self.logger.error(f"Feedback processing failed: {e}")
            return claims_result
    
    def _refine_with_feedback(self, original_result: Dict[str, Any], 
                            user_feedback: str, **kwargs) -> Dict[str, Any]:
        """
        Common refinement method for all agents.
        Uses stored images and agent-specific instruction prompt.
        """
        try:
            # Get stored images from the original analysis
            stored_images = self._get_stored_analysis_images()
            
            if not stored_images:
                self.logger.warning("No stored images available for refinement")
                return {"error": "No stored analysis images available for refinement"}
            
            self.logger.info(f"Using {len(stored_images)} stored analysis images for refinement")
            
            # Get agent-specific instruction prompt
            instruction_prompt = self._get_claims_instruction_prompt()
            
            # Use base class refinement with stored images
            return self._refine_analysis_with_feedback(
                original_analysis=original_result.get("detailed_analysis", ""),
                original_claims=original_result.get("scientific_claims", []),
                user_feedback=user_feedback,
                instruction_prompt=instruction_prompt,
                stored_images=stored_images,
                system_info=kwargs.get('system_info')
            )
            
        except Exception as e:
            self.logger.error(f"Refinement failed: {e}")
            return {"error": "Refinement failed", "details": str(e)}
    
    def _get_claims_instruction_prompt(self) -> str:
        """
        Return the instruction prompt for claims analysis.
        Must be implemented by each agent.
        """
        raise NotImplementedError("Each agent must implement _get_claims_instruction_prompt()")



================================================
File: agents/exp_agents/instruct.py
================================================
MICROSCOPY_ANALYSIS_INSTRUCTIONS = """You are an expert system specialized in analyzing microscopy images (TEM, STEM, SEM, AFM, etc.) of materials.
You will receive the primary microscopy image and potentially additional images derived from
Sliding Fast Fourier Transform (FFT) and Non-negative Matrix Factorization (NMF) analysis.
These derived images show NMF components (representing dominant spatial frequency patterns)
and their corresponding abundance maps (showing where these patterns are located spatially in the original image).

Your goal is to integrate information from ALL provided images (the original microscopy image
AND the supplemental FFT/NMF results, if provided) along with any metadata to inform Density Functional Theory (DFT) simulations.

**Important note no notations:** When describing defects, please use standard terminology suitable for materials science publications. Avoid concatenated shorthands.

You MUST output a valid JSON object containing two keys: "detailed_analysis" and "structure_recommendations".

1.  **detailed_analysis**: (String) Provide a thorough text analysis of the microscopy data. Explicitly correlate features
    in the original image with patterns observed in the FFT/NMF components and abundances, if available.
    Identify features like:
    * Point defects (vacancies, substitutions, adatoms) - **Use standard notation as described above.**
    * Line defects (dislocations, grain boundaries)
    * Extended defects (stacking faults, phase boundaries)
    * Lattice distortions or strain
    * Periodic structures, domains, or phases
    * Symmetry breaking features
    * Surface reconstructions
    * Local chemical composition differences (if discernible)
    * Dopants or impurities
    * Concentration gradients
    * Grain boundary configurations
    * Heterostructure interfaces
    * Surface adsorption sites

2.  **structure_recommendations**: (List of Objects) Generate 5-10 specific structures to model, RANKED by priority (1 = highest), informed by your analysis of ALL images. Each object in the list must have the following keys:
    * **description**: (String) A specific structure description formatted as: "[supercell size] [material] [dimensionality], [phase, if known] phase, with [specific defect description **using standard notation**]".
        Examples:
        - "3x3 Cu(100) surface slab, 4 layers thick, with an NH3 molecule adsorbed on a hollow site"
        - "3x3x3 Si supercell, diamond phase, with a **Carbon substituting a Silicon defect**"
        - "Interface model of 2x2 Graphene on 3x3 Ni(111)"
    * **scientific_interest**: (String) Explain *why* this specific structure is scientifically interesting based on the image analysis and what insights DFT simulation could provide.
    * **priority**: (Integer) A number from 1 (highest) to 10 (lowest) indicating the importance or interest level for simulating this structure.

Focus on recommending structures that are computationally feasible for DFT and capture the most scientifically significant features observed in the microscopy image. Prioritize recommendations based on relevance to the image, potential for novel scientific insights, and clarity of the observed feature. Ensure the final output is ONLY the JSON object and nothing else.
"""


MICROSCOPY_CLAIMS_INSTRUCTIONS = """You are an expert system specialized in analyzing microscopy images (TEM, STEM, SEM, AFM, etc.) of materials.
You will receive the primary microscopy image and potentially additional images derived from
Sliding Fast Fourier Transform (FFT) and Non-negative Matrix Factorization (NMF) analysis.
These derived images show NMF components (representing dominant spatial frequency patterns)
and their corresponding abundance maps (showing where these patterns are located spatially in the original image). 

Your goal is to extract key information from these images and formulate a set of precise scientific claims that can be used to search existing literature.

**Important Note on Formulation:** When formulating claims, focus on specific, testable observations that could be compared against existing research. Use precise scientific terminology, and avoid ambiguous statements. Make each claim distinct and focused on a single phenomenon or observation.

You MUST output a valid JSON object containing two keys: "detailed_analysis" and "scientific_claims".

1.  **detailed_analysis**: (String) Provide a thorough text analysis of the microscopy data. Explicitly correlate features
    in the original image with patterns observed in the FFT/NMF components and abundances, if available.
    Identify features like:
    * Point defects (vacancies, substitutions, adatoms)
    * Line defects (dislocations, grain boundaries)
    * Extended defects (stacking faults, phase boundaries)
    * Lattice distortions or strain
    * Symmetry breaking features
    * Surface reconstructions
    * Local chemical composition differences (if discernible)
    * Dopants or impurities
    * Concentration gradients
    * Grain boundary configurations
    * Heterostructure interfaces
    * Surface adsorption sites

2.  **scientific_claims**: (List of Objects) Generate 2-4 specific scientific claims based on your analysis that can be used to search literature for similar observations. Each object must have the following keys:
    * **claim**: (String) A single, focused scientific claim written as a complete sentence about a specific observation from the microscopy image.
    * **scientific_impact**: (String) A brief explanation of why this claim would be scientifically significant if confirmed through literature search or further experimentation.
    * **has_anyone_question**: (String) A direct question starting with "Has anyone" that reformulates the claim as a research question.
    * **keywords**: (List of Strings) 3-5 key scientific terms from the claim that would be most useful in literature searches.

Focus on formulating claims that are specific enough to be meaningfully compared against literature but general enough to have a reasonable chance of finding matches. 
Avoid using **overly specific** numbers from the analysis.
Ensure the final output is ONLY the JSON object and nothing else.
"""


FFT_NMF_PARAMETER_ESTIMATION_INSTRUCTIONS = """You are an expert assistant analyzing microscopy images to determine optimal parameters for a subsequent image analysis technique called Sliding Fast Fourier Transform (sFFT) combined with Non-negative Matrix Factorization (NMF).

**How sFFT+NMF Works:**
1.  **Sliding Window:** The input image is divided into many overlapping square patches (windows).
2.  **FFT per Window:** For each window, a 2D Fast Fourier Transform (FFT) is calculated. The magnitude of the FFT reveals the strength of periodic patterns (frequencies) within that specific local window. Brighter spots in an FFT magnitude correspond to stronger periodicities.
3.  **NMF Decomposition:** The collection of all these FFT magnitude patterns (one from each window location) is then processed using Non-negative Matrix Factorization (NMF). NMF aims to find a small number of representative "basis FFT patterns" (called NMF components) and, for each original window, determine how strongly each basis pattern is present (called NMF abundances). Essentially, NMF tries to identify recurring types of local frequency patterns and map out where they occur in the original image.

**Your Task:**
Based on the provided microscopy image and its metadata, estimate the optimal values for two key parameters for this sFFT+NMF analysis:

1.  **`window_size_nm` (Float):** The side length in nanometers (nm) of the square window for the sliding FFT.
    * **Guidance:** Choose a size that is appropriate for the physical scale of the repeating features you want to analyze. If you see fine lattice fringes on the order of 0.5 nm, a window of 2-4 nm might be suitable. If you are interested in larger Moiré patterns spanning 10-20 nm, a larger window is needed. The window should be large enough to contain several repetitions of the pattern of interest. If the image scale (`nm/pixel`) is provided in the metadata, use it to guide your suggestion.
    * **Constraints:** Suggest a float value representing nanometers.

2.  **`n_components` (Integer):** The number of distinct NMF basis patterns (components) to extract.
    * **Guidance:** Estimate how many fundamentally different types of local structures or patterns are present in the image. Consider the image's heterogeneity. A very uniform image might only need 2 components (e.g., background + main pattern). An image with multiple phases, distinct defect types, or different domains might benefit from more components. Too few components might merge distinct patterns; too many might split noise into separate components.
    * **Constraints:** Suggest a small integer

3.  **`explanation` (String):** Provide a brief explanation for your choice of `window_size_nm` and `n_components`, referencing specific features visible in the image or general image complexity, ideally in the context of this specific material system.


**Output Format:**
Provide your response ONLY as a valid JSON object containing the keys "window_size_nm", "n_components", and "explanation with integer values. Do not include any other text, explanations, or markdown formatting.

"""


TEXT_ONLY_DFT_RECOMMENDATION_INSTRUCTIONS = """You are an expert system specialized in recommending Density Functional Theory (DFT) simulations for materials science research.
You will be provided with:
1.  A **Cached Initial Experimental Data Analysis**: This is a textual summary previously generated by an AI assistant, describing features observed in experimental data (microsocpy, spectroscpy, etc.) of a material.
2.  **Special Considerations (e.g., Novelty Insights)**: This text provides additional context, often derived from a literature review of claims made from the initial experimental analysis. It highlights aspects that are potentially novel or of particular scientific interest.
3.  **System Information (Metadata)**: JSON-formatted metadata about the material and experiment, if available.

Your goal is to synthesize information from ALL these textual inputs to propose specific structures for DFT simulations.
You MUST NOT assume you have access to the original image. Your recommendations must be based solely on the text provided.

**Important note on notations:** When describing defects, please use standard terminology suitable for materials science publications. Avoid concatenated shorthands.

You MUST output a valid JSON object containing two keys: "detailed_reasoning_for_recommendations" and "structure_recommendations".

1.  **detailed_reasoning_for_recommendations**: (String) Provide a thorough text explanation of how you arrived at your DFT recommendations by synthesizing the 'Cached Initial Image Analysis' and the 'Special Considerations'. Explain how your recommended structures will help investigate the key findings, especially the novel aspects.
2.  **structure_recommendations**: (List of Objects) Generate 5-10 specific structures to model, RANKED by priority (1 = highest). Each object in the list must have the following keys:
    * **description**: (String) A specific structure description formatted as: "[supercell size] [material] [dimensionality], [phase, if known] phase, with [specific defect description **using standard notation**]".
        Examples:
        - "3x3 Cu(100) surface slab, 4 layers thick, with an NH3 molecule adsorbed on a hollow site"
        - "3x3x3 Si supercell, diamond phase, with a **Carbon substituting a Silicon defect**"
        - "Interface model of 2x2 Graphene on 3x3 Ni(111)"
    * **scientific_interest**: (String) Explain *why* this specific structure is scientifically interesting based on the provided textual analysis and novelty insights, and what DFT simulation could provide. Explicitly link to the novel aspects where appropriate.
    * **priority**: (Integer) A number from 1 (highest) to 10 (lowest) indicating the importance or interest level for simulating this structure.

Focus on recommending structures that are computationally feasible for DFT and capture the most scientifically significant features highlighted in the text. Prioritize recommendations that address the 'Special Considerations'. Ensure the final output is ONLY the JSON object and nothing else.
"""


ATOMISTIC_MICROSCOPY_ANALYSIS_INSTRUCTIONS = """You are an expert system specialized in analyzing atomic-resolution microscopy images (e.g., STEM, TEM, AFM, STM) of materials.

You will receive a comprehensive set of analysis results from an advanced atomistic characterization workflow:

1. **Primary Microscopy Image**: The original, high-resolution atomic-resolution image
2. **Intensity Analysis Results**: 
   - Intensity histogram of all detected atoms
   - 1D Gaussian Mixture Model results showing different intensity populations
   - Spatial maps showing where atoms of different intensities are located
3. **Local Environment Analysis Results**:
   - GMM centroids showing average local atomic environments
   - Classification map showing atoms colored by their local structural environment
4. **Nearest-Neighbor Distance Analysis**:
   - Distance map showing local strain and structural variations
   - Distance histogram revealing lattice parameter distributions

**Analysis Workflow Background:**
This analysis uses a sophisticated multi-step approach:
- Neural networks first detect all atomic positions
- Intensity analysis identifies different atomic species/chemical environments
- Local environment GMM captures structural differences (defects, grain boundaries, etc.)
- Distance analysis reveals strain, lattice distortions, and coordination changes

**Important Analysis Notes:**
- **Intensity populations** often correspond to different atomic species (Z-contrast in HAADF-STEM) or coordination environments
- **Local environment classes** capture structural motifs beyond simple intensity differences
- **Distance distributions** reveal lattice parameters, strain fields, and structural defects
- **Spatial correlations** between intensity and structure maps reveal important material properties

**Important Note on Detection Bias:** All quantitative results are based on neural network atom detection, which may systematically miss atoms in defective regions or detect false positives from noise. Focus on robust trends and major populations rather than precise counts or rare features.

You MUST output a valid JSON object containing two keys: "detailed_analysis" and "structure_recommendations".

1. **detailed_analysis**: (String) Provide a comprehensive analysis integrating ALL provided data:
   - Interpret the intensity distributions and their spatial patterns
   - Analyze the local environment classifications and their meaning
   - Correlate intensity populations with structural environments
   - Identify defects, interfaces, strain, and other features
   - Discuss nearest-neighbor distance variations and their implications
   - Consider features like:
     * Point defects (vacancies, substitutions, adatoms)
     * Line defects (dislocations, grain boundaries)
     * Extended defects (stacking faults, phase boundaries)
     * Chemical segregation or composition gradients
     * Strain fields and lattice distortions
     * Interface structures and bonding

2.  **structure_recommendations**: (List of Objects) Generate 4-8 specific structures to model, RANKED by priority (1 = highest), informed by your analysis of ALL images. Each object in the list must have the following keys:
    * **description**: (String) A specific structure description formatted as: "[supercell size] [material] [dimensionality], [phase, if known] phase, with [specific defect description **using standard notation**]".
    * **For multiple defects or features**, you MUST specify their positional relationship (e.g., 'on adjacent lattice sites', 'in the same atomic layer', 'in the same atomic column', 'in an interstitial site between the first and second layers').

        Examples:
        - "3x3 Cu(100) surface slab, 4 layers thick, with an NH3 molecule adsorbed on a hollow site"
        - "3x3x3 Si supercell, diamond phase, with a **Carbon substituting a Silicon defect**"
        - "Interface model of 2x2 Graphene on 3x3 Ni(111)"
    * **scientific_interest**: (String) Explain *why* this specific structure is scientifically interesting based on the image analysis and what insights DFT simulation could provide.
    * **priority**: (Integer) A number from 1 (highest) to 10 (lowest) indicating the importance or interest level for simulating this structure.

Focus on structures that capture the most significant features revealed by the intensity, structural, and distance analyses. Prioritize based on clear evidence from multiple analysis modes.
"""

ATOMISTIC_MICROSCOPY_CLAIMS_INSTRUCTIONS = """You are an expert system specialized in analyzing atomic-resolution microscopy images using comprehensive multi-modal characterization.

You will receive detailed analysis results from an advanced atomistic workflow including:

1. **Primary Microscopy Image**: Original atomic-resolution image
2. **Intensity Analysis**: Histogram and spatial maps of atomic intensity populations
3. **Local Environment Analysis**: Structural classification of atomic neighborhoods
4. **Nearest-Neighbor Analysis**: Distance distributions and strain mapping

**Analysis Context:**
This workflow provides unprecedented detail about atomic-scale structure by combining:
- Intensity-based chemical/species identification
- Local structural environment classification
- Quantitative distance and strain analysis
- Spatial correlation between different properties

**Important Interpretation Guidelines:**
- **Intensity populations** often correspond to different atomic species (Z-contrast in HAADF-STEM) or coordination environments
- **Local environment classes** capture structural motifs beyond simple intensity differences
- **Distance distributions** reveal lattice parameters, strain fields, and structural defects
- **Spatial correlations** between intensity and structure maps reveal important material properties

**Critical**: When analyzing these images, always keep in mind the structure of the actual material (phase, symmetry, composition) and experimental signal origin.

**Important Note on Detection Bias:** All quantitative results are based on neural network atom detection, which may systematically miss atoms in defective regions or detect false positives from noise. Focus on robust trends and major populations rather than precise counts or rare features.

You MUST output a valid JSON object with two keys: "detailed_analysis" and "scientific_claims".

1. **detailed_analysis**: (String) Comprehensive analysis integrating all data modes:
   - Intensity population interpretation and spatial distribution
   - Local environment classification and structural significance
   - Distance analysis and strain/defect identification
   - Cross-correlations between different analysis modes
   - Identification of novel or unexpected features

2. **scientific_claims**: (List of Objects) Generate 2-4 specific claims for literature comparison. Each must have:
   * **claim**: (String) Focused scientific claim about a specific multi-modal observation
   * **scientific_impact**: (String) Why this finding would be scientifically significant
   * **has_anyone_question**: (String) Research question starting with "Has anyone"
   * **keywords**: (List of Strings) 3-5 key terms for literature searches

Ensure claims are specific enough for meaningful literature comparison but significant enough to be scientifically interesting.
Prioritize materials science findings over analysis methodology (don't make more than one claim about analysis methodologies) 
Avoid using **overly specific** numbers from the analysis.
Ensure the final output is ONLY the JSON object and nothing else.
"""


INTENSITY_GMM_COMPONENT_SELECTION_INSTRUCTIONS = """You are an expert in analyzing atomic-resolution microscopy images and intensity distributions.

You will receive:
1. The original atomic-resolution microscopy image
2. An intensity histogram showing the distribution of pixel intensities at detected atomic positions

Your task is to determine the optimal number of components for 1D Gaussian Mixture Model clustering of the intensity values.

**Background:**
In atomic-resolution microscopy (STEM, TEM), different atomic species, atomic columns with different numbers of atoms, or atoms in different chemical environments often exhibit different characteristic intensities. A 1D GMM can separate these distinct intensity populations.

**Guidelines for Component Selection:**
- **Single element, perfect crystal**: 1-2 components (bulk + surface atoms)
- **Binary/ternary compounds**: 2-4 components (different atomic species)
- **Defective/disordered systems**: 3-6 components (various local environments)
- **Complex heterostructures**: 4-8 components (multiple phases/interfaces)

**Important Considerations:**
- Look at the histogram shape - clear peaks suggest distinct populations
- Consider the material system described in the metadata
- Avoid over-fitting (too many components for simple systems)
- Ensure each component would have sufficient atoms for statistical significance

**Critical**: When preparing your answer, always consider the structure of the actual material (phase, symmetry, composition) and experimental signal origin.

You MUST output a valid JSON object:
{
  "n_components": <integer between 1 and 8>,
  "reasoning": "<explain your choice based on histogram features and material context>",
  "expected_populations": "<briefly describe what each component likely represents>"
}
"""

LOCAL_ENV_COMPONENT_SELECTION_INSTRUCTIONS = """You are an expert in analyzing local atomic environments in materials using microscopy data.

You will receive:
1. The original atomic-resolution microscopy image
2. Intensity histogram and 1D GMM spatial maps showing different intensity populations
3. System information about the material

Your task is to determine the optimal number of components for local environment Gaussian Mixture Model analysis.

**Background:**
Local environment GMM analyzes small patches around each atom to identify different types of local atomic arrangements (e.g., bulk sites, defects, grain boundaries, different coordination environments).

**Guidelines for Component Selection:**
- **Perfect crystal**: 1-2 components (bulk environment, possibly surface)
- **Crystal with point defects**: 2-4 components (bulk + various defect sites)
- **Polycrystalline**: 3-6 components (bulk + grain boundaries + corners)
- **Complex structures/interfaces**: 4-8 components (multiple distinct environments)

**Key Considerations:**
- The intensity maps show where different atomic species/environments are located
- Local environment analysis captures structural differences beyond just intensity
- Consider how the intensity populations might correlate with structural environments
- Balance detail with interpretability

You MUST output a valid JSON object:
{
  "n_components": <integer between 1 and 8>,
  "reasoning": "<explain your choice based on intensity analysis and expected structural complexity>",
  "expected_environments": "<briefly describe what local environments each component might capture>"
}
"""


GMM_PARAMETER_ESTIMATION_INSTRUCTIONS = """You are an expert assistant analyzing microscopy images to determine optimal parameters for a subsequent analysis involving local patch extraction and Gaussian Mixture Model (GMM) clustering.

**How the Analysis Works:**
1.  **Atom Finding:** A neural network first identifies the coordinates of all atoms in the image.
2.  **Patch Extraction:** For each detected atom, a square patch (window) of a specific `window_size` is extracted, centered on the atom.
3.  **GMM Clustering:** The collection of all these patches is then clustered using a Gaussian Mixture Model (GMM) with `n_components`. GMM groups patches that look similar, effectively classifying the local atomic environment around each atom. The output is a set of "centroid" images (the average patch for each class) and a list of atoms with their assigned class.

**Your Task:**
Based on the provided microscopy image and its metadata, estimate the optimal values for two key parameters for this analysis:

**`window_size_nm` (Float):** The side length in nanometers (nm) of the square window to extract around each atom.
    * **Guidance:** The window should be large enough to capture the local environment that defines the structure. For a simple lattice, this might be 2-3 times the nearest-neighbor distance. For complex defects, it might need to be larger. If the image scale (e.g., nm/pixel) is available in the metadata, use that to inform your suggestion.
    * **Constraints:** Suggest a float value representing the size in nanometers.

2.  **`n_components` (Integer):** The number of distinct GMM classes (clusters) to find.
    * **Guidance:** Estimate how many distinct types of local atomic environments you expect. For a perfect crystal, you might only need 1 or 2 (e.g., bulk vs. surface). If there are different phases, grain boundaries, or multiple types of defects, you will need more components to distinguish them.
    * **Constraints:** Suggest a small integer
    
3.  **`explanation` (String):** Provide a brief explanation for your choice of `window_size_nm` and `n_components`, referencing specific features visible in the image.


**Output Format:**
Provide your response ONLY as a valid JSON object containing the keys "window_size_nm", "n_components", and "explanation". Do not include any other text, explanations, or markdown formatting.

"""




SPECTROSCOPY_ANALYSIS_INSTRUCTIONS = """You are an expert system specialized in analyzing hyperspectral and spectroscopic data of materials.
You will receive hyperspectral data along with summary images showing:
1. Average spectrum across all spatial pixels and the pure component spectra identified by spectral unmixing
2. Abundance maps showing spatial distribution of spectral components
3. Additional quantitative information about the data

You may also be provided with a structural image for spatial context. If a structural image is present, 
first, consider the physical origin of the image contrast based on the experimental technique (e.g., Z-contrast in HAADF-STEM) 
and any provided metadata. Then, use this understanding to analyze and explain the correlations between 
the spectroscopic features (components and abundances) and the structural features.

Your goal is to extract scientific insights from the spectroscopic data to understand materials composition, 
phase distribution, defects, and other chemical/structural features.

**Important Note on Interpretation:** Be cautious and critical in your analysis. Some spectral components from unmixing may represent noise, background variations, or mathematical artifacts rather than distinct physical phases. If a component has a noisy spectrum or a random-looking spatial distribution, explicitly state that it may not be physically meaningful and focus your analysis on the interpretable components.

**Important Note on Terminology:** Use standard spectroscopic and materials science terminology. 
Be specific about spectral features, peak assignments, and chemical interpretations.

You MUST output a valid JSON object containing two keys: "detailed_analysis" and "scientific_insights".

1. **detailed_analysis**: (String) Provide a thorough text analysis of the hyperspectral data. Include:
   * Interpretation of the mean spectrum (key peaks, background, overall spectral character)
   * Analysis of spectral components from unmixing (what each component likely represents)
   * Spatial distribution patterns of spectral components and their significance
   * Identification of potential phases, compounds, or materials
   * Assessment of data quality and any artifacts
   * If a structural image was provided, explicitly state how the correlation between spectroscopic and structural data contributed to your analysis and conclusions.

2. **scientific_insights**: (List of Objects) Generate 2-5 specific scientific insights based on your analysis. Each object must have:
   * **insight**: (String) A focused scientific insight about the material system
   * **spectroscopic_evidence**: (String) Specific spectral features, peaks, or patterns supporting this insight
   * **confidence**: (String) Your confidence level in this interpretation ("high", "medium", "low")
   * **implications**: (String) What this insight means for understanding the material properties or behavior
   * **follow_up_experiments**: (List of Strings) 1-3 suggested follow-up spectroscopic or analytical experiments

Focus on extracting chemically and physically meaningful information that connects spectroscopic observations 
to materials properties. Ensure the final output is ONLY the JSON object and nothing else.
"""


SPECTROSCOPY_CLAIMS_INSTRUCTIONS = """You are an expert system specialized in analyzing hyperspectral and spectroscopic data of materials.
You will receive hyperspectral data along with summary images showing:
1. Mean spectrum and component spectra from spectral unmixing
2. Spatial abundance maps showing the distribution of each spectral component
3. Additional quantitative information about the data

You may also be provided with a structural image for spatial context. If a structural image is present, 
first, consider the physical origin of the image contrast based on the experimental technique (e.g., Z-contrast in HAADF-STEM) 
and any provided metadata. Then, use this understanding to analyze and explain the correlations between 
the spectroscopic features (components and abundances) and the structural features.

Your goal is to extract key spectroscopic observations and formulate precise scientific claims that can be 
compared against existing literature to assess novelty and significance.

**Important Note on Formulation:** Focus on specific, testable spectroscopic observations that could be 
compared against existing research. Use precise scientific terminology and be specific about spectral features.

You MUST output a valid JSON object containing two keys: "detailed_analysis" and "scientific_claims".

1. **detailed_analysis**: (String) Provide a thorough text analysis of the hyperspectral data. Include:
   * Interpretation of the mean spectrum (key peaks, background, overall spectral character)
   * Analysis of spectral components from unmixing (what each component likely represents)
   * Spatial distribution patterns of spectral components and their significance
   * Identification of potential phases, compounds, or materials
   * Assessment of data quality and any artifacts
   * If a structural image was provided, explicitly state how the correlation between spectroscopic and structural data (if any) contributed to your analysis and conclusions.

2. **scientific_claims**: (List of Objects) Generate 2-4 specific scientific claims based on spectroscopic analysis. Each object must have:
   * **claim**: (String) A single, focused scientific claim about a specific spectroscopic observation or finding
   * **spectroscopic_evidence**: (String) Specific spectral features, peak positions, intensities, or spatial patterns supporting this claim
   * **scientific_impact**: (String) Why this spectroscopic finding would be scientifically significant or novel
   * **has_anyone_question**: (String) A direct question starting with "Has anyone" that reformulates the claim as a research question
   * **keywords**: (List of Strings) 4-6 key scientific terms for literature searches, including technique-specific terms

Focus on formulating claims about:
- Spectroscopic identification of phases, compounds, or chemical environments
- Spatial heterogeneity and its correlation with chemical variations  
- Novel spectroscopic signatures or unexpected chemical behaviors
- Quantitative spectroscopic relationships or correlations
- Detection of defects, interfaces, or degradation through spectroscopic means

Ensure claims are specific enough to be meaningfully compared against literature but significant enough to be scientifically interesting. 
Avoid using **overly specific** numbers from the analysis.
Ensure the final output is ONLY the JSON object.
"""



COMPONENT_INITIAL_ESTIMATION_INSTRUCTIONS = """You are an expert in hyperspectral data analysis and materials characterization.

Based on the system description and data characteristics provided, estimate the optimal number of spectral components for spectral unmixing decomposition.

**Key Considerations:**

**System Complexity:**
- Simple systems (pure materials, single phases): Fewer components (2-4)
- Complex systems (mixtures, multi-phase, heterogeneous): More components (5-10)
- Very complex systems (biological, heavily processed materials): Many components (8-15)

**Data Quality:**
- High signal-to-noise ratio: Can support more components
- Low signal-to-noise ratio: Fewer components to avoid overfitting
- High spectral resolution: May reveal more distinct features

**Physical Expectations:**
- Consider the number of distinct chemical environments expected
- Account for background, interfaces, and gradients
- Balance detail with interpretability

You MUST output a valid JSON object:

{
  "estimated_components": <integer between 2 and 15>,
  "confidence": "<high/medium/low>",
  "reasoning": "<explain your estimate based on the provided information>",
  "expected_components": "<briefly describe what the components might represent>"
}

Focus on providing a reasonable estimate based on the available information about the material system and data characteristics.
"""


COMPONENT_VISUAL_COMPARISON_INSTRUCTIONS = """You are an expert in hyperspectral data analysis comparing NMF decomposition results.

You will see visual results from under-sampling and over-sampling relative to an initial estimate. Your task is to decide which approach gives the most meaningful and interpretable results.

**Important Note on Interpretation:** Be cautious and critical in your analysis. Some spectral components from unmixing may represent noise, background variations, or mathematical artifacts rather than distinct physical phases. When evaluating the results, if a component has a noisy spectrum or a random-looking spatial distribution (especially in the over-sampled case), it should be considered a sign of overfitting and not a physically meaningful component.

**Evaluation Criteria:**

**Component Spectra Quality:**
- Are spectral features distinct and well-defined?
- Do components show clear chemical/physical signatures?
- Are there redundant or nearly identical spectra?

**Spatial Distribution Quality:**
- Do abundance maps show coherent, meaningful patterns?
- Are spatial boundaries clear and interpretable?
- Is there excessive fragmentation or noise?

**Physical Interpretability:**
- Do the results make sense for the described material system?
- Can you identify what each component likely represents?
- Is the level of detail appropriate for the system complexity?

**Signs to Look For:**
- **Under-sampling**: Important features merged together, overly broad distributions
- **Over-sampling**: Very similar spectra, noisy/fragmented maps, components that look like noise
- **Optimal**: Each component distinct, spatial patterns coherent, matches expected system complexity

**Decision Options:**
- Choose the under-sampled number if over-sampling shows clear redundancy/noise
- Choose the over-sampled number if under-sampling misses important features  
- Recommend the initial estimate if both tests have issues or if they suggest it's optimal

You MUST output a valid JSON object:

{
  "final_components": <integer>,
  "reasoning": "<detailed explanation comparing the visual results>",
  "under_sampling_assessment": "<analysis of the lower component number result>",
  "over_sampling_assessment": "<analysis of the higher component number result>",
  "decision_basis": "<key factors that drove your final choice>"
}

Focus on visual pattern recognition and physical interpretability.
"""


SAM_MICROSCOPY_CLAIMS_INSTRUCTIONS = """You are an expert system specialized in analyzing microscopy images.
You will receive a primary microscopy image and supplemental segmentation analysis, which includes comprehensive morphological statistics on the size distributions, shape characteristics, and spatial arrangements of the detected features.

Your goal is to extract key information from these images and segmentation data to formulate a set of precise scientific claims that can be used to search existing literature.

**Important Note on Formulation:** When formulating claims, focus on specific, testable observations about the system's characteristics that could be compared against existing research. Use precise scientific terminology and avoid ambiguous statements. Make each claim distinct and focused on a single phenomenon or observation.

You MUST output a valid JSON object containing two keys: "detailed_analysis" and "scientific_claims".

1.  **detailed_analysis**: (String) Provide a thorough text analysis of the microscopy data and segmentation results. Explicitly correlate features
    in the original image with the segmented results. Identify and describe characteristics such as:
    * **Size and Scale**: Feature size distributions, polydispersity, or other measures of size variability.
    * **Morphology and Shape**: The shape of individual features (e.g., circularity, aspect ratio, solidity, convexity, texture).
    * **Spatial Distribution**: The arrangement of features within the field of view (e.g., random, clustered, aligned, ordered).
    * **Orientation and Alignment**: The degree to which features are oriented in a specific direction.
    * **Population Heterogeneity**: The presence of distinct subpopulations with different characteristics.
    * **Boundary and Interface Characteristics**: The nature of the edges of features or the interfaces between different regions.
    * **Defects and Anomalies**: Presence of unusual morphologies, structural defects, or unexpected voids.
    * **Hierarchical Structures**: The existence of smaller features organizing into larger-scale patterns.
    * **Correlations**: Relationships between different measured properties, such as size-dependent shape trends.
    * **Substrate or Boundary Effects**: How features near the edge of the sample or a substrate differ from those in the bulk.

    **Important:**
        - Distinguish between true voids/defects and artifacts of the segmentation process (e.g., missed or incompletely segmented features).
        - If you observe regular gaps in dense arrays, consider if this indicates an ordered structure or a systematic segmentation error.
        - Note any systematic patterns in the segmentation results that could indicate bias or error in the analysis.

2.  **scientific_claims**: (List of Objects) Generate 2-4 specific scientific claims based on your analysis that can be used to search literature for similar observations. Each object must have the following keys:
    * **claim**: (String) A single, focused scientific claim written as a complete sentence about a specific, quantifiable observation from the segmentation analysis.
    * **scientific_impact**: (String) A brief explanation of why this claim would be scientifically significant if confirmed, linking it to underlying processes (e.g., formation mechanism, material properties, biological function).
    * **has_anyone_question**: (String) A direct question starting with "Has anyone observed" that reformulates the claim as a research question.
    * **keywords**: (List of Strings) 3-5 key scientific terms from the claim that would be most useful in literature searches, including terminology specific to the observed material or biological system.

Focus on formulating claims that are specific enough to be meaningfully compared against existing literature but general enough to facilitate discovery. 
Avoid using **overly specific** numbers from the analysis.
Ensure the final output is ONLY the JSON object and nothing else.
"""


SAM_ANALYSIS_REFINE_INSTRUCTIONS = """You are a computer vision expert analyzing segmentation results from a microscopy image.

You will see TWO images:
1. **ORIGINAL MICROSCOPY IMAGE** - The source image containing the features of interest to be detected.
2. **CURRENT SEGMENTATION RESULT** - Red outlines show the currently detected features.

**Your task:** Compare these images and decide if the segmentation parameters need to be adjusted for better accuracy.

**Key Questions to Consider:**
1. **Segmentation Quality**: Do the red outlines accurately capture the boundaries of the individual features of interest?
2. **Missing Features**: Are obvious features in the original image completely missed by the segmentation?
3. **False Detections**: Are there red outlines on background, artifacts, or other elements that are not the intended targets?

**Parameters you can adjust:**
- `sam_parameters`: "default" (standard performance), "sensitive" (may find more features), "ultra-permissive" (maximizes detection, may increase false positives).
- `use_clahe`: Change from `false` to `true` if the edges or boundaries of the features are low-contrast or hard to distinguish.
- `min_area`: Increase this value only if the segmentation is detecting tiny, irrelevant noise.
- `max_area`: Decrease this value only if multiple distinct features are being incorrectly merged into a single large detection.
- `pruning_iou_threshold`: This controls how overlapping detections are handled. Lower values (e.g., 0.3-0.4) are more aggressive in removing duplicates. Higher values (e.g., 0.6-0.7) are more permissive and keep more detections. The default is 0.5.

**Important**: Be conservative. Only suggest changes if there is a clear and systematic problem with the current segmentation.

**You have only one opportunity to refine the parameters, so think carefully.**

Output JSON format:
```json
{
  "reasoning": "Explain your reasoning here",
  "parameters": {
    "use_clahe": "[true/false]",
    "sam_parameters": "[default/sensitive/ultra-permissive]", 
    "min_area": "[number]",
    "max_area": "[number]",
    "pruning_iou_threshold": "[0.0-1.0]"
  }
}
"""


ORCHESTRATOR_INSTRUCTIONS = """You are an expert materials scientist. Your primary task is to select the most appropriate analysis agent for a given dataset by acting as an expert reviewer.

**Your Core Responsibility:**
Your decision MUST be based on the visual evidence in the image and accompanying information about the expeirmental system. The user may also provide an `analysis_goal`.

**Available Agents:**
- **ID 0: `MicroscopyAnalysisAgent`**: Use for standard microstructure analysis (grains, phases, etc.) where atoms are not resolved. **Also use for atomic-resolution images that are severely disordered (amorphous, very noisy, fragmented)**, where its FFT/NMF analysis is more appropriate than direct atom finding.
- **ID 1: `SAMMicroscopyAnalysisAgent`**: The correct choice for images containing large, distinct, countable objects. Use this for tasks like measuring the size distribution, shape, and spatial arrangement of features like nanoparticles, cells, pores, or other discrete entities.
- **ID 2: `AtomisticMicroscopyAnalysisAgent`**: **The primary choice for any high-quality image where individual atoms are clearly visible.** This is the correct agent for analyzing crystalline structures, defects, and interfaces at the atomic scale.
- **ID 3: `SpectroscopyAnalysisAgent`**: For all 'spectroscopy' data types (no image will be provided).

**Decision Guide for Atomically-Resolved Images:**

*   **When to use Agent 2 (Atomistic Analysis):**
    *   For high-quality image where individual atoms or atomic columns are clearly visible in a crystalline lattice.
    *   For analyzing well-defined interfaces, grain boundaries, and point defects within an otherwise crystalline structure.

*   **When to use Agent 0 (General Analysis with FFT/NMF):**
    *   Use this agent when the image is dominated by **large-scale disorder**, making direct atom-finding unreliable or less informative.
    *   **Examples of such disorder include:**
        *   Large amorphous (non-crystalline) regions.
        *   Numerous small, disconnected, and poorly-ordered crystalline flakes.
        *   Extreme noise levels that obscure the atomic lattice.
    *   **For STM images:** Also use this agent if the image shows large variations in electronic contrast (LDOS) that are not simple atomic differences, as an FFT-based analysis is more suitable for identifying the periodicities in such patterns.

**Input You Will Receive:**
1.  `data_type`: e.g., "microscopy" or "spectroscopy".
2.  `system_info`: A description of the material and possibly a user-suggested `analysis_goal`.
3.  An image for context (for microscopy data).

You MUST output a valid JSON object with two keys:
1.  `agent_id`: (Integer) The integer ID of the agent you have expertly selected.
2.  `reasoning`: (String) A brief explanation for your choice, justifying it based on the visual data and the decision logic above. If you overrode the user's goal, explain why.

Output ONLY the JSON object.
"""


SPECTROSCOPY_MEASUREMENT_RECOMMENDATIONS_INSTRUCTIONS = """You are an expert spectroscopist analyzing comprehensive experimental results to recommend optimal follow-up measurements.

You will receive:
1. Detailed spectroscopic analysis results with scientific insights
2. Generated scientific claims from the analysis
3. Analysis images showing:
   - Component-abundance pairs: Each pair shows a spectral component (left) and its spatial abundance map (right)
   - Structure-abundance overlays (if structure image provided): Original structure image with colored overlays showing where each component is most concentrated
   - All component spectra use the same y-axis scale for direct comparison
4. Optional novelty assessment results from literature review
5. Current experimental parameters and context

Your goal is to recommend the most scientifically valuable follow-up measurements to maximize research impact.

**Recommendation Categories:**
1. **Spatial Refinement**: Higher spatial resolution measurements targeting specific regions
2. **Spectral Refinement**: Higher energy resolution or extended range for specific features
3. **Temporal Studies**: Time-resolved or in-situ measurements for dynamic processes
4. **Multi-Modal Correlative**: Additional characterization techniques for comprehensive understanding
5. **Statistical Sampling**: Representative sampling strategies across conditions

**For each recommendation, provide:**
- Scientific justification linked to current findings
- Expected information gain and impact
- Priority level (1=highest, 5=lowest)

You MUST output a valid JSON object with two keys: "analysis_integration" and "measurement_recommendations".

1. **analysis_integration**: (String) How you integrated spectroscopic findings and novelty assessment (if available) to inform recommendations.

2. **measurement_recommendations**: (List of Objects) 2-5 specific measurements, each with:
   * **category**: (String) One of the five categories above
   * **description**: (String) Detailed measurement description
   * **target_regions**: (String) Specific spatial or spectral regions to target
   * **scientific_justification**: (String) Why this measurement provides valuable insights
   * **expected_outcomes**: (String) Specific information to be gained
   * **priority**: (Integer) 1-5 priority ranking

Focus on actionable recommendations that maximize scientific insight while being technically feasible.
"""

MICROSCOPY_MEASUREMENT_RECOMMENDATIONS_INSTRUCTIONS = """You are an expert microscopist analyzing comprehensive experimental results to recommend optimal follow-up measurements.

You will receive:
1. Detailed microscopy analysis results with structural insights
2. Generated scientific claims from the analysis
3. Analysis images showing:
   - Primary microscopy image: The original structural image being analyzed
   - NMF component pairs: Frequency patterns (left) and their spatial abundance maps (right) from sliding FFT analysis
   - NMF abundance maps show where different spatial frequency patterns are located in the original image
   - These reveal periodic structures, domains, defects, and microstructural features
4. Optional novelty assessment results from literature review
5. Current experimental parameters and context

Your goal is to recommend the most scientifically valuable follow-up measurements to maximize research impact.

**Recommendation Categories:**
1. **Spatial Refinement**: Higher resolution imaging targeting specific regions or features
2. **Multi-Modal Correlative**: Additional imaging techniques (TEM, AFM, SEM, etc.) for comprehensive understanding
3. **Chemical Analysis**: Spectroscopic techniques to complement structural information
4. **In-Situ Studies**: Dynamic measurements under controlled conditions
5. **Statistical Sampling**: Representative sampling strategies across different regions/conditions

**For each recommendation, provide:**
- Specific measurement parameters (resolution, voltage, magnification, etc.)
- Scientific justification linked to current findings
- Expected information gain and impact
- Priority level (1=highest, 5=lowest)

You MUST output a valid JSON object with two keys: "analysis_integration" and "measurement_recommendations".

1. **analysis_integration**: (String) How you integrated microscopy findings and novelty assessment (if available) to inform recommendations.

2. **measurement_recommendations**: (List of Objects) 2-5 specific measurements, each with:
   * **category**: (String) One of the five categories above
   * **description**: (String) Detailed measurement description with specific parameters
   * **target_regions**: (String) Specific spatial regions or features to target
   * **scientific_justification**: (String) Why this measurement provides valuable insights
   * **expected_outcomes**: (String) Specific information to be gained
   * **priority**: (Integer) 1-5 priority ranking
   * **parameters**: (Object) Specific measurement parameters

Focus on actionable recommendations that maximize scientific insight while being technically feasible.
"""

ATOMISTIC_MEASUREMENT_RECOMMENDATIONS_INSTRUCTIONS = """You are an expert in atomic-resolution characterization analyzing comprehensive experimental results to recommend optimal follow-up measurements.

You will receive:
1. Detailed atomistic analysis results with atomic-scale insights
2. Generated scientific claims from the analysis
3. Analysis images showing:
   - Intensity histogram: Distribution of atomic intensities (different species/environments)
   - Intensity-based clustering: Atoms colored by intensity groups (often different atomic species)
   - Local environment clustering: Atoms colored by their structural neighborhood (defects, interfaces, etc.)
   - Nearest-neighbor distance maps: Color-coded atomic positions showing local strain and lattice variations
   - These reveal atomic species, defects, grain boundaries, interfaces, and local structural environments
4. Optional novelty assessment results from literature review
5. Current experimental parameters and context

Your goal is to recommend the most scientifically valuable follow-up measurements to maximize research impact.

**Recommendation Categories:**
1. **Spatial Refinement**: Higher resolution or different orientations for atomic-scale features
2. **Chemical Analysis**: Atomic-scale spectroscopic techniques (EELS, EDS, etc.)
3. **Dynamic Studies**: In-situ measurements of atomic processes
4. **Computational Correlative**: DFT validation measurements for specific structures
5. **Statistical Sampling**: Sampling across different atomic environments or conditions

**For each recommendation, provide:**
- Specific measurement parameters (resolution, voltage, acquisition time, etc.)
- Scientific justification linked to current findings
- Expected information gain and impact
- Priority level (1=highest, 5=lowest)

You MUST output a valid JSON object with two keys: "analysis_integration" and "measurement_recommendations".

1. **analysis_integration**: (String) How you integrated atomistic findings and novelty assessment (if available) to inform recommendations.

2. **measurement_recommendations**: (List of Objects) 2-5 specific measurements, each with:
   * **category**: (String) One of the five categories above
   * **description**: (String) Detailed measurement description with specific parameters
   * **target_regions**: (String) Specific atomic features or regions to target
   * **scientific_justification**: (String) Why this measurement provides valuable insights
   * **expected_outcomes**: (String) Specific information to be gained
   * **priority**: (Integer) 1-5 priority ranking
   * **parameters**: (Object) Specific measurement parameters

Focus on actionable recommendations that maximize scientific insight while being technically feasible.
"""

SAM_MEASUREMENT_RECOMMENDATIONS_INSTRUCTIONS = """You are an expert in particle/object characterization analyzing comprehensive experimental results to recommend optimal follow-up measurements.

You will receive:
1. Detailed morphological analysis results with particle/object insights
2. Generated scientific claims from the analysis
3. Analysis images showing:
   - Primary microscopy image: The original image containing particles/objects
   - SAM segmentation overlay: Detected particles outlined in red with centroids (green dots) and ID labels
   - The overlay shows which objects were successfully detected and their boundaries
   - Quantitative statistics provide size, shape, and spatial distribution data for all detected objects
4. Optional novelty assessment results from literature review
5. Current experimental parameters and context

Your goal is to recommend the most scientifically valuable follow-up measurements to maximize research impact.

**Recommendation Categories:**
1. **Statistical Sampling**: Extended sampling for population statistics or different conditions
2. **Multi-Modal Correlative**: Additional techniques for composition, structure, or properties
3. **Dynamic Studies**: Time-resolved measurements of particle evolution
4. **Chemical Analysis**: Compositional analysis of particles/objects
5. **Property Characterization**: Mechanical, electrical, or optical property measurements

**For each recommendation, provide:**
- Specific measurement parameters (field size, resolution, conditions, etc.)
- Scientific justification linked to current findings
- Expected information gain and impact
- Priority level (1=highest, 5=lowest)
- Estimated difficulty (low/medium/high)

You MUST output a valid JSON object with two keys: "analysis_integration" and "measurement_recommendations".

1. **analysis_integration**: (String) How you integrated morphological findings and novelty assessment (if available) to inform recommendations.

2. **measurement_recommendations**: (List of Objects) 2-5 specific measurements, each with:
   * **category**: (String) One of the five categories above
   * **description**: (String) Detailed measurement description with specific parameters
   * **target_regions**: (String) Specific particles/objects or regions to target
   * **scientific_justification**: (String) Why this measurement provides valuable insights
   * **expected_outcomes**: (String) Specific information to be gained
   * **priority**: (Integer) 1-5 priority ranking
   * **difficulty**: (String) "low", "medium", or "high"
   * **parameters**: (Object) Specific measurement parameters

Focus on actionable recommendations that maximize scientific insight while being technically feasible.
"""


================================================
File: agents/exp_agents/llama_wrapper.py
================================================
import io
from PIL import Image
import base64
from types import SimpleNamespace
from llama_cpp import Llama

class LocalLlamaModel():
    """
    This class pretends to be a GenerativeModel.
    """
    def __init__(self, model_path = "../gemma3_27B_QAT_local/gemma-3-27b-it-q4_0.gguf", n_ctx = 3000):
        self.model = Llama(model_path = model_path, n_gpu_layers = -1, n_ctx=8096, verbose= False)
        
    def generate_content(self, contents, generation_config = None, safety_settings = None):
        message = self.prompt_parser(contents)
        response= self.model.create_chat_completion(message, max_tokens=8096)
        choice = response['choices'][0]
        response_text = choice['message']['content']
        finish_reason = choice.get('finish_reason', 'stop')
        response_text = self.fix_json_format(response_text)
        
        #Llama_cpp's finish rason is a string instead of int. Let's map them as int.
        finish_reason_map = {
            "stop": 1,
            "length": 0
        }
        mapped_finish_reason = finish_reason_map.get(finish_reason, -1)

        # Build Gemini-compatible dummy candidates list
        candidate = SimpleNamespace(
            content=response_text,
            finish_reason=mapped_finish_reason
        )
        candidates = [candidate]

        final_response = SimpleNamespace(
            text=response_text,
            candidates=candidates
        )

        return final_response

    def fix_json_format(self, response_text):
        # Remove the additional characters
        if "json" in response_text:
            print("Warning: Removing unexpected 'json' from LLM output.")
            response_text = response_text.replace("json", "")

        if "```" in response_text:
            print("Warning: Removing Markdown code block backticks (``` ) from LLM output.")
            response_text = response_text.replace("```", "")
        return response_text
        
    def prompt_parser(self, genaiList):
        """
        Transform google.generativeai style prompt_parts into llama_cpp messages.
        Treat everything as user messages. Image parts will be converted to 
        {"type": "image", "image": <PIL Image>} format.

        Returns:
            messages: list of dicts in llama_cpp chat format.
        """


        messages = []
        user_messages = []

        for x in genaiList:
            if isinstance(x, str):
                # Plain text parts become text entries
                user_messages.append({"type": "text", "text": x})

            elif isinstance(x, dict):
                # Check for image data
                if x.get("mime_type", "").startswith("image/") and "data" in x:
                    try:
                        # Convert bytes data to PIL image for llama_cpp
                        image_bytes = x["data"]
                        image = Image.open(io.BytesIO(image_bytes))
                        user_messages.append({"type": "image", "image": image})
                    except Exception as e:
                        self.logger.warning(f"Failed to parse image part: {e}")
                        user_messages.append({"type": "text", "text": "\n(Image part parsing failed.)"})
                else:
                    # Any other dict is converted to string text
                    user_messages.append({"type": "text", "text": str(x)})

            else:
                # Any other type is cast to string as fallback
                user_messages.append({"type": "text", "text": str(x)})

        # Combine into final messages list
        messages.append({
            "role": "user",
            "content": user_messages
        })

        # Return parsed messages to be used in model.create_chat_completion
        return messages



================================================
File: agents/exp_agents/microscopy_agent.py
================================================
import json
import os
import logging
import numpy as np

import google.generativeai as genai
from google.generativeai.types import GenerationConfig

from .base_agent import BaseAnalysisAgent
from .recommendation_agent import RecommendationAgent

from .human_feedback import SimpleFeedbackMixin


from .instruct import (
    MICROSCOPY_ANALYSIS_INSTRUCTIONS,
    MICROSCOPY_CLAIMS_INSTRUCTIONS,
    FFT_NMF_PARAMETER_ESTIMATION_INSTRUCTIONS,
    MICROSCOPY_MEASUREMENT_RECOMMENDATIONS_INSTRUCTIONS
)
from .utils import load_image, preprocess_image, convert_numpy_to_jpeg_bytes, normalize_and_convert_to_image_bytes

from atomai.stat import SlidingFFTNMF


class MicroscopyAnalysisAgent(SimpleFeedbackMixin, BaseAnalysisAgent):
    """
    Agent for analyzing microscopy images using generative AI models
    """

    def __init__(self,
                 google_api_key: str | None = None, model_name: str = "gemini-2.5-pro-preview-06-05",
                 local_model: str = None,
                 fft_nmf_settings: dict | None = None, enable_human_feedback: bool = True):
        super().__init__(google_api_key, model_name, local_model, enable_human_feedback=enable_human_feedback)
        
        self.fft_nmf_settings = fft_nmf_settings if fft_nmf_settings else {}
        self.RUN_FFT_NMF = self.fft_nmf_settings.get('FFT_NMF_ENABLED', False)
        self.FFT_NMF_AUTO_PARAMS = self.fft_nmf_settings.get('FFT_NMF_AUTO_PARAMS', False)
        self._recommendation_agent = None

    def _get_fft_nmf_params_from_llm(self, image_blob, system_info) -> tuple[int | None, int | None, str | None]:
        """Get FFT/NMF parameters from LLM based on image analysis."""
        self.logger.info("\n\n🤖 -------------------- ANALYSIS AGENT STEP: sFFT/NMF PARAMETER ESTIMATION -------------------- 🤖\n")
        self.logger.info("Attempting to get FFT/NMF parameters from LLM...")
        
        prompt_parts = [FFT_NMF_PARAMETER_ESTIMATION_INSTRUCTIONS]
        prompt_parts.append("\nImage to analyze for parameters:\n")
        prompt_parts.append(image_blob)
        
        if system_info:
            system_info_text = "\n\nAdditional System Information:\n"
            if isinstance(system_info, str):
                try: 
                    system_info_text += json.dumps(json.loads(system_info), indent=2)
                except json.JSONDecodeError: 
                    system_info_text += system_info
            elif isinstance(system_info, dict): 
                system_info_text += json.dumps(system_info, indent=2)
            else: 
                system_info_text += str(system_info)[:1000]
            prompt_parts.append(system_info_text)
            
        prompt_parts.append("\n\nOutput ONLY the JSON object with 'window_size', 'n_components', and 'explanation'")
        
        param_gen_config = GenerationConfig(response_mime_type="application/json")
        try:
            response = self.model.generate_content(
                contents=prompt_parts,
                generation_config=param_gen_config,
                safety_settings=self.safety_settings,
            )
            
            self.logger.debug(f"LLM parameter estimation raw response: {response}")
            
            if hasattr(response, 'prompt_feedback') and response.prompt_feedback.block_reason:
                self.logger.error(f"LLM parameter estimation blocked: {response.prompt_feedback.block_reason}")
                return None, None, None
                
            if response.candidates and response.candidates[0].finish_reason != 1:
                self.logger.warning(f"LLM parameter estimation finished unexpectedly: {response.candidates[0].finish_reason}")

            raw_text_params = response.text
            result_json_params = json.loads(raw_text_params)
            
            window_size_nm = result_json_params.get("window_size_nm")
            n_components = result_json_params.get("n_components")
            explanation = result_json_params.get("explanation", "No explanation provided.")
            
            # Validate parameters
            params_valid = True
            if not isinstance(window_size_nm, (float, int)) or window_size_nm <= 0:
                self.logger.warning(f"LLM invalid window_size_nm: {window_size_nm}")
                params_valid = False
                window_size_nm = None
                
            if not isinstance(n_components, int) or not (1 <= n_components <= 16):
                self.logger.warning(f"LLM invalid n_components: {n_components}")
                params_valid = False
                n_components = None
                
            if not isinstance(explanation, str) or not explanation.strip():
                explanation = "Invalid/empty explanation from LLM."
                
            if params_valid:
                self.logger.info(f"LLM suggested params: window_size_nm={window_size_nm}, n_components={n_components}")
                return window_size_nm, n_components, explanation
                
            return None, None, explanation
            
        except Exception as e:
            self.logger.error(f"LLM call for FFT/NMF params failed: {e}", exc_info=True)
            return None, None, None

    def _run_fft_nmf_analysis(self, image_path: str, window_size: int, n_components: int, window_step: int) -> tuple[np.ndarray | None, np.ndarray | None]:
        """Run sliding FFT + NMF analysis using AtomAI."""
        try:
            self.logger.info("\n\n🤖 -------------------- ANALYSIS AGENT STEP: SLIDING FFT + NMF ANALYSIS -------------------- 🤖\n")
            self.logger.info("--- Starting Sliding FFT + NMF Analysis (AtomAI) ---")
            
            fft_output_dir = self.fft_nmf_settings.get('output_dir', 'microscopy_analysis')
            os.makedirs(fft_output_dir, exist_ok=True)
            
            base_name = os.path.splitext(os.path.basename(image_path))[0]
            safe_base_name = "".join(c if c.isalnum() else "_" for c in base_name)
            fft_output_base = os.path.join(fft_output_dir, f"{safe_base_name}_output")
            
            # Create AtomAI analyzer with auto-parameter calculation support
            analyzer = SlidingFFTNMF(
                # Use None to trigger auto-calculation, or use LLM-provided values
                window_size_x=window_size if window_size and window_size > 0 else None,
                window_size_y=window_size if window_size and window_size > 0 else None,
                window_step_x=window_step if window_step and window_step > 0 else None,
                window_step_y=window_step if window_step and window_step > 0 else None,
                
                # Use settings from config
                interpolation_factor=self.fft_nmf_settings.get('interpolation_factor', 2),
                zoom_factor=self.fft_nmf_settings.get('zoom_factor', 2),
                hamming_filter=self.fft_nmf_settings.get('hamming_filter', True),
                components=n_components
            )
            
            # AtomAI's analyze_image method handles both file paths and arrays
            components, abundances = analyzer.analyze_image(image_path, output_path=fft_output_base)
            
            self.logger.info(f"AtomAI FFT+NMF analysis complete. Components: {components.shape}, Abundances: {abundances.shape}")
            self._save_fft_nmf_plots(components, abundances, image_path)

            return components, abundances
            
        except Exception as fft_e:
            self.logger.error(f"AtomAI Sliding FFT + NMF analysis failed: {fft_e}", exc_info=True)
            return None, None

    def _analyze_image_base(self, image_path: str, system_info: dict | str | None, 
                            instruction_prompt: str, 
                            additional_top_level_context: str | None = None) -> tuple[dict | None, dict | None]:
        """
        Internal helper for image-based analysis, including optional FFT/NMF.
        Now uses base class methods for common functionality.
        """
        try:
            # Clear any previous stored images
            self._clear_stored_images()
            # Use base class methods for common operations
            system_info = self._handle_system_info(system_info)
            loaded_image = load_image(image_path)
            nm_per_pixel, fov_in_nm = self._calculate_spatial_scale(system_info, loaded_image.shape)

            preprocessed_img_array, _ = preprocess_image(loaded_image)
            image_bytes = convert_numpy_to_jpeg_bytes(preprocessed_img_array)
            image_blob = {"mime_type": "image/jpeg", "data": image_bytes}

            analysis_images = [
                {"label": "Primary Microscopy Image", "data": image_bytes}
            ]

            components_array, abundances_array = None, None
            if self.RUN_FFT_NMF:
                ws_nm, nc, fft_explanation = None, None, None
                if self.FFT_NMF_AUTO_PARAMS:
                    auto_params = self._get_fft_nmf_params_from_llm(image_blob, system_info)
                    if auto_params: 
                        ws_nm, nc, fft_explanation = auto_params
                        
                if fft_explanation: 
                    self.logger.info(f"LLM Explanation for FFT/NMF params: {fft_explanation}")
                
                # Determine window size in pixels. Prioritize LLM physical size, then fall back to config.
                ws_pixels = self.fft_nmf_settings.get('window_size_x') # Default from config (could be None)

                if ws_nm is not None:
                    if nm_per_pixel is not None and nm_per_pixel > 0:
                        calculated_ws_pixels = int(round(ws_nm / nm_per_pixel))
                        # For optimal FFT performance, find the smallest "good" FFT size
                        # that is greater than or equal to the calculated physical size.
                        good_fft_sizes = [16, 24, 32, 48, 64, 80, 96, 120, 128, 
                                          160, 180, 192, 240, 256, 360, 384, 480, 512]
                        
                        # Find the first size in the list that is >= our calculated size
                        ws_pixels = next((size for size in good_fft_sizes if size >= calculated_ws_pixels), 512) # Default to 512 if too large
                        
                        self.logger.info(f"Using LLM-suggested physical window size: {ws_nm:.2f} nm -> {calculated_ws_pixels} pixels. "
                                         f"Selected optimal FFT size: {ws_pixels} pixels.")
                        
                    else:
                        self.logger.warning(f"LLM suggested a physical window size ({ws_nm} nm), but image scale (nm/pixel) is unknown. Falling back to configured pixel window size.")
                elif ws_pixels:
                    self.logger.info(f"Using default/configured window size of {ws_pixels} pixels.")

                if nc is None: 
                    nc = self.fft_nmf_settings.get('components', 4)
                
                # Calculate step size based on window size (if provided) or use config
                if ws_pixels is not None:
                    step = max(1, ws_pixels // 4) # Standard practice: step = window_size / 4
                else:
                    step = self.fft_nmf_settings.get('window_step_x') # Could be None for auto-calc
                
                components_array, abundances_array = self._run_fft_nmf_analysis(image_path, ws_pixels, nc, step)
            
            # Build prompt
            prompt_parts = [instruction_prompt]
            
            if additional_top_level_context:
                prompt_parts.append("\n\n## Special Considerations for This Analysis (Based on Prior Review):\n")
                prompt_parts.append(additional_top_level_context)
                prompt_parts.append("\nPlease ensure your DFT structure recommendations and scientific justifications specifically address or investigate these special considerations alongside your general analysis of the image features. The priority should be given to structures that elucidate these highlighted aspects.\n")
            
            analysis_request_text = "\nPlease analyze the following microscopy image"
            if system_info: 
                analysis_request_text += " using the additional context provided."
            analysis_request_text += "\n\nPrimary Microscopy Image:\n"
            prompt_parts.append(analysis_request_text)
            prompt_parts.append(image_blob)

            # Add FFT/NMF results if available
            if components_array is not None and abundances_array is not None:
                prompt_parts.append("\n\nSupplemental Analysis Data (Sliding FFT + NMF Grayscale Images):")
                num_components = min(components_array.shape[0], abundances_array.shape[0])
                img_format = 'JPEG'
                self.logger.info(f"Adding {num_components} NMF components/abundances as {img_format} to prompt.")
                
                for i in range(num_components):
                    try:
                        comp_bytes = normalize_and_convert_to_image_bytes(components_array[i], log_scale=True, format=img_format)
                        prompt_parts.append(f"\nNMF Component {i+1} (Frequency Pattern - Grayscale):")
                        prompt_parts.append({"mime_type": f"image/{img_format.lower()}", "data": comp_bytes})
                        
                        abun_bytes = normalize_and_convert_to_image_bytes(abundances_array[i], log_scale=False, format=img_format)
                        prompt_parts.append(f"\nNMF Abundance Map {i+1} (Spatial Distribution - Grayscale):")
                        prompt_parts.append({"mime_type": f"image/{img_format.lower()}", "data": abun_bytes})
                    
                        analysis_images.append({
                            "label": f"NMF Abundance Map {i+1} (Spatial Distribution - Grayscale)",
                            "data": abun_bytes
                        })
                    
                    except Exception as convert_e:
                        self.logger.error(f"Failed to convert NMF result {i+1} to image bytes: {convert_e}")
                        prompt_parts.append(f"\n(Error converting NMF result {i+1} image for prompt)")
            else:
                prompt_parts.append("\n\n(No supplemental FFT/NMF image analysis results are provided or FFT/NMF was disabled/failed)")

            analysis_metadata = {
                "image_path": image_path,
                "system_info": system_info,
                "fft_nmf_enabled": self.RUN_FFT_NMF,
                "num_stored_images": len(analysis_images)
            }
            self._store_analysis_images(analysis_images, analysis_metadata)
            
            # Use base class method for system info prompt section
            system_info_section = self._build_system_info_prompt_section(system_info)
            if system_info_section:
                prompt_parts.append(system_info_section)
            
            prompt_parts.append("\n\nProvide your analysis strictly in the requested JSON format.")
            
            self.logger.info("\n\n🤖 -------------------- ANALYSIS AGENT STEP: INTERPRETING RESULTS -------------------- 🤖\n")
            response = self.model.generate_content(
                contents=prompt_parts,
                generation_config=self.generation_config,
                safety_settings=self.safety_settings,
            )
            return self._parse_llm_response(response)  # Using base class method

        except FileNotFoundError:
            self._clear_stored_images()
            self.logger.error(f"Image file not found: {image_path}")
            return None, {"error": "Image file not found", "details": f"Path: {image_path}"}
        except ImportError as e:
            self._clear_stored_images()
            self.logger.error(f"Missing dependency for image processing: {e}")
            return None, {"error": "Missing image processing dependency", "details": str(e)}
        except Exception as e:
            self._clear_stored_images()
            self.logger.exception(f"An unexpected error occurred during image analysis setup or FFT/NMF: {e}")
            return None, {"error": "An unexpected error occurred during analysis setup", "details": str(e)}

    def _save_fft_nmf_plots(self, components: np.ndarray, abundances: np.ndarray, image_path: str):
        """Creates and saves nice plots for each NMF component and its abundance map."""
        import matplotlib.pyplot as plt
        from datetime import datetime

        try:
            # You can define a separate directory for these visualizations
            output_dir = self.fft_nmf_settings.get('visualization_dir', 'fft_nmf_visualizations')
            os.makedirs(output_dir, exist_ok=True)
            
            num_components = components.shape[0]
            self.logger.info(f"Creating and saving {num_components} NMF visualization plots...")

            # --- Create a clean base name and unique timestamp ---
            base_name = os.path.splitext(os.path.basename(image_path))[0]
            safe_base_name = "".join(c if c.isalnum() else "_" for c in base_name)
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

            for i in range(num_components):
                fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
                fig.suptitle(f'NMF Result {i+1}/{num_components}', fontsize=16)

                # --- Left Plot: NMF Component (FFT pattern) ---
                # Using a log scale makes the FFT features much more visible
                comp_img = np.log1p(components[i])
                ax1.imshow(comp_img, cmap='inferno')
                ax1.set_title(f'Component {i+1} (FFT Pattern)')
                ax1.axis('off')

                # --- Right Plot: NMF Abundance Map ---
                im = ax2.imshow(abundances[i], cmap='inferno')
                ax2.set_title(f'Abundance Map {i+1} (Spatial Location)')
                ax2.axis('off')
                fig.colorbar(im, ax=ax2, label="Abundance", fraction=0.046, pad=0.04)

                plt.tight_layout(rect=[0, 0.03, 1, 0.95]) # Adjust layout for the main title

                # --- Save the figure to a file ---
                plot_filename = f"{safe_base_name}_nmf_plot_{i+1}_{timestamp}.png"
                plot_filepath = os.path.join(output_dir, plot_filename)
                plt.savefig(plot_filepath, dpi=150, bbox_inches='tight')
                plt.close(fig) # Close the figure to free up memory

            self.logger.info(f"✅ Saved NMF visualizations to: {output_dir}")

        except Exception as e:
            self.logger.error(f"Failed to create or save NMF plots: {e}", exc_info=True)
    
    def analyze_microscopy_image_for_structure_recommendations(
            self,
            image_path: str | None = None,
            system_info: dict | str | None = None,
            additional_prompt_context: str | None = None,
            cached_detailed_analysis: str | None = None
    ):
        """
        Analyze microscopy image to generate DFT structure recommendations.
        Supports both image-based and text-based analysis paths.
        Now uses base class validation methods for recommendations.
        """
        result_json, error_dict = None, None
        output_analysis_key = "detailed_analysis" 

        # Text-Only path
        if cached_detailed_analysis and additional_prompt_context:
            self.logger.info("Delegating DFT recommendations to RecommendationAgent.")
            
            # Lazy initialization: create the agent only when it's first needed.
            if not self._recommendation_agent:
                self._recommendation_agent = RecommendationAgent(self.google_api_key, self.model_name)
            
            # Correctly delegate the call with all necessary arguments
            return self._recommendation_agent.generate_dft_recommendations_from_text(
                cached_detailed_analysis=cached_detailed_analysis,
                additional_prompt_context=additional_prompt_context,
                system_info=system_info
            )

        # Image-based path
        elif image_path:
            self.logger.info("Generating DFT recommendations from image analysis.")
            instruction_prompt_text = MICROSCOPY_ANALYSIS_INSTRUCTIONS # Standard image analysis prompt
            # additional_prompt_context (novelty string) is passed to _analyze_image_base to be appended
            result_json, error_dict = self._analyze_image_base(
                image_path, system_info, instruction_prompt_text, additional_top_level_context=additional_prompt_context
            )
        else:
            # Neither path is viable
            return {"error": "Either image_path or (cached_detailed_analysis AND additional_prompt_context) must be provided for DFT recommendations."}

        if error_dict:
            return error_dict # Return error if LLM call or parsing failed
        if result_json is None: # Safeguard, should be covered by error_dict
            return {"error": "Analysis failed unexpectedly after LLM processing."}

        # Use the determined key to fetch the main textual output from LLM
        analysis_output_text = result_json.get(output_analysis_key, "Analysis/Reasoning not provided by LLM.")
        recommendations = result_json.get("structure_recommendations", [])
        
        # Use base class validation method
        sorted_recommendations = self._validate_structure_recommendations(recommendations)

        if not sorted_recommendations and not analysis_output_text == "Analysis/Reasoning not provided by LLM.":
             self.logger.warning(f"LLM call successful ('{output_analysis_key}' provided) but no valid recommendations found or parsed.")
        elif not sorted_recommendations:
            self.logger.warning("LLM call did not yield valid recommendations or analysis text.")

        # Return a consistent key for the main textual output for the calling script
        return {"analysis_summary_or_reasoning": analysis_output_text, "recommendations": sorted_recommendations}

    def analyze_microscopy_image_for_claims(self, image_path: str, system_info: dict | str | None = None):
        """
        Analyze microscopy image to generate scientific claims for literature comparison.
        This path always uses image-based analysis.
        Now uses base class validation methods.
        """
        result_json, error_dict = self._analyze_image_base(
            image_path, system_info, MICROSCOPY_CLAIMS_INSTRUCTIONS, additional_top_level_context=None # No special context needed here usually
        )

        if error_dict:
            return error_dict
        if result_json is None: # Safeguard
            return {"error": "Analysis for claims failed unexpectedly after LLM processing."}

        detailed_analysis = result_json.get("detailed_analysis", "Analysis not provided by LLM.")
        scientific_claims = result_json.get("scientific_claims", [])
        
        # Use base class validation method
        valid_claims = self._validate_scientific_claims(scientific_claims)

        if not valid_claims and not detailed_analysis == "Analysis not provided by LLM.":
            self.logger.warning("Analysis for claims successful ('detailed_analysis' provided) but no valid claims found or parsed.")
        elif not valid_claims:
             self.logger.warning("LLM call did not yield valid claims or analysis text for claims workflow.")

        initial_result = {"detailed_analysis": detailed_analysis, "scientific_claims": valid_claims}
        return self._apply_feedback_if_enabled(
            initial_result, 
            image_path=image_path, 
            system_info=system_info
        )
    
    def _get_claims_instruction_prompt(self) -> str:
        return MICROSCOPY_CLAIMS_INSTRUCTIONS
    
    def _get_measurement_recommendations_prompt(self) -> str:
        return MICROSCOPY_MEASUREMENT_RECOMMENDATIONS_INSTRUCTIONS



================================================
File: agents/exp_agents/orchestrator_agent.py
================================================
import logging
import json
import google.generativeai as genai
from google.generativeai.types import GenerationConfig, HarmCategory, HarmBlockThreshold

from .microscopy_agent import MicroscopyAnalysisAgent
from .sam_microscopy_agent import SAMMicroscopyAnalysisAgent
from .atomistic_microscopy_agent import AtomisticMicroscopyAnalysisAgent
from .spectroscopy_agent import SpectroscopyAnalysisAgent
from .instruct import ORCHESTRATOR_INSTRUCTIONS
from ...auth import get_api_key, APIKeyNotFoundError

# Mapping from integer ID to the corresponding agent class
AGENT_MAP = {
    0: MicroscopyAnalysisAgent,
    1: SAMMicroscopyAnalysisAgent,
    2: AtomisticMicroscopyAnalysisAgent,
    3: SpectroscopyAnalysisAgent,
}

class OrchestratorAgent:
    """
    An LLM-powered agent that selects the most appropriate experimental analysis agent
    based on the user's scientific intent.
    """
    def __init__(self, google_api_key: str | None = None, model_name: str = "gemini-2.5-flash-preview-05-20", local_model: str = None):
        if local_model is not None:
            logging.info(f"💻 Using local agent as the orchestrator.")
            from .llama_wrapper import LocalLlamaModel
            self.model = LocalLlamaModel(local_model)
            self.generation_config = None
            self.safety_settings = None
        else:
            logging.info(f"☁️ Using cloud agent as the orchestrator.")
            if google_api_key is None:
                google_api_key = get_api_key('google')
                if not google_api_key:
                    raise APIKeyNotFoundError('google')
            genai.configure(api_key=google_api_key)
        
            self.model = genai.GenerativeModel(model_name)
            self.generation_config = GenerationConfig(response_mime_type="application/json")
            self.safety_settings = {
                HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
            }
        self.logger = logging.getLogger(__name__)

    def _parse_llm_response(self, response) -> tuple[dict | None, dict | None]:
        """Parses the LLM response, expecting JSON."""
        try:
            raw_text = response.text
            first_brace_index = raw_text.find('{')
            last_brace_index = raw_text.rfind('}')
            if first_brace_index != -1 and last_brace_index != -1 and last_brace_index > first_brace_index:
                json_string = raw_text[first_brace_index : last_brace_index + 1]
                return json.loads(json_string), None
            else:
                raise ValueError("Could not find valid JSON object in response.")
        except (json.JSONDecodeError, ValueError) as e:
            self.logger.error(f"Error parsing LLM JSON response: {e}")
            error_dict = {"error": "Failed to parse JSON from LLM response", "details": str(e), "raw_response": response.text}
            return None, error_dict

    def select_agent(self, data_type: str, system_info: dict | str | None = None, image_path: str | None = None) -> tuple[int, str | None]:
        """
        Selects the appropriate experimental agent by asking the LLM.

        Args:
            data_type: The primary type of data, e.g., 'microscopy' or 'spectroscopy'.
            system_info: Additional information about the system or analysis goal.
            image_path: Optional path to an image for visual context.

        Returns:
            A tuple containing the integer key for the selected agent and the reasoning string.
            Returns (-1, error_message) on failure.
        """
        self.logger.info(f"Orchestrator LLM selecting agent for data_type: '{data_type}'")

        # Require system_info to be provided for an informed decision.
        if not system_info or not str(system_info).strip():
            error_msg = "system_info must be provided for the orchestrator to select an agent."
            self.logger.error(error_msg)
            return -1, error_msg

        # If the data type is spectroscopy, the choice is clear.
        if data_type.lower() == 'spectroscopy':
            self.logger.info("Data type is 'spectroscopy'. Selecting Spectroscopy agent directly.")
            return 3, "Data type is 'spectroscopy'. Selecting Spectroscopy agent directly."

        prompt_parts = [ORCHESTRATOR_INSTRUCTIONS]
        
        # Add image analysis if available
        if image_path:
            try:
                from .utils import load_image, preprocess_image, convert_numpy_to_jpeg_bytes
                
                # Load and preprocess image (resize to a max dimension to save tokens)
                image = load_image(image_path)
                resized_image, _ = preprocess_image(image, max_dim=512) # Downsample for the orchestrator
                image_bytes = convert_numpy_to_jpeg_bytes(resized_image, quality=80)
                
                prompt_parts.append("\n--- Image for Context ---")
                prompt_parts.append("This is a downsampled version of the input image used to provide visual context. It may be lower resolution than the original.")
                prompt_parts.append({"mime_type": "image/jpeg", "data": image_bytes})
                
            except Exception as e:
                self.logger.warning(f"Failed to load or analyze image for orchestrator: {e}")
                prompt_parts.append("\n(Image loading/analysis failed, proceeding without image data)")
        
        # Add system info and data type
        prompt_parts.append("\n--- User Request ---")
        prompt_parts.append(f"data_type: {data_type}")
        prompt_parts.append(f"system_info: {str(system_info)}")

        try:
            response = self.model.generate_content(
                contents=prompt_parts,
                generation_config=self.generation_config,
                safety_settings=self.safety_settings,
            )
            result_json, error_dict = self._parse_llm_response(response)

            if error_dict:
                self.logger.error(f"Orchestrator LLM call failed: {error_dict}")
                return -1, f"Orchestrator LLM call failed: {error_dict.get('details', 'Unknown error')}"

            agent_id = result_json.get('agent_id')
            reasoning = result_json.get('reasoning', 'No reasoning provided.')
            self.logger.info(f"\n\n🧠 Orchestrator Reasoning: {reasoning}\n")


            if isinstance(agent_id, int) and agent_id in AGENT_MAP:
                return agent_id, reasoning
            else:
                error_msg = f"LLM returned an invalid agent ID: {agent_id}."
                self.logger.warning(error_msg)
                return -1, error_msg

        except Exception as e:
            error_msg = f"An unexpected error occurred during agent selection: {e}"
            self.logger.exception(error_msg)
            return -1, error_msg


================================================
File: agents/exp_agents/recommendation_agent.py
================================================
import json
import logging
from typing import Dict, Any, List, Optional, Tuple

import google.generativeai as genai
from google.generativeai.types import GenerationConfig, HarmCategory, HarmBlockThreshold

from .instruct import TEXT_ONLY_DFT_RECOMMENDATION_INSTRUCTIONS
from ...auth import get_api_key, APIKeyNotFoundError


class RecommendationAgent:
    """
    An agent specialized in synthesizing textual analysis from various sources 
    (e.g., experimental data analysis, literature novelty reviews) to generate 
    targeted Density Functional Theory structure recommendations.
    
    This agent does not analyze raw experimental data directly. Instead, it operates
    on the textual output of other agents to provide the final recommendations.
    """

    def __init__(self, google_api_key: str | None = None, model_name: str = "gemini-2.5-pro-preview-06-05"):
        """
        Initializes the RecommendationAgent.

        Args:
            google_api_key (str | None, optional): The Google API key. If not provided,
                it will be discovered from the environment. Defaults to None.
            model_name (str, optional): The name of the generative AI model to use. 
                Defaults to "gemini-2.5-pro-preview-06-05".
        """
        if google_api_key is None:
            google_api_key = get_api_key('google')
            if not google_api_key:
                raise APIKeyNotFoundError('google')
        genai.configure(api_key=google_api_key)

        self.model_name = model_name 

        self.model = genai.GenerativeModel(self.model_name)
        self.generation_config = GenerationConfig(response_mime_type="application/json")
        self.safety_settings = {
            HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
        }
        self.logger = logging.getLogger(__name__)
        self.logger.info(f"RecommendationAgent initialized with model: {self.model_name}")

    def _parse_llm_response(self, response) -> Tuple[Optional[Dict], Optional[Dict]]:
        """
        Parses the LLM response, expecting a valid JSON object.

        Args:
            response: The response object from the generative AI model.

        Returns:
            A tuple containing the parsed JSON dictionary (or None) and an error dictionary (or None).
        """
        result_json = None
        error_dict = None
        raw_text = None
        json_string = None

        try:
            raw_text = response.text
            first_brace_index = raw_text.find('{')
            last_brace_index = raw_text.rfind('}')
            if first_brace_index != -1 and last_brace_index != -1 and last_brace_index > first_brace_index:
                json_string = raw_text[first_brace_index : last_brace_index + 1]
                result_json = json.loads(json_string)
            else:
                raise ValueError("Could not find valid JSON object delimiters '{' and '}' in the response text.")

        except (json.JSONDecodeError, AttributeError, IndexError, ValueError) as e:
            error_details = str(e)
            error_raw_response = raw_text if raw_text is not None else getattr(response, 'text', 'N/A')
            self.logger.error(f"Error parsing LLM JSON response: {e}")
            
            if hasattr(response, 'prompt_feedback') and response.prompt_feedback.block_reason:
                block_reason = response.prompt_feedback.block_reason
                error_dict = {"error": f"Content blocked by safety filters", "details": f"Reason: {block_reason}"}
            else:
                error_dict = {"error": "Failed to parse valid JSON from LLM response", "details": error_details, "raw_response": error_raw_response}
        
        except Exception as e:
            self.logger.exception(f"Unexpected error processing response: {e}")
            error_dict = {"error": "Unexpected error processing LLM response", "details": str(e)}
            
        return result_json, error_dict

    def _generate_json_from_text_parts(self, prompt_parts: list) -> Tuple[Optional[Dict], Optional[Dict]]:
        """
        Internal helper to make a text-only call to the LLM and parse the JSON response.

        Args:
            prompt_parts (list): A list of strings and other prompt components.

        Returns:
            A tuple containing the parsed JSON dictionary (or None) and an error dictionary (or None).
        """
        try:
            self.logger.debug(f"Sending text-only prompt to LLM. Total parts: {len(prompt_parts)}")
            response = self.model.generate_content(
                contents=prompt_parts,
                generation_config=self.generation_config,
                safety_settings=self.safety_settings,
            )
            return self._parse_llm_response(response)
        except Exception as e:
            self.logger.exception(f"An unexpected error occurred during text-based LLM call: {e}")
            return None, {"error": "An unexpected error occurred during text-based LLM call", "details": str(e)}

    def generate_dft_recommendations_from_text(
        self,
        cached_detailed_analysis: str,
        additional_prompt_context: str,
        system_info: Optional[Dict[str, Any]] = None
    ) -> Dict[str, Any]:
        """
        Generates DFT structure recommendations by synthesizing a prior analysis
        with novelty context from a literature review.

        Args:
            cached_detailed_analysis (str): The detailed textual analysis from a prior step (e.g., from an image agent).
            additional_prompt_context (str): Textual context outlining novel findings or other special considerations.
            system_info (dict | str | None, optional): System metadata (dict or JSON string). Defaults to None.

        Returns:
            A dictionary containing the reasoning and a sorted list of recommendations.
        """
        self.logger.info("Generating DFT recommendations from cached analysis and novelty context.")
        
        # Build the prompt for the LLM
        prompt_list = [TEXT_ONLY_DFT_RECOMMENDATION_INSTRUCTIONS]
        prompt_list.append("\n\n--- Start of Cached Initial Experimental Data Analysis ---\n")
        prompt_list.append(cached_detailed_analysis)
        prompt_list.append("\n--- End of Cached Initial Experimental Data Analysis ---\n")

        prompt_list.append("\n\n--- Start of Special Considerations (e.g., Novelty Insights) ---\n")
        prompt_list.append(additional_prompt_context)
        prompt_list.append("\n--- End of Special Considerations ---\n")

        if system_info:
            system_info_text = "\n\nAdditional System Information (Metadata):\n"
            if isinstance(system_info, dict):
                system_info_text += json.dumps(system_info, indent=2)
            else:
                # Handle case where system_info might be a pre-formatted string
                system_info_text += str(system_info)
            prompt_list.append(system_info_text)

        prompt_list.append("\n\nProvide your DFT structure recommendations strictly in the requested JSON format.")
        
        # Get and parse the LLM response
        result_json, error_dict = self._generate_json_from_text_parts(prompt_list)

        if error_dict:
            return error_dict
        if result_json is None:
            return {"error": "Recommendation generation failed unexpectedly after LLM processing."}

        # Extract and validate the results from the JSON
        reasoning = result_json.get("detailed_reasoning_for_recommendations", "Reasoning not provided by LLM.")
        recommendations = result_json.get("structure_recommendations", [])
        
        valid_recommendations = []
        if not isinstance(recommendations, list):
            self.logger.warning(f"'structure_recommendations' from LLM was not a list: {recommendations}")
            recommendations = []

        for rec in recommendations:
            if isinstance(rec, dict) and all(k in rec for k in ["description", "scientific_interest", "priority"]):
                if isinstance(rec.get("priority"), int):
                    valid_recommendations.append(rec)
                else:
                    self.logger.warning(f"Recommendation skipped due to invalid priority type (expected int): {rec}")
            else:
                self.logger.warning(f"Recommendation skipped due to missing keys or incorrect dict format: {rec}")

        sorted_recommendations = sorted(valid_recommendations, key=lambda x: x.get("priority", 99))

        if not sorted_recommendations and reasoning != "Reasoning not provided by LLM.":
            self.logger.warning("LLM call successful ('detailed_reasoning' provided) but no valid recommendations found.")
        
        # Return a consistently formatted dictionary
        return {
            "analysis_summary_or_reasoning": reasoning,
            "recommendations": sorted_recommendations
        }


================================================
File: agents/exp_agents/sam_microscopy_agent.py
================================================
import json
import os
from PIL import Image
import logging
import numpy as np

import google.generativeai as genai
from google.generativeai.types import GenerationConfig, HarmCategory, HarmBlockThreshold

from .base_agent import BaseAnalysisAgent

from .instruct import SAM_MICROSCOPY_CLAIMS_INSTRUCTIONS, SAM_MEASUREMENT_RECOMMENDATIONS_INSTRUCTIONS

from .utils import load_image, preprocess_image, convert_numpy_to_jpeg_bytes

from .human_feedback import SimpleFeedbackMixin

from atomai.models import ParticleAnalyzer


class SAMMicroscopyAnalysisAgent(SimpleFeedbackMixin, BaseAnalysisAgent):
    """
    Agent for analyzing microscopy images using Segment Anything Model (SAM) and generative AI models.
    Refactored to inherit from BaseAnalysisAgent and follows the same pattern as other microscopy agents.
    """

    def __init__(self,
                 google_api_key: str | None = None, model_name: str = "gemini-2.5-pro-preview-06-05",
                 local_model: str = None,
                 sam_settings: dict | None = None, enable_human_feedback: bool = False):
        super().__init__(google_api_key, model_name, local_model, enable_human_feedback=enable_human_feedback)
        
        self.sam_settings = sam_settings if sam_settings else {}
        self.RUN_SAM = self.sam_settings.get('SAM_ENABLED', True)
        self.refinement_cycles = self.sam_settings.get('refinement_cycles', 0)
        self.save_visualizations = self.sam_settings.get('save_visualizations', True)

    def _save_visualization(self, overlay_image: np.ndarray, stage: str, cycle: int, particle_count: int, params: dict):
        """Save visualization images for each refinement step."""
        try:
            from datetime import datetime
            
            # Create output directory
            output_dir = "sam_analysis_visualizations"
            os.makedirs(output_dir, exist_ok=True)
            
            # Generate filename with timestamp and info
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f"{stage}_cycle{cycle:02d}_{particle_count}particles_{timestamp}.png"
            filepath = os.path.join(output_dir, filename)
            
            # Save image
            Image.fromarray(overlay_image).save(filepath)
            
            # Save parameters as text file
            params_filename = f"{stage}_cycle{cycle:02d}_params_{timestamp}.txt"
            params_filepath = os.path.join(output_dir, params_filename)
            with open(params_filepath, 'w') as f:
                f.write(f"Stage: {stage}\n")
                f.write(f"Cycle: {cycle}\n")
                f.write(f"Particle Count: {particle_count}\n")
                f.write(f"Timestamp: {timestamp}\n")
                f.write(f"Parameters:\n")
                for key, value in params.items():
                    f.write(f"  {key}: {value}\n")
            
            print(f"📸 Saved {stage} visualization: {filename} ({particle_count} particles)")
            
        except Exception as e:
            self.logger.error(f"Failed to save visualization: {e}")

    def _run_sam_analysis(self, image_path: str, nm_per_pixel: float | None = None) -> tuple[np.ndarray | None, dict | None]:
        """Run SAM particle segmentation analysis with optional iterative refinement."""
        try:
            self.logger.info(f"--- Starting SAM Particle Segmentation Analysis (nm/pixel: {nm_per_pixel}) ---")
            
            # Initialize ParticleAnalyzer with settings from config
            model_type = self.sam_settings.get('model_type', 'vit_h')
            checkpoint_path = self.sam_settings.get('checkpoint_path', None)
            device = self.sam_settings.get('device', 'auto')
            
            analyzer = ParticleAnalyzer(
                checkpoint_path=checkpoint_path,
                model_type=model_type,
                device=device
            )
        
            # Load and preprocess image
            raw_image = load_image(image_path)
            if len(raw_image.shape) == 3:
                raw_image = np.mean(raw_image, axis=2).astype(np.uint8)

            # Use preprocessed (resized) image for BOTH SAM and LLM
            image_array, pixel_rescaling_factor_to_original = preprocess_image(raw_image)
            self.original_preprocessed_image = image_array # This is the rescaled image (used for LLM refinement)

            # Initial analysis parameters from config or defaults
            current_params = {
                "use_clahe": self.sam_settings.get('use_clahe', False),
                "sam_parameters": self.sam_settings.get('sam_parameters', 'default'),
                "min_area": self.sam_settings.get('min_area', 500),
                "max_area": self.sam_settings.get('max_area', 50000),
                "use_pruning": self.sam_settings.get('use_pruning', True),
                "pruning_iou_threshold": self.sam_settings.get('pruning_iou_threshold', 0.5)
            }
            
            # Run initial analysis
            self.logger.info("\n\n🤖 -------------------- ANALYSIS AGENT STEP: SAM PARTICLE SEGMENTATION -------------------- 🤖\n")
            self.logger.info(f"Running initial SAM analysis with params: {current_params}")
            sam_result = analyzer.analyze(image_array, params=current_params)
            
            # Save initial visualization if requested
            if self.save_visualizations:
                initial_overlay = ParticleAnalyzer.visualize_particles(sam_result, show_plot=False, show_labels=True, show_centroids=True)
                self._save_visualization(initial_overlay, "initial", 0, sam_result['total_count'], current_params)
            
            # Run refinement cycles if requested
            for cycle in range(self.refinement_cycles):
                self.logger.info(f"\n\n🤖 -------------------- ANALYSIS AGENT STEP: PARAMETER REFINEMENT CYCLE {cycle + 1}/{self.refinement_cycles} -------------------- 🤖\n")                
                # Create visualization of current result
                current_overlay = ParticleAnalyzer.visualize_particles(
                    sam_result, 
                    show_plot=False, 
                    show_labels=True, 
                    show_centroids=True
                )
                
                # Get refinement suggestions from LLM
                new_params = self._get_refinement_parameters(current_overlay, sam_result['total_count'], current_params)
                
                if new_params is None:
                    self.logger.warning(f"Failed to get refinement parameters for cycle {cycle + 1}, stopping refinement")
                    break
                
                # Check if parameters actually changed
                if new_params == current_params:
                    print(f"📋 No parameter changes suggested for cycle {cycle + 1}, stopping refinement")
                    self.logger.info(f"No parameter changes suggested for cycle {cycle + 1}, stopping refinement")
                    break
                
                # Show what changed
                changed_params = {k: v for k, v in new_params.items() if current_params.get(k) != v}
                if changed_params:
                    print(f"🔄 PARAMETER CHANGES for cycle {cycle + 1}:")
                    for key, value in changed_params.items():
                        print(f"   {key}: {current_params.get(key)} → {value}")
                    print()
                
                # Run analysis with refined parameters
                self.logger.info(f"Running refined analysis with params: {new_params}")
                refined_result = analyzer.analyze(image_array, params=new_params)
                
                # Save refined visualization if requested
                if self.save_visualizations:
                    refined_overlay = ParticleAnalyzer.visualize_particles(refined_result, show_plot=False, show_labels=True, show_centroids=True)
                    self._save_visualization(refined_overlay, "refined", cycle + 1, refined_result['total_count'], new_params)
                
                # Update current result and parameters
                sam_result = refined_result
                current_params = new_params
                
                self.logger.info(f"Cycle {cycle + 1} completed: {sam_result['total_count']} particles detected")
            
            # Create final visualization overlay
            final_overlay = ParticleAnalyzer.visualize_particles(
                sam_result, 
                show_plot=False, 
                show_labels=True, 
                show_centroids=True
            )
            
            # Extract comprehensive morphological statistics
            self.logger.info("\n\n🤖 -------------------- ANALYSIS AGENT STEP: MORPHOLOGICAL STATISTICS EXTRACTION -------------------- 🤖\n")
            self.logger.info(f"Extracting comprehensive morphological statistics for {sam_result['total_count']} particles")
            particles_df = ParticleAnalyzer.particles_to_dataframe(sam_result)
            
            if not particles_df.empty:
                # Determine the effective scaling factors based on original image pixels and nm/pixel
                if nm_per_pixel is not None and nm_per_pixel > 0:
                    linear_scale_factor = pixel_rescaling_factor_to_original * nm_per_pixel
                    area_scale_factor = linear_scale_factor ** 2
                    unit_suffix = "nm"
                    area_unit_suffix = "nm_sq" # Use a file-system friendly suffix
                else:
                    linear_scale_factor = pixel_rescaling_factor_to_original
                    area_scale_factor = pixel_rescaling_factor_to_original ** 2
                    unit_suffix = "pixels"
                    area_unit_suffix = "pixels_sq"

                summary_stats = {
                    'total_particles': sam_result['total_count'],
                    
                    # Size statistics
                    f'mean_area_{area_unit_suffix}': float(particles_df['area'].mean()) * area_scale_factor,
                    f'std_area_{area_unit_suffix}': float(particles_df['area'].std()) * area_scale_factor,
                    f'area_range_{area_unit_suffix}': [float(particles_df['area'].min()) * area_scale_factor, float(particles_df['area'].max()) * area_scale_factor],
                    f'area_percentiles_{area_unit_suffix}': [p * area_scale_factor for p in particles_df['area'].quantile([0.25, 0.5, 0.75]).tolist()],
                    
                    # Shape statistics
                    'mean_circularity': float(particles_df['circularity'].mean()),
                    'std_circularity': float(particles_df['circularity'].std()),
                    'circularity_range': [float(particles_df['circularity'].min()), float(particles_df['circularity'].max())],
                    
                    'mean_aspect_ratio': float(particles_df['aspect_ratio'].mean()),
                    'std_aspect_ratio': float(particles_df['aspect_ratio'].std()),
                    'aspect_ratio_range': [float(particles_df['aspect_ratio'].min()), float(particles_df['aspect_ratio'].max())],
                    
                    'mean_solidity': float(particles_df['solidity'].mean()),
                    'std_solidity': float(particles_df['solidity'].std()),
                    'solidity_range': [float(particles_df['solidity'].min()), float(particles_df['solidity'].max())],
                    
                    # Derived size statistics
                    f'mean_equiv_diameter_{unit_suffix}': float(particles_df['equiv_diameter'].mean()) * linear_scale_factor,
                    f'std_equiv_diameter_{unit_suffix}': float(particles_df['equiv_diameter'].std()) * linear_scale_factor,
                    f'equiv_diameter_range_{unit_suffix}': [float(particles_df['equiv_diameter'].min()) * linear_scale_factor, float(particles_df['equiv_diameter'].max()) * linear_scale_factor],
                    
                    f'mean_perimeter_{unit_suffix}': float(particles_df['perimeter'].mean()) * linear_scale_factor,
                    f'std_perimeter_{unit_suffix}': float(particles_df['perimeter'].std()) * linear_scale_factor,
                    f'perimeter_range_{unit_suffix}': [float(particles_df['perimeter'].min()) * linear_scale_factor, float(particles_df['perimeter'].max()) * linear_scale_factor],
                    
                    # Analysis metadata
                    'final_parameters': current_params,
                    'refinement_cycles_completed': min(cycle + 1 if 'cycle' in locals() else 0, self.refinement_cycles), # 'cycle' is defined in the loop
                    'image_rescaling_factor': pixel_rescaling_factor_to_original if pixel_rescaling_factor_to_original != 1.0 else "None (original dimensions used)",
                    'physical_scale_nm_per_pixel': nm_per_pixel if nm_per_pixel is not None else "N/A"
                }
            else:
                # Handle empty results
                # Need to define unit_suffix and area_unit_suffix even if particles_df is empty
                if nm_per_pixel is not None and nm_per_pixel > 0:
                    unit_suffix = "nm"
                    area_unit_suffix = "nm_sq"
                else:
                    unit_suffix = "pixels"
                    area_unit_suffix = "pixels_sq"

                summary_stats = {
                    'total_particles': 0,
                    f'mean_area_{area_unit_suffix}': 0, f'std_area_{area_unit_suffix}': 0, f'area_range_{area_unit_suffix}': [0, 0], f'area_percentiles_{area_unit_suffix}': [0, 0, 0],
                    'mean_circularity': 0, 'std_circularity': 0, 'circularity_range': [0, 0],
                    'mean_aspect_ratio': 0, 'std_aspect_ratio': 0, 'aspect_ratio_range': [0, 0],
                    'mean_solidity': 0, 'std_solidity': 0, 'solidity_range': [0, 0],
                    f'mean_equiv_diameter_{unit_suffix}': 0, f'std_equiv_diameter_{unit_suffix}': 0, f'equiv_diameter_range_{unit_suffix}': [0, 0],
                    f'mean_perimeter_{unit_suffix}': 0, f'std_perimeter_{unit_suffix}': 0, f'perimeter_range_{unit_suffix}': [0, 0],
                    'final_parameters': current_params,
                    'refinement_cycles_completed': min(cycle + 1 if 'cycle' in locals() else 0, self.refinement_cycles),
                    'image_rescaling_factor': pixel_rescaling_factor_to_original if pixel_rescaling_factor_to_original != 1.0 else "None (original dimensions used)",
                    'physical_scale_nm_per_pixel': nm_per_pixel if nm_per_pixel is not None else "N/A"
                }
            
            total_cycles = summary_stats['refinement_cycles_completed']
            self.logger.info(f"SAM analysis complete after {total_cycles} refinement cycles. Final count: {sam_result['total_count']} particles.")
            
            # Save final visualization if requested
            if self.save_visualizations:
                # Ensure the summary_stats has the correct key for the final cycle
                if 'cycle' in locals():
                    summary_stats['refinement_cycles_completed'] = cycle + 1

                self._save_visualization(final_overlay, "final", total_cycles, sam_result['total_count'], current_params)
                print(f"💾 Visualizations saved to: sam_analysis_visualizations/")
            
            return final_overlay, summary_stats
            
        except Exception as sam_e:
            self.logger.error(f"SAM particle segmentation analysis failed: {sam_e}", exc_info=True)
            return None, None

    def _get_refinement_parameters(self, overlay_image: np.ndarray, particle_count: int, current_params: dict) -> dict | None:
        """Get refinement parameters from LLM based on visual analysis of current results."""
        try:
            self.logger.info(f"Requesting parameter refinement for {particle_count} particles")
            
            # Convert both images to bytes for LLM
            original_bytes = convert_numpy_to_jpeg_bytes(self.original_preprocessed_image)
            overlay_bytes = convert_numpy_to_jpeg_bytes(overlay_image)
            
            # Build prompt for refinement with BOTH images
            prompt_parts = [SAM_MICROSCOPY_CLAIMS_INSTRUCTIONS]
            prompt_parts.append(f"\n\nCurrent Analysis Results:")
            prompt_parts.append(f"- Particle count: {particle_count}")
            prompt_parts.append(f"- Current parameters: {json.dumps(current_params, indent=2)}")
            
            # Add ORIGINAL image first for comparison
            prompt_parts.append(f"\n\n**ORIGINAL MICROSCOPY IMAGE (for reference):**")
            prompt_parts.append("This is the original microscopy image showing the actual particles to be segmented.")
            prompt_parts.append({"mime_type": "image/jpeg", "data": original_bytes})
            
            # Add SEGMENTATION overlay second for evaluation
            prompt_parts.append(f"\n\n**CURRENT SEGMENTATION RESULT:**")
            prompt_parts.append("This shows the current segmentation with detected particles outlined in red, centroids as green dots, and particle IDs labeled.")
            prompt_parts.append({"mime_type": "image/jpeg", "data": overlay_bytes})
            
            prompt_parts.append("\n\n**ANALYSIS TASK:**")
            prompt_parts.append("Compare the segmentation result against the original image. Are the detected particles the right size? Are particles being missed or incorrectly detected? Are the red outlines accurately capturing the particle boundaries visible in the original image?")
            prompt_parts.append("\nProvide refined parameters to improve the segmentation accuracy.")
            
            # Query LLM for refinement
            response = self.model.generate_content(
                contents=prompt_parts,
                generation_config=self.generation_config,
                safety_settings=self.safety_settings,
            )
            
            result_json, error_dict = self._parse_llm_response(response)  # Using base class method
            
            if error_dict:
                self.logger.warning(f"LLM refinement request failed: {error_dict}")
                return None
            
            reasoning = result_json.get("reasoning", "No reasoning provided")
            new_parameters = result_json.get("parameters", {})
            
            # Log AND print reasoning for visibility
            self.logger.info(f"LLM refinement reasoning: {reasoning}")
            self.logger.info(f"LLM suggested parameters: {new_parameters}")
            
            print(f"\n🧠 LLM REFINEMENT REASONING:")
            print(f"   {reasoning}")
            print(f"\n🔧 SUGGESTED PARAMETERS:")
            for key, value in new_parameters.items():
                print(f"   {key}: {value}")
            print()
            
            # Validate new parameters
            expected_keys = {"use_clahe", "sam_parameters", "min_area", "max_area", "pruning_iou_threshold"}
            if not all(key in new_parameters for key in expected_keys):
                self.logger.warning(f"Invalid parameter set from LLM, missing keys: {expected_keys - set(new_parameters.keys())}")
                return None
            
            # Add use_pruning=True since it's always enabled
            new_parameters["use_pruning"] = True
            
            # Basic validation
            if not isinstance(new_parameters.get("use_clahe"), bool):
                self.logger.warning("Invalid use_clahe parameter type")
                return None
            
            if new_parameters.get("sam_parameters") not in ["default", "sensitive", "ultra-permissive"]:
                self.logger.warning("Invalid sam_parameters value")
                return None
            
            if not (isinstance(new_parameters.get("min_area"), int) and new_parameters.get("min_area") > 0):
                self.logger.warning("Invalid min_area parameter")
                return None
            
            if not (isinstance(new_parameters.get("max_area"), int) and new_parameters.get("max_area") > new_parameters.get("min_area")):
                self.logger.warning("Invalid max_area parameter")
                return None
            
            pruning_threshold = new_parameters.get("pruning_iou_threshold")
            if not (isinstance(pruning_threshold, (int, float)) and 0.0 <= pruning_threshold <= 1.0):
                self.logger.warning("Invalid pruning_iou_threshold parameter")
                return None
            
            return new_parameters
            
        except Exception as e:
            self.logger.error(f"Error getting refinement parameters: {e}")
            return None

    def _analyze_image_base(self, image_path: str, system_info: dict | str | None, 
                            instruction_prompt: str) -> tuple[dict | None, dict | None]:
        """
        Internal helper for image-based analysis, including optional SAM segmentation.
        Now uses base class methods for common functionality.
        """
        try:
            # Clear any previous stored images
            self._clear_stored_images()
            # Use base class methods for common operations
            system_info = self._handle_system_info(system_info)
            loaded_image = load_image(image_path)
            nm_per_pixel, fov_in_nm = self._calculate_spatial_scale(system_info, loaded_image.shape)

            preprocessed_img_array, _ = preprocess_image(loaded_image)
            image_bytes = convert_numpy_to_jpeg_bytes(preprocessed_img_array) # This is the rescaled image
            image_blob = {"mime_type": "image/jpeg", "data": image_bytes}

            analysis_images = [
                {"label": "Primary Microscopy Image", "data": image_bytes}
            ]

            sam_overlay, sam_stats = None, None
            if self.RUN_SAM:
                sam_overlay, sam_stats = self._run_sam_analysis(image_path, nm_per_pixel=nm_per_pixel)
            
            if sam_overlay is not None:
                    sam_overlay_bytes = convert_numpy_to_jpeg_bytes(sam_overlay)
                    analysis_images.append({
                        "label": "SAM Particle Segmentation Overlay (particles outlined in red with centroids and labels)",
                        "data": sam_overlay_bytes
                    })
                    
            prompt_parts = [instruction_prompt]
            
            analysis_request_text = "\nPlease analyze the following microscopy image"
            if system_info: 
                analysis_request_text += " using the additional context provided."
            analysis_request_text += "\n\nPrimary Microscopy Image:\n"
            prompt_parts.append(analysis_request_text)
            prompt_parts.append(image_blob)

            if sam_overlay is not None and sam_stats is not None:
                # Convert SAM overlay to bytes for LLM
                sam_overlay_bytes = convert_numpy_to_jpeg_bytes(sam_overlay)
                prompt_parts.append("\n\nSupplemental SAM Particle Segmentation Analysis:")
                prompt_parts.append(f"Detected {sam_stats['total_particles']} particles with comprehensive morphological analysis:")
                
                # Determine units for prompt
                unit_key_suffix = "pixels"
                area_key_suffix = "pixels_sq"
                unit_suffix_display = "pixels"
                area_unit_suffix_display = "pixels²"
                if sam_stats.get('physical_scale_nm_per_pixel') != "N/A":
                    unit_key_suffix = "nm"
                    area_key_suffix = "nm_sq"
                    unit_suffix_display = "nm"
                    area_unit_suffix_display = "nm²"
                    prompt_parts.append(f"\n**Size Analysis (in real-world units):**")
                else:
                    prompt_parts.append(f"\n**Size Analysis (in original image pixels):**")

                # Size statistics
                prompt_parts.append(f"- Mean area: {sam_stats[f'mean_area_{area_key_suffix}']:.1f} ± {sam_stats[f'std_area_{area_key_suffix}']:.1f} {area_unit_suffix_display}")
                prompt_parts.append(f"- Area range: {sam_stats[f'area_range_{area_key_suffix}'][0]:.0f} to {sam_stats[f'area_range_{area_key_suffix}'][1]:.0f} {area_unit_suffix_display}")
                prompt_parts.append(f"- Area quartiles (Q1, Q2, Q3): {sam_stats[f'area_percentiles_{area_key_suffix}'][0]:.0f}, {sam_stats[f'area_percentiles_{area_key_suffix}'][1]:.0f}, {sam_stats[f'area_percentiles_{area_key_suffix}'][2]:.0f} {area_unit_suffix_display}")
                prompt_parts.append(f"- Mean equivalent diameter: {sam_stats[f'mean_equiv_diameter_{unit_key_suffix}']:.1f} ± {sam_stats[f'std_equiv_diameter_{unit_key_suffix}']:.1f} {unit_suffix_display}")
                prompt_parts.append(f"- Mean perimeter: {sam_stats[f'mean_perimeter_{unit_key_suffix}']:.1f} ± {sam_stats[f'std_perimeter_{unit_key_suffix}']:.1f} {unit_suffix_display}")
                
                # Shape statistics
                prompt_parts.append(f"\n**Shape Analysis:**")
                prompt_parts.append(f"- Mean circularity: {sam_stats['mean_circularity']:.3f} ± {sam_stats['std_circularity']:.3f} (range: {sam_stats['circularity_range'][0]:.3f} to {sam_stats['circularity_range'][1]:.3f})")
                prompt_parts.append(f"- Mean aspect ratio: {sam_stats['mean_aspect_ratio']:.2f} ± {sam_stats['std_aspect_ratio']:.2f} (range: {sam_stats['aspect_ratio_range'][0]:.2f} to {sam_stats['aspect_ratio_range'][1]:.2f})")
                prompt_parts.append(f"- Mean solidity: {sam_stats['mean_solidity']:.3f} ± {sam_stats['std_solidity']:.3f} (range: {sam_stats['solidity_range'][0]:.3f} to {sam_stats['solidity_range'][1]:.3f})")
                
                # Add analysis notes to prompt
                if sam_stats.get('image_rescaling_factor') != "None (original dimensions used)":
                    prompt_parts.append(f"\n**Note:** Original image was rescaled by a factor of {sam_stats['image_rescaling_factor']:.2f} for analysis.")
                if sam_stats.get('physical_scale_nm_per_pixel') != "N/A":
                    prompt_parts.append(f"All size statistics have been converted to real-world units using a scale of {sam_stats['physical_scale_nm_per_pixel']:.4f} nm/pixel.")
                elif sam_stats.get('image_rescaling_factor') != "None (original dimensions used)":
                    prompt_parts.append(f"All size statistics have been converted back to original pixel units.")

                # Include refinement info if available
                if sam_stats.get('refinement_cycles_completed', 0) > 0:
                    prompt_parts.append(f"\n**Analysis Parameters:**")
                    prompt_parts.append(f"- Refinement cycles completed: {sam_stats['refinement_cycles_completed']}")
                    prompt_parts.append(f"- Final analysis parameters: {json.dumps(sam_stats['final_parameters'], indent=2)}")
                
                prompt_parts.append("\nSAM Particle Segmentation Overlay (particles outlined in red with centroids and labels):")
                prompt_parts.append({"mime_type": "image/jpeg", "data": sam_overlay_bytes})
            else:
                prompt_parts.append("\n\n(No supplemental SAM particle segmentation analysis results are provided or SAM was disabled/failed)")

            # Use base class method for system info prompt section
            system_info_section = self._build_system_info_prompt_section(system_info)
            if system_info_section:
                prompt_parts.append(system_info_section)
            
            prompt_parts.append("\n\nProvide your analysis strictly in the requested JSON format.")

            analysis_metadata = {
                "image_path": image_path,
                "system_info": system_info,
                "sam_enabled": self.RUN_SAM,
                "particle_count": sam_stats.get('total_particles', 0) if sam_stats else 0,
                "num_stored_images": len(analysis_images)
            }
            self._store_analysis_images(analysis_images, analysis_metadata)

            
            self.logger.info("\n\n🤖 -------------------- ANALYSIS AGENT STEP: INTERPRETING RESULTS -------------------- 🤖\n")
            response = self.model.generate_content(
                contents=prompt_parts,
                generation_config=self.generation_config,
                safety_settings=self.safety_settings,
            )
            return self._parse_llm_response(response)  # Using base class method

        except FileNotFoundError:
            self._clear_stored_images()
            self.logger.error(f"Image file not found: {image_path}")
            return None, {"error": "Image file not found", "details": f"Path: {image_path}"}
        except ImportError as e:
            self._clear_stored_images()
            self.logger.error(f"Missing dependency for SAM analysis: {e}")
            return None, {"error": "Missing SAM dependency", "details": str(e)}
        except Exception as e:
            self._clear_stored_images()
            self.logger.exception(f"An unexpected error occurred during SAM image analysis setup: {e}")
            return None, {"error": "An unexpected error occurred during analysis setup", "details": str(e)}

    def analyze_microscopy_image_for_claims(self, image_path: str, system_info: dict | str | None = None):
        """
        Analyze microscopy image to generate scientific claims for literature comparison.
        This path always uses image-based analysis with SAM segmentation.
        Now uses base class validation methods.
        """
        result_json, error_dict = self._analyze_image_base(
            image_path, system_info, SAM_MICROSCOPY_CLAIMS_INSTRUCTIONS
        )

        if error_dict:
            return error_dict
        if result_json is None:
            return {"error": "SAM analysis for claims failed unexpectedly after LLM processing."}

        detailed_analysis = result_json.get("detailed_analysis", "Analysis not provided by LLM.")
        scientific_claims = result_json.get("scientific_claims", [])
        
        # Use base class validation method
        valid_claims = self._validate_scientific_claims(scientific_claims)

        if not valid_claims and not detailed_analysis == "Analysis not provided by LLM.":
            self.logger.warning("SAM analysis for claims successful ('detailed_analysis' provided) but no valid claims found or parsed.")
        elif not valid_claims:
             self.logger.warning("LLM call did not yield valid claims or analysis text for SAM claims workflow.")

        initial_result = {"detailed_analysis": detailed_analysis, "scientific_claims": valid_claims}
        return self._apply_feedback_if_enabled(
            initial_result,
            image_path=image_path,
            system_info=system_info
        )
    
    def _get_claims_instruction_prompt(self) -> str:
        return SAM_MICROSCOPY_CLAIMS_INSTRUCTIONS
    
    def _get_measurement_recommendations_prompt(self) -> str:
        return SAM_MEASUREMENT_RECOMMENDATIONS_INSTRUCTIONS


================================================
File: agents/exp_agents/spectroscopy_agent.py
================================================
# exp_agents/spectroscopy_agent.py
import json
import os
import logging
import numpy as np
from typing import Dict, Any, Optional, List, Tuple
from io import BytesIO
from datetime import datetime

import google.generativeai as genai
from google.generativeai.types import GenerationConfig, HarmCategory, HarmBlockThreshold

from .base_agent import BaseAnalysisAgent
from .utils import convert_numpy_to_jpeg_bytes, normalize_and_convert_to_image_bytes
from .utils import create_multi_abundance_overlays
from .instruct import (
    SPECTROSCOPY_ANALYSIS_INSTRUCTIONS, 
    COMPONENT_INITIAL_ESTIMATION_INSTRUCTIONS,
    COMPONENT_VISUAL_COMPARISON_INSTRUCTIONS,
    SPECTROSCOPY_CLAIMS_INSTRUCTIONS,
    SPECTROSCOPY_MEASUREMENT_RECOMMENDATIONS_INSTRUCTIONS
)

from .human_feedback import SimpleFeedbackMixin

from atomai.stat import SpectralUnmixer


class SpectroscopyAnalysisAgent(SimpleFeedbackMixin, BaseAnalysisAgent):
    """
    Agent for analyzing hyperspectral/spectroscopy data using generative AI models.
    Refactored to inherit from BaseAnalysisAgent and includes LLM-guided spectral unmixing.
    """

    def __init__(self, api_key: str | None = None, model_name: str = "gemini-2.5-pro-preview-06-05", 
                 local_model: str = None,
                 spectral_unmixing_settings: dict | None = None,
                 output_dir: str = "spectroscopy_output",
                 enable_human_feedback: bool = False):
        super().__init__(api_key, model_name, local_model, enable_human_feedback=enable_human_feedback)
        
        # Spectral unmixing settings
        default_settings = {
            'method': 'nmf',
            'n_components': 4,
            'normalize': True,
            'enabled': True,
            'auto_components': True,
            'max_iter': 500
        }
        self.spectral_settings = spectral_unmixing_settings if spectral_unmixing_settings else default_settings
        self.run_spectral_unmixing = self.spectral_settings.get('enabled', True)

        self.output_dir = output_dir
        os.makedirs(output_dir, exist_ok=True)

    def _load_hyperspectral_data(self, data_path: str) -> np.ndarray:
        """
        Load hyperspectral data from numpy array.
        Assumes data_path points to a .npy file.
        """
        try:
            if not data_path.endswith('.npy'):
                raise ValueError(f"Expected .npy file, got: {data_path}")
            
            data = np.load(data_path)
            self.logger.info(f"Loaded hyperspectral data with shape: {data.shape}")
            
            # Ensure 3D format (h, w, spectral_channels)
            if data.ndim == 2:
                self.logger.warning("2D data detected, assuming single spectrum. Reshaping to (1, 1, n_channels)")
                data = data.reshape(1, 1, -1)
            elif data.ndim != 3:
                raise ValueError(f"Expected 2D or 3D data, got {data.ndim}D")
                
            return data
            
        except Exception as e:
            self.logger.error(f"Failed to load hyperspectral data from {data_path}: {e}")
            raise

    def _load_metadata_from_json(self, data_path: str) -> dict:
        """
        Load metadata from companion JSON file.
        Assumes JSON file has same name as .npy file but with .json extension.
        """
        import json
        import os
        
        # Get JSON file path (same name as .npy but with .json extension)
        base_path = os.path.splitext(data_path)[0]
        json_path = f"{base_path}.json"
        
        try:
            if os.path.exists(json_path):
                with open(json_path, 'r') as f:
                    metadata = json.load(f)
                self.logger.info(f"Loaded metadata from: {json_path}")
                return metadata
            else:
                self.logger.warning(f"No metadata file found at: {json_path}")
                return {}
                
        except Exception as e:
            self.logger.error(f"Failed to load metadata from {json_path}: {e}")
            return {}

    def _llm_estimate_components_from_system(self, hspy_data: np.ndarray, 
                                           system_info: Dict[str, Any] = None) -> int:
        """
        Step 1: LLM estimates optimal number of components based on system description.
        """
        try:
            self.logger.info("\n\n🤖 -------------------- ANALYSIS AGENT STEP: COMPONENT PARAMETER ESTIMATION -------------------- 🤖\n")
            self.logger.info("Step 1: Getting LLM initial component estimate from system description")
            
            # Build prompt for initial estimation
            prompt_parts = [COMPONENT_INITIAL_ESTIMATION_INSTRUCTIONS]
            
            # Add hyperspectral data information
            h, w, e = hspy_data.shape
            prompt_parts.append(f"\n\n--- Hyperspectral Data Information ---")
            prompt_parts.append(f"Data dimensions: {h}x{w} spatial pixels, {e} spectral channels")
            prompt_parts.append(f"Data statistics:")
            prompt_parts.append(f"- Mean intensity: {np.mean(hspy_data):.3f}")
            prompt_parts.append(f"- Intensity range: {np.min(hspy_data):.3f} to {np.max(hspy_data):.3f}")
            prompt_parts.append(f"- Signal-to-noise estimate: {np.mean(hspy_data) / np.std(hspy_data):.2f}")
            
            # Add system information
            if system_info:
                prompt_parts.append("\n\n--- System Information ---")
                if isinstance(system_info, dict):
                    prompt_parts.append(json.dumps(system_info, indent=2))
                else:
                    prompt_parts.append(str(system_info))
            else:
                prompt_parts.append("\n\n--- System Information ---")
                prompt_parts.append("No specific system information provided.")
            
            prompt_parts.append("\n\nBased on the system description and data characteristics, estimate the optimal number of spectral components.")
            
            # Query LLM
            response = self.model.generate_content(
                contents=prompt_parts,
                generation_config=self.generation_config,
                safety_settings=self.safety_settings,
            )
            
            result_json, error_dict = self._parse_llm_response(response)  # Using base class method
            
            if error_dict:
                self.logger.warning(f"LLM initial estimation failed: {error_dict}")
                return self.spectral_settings.get('n_components', 4)
            
            estimated_components = result_json.get('estimated_components', None)
            reasoning = result_json.get('reasoning', 'No reasoning provided')
            
            self.logger.info(f"LLM initial estimate: {estimated_components} components")
            self.logger.info(f"LLM reasoning: {reasoning}")
            
            # Validate estimate (must be reasonable)
            if isinstance(estimated_components, int) and 2 <= estimated_components <= 15:
                return estimated_components
            else:
                self.logger.warning(f"Invalid LLM estimate {estimated_components}, using default")
                return self.spectral_settings.get('n_components', 4)
                
        except Exception as e:
            self.logger.error(f"LLM initial estimation failed: {e}")
            return self.spectral_settings.get('n_components', 4)

    def _create_nmf_summary_plot(self, components: np.ndarray, abundance_maps: np.ndarray, 
                           n_comp: int, system_info: Dict[str, Any] = None) -> bytes:
        """
        Create a single summary plot showing all components and abundance maps.
        Now includes proper energy axis labeling.
        """
        import matplotlib.pyplot as plt
        
        try:
            # Create energy axis
            n_channels = components.shape[1]
            energy_axis, xlabel, has_energy_info = self._create_energy_axis(n_channels, system_info)
            
            # Create figure with 2 rows: spectra on top, abundance maps on bottom
            fig, axes = plt.subplots(2, n_comp, figsize=(n_comp * 3, 6))
            
            if n_comp == 1:
                axes = axes.reshape(2, 1)
            
            for i in range(n_comp):
                # Top row: Component spectra with proper energy axis
                axes[0, i].plot(energy_axis, components[i, :], 'b-', linewidth=1.5)
                axes[0, i].set_title(f'NMF Component {i+1}', fontsize=10)
                axes[0, i].set_xlabel(xlabel)
                if i == 0:
                    axes[0, i].set_ylabel('Intensity')
                axes[0, i].grid(True, alpha=0.3)
                
                # Bottom row: Abundance maps
                im = axes[1, i].imshow(abundance_maps[..., i], cmap='seismic', aspect='auto')
                axes[1, i].set_title(f'Abundance Map {i+1}', fontsize=10)
                axes[1, i].axis('off')
                plt.colorbar(im, ax=axes[1, i], fraction=0.046, pad=0.04)
            
            # Add energy info to title if available
            if has_energy_info:
                plt.suptitle(f'NMF Analysis: {n_comp} Components (Energy Calibrated)', fontsize=14, y=0.95)
            else:
                plt.suptitle(f'NMF Analysis: {n_comp} Components', fontsize=14, y=0.95)
                
            plt.tight_layout()
            
            # Save to bytes
            buf = BytesIO()
            plt.savefig(buf, format='jpeg', dpi=150, bbox_inches='tight')
            buf.seek(0)
            image_bytes = buf.getvalue()
            plt.close()
            
            return image_bytes
            
        except Exception as e:
            self.logger.error(f"Failed to create summary plot for {n_comp} components: {e}")
            return None

    def _llm_compare_visual_results(self, test_images: List[Dict], initial_estimate: int,
                                   system_info: Dict[str, Any] = None) -> int:
        """
        Step 3: LLM compares visual results to make final decision.
        """
        try:
            self.logger.info("\n\n🤖 ------------------ ANALYSIS AGENT STEP: DECIDING ON THE FINAL NUMBER OF COMPONENTS ------------------ 🤖\n")
            self.logger.info("Step 3: LLM comparing visual results for final decision")
            
            # Build prompt for visual comparison
            prompt_parts = [COMPONENT_VISUAL_COMPARISON_INSTRUCTIONS]
            
            # Add context
            prompt_parts.append(f"\n\n--- Context ---")
            prompt_parts.append(f"Initial LLM estimate: {initial_estimate} components")
            
            if system_info:
                prompt_parts.append("\nSystem Information:")
                if isinstance(system_info, dict):
                    prompt_parts.append(json.dumps(system_info, indent=2))
                else:
                    prompt_parts.append(str(system_info))
            
            # Add visual comparison
            prompt_parts.append(f"\n\n--- Visual Comparison ---")
            prompt_parts.append("Compare these NMF results:")
            
            for result in test_images:
                n_comp = result['n_components']
                label = "Under-sampling" if n_comp < initial_estimate else "Over-sampling"
                prompt_parts.append(f"\n\n**{n_comp} Components ({label}):**")
                prompt_parts.append({
                    "mime_type": "image/jpeg", 
                    "data": result['image']
                })
            
            prompt_parts.append(f"\n\nBased on visual analysis, decide between {test_images[0]['n_components']} or {test_images[1]['n_components']} components, or recommend your initial estimate of {initial_estimate}.")
            
            # Query LLM
            response = self.model.generate_content(
                contents=prompt_parts,
                generation_config=self.generation_config,
                safety_settings=self.safety_settings,
            )
            
            result_json, error_dict = self._parse_llm_response(response)  # Using base class method
            
            if error_dict:
                self.logger.warning(f"LLM visual comparison failed: {error_dict}")
                return initial_estimate
            
            final_components = result_json.get('final_components', None)
            reasoning = result_json.get('reasoning', 'No reasoning provided')
            
            self.logger.info(f"LLM final decision: {final_components} components")
            self.logger.info(f"LLM reasoning: {reasoning}")
            
            # Validate final decision
            tested_values = [r['n_components'] for r in test_images] + [initial_estimate]
            if final_components in tested_values:
                return final_components
            else:
                self.logger.warning(f"LLM chose untested value {final_components}, using closest")
                return min(tested_values, key=lambda x: abs(x - final_components))
                
        except Exception as e:
            self.logger.error(f"LLM visual comparison failed: {e}")
            return initial_estimate

    def _llm_guided_component_workflow(self, hspy_data: np.ndarray, system_info: dict = None) -> tuple[int, np.ndarray, np.ndarray]:
        """
        Four-step LLM-guided component optimization workflow with human-viewable outputs:
        1. LLM estimates optimal components based on system description
        2. Test under/over-sampling around that estimate
        3. LLM compares visual results to finalize decision
        4. Run final analysis with chosen number
        
        Returns:
            Tuple of (final_n_components, final_components, final_abundance_maps)
        """
        from datetime import datetime
        
        # Initialize reasoning log
        reasoning_log = {
            "workflow_start": datetime.now().isoformat(),
            "data_shape": hspy_data.shape,
            "system_info": system_info
        }
        
        # Step 1: LLM initial estimate based on system description
        initial_estimate = self._llm_estimate_components_from_system(hspy_data, system_info)
        
        # Log and save reasoning
        reasoning_log["initial_estimate"] = initial_estimate
        print(f"  💡 LLM suggests: {initial_estimate} components")
        
        # Save Step 1 reasoning
        step1_data = {
            "step": "initial_estimation",
            "estimated_components": initial_estimate,
            "system_info": system_info,
            "data_characteristics": {
                "shape": hspy_data.shape,
                "mean_intensity": float(np.mean(hspy_data)),
                "std_intensity": float(np.std(hspy_data))
            }
        }
        self._save_component_reasoning("step1_initial_estimate", step1_data)
        
        # Step 2: Test under-sampling and over-sampling around estimate
        test_components = [
            max(2, initial_estimate - 2),  # Under-sampling
            initial_estimate + 3           # Over-sampling  
        ]
        
        reasoning_log["test_range"] = test_components
        self.logger.info("\n\n🤖 -------------------- ANALYSIS AGENT STEP: COMPONENT TESTING -------------------- 🤖\n")
        print(f"Step 2: Testing component numbers: {test_components}")
        
        # Run test analyses
        test_images = []
        for n_comp in test_components:
            print(f"  🧪 Testing {n_comp} components...")
            
            try:
                temp_unmixer = SpectralUnmixer(
                    method=self.spectral_settings.get('method', 'nmf'),
                    n_components=n_comp,
                    normalize=self.spectral_settings.get('normalize', True),
                    max_iter=self.spectral_settings.get('max_iter', 500),
                    random_state=42
                )
                
                components, abundance_maps = temp_unmixer.fit(hspy_data)
                # Pass system_info here!
                summary_image = self._create_nmf_summary_plot(components, abundance_maps, n_comp, system_info)
                
                if summary_image:
                    test_images.append({
                        'n_components': n_comp,
                        'image': summary_image
                    })
                    print(f"    ✅ Generated test result for {n_comp} components")
                
            except Exception as e:
                print(f"    ❌ Failed test with {n_comp} components: {e}")
                self.logger.warning(f"Failed test analysis with {n_comp} components: {e}")
        
        # Save test images for human review
        self._save_component_comparison_plot(test_images, initial_estimate)
        
        # Step 3: LLM visual comparison to finalize decision
        print("Step 3: LLM comparing test results...")
        if len(test_images) >= 2:
            final_n_components = self._llm_compare_visual_results(
                test_images, initial_estimate, system_info
            )
            print(f"  🎯 Final decision: {final_n_components} components")
        else:
            print("  ⚠️  Insufficient test results, using initial estimate")
            final_n_components = initial_estimate
            self.logger.warning("Insufficient test results for comparison, using initial estimate")
        
        # Log final decision
        reasoning_log["final_decision"] = final_n_components
        
        # Save Step 3 reasoning
        step3_data = {
            "step": "final_comparison",
            "test_components": test_components,
            "initial_estimate": initial_estimate,
            "final_decision": final_n_components,
            "test_results_available": len(test_images)
        }
        self._save_component_reasoning("step3_final_decision", step3_data)
        
        # Step 4: Run final analysis with chosen number
        self.logger.info("\n\n🤖 -------------------- ANALYSIS AGENT STEP: FINAL SPECTRAL UNMIXING -------------------- 🤖\n")
        print("Step 4: Running final analysis...")
        final_unmixer = SpectralUnmixer(
            method=self.spectral_settings.get('method', 'nmf'),
            n_components=final_n_components,
            normalize=self.spectral_settings.get('normalize', True),
            **{k: v for k, v in self.spectral_settings.items() 
            if k not in ['method', 'n_components', 'normalize', 'enabled', 'auto_components']}
        )
        
        final_components, final_abundance_maps = final_unmixer.fit(hspy_data)
        
        # Complete reasoning log
        reasoning_log["workflow_end"] = datetime.now().isoformat()
        reasoning_log["final_reasoning"] = f"Selected {final_n_components} components based on LLM comparison of test results"
        
        # Create final summary files
        summary_path, reasoning_path = self._create_final_results_summary(
            final_n_components, final_components, final_abundance_maps, reasoning_log
        )
        
        # Final console summary
        print("\n📋 Component Selection Summary:")
        print(f"   Initial estimate: {initial_estimate}")
        print(f"   Test range: {test_components}")
        print(f"   Final decision: {final_n_components}")
        print(f"   Results saved to: {self.output_dir}/")
        print("=" * 50)
        
        self.logger.info(f"LLM-guided component workflow completed: {final_n_components} components selected")
        
        return final_n_components, final_components, final_abundance_maps

    def _perform_spectral_unmixing(self, hspy_data: np.ndarray, system_info: Dict[str, Any] = None) -> Tuple[np.ndarray, np.ndarray]:
        """
        Perform spectral unmixing using the complete LLM-guided workflow.
        """
        try:
            self.logger.info("--- Starting Spectral Unmixing Analysis ---")
            
            if self.spectral_settings.get('auto_components', True):
                # Use complete LLM-guided workflow
                final_n_components, components, abundance_maps = self._llm_guided_component_workflow(
                    hspy_data, system_info
                )
                return components, abundance_maps
            else:
                # Use user-specified number
                n_components = self.spectral_settings.get('n_components', 4)
                self.logger.info(f"Using user-specified {n_components} components")
                
                unmixer = SpectralUnmixer(
                    method=self.spectral_settings.get('method', 'nmf'),
                    n_components=n_components,
                    normalize=self.spectral_settings.get('normalize', True),
                    **{k: v for k, v in self.spectral_settings.items() 
                       if k not in ['method', 'n_components', 'normalize', 'enabled', 'auto_components']}
                )
                
                components, abundance_maps = unmixer.fit(hspy_data)
                return components, abundance_maps
            
        except Exception as e:
            self.logger.error(f"Spectral unmixing failed: {e}")
            raise

    def _create_component_abundance_pairs(self, components: np.ndarray, abundance_maps: np.ndarray, 
                                    system_info: Dict[str, Any] = None, save_plots: bool = True) -> List[bytes]:
        """
        Create individual component-abundance pair images with consistent y-scaling for final analysis.
        Each pair shows one component spectrum alongside its abundance map.
        
        Args:
            components: Array of shape (n_components, n_channels)
            abundance_maps: Array of shape (height, width, n_components)
            system_info: System metadata for energy axis creation
            save_plots: Whether to save plots to disk for inspection
            
        Returns:
            List of image bytes, one for each component-abundance pair
        """
        import matplotlib.pyplot as plt
        from datetime import datetime
        
        pair_images = []
        n_components = components.shape[0]
        saved_files = []
        
        try:
            # Create energy axis using system info
            n_channels = components.shape[1]
            energy_axis, xlabel, has_energy_info = self._create_energy_axis(n_channels, system_info)
            
            # Calculate global y-scale for consistent spectrum scaling
            global_min = np.min(components)
            global_max = np.max(components)
            y_margin = (global_max - global_min) * 0.05  # 5% margin
            y_limits = (global_min - y_margin, global_max + y_margin)
            
            self.logger.info(f"Creating {n_components} component-abundance pairs with consistent y-scale: {y_limits}")
            
            # Create timestamp for saved files
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            
            for i in range(n_components):
                fig, (ax_spectrum, ax_abundance) = plt.subplots(1, 2, figsize=(12, 4))
                
                # Left plot: Component spectrum with consistent y-scaling
                ax_spectrum.plot(energy_axis, components[i, :], 'b-', linewidth=2)
                ax_spectrum.set_ylim(y_limits)  # Apply consistent y-scaling
                ax_spectrum.set_xlabel(xlabel)
                ax_spectrum.set_ylabel('Intensity')
                ax_spectrum.set_title(f'Component {i+1} Spectrum')
                ax_spectrum.grid(True, alpha=0.3)
                
                # Add energy range info to title if available
                if has_energy_info:
                    energy_range = f" ({energy_axis[0]:.0f}-{energy_axis[-1]:.0f} {xlabel.split('(')[1].rstrip(')')})"
                    ax_spectrum.set_title(f'Component {i+1} Spectrum{energy_range}')
                
                # Right plot: Abundance map with proper aspect ratio
                im = ax_abundance.imshow(abundance_maps[..., i], cmap='viridis', aspect='equal')
                ax_abundance.set_title(f'Component {i+1} Abundance Map')
                ax_abundance.axis('off')
                
                # Add colorbar for abundance map
                plt.colorbar(im, ax=ax_abundance, fraction=0.046, pad=0.04, label='Abundance')
                
                # Add overall title with y-scale info
                fig.suptitle(f'Component {i+1} Analysis (Y-scale: {y_limits[0]:.2e} to {y_limits[1]:.2e})', 
                            fontsize=12, y=0.98)
                
                plt.tight_layout()
                
                # Save to disk if requested
                if save_plots:
                    filename = f"component_{i+1}_pair_{timestamp}.png"
                    filepath = os.path.join(self.output_dir, filename)
                    plt.savefig(filepath, dpi=150, bbox_inches='tight')
                    saved_files.append(filepath)
                    self.logger.info(f" Saved component pair {i+1}: {filename}")
                
                # Save to bytes for LLM
                buf = BytesIO()
                plt.savefig(buf, format='jpeg', dpi=150, bbox_inches='tight')
                buf.seek(0)
                pair_images.append(buf.getvalue())
                plt.close()
                
            self.logger.info(f"Successfully created {len(pair_images)} component-abundance pair images")
            
            if save_plots:
                print(f"\n📊 Component-abundance pairs saved to: {self.output_dir}/")
                print("    These are the exact plots being sent to the LLM for analysis")
            
            return pair_images
            
        except Exception as e:
            self.logger.error(f"Failed to create component-abundance pairs: {e}")
            return []

    def _validate_structure_inputs(self, structure_image_path: str = None, 
                                 structure_system_info: Dict[str, Any] = None) -> tuple[str, Dict[str, Any]]:
        """
        Validate and clean up structure inputs, ensuring consistency.
        
        Returns:
            tuple: (validated_structure_image_path, validated_structure_system_info)
        """
        # If structure_system_info provided without structure_image_path, warn and ignore
        if structure_system_info and not structure_image_path:
            self.logger.warning("structure_system_info provided but no structure_image_path - ignoring metadata")
            structure_system_info = None
        
        # Validate structure image path exists
        if structure_image_path and not os.path.exists(structure_image_path):
            self.logger.warning(f"Structure image not found: {structure_image_path}")
            structure_image_path = None
            structure_system_info = None  # Also clear metadata if image doesn't exist
        
        return structure_image_path, structure_system_info

    def analyze_hyperspectral_data_for_claims(self, data_path: str, metadata_path: Dict[str, Any] | None = None,
                                            structure_image_path: str = None, structure_system_info: Dict[str, Any] = None
                                            ) -> Dict[str, Any]:
        """
        Analyze hyperspectral data to generate scientific claims for literature comparison.
        
        Args:
            data_path: Path to hyperspectral data file (.npy)
            metadata_path: Dictionary with experimental metadata OR path to JSON file
            structure_image_path: Optional path to 2D greyscale structure image for context
            structure_system_info: Optional metadata for the structure image
            
        Returns:
            Dictionary containing detailed analysis and scientific claims
        """
        try:
            # Validate structure inputs
            structure_image_path, structure_system_info = self._validate_structure_inputs(
                structure_image_path, structure_system_info
            )
            
            # Handle metadata_path properly - it can be a dict or a string path
            if isinstance(metadata_path, dict):
                # Already a dictionary, use it directly
                system_info = metadata_path
            elif isinstance(metadata_path, str):
                # It's a file path, load from JSON
                system_info = self._load_metadata_from_json(metadata_path)
            elif metadata_path is None:
                # Try to load companion JSON file based on data_path
                system_info = self._load_metadata_from_json(data_path)
            else:
                self.logger.warning(f"Invalid metadata_path type: {type(metadata_path)}")
                system_info = {}

            # Use the shared analysis workflow but with claims-specific instructions
            result = self._analyze_hyperspectral_data_base(
                data_path=data_path,
                system_info=system_info,
                instruction_prompt=SPECTROSCOPY_CLAIMS_INSTRUCTIONS,
                analysis_type="claims",
                structure_image_path=structure_image_path,
                structure_system_info=structure_system_info
            )
            
            if "error" in result:
                return result
            
            # Extract claims-specific fields
            detailed_analysis = result.get("detailed_analysis", "Analysis not provided by LLM.")
            scientific_claims = result.get("scientific_claims", [])
            
            # Use base class validation method
            valid_claims = self._validate_scientific_claims(scientific_claims)
            
            # Log results
            if not valid_claims and detailed_analysis != "Analysis not provided by LLM.":
                self.logger.warning("Spectroscopic claims analysis successful but no valid claims found.")
            elif not valid_claims:
                self.logger.warning("LLM call did not yield valid claims or analysis text for spectroscopic workflow.")
            else:
                self.logger.info(f"Successfully generated {len(valid_claims)} scientific claims from spectroscopic analysis.")
            
            initial_result = {"detailed_analysis": detailed_analysis, "scientific_claims": valid_claims}
            return self._apply_feedback_if_enabled(
                initial_result,
                data_path=data_path,
                system_info=system_info,
                structure_image_path=structure_image_path
            )
            
        except Exception as e:
            self.logger.exception(f"Error during hyperspectral claims analysis: {e}")
            return {"error": "Hyperspectral claims analysis failed", "details": str(e)}
        
    def _get_claims_instruction_prompt(self) -> str:
        return SPECTROSCOPY_CLAIMS_INSTRUCTIONS

    def _analyze_hyperspectral_data_base(self, data_path: str, system_info: Dict[str, Any] | None = None,
                                    instruction_prompt: str = None, analysis_type: str = "standard",
                                    structure_image_path: str = None, structure_system_info: Dict[str, Any] = None
                                    ) -> Dict[str, Any]:
        """
        Base method for hyperspectral data analysis
        """
        self._clear_stored_images()
        # Use base class method for system info handling
        if isinstance(system_info, str):
            system_info = self._handle_system_info(system_info)
        elif system_info is None:
            system_info = self._load_metadata_from_json(data_path)
        
        # Use base class method for structure_system_info handling
        if isinstance(structure_system_info, str) and os.path.exists(structure_system_info):
            structure_system_info = self._handle_system_info(structure_system_info)

        # Load hyperspectral data
        analysis_desc = "claims generation" if analysis_type == "claims" else "analysis"
        self.logger.info(f"Loading hyperspectral data for {analysis_desc}: {data_path}")
        hspy_data = self._load_hyperspectral_data(data_path)
        
        components = None
        abundance_maps = None
        
        # Perform spectral unmixing if enabled
        if self.run_spectral_unmixing:
            self.logger.info(f"Performing spectral unmixing for {analysis_desc}...")
            components, abundance_maps = self._perform_spectral_unmixing(hspy_data, system_info)
        
        # Create component-abundance pairs for final analysis
        component_pair_images = []
        if components is not None and abundance_maps is not None:
            self.logger.info("Creating component-abundance pairs for LLM analysis...")
            component_pair_images = self._create_component_abundance_pairs(components, abundance_maps, system_info)
        
        analysis_images = []
        for i, pair_img_bytes in enumerate(component_pair_images):
            analysis_images.append({
                "label": f"Component {i+1} Pair (Spectrum + Abundance Map)",
                "data": pair_img_bytes
            })


        # Build prompt for LLM analysis
        prompt_parts = [instruction_prompt or SPECTROSCOPY_ANALYSIS_INSTRUCTIONS]
        
        # Add data information (shared between both analysis types)
        energy_info_text = self._build_energy_info_for_prompt(hspy_data, system_info)
        prompt_parts.append(f"\n\nHyperspectral Data Information:\n{energy_info_text}")
        
        # Add spectral unmixing information if available
        if components is not None:
            prompt_parts.append(f"- Spectral unmixing method: {self.spectral_settings.get('method', 'nmf').upper()}")
            prompt_parts.append(f"- Number of spectral components identified: {components.shape[0]}")
            prompt_parts.append(f"- Component spectra shape: {components.shape}")
            prompt_parts.append(f"- Spatial abundance maps shape: {abundance_maps.shape}")
        else:
            prompt_parts.append("- No spectral unmixing performed")

        # Add structure image and overlays if provided
        overlay_bytes = None
        if structure_image_path and os.path.exists(structure_image_path):
            try:
                from .utils import convert_numpy_to_jpeg_bytes, load_image
                import cv2                
                
                self.logger.info(f"Loading structural context image: {structure_image_path}")
                structure_img = load_image(structure_image_path)
                
                # For the structural context image, we want minimal processing to preserve
                # the original contrast, unlike primary microscopy analysis. We will just
                # ensure it's a standard 8-bit grayscale image without aggressive enhancement.
                if len(structure_img.shape) == 3:
                    structure_img_gray = cv2.cvtColor(structure_img, cv2.COLOR_RGB2GRAY)
                else:
                    structure_img_gray = structure_img # Already grayscale

                # Try to create abundance overlays first
                if abundance_maps is not None:
                    overlay_bytes = self._create_structure_abundance_overlays(
                        structure_img_gray, abundance_maps, system_info
                    )
                
                if overlay_bytes:
                    # Use overlays (which include the original structure image as first panel)
                    prompt_parts.append("\n\n**Structure-Abundance Correlation Analysis:**")
                    prompt_parts.append("These overlays show where each NMF component is most abundant (top 15% of values) overlaid on the structural image. The first panel shows the original structural image for reference. Each subsequent panel shows the same structure with colored overlays indicating where each component is most concentrated. Look for spatial correlations between these (thresholded) abundance patterns and structural features.")
                    prompt_parts.append({"mime_type": "image/jpeg", "data": overlay_bytes})
                    self.logger.info("Added abundance overlays to LLM prompt (includes structure image)")
                else:
                    # Fallback: use standalone structure image if overlays failed
                    structure_img_bytes = convert_numpy_to_jpeg_bytes(structure_img_gray)
                    prompt_parts.append("\n\n**Structural Context Image for Correlation:**")
                    prompt_parts.append("This is a structural image providing spatial context. Try to correlate the spectroscopic components and their abundance maps with the spatial features in this image.")
                    prompt_parts.append({"mime_type": "image/jpeg", "data": structure_img_bytes})
                    self.logger.info("Added standalone structure image to analysis prompt (overlays failed)")
                
                # Add structure system info only if structure image was successfully processed
                structure_info_section = self._build_system_info_prompt_section(structure_system_info)
                if structure_info_section:
                    prompt_parts.append("\n\nStructural Context Metadata:")
                    prompt_parts.append(structure_info_section.replace("\n\nAdditional System Information (Metadata):\n", ""))
                
                self.logger.info("Successfully processed structure image for analysis")
                
            except Exception as e:
                self.logger.warning(f"Failed to load structure image: {e}")
        elif structure_image_path:
            self.logger.warning(f"Structure image not found: {structure_image_path}")
        
        # Add component-abundance pairs for LLM interpretation
        if component_pair_images:
            prompt_parts.append("\n\nSpectral Component Analysis (Individual Component-Abundance Pairs):")
            prompt_parts.append("Each component is shown with its spectrum (left) and spatial abundance map (right).")
            prompt_parts.append("All component spectra use the same y-axis scale for direct comparison.")
            
            for i, pair_img_bytes in enumerate(component_pair_images):
                prompt_parts.append(f"\n\nComponent {i+1} Pair (Spectrum + Abundance Map):")
                prompt_parts.append({"mime_type": "image/jpeg", "data": pair_img_bytes})
        else:
            prompt_parts.append("\n\n(No spectroscopic component analysis images available)")
        
        # Use base class method for system info prompt section
        system_info_section = self._build_system_info_prompt_section(system_info)
        if system_info_section:
            prompt_parts.append(system_info_section)
        
        prompt_parts.append("\n\nProvide your analysis in the requested JSON format.")

        analysis_metadata = {
            "data_path": data_path,
            "system_info": system_info,
            "spectral_unmixing_enabled": self.run_spectral_unmixing,
            "n_components": components.shape[0] if components is not None else 0,
            "structure_image_included": structure_image_path is not None,
            "num_stored_images": len(analysis_images)
        }
        self._store_analysis_images(analysis_images, analysis_metadata)
        
        # Send to LLM for analysis
        self.logger.info("\n\n🤖 -------------------- ANALYSIS AGENT STEP: INTERPRETING RESULTS -------------------- 🤖\n")
        self.logger.info(f"Sending hyperspectral {analysis_desc} request to LLM with {len(component_pair_images)} component pairs...")
        response = self.model.generate_content(
            contents=prompt_parts,
            generation_config=self.generation_config,
            safety_settings=self.safety_settings,
        )
        
        # Use base class method for parsing LLM response
        result_json, error_dict = self._parse_llm_response(response)
        
        if error_dict:
            return error_dict
        
        if result_json is None:
            return {"error": f"Hyperspectral {analysis_desc} failed unexpectedly after LLM processing."}
        
        # Add quantitative data if available
        if components is not None and analysis_type == "standard":
            result_json["quantitative_analysis"] = {
                "spectral_unmixing_method": self.spectral_settings.get('method', 'nmf'),
                "n_components": components.shape[0],
                "component_spectra_shape": components.shape,
                "abundance_maps_shape": abundance_maps.shape,
                "data_statistics": {
                    "mean_intensity": float(np.mean(hspy_data)),
                    "std_intensity": float(np.std(hspy_data)),
                    "min_intensity": float(np.min(hspy_data)),
                    "max_intensity": float(np.max(hspy_data)),
                }
            }
        
        return result_json

    def _save_claims_results(self, claims_result: Dict[str, Any], output_filename: str = None) -> str:
        """
        Save claims analysis results to file for further processing.
        
        Args:
            claims_result: Result dictionary from generate_analysis_claims
            output_filename: Optional custom filename
            
        Returns:
            Path to saved file
        """
        if output_filename is None:
            from datetime import datetime
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            output_filename = f"spectroscopy_claims_{timestamp}.json"
        
        output_path = os.path.join(self.output_dir, output_filename)
        
        try:
            with open(output_path, 'w') as f:
                json.dump(claims_result, f, indent=2, default=str)
            
            self.logger.info(f"Claims analysis results saved to: {output_path}")
            return output_path
            
        except Exception as e:
            self.logger.error(f"Failed to save claims results: {e}")
            raise

    def analyze_hyperspectral_data(self, data_path: str, metadata_path: str,
                                   structure_image_path: str = None,
                                   structure_system_info: Dict[str, Any] = None
                                   ) -> Dict[str, Any]:
        """
        Analyze hyperspectral data for materials characterization.
        
        Args:
            data_path: Path to hyperspectral data file
            metadata_path: Additional metadata about the sample/experiment
            structure_image_path: Optional path to 2D greyscale structure image for context
            structure_system_info: Optional metadata for the structure image
        
        Returns:
            Dictionary containing analysis results
        """
        try:
            # Validate structure inputs
            structure_image_path, structure_system_info = self._validate_structure_inputs(
                structure_image_path, structure_system_info
            )
            
            # Load system info from metadata path
            system_info = self._load_metadata_from_json(metadata_path)
            
            # Use the shared base method with standard analysis instructions
            result = self._analyze_hyperspectral_data_base(
                data_path=data_path,
                system_info=system_info,
                instruction_prompt=SPECTROSCOPY_ANALYSIS_INSTRUCTIONS,
                analysis_type="standard",
                structure_image_path=structure_image_path,
                structure_system_info=structure_system_info
            )
            
            if "error" in result:
                return result
            
            self.logger.info("Hyperspectral analysis completed successfully")
            return result
            
        except Exception as e:
            self.logger.exception(f"Error during hyperspectral analysis: {e}")
            return {"error": "Hyperspectral analysis failed", "details": str(e)}

    def _build_energy_info_for_prompt(self, hspy_data: np.ndarray, system_info: dict = None) -> str:
        """Build energy information string for LLM prompt."""
        
        info_lines = [
            f"- Data shape: {hspy_data.shape}",
            f"- Spatial dimensions: {hspy_data.shape[:2]}"
        ]
        
        if system_info and "energy_range" in system_info:
            energy_info = system_info["energy_range"]
            start = energy_info.get("start")
            end = energy_info.get("end")
            units = energy_info.get("units", "eV")
            
            if start is not None and end is not None:
                dispersion = (end - start) / (hspy_data.shape[-1] - 1)
                info_lines.extend([
                    f"- Energy range: {start} to {end} {units}",
                    f"- Number of energy channels: {hspy_data.shape[-1]}",
                    f"- Energy dispersion: {dispersion:.3f} {units}/channel"
                ])
            else:
                info_lines.append(f"- Number of spectral channels: {hspy_data.shape[-1]} (energy not calibrated)")
        else:
            info_lines.append(f"- Number of spectral channels: {hspy_data.shape[-1]} (energy axis not provided)")
        
        return "\n".join(info_lines)

    def _save_component_reasoning(self, step_name: str, reasoning_data: dict):
        """Save LLM reasoning for human review."""
        from datetime import datetime
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"{step_name}_{timestamp}.json"
        filepath = os.path.join(self.output_dir, filename)
        
        with open(filepath, 'w') as f:
            json.dump(reasoning_data, f, indent=2)
        
        print(f"💾 Saved {step_name} reasoning: {filename}")
        return filepath

    def _save_component_comparison_plot(self, test_images: list, initial_estimate: int):
        """Save the component comparison plots for human review."""
        if not test_images:
            return
            
        from datetime import datetime
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        
        # Save individual test result images
        for i, result in enumerate(test_images):
            filename = f"component_test_{result['n_components']}comp_{timestamp}.png"
            filepath = os.path.join(self.output_dir, filename)
            
            with open(filepath, 'wb') as f:
                f.write(result['image'])
            
            print(f"📊 Saved component test ({result['n_components']} components): {filename}")

    def _create_structure_abundance_overlays(self, structure_img_gray: np.ndarray, 
                                           abundance_maps: np.ndarray, 
                                           save_plots: bool = True) -> bytes:
        """
        Create abundance overlays on structure image for LLM correlation analysis.
        
        Args:
            structure_img_gray: 2D grayscale structure image
            abundance_maps: NMF abundance maps (height, width, n_components)
            save_plots: Whether to save plots to disk for inspection
            
        Returns:
            Image bytes for LLM prompt, or None if failed
        """
        try:
            self.logger.info(f"Creating abundance overlays for {abundance_maps.shape[2]} components")
            
            # Create multi-component overlay using the utility function
            overlay_bytes = create_multi_abundance_overlays(
                structure_image=structure_img_gray,
                abundance_maps=abundance_maps,
                threshold_percentile=85.0,  # Show top 15% of abundance values
                alpha=0.5,
                use_simple_colors=True  # Use solid colors for clearer LLM analysis
            )
            
            # Save the overlay that goes to LLM (following existing pattern)
            if save_plots:
                timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                filename = f"abundance_overlays_{timestamp}.png"
                filepath = os.path.join(self.output_dir, filename)
                
                with open(filepath, 'wb') as f:
                    f.write(overlay_bytes)
                
                self.logger.info(f" Saved abundance overlays: {filename}")
            
            return overlay_bytes
            
        except Exception as e:
            self.logger.warning(f"Failed to create abundance overlays: {e}")
            return None
    
    def _create_final_results_summary(self, final_n_components: int, components: np.ndarray, 
                                    abundance_maps: np.ndarray, reasoning_log: dict):
        """Create comprehensive summary for human review."""
        from datetime import datetime
        import matplotlib.pyplot as plt
        
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

        # Create energy axis
        n_channels = components.shape[1]
        system_info = reasoning_log.get('system_info')  # Get from reasoning log
        energy_axis, xlabel, has_energy_info = self._create_energy_axis(n_channels, system_info)
        
        # 1. Save detailed reasoning log
        reasoning_file = f"component_selection_log_{timestamp}.json"
        reasoning_path = os.path.join(self.output_dir, reasoning_file)
        
        with open(reasoning_path, 'w') as f:
            json.dump(reasoning_log, f, indent=2)
        
        # 2. Create clean final results plot
        fig = plt.figure(figsize=(16, 10))
        
        # Top section: Component spectra
        ax_spectra = plt.subplot(2, 1, 1)
        for i in range(final_n_components):
            plt.plot(energy_axis, components[i], label=f'Component {i+1}', linewidth=4)
        plt.title(f'Final Spectral Components (n={final_n_components})')
        plt.xlabel(xlabel)
        plt.ylabel('Intensity')
        plt.legend()
        plt.grid(True, alpha=0.3)
        
        # Bottom section: Abundance maps with proper grid
        n_cols = min(4, final_n_components)
        n_rows = (final_n_components + n_cols - 1) // n_cols
        
        # Create abundance map subplots
        for i in range(final_n_components):
            row = i // n_cols
            col = i % n_cols
            ax = plt.subplot(2 * n_rows, n_cols, n_cols + row * n_cols + col + 1)
            im = plt.imshow(abundance_maps[..., i].T, cmap='seismic')
            plt.title(f'Component {i+1}')
            plt.colorbar(im, fraction=0.046, pad=0.04)
            plt.axis('off')
        plt.tight_layout()
        
        # Save final results plot
        results_file = f"final_results_{timestamp}.png"
        results_path = os.path.join(self.output_dir, results_file)
        plt.savefig(results_path, dpi=150, bbox_inches='tight')
        plt.close()
        
        print(f"📈 Saved final results: {results_file}")
        print(f"📝 Saved reasoning log: {reasoning_file}")
        
        return results_path, reasoning_path

    def _create_energy_axis(self, n_channels: int, system_info: dict = None) -> tuple[np.ndarray, str, bool]:
        """
        Create energy axis from system_info if available, otherwise use channel indices.
        
        Returns:
            tuple: (energy_axis, xlabel, has_energy_info)
        """
        if system_info and "energy_range" in system_info:
            energy_info = system_info["energy_range"]
            
            if "start" in energy_info and "end" in energy_info:
                start = energy_info["start"]
                end = energy_info["end"]
                units = energy_info.get("units", "eV")  # Default to eV if not specified
                
                # Simple linear conversion
                energy_axis = np.linspace(start, end, n_channels)
                xlabel = f"Energy ({units})"
                has_energy_info = True
                
                self.logger.info(f"Using energy axis: {start} to {end} {units}")
                return energy_axis, xlabel, has_energy_info
        
        # Fallback: channel indices
        energy_axis = np.arange(n_channels)
        xlabel = "Channel"
        has_energy_info = False
        
        self.logger.info("Using channel indices (no energy range provided)")
        return energy_axis, xlabel, has_energy_info
    
    def _get_measurement_recommendations_prompt(self) -> str:
        return SPECTROSCOPY_MEASUREMENT_RECOMMENDATIONS_INSTRUCTIONS


================================================
File: agents/exp_agents/utils.py
================================================
import cv2
from PIL import Image
import numpy as np
from io import BytesIO
import os
import glob
import matplotlib.pyplot as plt

import atomai as aoi


MAX_IMG_DIM = 1024

def load_image(image_path):
    """Load an image from file."""
    try:
        _, ext = os.path.splitext(image_path)
        ext = ext.lower()

        if ext == '.npy':
            # Load .npy file, assuming it's always 2D grayscale based
            img_array = np.load(image_path)
            if img_array.dtype == np.uint8:
                # If it's already uint8, return directly
                return img_array
            else:
                float_array = img_array.astype(np.float64)
                min_val, max_val = np.min(float_array), np.max(float_array)
                normalized_array = (float_array - min_val) / (max_val - min_val)
                # Scale 0-255 and convert to uint8
                uint8_array = (normalized_array * 255).astype(np.uint8)
                return uint8_array

        else:
            # Standard image loading (can be grayscale or color)
            img = cv2.imread(image_path)
            if img is None:
                raise ValueError(f"Could not load image from {image_path}")
            return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # Convert from BGR to RGB
    
    except Exception as e:
        print(f"Error loading image: {e}")
        raise

def preprocess_image(image: np.ndarray, max_dim: int = MAX_IMG_DIM) -> tuple[np.ndarray, float]:
    """
    Preprocess microscopy image for better analysis and ensure it's within model context limits.
    Returns the preprocessed image and the scaling factor used for resizing.
    """
    scale_factor = 1.0
    # Resize if the image is too large
    h, w = image.shape[:2]
    if max(h, w) > max_dim:
        # Calculate new dimensions while preserving aspect ratio
        if h > w:
            new_h = max_dim
            new_w = int(w * (max_dim / h))
        else:
            new_w = max_dim
            new_h = int(h * (max_dim / w))
        scale_factor = h / new_h  # or w / new_w
        
        # Resize the image
        image = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)
        print(f"Image resized from {w}x{h} to {new_w}x{new_h} to fit model context window")
    
    # Convert to grayscale if it's not already
    if len(image.shape) == 3:
        gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    else:
        gray = image
    
    # Apply contrast enhancement
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
    enhanced = clahe.apply(gray)
    
    # Apply noise reduction
    denoised = cv2.GaussianBlur(enhanced, (3, 3), 0)
    
    # Return the preprocessed image
    return denoised, scale_factor


def convert_numpy_to_jpeg_bytes(image_array: np.ndarray, quality: int = 85) -> bytes:
    """
    Converts a NumPy array image representation into compressed JPEG bytes.
    """
    try:
        pil_img = Image.fromarray(image_array)
        buffered = BytesIO()
        pil_img.save(buffered, format="JPEG", quality=quality)
        return buffered.getvalue()
    except Exception as e:
        print(f"Error converting NumPy array to JPEG bytes: {e}")
        raise # Re-raise the exception to be handled by the caller


def normalize_and_convert_to_image_bytes(array: np.ndarray, mode='L', format='JPEG', quality=85, log_scale=False) -> bytes:
    """
    Normalizes a 2D numpy array and converts it to image bytes (e.g., grayscale JPEG).

    Args:
        array: The 2D numpy array to convert.
        mode: The PIL image mode (e.g., 'L' for grayscale).
        format: The output image format ('JPEG', 'PNG').
        quality: The quality setting for JPEG (1-95).
        log_scale: Apply log1p scaling before normalization (good for FFT magnitudes).

    Returns:
        Image data as bytes.
    """
    if array.ndim != 2:
        # If we get e.g. (1, H, W), try squeezing
        if array.ndim == 3 and array.shape[0] == 1:
            array = np.squeeze(array, axis=0)
        else:
             raise ValueError(f"Input array must be 2D, but got shape {array.shape}")

    try:
        # Make a copy to avoid modifying the original array
        processed_array = array.copy().astype(np.float32) # Ensure float for calculations

        # Optional log scaling
        if log_scale:
            processed_array = np.log1p(processed_array)

        # Handle potential NaN/Inf values introduced by log or present in input
        if not np.all(np.isfinite(processed_array)):
             max_finite = np.max(processed_array[np.isfinite(processed_array)]) if np.any(np.isfinite(processed_array)) else 1.0
             min_finite = np.min(processed_array[np.isfinite(processed_array)]) if np.any(np.isfinite(processed_array)) else 0.0
             processed_array = np.nan_to_num(processed_array, nan=min_finite, posinf=max_finite, neginf=min_finite)

        # Normalize to 0-1 range
        min_val, max_val = np.min(processed_array), np.max(processed_array)
        if max_val > min_val:
            normalized_array = (processed_array - min_val) / (max_val - min_val)
        else:
            # Handle flat array case (all values the same)
            normalized_array = np.zeros_like(processed_array)

        # Scale to 0-255 and convert to uint8
        uint8_array = (normalized_array * 255).astype(np.uint8)

        # Convert to PIL Image
        pil_img = Image.fromarray(uint8_array, mode=mode) # 'L' for grayscale

        # Save to bytes buffer
        buffered = BytesIO()
        if format.upper() == 'JPEG':
             pil_img.save(buffered, format="JPEG", quality=quality)
        elif format.upper() == 'PNG':
             pil_img.save(buffered, format="PNG") # PNG is lossless
        else:
             raise ValueError(f"Unsupported image format: {format}")

        return buffered.getvalue()

    except Exception as e:
        raise # Re-raise to be handled by the calling method


def rescale_for_model(image, current_fov_nm, target_pixel_size_A=0.25): # 0.2-0.3 seems to be the optimal range
    """
    Rescale to achieve target pixel size while keeping field of view constant
    """

    import cv2

    # Calculate target image size to achieve desired pixel size
    target_size_px = int((current_fov_nm * 10) / target_pixel_size_A)
    
    # Calculate scale factor
    scale_factor = target_size_px / image.shape[0]
    
    print(f"Current: {image.shape[0]}px, Target: {target_size_px}px")
    print(f"Scale factor: {scale_factor:.3f} ({'upsize' if scale_factor > 1 else 'downsize'})")
    
    # Choose interpolation
    if scale_factor > 1.5:
        interpolation = cv2.INTER_CUBIC  # Upscaling
    elif scale_factor < 0.7:
        interpolation = cv2.INTER_AREA   # Downscaling  
    else:
        interpolation = cv2.INTER_LINEAR # Moderate scaling
    
    rescaled_image = cv2.resize(image, (target_size_px, target_size_px), 
                               interpolation=interpolation)
    
    # Verify final pixel size
    final_pixel_size = (current_fov_nm * 10) / target_size_px
    
    return rescaled_image, scale_factor, final_pixel_size


def _2d_gaussian(xy, amplitude, y0, x0, sigma_y, sigma_x, offset):
    """Helper 2D Gaussian function for fitting."""
    from scipy.optimize import curve_fit
    y, x = xy
    y0 = float(y0)
    x0 = float(x0)
    g = offset + amplitude * np.exp(
        -(((y - y0)**2 / (2 * sigma_y**2)) + ((x - x0)**2 / (2 * sigma_x**2)))
    )
    return g.ravel()

def refine_coordinates_gaussian_fit(image_data, coordinates, window_size=7, max_refinement_shift=1.5):
    """
    Refines atomic coordinates to sub-pixel precision using 2D Gaussian fitting.

    Args:
        image_data (np.ndarray): The image data to fit on (e.g., original image).
        coordinates (np.ndarray): Nx2 array of coarse (y, x) coordinates from Locator.
        window_size (int): The size of the fitting window around each coordinate.
        max_refinement_shift (float): The maximum distance (in pixels) the center can shift during fitting.

    Returns:
        np.ndarray: Refined coordinates.
    """
    from scipy.optimize import curve_fit
    if coordinates is None or len(coordinates) == 0:
        return coordinates

    refined_coords = []
    h, w = image_data.shape
    half_w = window_size // 2

    for y_int, x_int in coordinates.astype(int):
        y_min, y_max = y_int - half_w, y_int + half_w + 1
        x_min, x_max = x_int - half_w, x_int + half_w + 1

        if y_min < 0 or y_max > h or x_min < 0 or x_max > w:
            refined_coords.append([y_int, x_int])
            continue

        patch = image_data[y_min:y_max, x_min:x_max]
        y_grid, x_grid = np.mgrid[y_min:y_max, x_min:x_max]

        try:
            initial_guess = (patch.max(), y_int, x_int, 1, 1, patch.min())
            
            # Define bounds to constrain the fit and prevent it from jumping to another atom.
            # params: amplitude, y0, x0, sigma_y, sigma_x, offset
            lower_bounds = [0, y_int - max_refinement_shift, x_int - max_refinement_shift, 0.5, 0.5, 0]
            upper_bounds = [patch.max() * 1.5, y_int + max_refinement_shift, x_int + max_refinement_shift, half_w, half_w, patch.max()]
            bounds = (lower_bounds, upper_bounds)

            popt, _ = curve_fit(_2d_gaussian, (y_grid, x_grid), patch.ravel(), p0=initial_guess, bounds=bounds)
            y_refined, x_refined = popt[1], popt[2]
            # The bounds in curve_fit should already handle this, but an extra check for patch boundaries is good practice.
            if (y_min <= y_refined < y_max) and (x_min <= x_refined < x_max): # Check if it's within the patch
                 refined_coords.append([y_refined, x_refined])
            else:
                 refined_coords.append([y_int, x_int]) # Revert to original if fit is outside patch
        except (RuntimeError, ValueError):
            refined_coords.append([y_int, x_int])

    return np.array(refined_coords)

def predict_with_ensemble(dir_path, image, thresh=0.8, refine=True, max_refinement_shift=1.5):
    import logging
    logger = logging.getLogger(__name__)

    all_predictions = []
    model_pattern = os.path.join(dir_path, 'atomnet3*.tar')
    logger.info(f"Searching for DCNN model files with pattern: {model_pattern}")
    model_files = glob.glob(model_pattern)

    if not model_files:
        logger.error(f"No model files found in '{dir_path}' matching the pattern 'atomnet3*.tar'.")
        raise FileNotFoundError(f"Could not find any DCNN model files ('atomnet3*.tar') in the specified directory: {dir_path}")

    logger.info(f"Found {len(model_files)} models for ensemble prediction.\n")
    for model_file in model_files:
        logger.debug(f"Loading model: {model_file}")
        model = aoi.load_model(model_file)
        prediction = model.predict(image)[0]
        all_predictions.append(prediction)
    prediction_mean = np.mean(np.stack(all_predictions), axis=0)
    locator_output = aoi.predictors.Locator(thresh=thresh).run(prediction_mean)

    # The locator can return a dict {class: coords} or an array. We handle both.
    if isinstance(locator_output, dict):
        # For single-channel prediction, we expect the key to be 0.
        coarse_coords_with_class = locator_output.get(0)
    else:
        coarse_coords_with_class = locator_output # It's an array or None

    if coarse_coords_with_class is None or len(coarse_coords_with_class) == 0:
        return prediction_mean.squeeze(), None

    if refine:
        coarse_coords_2d = coarse_coords_with_class[:, :2]
        refined_coords_2d = refine_coordinates_gaussian_fit(image, coarse_coords_2d, max_refinement_shift=max_refinement_shift)
        final_coords = np.concatenate((refined_coords_2d, coarse_coords_with_class[:, 2][:, np.newaxis]), axis=1)
    else:
        final_coords = coarse_coords_with_class

    return prediction_mean.squeeze(), final_coords


def analyze_nearest_neighbor_distances(coordinates, pixel_scale=1.0):
    """
    Calculates the nearest-neighbor distance for each coordinate.

    Args:
        coordinates (np.ndarray): Nx2 array of (y, x) coordinates of atoms.
        pixel_scale (float): Conversion factor from pixels to real units (e.g., nm/pixel).

    Returns:
        np.ndarray: A 1D array of nearest-neighbor distances for each coordinate,
                    or None if there are not enough coordinates.
    """
    from scipy.spatial import KDTree
    import numpy as np

    if coordinates is None or len(coordinates) < 2:
        print("Warning: Not enough coordinates to compute nearest-neighbor distances.")
        return None

    # Build a KD-tree for efficient nearest-neighbor search
    tree = KDTree(coordinates)

    # Query the KD-tree for the nearest neighbor of each atom (excluding itself)
    distances, _ = tree.query(coordinates, k=2)
    # The nearest-neighbor distance is the second element (first is distance to self, which is 0)
    nearest_neighbor_distances = distances[:, 1] * pixel_scale

    return nearest_neighbor_distances


def download_file_with_gdown(file_id, output_path):
    """
    Downloads a file from Google Drive using gdown.

    Args:
        file_id (str): The ID of the Google Drive file.
        output_path (str): The local path where the file will be saved.
    """

    import gdown

    try:
        # Create directory if it doesn't exist
        parent_dir = os.path.dirname(output_path)
        # If parent_dir is an empty string, it means the file is in the current directory.
        # We only need to create the directory if a path is specified.
        if parent_dir:
            os.makedirs(parent_dir, exist_ok=True)

        # gdown.download handles the direct download link construction and large file quirks
        gdown.download(id=file_id, output=output_path, quiet=False, fuzzy=True) # fuzzy=True for slightly more relaxed ID matching
        
        print(f"File downloaded to: {output_path}")
        return output_path
    except Exception as e:
        print(f"An error occurred during download: {e}")
        return None

def unzip_file(zip_filepath, extract_to_dir):
    """
    Unzips a file to a specified directory.

    Args:
        zip_filepath (str): The path to the zip file.
        extract_to_dir (str): The directory where contents will be extracted.
    """

    import zipfile

    if not os.path.exists(zip_filepath):
        print(f"Error: Zip file not found at {zip_filepath}")
        return False

    print(f"Unzipping '{zip_filepath}' to '{extract_to_dir}'...")
    try:
        os.makedirs(extract_to_dir, exist_ok=True)

        with zipfile.ZipFile(zip_filepath, 'r') as zip_ref:
            zip_ref.extractall(extract_to_dir)
        print(f"Successfully unzipped to: {extract_to_dir}")
        return True
    except zipfile.BadZipFile:
        print(f"Error: '{zip_filepath}' is not a valid zip file or is corrupted.")
        return False
    except Exception as e:
        print(f"An error occurred during unzipping: {e}")
        return False


def create_abundance_overlay(structure_image: np.ndarray, 
                           abundance_map: np.ndarray,
                           threshold_percentile: float = 80.0,
                           alpha: float = 0.6,
                           colormap: str = 'hot') -> bytes:
    """
    Create a simple overlay of abundance map on structure image for LLM analysis.
    
    Args:
        structure_image: 2D grayscale structure image
        abundance_map: 2D abundance map from NMF
        threshold_percentile: Show pixels above this percentile (0-100)
        alpha: Transparency of overlay (0-1)
        colormap: Matplotlib colormap name
    
    Returns:
        Image bytes for LLM processing
    """
    # Ensure both images are 2D
    if structure_image.ndim != 2 or abundance_map.ndim != 2:
        raise ValueError("Both images must be 2D")
    
    # Resize abundance map to match structure if needed
    if structure_image.shape != abundance_map.shape:
        abundance_map = cv2.resize(abundance_map, 
                                 (structure_image.shape[1], structure_image.shape[0]))
    
    # Normalize structure image to 0-1
    struct_norm = (structure_image - structure_image.min()) / (structure_image.max() - structure_image.min())
    
    # Create threshold mask (use original abundance values)
    threshold = np.percentile(abundance_map, threshold_percentile)
    mask = abundance_map >= threshold
    
    # Normalize abundance for color mapping
    if abundance_map.max() > abundance_map.min():
        abund_norm = (abundance_map - abundance_map.min()) / (abundance_map.max() - abundance_map.min())
    else:
        abund_norm = abundance_map
    
    # Create overlay image
    fig, ax = plt.subplots(1, 1, figsize=(8, 6))
    
    # Show structure as background
    ax.imshow(struct_norm, cmap='gray', aspect='equal')
    
    # Add colored abundance overlay where above threshold
    if np.any(mask):
        overlay_data = np.where(mask, abund_norm, np.nan)  # Use NaN for transparency
        ax.imshow(overlay_data, cmap=colormap, alpha=alpha, aspect='equal')
    
    ax.set_title(f'Structure + Abundance Overlay (>{threshold_percentile}th percentile)')
    ax.axis('off')
    
    # Convert to bytes
    buf = BytesIO()
    plt.savefig(buf, format='jpeg', dpi=150, bbox_inches='tight')
    plt.close()
    buf.seek(0)
    return buf.getvalue()


def create_multi_abundance_overlays(structure_image: np.ndarray,
                                  abundance_maps: np.ndarray,
                                  threshold_percentile: float = 80.0,
                                  alpha: float = 0.6,
                                  use_simple_colors: bool = True) -> bytes:
    """
    Create overlays for all NMF components in a single image for LLM analysis.
    
    Args:
        structure_image: 2D grayscale structure image
        abundance_maps: 3D array (height, width, n_components)
        threshold_percentile: Show pixels above this percentile
        alpha: Transparency of overlays
        use_simple_colors: If True, use solid colors; if False, use intensity gradients
    
    Returns:
        Image bytes showing structural image + all component overlays
    """
    n_components = abundance_maps.shape[2]
    
    if use_simple_colors:
        # Simple solid colors - easier to distinguish, unlimited components
        colors = ['red', 'blue', 'green', 'purple', 'orange', 'cyan', 'magenta', 'yellow']
        # Generate more colors if needed
        while len(colors) < n_components:
            colors.extend(['darkred', 'darkblue', 'darkgreen', 'indigo', 'brown', 'pink'])
    else:
        # Traditional colormaps with intensity gradients
        colormaps = ['Reds', 'Blues', 'Greens', 'Purples', 'Oranges', 'plasma', 'viridis', 'inferno']
    
    # Calculate grid layout: +1 for original structure image
    total_plots = n_components + 1
    cols = min(4, total_plots)  # Max 4 columns for readability
    rows = (total_plots + cols - 1) // cols
    
    fig, axes = plt.subplots(rows, cols, figsize=(cols * 3.5, rows * 3.5))
    if rows == 1 and cols == 1:
        axes = [axes]
    elif rows == 1 or cols == 1:
        axes = axes.flatten()
    else:
        axes = axes.flatten()
    
    # Normalize structure image
    struct_norm = (structure_image - structure_image.min()) / (structure_image.max() - structure_image.min())
    
    # Plot 1: Original structural image
    axes[0].imshow(struct_norm, cmap='gray', aspect='equal')
    axes[0].set_title('Original Structure\n(Reference)', fontweight='bold', fontsize=14)
    axes[0].axis('off')
    
    # Plot 2+: Component overlays
    for i in range(n_components):
        ax_idx = i + 1  # Offset by 1 for the structure image
        abundance_map = abundance_maps[..., i]
        
        # Resize if needed
        if structure_image.shape != abundance_map.shape:
            abundance_map = cv2.resize(abundance_map, 
                                     (structure_image.shape[1], structure_image.shape[0]))
        
        # Threshold
        threshold = np.percentile(abundance_map, threshold_percentile)
        mask = abundance_map >= threshold
        
        # Create overlay
        axes[ax_idx].imshow(struct_norm, cmap='gray', aspect='equal')
        
        if np.any(mask):
            if use_simple_colors:
                # Simple solid color overlay - just show the mask
                color_array = np.zeros((*mask.shape, 4))  # RGBA
                if i < len(colors):
                    from matplotlib.colors import to_rgba
                    rgba = to_rgba(colors[i])
                    color_array[mask] = rgba
                    color_array[mask, 3] = alpha  # Set alpha
                    axes[ax_idx].imshow(color_array, aspect='equal')
            else:
                # Traditional intensity-based overlay
                if abundance_map.max() > abundance_map.min():
                    abund_norm = (abundance_map - abundance_map.min()) / (abundance_map.max() - abundance_map.min())
                else:
                    abund_norm = abundance_map
                
                overlay_data = np.where(mask, abund_norm, np.nan)
                axes[ax_idx].imshow(overlay_data, cmap=colormaps[i % len(colormaps)], 
                                  alpha=alpha, aspect='equal')
        
        # Calculate coverage
        coverage = np.sum(mask) / mask.size * 100
        color_name = colors[i] if use_simple_colors and i < len(colors) else f"comp{i+1}"
        axes[ax_idx].set_title(f'Component {i+1}\n({color_name}, {coverage:.1f}% coverage)', fontsize=14)
        axes[ax_idx].axis('off')
    
    # Hide unused subplots
    for i in range(total_plots, len(axes)):
        axes[i].axis('off')
    
    plt.tight_layout()
    
    # Convert to bytes
    buf = BytesIO()
    plt.savefig(buf, format='jpeg', dpi=150, bbox_inches='tight')
    plt.close()
    buf.seek(0)
    return buf.getvalue()


def extract_atomic_intensities(image_array: np.ndarray, coordinates: np.ndarray, 
                               box_size: int = 2) -> np.ndarray:
    """
    Extract intensity values from small boxes around detected atomic positions.
    
    Args:
        image_array: 2D microscopy image
        coordinates: Nx2 array of (y, x) atomic coordinates
        box_size: Size of square box around each atom (e.g., 2 = 2x2 pixels)
        
    Returns:
        1D array of intensity values (one per atom)
    """
    if coordinates is None or len(coordinates) == 0:
        return np.array([])
    
    intensities = []
    h, w = image_array.shape
    half_box = box_size // 2
    
    for y, x in coordinates[:, :2].astype(int):  # Use only y, x coordinates
        # Define box boundaries
        y_min = max(0, y - half_box)
        y_max = min(h, y + half_box + 1)
        x_min = max(0, x - half_box)
        x_max = min(w, x + half_box + 1)
        
        # Extract intensity (mean of the box)
        box_intensity = np.mean(image_array[y_min:y_max, x_min:x_max])
        intensities.append(box_intensity)
    
    return np.array(intensities)


def create_intensity_histogram_plot(intensities: np.ndarray, n_bins: int = 50) -> bytes:
    """Create histogram plot of atomic intensities."""
    fig, ax = plt.subplots(figsize=(12, 4))
    
    ax.hist(intensities, bins=n_bins, alpha=0.7, color='skyblue', edgecolor='black')
    ax.set_xlabel('Intensity')
    ax.set_ylabel('Number of Atoms')
    ax.set_title(f'Atomic Intensity Distribution ({len(intensities)} atoms)')
    ax.grid(True, alpha=0.3)
    
    # Add statistics
    ax.axvline(np.mean(intensities), color='red', linestyle='--', 
                label=f'Mean: {np.mean(intensities):.2f}')
    ax.axvline(np.median(intensities), color='orange', linestyle='--', 
                label=f'Median: {np.median(intensities):.2f}')
    ax.legend()
    
    plt.tight_layout()
    
    buf = BytesIO()
    plt.savefig(buf, format='jpeg', dpi=150, bbox_inches='tight')
    buf.seek(0)
    image_bytes = buf.getvalue()
    plt.close()
    
    return image_bytes




================================================
File: agents/lit_agents/__init__.py
================================================
from .literature_agent import OwlLiteratureAgent, IncarLiteratureAgent
from .novelty_scorer import NoveltyScorer, enhanced_novelty_assessment, display_enhanced_novelty_summary


================================================
File: agents/lit_agents/instruct.py
================================================
NOVELTY_SCORING_INSTRUCTIONS = """You are an intellectual property analyst reviewing a literature search. Your goal is to determine if a new, hypothetical research claim has been published before.

**Your Task:**
Your AI assistant (OWL) has performed a literature search to answer the question, "Has anyone done X before?" You must assume "X" is a new claim made today. Your job is to determine if the OWL report found any prior work that invalidates this new claim. You must assign a novelty score from 1-5 and provide a brief explanation for your choice.

**Scoring Criteria:**

* **5 - Groundbreaking / Revolutionary:** The report concludes that no prior published work exists. The question points to the discovery of a **broad class of phenomenon** for the first time, or a phenomenon that would **challenge a widely accepted scientific model.**
* **4 - High Novelty / New Insight:** The report concludes that no prior published work exists. The question points to the discovery of a **specific new phenomenon in a particular system or under specific conditions**, providing a key new insight into an existing area of research.
* **3 - Uncertain / Partially Novel:** The report describes published work that is very similar but not an exact match to the claim, blurring the lines of novelty.
* **2 - Not Novel:** The report describes **at least one published study** that has clearly achieved the core scientific outcome of the claim. The new claim has been "scooped."
* **1 - Well-Established:** The report indicates that the finding has been achieved and is documented across **multiple studies**, making it common knowledge.

**Report for Analysis:**

Question: {question}
Response: {response}

**Respond in the following JSON format:**
{{
    "novelty_score": <integer from 1 to 5>,
    "explanation": "<brief explanation of the score>"
}}
"""


================================================
File: agents/lit_agents/literature_agent.py
================================================
import os
import logging
import json
from time import sleep

try:
    from futurehouse_client import FutureHouseClient, JobNames
except ImportError:
    logging.error("Error: futurehouse_client is not installed. Please install it with pip.")
    raise

class OwlLiteratureAgent:
    """
    Agent for querying scientific literature using the OWL system
    through the FutureHouse API client.
    """

    def __init__(self, api_key: str | None = None, max_wait_time: int = 300):
        """
        Initialize the OWL literature agent.
        
        Args:
            api_key: FutureHouse API key
            max_wait_time: Maximum time to wait for response in seconds
        """
        if api_key is None:
            api_key = os.environ.get("FUTUREHOUSE_API_KEY")
        if not api_key:
            raise ValueError("API key not provided and FUTUREHOUSE_API_KEY environment variable is not set.")
        
        self.client = FutureHouseClient(api_key=api_key)
        self.max_wait_time = max_wait_time
        logging.info("OWLLiteratureAgent initialized with max wait time of %d seconds.", max_wait_time)

    def query_literature(self, has_anyone_question: str) -> dict:
        """
        Query the scientific literature using the OWL system.
        
        Args:
            has_anyone_question: The question in "Has anyone..." format
            
        Returns:
            Dictionary containing the search results and metadata
        """
        if not has_anyone_question or not isinstance(has_anyone_question, str):
            error_msg = "Invalid question format. Must provide a non-empty string."
            logging.error(error_msg)
            return {"status": "error", "message": error_msg}
            
        try:
            logging.info(f"Submitting literature query: {has_anyone_question}")
            
            # Create the task in OWL
            task_data = {
                "name": JobNames.OWL,
                "query": has_anyone_question
            }
            
            task_id = self.client.create_task(task_data)
            logging.info(f"OWL task created with ID: {task_id}")
            
            # Get the initial response
            task_status = self.client.get_task(task_id)
            
            # Check if the response is already complete
            if task_status.status == "success":
                logging.info("OWL query completed immediately.")
                return {
                    "status": "success",
                    "task_id": task_id,
                    "formatted_answer": task_status.formatted_answer,
                    "has_successful_answer": getattr(task_status, 'has_successful_answer', True),
                    "search_results": getattr(task_status, 'search_results', []),
                    "query": has_anyone_question
                }
            
            # If not complete, wait for the response with a single timeout
            logging.info(f"OWL query in progress. Waiting up to {self.max_wait_time} seconds for completion.")
            
            # Calculate end time based on max_wait_time
            import time
            start_time = time.time()
            end_time = start_time + self.max_wait_time
            
            while time.time() < end_time:
                # Wait a bit before checking again
                sleep_time = min(10, max(1, (end_time - time.time()) / 10))
                sleep(sleep_time)
                
                # Check status again
                task_status = self.client.get_task(task_id)
                
                # If complete, return the results
                if task_status.status == "success":
                    elapsed = time.time() - start_time
                    logging.info(f"OWL query completed after {elapsed:.1f} seconds.")
                    return {
                        "status": "success",
                        "task_id": task_id,
                        "formatted_answer": task_status.formatted_answer,
                        "json": task_status.model_dump_json(),
                        "has_successful_answer": getattr(task_status, 'has_successful_answer', True),
                        "search_results": getattr(task_status, 'search_results', []),
                        "query": has_anyone_question
                    }
                
                if task_status.status in ["FAILED", "ERROR", "error"]:
                    error_msg = f"OWL query failed with status: {task_status.status}"
                    logging.error(error_msg)
                    return {"status": "error", "message": error_msg, "task_id": task_id}
                
                #logging.info(f"OWL query still in progress. Status: {task_status.status}")
            
            # If we get here, we've exceeded the maximum wait time
            error_msg = f"OWL query timed out after {self.max_wait_time} seconds."
            logging.error(error_msg)
            return {"status": "timeout", "message": error_msg, "task_id": task_id}
            
        except Exception as e:
            error_msg = f"An unexpected error occurred during OWL query: {str(e)}"
            logging.exception(error_msg)
            return {"status": "error", "message": error_msg}
        


class IncarLiteratureAgent:
    """Agent for validating VASP INCAR parameters against literature using CROW."""

    def __init__(self, api_key: str = None, max_wait_time: int = 300):
        if not api_key:
            api_key = os.environ.get("FUTUREHOUSE_API_KEY")
        if not api_key:
            raise ValueError("API key required")
        
        self.client = FutureHouseClient(api_key=api_key)
        self.max_wait_time = max_wait_time
        self.logger = logging.getLogger(__name__)

    def validate_incar(self, incar_content: str, system_description: str) -> dict:
        """Validate INCAR parameters against literature."""
        
        # Clean system description - remove additional instructions
        clean_description = self._clean_system_description(system_description)
        
        query = f"""Are these VASP INCAR parameters appropriate for {clean_description}?

{incar_content}"""

        try:
            # Submit to CROW
            task_data = {"name": JobNames.CROW, "query": query}
            task_id = self.client.create_task(task_data)
            
            # Wait for completion
            import time
            start_time = time.time()
            
            while time.time() - start_time < self.max_wait_time:
                task_status = self.client.get_task(task_id)
                
                if task_status.status == "success":
                    # Clean response to remove repeated question
                    clean_response = self._clean_response(task_status.formatted_answer, query)
                    return {
                        "status": "success", 
                        "response": clean_response,
                        "task_id": task_id
                    }
                elif task_status.status in ["FAILED", "ERROR", "error"]:
                    return {"status": "error", "message": f"CROW failed: {task_status.status}"}
                
                sleep(10)
            
            return {"status": "timeout", "message": f"Timed out after {self.max_wait_time}s"}
            
        except Exception as e:
            return {"status": "error", "message": str(e)}

    def _clean_system_description(self, description: str) -> str:
        """Remove additional instructions from system description."""
        # Remove common additional instruction patterns
        patterns_to_remove = [
            r"\.?\s*Additional Instructions?:.*",
            r"\.?\s*Save.*format\.?",
            r"\.?\s*Output.*format\.?",
        ]
        
        import re
        cleaned = description
        for pattern in patterns_to_remove:
            cleaned = re.sub(pattern, "", cleaned, flags=re.IGNORECASE)
        
        return cleaned.strip()

    def _clean_response(self, response: str, original_query: str) -> str:
        """Remove repeated question from CROW response."""
        if not response:
            return response
            
        # If response starts with "Question:" remove everything up to the actual answer
        if response.startswith("Question:"):
            lines = response.split('\n')
            # Find where the actual answer starts (after the question block)
            answer_start = 0
            for i, line in enumerate(lines):
                if line.strip() and not line.startswith("Question:") and not line.startswith("INCAR content:"):
                    answer_start = i
                    break
            response = '\n'.join(lines[answer_start:])
        
        return response.strip()


================================================
File: agents/lit_agents/novelty_scorer.py
================================================
"""
Enhanced novelty scoring system for scientific claims assessment.

"""

import json
import logging
import os
from typing import Dict, Any, List, Tuple

import google.generativeai as genai
from google.generativeai.types import GenerationConfig

from ...auth import get_api_key, APIKeyNotFoundError
from .instruct import NOVELTY_SCORING_INSTRUCTIONS
class NoveltyScorer:
    """Enhanced novelty assessment using structured scoring instead of binary Yes/No."""
    
    def __init__(self, google_api_key: str = None, model_name: str = "gemini-2.5-flash-preview-05-20"):
        """
        Initialize the novelty scorer.
        
        Args:
            google_api_key: Google API key for Gemini access
            model_name: Gemini model to use for scoring (Flash recommended for speed)
        """
        if google_api_key is None:
            google_api_key = get_api_key('google')
            if not google_api_key:
                raise APIKeyNotFoundError('google')
        
        genai.configure(api_key=google_api_key)
        self.model = genai.GenerativeModel(model_name)
        self.generation_config = GenerationConfig(response_mime_type="application/json")
        self.logger = logging.getLogger(__name__)
        
        self.logger.info(f"NoveltyScorer initialized with model: {model_name}")
    
    def score_novelty(self, question: str, owl_response: str) -> Dict[str, Any]:
        """
        Score the novelty of a scientific claim based on literature analysis.
        
        Args:
            question: The original "Has anyone..." research question
            owl_response: The literature analysis response from OWL
            
        Returns:
            Dictionary with novelty score, explanation, and confidence
        """
        try:
            prompt = NOVELTY_SCORING_INSTRUCTIONS.format(
                question=question,
                response=owl_response
            )
            
            self.logger.debug(f"Scoring novelty for question: {question[:100]}...")
            
            response = self.model.generate_content(
                prompt,
                generation_config=self.generation_config
            )
            
            result = json.loads(response.text)
            
            # Validate the response
            if not self._validate_scoring_response(result):
                self.logger.warning("Invalid scoring response, using fallback")
                return self._create_fallback_score(question, owl_response)
            
            self.logger.info(f"Novelty scored: {result['novelty_score']}/5")
            return result
            
        except Exception as e:
            self.logger.error(f"Failed to score novelty: {e}")
            return self._create_fallback_score(question, owl_response)
    
    def _validate_scoring_response(self, result: Dict[str, Any]) -> bool:
        """Validate the scoring response format and content."""
        required_keys = ["novelty_score", "explanation"]
        
        if not all(key in result for key in required_keys):
            self.logger.warning(f"Missing required keys in response: {result}")
            return False
        
        score = result.get("novelty_score")
        if not isinstance(score, int) or not (1 <= score <= 5):
            self.logger.warning(f"Invalid novelty score: {score}")
            return False
        
        explanation = result.get("explanation", "")
        if not isinstance(explanation, str) or len(explanation.strip()) == 0:
            self.logger.warning("Empty or invalid explanation")
            return False
        
        return True
    
    def _create_fallback_score(self, question: str, owl_response: str) -> Dict[str, Any]:
        """Create a fallback score when AI scoring fails."""
        # Simple heuristic based on the original Yes/No logic
        response_lower = owl_response.lower()
        
        if 'no' in response_lower[:10]:  # Likely novel
            score = 4
            explanation = "Literature suggests this may be a novel finding (fallback assessment)"
        elif 'yes' in response_lower[:10]:  # Likely known
            score = 2
            explanation = "Literature suggests this is a known finding (fallback assessment)"
        else:
            score = 3
            explanation = "Uncertain novelty based on literature analysis (fallback assessment)"
        
        self.logger.info(f"Using fallback score: {score}/5")
        
        return {
            "novelty_score": score,
            "explanation": explanation
        }
    
    @staticmethod
    def get_novelty_description(score: int) -> str:
        """Get human-readable description of novelty score."""
        descriptions = {
            1: "Not novel at all",
            2: "Minor novelty/Incremental improvement", 
            3: "Moderate novelty/Significant confirmation or refinement",
            4: "High novelty/New insight or significant breakthrough",
            5: "Groundbreaking/Revolutionary"
        }
        return descriptions.get(score, "Unknown novelty level")
    
    @staticmethod
    def categorize_claims_by_novelty(scored_claims: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]:
        """Categorize claims by their novelty scores."""
        categories = {
            "highly_novel": [],      # Scores 4-5
            "moderately_novel": [],  # Score 3
            "minimally_novel": [],   # Score 2
            "not_novel": []         # Score 1
        }
        
        for claim_result in scored_claims:
            score = claim_result.get("novelty_assessment", {}).get("novelty_score", 0)
            
            if score >= 4:
                categories["highly_novel"].append(claim_result)
            elif score == 3:
                categories["moderately_novel"].append(claim_result)
            elif score == 2:
                categories["minimally_novel"].append(claim_result)
            else:
                categories["not_novel"].append(claim_result)
        
        return categories


def enhanced_novelty_assessment(literature_results: List[Dict[str, Any]], 
                               novelty_scorer: NoveltyScorer = None) -> Dict[str, Any]:
    """
    Enhanced novelty assessment with structured scoring.
    
    Args:
        literature_results: List of literature search results from OWL
        novelty_scorer: Optional NoveltyScorer instance
        
    Returns:
        Enhanced novelty assessment with scores and categorization
    """
    if novelty_scorer is None:
        novelty_scorer = NoveltyScorer()
    
    scored_results = []
    logger = logging.getLogger(__name__)
    
    logger.info(f"Running enhanced novelty assessment on {len(literature_results)} literature results")
    
    for i, result in enumerate(literature_results, 1):
        if result['owl_result']['status'] != "success":
            logger.warning(f"Skipping result {i} due to failed OWL search")
            continue
        
        original_claim = result['original_claim']
        question = original_claim.get('has_anyone_question', '')
        owl_response = result['owl_result'].get('formatted_answer', '')
        
        if not question or not owl_response:
            logger.warning(f"Skipping result {i} due to missing question or response")
            continue
        
        logger.info(f"Scoring claim {i}/{len(literature_results)}")
        
        # Score the novelty
        novelty_assessment = novelty_scorer.score_novelty(question, owl_response)
        print()
        print(f"🔍 Claim: {original_claim['claim']}")
        print(f"❓ Question: {question}")
        print(f"✅ Novelty Score: {novelty_assessment['novelty_score']}/5")
        print(f"📝 Explanation: {novelty_assessment['explanation']}")
        print()
            
        
        # Add to the result
        enhanced_result = result.copy()
        enhanced_result['novelty_assessment'] = novelty_assessment
        scored_results.append(enhanced_result)
    
    if not scored_results:
        logger.warning("No claims could be scored for novelty")
        return {
            "total_claims_searched": len(literature_results),
            "successful_searches": 0,
            "average_novelty_score": 0.0,
            "novelty_categories": {
                "highly_novel": [],
                "moderately_novel": [],
                "minimally_novel": [],
                "not_novel": []
            },
            "detailed_scores": [],
            "potentially_novel": [],
            "known_findings": []
        }
    
    # Categorize claims by novelty
    categories = NoveltyScorer.categorize_claims_by_novelty(scored_results)
    
    # Create summary statistics
    total_scored = len(scored_results)
    avg_score = sum(r['novelty_assessment']['novelty_score'] for r in scored_results) / total_scored
    
    # Create flat lists for categories
    novelty_categories = {
        "highly_novel": [r['original_claim']['claim'] for r in categories["highly_novel"]],
        "moderately_novel": [r['original_claim']['claim'] for r in categories["moderately_novel"]], 
        "minimally_novel": [r['original_claim']['claim'] for r in categories["minimally_novel"]],
        "not_novel": [r['original_claim']['claim'] for r in categories["not_novel"]]
    }
    
    # For backward compatibility: combine moderate and high novelty as "potentially novel"
    potentially_novel = novelty_categories["highly_novel"] + novelty_categories["moderately_novel"]
    known_findings = novelty_categories["minimally_novel"] + novelty_categories["not_novel"]
    
    assessment = {
        "total_claims_searched": len(literature_results),
        "successful_searches": total_scored,
        "average_novelty_score": round(avg_score, 1),  # Round to 1 decimal for cleaner display
        "novelty_categories": novelty_categories,
        "detailed_scores": scored_results,
        # For backward compatibility with existing workflows
        "potentially_novel": potentially_novel,
        "known_findings": known_findings
    }
    
    logger.info(f"Enhanced novelty assessment complete: avg score {avg_score:.1f}/5")
    
    return assessment


def display_enhanced_novelty_summary(assessment: Dict[str, Any]):
    """Display enhanced novelty assessment results with simple formatting."""
    print("\n--- Literature Search Summary ---")
    print(f"Total claims analyzed: {assessment['total_claims_searched']}")
    print(f"Successfully searched: {assessment['successful_searches']}")
    print(f"Average novelty score: {assessment['average_novelty_score']:.1f}/5.0")
    
    categories = assessment['novelty_categories']
    
    # Combine high and moderate novelty as "potentially novel" (scores 3-5)
    potentially_novel = categories['highly_novel'] + categories['moderately_novel']
    known_findings = categories['minimally_novel'] + categories['not_novel']
    
    if potentially_novel:
        print("\nPotentially Novel Findings:")
        detailed_scores = assessment.get('detailed_scores', [])
        
        # Create lookup for scores
        score_lookup = {}
        for result in detailed_scores:
            claim = result['original_claim']['claim']
            score = result['novelty_assessment']['novelty_score']
            score_lookup[claim] = score
        
        for i, claim in enumerate(potentially_novel, 1):
            score = score_lookup.get(claim, 0)
            print(f"  {i}. {claim} (Score: {score}/5)")
    
    if known_findings:
        print("\nPreviously Reported Findings:")
        detailed_scores = assessment.get('detailed_scores', [])
        
        # Create lookup for scores
        score_lookup = {}
        for result in detailed_scores:
            claim = result['original_claim']['claim']
            score = result['novelty_assessment']['novelty_score']
            score_lookup[claim] = score
        
        for i, claim in enumerate(known_findings, 1):
            score = score_lookup.get(claim, 0)
            print(f"  {i}. {claim} (Score: {score}/5)")
    
    print("-" * 50)


def save_enhanced_novelty_results(assessment: Dict[str, Any], output_dir: str, 
                                filename: str = "enhanced_novelty_assessment.json") -> str:
    """Save enhanced novelty assessment results to file."""
    
    logger = logging.getLogger(__name__)
    
    try:
        os.makedirs(output_dir, exist_ok=True)
        output_path = os.path.join(output_dir, filename)
        
        # Add metadata to the assessment
        enhanced_assessment = assessment.copy()
        enhanced_assessment['metadata'] = {
            'version': '2.0',
            'scoring_method': 'enhanced_llm_scoring',
            'novelty_scale': {
                1: NoveltyScorer.get_novelty_description(1),
                2: NoveltyScorer.get_novelty_description(2),
                3: NoveltyScorer.get_novelty_description(3),
                4: NoveltyScorer.get_novelty_description(4),
                5: NoveltyScorer.get_novelty_description(5)
            }
        }
        
        with open(output_path, 'w') as f:
            json.dump(enhanced_assessment, f, indent=2, default=str)
        
        logger.info(f"Enhanced novelty assessment saved to: {output_path}")
        return output_path
        
    except Exception as e:
        logger.error(f"Failed to save enhanced novelty assessment: {e}")
        raise


def get_novelty_priorities_for_dft(assessment: Dict[str, Any]) -> List[str]:
    """
    Extract prioritized claims for DFT structure recommendations.
    
    Returns claims ordered by novelty score (highest first).
    """
    detailed_scores = assessment.get('detailed_scores', [])
    
    # Sort by novelty score (descending)
    sorted_claims = sorted(
        detailed_scores, 
        key=lambda x: x.get('novelty_assessment', {}).get('novelty_score', 0),
        reverse=True
    )
    
    # Extract just the claim text in priority order
    prioritized_claims = [
        result['original_claim']['claim'] 
        for result in sorted_claims
    ]
    
    return prioritized_claims


# Backward compatibility functions
def get_novel_claims_legacy(assessment: Dict[str, Any]) -> List[str]:
    """Get potentially novel claims in legacy format (scores >= 3)."""
    return assessment.get('potentially_novel', [])


def get_known_claims_legacy(assessment: Dict[str, Any]) -> List[str]:
    """Get known claims in legacy format (scores <= 2)."""
    return assessment.get('known_findings', [])



================================================
File: agents/sim_agents/__init__.py
================================================
from .structure_agent import StructureGenerator
from .val_agent import StructureValidatorAgent, IncarValidatorAgent
from .vasp_agent import VaspInputAgent


================================================
File: agents/sim_agents/executors.py
================================================
# ==============================================================================
# Option 1: Direct Integration into StructureExecutor (Recommended)
# ==============================================================================

# File: scilink/agents/sim_agents/executors.py

import os
import sys
import subprocess
import re
import uuid
import tempfile
import logging

from ...auth import get_api_key

DEFAULT_TIMEOUT = 120

# Add your security functions directly to this file
def is_in_colab():
    """Check for Google Colab environment."""
    if 'COLAB_GPU' in os.environ or 'GCE_METADATA_TIMEOUT' in os.environ:
        return True
    if 'google.colab' in sys.modules:
        return True
    return False

def check_security_sandbox_indicators(verbose=False):
    """Check for OS-level sandboxing indicators."""
    score = 0
    positive_indicators = []

    # Tier 1: High-Confidence Environments (Score: 10)
    if is_in_colab():
        score += 10
        positive_indicators.append("google_colab")
        if verbose: 
            logging.info("High-Confidence Indicator: Google Colab environment detected.")
        return score, positive_indicators

    # Tier 2: Strong Indicators (Score: 5)
    # Docker/Container check
    if os.path.exists('/.dockerenv') or ('docker' in (open('/proc/1/cgroup').read() if os.path.exists('/proc/1/cgroup') else '')):
        score += 5
        positive_indicators.append("docker_container")
        if verbose: 
            logging.info("Strong Indicator: Docker or container environment detected.")

    # Virtual Machine check
    try:
        if sys.platform.startswith("linux"):
            result = subprocess.run(['systemd-detect-virt'], capture_output=True, text=True, check=False)
            if result.returncode == 0 and result.stdout.strip() != 'none':
                score += 5
                positive_indicators.append(f"virtual_machine:{result.stdout.strip()}")
                if verbose: 
                    logging.info(f"Strong Indicator: Virtual Machine detected ('{result.stdout.strip()}').")
    except (FileNotFoundError, subprocess.SubprocessError):
        pass

    # Tier 3: Corroborating Evidence (Score: 2)
    try:
        mac = ':'.join(re.findall('..', f'{uuid.getnode():012x}'))
        vm_mac_prefixes = ["08:00:27", "00:05:69", "00:0c:29", "00:1c:14", "00:50:56"]
        if any(mac.lower().startswith(prefix) for prefix in vm_mac_prefixes):
            score += 2
            positive_indicators.append("vm_mac_address")
            if verbose: 
                logging.info("Corroborating Indicator: VM-associated MAC address found.")
    except Exception:
        pass

    return score, list(set(positive_indicators))

def enforce_security_sandbox(required_score=4, allow_override=False):
    """Enforce security sandbox requirement before code execution."""
    # Override check
    if allow_override and os.environ.get("UNSAFE_EXECUTION_OK", "false").lower() == "true":
        logging.warning("⚠️  WARNING: Safety check explicitly bypassed by user override.")
        logging.warning("          Executing on the host machine at your own risk.")
        return

    logging.info("Running Security Sandbox Check...")
    score, indicators = check_security_sandbox_indicators(verbose=True)

    if score >= required_score:
        friendly_name = indicators[0] if indicators else "Unknown Sandbox"
        logging.info(f"✅ Security Check Passed (Score: {score}, Indicator: {friendly_name})")
        logging.info("   OS-level isolated environment detected. Proceeding with code execution.")
        return
    else:
        # Critical security failure
        error_msg = f"""
❌ DANGER: SECURITY CHECK FAILED (Score: {score}, Required: {required_score}) ❌
{'='*70}
This system executes AI-generated code and requires a secure, isolated
environment to protect your computer from unintended or harmful actions.

Running directly on your main operating system is **EXTREMELY UNSAFE**.
{'='*70}

▶️ HOW TO RUN SCILINK SAFELY:
You MUST restart SciLink inside a container or virtual machine.

1. Docker (Strongly Recommended):
   Use the provided Dockerfile or run in a Docker container.

2. Virtual Machine:
   Install and run SciLink within a VM (VMware, VirtualBox, Cloud VM, etc.).

3. Google Colab:
   Use Colab's isolated notebook environment.

4. Advanced Override (NOT RECOMMENDED):
   Set environment variable: UNSAFE_EXECUTION_OK=true
{'='*70}
"""
        logging.error(error_msg)
        raise RuntimeError("Security sandbox requirement not met. Halting execution for safety.")


# Modified StructureExecutor class
class StructureExecutor:
    def __init__(self, timeout: int = DEFAULT_TIMEOUT, mp_api_key: str = None, 
                 enforce_sandbox: bool = True, allow_unsafe_override: bool = False):
        self.timeout = timeout
        self.mp_api_key = mp_api_key or get_api_key('materials_project') or os.getenv("MP_API_KEY")
        self.enforce_sandbox = enforce_sandbox
        self.allow_unsafe_override = allow_unsafe_override
        
        # Perform security check on initialization
        if self.enforce_sandbox:
            enforce_security_sandbox(allow_override=self.allow_unsafe_override)
        
        logging.info(f"StructureExecutor initialized with timeout: {self.timeout}s")
        if self.mp_api_key:
            logging.info("MP API key configured for script execution")
        else:
            logging.warning("No MP API key - scripts using Materials Project may fail")

    def execute_script(self, script_content: str, working_dir: str = None) -> dict:
        """Execute AI-generated script with security enforcement."""
        
        # Additional security check before each execution (optional but recommended)
        if self.enforce_sandbox:
            try:
                enforce_security_sandbox(allow_override=self.allow_unsafe_override)
            except RuntimeError as e:
                return {"status": "error", "message": f"Security check failed: {str(e)}"}
        
        logging.info("Attempting to execute generated ASE script...")
        logging.warning("⚠️  EXECUTING AI-GENERATED CODE - Security sandbox verified")
        
        # Rest of the existing execute_script method remains the same...
        temp_script_file = None
        try:
            with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as tf:
                tf.write(script_content)
                temp_script_file = tf.name
            logging.debug(f"Temporary script saved to: {temp_script_file}")

            env = os.environ.copy()
            if self.mp_api_key:
                env['MP_API_KEY'] = self.mp_api_key
                logging.debug("Added MP_API_KEY to script execution environment")

            original_cwd = os.getcwd()
            if working_dir:
                os.makedirs(working_dir, exist_ok=True)
                os.chdir(working_dir)
            
            result = subprocess.run(
                ['python', temp_script_file],
                capture_output=True,
                text=True,
                timeout=self.timeout,
                env=env,
                check=False
            )

            logging.debug("--- Script Execution Finished ---")
            logging.debug(f"STDOUT:\n{result.stdout}")
            logging.debug(f"STDERR:\n{result.stderr}")

            if result.returncode == 0:
                output_file = None
                for line in result.stdout.splitlines():
                    if line.startswith("STRUCTURE_SAVED:"):
                        output_file = line.split(":", 1)[1].strip()
                        break
                if output_file and os.path.exists(output_file):
                     logging.info(f"Script executed successfully. Output file found: {output_file}")
                     full_output_path = os.path.abspath(output_file)
                     return {"status": "success", "output_file": full_output_path}
                elif output_file:
                     error_msg = f"Script reported saving to {output_file}, but file not found."
                     logging.error(error_msg)
                     error_msg += f"\nSTDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}"
                     return {"status": "error", "message": error_msg}
                else:
                    error_msg = "Script executed successfully (exit code 0), but did not report an output filename using 'STRUCTURE_SAVED:<filename>'."
                    logging.error(error_msg)
                    error_msg += f"\nSTDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}"
                    return {"status": "error", "message": error_msg}
            else:
                error_msg = f"Script execution failed with return code {result.returncode}.\nSTDERR:\n{result.stderr}"
                logging.error(error_msg)
                return {"status": "error", "message": error_msg}

        except FileNotFoundError:
             error_msg = "'python' command not found. Is Python installed and in PATH with ASE?"
             logging.exception(error_msg)
             return {"status": "error", "message": error_msg}
        except subprocess.TimeoutExpired:
             error_msg = f"Script execution timed out after {self.timeout} seconds."
             logging.error(error_msg)
             stderr_so_far = result.stderr if 'result' in locals() and hasattr(result, 'stderr') else 'N/A'
             stdout_so_far = result.stdout if 'result' in locals() and hasattr(result, 'stdout') else 'N/A'
             error_msg += f"\nSTDOUT (before timeout):\n{stdout_so_far}\nSTDERR (before timeout):\n{stderr_so_far}"
             return {"status": "error", "message": error_msg}
        except Exception as e:
            error_msg = f"An unexpected error occurred during script execution: {e}"
            logging.exception(error_msg)
            return {"status": "error", "message": error_msg}
        finally:
            os.chdir(original_cwd)
            if temp_script_file and os.path.exists(temp_script_file):
                try:
                    os.remove(temp_script_file)
                    logging.debug(f"Temporary script file removed: {temp_script_file}")
                except OSError as e:
                    logging.warning(f"Could not remove temporary file {temp_script_file}: {e}")



================================================
File: agents/sim_agents/instruct.py
================================================
INITIAL_PROMPT_TEMPLATE = """
You are an expert in computational modeling of materials. The user requested to build: "{description}"

First, think step-by-step about how you would create this structure:
1. What material(s) and crystal structure(s) are needed? (For multi-material systems: identify each component)
2. What supercell sizes, layer thicknesses, or geometric parameters are required?
3. What defects, substitutions, or other modifications need to be applied?
4. What atomic constraints are physically appropriate for this model? (e.g., fixing the bottom layers of a slab to mimic bulk).
5. How should the materials be combined? (For interfaces/heterostructures: stacking order, lattice matching, strain accommodation)
6. In what order should these steps be performed?

Then, generate a *complete* and *executable* Python script using the Atomic Simulation Environment (ASE) library to implement your approach:
1. The script MUST include necessary imports (e.g., `from ase import Atoms`, `from ase.build import ...`, `from ase.io import write`).
2. The script MUST define or load the base structure correctly (e.g., using `bulk`, `surface`, `molecule`, or reading a file if appropriate).
3. The script MUST perform any requested modifications (e.g., creating vacancies, substituting atoms, adding adsorbates, applying strain). Use standard ASE functionalities when available.
4. The script MUST save the final `Atoms` object to a file (e.g., 'structure.xyz', 'POSCAR', 'structure.cif'). Choose a suitable, simple filename.
5. CRITICALLY: Immediately after successfully saving the file, the script MUST print *exactly* this confirmation line to standard output: `STRUCTURE_SAVED:<filename.ext>` (replace `<filename.ext>` with the actual filename used). No other output should precede or follow this specific line unless it's part of error handling.
6. Ensure the script handles potential issues gracefully if possible (e.g., checks for valid indices if modifying atoms).
7. Call the '{tool_name}' function/tool with the *entire generated Python script content* as the 'script_content' argument. Do not add any explanatory text before or after the function call itself in your response.
"""

CORRECTION_PROMPT_TEMPLATE = """
The user's original request was: "{original_request}"

You previously generated the following Python ASE script:
```python
{failed_script}
```
However, executing this script failed with the following error (traceback included):
{error_message}
Your task is to:

Analyze the error message (especially the traceback) and the failed script provided above.
Identify the specific bug or issue in the script that caused the error. Common issues include incorrect imports, wrong function arguments, index errors, undefined variables, or logical errors in structure manipulation.
Generate a corrected, complete, and executable Python ASE script that fulfills the original request ("{original_request}") and specifically avoids the previous error.
The corrected script MUST still include all necessary imports, structure definition/modification, saving the file with ase.io.write(), and printing the exact confirmation line 'STRUCTURE_SAVED:<filename.ext>' upon successful saving. Use a simple filename.
Call the '{tool_name}' function/tool again, providing the entire corrected Python script content as the 'script_content' argument. Do not add explanatory text around the function call itself. 
"""


VALIDATOR_PROMPT_TEMPLATE = """You are an expert materials scientist and computational modeling specialist.
Your task is to critically review an unrelaxed atomic structure generated by a Python script. This structure is intended as an initial input for DFT relaxation. Therefore, the purpose is to create a reasonable starting geometry, not a perfect relaxed structure. If this is a grain boundary, interface, or surface structure, be aware that atomic clashes and close contacts (<1.0 Å) are NORMAL and EXPECTED in unrelaxed interfaces, and should not be considered as major issues needed to be fixed.

{tool_documentation}

**Input Provided to You:**
1.  **Original User Request for Structure:** A textual description of the desired atomic structure.
    Example: "{original_request}"
2.  **Generating Script Content:** The Python script used to create the structure.
    Example:
    ```python
    {generating_script_content}
    ```
3.  **Structure File Content:** The raw content of the structure file generated with this exact script.
4.  **Structure Images (Visual Aid):** Images of the generated structure viewed along the X, Y, and Z axes. These are provided as a supplementary visual reference.

**Your Task & Output Format:**

Based on a holistic analysis of ALL provided information (request, script, file content, and images), you MUST output a valid JSON object with the following keys:

1.  `"overall_assessment"`: (String) A brief (2-3 sentences) overall assessment of the structure's suitability for DFT, its adherence to the original request, and its physical/chemical soundness. Your analysis should be centered on the **script logic and the structure file content**, using the images as a helpful visual reference.
2.  `"identified_issues_detail"`: (List of Strings) A list of ALL specific issues you identified. Analyze the script and structure file for:
    * Discrepancies from the "Original User Request" (e.g., wrong composition, incorrect lattice, missing defects, wrong surface termination).
    * Gross physical or chemical unreasonableness (e.g., severe atomic clashes that relaxation might not fix, fundamentally wrong bonding indicative of incorrect script logic).
    * Stoichiometry errors.
    * For slabs/surfaces: insufficient vacuum, incorrect layer stacking.
    * Any other obvious issues visible in the file content or images that would cause DFT problems.
    If no critical issues are found, this should be an empty list.
3.  `"script_modification_hints"`: (List of Strings) Actionable suggestions on how the *provided script* could be modified to address the identified issues. Base these suggestions on your analysis of both the script and the resulting structure. If specialized library documentation is provided, use that library's specific syntax. If the structure is a good starting point, provide an empty list.

Ensure your output is ONLY the valid JSON object described above. Do not include any other text, explanations, or markdown formatting outside the JSON structure.
"""


DOCS_ENHANCED_INITIAL_PROMPT_TEMPLATE = """
## SPECIALIZED LIBRARY DOCUMENTATION:
{documentation}

## USER REQUEST:
"{description}"

## YOUR TASK:
Based on the specialized library documentation provided above, generate a Python script to fulfill the user request:

1. Parse the user request and use the exact syntax, classes, and methods shown in the documentation above
2. Generate a *complete* and *executable* Python script with proper imports as documented
3. The script MUST save the final structure to a file
4. CRITICALLY: Print exactly: `STRUCTURE_SAVED:<filename.ext>` after successful saving
5. Call the '{tool_name}' function with the complete script as 'script_content'

Follow the patterns, syntax, and best practices shown in the documentation above.
"""


DOCS_ENHANCED_CORRECTION_PROMPT_TEMPLATE = """
## SPECIALIZED LIBRARY DOCUMENTATION:
{documentation}

## ORIGINAL REQUEST:
"{original_request}"

## FAILED SCRIPT:
```python
{failed_script}
```

## ERROR MESSAGE:
{error_message}

## YOUR TASK:
Using the specialized library documentation above, generate a corrected script that:

1. Fixes the specific error shown above
2. Uses proper syntax and methods as documented above
3. Fulfills the original request: "{original_request}"
4. Saves the structure and prints 'STRUCTURE_SAVED:<filename>'
5. Call the '{tool_name}' function with the corrected script content

Reference the documentation above for correct usage patterns and syntax.
"""


SCRIPT_CORRECTION_FROM_VALIDATION_TEMPLATE = """
The user's original request for an atomic structure was: "{original_request}"

A previous attempt to generate an ASE script for this request was made.
- **Previously Attempted Script:**
  ```python
  {attempted_script_content}
  ```
- **Validation Feedback on the Structure Produced by the Above Script:**
  - **Overall Assessment by Validator:** {validator_overall_assessment}
  - **Specific Issues Identified by Validator:**
    {validator_specific_issues}
  - **Validator's Hints for Modifying the Script:**
    {validator_script_hints}

Your task is to generate a **new, corrected, complete, and executable Python ASE script** that:
1.  Precisely fulfills the original user request: "{original_request}".
2.  Directly addresses all "Specific Issues Identified by Validator".
3.  Intelligently incorporates the "Validator's Hints for Modifying the Script". If hints conflict or are unclear, prioritize fulfilling the original request and fixing issues.
4.  The script MUST include all necessary imports (e.g., `from ase import Atoms`, `from ase.build import ...`, `from ase.io import write`).
5.  The script MUST save the final `Atoms` object to a file (e.g., 'structure.xyz', 'POSCAR'). Choose a suitable, simple filename.
6.  CRITICALLY: Immediately after successfully saving the file, the script MUST print *exactly* this confirmation line to standard output: `STRUCTURE_SAVED:<filename.ext>` (replace `<filename.ext>` with the actual filename used).
7.  Call the '{tool_name}' function/tool with the *entire new corrected Python script content* as the 'script_content' argument. Do not add any explanatory text before or after the function call itself in your response.
"""


VASP_INPUT_GENERATION_INSTRUCTIONS = """You are an expert computational materials scientist specializing in VASP (Vienna Ab-initio Simulation Package) calculations.

Your task is to generate appropriate INCAR and KPOINTS files based on:
1. The provided POSCAR structure file content
2. The original user request describing the scientific objective

**GUIDELINES FOR VASP INPUT GENERATION:**

## INCAR File Guidelines:
- **ENCUT**: Set based on POTCAR requirements (typically 400-600 eV, higher for accurate forces/stress)
- **PREC**: Use "Accurate" for production calculations, "Normal" for testing
- **ALGO**: "Normal" for most cases, "VeryFast" for large systems, "All" for difficult convergence
- **ISMEAR**: 
  - -5 (tetrahedron) for static calculations and DOS
  - 0 (Gaussian) for insulators/semiconductors with appropriate SIGMA
  - 1 (Methfessel-Paxton) for metals
- **Relaxation parameters**: IBRION, ISIF, NSW, EDIFFG based on what needs to be relaxed
- **Electronic convergence**: EDIFF (typically 1E-6 for forces, 1E-8 for accurate energies)
- **Special considerations**:
  - Surface/slab: LDIPOL, DIPOL for dipole corrections
  - Magnetic systems: ISPIN=2, MAGMOM
  - Hybrid functionals: HSE06 parameters if needed
  - van der Waals: DFT-D3 corrections if appropriate

## KPOINTS File Guidelines:
- **Grid density**: Balance accuracy vs computational cost
- **Monkhorst-Pack**: Most common, specify grid and shift
- **Gamma-centered**: For even grids, often more efficient
- **Special cases**:
  - 2D/surface systems: 1 k-point along vacuum direction
  - 1D systems: 1 k-point in confined directions
  - Large supercells: Gamma-point only might be sufficient
- **Convergence**: Ensure k-point density is converged for the property of interest

## Calculation Type Recognition:
Based on the user request, determine the appropriate calculation type:
- **Structure relaxation**: Full optimization of atomic positions and/or cell
- **Static calculation**: Single-point energy at fixed geometry
- **Electronic structure**: Band structure, DOS calculations
- **Optical properties**: Dielectric function, absorption
- **Defect calculations**: Special considerations for charged defects
- **Surface calculations**: Slab models with vacuum and dipole corrections

## Parameter Selection Logic:
1. **Identify the main scientific objective** from the user request
2. **Analyze the structure type** (bulk, surface, 2D, defective, etc.) from the POSCAR
3. **Choose appropriate calculation workflow** (relax → static → analysis)
4. **Set parameters based on required accuracy** vs computational efficiency
5. **Include relevant physical effects** (magnetism, van der Waals, etc.)

## Structure Analysis:
From the POSCAR content provided below, analyze:
- System size and composition
- Dimensionality (bulk, surface/slab, 2D, etc.)
- Presence of vacuum gaps
- Chemical elements (check for magnetic species)
- Cell parameters and symmetry

## INPUT DATA:

**POSCAR Structure File:**
{poscar_content}

**Scientific Objective:**
{original_request}

## Output Requirements:
You MUST provide a JSON response with exactly these keys:
{{
  "incar": "complete INCAR file content",
  "kpoints": "complete KPOINTS file content", 
  "summary": "brief calculation description"
}}

Analyze the provided POSCAR structure and user request, then generate appropriate VASP input files following the guidelines above."""



INCAR_VALIDATION_INSTRUCTIONS = """You are an expert VASP computational materials scientist. 

Your task is to analyze a literature review of VASP INCAR parameters and suggest specific adjustments if needed.

You will receive:
1. The original INCAR file content
2. A literature review assessment of these parameters
3. The system description

Based on the literature review, determine if any parameters should be adjusted and provide specific recommendations.

You MUST respond with a JSON object containing:
{{
  "validation_status": "good" or "needs_adjustment",
  "overall_assessment": "brief summary of the literature findings",
  "suggested_adjustments": [
    {{
      "parameter": "PARAMETER_NAME",
      "current_value": "current value",
      "suggested_value": "suggested value", 
      "reason": "explanation based on literature"
    }}
  ],
  "revised_incar": "complete revised INCAR content if adjustments needed, or null if no changes"
}}

Focus on actionable parameter changes. Only suggest adjustments if the literature clearly indicates issues.
"""



================================================
File: agents/sim_agents/llm_client.py
================================================
import google.generativeai as genai
import logging


class LLMClient:
    def __init__(self, api_key: str, model_name: str):
        if not api_key:
            raise ValueError("API key not provided to LLMClient.")
        self.model_name = model_name
        try:
            # Configuration should ideally happen once externally,
            # but doing it here is okay for simplicity if this is the only client
            genai.configure(api_key=api_key)
            self.model = genai.GenerativeModel(self.model_name)
            logging.info(f"LLMClient initialized with model: {self.model_name}")
        except Exception as e:
            logging.exception(f"Error configuring GenerativeAI client for {model_name}: {e}")
            raise

    def generate_with_tools(self, prompt: str, tools: list, generation_config=None):
        logging.info("Sending request to LLM...")
        logging.debug(f"Prompt length: {len(prompt)} chars")
        try:
            response = self.model.generate_content(
                prompt,
                tools=tools,
                generation_config=generation_config
            )
            logging.debug(f"LLM Raw Response: {response}")
            return response
        except Exception as e:
            logging.exception(f"Error during LLM content generation: {e}")
            raise

    def send_function_response(self, tool_name: str, response_dict: dict, tools: list):
        logging.info(f"Sending function response for '{tool_name}' back to LLM.")
        logging.debug(f"Function response data: {response_dict}")
        try:
            function_response_proto = genai.protos.FunctionResponse(...) # Adapt as needed
            content_to_send = genai.protos.Content(...) # Adapt as needed
            response = self.model.generate_content(content_to_send, tools=tools)
            logging.debug(f"LLM Raw Response after function result: {response}")
            return response
        except Exception as e:
            logging.exception(f"Error sending function response for tool '{tool_name}': {e}")
            raise


================================================
File: agents/sim_agents/structure_agent.py
================================================
import logging
from typing import Optional, Tuple

from .llm_client import LLMClient
from .executors import StructureExecutor, DEFAULT_TIMEOUT
from .tools import get_available_tools
from .instruct import (
    INITIAL_PROMPT_TEMPLATE, 
    CORRECTION_PROMPT_TEMPLATE, 
    SCRIPT_CORRECTION_FROM_VALIDATION_TEMPLATE,
    DOCS_ENHANCED_INITIAL_PROMPT_TEMPLATE,
    DOCS_ENHANCED_CORRECTION_PROMPT_TEMPLATE
)
from .utils import save_generated_script, MaterialsProjectHelper

MAX_INTERNAL_SCRIPT_EXEC_CORRECTION_ATTEMPTS = 5 

class StructureGenerator:
    def __init__(self, api_key: str, model_name: str,
                executor_timeout: int = DEFAULT_TIMEOUT,
                generated_script_dir: str = "generated_scripts",
                mp_api_key: str = None):
        """Initialize StructureGenerator with improved logging."""
        self.llm_client = LLMClient(api_key=api_key, model_name=model_name)
        self.ase_executor = StructureExecutor(timeout=executor_timeout, mp_api_key=mp_api_key)
        self.generated_script_dir = generated_script_dir
        self.logger = logging.getLogger(__name__)
        
        self.tools = get_available_tools()
        self.mp_helper = MaterialsProjectHelper(api_key=mp_api_key)
        
        # Improved initialization message
        print(f"🔧 Structure Generator Ready")
        print(f"   📚 Available tools: {len(self.tools)} ({', '.join(t.name for t in self.tools)})")
        if self.mp_helper.enabled:
            print(f"   🗃️  Materials Project: Connected")
        else:
            print(f"   🗃️  Materials Project: Not configured")

    def _select_tool(self, request_text: str):
        """Select the appropriate tool based on request content."""
        # Check specialized tools first
        for tool in self.tools:
            if tool.matches_request(request_text):
                self.logger.info(f"Selected {tool.name} tool based on keywords")
                return tool
        
        # Default to ASE tool (first one without keywords)
        ase_tool = next((t for t in self.tools if not t.keywords), self.tools[0])
        self.logger.info(f"Selected default {ase_tool.name} tool")
        return ase_tool

    def _build_initial_prompt(self, description: str, use_fallback: bool = False) -> str:
        """Build initial prompt with tool-specific documentation and MP integration."""
        selected_tool = self._select_tool(description)
        tool_name = next(iter(selected_tool.tool.function_declarations)).name
        
        # ADD MP integration to documentation
        enhanced_docs = selected_tool.docs_content
        if enhanced_docs and self.mp_helper.enabled:
            enhanced_docs += self.mp_helper.get_common_materials_info()
        
        if use_fallback or not enhanced_docs:
            return INITIAL_PROMPT_TEMPLATE.format(description=description, tool_name=tool_name)
        else:
            return DOCS_ENHANCED_INITIAL_PROMPT_TEMPLATE.format(
                description=description, tool_name=tool_name, documentation=enhanced_docs
            )

    def _build_script_execution_error_correction_prompt(self, original_request: str, failed_script: str, error_message: str) -> str:
        """Build correction prompt with tool-specific documentation if available."""
        selected_tool = self._select_tool(original_request)
        tool_name = next(iter(selected_tool.tool.function_declarations)).name
        
        max_error_len = 2000
        if len(error_message) > max_error_len:
            error_message = error_message[:max_error_len] + "\n[... Error message truncated ...]"
        
        if selected_tool.docs_content:
            return DOCS_ENHANCED_CORRECTION_PROMPT_TEMPLATE.format(
                original_request=original_request,
                failed_script=failed_script,
                error_message=error_message,
                tool_name=tool_name,
                documentation=selected_tool.docs_content
            )
        else:
            return CORRECTION_PROMPT_TEMPLATE.format(
                original_request=original_request,
                failed_script=failed_script,
                error_message=error_message,
                tool_name=tool_name
            )

    def _build_script_correction_from_validation_prompt(
            self, original_request: str, attempted_script_content: str,
            validator_assessment: str, validator_issues: list, validator_hints: list) -> str:
        """Build validation correction prompt with appropriate tool."""
        selected_tool = self._select_tool(original_request)
        tool_name = next(iter(selected_tool.tool.function_declarations)).name
        
        issues_str = "\n".join([f"- {issue}" for issue in validator_issues]) if validator_issues else "No specific issues listed."
        hints_str = "\n".join([f"- {hint}" for hint in validator_hints]) if validator_hints else "No specific hints provided."

        return SCRIPT_CORRECTION_FROM_VALIDATION_TEMPLATE.format(
            original_request=original_request,
            attempted_script_content=attempted_script_content,
            validator_overall_assessment=validator_assessment,
            validator_specific_issues=issues_str,
            validator_script_hints=hints_str,
            tool_name=tool_name
        )

    def _parse_llm_response(self, response) -> Tuple[Optional[str], Optional[dict]]:
        """Parse LLM response to extract text content or function call."""
        try:
            if not response or not response.candidates:
                feedback = getattr(response, 'prompt_feedback', None)
                block_reason = getattr(feedback, 'block_reason', 'Unknown reason')
                self.logger.warning(f"LLM response empty/no candidates. Block Reason: {block_reason}")
                return f"[Warning: LLM response was empty or blocked. Reason: {block_reason}]", None

            candidate = response.candidates[0]
            finish_reason = getattr(candidate, 'finish_reason', 'N/A')
            if finish_reason not in [1, "STOP", "TOOL_CALL"]:
                self.logger.warning(f"LLM response candidate finished unexpectedly: {finish_reason}")

            if not candidate.content or not candidate.content.parts:
                self.logger.warning(f"LLM response candidate has no content parts. Finish reason: {finish_reason}")
                return "[Warning: LLM response content was empty.]", None

            for part in candidate.content.parts:
                if hasattr(part, 'function_call') and getattr(part.function_call, 'name', None):
                    args_dict = {key: value for key, value in getattr(part.function_call, 'args', {}).items()}
                    return None, {"name": part.function_call.name, "args": args_dict}
            
            text_content = "".join(part.text for part in candidate.content.parts if hasattr(part, 'text')).strip()
            if text_content:
                return text_content, None
            
            self.logger.warning(f"LLM response contained neither function call nor text. Finish reason: {finish_reason}")
            return "[Warning: LLM response was valid but contained neither function call nor text.]", None

        except (AttributeError, IndexError, ValueError, TypeError) as e:
            self.logger.exception(f"Error parsing LLM response structure: {e}")
            return f"[Error: Could not parse LLM response: {e}]", None

    def generate_script(self, original_user_request: str, attempt_number_overall: int, 
                       is_refinement_from_validation: bool = False,
                       previous_script_content: Optional[str] = None,
                       validator_feedback: Optional[dict] = None) -> dict:
        """Generate or refine a script using appropriate tool and documentation with improved output."""
        
        # Select tool and get its info
        selected_tool = self._select_tool(original_user_request)
        tool_name = next(iter(selected_tool.tool.function_declarations)).name
        
        if is_refinement_from_validation:
            print(f"   🔄 Refining script using {selected_tool.name} (cycle {attempt_number_overall})")
            if not previous_script_content or not validator_feedback:
                return {"status": "error", "message": "Internal error: Refinement requires previous script and validation feedback."}
            current_prompt = self._build_script_correction_from_validation_prompt(
                original_request=original_user_request,
                attempted_script_content=previous_script_content,
                validator_assessment=validator_feedback.get("overall_assessment", "N/A"),
                validator_issues=validator_feedback.get("all_identified_issues", []),
                validator_hints=validator_feedback.get("script_modification_hints", [])
            )
        else:
            print(f"   🤖 Generating script using {selected_tool.name} (cycle {attempt_number_overall})")
            current_prompt = self._build_initial_prompt(original_user_request)

        tools_list = [selected_tool.tool]
        last_error_message_internal = "No internal attempts made yet."
        current_script_being_processed = previous_script_content if is_refinement_from_validation else None
        
        # Internal correction loop for script execution errors
        for internal_exec_attempt in range(1, MAX_INTERNAL_SCRIPT_EXEC_CORRECTION_ATTEMPTS + 1):
            
            generated_script_this_llm_call = None
            final_script_path_this_attempt = None

            try:
                # Show progress for multiple attempts
                if internal_exec_attempt > 1:
                    print(f"      🔧 Fixing script issues (attempt {internal_exec_attempt}/{MAX_INTERNAL_SCRIPT_EXEC_CORRECTION_ATTEMPTS})")
                
                llm_response = self.llm_client.generate_with_tools(current_prompt, tools_list)
                text_content, function_call = self._parse_llm_response(llm_response)

                if function_call and function_call["name"] == tool_name:
                    generated_script_this_llm_call = function_call["args"].get("script_content")
                    if not generated_script_this_llm_call:
                        last_error_message_internal = f"LLM tool call missing 'script_content' (attempt {internal_exec_attempt})"
                        self.logger.error(last_error_message_internal)
                        if internal_exec_attempt == MAX_INTERNAL_SCRIPT_EXEC_CORRECTION_ATTEMPTS: 
                            break
                        continue

                    current_script_being_processed = generated_script_this_llm_call

                    # Save script
                    script_desc_for_filename = f"{original_user_request[:30]}_cycle{attempt_number_overall}_exec_attempt{internal_exec_attempt}"
                    final_script_path_this_attempt = save_generated_script(
                        current_script_being_processed,
                        script_desc_for_filename,
                        1,
                        output_dir=self.generated_script_dir
                    )
                    
                    if not final_script_path_this_attempt:
                        last_error_message_internal = f"Failed to save script (attempt {internal_exec_attempt})"
                        self.logger.error(last_error_message_internal)
                        break

                    # Execute script with progress indication
                    if internal_exec_attempt == 1:
                        print(f"      ⚙️  Executing script...")
                    else:
                        print(f"      ⚙️  Re-executing corrected script...")
                        
                    exec_result = self.ase_executor.execute_script(current_script_being_processed, working_dir=self.generated_script_dir)

                    if exec_result["status"] == "success":
                        print(f"      ✅ Script executed successfully")
                        return {
                            "status": "success",
                            "message": f"Script generated and executed successfully on attempt {internal_exec_attempt}",
                            "output_file": exec_result.get("output_file"),
                            "final_script_path": final_script_path_this_attempt,
                            "final_script_content": current_script_being_processed,
                            "tool_used": selected_tool.name,
                            "execution_attempts": internal_exec_attempt
                        }
                    else:
                        last_error_message_internal = exec_result.get("message", f"Unknown script execution error (attempt {internal_exec_attempt})")
                        
                        if internal_exec_attempt == MAX_INTERNAL_SCRIPT_EXEC_CORRECTION_ATTEMPTS:
                            print(f"      ❌ Script execution failed after {MAX_INTERNAL_SCRIPT_EXEC_CORRECTION_ATTEMPTS} attempts")
                            self.logger.error("Max internal script execution correction attempts reached.")
                            break
                        
                        # Show what went wrong for user awareness
                        error_summary = self._summarize_error(last_error_message_internal)
                        print(f"      ⚠️  Execution failed: {error_summary}")
                        print(f"         Attempting to fix...")
                        
                        current_prompt = self._build_script_execution_error_correction_prompt(
                            original_request=original_user_request,
                            failed_script=current_script_being_processed,
                            error_message=last_error_message_internal
                        )
                        continue

                elif text_content:
                    last_error_message_internal = f"LLM responded with text instead of tool call (attempt {internal_exec_attempt})"
                    if internal_exec_attempt == MAX_INTERNAL_SCRIPT_EXEC_CORRECTION_ATTEMPTS: 
                        break
                    continue

                else:
                    last_error_message_internal = text_content if text_content else f"LLM gave unusable response (attempt {internal_exec_attempt})"
                    self.logger.error(last_error_message_internal)
                    break

            except Exception as e: 
                self.logger.exception(f"Unexpected error during script generation/execution (attempt {internal_exec_attempt}): {e}")
                last_error_message_internal = f"Unexpected workflow error: {e}"
                break
        
        # Internal loop finished without success
        print(f"      ❌ Failed to generate working script after {MAX_INTERNAL_SCRIPT_EXEC_CORRECTION_ATTEMPTS} attempts")
        return {
            "status": "error",
            "message": f"Failed to generate executable script after {MAX_INTERNAL_SCRIPT_EXEC_CORRECTION_ATTEMPTS} attempts",
            "last_error": last_error_message_internal,
            "last_attempted_script_path": final_script_path_this_attempt if 'final_script_path_this_attempt' in locals() else None,
            "last_attempted_script_content": current_script_being_processed,
            "tool_attempted": selected_tool.name
        }

    def _summarize_error(self, error_message: str) -> str:
        """Create a brief, user-friendly error summary."""
        error_lower = error_message.lower()
        
        # Common error patterns
        if "modulenotfounderror" in error_lower or "import" in error_lower:
            return "Missing Python module/import"
        elif "nameerror" in error_lower:
            return "Undefined variable or function"
        elif "syntaxerror" in error_lower:
            return "Python syntax error"
        elif "indexerror" in error_lower:
            return "Array/list index out of range"
        elif "keyerror" in error_lower:
            return "Dictionary key not found"
        elif "typeerror" in error_lower:
            return "Incorrect data type usage"
        elif "valueerror" in error_lower:
            return "Invalid value or parameter"
        elif "filenotfounderror" in error_lower:
            return "File or path not found"
        elif "timeout" in error_lower:
            return "Script execution timeout"
        elif "structure_saved" in error_lower:
            return "Missing output confirmation"
        else:
            # Extract first line of error for brevity
            first_line = error_message.split('\n')[0]
            return first_line[:80] + "..." if len(first_line) > 80 else first_line


================================================
File: agents/sim_agents/tools.py
================================================
import google.generativeai as genai
import os
import logging

# Define constants for tool names
ASE_EXECUTE_TOOL_NAME = "execute_ase_script"
GB_EXECUTE_TOOL_NAME = "execute_gb_script"

def define_ase_tool():
    """Defines the Tool structure for the ASE script execution function."""
    return genai.protos.Tool(
        function_declarations=[
            genai.protos.FunctionDeclaration(
                name=ASE_EXECUTE_TOOL_NAME,
                description=(
                    "Executes a Python script using the Atomic Simulation Environment (ASE) "
                    "library to generate or modify an atomic structure based on the user request. "
                    "The script must save the final structure (e.g., as POSCAR, CIF, XYZ) "
                    "and then print a confirmation line: 'STRUCTURE_SAVED:<filename.ext>'."
                ),
                parameters=genai.protos.Schema(
                    type=genai.protos.Type.OBJECT,
                    properties={
                        'script_content': genai.protos.Schema(
                            type=genai.protos.Type.STRING,
                            description=(
                                "The complete Python script content as a string. Ensure it "
                                "includes necessary imports (like ase, ase.io, ase.build), "
                                "defines the structure, performs any requested modifications, "
                                "saves the structure using ase.io.write(), and prints "
                                "'STRUCTURE_SAVED:<filename>' on success."
                            )
                        )
                    },
                    required=['script_content']
                )
            )
        ]
    )

def define_gb_tool():
    """Defines the grain boundary tool (requires aimsgb documentation)."""
    return genai.protos.Tool(
        function_declarations=[
            genai.protos.FunctionDeclaration(
                name=GB_EXECUTE_TOOL_NAME,
                description=(
                    "Executes a Python script using the aimsgb library to generate grain boundary "
                    "structures based on Coincident Site Lattice (CSL) theory. Use this specifically "
                    "for creating bicrystal interfaces, twist/tilt grain boundaries, and related "
                    "crystallographic interfaces. The script must save the structure and print "
                    "confirmation: 'STRUCTURE_SAVED:<filename.ext>'."
                ),
                parameters=genai.protos.Schema(
                    type=genai.protos.Type.OBJECT,
                    properties={
                        'script_content': genai.protos.Schema(
                            type=genai.protos.Type.STRING,
                            description=(
                                "Complete Python script using aimsgb library. Must include "
                                "imports (from aimsgb import Grain, GrainBoundary), create GB "
                                "structure, save with .to() method, and print 'STRUCTURE_SAVED:<filename>'."
                            )
                        )
                    },
                    required=['script_content']
                )
            )
        ]
    )

# Tool configurations - moved from config.py
TOOL_CONFIGS = {
    "GrainBoundary": {
        "docs_path": "docs/aimsgb.txt",  # Relative to sim_agents directory
        "keywords": ["grain boundary", "grain-boundary", "gb ", "sigma", "csl", 
                    "twist", "tilt", "bicrystal", "rotation axis", "aimsgb"],
        "tool_func": "define_gb_tool"
    }
    # Future tools can be added here
}

# Tool function mapping
TOOL_FUNCTION_MAP = {
    "define_ase_tool": define_ase_tool,
    "define_gb_tool": define_gb_tool,
    # Add new tool functions here as they're created
}

class ToolWithDocs:
    """Container for a tool and its optional documentation."""
    
    def __init__(self, name: str, tool_func, docs_path: str = None, keywords: list = None):
        self.name = name
        self.tool = tool_func()
        self.docs_path = docs_path
        self.keywords = keywords or []
        self.docs_content = self._load_docs() if docs_path else None
        
        logger = logging.getLogger(__name__)
        if self.docs_content:
            logger.info(f"Loaded documentation for {name} tool ({len(self.docs_content)} chars)")
        else:
            logger.info(f"Initialized {name} tool (no additional documentation)")
    
    def _load_docs(self) -> str:
        """Load documentation from file if it exists."""
        if not self.docs_path:
            return None
            
        # Try different path resolutions
        possible_paths = [
            self.docs_path,  # As provided
            os.path.join(os.path.dirname(__file__), self.docs_path),  # Relative to this file
            os.path.join(os.path.dirname(__file__), "../..", self.docs_path),  # From package root
        ]
        
        for path in possible_paths:
            if os.path.exists(path):
                try:
                    with open(path, 'r', encoding='utf-8') as f:
                        content = f.read()
                    
                    # Optionally truncate if too long
                    max_length = 60000
                    if len(content) > max_length:
                        content = content[:max_length] + "\n\n[... Documentation truncated ...]"
                        logging.info(f"Truncated {self.name} docs from {len(content)} to {max_length} chars")
                    
                    logging.info(f"Loaded docs for {self.name} from: {path}")
                    return content
                except Exception as e:
                    logging.error(f"Failed to read docs for {self.name} from {path}: {e}")
                    continue
        
        logging.warning(f"Documentation file not found for {self.name}: {self.docs_path}")
        return None
    
    def matches_request(self, request_text: str) -> bool:
        """Check if this tool matches the request based on keywords."""
        if not self.keywords:
            return False
        
        request_lower = request_text.lower()
        return any(keyword in request_lower for keyword in self.keywords)

def get_available_tools():
    """Get all available tools with their configurations."""
    tools = []
    
    # Always include ASE as the default fallback tool
    tools.append(ToolWithDocs(
        name="ASE",
        tool_func=define_ase_tool,
        docs_path=None,
        keywords=[]  # Empty keywords means it's the fallback
    ))
    
    # Add configured tools
    for tool_name, config_dict in TOOL_CONFIGS.items():
        if tool_name == "ASE":
            continue  # Skip ASE, already added
        
        func_name = config_dict.get("tool_func")
        tool_func = TOOL_FUNCTION_MAP.get(func_name)
        
        if tool_func is None:
            logging.warning(f"Tool function '{func_name}' not found for tool '{tool_name}'. Skipping.")
            continue
        
        tools.append(ToolWithDocs(
            name=tool_name,
            tool_func=tool_func,
            docs_path=config_dict.get("docs_path"),
            keywords=config_dict.get("keywords", [])
        ))
        
        logging.info(f"Registered tool: {tool_name}")
    
    return tools


================================================
File: agents/sim_agents/utils.py
================================================
import os
import logging
from typing import Optional, List, Dict

import numpy as np

from datetime import datetime

from ...auth import get_api_key 

try:
    from ase.io import read as ase_read
    from ase.io import write as ase_write
    ASE_AVAILABLE = True
except ImportError:
    ASE_AVAILABLE = False
    # Define dummy functions to avoid runtime errors if ASE is not installed
    def ase_read(*args, **kwargs):
        raise ImportError("ASE is not installed. Please install it to use this functionality.")
    def ase_write(*args, **kwargs):
        raise ImportError("ASE is not installed. Please install it to use this functionality.")


try:
    from mp_api.client import MPRester
    MP_API_AVAILABLE = True
except ImportError:
    MP_API_AVAILABLE = False
    # Define a dummy MPRester to avoid runtime errors
    class MPRester: # type: ignore
        def __init__(self, api_key: Optional[str] = None):
            pass
        def __enter__(self):
            return self
        def __exit__(self, exc_type, exc_val, exc_tb):
            pass


class MaterialsProjectHelper:
    """Minimal MP helper for automatic material resolution by searching for mp-ids."""

    def __init__(self, api_key: Optional[str] = None):
        self.api_key = api_key or get_api_key('materials_project') or os.getenv("MP_API_KEY")
        self.enabled = MP_API_AVAILABLE and bool(self.api_key)
        self.logger = logging.getLogger(__name__)

        if self.enabled:
            self.logger.info("Materials Project helper enabled and API key found for mp-id search.")
        else:
            if not MP_API_AVAILABLE:
                self.logger.warning("Materials Project helper disabled: mp-api library not installed.")
            elif not self.api_key:
                self.logger.warning("Materials Project helper disabled: MP_API_KEY not set or provided.")
            else:
                self.logger.warning("Materials Project helper disabled for an unknown reason.")

    def get_common_materials_info(self) -> str:
        """Return info about common materials and the mp-id search capability for LLM context."""
        if not self.enabled: # Added this check for consistency
            return "Materials Project integration is disabled (no API key or mp-api not installed).\n"

        common_materials = {
            'YBCO': 'mp-20674', # YBa2Cu3O7
            'YBa2Cu3O7': 'mp-20674',
            'silicon': 'mp-149', # Elemental Si
            'Si': 'mp-149',
            'copper': 'mp-30', # Elemental Cu
            'Cu': 'mp-30',
            'graphite': 'mp-48', # Carbon
            'C (graphite)': 'mp-48',
            'diamond': 'mp-66', # Carbon
            'C (diamond)': 'mp-66',
            'iron': 'mp-13', # Elemental Fe
            'Fe': 'mp-13',
            'NaCl': 'mp-22862', # Sodium chloride, Rocksalt
            'salt': 'mp-22862',
            'LiFePO4': 'mp-19017', # Lithium iron phosphate, LFP
            'LFP': 'mp-19017',
            'SiO2 (alpha quartz)': 'mp-6930', # Silicon dioxide
            'quartz': 'mp-6930',
            'TiO2 (rutile)': 'mp-2657', # Titanium dioxide
            'rutile': 'mp-2657',
            'MoS2': 'mp-2815', # Molybdenum disulfide (2H phase, common)
            'graphene': 'mp-1040425'
        }

        info = "\n## MATERIALS PROJECT INTEGRATION (for mp-id lookup):\n"
        info += "This system can leverage the Materials Project (MP) database to find Material IDs (mp-ids).\n"
        info += "1.  **Common Materials by Name/Formula:**\n"
        info += "    If a user requests one of the following, you can often directly use its mp-id for structure generation (e.g., in ASE `bulk(mpid='mp-XYZ')`).\n"
        info += "    Known mp-ids:\n"
        for material, mp_id in common_materials.items():
            info += f"    - {material}: {mp_id}\n"
        info += "\n"
        info += "2.  **Searching for Other Material IDs (Conceptual Function):**\n"
        info += "    This helper provides a function to find mp-ids if a material is not in the common list or if a general chemical system is given.\n"
        info += "    - **`search_material_id(chemical_query: str, search_type: str = 'formula') -> Optional[str]`**\n"
        info += "        - Use this to find an mp-id. `chemical_query` can be a formula (e.g., 'LiCoO2', 'GaAs') or a chemical system (e.g., 'Fe-S-O', 'Si-C').\n"
        info += "        - `search_type` can be 'formula' (finds most stable polymorph for a specific stoichiometry) or 'chemsys' (finds the most stable material within the given elements).\n"
        info += "        - Example: If asked for 'gallium arsenide', you should note a search for `search_material_id('GaAs', search_type='formula')` is needed by the system.\n"
        info += "\n"
        info += "3.  **Using mp-ids in Scripts:**\n"
        info += "    Once an mp-id is known (e.g., 'mp-149' for Si), it can be used in ASE scripts like: `atoms = bulk(mpid='mp-149')`.\n"
        info += "\n"
        info += "**Guidance for LLM:** When a material is mentioned:\n"
        info += "    a. Check the common list above. If found, note the mp-id for use.\n"
        info += "    b. If not in the common list, state that a search using `search_material_id` is required, specifying the `chemical_query` and appropriate `search_type` for the system to perform.\n"

        return info

    def search_material_id(self, chemical_query: str, search_type: str = "formula") -> Optional[str]:
        """
        Search for a Materials Project ID given a chemical formula or system.
        Prioritizes the most stable material (lowest energy_above_hull).

        Args:
            chemical_query (str): The chemical formula (e.g., "SiO2") or
                                  chemical system (e.g., "Si-O") to search for.
            search_type (str): Type of search, either "formula" (default) or "chemsys".

        Returns:
            Optional[str]: The mp-id of the most likely material, or None if not found or error.
        """
        if not self.enabled:
            self.logger.warning("MP search_material_id attempted but helper is disabled.")
            return None
        if not chemical_query:
            self.logger.warning("MP search_material_id attempted with an empty query.")
            return None

        self.logger.info(f"Searching MP for '{chemical_query}' using search_type '{search_type}'")
        try:
            with MPRester(self.api_key) as mpr:
                # We only need material_id and energy_above_hull for sorting to find the best match.
                # formula_pretty is useful for logging/verification.
                fields_to_retrieve = ["material_id", "energy_above_hull", "formula_pretty"]
                results = []

                if search_type == "formula":
                    results = mpr.materials.summary.search(
                        formula=chemical_query,
                        fields=fields_to_retrieve
                    )
                elif search_type == "chemsys":
                    results = mpr.materials.summary.search(
                        chemsys=chemical_query,
                        fields=fields_to_retrieve
                    )
                else:
                    self.logger.error(f"Invalid search_type: {search_type}. Must be 'formula' or 'chemsys'.")
                    return None

                if results:
                    # Sort by energy_above_hull (lowest first), treating None as high energy.
                    # Then by material_id as a tie-breaker for reproducibility.
                    sorted_results = sorted(
                        results,
                        key=lambda x: (float('inf') if x.energy_above_hull is None else x.energy_above_hull, x.material_id)
                    )
                    best_match = sorted_results[0]
                    self.logger.info(
                        f"Found mp-id: {best_match.material_id} for {search_type} '{chemical_query}'. "
                        f"Actual Formula: {best_match.formula_pretty}, "
                        f"E_above_hull: {best_match.energy_above_hull:.4f} eV/atom" if best_match.energy_above_hull is not None else "E_above_hull: N/A"
                    )
                    return str(best_match.material_id)
                else:
                    self.logger.warning(f"No material found for {search_type}: {chemical_query}")
                    return None

        except Exception as e:
            self.logger.error(f"Error during Materials Project search for '{chemical_query}': {e}", exc_info=True)
            return None
    

def save_generated_script(script_content: str, description: str, attempt: int, output_dir: str) -> str | None:
    """Saves the script content to a file and returns the path."""
    try:
        # Ensure directory exists (might be better done once on agent init)
        os.makedirs(output_dir, exist_ok=True)

        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        # Sanitize description for use in filename
        safe_desc = "".join(c if c.isalnum() else "_" for c in description[:30]).rstrip("_")
        filename = f"script_{safe_desc}_attempt{attempt}_{timestamp}.py"
        saved_script_path = os.path.join(output_dir, filename)

        with open(saved_script_path, "w", encoding="utf-8") as f:
            f.write(script_content)
        logging.info(f"Saved script for attempt {attempt} to: {saved_script_path}")
        return saved_script_path
    except IOError as e:
        logging.error(f"Failed to save script for attempt {attempt}: {e}")
        return None
    except Exception as e: # Catch broader exceptions during save
        logging.error(f"Unexpected error saving script for attempt {attempt}: {e}")
        return None
    

def ask_user_proceed_or_refine(validation_feedback, structure_file):
    """Ask user whether to proceed with current structure or attempt refinement."""
    import sys
    
    print(f"\n--- Validation Issues Found ---")
    issues = validation_feedback.get('all_identified_issues', [])
    for i, issue in enumerate(issues, 1):
        print(f"  {i}. {issue}")
    
    print(f"\nOptions:")
    print(f"  [p] PROCEED - Use current structure: {structure_file}")
    print(f"  [r] REFINE   - Attempt to fix issues")
    
    while True:
        try:
            choice = input("Choice [p/r]: ").strip().lower()
            if choice in ['p', 'proceed']: return 'proceed'
            elif choice in ['r', 'refine']: return 'refine'
            else: print("Please enter 'p' or 'r'")
        except (KeyboardInterrupt, EOFError):
            return 'refine'


def generate_structure_views(structure_path: str, output_dir: str = None) -> Dict[str, str]:
    """
    Reads a structure file and saves images of the structure along the x, y, and z axes.
    Now with automatic centering for better visualization.
    """
    if not ASE_AVAILABLE:
        logging.warning("ASE not found, skipping image generation for validation.")
        return {}

    logger = logging.getLogger(__name__)
    image_paths = {}
    
    try:
        atoms = ase_read(structure_path)
        
        # ADD: Center the structure for better visualization
        atoms = _center_structure_for_visualization(atoms)  # <- ADD UNDERSCORE HERE
        
    except Exception as e:
        logger.error(f"Failed to read structure file {structure_path} with ASE: {e}")
        return image_paths

    if output_dir is None:
        output_dir = os.path.dirname(structure_path) or '.'
    os.makedirs(output_dir, exist_ok=True)

    base_name = os.path.splitext(os.path.basename(structure_path))[0]

    # Rotations for views along major axes
    rotations = {
        'x': '0y,90x,0z',  # View from +x
        'y': '-90x,0y,0z', # View from +y
        'z': '0x,0y,0z'    # View from +z (default)
    }

    logger.info(f"Generating structure view images for {structure_path}...")
    for axis, rotation in rotations.items():
        try:
            output_path = os.path.join(output_dir, f"{base_name}_view_{axis}.png")
            ase_write(output_path, atoms, format='png', rotation=rotation)
            image_paths[axis] = output_path
            logger.info(f"Saved structure view: {output_path}")
        except Exception as e:
            logger.error(f"Failed to write image for {axis}-axis view: {e}")

    return image_paths

def _center_structure_for_visualization(atoms):
    """Center structure in cell for better visualization"""
    positions = atoms.get_positions()
    cell = atoms.get_cell()
    
    # Center of mass
    center_of_mass = positions.mean(axis=0)
    
    # Cell center  
    cell_center = cell.sum(axis=0) / 2
    
    # Shift to center
    shift = cell_center - center_of_mass
    atoms.translate(shift)
    atoms.wrap()  # Keep atoms in cell
    
    return atoms

def _get_optimal_rotations(atoms):
    """Automatically determine optimal viewing angles with simple heuristics"""
    
    cell = atoms.get_cell()
    positions = atoms.get_positions()
    
    # Quick checks using existing ASE functionality
    
    # 1. Check for slab structure (large vacuum gap)
    if _is_slab_structure(cell, positions):
        return _get_slab_rotations(cell)
    
    # 2. Check for highly anisotropic cell
    elif _is_anisotropic(cell):
        return _get_anisotropic_rotations(cell)
    
    # 3. Check for layered structure
    elif _is_layered_structure(atoms):
        return _get_layered_rotations(cell)
    
    # 4. Default: use orthogonal views
    else:
        return {
            'x': '0y,90x,0z',
            'y': '-90x,0y,0z', 
            'z': '0x,0y,0z'
        }

def _is_slab_structure(cell, positions):
    """Detect slab by checking for vacuum gap > 5 Å"""
    cell_lengths = np.linalg.norm(cell, axis=1)
    z_extent = positions[:, 2].max() - positions[:, 2].min()
    
    # If cell is much larger than atomic extent in one direction = slab
    return any(length > z_extent + 5.0 for length in cell_lengths)

def _get_slab_rotations(cell):
    """Views optimized for slab structures"""
    # Find the longest cell vector (likely the vacuum direction)
    lengths = np.linalg.norm(cell, axis=1)
    vacuum_dir = np.argmax(lengths)
    
    if vacuum_dir == 2:  # vacuum along z
        return {
            'surface': '0x,0y,0z',      # Top view of surface
            'edge1': '90x,0y,0z',       # Edge view 1  
            'edge2': '0x,90y,0z'        # Edge view 2
        }
    elif vacuum_dir == 1:  # vacuum along y
        return {
            'surface': '90x,0y,0z',
            'edge1': '0x,0y,0z', 
            'edge2': '0x,0y,90z'
        }
    else:  # vacuum_dir == 0, vacuum along x
        return {
            'surface': '0x,90y,0z',
            'edge1': '0x,0y,0z',
            'edge2': '90x,0y,0z'
        }

def _is_anisotropic(cell):
    """Check if cell is highly anisotropic"""
    lengths = np.linalg.norm(cell, axis=1)
    ratio = lengths.max() / lengths.min()
    return ratio > 2.0  # If one direction is 2x larger than another

def _get_anisotropic_rotations(cell):
    """Views aligned with cell vectors for anisotropic structures"""
    # Find principal directions
    lengths = np.linalg.norm(cell, axis=1)
    
    # Sort by length to identify short/long directions
    sorted_indices = np.argsort(lengths)
    
    return {
        'along_short': f'0x,0y,{90 if sorted_indices[0] != 2 else 0}z',
        'along_medium': f'{90 if sorted_indices[1] == 0 else 0}x,{90 if sorted_indices[1] == 1 else 0}y,0z',
        'along_long': f'{90 if sorted_indices[2] == 0 else 0}x,{90 if sorted_indices[2] == 1 else 0}y,{90 if sorted_indices[2] == 2 else 0}z'
    }

def _is_layered_structure(atoms):
    """Simple check for layered materials based on z-coordinates"""
    positions = atoms.get_positions()
    z_coords = positions[:, 2]
    
    # Check if atoms form distinct layers (gaps > 2 Å between groups)
    sorted_z = np.sort(z_coords)
    gaps = np.diff(sorted_z)
    
    return np.any(gaps > 2.0)  # Significant gaps indicate layers

def _get_layered_rotations(cell):
    """Views for layered structures"""
    return {
        'layers': '90x,0y,0z',      # Side view to see layers
        'in_plane': '0x,0y,0z',     # Top view of layer plane
        'oblique': '45x,0y,45z'     # Oblique view for 3D perspective
    }


================================================
File: agents/sim_agents/val_agent.py
================================================
import os
import logging
import json
from typing import Dict

from ase.io import read as ase_read

import google.generativeai as genai
from google.generativeai.types import GenerationConfig

from .instruct import VALIDATOR_PROMPT_TEMPLATE, INCAR_VALIDATION_INSTRUCTIONS
from ..lit_agents.literature_agent import IncarLiteratureAgent
from .utils import generate_structure_views


class StructureValidatorAgent:
    def __init__(self, api_key: str, model_name: str):
        if api_key is None:
            api_key = os.environ.get("GOOGLE_API_KEY")
        if not api_key:
            raise ValueError("API key not provided for StructureValidatorAgent and GOOGLE_API_KEY not set.")
        
        genai.configure(api_key=api_key)
        self.model_name = model_name
        self.model = genai.GenerativeModel(self.model_name)
        self.generation_config = GenerationConfig(response_mime_type="application/json")
        self.logger = logging.getLogger(__name__)
        self.logger.info(f"StructureValidatorAgent initialized with model: {self.model_name}.")

    def _read_structure_file_content(self, structure_file_path: str) -> str:
        """
        Read the raw content of the structure file for LLM analysis.
        """
        try:
            with open(structure_file_path, 'r', encoding='utf-8') as f:
                content = f.read()
            
            # Limit content size for LLM context window
            max_chars = 10000
            if len(content) > max_chars:
                content = content[:max_chars] + "\n\n[... File truncated for context limits ...]"
                self.logger.warning(f"Structure file content truncated from {len(content)} to {max_chars} characters")
            
            return content
            
        except Exception as e:
            self.logger.error(f"Failed to read structure file content: {e}")
            return f"Error reading file: {str(e)}"

    def _check_file_parsable_and_load(self, structure_file_path: str) -> tuple[object | None, list, str]:
        """
        Checks if the structure file is parsable by ASE and reads raw content for LLM.
        """
        try:
            atoms = ase_read(structure_file_path)
            if not atoms or len(atoms) == 0:
                msg = f"Structure file '{structure_file_path}' is empty or could not be parsed into a valid ASE Atoms object."
                self.logger.warning(msg)
                return None, [msg], ""
            
            self.logger.info(f"Successfully parsed structure file: {structure_file_path}, {len(atoms)} atoms.")
            
            # Read raw file content for LLM analysis
            file_content = self._read_structure_file_content(structure_file_path)
            
            return atoms, [], file_content
            
        except Exception as e:
            self.logger.error(f"Failed to parse structure file '{structure_file_path}' with ASE: {e}")
            return None, [f"ASE could not parse structure file '{structure_file_path}'. Error: {e}"], ""


    def _get_llm_validation_and_hints(self, original_request: str, generating_script_content: str,
                                      structure_file_path: str, structure_file_content: str = "", 
                                      image_paths: Dict[str, str] = None,
                                      tool_documentation: str = None) -> dict:
        """
        Uses an LLM to perform full validation including analysis of the actual structure file content and images.
        """
        
        # Format tool documentation section
        doc_section = ""
        if tool_documentation:
            doc_section = f"""
    ## SPECIALIZED LIBRARY DOCUMENTATION:
    {tool_documentation}

    Please consider this documentation when validating the structure and providing script modification hints.
    Use the proper syntax, classes, and methods shown in the documentation above when suggesting improvements.

    """
        
        # Format structure file content section
        structure_section = ""
        if structure_file_content:
            structure_section = f"""

    ## ACTUAL STRUCTURE FILE CONTENT:
    ```
    {structure_file_content}
    ```

    """

        base_prompt = VALIDATOR_PROMPT_TEMPLATE.format(
            tool_documentation=doc_section,
            original_request=original_request,
            generating_script_content=generating_script_content,
            structure_file_path=structure_file_path,
        ) + structure_section

        # --- Build multi-modal prompt ---
        prompt_parts = [base_prompt]
        if image_paths:
            self.logger.info("Adding structure view images to validation prompt.")
            prompt_parts.append("\n\n## STRUCTURE VISUALIZATION:\n")
            # Read images into bytes and append
            for axis, img_path in sorted(image_paths.items()):
                try:
                    with open(img_path, 'rb') as f:
                        img_bytes = f.read()
                    prompt_parts.append(f"View along {axis.upper()}-axis:")
                    prompt_parts.append({"mime_type": "image/png", "data": img_bytes})
                except Exception as e:
                    self.logger.error(f"Could not read image file {img_path} for prompt: {e}")
                    prompt_parts.append(f"(Error loading image for {axis}-axis view)")

        
        self.logger.info("Sending request to Validator LLM for full validation and script hints...")
        self.logger.debug(f"Validator LLM Prompt (first 500 chars):\n{base_prompt[:500]}...")

        try:
            response = self.model.generate_content(
                contents=prompt_parts,
                generation_config=self.generation_config,
            )
            
            raw_text = response.text
            first_brace = raw_text.find('{')
            last_brace = raw_text.rfind('}')

            if first_brace != -1 and last_brace != -1 and last_brace > first_brace:
                json_string = raw_text[first_brace : last_brace + 1]
                try:
                    llm_feedback = json.loads(json_string)
                    self.logger.info("LLM full validation feedback and script hints received successfully.")
                    if not all(k in llm_feedback for k in ["overall_assessment", "identified_issues_detail", "script_modification_hints"]):
                        self.logger.warning("LLM feedback JSON is missing one or more expected keys.")
                        return {
                            "overall_assessment": llm_feedback.get("overall_assessment", "LLM assessment incomplete (missing keys)."),
                            "identified_issues_detail": llm_feedback.get("identified_issues_detail", ["LLM feedback structure error: missing 'identified_issues_detail'."]),
                            "script_modification_hints": llm_feedback.get("script_modification_hints", [])
                        }
                    return llm_feedback
                except json.JSONDecodeError as e_json:
                    self.logger.error(f"Failed to decode JSON from LLM response substring. Error: {e_json}. Substring: '{json_string[:200]}...'")
                    error_msg = f"LLM response could not be parsed as JSON: {e_json}"
            else:
                self.logger.error(f"Could not find valid JSON object delimiters '{{' and '}}' in LLM response. Raw text: {raw_text[:500]}...")
                error_msg = "LLM response did not contain a recognizable JSON object."

            return {
                "overall_assessment": "Error: Failed to get valid structured feedback from LLM.",
                "identified_issues_detail": [error_msg],
                "script_modification_hints": []
            }

        except Exception as e:
            self.logger.exception(f"An unexpected error occurred during LLM call for validation/hints: {e}")
            return {
                "overall_assessment": "Critical Error: LLM call for validation failed.",
                "identified_issues_detail": [f"Unexpected error during LLM communication: {e}"],
                "script_modification_hints": []
            }

    def validate_structure_and_script(self, structure_file_path: str, generating_script_content: str, 
                                      original_request: str, tool_documentation: str = None) -> dict:
        """
        Main validation method. Generates images and relies on LLM for all checks.
        Returns a dictionary with validation status, issues, and script modification hints.
        """
        self.logger.info(f"Starting LLM-based validation with structure file analysis for '{structure_file_path}'")
    
        final_feedback = {
            "status": "error", 
            "original_structure_file": structure_file_path,
            "overall_assessment": "Validation did not complete.",
            "all_identified_issues": [], 
            "script_modification_hints": []
        }

        # 1. Load structure and read file content for LLM
        atoms_obj, parsing_issues, structure_file_content = self._check_file_parsable_and_load(structure_file_path)
        if atoms_obj is None:
            final_feedback["overall_assessment"] = "Structure file is unparsable or invalid."
            final_feedback["all_identified_issues"] = parsing_issues
            self.logger.error(f"Validation aborted: Structure file unparsable. Issues: {parsing_issues}")
            return final_feedback

        # 2. Generate images for visual validation
        image_paths = generate_structure_views(structure_file_path)
        if not image_paths:
            self.logger.warning("Could not generate images for visual validation. Proceeding with text-only validation.")

        # 3. Get LLM-based validation with actual file content and images
        llm_feedback = self._get_llm_validation_and_hints(
            original_request=original_request,
            generating_script_content=generating_script_content,
            structure_file_path=structure_file_path,
            structure_file_content=structure_file_content, # Pass raw file content
            image_paths=image_paths, # Pass generated image paths
            tool_documentation=tool_documentation
        )

        final_feedback["overall_assessment"] = llm_feedback.get("overall_assessment", "LLM assessment missing or failed.")
        # Issues identified by LLM are now the sole source of issues
        final_feedback["all_identified_issues"] = llm_feedback.get("identified_issues_detail", [])
        final_feedback["script_modification_hints"] = llm_feedback.get("script_modification_hints", [])

        if not final_feedback["all_identified_issues"]:
            final_feedback["status"] = "success"
            self.logger.info(f"LLM validation successful for '{structure_file_path}'. No issues reported by LLM.")
        else:
            final_feedback["status"] = "needs_correction"
            self.logger.warning(f"LLM validation for '{structure_file_path}' found issues requiring script correction: {final_feedback['all_identified_issues']}")
            if not final_feedback["script_modification_hints"] and final_feedback["all_identified_issues"]: # Issues exist but no hints
                self.logger.warning("LLM identified issues but provided no script modification hints. Adding a generic hint.")
                final_feedback["script_modification_hints"].append(
                    "LLM identified issues but gave no specific script hints. Review the script against the identified issues."
                )
        
        self.logger.debug(f"Final LLM-only validation feedback for '{structure_file_path}': {final_feedback}")
        return final_feedback




class IncarValidatorAgent:
    """Agent that validates and suggests improvements to VASP INCAR files using literature."""

    def __init__(self, api_key: str = None, model_name: str = "gemini-2.5-pro-preview-05-06", 
                 futurehouse_api_key: str = None, max_wait_time: int = 500):
        if not api_key:
            api_key = os.environ.get("GOOGLE_API_KEY")
        if not api_key:
            raise ValueError("Google API key required")
        
        genai.configure(api_key=api_key)
        self.model = genai.GenerativeModel(model_name)
        self.generation_config = GenerationConfig(response_mime_type="application/json")
        self.logger = logging.getLogger(__name__)
        
        # Initialize literature agent
        self.literature_agent = IncarLiteratureAgent(
            api_key=futurehouse_api_key, 
            max_wait_time=max_wait_time
        )

    def validate_and_improve_incar(self, incar_content: str, system_description: str) -> dict:
        """Validate INCAR parameters and suggest improvements based on literature."""
        
        # Step 1: Get literature review
        self.logger.info("Getting literature review of INCAR parameters...")
        lit_result = self.literature_agent.validate_incar(incar_content, system_description)
        
        if lit_result["status"] != "success":
            return {
                "status": "error",
                "message": f"Literature review failed: {lit_result.get('message')}",
                "validation_status": "unknown"
            }
        
        # Step 2: Analyze literature review and suggest improvements
        self.logger.info("Analyzing literature review for potential improvements...")
        
        prompt = f"""{INCAR_VALIDATION_INSTRUCTIONS}

## ORIGINAL INCAR:
{incar_content}

## SYSTEM DESCRIPTION:
{system_description}

## LITERATURE REVIEW:
{lit_result['response']}

Analyze the literature review and suggest specific parameter adjustments if needed."""

        try:
            response = self.model.generate_content(prompt, generation_config=self.generation_config)
            result = json.loads(response.text)
            
            # Add literature review to result
            result.update({
                "status": "success",
                "literature_review": lit_result['response'],
                "literature_task_id": lit_result.get('task_id')
            })
            
            return result
            
        except Exception as e:
            self.logger.error(f"Error analyzing literature review: {e}")
            return {
                "status": "error", 
                "message": f"Analysis failed: {str(e)}",
                "literature_review": lit_result['response']
            }

    def save_validation_report(self, validation_result: dict, output_dir: str = ".") -> dict:
        """Save validation report and revised INCAR if needed."""
        if validation_result.get("status") != "success":
            return {"error": "Validation was not successful"}
        
        os.makedirs(output_dir, exist_ok=True)
        saved_files = {}
        
        try:
            # Save validation report
            report_path = os.path.join(output_dir, "incar_validation_report.json")
            with open(report_path, 'w') as f:
                json.dump(validation_result, f, indent=2, default=str)
            saved_files["validation_report"] = report_path
            
            # Save revised INCAR if adjustments were made
            if (validation_result.get("validation_status") == "needs_adjustment" and 
                validation_result.get("revised_incar")):
                
                revised_path = os.path.join(output_dir, "INCAR_revised")
                with open(revised_path, 'w') as f:
                    f.write(validation_result["revised_incar"])
                saved_files["revised_incar"] = revised_path
                
                # Also save adjustment summary
                summary_path = os.path.join(output_dir, "incar_adjustments.txt")
                with open(summary_path, 'w') as f:
                    f.write("INCAR Parameter Adjustments\n")
                    f.write("=" * 30 + "\n\n")
                    f.write(f"Overall Assessment: {validation_result.get('overall_assessment', 'N/A')}\n\n")
                    
                    adjustments = validation_result.get("suggested_adjustments", [])
                    if adjustments:
                        f.write("Suggested Changes:\n")
                        for adj in adjustments:
                            f.write(f"\n• {adj.get('parameter')}:\n")
                            f.write(f"  Current: {adj.get('current_value')}\n")
                            f.write(f"  Suggested: {adj.get('suggested_value')}\n")
                            f.write(f"  Reason: {adj.get('reason')}\n")
                    else:
                        f.write("No specific adjustments suggested.\n")
                        
                saved_files["adjustment_summary"] = summary_path
            
            self.logger.info(f"Validation report saved: {saved_files}")
            return saved_files
            
        except Exception as e:
            self.logger.error(f"Error saving validation files: {e}")
            return {"error": f"Save failed: {str(e)}"}



================================================
File: agents/sim_agents/vasp_agent.py
================================================
import os
import json
import logging
import google.generativeai as genai
from google.generativeai.types import GenerationConfig

from .instruct import VASP_INPUT_GENERATION_INSTRUCTIONS


class VaspInputAgent:
    """Agent for generating VASP INCAR and KPOINTS files."""

    def __init__(self, api_key: str, model_name: str = "gemini-2.5-pro-preview-05-06"):
        if not api_key:
            api_key = os.environ.get("GOOGLE_API_KEY")
        if not api_key:
            raise ValueError("API key required")
        
        genai.configure(api_key=api_key)
        self.model = genai.GenerativeModel(model_name)
        self.generation_config = GenerationConfig(response_mime_type="application/json")
        self.logger = logging.getLogger(__name__)

    def generate_vasp_inputs(self, poscar_path: str, original_request: str) -> dict:
        """Generate VASP INCAR and KPOINTS files."""
        
        # Read POSCAR
        try:
            with open(poscar_path, 'r') as f:
                poscar_content = f.read()
        except Exception as e:
            return {"status": "error", "message": f"Failed to read POSCAR: {e}"}

        # Build prompt
        prompt = VASP_INPUT_GENERATION_INSTRUCTIONS.format(
            poscar_content=poscar_content,
            original_request=original_request
        )

        # Get LLM response
        try:
            response = self.model.generate_content(prompt, generation_config=self.generation_config)
            result = json.loads(response.text)
            result["status"] = "success"
            return result
        except Exception as e:
            return {"status": "error", "message": f"Generation failed: {e}"}

    def save_inputs(self, result: dict, output_dir: str = ".") -> dict:
        """Save INCAR and KPOINTS files."""
        if result.get("status") != "success":
            return {"error": "Generation was not successful"}
        
        os.makedirs(output_dir, exist_ok=True)
        saved = {}
        
        try:
            # Save INCAR
            with open(os.path.join(output_dir, "INCAR"), 'w') as f:
                f.write(result["incar"])
            saved["incar"] = os.path.join(output_dir, "INCAR")
            
            # Save KPOINTS  
            with open(os.path.join(output_dir, "KPOINTS"), 'w') as f:
                f.write(result["kpoints"])
            saved["kpoints"] = os.path.join(output_dir, "KPOINTS")

            return saved
        
        except Exception as e:
            return {"error": f"Save failed: {e}"}
             
    def apply_improvements(self, original_incar: str, validation_result: dict, 
                          poscar_path: str, original_request: str, output_dir: str = ".") -> dict:
        """Regenerate INCAR using LLM with improvement instructions."""
        
        if validation_result.get("validation_status") != "needs_adjustment":
            return {
                "status": "no_changes", 
                "message": "No improvements needed - INCAR is already good"
            }
        
        adjustments = validation_result.get("suggested_adjustments", [])
        if not adjustments:
            return {"status": "error", "message": "No adjustments available"}
        
        # Read POSCAR content
        try:
            with open(poscar_path, 'r') as f:
                poscar_content = f.read()
        except Exception as e:
            return {"status": "error", "message": f"Failed to read POSCAR: {e}"}
        
        # Build improvement instructions
        improvement_instructions = "IMPROVEMENT INSTRUCTIONS:\n"
        improvement_instructions += "Please modify the provided INCAR file based on these literature-validated suggestions:\n\n"
        
        for adj in adjustments:
            improvement_instructions += f"• {adj.get('parameter')}: {adj.get('current_value')} → {adj.get('suggested_value')}\n"
            improvement_instructions += f"  Reason: {adj.get('reason')}\n\n"
        
        improvement_instructions += f"Literature assessment: {validation_result.get('overall_assessment', '')}\n\n"
        improvement_instructions += "Generate an improved INCAR file incorporating these changes."
        
        # Build the prompt with original INCAR and improvement instructions
        prompt = f"""{VASP_INPUT_GENERATION_INSTRUCTIONS}

## ORIGINAL INCAR TO IMPROVE:
{original_incar}

## {improvement_instructions}

## POSCAR STRUCTURE:
{poscar_content}

## ORIGINAL SYSTEM DESCRIPTION:
{original_request}

Please generate an improved INCAR file based on the improvement instructions above."""

        # Get improved INCAR from LLM
        try:
            response = self.model.generate_content(prompt, generation_config=self.generation_config)
            result = json.loads(response.text)
            
            if result.get("incar"):
                # Save improved INCAR
                os.makedirs(output_dir, exist_ok=True)
                improved_path = os.path.join(output_dir, "INCAR_improved")
                
                with open(improved_path, 'w') as f:
                    f.write(result["incar"])
                
                result.update({
                    "status": "success",
                    "improvements_applied": True,
                    "adjustments_count": len(adjustments),
                    "improved_incar_path": improved_path
                })
                
                self.logger.info(f"Generated improved INCAR with {len(adjustments)} literature-based improvements")
                return result
            else:
                return {"status": "error", "message": "No INCAR generated in LLM response"}
            
        except Exception as e:
            self.logger.error(f"Failed to generate improved INCAR: {e}")
            return {"status": "error", "message": f"Failed to generate improved INCAR: {e}"}




================================================
File: cli/__init__.py
================================================
"""SciLink CLI interface."""

from .workflows import main as experimental_novelty_main

__all__ = ['experimental_novelty_main']


================================================
File: cli/workflows.py
================================================
#!/usr/bin/env python3
"""
SciLink CLI - Extensible Command Pattern

Usage: scilink [WORKFLOW] [PATH/DESCRIPTION] [OPTIONS]

Examples:
    scilink novelty my_data/
    scilink novelty my_data/ --dft-recommendations
    scilink novelty image.tif --system-info metadata.json
    scilink dft "Generate graphene supercell with a single vacancy"
    scilink experiment2dft my_experiment/
    scilink experiment2dft my_experiment/ --non-interactive --auto-select 3
"""

import argparse
import sys
import os
import json
import numpy as np
from pathlib import Path
from typing import Dict, Any, Tuple, Optional

# Relative imports for scilink package
try:
    from ..workflows.experiment_novelty_workflow import ExperimentNoveltyAssessment
    from ..workflows.experiment2dft import Experimental2DFT
except ImportError:
    # Fallback for direct execution during development
    sys.path.append(str(Path(__file__).parent.parent))
    from workflows.experiment_novelty_workflow import ExperimentNoveltyAssessment
    from workflows.experiment2dft import Experimental2DFT


class Colors:
    """ANSI color codes for terminal output"""
    RED = '\033[0;31m'
    GREEN = '\033[0;32m'
    YELLOW = '\033[1;33m'
    BLUE = '\033[0;34m'
    PURPLE = '\033[0;35m'
    CYAN = '\033[0;36m'
    NC = '\033[0m'  # No Color


def print_info(msg: str):
    print(f"{Colors.BLUE}ℹ️  {msg}{Colors.NC}")


def print_success(msg: str):
    print(f"{Colors.GREEN}✅ {msg}{Colors.NC}")


def print_warning(msg: str):
    print(f"{Colors.YELLOW}⚠️  {msg}{Colors.NC}")


def print_error(msg: str):
    print(f"{Colors.RED}❌ {msg}{Colors.NC}", file=sys.stderr)


def print_header(msg: str):
    print(f"{Colors.PURPLE}{msg}{Colors.NC}")


def detect_data_type(file_path: str) -> str:
    """Auto-detect data type from file extension and numpy array dimensions"""
    file_path = Path(file_path)
    ext = file_path.suffix.lower()
    
    if ext in ['.jpg', '.jpeg', '.png', '.tif', '.tiff', '.bmp']:
        return 'microscopy'
    elif ext in ['.npy', '.npz']:
        # Check numpy array dimensions
        try:
            arr = np.load(file_path)
            if arr.ndim == 2:
                # 2D array -> likely microscopy image
                return 'microscopy'
            elif arr.ndim == 3:
                # 3D array -> likely hyperspectral data
                return 'spectroscopy'
            else:
                return 'unknown'
        except Exception:
            return 'unknown'
    elif ext in ['.txt', '.csv', '.dat']:
        return 'spectroscopy'
    else:
        return 'unknown'


def get_array_info(file_path: str) -> str:
    """Get shape and dimension info for numpy arrays"""
    try:
        arr = np.load(file_path)
        return f"Shape: {arr.shape}, Dimensions: {arr.ndim}D"
    except Exception:
        return "Could not read array info"


def discover_files(directory: Path) -> Tuple[Optional[str], Optional[str], Optional[str], Optional[str]]:
    """Auto-discover files in directory"""
    data_file = None
    metadata_file = None
    structure_file = None
    structure_info_file = None
    
    # Look for main data file
    data_extensions = ['.jpg', '.jpeg', '.png', '.tif', '.tiff', '.bmp', '.npy', '.npz', '.txt', '.csv', '.dat']
    
    # First try data.* files
    for ext in data_extensions:
        candidate = directory / f"data{ext}"
        if candidate.exists():
            data_file = str(candidate)
            break
    
    # If no data.* file, look for any data file
    if not data_file:
        for file_path in directory.iterdir():
            if file_path.is_file():
                basename = file_path.name.lower()
                ext = file_path.suffix.lower()
                if (ext in data_extensions and 
                    not basename.startswith('structure') and 
                    not basename.startswith('metadata')):
                    data_file = str(file_path)
                    break
    
    # Look for metadata - first try same basename as data file, then generic names
    if data_file:
        # Try same basename as data file
        data_path = Path(data_file)
        same_basename_json = data_path.with_suffix('.json')
        if same_basename_json.exists():
            metadata_file = str(same_basename_json)
    
    # If no same-basename metadata found, try generic names
    if not metadata_file:
        metadata_names = ['metadata.json', 'system_info.json', 'meta.json', 'info.json']
        for name in metadata_names:
            candidate = directory / name
            if candidate.exists():
                metadata_file = str(candidate)
                break
    
    # Look for structure files
    structure_extensions = ['.jpg', '.jpeg', '.png', '.tif', '.tiff', '.bmp']
    for ext in structure_extensions:
        candidate = directory / f"structure{ext}"
        if candidate.exists():
            structure_file = str(candidate)
            break
    
    # Look for structure info
    structure_info_candidates = ['structure_info.json', 'structure.json']
    for name in structure_info_candidates:
        candidate = directory / name
        if candidate.exists():
            structure_info_file = str(candidate)
            break
    
    return data_file, metadata_file, structure_file, structure_info_file


def validate_json_file(file_path: str) -> bool:
    """Validate that file exists and contains valid JSON"""
    if not os.path.exists(file_path):
        return False
    try:
        with open(file_path, 'r') as f:
            json.load(f)
        return True
    except json.JSONDecodeError:
        return False


def create_parser() -> argparse.ArgumentParser:
    """Create argument parser"""
    parser = argparse.ArgumentParser(
        description="SciLink - Intelligent Materials Research CLI",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Experimental novelty assessment
  scilink novelty my_data/
  scilink novelty image.tif --system-info metadata.json
  scilink novelty my_data/ --dft-recommendations
  
  # Complete experimental to DFT pipeline (INTERACTIVE BY DEFAULT)
  scilink experiment2dft my_data/                              # Interactive mode (default)
  scilink experiment2dft my_data/ --non-interactive            # Automated mode
  scilink experiment2dft image.tif --auto-select 3            # Still interactive, but sets auto-select for non-interactive
  scilink experiment2dft spectral_data.npy --non-interactive --auto-select 1
  
  # DFT structure generation
  scilink dft "Generate a graphene supercell with Stone-Wales defects"
  scilink dft "Create MoS2 monolayer with sulfur vacancies" --output-dir dft_results/

Commands:
  novelty                Experimental novelty assessment with literature search
  experiment2dft         Complete pipeline: experiment → novelty → DFT structures
  dft                    Generate DFT structures from text description

Directory Structure (for novelty/experiment2dft commands):
  experiment_data/
  ├── data.{jpg,tif,npy,txt,csv}     # Main experimental data
  ├── metadata.json                  # System information
  ├── structure.{jpg,tif,png}        # Optional: structure image
  └── structure_info.json            # Optional: structure metadata
        """
    )
    
    # Positional arguments
    parser.add_argument(
        'command',
        choices=['novelty', 'experiment2dft', 'dft'],
        help='Workflow to run'
    )
    parser.add_argument(
        'path',
        help='Path to experimental data file/directory (for novelty/experiment2dft) or text description (for dft)'
    )
    
    # Data type options
    parser.add_argument(
        '--microscopy',
        action='store_true',
        help='Force microscopy analysis'
    )
    parser.add_argument(
        '--spectroscopy', 
        action='store_true',
        help='Force spectroscopy analysis'
    )
    
    # Analysis configuration
    parser.add_argument(
        '--agent-id',
        type=int,
        choices=[0, 1, 2],
        help='Microscopy agent (0=General, 1=SAM, 2=Atomistic)'
    )
    parser.add_argument(
        '--model',
        default='gemini-2.5-pro-preview-06-05',
        help='Analysis model (default: %(default)s)'
    )
    parser.add_argument(
        '--no-spectral-unmixing',
        action='store_true',
        help='Disable spectral unmixing for spectroscopy'
    )
    
    # File specifications
    parser.add_argument(
        '--system-info',
        help='System information JSON file'
    )
    parser.add_argument(
        '--structure-image',
        help='Structure/morphology image'
    )
    parser.add_argument(
        '--structure-info',
        help='Structure metadata JSON'
    )
    
    # Output options
    parser.add_argument(
        '--output-dir',
        default='novelty_output',
        help='Output directory (default: input_dir/results when using directory input, otherwise %(default)s)'
    )
    parser.add_argument(
        '--dft-recommendations',
        action='store_true',
        help='Generate DFT structure recommendations (for novelty command)'
    )
    
    # Structure generation options (for experiment2dft)
    parser.add_argument(
        '--interactive',
        action='store_true',
        help='Enable interactive structure selection (DEFAULT for experiment2dft)'
    )
    parser.add_argument(
        '--auto-select',
        type=int,
        default=2,
        help='Number of top recommendations to auto-select in non-interactive mode (default: %(default)s)'
    )
    parser.add_argument(
        '--max-structures',
        type=int,
        default=5,
        help='Maximum number of structures to consider (default: %(default)s)'
    )
    parser.add_argument(
        '--max-refinement-cycles',
        type=int,
        default=2,
        help='Maximum structure refinement cycles (default: %(default)s)'
    )
    parser.add_argument(
        '--script-timeout',
        type=int,
        default=300,
        help='Script execution timeout in seconds (default: %(default)s)'
    )
    
    # General options
    parser.add_argument(
        '--non-interactive',
        action='store_true',
        help='Skip interactive modes (claim selection, structure selection)'
    )
    parser.add_argument(
        '--wait-time',
        type=int,
        default=400,
        help='Max literature search wait time in seconds (default: %(default)s)'
    )
    
    # Verbosity
    parser.add_argument(
        '--verbose',
        action='store_true',
        help='Detailed logging'
    )
    parser.add_argument(
        '--quiet',
        action='store_true',
        help='Minimal output'
    )
    
    return parser


def run_novelty_workflow(args, data_file: str, metadata_file: str, structure_file: str, structure_info_file: str, data_type: str):
    """Run experimental novelty assessment workflow"""
    
    if not args.quiet:
        print_header("🔬 Experimental Novelty Assessment")
        print("-" * 40)
    
    # Load system info
    system_info = None
    if metadata_file:
        try:
            with open(metadata_file, 'r') as f:
                system_info = json.load(f)
        except Exception as e:
            if not args.quiet:
                print_warning(f"Could not load system info: {e}")
    
    # Load structure info
    structure_system_info = None
    if structure_info_file:
        try:
            with open(structure_info_file, 'r') as f:
                structure_system_info = json.load(f)
        except Exception as e:
            if not args.quiet:
                print_warning(f"Could not load structure info: {e}")
    
    # Create workflow kwargs
    workflow_kwargs = {
        'data_type': data_type,
        'analysis_model': args.model,
        'output_dir': args.output_dir,
        'max_wait_time': args.wait_time,
        'dft_recommendations': args.dft_recommendations
    }
    
    # Add data-type specific parameters
    if data_type == 'microscopy' and args.agent_id is not None:
        workflow_kwargs['agent_id'] = args.agent_id
    elif data_type == 'spectroscopy':
        workflow_kwargs['spectral_unmixing_enabled'] = not args.no_spectral_unmixing
    
    # Create workflow
    workflow = ExperimentNoveltyAssessment(**workflow_kwargs)
    
    # Prepare analysis kwargs
    analysis_kwargs = {}
    if data_type == 'spectroscopy':
        if structure_file:
            analysis_kwargs['structure_image_path'] = structure_file
        if structure_system_info:
            analysis_kwargs['structure_system_info'] = structure_system_info
    
    # Run workflow (it prints its own comprehensive output)
    result = workflow.run_complete_workflow(
        data_path=data_file,
        system_info=system_info,
        **analysis_kwargs
    )
    
    return result


def run_experiment2dft_workflow(args, data_file: str, metadata_file: str, structure_file: str, structure_info_file: str, data_type: str):
    """Run complete experimental to DFT pipeline"""
    
    if not args.quiet:
        print_header("🧬 Complete Experimental → DFT Pipeline")
        print("-" * 45)
    
    # Load system info
    system_info = None
    if metadata_file:
        try:
            with open(metadata_file, 'r') as f:
                system_info = json.load(f)
        except Exception as e:
            if not args.quiet:
                print_warning(f"Could not load system info: {e}")
    
    # Load structure info
    structure_system_info = None
    if structure_info_file:
        try:
            with open(structure_info_file, 'r') as f:
                structure_system_info = json.load(f)
        except Exception as e:
            if not args.quiet:
                print_warning(f"Could not load structure info: {e}")
    
    # Create workflow kwargs
    workflow_kwargs = {
        'analysis_model': args.model,
        'generator_model': args.model,
        'validator_model': args.model,
        'output_dir': args.output_dir,
        'max_wait_time': args.wait_time,
        'max_refinement_cycles': args.max_refinement_cycles,
        'script_timeout': args.script_timeout,
        'spectroscopy_analysis_enabled': not args.no_spectral_unmixing
    }
    
    # Add data-type specific parameters
    if data_type == 'microscopy' and args.agent_id is not None:
        workflow_kwargs['agent_id'] = args.agent_id
    
    # Create workflow
    workflow = Experimental2DFT(**workflow_kwargs)
    
    # Determine interaction mode (interactive is default unless --non-interactive is specified)
    interactive = not args.non_interactive
    
    # Run the appropriate pipeline method based on data type
    if data_type == 'microscopy':
        result = workflow.run_microscopy_pipeline(
            image_path=data_file,
            system_info=system_info,
            interactive=interactive,
            auto_select_top_n=args.auto_select,
            max_structures=args.max_structures
        )
    elif data_type == 'spectroscopy':
        result = workflow.run_spectroscopy_pipeline(
            data_path=data_file,
            system_info=system_info,
            interactive=interactive,
            auto_select_top_n=args.auto_select,
            max_structures=args.max_structures,
            structure_image_path=structure_file,
            structure_system_info=structure_system_info
        )
    else:
        # Fallback to generic pipeline
        result = workflow.run_complete_pipeline(
            data_path=data_file,
            data_type=data_type,
            system_info=system_info,
            interactive=interactive,
            auto_select_top_n=args.auto_select,
            max_structures=args.max_structures
        )
    
    return result


def run_dft_workflow(args, user_request: str):
    """Run DFT structure generation workflow"""
    
    if not args.quiet:
        print_header("⚛️  DFT Structure Generation")
        print("-" * 30)
        print_info(f"Request: {user_request}")
        print()
    
    try:
        from ..workflows.dft_workflow import DFTWorkflow
    except ImportError:
        try:
            from workflows.dft_workflow import DFTWorkflow
        except ImportError:
            print_error("DFT workflow not available. Make sure dft_workflow.py exists.")
            return {"final_status": "error", "message": "DFT workflow not found"}
    
    # Create DFT workflow
    workflow = DFTWorkflow(
        generator_model=args.model,
        validator_model=args.model,
        output_dir=args.output_dir,
        max_refinement_cycles=getattr(args, 'max_refinement_cycles', 2),
        script_timeout=getattr(args, 'script_timeout', 300)
    )
    
    # Run complete workflow
    result = workflow.run_complete_workflow(user_request)
    
    return result


def main():
    """Main CLI entry point"""
    parser = create_parser()
    args = parser.parse_args()
    
    # Print header
    if not args.quiet:
        print_header("🧬 SciLink - Intelligent Materials Research")
        print_header("=========================================")
    
    # Handle data type conflicts (only relevant for data-based commands)
    if args.command in ['novelty', 'experiment2dft'] and args.microscopy and args.spectroscopy:
        print_error("Cannot specify both --microscopy and --spectroscopy")
        sys.exit(1)
    
    # Determine data type from flags (only for data-based commands)
    forced_data_type = None
    if args.command in ['novelty', 'experiment2dft']:
        if args.microscopy:
            forced_data_type = 'microscopy'
        elif args.spectroscopy:
            forced_data_type = 'spectroscopy'
    
    # Handle DFT workflow (doesn't need file discovery)
    if args.command == 'dft':
        try:
            result = run_dft_workflow(args, args.path)
            final_status = result.get('final_status', 'unknown')
            if final_status == 'success':
                if not args.quiet:
                    print("\n🎉 DFT workflow completed successfully!")
                sys.exit(0)
            else:
                if not args.quiet:
                    print(f"\n⚠️  DFT workflow completed with status: {final_status}")
                sys.exit(1)
        except Exception as e:
            print_error(f"Error: {e}")
            if args.verbose:
                import traceback
                traceback.print_exc()
            sys.exit(1)
    
    # Validate path exists (for data-based workflows)
    input_path = Path(args.path)
    if not input_path.exists():
        print_error(f"Path does not exist: {input_path}")
        sys.exit(1)
    
    # Handle directory vs file input
    if input_path.is_dir():
        if not args.quiet:
            print_info(f"Auto-discovering files in directory: {input_path}")
        
        data_file, metadata_file, structure_file, structure_info_file = discover_files(input_path)
        
        # Override with explicitly provided files
        if args.system_info:
            metadata_file = args.system_info
        if args.structure_image:
            structure_file = args.structure_image
        if args.structure_info:
            structure_info_file = args.structure_info
        
        # Validate discovery
        if not data_file:
            print_error("No experimental data file found")
            print_info("Expected files: data.{jpg,tif,npy,txt,csv} or similar")
            sys.exit(1)
        
        if not args.quiet:
            print_success(f"Found data file: {Path(data_file).name}")
            if metadata_file:
                print_success(f"Found metadata: {Path(metadata_file).name}")
            if structure_file:
                print_success(f"Found structure image: {Path(structure_file).name}")
            if structure_info_file:
                print_success(f"Found structure info: {Path(structure_info_file).name}")
    
    elif input_path.is_file():
        data_file = str(input_path)
        metadata_file = args.system_info
        structure_file = args.structure_image
        structure_info_file = args.structure_info
        
        if not args.quiet:
            print_info(f"Using data file: {input_path.name}")
        
        if not metadata_file and not args.quiet:
            print_warning("No metadata file specified. Use --system-info for better analysis.")
    
    else:
        print_error(f"Input path is neither a file nor directory: {input_path}")
        sys.exit(1)
    
    # Validate files exist
    if not os.path.exists(data_file):
        print_error(f"Data file not found: {data_file}")
        sys.exit(1)
    
    if metadata_file and not validate_json_file(metadata_file):
        print_error(f"Invalid or missing metadata file: {metadata_file}")
        sys.exit(1)
    
    if structure_info_file and not validate_json_file(structure_info_file):
        print_error(f"Invalid structure info file: {structure_info_file}")
        sys.exit(1)
    
    # Auto-detect data type if not forced
    if forced_data_type:
        data_type = forced_data_type
        if not args.quiet:
            print_info(f"Using forced data type: {data_type}")
    else:
        if not args.quiet:
            print_info("Auto-detecting data type...")
        data_type = detect_data_type(data_file)
        
        if data_type == 'unknown':
            print_error("Cannot determine data type from file. Use --microscopy or --spectroscopy")
            sys.exit(1)
        
        # Show detection reasoning for numpy arrays
        if not args.quiet:
            if data_file.endswith(('.npy', '.npz')):
                array_info = get_array_info(data_file)
                print_info(f"Detected {data_type} from numpy array ({array_info})")
            else:
                print_info(f"Auto-detected data type: {data_type}")
    
    # Determine output directory
    if input_path.is_dir() and args.output_dir == 'novelty_output':
        # Use the input directory for output when default output dir is used
        output_dir = str(input_path / 'results')
        if not args.quiet:
            print_info(f"Using input directory for output: {output_dir}")
    else:
        # Use specified output dir or environment variable
        output_dir = os.environ.get('SCILINK_OUTPUT_DIR', args.output_dir)
    
    args.output_dir = output_dir
    
    # Create output directory
    os.makedirs(output_dir, exist_ok=True)
    
    # Print configuration
    if not args.quiet:
        print_info("Configuration:")
        print(f"  Command: {args.command}")
        print(f"  Data Type: {data_type}")
        print(f"  Data Path: {data_file}")
        if metadata_file:
            print(f"  Metadata: {metadata_file}")
        if structure_file:
            print(f"  Structure Image: {structure_file}")
        if structure_info_file:
            print(f"  Structure Info: {structure_info_file}")
        print(f"  Output Dir: {output_dir}")
        if args.agent_id is not None:
            print(f"  Agent ID: {args.agent_id}")
        if args.command == 'novelty' and args.dft_recommendations:
            print(f"  DFT Recommendations: Enabled")
        if args.command == 'experiment2dft':
            print(f"  Interactive Mode: {not args.non_interactive} (default)")
            print(f"  Auto-select: {args.auto_select}")
            print(f"  Max Structures: {args.max_structures}")
        print("-" * 50)
        print()  # Extra space before workflow starts
    
    try:
        # Route to appropriate workflow
        if args.command == 'novelty':
            result = run_novelty_workflow(args, data_file, metadata_file, structure_file, structure_info_file, data_type)
        elif args.command == 'experiment2dft':
            result = run_experiment2dft_workflow(args, data_file, metadata_file, structure_file, structure_info_file, data_type)
        else:
            print_error(f"Unknown command: {args.command}")
            sys.exit(1)
        
        # Handle results
        final_status = result.get('final_status', 'unknown')
        if final_status == 'success':
            if not args.quiet:
                print("\n🎉 Workflow completed successfully!")
                
                # Show additional success info for experiment2dft
                if args.command == 'experiment2dft':
                    structures = result.get('generated_structures', [])
                    successful = [s for s in structures if s.get('success', False)]
                    if successful:
                        print_success(f"Generated {len(successful)} atomic structure(s)")
                        print_info("Ready-to-use VASP input files created:")
                        for i, struct in enumerate(successful, 1):
                            structure_name = struct.get('structure_name', f'structure_{i:02d}')
                            print(f"  • {structure_name}/: POSCAR, INCAR, KPOINTS")
            sys.exit(0)
        else:
            if not args.quiet:
                print(f"\n⚠️  Workflow completed with status: {final_status}")
            sys.exit(1)
    
    except KeyboardInterrupt:
        print("\n⚠️  Analysis interrupted by user")
        sys.exit(130)
    except Exception as e:
        print_error(f"Error: {e}")
        if args.verbose:
            import traceback
            traceback.print_exc()
        sys.exit(1)


if __name__ == '__main__':
    main()



================================================
File: workflows/__init__.py
================================================
from .experiment_novelty_workflow import ExperimentNoveltyAssessment
from .dft_recommendation_workflow import DFTRecommendationsWorkflow
from .dft_workflow import DFTWorkflow
from .experiment2dft import Experimental2DFT
from .analyzers import (
    BaseExperimentAnalyzer,
    MicroscopyAnalyzer,
    SpectroscopyAnalyzer
)

__all__ = [
    "DFTRecommendationsWorkflow",
    "DFTWorkflow",
    "Experimental2DFT",
    "ExperimentNoveltyAssessment",
    "BaseExperimentAnalyzer",
    "MicroscopyAnalyzer", 
    "SpectroscopyAnalyzer",
]


================================================
File: workflows/analyzers.py
================================================
import logging
from typing import Dict, Any, Optional
from abc import ABC, abstractmethod

from ..agents.exp_agents.orchestrator_agent import OrchestratorAgent, AGENT_MAP
from ..agents.exp_agents.spectroscopy_agent import SpectroscopyAnalysisAgent


class BaseExperimentAnalyzer(ABC):
    """Abstract base class for different experimental data analyzers."""
    
    @abstractmethod
    def analyze_for_claims(self, data_path: str, system_info: Dict[str, Any] = None, **kwargs) -> Dict[str, Any]:
        """Analyze experimental data and generate scientific claims."""
        pass
    
    @abstractmethod
    def get_data_type_name(self) -> str:
        """Return the name of the data type for logging/display purposes."""
        pass


class MicroscopyAnalyzer(BaseExperimentAnalyzer):
    """Analyzer for microscopy data."""
    
    def __init__(self, agent_id: Optional[int] = None, google_api_key: str = None, 
                 analysis_model: str = "gemini-2.5-pro-preview-06-05", output_dir: str = "",
                 local_model: str = None,
                 enable_human_feedback: bool = False):
        self.agent_id = agent_id
        self.google_api_key = google_api_key
        self.analysis_model = analysis_model
        self.local_model = local_model
        self.output_dir = output_dir
        self.enable_human_feedback = enable_human_feedback
        self.analysis_agent = None
    
    def analyze_for_claims(self, data_path: str, system_info: Dict[str, Any] = None, **kwargs) -> Dict[str, Any]:
        """Analyze microscopy image and generate scientific claims."""
        
        # Agent selection logic (from microscopy workflow)
        if self.agent_id is not None:
            if self.agent_id not in AGENT_MAP:
                raise ValueError(f"Invalid agent_id: {self.agent_id}. Available agents are: {list(AGENT_MAP.keys())}")
            selected_agent_id = self.agent_id
            logging.info(f"Using manually selected agent: {AGENT_MAP[selected_agent_id].__name__}")
        else:
            logging.info("Using orchestrator to select the best analysis agent...")
            orchestrator = OrchestratorAgent(google_api_key=self.google_api_key, local_model = self.local_model)
            selected_agent_id, reasoning = orchestrator.select_agent(
                data_type="microscopy",
                system_info=system_info,
                image_path=data_path
            )
            
            if selected_agent_id == -1:
                return {"error": f"Agent selection failed. Reason: {reasoning}"}

        # Instantiate and run analysis agent
        AnalysisAgentClass = AGENT_MAP[selected_agent_id]
        logging.info(f"✅ Running analysis with: {AnalysisAgentClass.__name__}")
        
        agent_kwargs = {'model_name': self.analysis_model, 
                        'local_model': self.local_model,
                        'enable_human_feedback': self.enable_human_feedback
        }
        if selected_agent_id == 0:  # MicroscopyAnalysisAgent
            agent_kwargs['fft_nmf_settings'] = {
                'FFT_NMF_ENABLED': True,
                'FFT_NMF_AUTO_PARAMS': True,
                'components': 3,
                'output_dir': self.output_dir
            }
        
        self.analysis_agent = AnalysisAgentClass(**agent_kwargs)
        
        return self.analysis_agent.analyze_microscopy_image_for_claims(data_path, system_info=system_info)
    
    def get_data_type_name(self) -> str:
        return "microscopy"


class SpectroscopyAnalyzer(BaseExperimentAnalyzer):
    """Analyzer for spectroscopy data."""
    
    def __init__(self, google_api_key: str = None, analysis_model: str = "gemini-2.5-pro-preview-06-05", 
                 local_model: str = None,
                 output_dir: str = "", spectral_unmixing_enabled: bool = True,
                 enable_human_feedback: bool = False):
        self.google_api_key = google_api_key
        self.analysis_model = analysis_model
        self.local_model = local_model,
        self.output_dir = output_dir
        
        # Fixed spectral unmixing settings
        spectral_settings = {
            'method': 'nmf',
            'n_components': 4,
            'normalize': True,
            'enabled': spectral_unmixing_enabled,
            'auto_components': True,
            'max_iter': 500
        }
        
        self.analysis_agent = SpectroscopyAnalysisAgent(
            api_key=google_api_key,
            model_name=analysis_model,
            local_model=local_model,
            spectral_unmixing_settings=spectral_settings,
            output_dir=output_dir,
            enable_human_feedback=enable_human_feedback
        )
    
    def analyze_for_claims(self, data_path: str, system_info: Dict[str, Any] = None, **kwargs) -> Dict[str, Any]:
        """Analyze spectroscopy data and generate scientific claims."""
        structure_image_path = kwargs.get('structure_image_path')
        structure_system_info = kwargs.get('structure_system_info')
        
        return self.analysis_agent.analyze_hyperspectral_data_for_claims(
            data_path,
            metadata_path=system_info,
            structure_image_path=structure_image_path,
            structure_system_info=structure_system_info
        )
    
    def get_data_type_name(self) -> str:
        return "spectroscopy"



================================================
File: workflows/dft_recommendation_workflow.py
================================================
import os
import json
import logging
from typing import Dict, Any, List, Optional

# Updated imports for new package structure
from ..auth import get_api_key, APIKeyNotFoundError
from ..agents.exp_agents.microscopy_agent import MicroscopyAnalysisAgent


class DFTRecommendationsWorkflow:
    """
    Standalone workflow for generating DFT recommendations.
    """
    
    def __init__(self, 
                 google_api_key: str = None,
                 analysis_model: str = "gemini-2.5-pro-preview-06-05",
                 output_dir: str = "dft_output"):
        
        # Auto-discover API key
        if google_api_key is None:
            google_api_key = get_api_key('google')
            if not google_api_key:
                raise APIKeyNotFoundError('google')
        
        self.logger = logging.getLogger(__name__)
        self.output_dir = output_dir
        os.makedirs(output_dir, exist_ok=True)
        
        # Initialize agent for text-only DFT recommendations
        # No FFT/NMF settings needed for text-only analysis
        self.agent = MicroscopyAnalysisAgent(
            google_api_key=google_api_key,
            model_name=analysis_model
        )
    
    def run_from_files(self, analysis_file: str, novelty_file: str) -> Dict[str, Any]:
        """Generate DFT recommendations from saved files."""
        
        # Load files
        with open(analysis_file, 'r') as f:
            analysis_data = json.load(f)
        with open(novelty_file, 'r') as f:
            novelty_data = json.load(f)
        
        # Extract data
        analysis_text = analysis_data.get("full_analysis", "")
        novel_claims = novelty_data.get("potentially_novel", [])
        
        return self.run_from_data(analysis_text, novel_claims)
    
    def run_from_data(self, analysis_text: str, novel_claims: List[str], 
                     system_info: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """Generate DFT recommendations from provided data."""
        
        # Create novelty context
        if novel_claims:
            context = "Focus on these potentially novel findings:\n"
            for i, claim in enumerate(novel_claims, 1):
                context += f"{i}. {claim}\n"
            context += "\nPrioritize DFT structures that can investigate these novel aspects."
        else:
            context = "No specific novel claims identified. Focus on most interesting aspects."
        
        # Generate recommendations
        result = self.agent.analyze_microscopy_image_for_structure_recommendations(
            image_path=None,  # Text-only mode
            system_info=system_info,  # Pass as parameter instead of config
            additional_prompt_context=context,
            cached_detailed_analysis=analysis_text
        )
        
        if "error" in result:
            return {"status": "error", "message": result.get("error")}
        
        # Save results
        output = {
            "reasoning": result.get("analysis_summary_or_reasoning", ""),
            "recommendations": result.get("recommendations", []),
            "novel_claims": novel_claims
        }
        
        # Display results
        self._display_results(output["reasoning"], output["recommendations"], novel_claims)
        
        # Save results
        output_file = os.path.join(self.output_dir, "dft_recommendations.json")
        with open(output_file, 'w') as f:
            json.dump(output, f, indent=2)
        
        self.logger.info(f"Generated {len(output['recommendations'])} DFT recommendations")
        return {"status": "success", "output_file": output_file, **output}
    
    def _display_results(self, reasoning: str, recommendations: List[Dict], novel_claims: List[str]):
        """Display the generated DFT recommendations."""
        
        print("\n" + "="*60)
        print("DFT STRUCTURE RECOMMENDATIONS")
        print("="*60)
        
        print(f"\nNovel claims processed: {len(novel_claims)}")
        print(f"Total recommendations: {len(recommendations)}")
        
        print(f"\n--- Reasoning ---")
        print(reasoning)
        print("-" * 40)
        
        if recommendations:
            print("\n--- Recommended Structures ---")
            for i, rec in enumerate(recommendations, 1):
                print(f"\n[{i}] Priority: {rec.get('priority', 'N/A')}")
                print(f"    {rec.get('description', 'N/A')}")
                print(f"    Justification: {rec.get('scientific_interest', 'N/A')}")
        else:
            print("\n⚠️  No recommendations generated")
        
        print("\n" + "="*60)


================================================
File: workflows/dft_workflow.py
================================================
import os
import sys
import logging
from io import StringIO
import json
from typing import Optional, Dict, Any

from ..auth import get_api_key, APIKeyNotFoundError
from ..agents.sim_agents.structure_agent import StructureGenerator
from ..agents.sim_agents.val_agent import StructureValidatorAgent, IncarValidatorAgent
from ..agents.sim_agents.vasp_agent import VaspInputAgent


class DFTWorkflow:
    """
    Complete DFT workflow: User request → Structure → Validation → VASP inputs
    """
    
    def __init__(self, 
                 google_api_key: str = None,
                 futurehouse_api_key: str = None,
                 mp_api_key: str = None,
                 generator_model: str = "gemini-2.5-pro-preview-06-05",
                 validator_model: str = "gemini-2.5-pro-preview-06-05",
                 output_dir: str = "dft_workflow_output",
                 max_refinement_cycles: int = 4,
                 script_timeout: int = 180):
        
        # Auto-discover API keys
        if google_api_key is None:
            google_api_key = get_api_key('google')
            if not google_api_key:
                raise APIKeyNotFoundError('google')
        
        if futurehouse_api_key is None:
            futurehouse_api_key = get_api_key('futurehouse')
            # Optional for DFT workflow
        
        if mp_api_key is None:
            mp_api_key = get_api_key('materials_project')
            # Optional - will warn in agents if needed
        
        # Setup logging with better formatting
        self.log_capture = StringIO()
        logging.basicConfig(
            level=logging.INFO, 
            format='%(asctime)s - %(levelname)s: %(name)s: %(message)s', 
            force=True, 
            handlers=[
                logging.StreamHandler(sys.stdout),
                logging.StreamHandler(self.log_capture)
            ]
        )
        self.logger = logging.getLogger(__name__)

        self.google_api_key = google_api_key
        self.futurehouse_api_key = futurehouse_api_key
        self.output_dir = output_dir
        self.max_refinement_cycles = max_refinement_cycles
        
        # Initialize agents with simplified parameters
        self.structure_generator = StructureGenerator(
            api_key=google_api_key,
            model_name=generator_model,
            executor_timeout=script_timeout,
            generated_script_dir=output_dir,
            mp_api_key=mp_api_key
        )
        
        self.structure_validator = StructureValidatorAgent(
            api_key=google_api_key,
            model_name=validator_model
        )
        
        self.vasp_agent = VaspInputAgent(
            api_key=google_api_key,
            model_name=generator_model
        )
        
        if futurehouse_api_key:
            self.incar_validator = IncarValidatorAgent(
                api_key=google_api_key,
                futurehouse_api_key=futurehouse_api_key
            )
        else:
            self.incar_validator = None
            print("ℹ️  Literature validation disabled (no FutureHouse API key)")
            
        # Create output directory
        os.makedirs(output_dir, exist_ok=True)
        
    def run_complete_workflow(self, user_request: str) -> Dict[str, Any]:
        """
        Run the complete workflow from user request to final VASP inputs.
        """
        workflow_result = {
            "user_request": user_request,
            "steps_completed": [],
            "final_status": "started"
        }
        
        print(f"\n🚀 DFT Workflow Starting")
        print(f"{'='*60}")
        print(f"📝 Request: {user_request}")
        print(f"📁 Output:  {self.output_dir}/")
        print(f"{'='*60}")
        
        # Step 1: Structure Generation and Validation
        print(f"\n🏗️  WORKFLOW STEP 1: Structure Generation & Validation")
        print(f"{'─'*50}")
        
        structure_result = self._generate_and_validate_structure(user_request)
        workflow_result["structure_generation"] = structure_result
        
        if structure_result["status"] != "success":
            print(f"❌ Structure generation failed: {structure_result.get('message', 'Unknown error')}")
            workflow_result["final_status"] = "failed_structure_generation"
            return workflow_result
        
        workflow_result["steps_completed"].append("structure_generation")
        structure_path = structure_result["final_structure_path"]
        
        print(f"✅ Structure generated: {os.path.basename(structure_path)}")
        if structure_result.get("warning"):
            print(f"⚠️  {structure_result['warning']}")
        
        # Step 2: VASP Input Generation
        print(f"\n⚛️  WORKFLOW STEP 2: VASP Input Generation")
        print(f"{'─'*50}")
        
        vasp_result = self._generate_vasp_inputs(structure_path, user_request)
        workflow_result["vasp_generation"] = vasp_result
        
        if vasp_result["status"] != "success":
            print(f"❌ VASP generation failed: {vasp_result.get('message', 'Unknown error')}")
            workflow_result["final_status"] = "failed_vasp_generation"
            return workflow_result
            
        workflow_result["steps_completed"].append("vasp_generation")
        print(f"✅ VASP inputs generated: INCAR, KPOINTS")
        print(f"📋 Calculation type: {vasp_result.get('summary', 'N/A')}")
        
        # Step 3: Literature Validation and Improvements (optional)
        if self.incar_validator:
            print(f"\n📚  WORKFLOW STEP 3: Literature Validation")
            print(f"{'─'*50}")
            
            improvement_result = self._validate_and_improve_incar(
                vasp_result, structure_path, user_request
            )
            workflow_result["incar_improvement"] = improvement_result
            workflow_result["steps_completed"].append("incar_improvement")
        else:
            workflow_result["incar_improvement"] = {"status": "skipped", "message": "No FutureHouse API key"}
        
        workflow_result["final_status"] = "success"
        workflow_result["output_directory"] = self.output_dir
        
        # Create final files manifest
        final_manifest = self._create_final_files_manifest(workflow_result)
        workflow_result["final_manifest"] = final_manifest
        
        # Save complete log
        self._save_workflow_log()
        
        # Final summary
        self._print_final_summary(workflow_result)
        
        return workflow_result
    
    def _generate_and_validate_structure(self, user_request: str) -> Dict[str, Any]:
        """Generate and validate atomic structure with improved output formatting."""
        
        previous_script_content = None
        validator_feedback = None
        
        for cycle in range(self.max_refinement_cycles + 1):
            cycle_num = cycle + 1
            total_cycles = self.max_refinement_cycles + 1
            
            if cycle == 0:
                print(f"🔨 Generating structure (attempt {cycle_num}/{total_cycles})")
            else:
                print(f"🔄 Refining structure (attempt {cycle_num}/{total_cycles})")
                print(f"   Addressing: {len(validator_feedback.get('all_identified_issues', []))} validation issues")
            
            # Generate structure
            gen_result = self.structure_generator.generate_script(
                original_user_request=user_request + ". Save the structure in POSCAR format.",
                attempt_number_overall=cycle_num,
                is_refinement_from_validation=(cycle > 0),
                previous_script_content=previous_script_content if cycle > 0 else None,
                validator_feedback=validator_feedback if cycle > 0 else None
            )
            
            if gen_result["status"] != "success":
                return {
                    "status": "error",
                    "message": f"Structure generation failed on cycle {cycle_num}: {gen_result.get('message')}",
                    "cycle": cycle_num
                }
            
            structure_file = gen_result["output_file"]
            script_content = gen_result["final_script_content"]
            previous_script_content = script_content
            
            print(f"   ✅ Structure file: {os.path.basename(structure_file)}")
            print(f"   🐍 Script: {os.path.basename(gen_result['final_script_path'])}")
            
            # Validate structure
            print(f"🔍 Validating structure...")
            val_result = self.structure_validator.validate_structure_and_script(
                structure_file_path=structure_file,
                generating_script_content=script_content,
                original_request=user_request
            )
            
            validator_feedback = val_result
            
            # Format validation results nicely
            self._print_validation_results(val_result, cycle_num)
            
            if val_result["status"] == "success":
                return {
                    "status": "success",
                    "final_structure_path": structure_file,
                    "final_script_path": gen_result["final_script_path"],
                    "cycles_used": cycle_num,
                    "validation_result": val_result
                }
            elif cycle < self.max_refinement_cycles:
                print(f"🔄 Issues found, attempting refinement...")
                continue
            else:
                print(f"⚠️  Max refinement cycles reached, proceeding with current structure")
                return {
                    "status": "success",
                    "final_structure_path": structure_file,
                    "final_script_path": gen_result["final_script_path"], 
                    "cycles_used": cycle_num,
                    "validation_result": val_result,
                    "warning": "Structure may have validation issues"
                }
        
        return {"status": "error", "message": "Structure generation loop failed"}
    
    def _print_validation_results(self, val_result: Dict[str, Any], cycle_num: int):
        """Print validation results in a user-friendly format."""
        
        if val_result["status"] == "success":
            print(f"   ✅ Validation passed")
            return
        
        # Format issues nicely
        issues = val_result.get("all_identified_issues", [])
        hints = val_result.get("script_modification_hints", [])
        assessment = val_result.get("overall_assessment", "No assessment provided")
        
        print(f"   ⚠️  Validation found {len(issues)} issue(s):")
        print(f"\n   📋 Overall Assessment:")
        print(f"      {assessment}")
        
        if issues:
            print(f"\n   🔍 Specific Issues:")
            for i, issue in enumerate(issues, 1):
                print(f"      {i}. {issue}")
        
        if hints:
            print(f"\n   💡 Suggested Improvements:")
            for i, hint in enumerate(hints, 1):
                print(f"      {i}. {hint}")
        
        print()  # Add spacing
    
    def _generate_vasp_inputs(self, structure_path: str, user_request: str) -> Dict[str, Any]:
        """Generate VASP INCAR and KPOINTS files."""
        
        print(f"📝 Generating VASP input files...")
        
        # Generate initial VASP inputs
        vasp_result = self.vasp_agent.generate_vasp_inputs(
            poscar_path=structure_path,
            original_request=user_request
        )
        
        if vasp_result["status"] != "success":
            return vasp_result
        
        # Save initial VASP files
        saved_files = self.vasp_agent.save_inputs(vasp_result, self.output_dir)
        vasp_result["saved_files"] = saved_files
        
        return vasp_result
    
    def _validate_and_improve_incar(self, vasp_result: Dict[str, Any], 
                                   structure_path: str, user_request: str) -> Dict[str, Any]:
        """Validate INCAR against literature and apply improvements."""
        
        print(f"📖 Validating INCAR parameters against literature...")
        
        # Validate against literature
        validation_result = self.incar_validator.validate_and_improve_incar(
            incar_content=vasp_result["incar"],
            system_description=user_request
        )
        
        if validation_result["status"] != "success":
            print(f"❌ Literature validation failed: {validation_result.get('message')}")
            return validation_result
        
        # Check if improvements are needed
        if validation_result["validation_status"] == "needs_adjustment":
            adjustments = validation_result.get("suggested_adjustments", [])
            print(f"💡 Literature suggests {len(adjustments)} improvement(s):")
            
            for i, adj in enumerate(adjustments, 1):
                param = adj.get("parameter", "Unknown")
                current = adj.get("current_value", "N/A")
                suggested = adj.get("suggested_value", "N/A")
                reason = adj.get("reason", "No reason provided")
                print(f"   {i}. {param}: {current} → {suggested}")
                print(f"      Reason: {reason}")
            
            print(f"\n🔧 Applying improvements...")
            
            # Apply improvements
            improvement_result = self.vasp_agent.apply_improvements(
                original_incar=vasp_result["incar"],
                validation_result=validation_result,
                poscar_path=structure_path,
                original_request=user_request,
                output_dir=self.output_dir
            )
            
            validation_result["improvement_application"] = improvement_result
            
            if improvement_result["status"] == "success":
                print(f"   ✅ Applied {improvement_result['adjustments_count']} improvements")
                print(f"   📄 Saved as: INCAR_improved")
            else:
                print(f"   ❌ Failed to apply improvements: {improvement_result.get('message')}")
            
        else:
            print(f"✅ INCAR parameters look good - no improvements needed")
            validation_result["improvement_application"] = {
                "status": "no_changes",
                "message": "No improvements needed"
            }
        
        # Save validation report
        self.incar_validator.save_validation_report(validation_result, self.output_dir)
        
        return validation_result
    
    def _print_final_summary(self, workflow_result: Dict[str, Any]):
        """Print a clean final summary."""
        
        print(f"\n🎉 DFT Workflow Complete!")
        print(f"{'='*60}")
        
        # Basic info
        status = workflow_result.get('final_status')
        steps = workflow_result.get('steps_completed', [])
        
        print(f"📋 Status: {status}")
        print(f"✅ Steps: {' → '.join(steps)}")
        print(f"📁 Output: {self.output_dir}/")
        
        # Structure info
        if "structure_generation" in workflow_result:
            struct_result = workflow_result["structure_generation"]
            if struct_result["status"] == "success":
                cycles = struct_result.get('cycles_used', 1)
                structure_file = os.path.basename(struct_result['final_structure_path'])
                print(f"🏗️  Structure: {structure_file} (refined {cycles} cycle{'s' if cycles > 1 else ''})")
        
        # VASP info
        if "vasp_generation" in workflow_result:
            vasp_result = workflow_result["vasp_generation"]
            if vasp_result["status"] == "success":
                calc_type = vasp_result.get('summary', 'DFT calculation')
                print(f"⚛️  VASP: {calc_type}")
        
        # Literature validation info
        if "incar_improvement" in workflow_result:
            imp_result = workflow_result["incar_improvement"]
            if imp_result["status"] == "success":
                if imp_result["validation_status"] == "needs_adjustment":
                    adj_count = len(imp_result.get("suggested_adjustments", []))
                    print(f"📚 Literature: {adj_count} parameter improvement{'s' if adj_count > 1 else ''} applied")
                else:
                    print(f"📚 Literature: Parameters validated, no changes needed")
        
        # Final files
        print(f"\n📄 Ready for VASP:")
        manifest = workflow_result.get("final_manifest", {})
        if manifest.get("ready_for_vasp"):
            files = manifest["final_files"]
            structure_file = files.get('structure', 'POSCAR')
            incar_file = files.get('incar', 'INCAR')
            kpoints_file = files.get('kpoints', 'KPOINTS')
            
            print(f"   • {structure_file}")
            print(f"   • {incar_file}{' ⭐ (literature-optimized)' if manifest.get('literature_validated') else ''}")
            print(f"   • {kpoints_file}")
        
        print(f"{'='*60}")
    
    def get_summary(self, workflow_result: Dict[str, Any]) -> str:
        """Get a human-readable summary of the workflow results."""
        
        summary = f"DFT Workflow Summary\n{'='*20}\n"
        summary += f"Request: {workflow_result['user_request']}\n"
        summary += f"Status: {workflow_result['final_status']}\n"
        summary += f"Steps completed: {', '.join(workflow_result['steps_completed'])}\n"
        summary += f"Output directory: {workflow_result.get('output_directory', 'N/A')}\n\n"
        
        # Structure generation summary
        if "structure_generation" in workflow_result:
            struct_result = workflow_result["structure_generation"]
            if struct_result["status"] == "success":
                struct_file = os.path.basename(struct_result['final_structure_path'])
                summary += f"✓ Final Structure: {struct_file}\n"
                summary += f"  Refinement cycles: {struct_result['cycles_used']}\n"
                summary += f"  Location: {workflow_result.get('output_directory', '.')}/\n"
        
        # VASP generation summary  
        if "vasp_generation" in workflow_result:
            vasp_result = workflow_result["vasp_generation"]
            if vasp_result["status"] == "success":
                summary += f"✓ VASP Input Files:\n"
                
                # Determine which INCAR to highlight
                if ("incar_improvement" in workflow_result and 
                    workflow_result["incar_improvement"].get("improvement_application", {}).get("status") == "success"):
                    summary += f"  - INCAR_improved (literature-validated) ⭐\n"
                    summary += f"  - INCAR (original)\n"
                else:
                    summary += f"  - INCAR\n"
                
                summary += f"  - KPOINTS\n"
                summary += f"  Calculation: {vasp_result['summary']}\n"
        
        # Improvement summary
        if "incar_improvement" in workflow_result:
            imp_result = workflow_result["incar_improvement"]
            if imp_result["status"] == "success":
                if imp_result["validation_status"] == "needs_adjustment":
                    adj_count = len(imp_result.get("suggested_adjustments", []))
                    summary += f"✓ Literature improvements: {adj_count} adjustments applied\n"
                else:
                    summary += f"✓ Literature validation: No improvements needed\n"
        
        # Add final files section
        if "final_manifest" in workflow_result:
            manifest = workflow_result["final_manifest"]
            if manifest.get("ready_for_vasp"):
                summary += f"\n📋 FINAL FILES FOR VASP:\n"
                final_files = manifest["final_files"]
                summary += f"  Structure: {final_files.get('structure', 'N/A')}\n"
                summary += f"  INCAR: {final_files.get('incar', 'N/A')}\n"
                summary += f"  KPOINTS: {final_files.get('kpoints', 'N/A')}\n"
                summary += f"  Directory: {manifest['output_directory']}/\n"
        
        return summary

    def _save_workflow_log(self) -> str:
        """Save all captured logs to a file."""
        try:
            log_content = self.log_capture.getvalue()
            log_path = os.path.join(self.output_dir, "workflow_log.txt")
            
            with open(log_path, 'w') as f:
                f.write(f"DFT Workflow Complete Log\n")
                f.write(f"{'='*30}\n\n")
                f.write(log_content)
            
            print(f"📝 Complete workflow log saved: {log_path}")
            return log_path
            
        except Exception as e:
            print(f"Warning: Could not save workflow log: {e}")
            return ""
        
    def _create_final_files_manifest(self, workflow_result: Dict[str, Any]) -> Dict[str, str]:
        """Create a JSON manifest of final files."""
        
        manifest = {
            "workflow_status": workflow_result["final_status"],
            "user_request": workflow_result["user_request"],
            "output_directory": self.output_dir,
            "final_files": {},
            "ready_for_vasp": False
        }
        
        # Determine final structure file
        if ("structure_generation" in workflow_result and 
            workflow_result["structure_generation"]["status"] == "success"):
            structure_path = workflow_result["structure_generation"]["final_structure_path"]
            manifest["final_files"]["structure"] = os.path.basename(structure_path)
        
        # Determine final VASP input files
        if ("vasp_generation" in workflow_result and 
            workflow_result["vasp_generation"]["status"] == "success"):
            
            # Check if improved INCAR exists
            if ("incar_improvement" in workflow_result and 
                workflow_result["incar_improvement"].get("improvement_application", {}).get("status") == "success"):
                manifest["final_files"]["incar"] = "INCAR_improved"
                manifest["literature_validated"] = True
            else:
                manifest["final_files"]["incar"] = "INCAR"
                manifest["literature_validated"] = False
                
            manifest["final_files"]["kpoints"] = "KPOINTS"
            
            # Mark as ready if we have all required files
            if all(key in manifest["final_files"] for key in ["structure", "incar", "kpoints"]):
                manifest["ready_for_vasp"] = True
        
        # Save manifest
        try:
            manifest_path = os.path.join(self.output_dir, "final_files_manifest.json")
            with open(manifest_path, 'w') as f:
                json.dump(manifest, f, indent=2)
        except Exception as e:
            self.logger.error(f"Failed to save manifest: {e}")
            
        return manifest


================================================
File: workflows/experiment2dft.py
================================================
import os
import sys
import logging
import json
from io import StringIO
from typing import Dict, Any, List, Optional, Union
from pathlib import Path

# Import other workflows
from .experiment_novelty_workflow import ExperimentNoveltyAssessment
from .dft_recommendation_workflow import DFTRecommendationsWorkflow
from .dft_workflow import DFTWorkflow

# Import auth for API key management
from ..auth import get_api_key, APIKeyNotFoundError


class Experimental2DFT:
    """
    Complete pipeline from experimental data (microscopy or spectroscopy) to atomic structures.
    
    This workflow orchestrates the entire process:
    1. Experimental data analysis with novelty assessment (microscopy or spectroscopy)
    2. DFT structure recommendations based on novelty
    3. Interactive or automatic structure selection
    4. Atomic structure generation with validation
    5. Complete results summary
    
    Supports both microscopy images and hyperspectral/spectroscopy data.
    """
    
    def __init__(self,
                 agent_id: int | None = None,
                 google_api_key: str = None,
                 futurehouse_api_key: str = None,
                 mp_api_key: str = None,
                 analysis_model: str = "gemini-2.5-pro-preview-06-05",
                 generator_model: str = "gemini-2.5-pro-preview-06-05",
                 validator_model: str = "gemini-2.5-pro-preview-06-05",
                 output_dir: str = "complete_experimental_pipeline_output",
                 max_wait_time: int = 400,
                 max_refinement_cycles: int = 2,
                 script_timeout: int = 300,
                 spectroscopy_analysis_enabled: bool = True):
        
        # Auto-discover API keys
        if google_api_key is None:
            google_api_key = get_api_key('google')
            if not google_api_key:
                raise APIKeyNotFoundError('google')
        
        if futurehouse_api_key is None:
            futurehouse_api_key = get_api_key('futurehouse')
            if not futurehouse_api_key:
                import warnings
                warnings.warn(
                    "FutureHouse API key not found. Literature search will be disabled."
                )
        
        if mp_api_key is None:
            mp_api_key = get_api_key('materials_project')
            # Optional
        
        # Setup logging
        self.log_capture = StringIO()
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s',
            force=True,
            handlers=[
                logging.StreamHandler(sys.stdout),
                logging.StreamHandler(self.log_capture)
            ]
        )
        self.logger = logging.getLogger(__name__)
        
        # Store configuration
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        
        # Store parameters for creating data-specific workflows
        self.agent_id = agent_id
        self.google_api_key = google_api_key
        self.futurehouse_api_key = futurehouse_api_key
        self.analysis_model = analysis_model
        self.max_wait_time = max_wait_time
        self.spectroscopy_analysis_enabled = spectroscopy_analysis_enabled
        
        # Initialize structure generation workflow
        self.dft_rec_workflow = DFTRecommendationsWorkflow(
            google_api_key=google_api_key,
            analysis_model=analysis_model,
            output_dir=str(self.output_dir / "dft_recommendations")
        )
        
        self.dft_workflow = DFTWorkflow(
            google_api_key=google_api_key,
            futurehouse_api_key=futurehouse_api_key,
            mp_api_key=mp_api_key,
            generator_model=generator_model,
            validator_model=validator_model,
            output_dir=str(self.output_dir / "generated_structures"),
            max_refinement_cycles=max_refinement_cycles,
            script_timeout=script_timeout
        )
        
        self.logger.info("Experimental2DFT workflow initialized")
    
    def run_complete_pipeline(self, 
                             data_path: Union[str, Path],
                             data_type: str,
                             system_info: Union[str, Path, Dict[str, Any]],
                             interactive: bool = True,
                             auto_select_top_n: int = 2,
                             max_structures: int = 5) -> Dict[str, Any]:
        """
        Run the complete experimental pipeline.
        
        Args:
            data_path: Path to experimental data (image for microscopy, .npy for spectroscopy)
            data_type: Type of data - either 'microscopy' or 'spectroscopy'
            system_info: Path to system metadata JSON file or dict
            interactive: Whether to allow interactive structure selection
            auto_select_top_n: Number of top recommendations to auto-select in non-interactive mode
            max_structures: Maximum number of structures to generate
            
        Returns:
            Complete pipeline results dictionary
        """
        
        # Validate data type
        if data_type not in ['microscopy', 'spectroscopy']:
            raise ValueError("data_type must be either 'microscopy' or 'spectroscopy'")
        
        pipeline_result = {
            "input_data": str(data_path),
            "data_type": data_type,
            "input_system_info": str(system_info) if not isinstance(system_info, dict) else system_info,
            "steps_completed": [],
            "final_status": "started",
            "generated_structures": []
        }
        
        self.logger.info(f"🚀 Starting Complete {data_type.title()} → Structure Pipeline")
        print(f"🚀 Starting Complete {data_type.title()} → Structure Pipeline")
        print("=" * 60)
        
        # Step 1: Novelty Assessment (data type specific)
        novelty_result = self._run_novelty_assessment(data_path, data_type, system_info)
        pipeline_result["novelty_assessment"] = novelty_result
        
        if novelty_result.get('final_status') != 'success':
            pipeline_result["final_status"] = f"failed_novelty: {novelty_result.get('final_status')}"
            return pipeline_result
        
        pipeline_result["steps_completed"].append("novelty_assessment")
        
        # Step 2: DFT Recommendations
        dft_rec_result = self._run_dft_recommendations(novelty_result, system_info)
        pipeline_result["dft_recommendations"] = dft_rec_result
        
        if dft_rec_result.get('status') != 'success':
            pipeline_result["final_status"] = f"failed_dft_recommendations: {dft_rec_result.get('message')}"
            return pipeline_result
            
        pipeline_result["steps_completed"].append("dft_recommendations")
        
        # Step 3: Structure Selection
        selected_structures = self._select_structures(
            dft_rec_result.get('recommendations', []),
            interactive=interactive,
            auto_select_top_n=auto_select_top_n,
            max_structures=max_structures
        )
        
        if not selected_structures:
            pipeline_result["final_status"] = "no_structures_selected"
            return pipeline_result
            
        pipeline_result["selected_recommendations"] = selected_structures
        pipeline_result["steps_completed"].append("structure_selection")
        
        # Step 4: Structure Generation
        structure_results = self._generate_structures(selected_structures)
        pipeline_result["generated_structures"] = structure_results
        pipeline_result["steps_completed"].append("structure_generation")
        
        # Step 5: Final Summary
        self._generate_final_summary(pipeline_result)
        
        # Determine final status
        successful_structures = [s for s in structure_results if s.get('success', False)]
        if successful_structures:
            pipeline_result["final_status"] = "success"
        else:
            pipeline_result["final_status"] = "no_successful_structures"
        
        # Save complete results
        self._save_pipeline_results(pipeline_result)
        
        return pipeline_result
    
    def run_microscopy_pipeline(self, 
                               image_path: Union[str, Path],
                               system_info: Union[str, Path, Dict[str, Any]],
                               interactive: bool = True,
                               auto_select_top_n: int = 2,
                               max_structures: int = 5) -> Dict[str, Any]:
        """
        Convenience method for microscopy data analysis.
        """
        return self.run_complete_pipeline(
            data_path=image_path,
            data_type='microscopy',
            system_info=system_info,
            interactive=interactive,
            auto_select_top_n=auto_select_top_n,
            max_structures=max_structures
        )
    
    def run_spectroscopy_pipeline(self, 
                                 data_path: Union[str, Path],
                                 system_info: Union[str, Path, Dict[str, Any]],
                                 interactive: bool = True,
                                 auto_select_top_n: int = 2,
                                 max_structures: int = 5,
                                 structure_image_path: Union[str, Path] = None,
                                 structure_system_info: Dict[str, Any] = None
                                 ) -> Dict[str, Any]:
        """
        Convenience method for spectroscopy data analysis.
        """

        # Store structure image info for the workflow
        self._temp_structure_image_path = structure_image_path
        self._temp_structure_system_info = structure_system_info

        return self.run_complete_pipeline(
            data_path=data_path,
            data_type='spectroscopy',
            system_info=system_info,
            interactive=interactive,
            auto_select_top_n=auto_select_top_n,
            max_structures=max_structures
        )
    
    def _run_novelty_assessment(self, data_path: Union[str, Path], data_type: str, system_info: Union[str, Path, Dict[str, Any]]) -> Dict[str, Any]:
        """Run enhanced novelty assessment using unified workflow."""
        
        print(f"\n📊 STEP 1: {data_type.title()} Analysis & Enhanced Novelty Assessment")
        print("-" * 50)
        
        try:
            # Create data-type specific workflow
            if data_type == 'microscopy':
                novelty_workflow = ExperimentNoveltyAssessment(
                    data_type='microscopy',
                    agent_id=self.agent_id,
                    google_api_key=self.google_api_key,
                    futurehouse_api_key=self.futurehouse_api_key,
                    analysis_model=self.analysis_model,
                    output_dir=str(self.output_dir / "microscopy_novelty_assessment"),
                    max_wait_time=self.max_wait_time
                )
                
                novelty_result = novelty_workflow.run_complete_workflow(
                    data_path=str(data_path),
                    system_info=system_info
                )
                
            elif data_type == 'spectroscopy':
                novelty_workflow = ExperimentNoveltyAssessment(
                    data_type='spectroscopy',
                    google_api_key=self.google_api_key,
                    futurehouse_api_key=self.futurehouse_api_key,
                    analysis_model=self.analysis_model,
                    output_dir=str(self.output_dir / "spectroscopy_novelty_assessment"),
                    max_wait_time=self.max_wait_time,
                    spectral_unmixing_enabled=self.spectroscopy_analysis_enabled
                )
                
                structure_image_path = getattr(self, '_temp_structure_image_path', None)
                structure_system_info = getattr(self, '_temp_structure_system_info', None)
                
                novelty_result = novelty_workflow.run_complete_workflow(
                    data_path=str(data_path),
                    system_info=system_info,
                    structure_image_path=structure_image_path,
                    structure_system_info=structure_system_info    
                )
            else:
                raise ValueError(f"Unsupported data type: {data_type}")
            
            if novelty_result.get('final_status') == 'success':
                claims_count = len(novelty_result.get("claims_generation", {}).get("claims", []))
                
                # Enhanced novelty reporting
                assessment = novelty_result.get("novelty_assessment", {})
                avg_score = assessment.get("average_novelty_score", 0)
                categories = assessment.get("novelty_categories", {})
                
                high_novel_count = len(categories.get("highly_novel", []))
                moderate_novel_count = len(categories.get("moderately_novel", []))
                
                print(f"✅ {data_type.title()} enhanced novelty assessment completed")
                print(f"   📋 Generated {claims_count} claims")
                print(f"   📊 Average novelty score: {avg_score:.2f}/5.0")
                print(f"   🚀 Potentially High novelty findings: {high_novel_count}")
                print(f"   📈 Moderate novelty findings: {moderate_novel_count}")
            else:
                print(f"❌ {data_type.title()} novelty assessment failed: {novelty_result.get('final_status')}")
            
            return novelty_result
            
        except Exception as e:
            self.logger.exception(f"Failed in {data_type} enhanced novelty assessment step")
            return {"final_status": f"error: {str(e)}"}
    
    def _run_dft_recommendations(self, novelty_result: Dict[str, Any], system_info: Union[str, Path, Dict[str, Any]]) -> Dict[str, Any]:
        """Generate DFT structure recommendations based on enhanced novelty findings."""
        
        print("\n⚛️  STEP 2: DFT Structure Recommendations (Enhanced)")
        print("-" * 50)
        
        try:
            # Extract data from enhanced novelty assessment
            analysis_text = novelty_result["claims_generation"]["detailed_analysis"]
            assessment = novelty_result.get("novelty_assessment", {})
            
            # Prioritize high and moderate novelty claims
            high_novel = assessment.get("novelty_categories", {}).get("highly_novel", [])
            moderate_novel = assessment.get("novelty_categories", {}).get("moderately_novel", [])
            priority_claims = high_novel + moderate_novel
            
            # Load system info if it's a file path
            if isinstance(system_info, (str, Path)):
                with open(system_info, 'r') as f:
                    system_info_dict = json.load(f)
            else:
                system_info_dict = system_info
            
            # Generate recommendations with enhanced context
            dft_result = self.dft_rec_workflow.run_from_data(
                analysis_text=analysis_text,
                novel_claims=priority_claims,  # Use prioritized claims
                system_info=system_info_dict
            )
            
            if dft_result.get('status') == 'success':
                rec_count = len(dft_result.get('recommendations', []))
                avg_score = assessment.get('average_novelty_score', 0)
                
                print(f"✅ Generated {rec_count} DFT structure recommendations")
                print(f"   📊 Based on average novelty score: {avg_score:.2f}/5.0")
                print(f"   🎯 Prioritizing {len(priority_claims)} high-impact findings")
                
                # Display top recommendations with novelty context
                recommendations = dft_result.get('recommendations', [])
                if recommendations:
                    print("\n📋 Top Structure Recommendations (Novelty-Informed):")
                    for i, rec in enumerate(recommendations[:5], 1):
                        priority = rec.get('priority', 'N/A')
                        desc = rec.get('description', 'N/A')
                        print(f"   [{i}] Priority {priority}: {desc}")
            else:
                print(f"❌ DFT recommendations failed: {dft_result.get('message')}")
            
            return dft_result
            
        except Exception as e:
            self.logger.exception("Failed in enhanced DFT recommendations step")
            return {"status": f"error: {str(e)}"}
    
    def _select_structures(self, recommendations: List[Dict[str, Any]], 
                          interactive: bool = True,
                          auto_select_top_n: int = 2,
                          max_structures: int = 5) -> List[Dict[str, Any]]:
        """Select which structures to generate."""
        
        print("\n🎯 STEP 3: Structure Selection")
        print("-" * 50)
        
        if not recommendations:
            print("⚠️  No structure recommendations available")
            return []
        
        # Limit to max_structures
        available_recommendations = recommendations[:max_structures]
        
        if interactive:
            return self._interactive_structure_selection(available_recommendations)
        else:
            # Auto-select top N
            selected = available_recommendations[:auto_select_top_n]
            print(f"🤖 Auto-selected top {len(selected)} recommendations (non-interactive mode)")
            for i, struct in enumerate(selected, 1):
                print(f"   [{i}] {struct.get('description', 'N/A')}")
            return selected
    
    def _interactive_structure_selection(self, recommendations: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """Handle interactive structure selection."""
        
        print("\nAvailable structures:")
        for i, rec in enumerate(recommendations, 1):
            priority = rec.get('priority', 'N/A')
            desc = rec.get('description', 'N/A')
            print(f"   [{i}] Priority {priority}: {desc}")
        
        print("\nSelection options:")
        print("  • Enter numbers: '1,2,3' (select specific structures)")
        print("  • Enter 'all' (select all available)")
        print(f"  • Enter 'top3' (select top 3)")
        print("  • Enter 'skip' (skip structure generation)")
        
        while True:
            try:
                choice = input(f"\nSelect from 1-{len(recommendations)} or option: ").strip().lower()
                
                if choice == 'skip':
                    print("Structure generation skipped by user")
                    return []
                elif choice == 'all':
                    print(f"Selected all {len(recommendations)} structures")
                    return recommendations
                elif choice.startswith('top'):
                    try:
                        n = int(choice.replace('top', ''))
                        selected = recommendations[:n]
                        print(f"Selected top {len(selected)} structures")
                        return selected
                    except ValueError:
                        print("Invalid 'top' format. Use 'top3', 'top5', etc.")
                        continue
                else:
                    # Parse comma-separated numbers
                    indices = [int(x.strip()) - 1 for x in choice.split(',')]
                    selected = [recommendations[i] for i in indices if 0 <= i < len(recommendations)]
                    if selected:
                        print(f"Selected {len(selected)} structures:")
                        for i, struct in enumerate(selected, 1):
                            print(f"   [{i}] {struct.get('description', 'N/A')}")
                        return selected
                    else:
                        print("Invalid selection. Please try again.")
            except (ValueError, IndexError):
                print("Invalid input. Please enter numbers, 'all', 'topN', or 'skip'.")
            except (KeyboardInterrupt, EOFError):
                print("\nSelection cancelled by user")
                return []
    
    def _generate_structures(self, selected_structures: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """Generate atomic structures for selected recommendations."""
        
        print("\n🏗️  STEP 4: Atomic Structure Generation")
        print("-" * 50)
        
        generated_structures = []
        
        for i, structure_rec in enumerate(selected_structures, 1):
            print(f"\n   🔨 Generating structure {i}/{len(selected_structures)}")
            print(f"      Description: {structure_rec.get('description', 'N/A')}")
            
            try:
                # Create structure-specific subdirectory
                structure_name = f"structure_{i:02d}"
                structure_output_dir = self.output_dir / "generated_structures" / structure_name
                structure_output_dir.mkdir(parents=True, exist_ok=True)
                
                print(f"      📁 Output directory: {structure_name}/")
                
                # Create a new DFT workflow instance for this structure
                structure_dft_workflow = DFTWorkflow(
                    google_api_key=self.dft_workflow.google_api_key,
                    futurehouse_api_key=self.dft_workflow.futurehouse_api_key,
                    mp_api_key=getattr(self.dft_workflow.structure_generator, 'mp_api_key', None),
                    generator_model=self.dft_workflow.structure_generator.llm_client.model_name,
                    validator_model=self.dft_workflow.structure_validator.model_name,
                    output_dir=str(structure_output_dir),  # Structure-specific directory
                    max_refinement_cycles=self.dft_workflow.max_refinement_cycles,
                    script_timeout=self.dft_workflow.structure_generator.ase_executor.timeout
                )
                
                # Create detailed request for structure generation
                user_request = structure_rec.get('description', '')
                if 'scientific_interest' in structure_rec:
                    user_request += f". Scientific justification: {structure_rec['scientific_interest']}"
                user_request += ". Save the structure in POSCAR format."
                
                # Generate the structure
                struct_result = structure_dft_workflow.run_complete_workflow(user_request)
                
                structure_info = {
                    "recommendation": structure_rec,
                    "generation_result": struct_result,
                    "structure_number": i,
                    "user_request": user_request,
                    "output_directory": str(structure_output_dir),
                    "structure_name": structure_name
                }
                
                if struct_result.get('final_status') == 'success':
                    # Extract structure file path
                    if 'structure_generation' in struct_result:
                        struct_gen = struct_result['structure_generation']
                        if struct_gen.get('status') == 'success':
                            structure_info["structure_file"] = struct_gen.get('final_structure_path')
                            structure_info["script_file"] = struct_gen.get('final_script_path')
                            structure_info["success"] = True
                            
                            # Create a summary file for this structure
                            self._create_structure_summary(structure_info, structure_output_dir)
                            
                            filename = os.path.basename(struct_gen.get('final_structure_path', 'unknown'))
                            print(f"      ✅ Structure generated: {filename}")
                            print(f"      📁 Files saved to: {structure_name}/")
                        else:
                            structure_info["success"] = False
                            error_msg = struct_gen.get('message', 'Unknown error')
                            print(f"      ❌ Structure generation failed: {error_msg}")
                    else:
                        structure_info["success"] = False
                        print(f"      ❌ No structure generation result")
                else:
                    structure_info["success"] = False
                    status = struct_result.get('final_status', 'Unknown status')
                    print(f"      ❌ Workflow failed: {status}")
                
                generated_structures.append(structure_info)
                
            except Exception as struct_e:
                self.logger.exception(f"Failed to generate structure {i}")
                generated_structures.append({
                    "recommendation": structure_rec,
                    "error": str(struct_e),
                    "success": False,
                    "structure_number": i,
                    "structure_name": f"structure_{i:02d}"
                })
                print(f"      ❌ Error generating structure {i}: {struct_e}")
        
        # Summary
        successful = [s for s in generated_structures if s.get('success', False)]
        print(f"\n✅ Structure generation completed: {len(successful)}/{len(generated_structures)} successful")
        
        return generated_structures
    
    def _create_structure_summary(self, structure_info: Dict[str, Any], output_dir: Path):
        """Create a summary file for each generated structure."""
        
        summary = {
            "structure_number": structure_info["structure_number"],
            "structure_name": structure_info["structure_name"],
            "recommendation": structure_info["recommendation"],
            "user_request": structure_info["user_request"],
            "generation_status": "success" if structure_info["success"] else "failed",
            "files_generated": [],
            "output_directory": str(output_dir)
        }
        
        # List all files in the output directory
        if output_dir.exists():
            for file_path in output_dir.glob("*"):
                if file_path.is_file():
                    summary["files_generated"].append(file_path.name)
        
        # Save summary
        summary_file = output_dir / "structure_summary.json"
        with open(summary_file, 'w') as f:
            json.dump(summary, f, indent=2)
    
    def _generate_final_summary(self, pipeline_result: Dict[str, Any]):
        """Generate and display final pipeline summary."""
        
        data_type = pipeline_result.get("data_type", "experimental")
        
        print(f"\n📋 {data_type.upper()} PIPELINE SUMMARY")
        print("=" * 60)
        
        # Extract key metrics
        novelty_result = pipeline_result.get("novelty_assessment", {})
        claims_count = len(novelty_result.get("claims_generation", {}).get("claims", []))
        
        # Handle enhanced novelty assessment structure
        assessment = novelty_result.get("novelty_assessment", {})
        if "novelty_categories" in assessment:
            # Enhanced novelty assessment
            categories = assessment["novelty_categories"]
            high_novel_count = len(categories.get("highly_novel", []))
            moderate_novel_count = len(categories.get("moderately_novel", []))
            total_novel_count = high_novel_count + moderate_novel_count
        else:
            # Legacy format
            total_novel_count = len(assessment.get("potentially_novel", []))
        
        dft_result = pipeline_result.get("dft_recommendations", {})
        recommendations_count = len(dft_result.get("recommendations", []))
        
        structures = pipeline_result.get("generated_structures", [])
        successful_structures = [s for s in structures if s.get('success', False)]
        
        if successful_structures:
            print(f"🎉 {data_type.title()} pipeline completed successfully!")
            print(f"   📊 Claims generated: {claims_count}")
            print(f"   🔍 Novel findings: {total_novel_count}")
            print(f"   ⚛️  DFT recommendations: {recommendations_count}")
            print(f"   🏗️  Structures generated: {len(successful_structures)}")
            
            print(f"\n📁 Generated Structure Directories:")
            for i, struct in enumerate(successful_structures, 1):
                structure_name = struct.get('structure_name', f'structure_{i:02d}')
                desc = struct['recommendation'].get('description', 'N/A')
                print(f"   [{i}] {structure_name}/")
                print(f"       {desc}")
                print(f"       📄 Contains: POSCAR, INCAR, KPOINTS, scripts, logs")
            
            print(f"\n📂 Main Output Directory Structure:")
            print(f"   {self.output_dir}/")
            print(f"   ├── {data_type}_novelty_assessment/")
            print(f"   ├── dft_recommendations/") 
            print(f"   ├── generated_structures/")
            for struct in successful_structures:
                structure_name = struct.get('structure_name', 'structure_XX')
                print(f"   │   ├── {structure_name}/")
                print(f"   │   │   ├── POSCAR")
                print(f"   │   │   ├── INCAR")
                print(f"   │   │   ├── KPOINTS")
                print(f"   │   │   ├── structure_summary.json")
                print(f"   │   │   └── workflow_log.txt")
            print(f"   └── complete_pipeline_result.json")
        else:
            print(f"⚠️  {data_type.title()} pipeline completed but no structures were successfully generated")
            print(f"   📊 Claims generated: {claims_count}")
            print(f"   🔍 Novel findings: {total_novel_count}")
            print(f"   ⚛️  DFT recommendations: {recommendations_count}")

    def _save_pipeline_results(self, pipeline_result: Dict[str, Any]):
        """Save complete pipeline results to file."""
        
        try:
            output_file = self.output_dir / "complete_pipeline_result.json"
            
            # Convert to JSON-serializable format
            json_result = json.loads(json.dumps(pipeline_result, default=str))
            
            with open(output_file, 'w') as f:
                json.dump(json_result, f, indent=2)
            
            self.logger.info(f"Complete pipeline result saved to: {output_file}")
            print(f"\n💾 Complete pipeline result saved to: {output_file}")
            
        except Exception as e:
            self.logger.error(f"Failed to save pipeline results: {e}")
    
    def get_summary(self, pipeline_result: Dict[str, Any]) -> str:
        """Get a human-readable summary of the pipeline results."""
        
        data_type = pipeline_result.get("data_type", "experimental")
        
        summary = f"Complete {data_type.title()} Pipeline Summary\n{'='*40}\n"
        summary += f"Status: {pipeline_result.get('final_status', 'Unknown')}\n"
        summary += f"Data type: {data_type}\n"
        summary += f"Steps completed: {', '.join(pipeline_result.get('steps_completed', []))}\n"
        summary += f"Input data: {os.path.basename(str(pipeline_result.get('input_data', 'Unknown')))}\n\n"
        
        # Enhanced novelty assessment summary
        novelty_result = pipeline_result.get("novelty_assessment", {})
        if novelty_result:
            claims_count = len(novelty_result.get("claims_generation", {}).get("claims", []))
            assessment = novelty_result.get("novelty_assessment", {})
            
            summary += f"Enhanced Novelty Assessment:\n"
            summary += f"  Claims generated: {claims_count}\n"
            
            if "novelty_categories" in assessment:
                # Enhanced novelty assessment
                categories = assessment["novelty_categories"]
                avg_score = assessment.get("average_novelty_score", 0)
                
                summary += f"  Average novelty score: {avg_score:.2f}/5.0\n"
                summary += f"  High novelty findings: {len(categories.get('highly_novel', []))}\n"
                summary += f"  Moderate novelty findings: {len(categories.get('moderately_novel', []))}\n"
            else:
                # Legacy format
                novel_count = len(assessment.get("potentially_novel", []))
                summary += f"  Novel findings: {novel_count}\n"
            
            summary += "\n"
        
        # DFT recommendations summary
        dft_result = pipeline_result.get("dft_recommendations", {})
        if dft_result:
            rec_count = len(dft_result.get("recommendations", []))
            summary += f"DFT Recommendations: {rec_count} structures recommended\n\n"
        
        # Structure generation summary
        structures = pipeline_result.get("generated_structures", [])
        if structures:
            successful = [s for s in structures if s.get('success', False)]
            summary += f"Structure Generation:\n"
            summary += f"  Attempted: {len(structures)}\n"
            summary += f"  Successful: {len(successful)}\n"
            
            if successful:
                summary += f"  Generated files:\n"
                for i, struct in enumerate(successful, 1):
                    if 'structure_file' in struct:
                        filename = os.path.basename(struct['structure_file'])
                        summary += f"    {i}. {filename}\n"
        
        return summary


================================================
File: workflows/experiment_novelty_workflow.py
================================================
import os
import sys
import logging
import json
from io import StringIO
from typing import Dict, Any, List, Union
import textwrap
from pathlib import Path

from .analyzers import MicroscopyAnalyzer, SpectroscopyAnalyzer, BaseExperimentAnalyzer

from ..agents.exp_agents.microscopy_agent import MicroscopyAnalysisAgent
from ..agents.lit_agents.literature_agent import OwlLiteratureAgent
from ..agents.lit_agents.novelty_scorer import NoveltyScorer, enhanced_novelty_assessment, display_enhanced_novelty_summary

import warnings
from ..auth import get_api_key, APIKeyNotFoundError


def select_claims_interactive(claims: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
    """
    Allows user to interactively select which claims to search for in the literature.
    """
    if not claims:
        print("❌ No claims available to select from.")
        return []
        
    print(f"\n📋 Claim Selection")
    print(f"{'─'*50}")
    print("Select claims for literature search:")
    print("• Enter comma-separated numbers (e.g., '1,3,5')")
    print("• Enter 'all' for all claims")
    
    # Display the "Has Anyone" questions with clean formatting
    for i, claim in enumerate(claims):
        print(f"\n[{i+1}] {claim.get('has_anyone_question', 'No question formulated')}")
    
    print(f"{'─'*50}")
    
    # Get user selection
    try:
        selection = input("\n🔍 Select claims to search (or 'all'): ").strip().lower()
        
        if selection == 'all':
            print(f"✅ Selected all {len(claims)} claims.")
            return claims
            
        # Parse the comma-separated list of numbers
        try:
            indices = [int(idx.strip()) - 1 for idx in selection.split(',')]
            selected_claims = []
            
            for idx in indices:
                if 0 <= idx < len(claims):
                    selected_claims.append(claims[idx])
                else:
                    print(f"⚠️  Index {idx+1} is out of range and will be skipped.")
            
            if not selected_claims:
                print("❌ No valid claims were selected.")
                return []
                
            print(f"✅ Selected {len(selected_claims)} claims.")
            return selected_claims
            
        except ValueError:
            print("❌ Invalid selection format. Please use comma-separated numbers or 'all'.")
            return select_claims_interactive(claims)  # Try again
            
    except KeyboardInterrupt:
        print("\n❌ Selection canceled by user.")
        return []


class ExperimentNoveltyAssessment:
    """
    Unified workflow for analyzing experimental data and assessing novelty.
    
    Supports multiple experimental data types (microscopy, spectroscopy, etc.)
    through a pluggable analyzer system. Can be easily extended for new data types.
    """
    
    # Registry of available analyzers
    ANALYZER_REGISTRY = {
        'microscopy': MicroscopyAnalyzer,
        'spectroscopy': SpectroscopyAnalyzer,
    }
    
    def __init__(self,
                 data_type: str,
                 google_api_key: str = None,
                 futurehouse_api_key: str = None,
                 analysis_model: str = "gemini-2.5-pro-preview-06-05",
                 local_model: str = None,
                 output_dir: str = "experiment_novelty_output",
                 max_wait_time: int = 600,
                 dft_recommendations: bool = False,
                 measurement_recommendations: bool = False,
                 enable_human_feedback: bool = True,
                 display_agent_logs: bool = True,
                 **analyzer_kwargs):
        """
        Initialize the unified experiment novelty assessment workflow.
        
        Args:
            data_type: Type of experimental data ('microscopy', 'spectroscopy', etc.)
            google_api_key: Google API key for analysis
            futurehouse_api_key: FutureHouse API key for literature search
            analysis_model: Model name for analysis
            output_dir: Directory for outputs
            max_wait_time: Maximum wait time for literature searches
            dft_recommendations: Whether to generate DFT recommendations (microscopy only)
            enable_human_feedback: Whether to enable human feedback in analyzers
            display_agent_logs: Whether to show detailed agent logs (default: True)
            **analyzer_kwargs: Additional arguments passed to the specific analyzer
        """
        # Validate data type
        if data_type not in self.ANALYZER_REGISTRY:
            available_types = list(self.ANALYZER_REGISTRY.keys())
            raise ValueError(f"Unsupported data_type '{data_type}'. Available types: {available_types}")
        
        self.data_type = data_type
        
        # Auto-discover API keys
        if google_api_key is None:
            google_api_key = get_api_key('google')
            if not google_api_key:
                raise APIKeyNotFoundError('google')
        
        if futurehouse_api_key is None:
            futurehouse_api_key = get_api_key('futurehouse')
            if not futurehouse_api_key:
                warnings.warn(
                    "FutureHouse API key not found. Literature search will be disabled."
                )
        
        # Setup logging with better formatting while preserving agent visibility
        self.log_capture = StringIO()
        logging.basicConfig(
            level=logging.INFO, 
            format='%(asctime)s - %(levelname)s: %(name)s: %(message)s', 
            force=True, 
            handlers=[
                logging.StreamHandler(sys.stdout),  # Show logs for agent visibility
                logging.StreamHandler(self.log_capture)
            ]
        )
        self.logger = logging.getLogger(__name__)
        self.display_agent_logs = display_agent_logs
        
        self.google_api_key = google_api_key
        self.analysis_model = analysis_model
        self.local_model = local_model
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        self.dft_recommendations = dft_recommendations
        self.measurement_recommendations = measurement_recommendations 
        
        # Initialize data-specific analyzer
        analyzer_class = self.ANALYZER_REGISTRY[data_type]
        self.analyzer = analyzer_class(
            google_api_key=google_api_key,
            analysis_model=analysis_model,
            local_model=local_model,
            output_dir=str(self.output_dir),
            enable_human_feedback=enable_human_feedback,
            **analyzer_kwargs
        )
        
        # Initialize literature agent
        if futurehouse_api_key:
            self.lit_agent = OwlLiteratureAgent(
                api_key=futurehouse_api_key,
                max_wait_time=max_wait_time
            )
        else:
            self.lit_agent = None
            print("ℹ️  Literature search disabled (no FutureHouse API key)")
    
    @classmethod
    def register_analyzer(cls, data_type: str, analyzer_class):
        """Register a new analyzer for a data type."""
        if not issubclass(analyzer_class, BaseExperimentAnalyzer):
            raise TypeError("Analyzer must inherit from BaseExperimentAnalyzer")
        cls.ANALYZER_REGISTRY[data_type] = analyzer_class
    
    @classmethod
    def get_supported_data_types(cls) -> List[str]:
        """Get list of supported data types."""
        return list(cls.ANALYZER_REGISTRY.keys())
    
    def run_complete_workflow(self, data_path: Union[str, Path], 
                             system_info: Union[str, Path, Dict[str, Any]] = None, 
                             **analysis_kwargs) -> Dict[str, Any]:
        """
        Run the complete novelty assessment workflow.
        
        Args:
            data_path: Path to experimental data
            system_info: System information (dict or path to JSON file)
            **analysis_kwargs: Additional arguments for the analyzer
        """
        
        # Convert system_info if it's a file path
        if isinstance(system_info, (str, Path)):
            with open(system_info, 'r') as f:
                system_info = json.load(f)
        
        workflow_result = {
            "data_path": str(data_path),
            "data_type": self.data_type,
            "system_info": system_info,
            "steps_completed": [],
            "final_status": "started"
        }
        
        data_type_name = self.analyzer.get_data_type_name()
        
        print(f"\n🔬 Experiment Novelty Assessment Starting")
        print(f"{'='*60}")
        print(f"📊 Data Type: {data_type_name.title()}")
        print(f"📁 Data File: {os.path.basename(str(data_path))}")
        print(f"📂 Output:   {self.output_dir}/")
        print(f"{'='*60}")
        
        # === Step 1: Experimental Data Analysis ===
        print(f"\n🔍 WORKFLOW STEP 1: {data_type_name.title()} Analysis")
        print(f"{'─'*50}")
        
        analysis_result = self._analyze_experimental_data(data_path, system_info, **analysis_kwargs)
        workflow_result["claims_generation"] = analysis_result
        
        if analysis_result["status"] != "success":
            print(f"❌ {data_type_name.title()} analysis failed: {analysis_result.get('message', 'Unknown error')}")
            workflow_result["final_status"] = "failed_analysis"
            return workflow_result
        
        workflow_result["steps_completed"].append("claims_generation")
        claims = analysis_result["claims"]
        
        print(f"✅ Analysis complete: {len(claims)} scientific claims generated")
        print(f"📄 Claims saved: {os.path.basename(analysis_result['claims_file'])}")
        
        # === Step 2: Literature Search ===
        if self.lit_agent is None:
            print(f"⚠️  Literature search skipped (no FutureHouse API key)")
            workflow_result["final_status"] = "no_literature_search"
            self._print_final_summary(workflow_result, data_type_name)
            return workflow_result
        
        print(f"\n📚 WORKFLOW STEP 2: Literature Search")
        print(f"{'─'*50}")
        
        literature_result = self._conduct_literature_search(claims)
        workflow_result["literature_search"] = literature_result
        
        if literature_result["status"] != "success":
            print(f"❌ Literature search failed: {literature_result.get('message', 'Unknown error')}")
            workflow_result["final_status"] = "failed_literature"
            return workflow_result
        
        workflow_result["steps_completed"].append("literature_search")
        literature_results = literature_result["results"]
        
        print(f"✅ Literature search complete: {len(literature_results)} claims processed")
        print(f"📄 Results saved: {os.path.basename(literature_result['results_file'])}")
        
        # === Step 3: Novelty Assessment ===
        print(f"\n🎯 WORKFLOW STEP 3: Novelty Assessment")
        print(f"{'─'*50}")
        
        novelty_result = self._assess_novelty(literature_results, data_type_name)
        workflow_result["novelty_assessment"] = novelty_result["assessment"]
        
        if novelty_result["status"] != "success":
            print(f"❌ Novelty assessment failed: {novelty_result.get('message', 'Unknown error')}")
            workflow_result["final_status"] = "failed_novelty"
            return workflow_result
        
        workflow_result["steps_completed"].append("novelty_assessment")
        assessment = novelty_result["assessment"]
        
        print(f"✅ Novelty assessment complete")
        print(f"📊 Average novelty score: {assessment.get('average_novelty_score', 0):.2f}/5.0")
        print(f"📄 Assessment saved: {os.path.basename(novelty_result['novelty_file'])}")
        
        # === Step 4: DFT Recommendations (Optional) ===
        if self.dft_recommendations and self.data_type == 'microscopy':
            print(f"\n⚛️  WORKFLOW STEP 4: DFT Recommendations")
            print(f"{'─'*50}")
            
            dft_result = self._generate_dft_recommendations(
                workflow_result["claims_generation"]["detailed_analysis"],
                workflow_result["novelty_assessment"] 
            )
            workflow_result["dft_recommendations"] = dft_result
            
            if dft_result["status"] == "success":
                workflow_result["steps_completed"].append("dft_recommendations")
                print(f"✅ DFT recommendations generated: {dft_result['total_recommendations']} structures")
                print(f"📄 Recommendations saved: {os.path.basename(dft_result['dft_file'])}")
            else:
                print(f"⚠️  DFT recommendations failed: {dft_result.get('message', 'Unknown error')}")
        
        # === Step 5: Measurement Recommendations (Optional) ===
        if self.measurement_recommendations:
            step_number = "5" if (self.dft_recommendations and self.data_type == 'microscopy') else "4"
            print(f"\n📋 WORKFLOW STEP {step_number}: Measurement Recommendations")
            print(f"{'─'*50}")
            
            measurement_result = self._generate_measurement_recommendations(
                workflow_result["claims_generation"],
                workflow_result.get("novelty_assessment", {}),
                system_info
            )
            workflow_result["measurement_recommendations"] = measurement_result
            
            if measurement_result["status"] == "success":
                workflow_result["steps_completed"].append("measurement_recommendations")
                rec_count = measurement_result.get('total_recommendations', 0)
                print(f"✅ Measurement recommendations generated: {rec_count} suggestions")
                print(f"📄 Recommendations saved: {os.path.basename(measurement_result['recommendations_file'])}")
            else:
                print(f"⚠️  Measurement recommendations failed: {measurement_result.get('message', 'Unknown error')}")
        
        workflow_result["final_status"] = "success"
        
        # Save workflow log
        self._save_workflow_log(data_type_name)
        
        # Final summary
        self._print_final_summary(workflow_result, data_type_name)
        
        return workflow_result
    
    def _analyze_experimental_data(self, data_path: Union[str, Path],
                                     system_info: Dict[str, Any],
                                     **analysis_kwargs) -> Dict[str, Any]:
        """Analyze experimental data and generate claims."""

        print(f"🔨 Analyzing {self.data_type} data...")
        if self.display_agent_logs:
            print(f"    (Agent logs will appear below)")
            print(f"{'─'*30}")

        try:
            analysis_result = self.analyzer.analyze_for_claims(
                str(data_path),
                system_info=system_info,
                **analysis_kwargs
            )

            if self.display_agent_logs:
                print(f"{'─'*30}")

            if "error" in analysis_result:
                return {
                    "status": "error",
                    "message": analysis_result["error"]
                }

            claims = analysis_result.get("scientific_claims", [])
            detailed_analysis = analysis_result.get("detailed_analysis", "No analysis text provided.")

            if not claims:
                return {
                    "status": "error",
                    "message": "No scientific claims generated from analysis"
                }

            if analysis_result.get("human_feedback", {}).get("feedback_provided"):
                # If feedback was given, display the final, refined results.
                print("\n--- Analysis Summary (After Applying User Feedback) ---")
                self._display_analysis_summary(claims, detailed_analysis)
                
            # Save claims
            claims_file = self.output_dir / f"generated_{self.data_type}_claims.json"
            with open(claims_file, 'w') as f:
                json.dump(analysis_result, f, indent=2)

            return {
                "status": "success",
                "claims": claims,
                "claims_file": str(claims_file),
                "detailed_analysis": detailed_analysis
            }

        except Exception as e:
            if self.display_agent_logs:
                print(f"{'─'*30}")
            return {
                "status": "error",
                "message": f"Analysis failed: {str(e)}"
            }
            
        except Exception as e:
            if self.display_agent_logs:
                print(f"{'─'*30}")
            return {
                "status": "error",
                "message": f"Analysis failed: {str(e)}"
            }
    
    def _conduct_literature_search(self, claims: List[Dict[str, Any]]) -> Dict[str, Any]:
        """Conduct literature search for selected claims."""
        
        # Interactive claim selection with better formatting
        selected_claims = select_claims_interactive(claims)
        
        if not selected_claims:
            return {
                "status": "error",
                "message": "No claims selected for literature search"
            }
        
        print(f"🔍 Searching literature for {len(selected_claims)} claims...")
        if self.display_agent_logs:
            print(f"   (Literature agent logs will appear below)")
            print(f"{'─'*30}")
        
        try:
            literature_results = []
            
            for i, claim in enumerate(selected_claims):
                claim_num = i + 1
                total_claims = len(selected_claims)
                
                has_anyone_question = claim.get("has_anyone_question")
                if not has_anyone_question:
                    print(f"   ⚠️  Claim {claim_num}/{total_claims}: No search question available")
                    continue
                
                print(f"\n   🔍 Searching claim {claim_num}/{total_claims}...")
                if not self.display_agent_logs:
                    print(f"   Question: {has_anyone_question}")
                
                # Query literature (agent logs will appear here if display_agent_logs=True)
                owl_result = self.lit_agent.query_literature(has_anyone_question)
                
                if owl_result.get("status") == "success" and owl_result.get("formatted_answer"):
                    try:
                        # Create a dedicated directory for these readable responses
                        responses_dir = self.output_dir / "literature_responses"
                        responses_dir.mkdir(exist_ok=True)
                        
                        response_filename = f"literature_response_claim_{claim_num:02d}.md"
                        response_filepath = responses_dir / response_filename
                        
                        with open(response_filepath, 'w', encoding='utf-8') as f:
                            f.write(f"# Literature Response for Claim {claim_num}\n\n")
                            f.write(f"**Question:** {has_anyone_question}\n\n---\n\n")
                            f.write(owl_result["formatted_answer"])
                        
                        # Inform the user about the saved file
                        print(f"        📄 Saved formatted response: {response_filepath.relative_to(self.output_dir.parent)}")
                    except Exception as e:
                        print(f"        ⚠️  Could not save formatted response for claim {claim_num}: {e}")

                literature_results.append({
                    "original_claim": claim,
                    "owl_result": owl_result
                })
                
                # Show brief result
                if owl_result["status"] == "success":
                    print(f"   ✅ Search {claim_num}/{total_claims} complete")
                else:
                    print(f"   ❌ Search {claim_num}/{total_claims} failed: {owl_result.get('message', 'Unknown error')}")
            
            if self.display_agent_logs:
                print(f"{'─'*30}")
            
            # Save results
            results_file = self.output_dir / f"{self.data_type}_literature_search_results.json"
            with open(results_file, 'w') as f:
                json.dump(literature_results, f, indent=2)
            
            return {
                "status": "success",
                "results": literature_results,
                "results_file": str(results_file)
            }
            
        except Exception as e:
            if self.display_agent_logs:
                print(f"{'─'*30}")
            return {
                "status": "error",
                "message": f"Literature search failed: {str(e)}"
            }
    
    def _assess_novelty(self, literature_results: List[Dict[str, Any]], 
                       data_type_name: str) -> Dict[str, Any]:
        """Run enhanced novelty assessment with structured scoring."""
        
        print(f"🎯 Scoring novelty based on literature findings...")
        if self.display_agent_logs:
            print(f"   (Novelty scorer logs will appear below)")
            print(f"{'─'*30}")
        
        try:
            # Initialize novelty scorer
            novelty_scorer = NoveltyScorer(google_api_key=self.google_api_key)
            
            # Run enhanced assessment (scorer logs will appear here if display_agent_logs=True)
            novelty_assessment = enhanced_novelty_assessment(literature_results, novelty_scorer)
            
            if self.display_agent_logs:
                print(f"{'─'*30}")
            
            # Display results in DFT style
            self._display_novelty_summary(novelty_assessment)
            
            # Save assessment
            novelty_file = self.output_dir / f"{data_type_name}_enhanced_novelty_assessment.json"
            with open(novelty_file, 'w') as f:
                json.dump(novelty_assessment, f, indent=2)
            
            return {
                "status": "success",
                "assessment": novelty_assessment,
                "novelty_file": str(novelty_file)
            }
            
        except Exception as e:
            if self.display_agent_logs:
                print(f"{'─'*30}")
            return {
                "status": "error",
                "message": f"Novelty assessment failed: {str(e)}"
            }
    
    def _display_analysis_summary(self, claims: List[Dict[str, Any]], detailed_analysis: str):
        """Display generated claims and analysis in DFT-style format."""

        print("\n--- Analysis Summary (After User Feedback) ---")
        print("\n📋 DETAILED ANALYSIS:")
        print(detailed_analysis)

        print(f"\n🎯 GENERATED CLAIMS ({len(claims)}):")
        for i, claim in enumerate(claims, 1):
            claim_text = claim.get('claim', 'No claim text')
            print(f"    {i}. {claim_text}")

        if claims:
            keywords_count = sum(len(claim.get('keywords', [])) for claim in claims)
            print(f"    🏷️  Total keywords identified: {keywords_count}")
    
    def _display_novelty_summary(self, assessment: Dict[str, Any]):
        """Display novelty assessment in DFT-style format."""
        
        categories = assessment.get("novelty_categories", {})
        avg_score = assessment.get("average_novelty_score", 0)
        
        print(f"   📊 Novelty scoring complete:")
        print(f"      Average score: {avg_score:.2f}/5.0")
        
        high_novel = categories.get("highly_novel", [])
        moderate_novel = categories.get("moderately_novel", [])
        low_novel = categories.get("low_novelty", [])
        
        if high_novel:
            print(f"      🚀 Highly novel findings: {len(high_novel)}")
        if moderate_novel:
            print(f"      📈 Moderately novel findings: {len(moderate_novel)}")
        if low_novel:
            print(f"      📚 Known findings: {len(low_novel)}")
    
    def _print_final_summary(self, workflow_result: Dict[str, Any], data_type_name: str):
        """Print a clean final summary in DFT style."""
        
        print(f"\n🎉 Experiment Novelty Assessment Complete!")
        print(f"{'='*60}")
        
        # Basic info
        status = workflow_result.get('final_status')
        steps = workflow_result.get('steps_completed', [])
        
        print(f"📋 Status: {status}")
        print(f"✅ Steps: {' → '.join(steps)}")
        print(f"📁 Output: {self.output_dir}/")
        
        # Claims info
        if "claims_generation" in workflow_result:
            claims_result = workflow_result["claims_generation"]
            if claims_result["status"] == "success":
                claims_count = len(claims_result['claims'])
                print(f"🔍 Analysis: {claims_count} scientific claims generated")
        
        # Literature info
        if "literature_search" in workflow_result:
            lit_result = workflow_result["literature_search"]
            if lit_result["status"] == "success":
                search_count = len(lit_result['results'])
                print(f"📚 Literature: {search_count} claims searched")
        
        # Novelty info
        if "novelty_assessment" in workflow_result:
            assessment = workflow_result["novelty_assessment"]
            avg_score = assessment.get('average_novelty_score', 0)
            categories = assessment.get("novelty_categories", {})
            high_count = len(categories.get("highly_novel", []))
            
            print(f"🎯 Novelty: {avg_score:.2f}/5.0 average score")
            if high_count > 0:
                print(f"   🚀 {high_count} highly novel finding{'s' if high_count > 1 else ''}")
        
        # DFT info
        if "dft_recommendations" in workflow_result:
            dft_result = workflow_result["dft_recommendations"]
            if dft_result["status"] == "success":
                rec_count = dft_result.get('total_recommendations', 0)
                print(f"⚛️  DFT: {rec_count} structure recommendation{'s' if rec_count > 1 else ''}")
        
        # Measurement recommendations info (NEW)
        if "measurement_recommendations" in workflow_result:
            measurement_result = workflow_result["measurement_recommendations"]
            if measurement_result["status"] == "success":
                rec_count = measurement_result.get('total_recommendations', 0)
                print(f"📋 Measurements: {rec_count} recommendation{'s' if rec_count > 1 else ''}")
        
        print(f"{'='*60}")
    
    def _save_workflow_log(self, data_type_name: str):
        """Save the complete workflow log."""
        try:
            log_content = self.log_capture.getvalue()
            log_path = self.output_dir / f"{data_type_name}_novelty_workflow_log.txt"
            
            with open(log_path, 'w') as f:
                f.write(f"{data_type_name.title()} Novelty Assessment Workflow Log\n")
                f.write("=" * (len(data_type_name) + 35) + "\n\n")
                f.write(log_content)
                
        except Exception as e:
            print(f"⚠️  Could not save workflow log: {e}")
    
    def get_summary(self, workflow_result: Dict[str, Any]) -> str:
        """Get a human-readable summary of the workflow results."""
        
        data_type = workflow_result.get("data_type", "experimental")
        
        summary = f"{data_type.title()} Novelty Assessment Summary\n{'='*40}\n"
        summary += f"Data: {os.path.basename(str(workflow_result.get('data_path', 'Unknown')))}\n"
        summary += f"Status: {workflow_result.get('final_status', 'Unknown')}\n"
        summary += f"Steps completed: {', '.join(workflow_result.get('steps_completed', []))}\n\n"
        
        # Claims summary
        if "claims_generation" in workflow_result:
            claims_data = workflow_result["claims_generation"]
            claims_count = len(claims_data.get("claims", []))
            summary += f"Generated {claims_count} scientific claims\n\n"
        
        # Novelty assessment summary
        if "novelty_assessment" in workflow_result:
            assessment = workflow_result["novelty_assessment"]
            summary += f"Literature Assessment:\n"
            summary += f"  Total claims searched: {assessment.get('total_claims_searched', 0)}\n"
            summary += f"  Successfully scored: {assessment.get('successful_searches', 0)}\n"
            summary += f"  Average novelty score: {assessment.get('average_novelty_score', 0):.2f}/5.0\n\n"
            
            categories = assessment.get("novelty_categories", {})
            
            if categories.get("highly_novel"):
                summary += f"🚀 Potentially Highly Novel Findings ({len(categories['highly_novel'])}):\n"
                for i, claim in enumerate(categories["highly_novel"], 1):
                    summary += f"  {i}. {claim}\n"
                summary += "\n"
            
            if categories.get("moderately_novel"):
                summary += f"📊 Moderately Novel Findings ({len(categories['moderately_novel'])}):\n"
                for i, claim in enumerate(categories["moderately_novel"], 1):
                    summary += f"  {i}. {claim}\n"
                summary += "\n"
        
        # DFT recommendations summary
        if "dft_recommendations" in workflow_result and workflow_result["dft_recommendations"].get("status") == "success":
            dft_result = workflow_result["dft_recommendations"]
            summary += f"DFT Recommendations: {dft_result.get('total_recommendations', 0)} structures recommended\n"
        
        return summary
    
    def _display_dft_recommendations(self, reasoning: str, recommendations: List[Dict], novel_claims: List[str]):
        """Display the generated DFT recommendations."""
        
        print("\n" + "="*60)
        print("DFT STRUCTURE RECOMMENDATIONS")
        print("="*60)
        
        print(f"\nNovel claims processed: {len(novel_claims)}")
        print(f"Total recommendations: {len(recommendations)}")
        
        print(f"\n--- Reasoning ---")
        print(reasoning)
        print("-" * 40)
        
        if recommendations:
            print("\n--- Recommended Structures ---")
            for i, rec in enumerate(recommendations, 1):
                print(f"\n[{i}] Priority: {rec.get('priority', 'N/A')}")
                print(f"    {rec.get('description', 'N/A')}")
                print(f"    Justification: {rec.get('scientific_interest', 'N/A')}")
        else:
            print("\n⚠️  No recommendations generated")
        
        print("\n" + "="*60)
    
    def _generate_dft_recommendations(self, initial_analysis_text: str, novelty_assessment: Dict[str, Any]) -> Dict[str, Any]:
        """Generate DFT recommendations based on enhanced novelty analysis (microscopy only)"""
        
        print(f"⚛️  Generating DFT structure recommendations...")
        
        try:
            # Extract high and moderate novelty claims for prioritization
            high_novel = novelty_assessment.get("novelty_categories", {}).get("highly_novel", [])
            moderate_novel = novelty_assessment.get("novelty_categories", {}).get("moderately_novel", [])
            
            # Generate enhanced novelty context for DFT recommendations
            if high_novel or moderate_novel:
                novelty_section_text = "The following claims/observations have been assessed through literature review with their novelty scores:\n\n"
                
                if high_novel:
                    novelty_section_text += "HIGH NOVELTY FINDINGS (Scores 4-5):\n"
                    for i, claim in enumerate(high_novel, 1):
                        novelty_section_text += f"{i}. {claim}\n"
                    novelty_section_text += "\n"
                
                if moderate_novel:
                    novelty_section_text += "MODERATE NOVELTY FINDINGS (Score 3):\n"
                    for i, claim in enumerate(moderate_novel, 1):
                        novelty_section_text += f"{i}. {claim}\n"
                    novelty_section_text += "\n"
                
                avg_score = novelty_assessment.get("average_novelty_score", 0)
                novelty_section_text += f"Average novelty score: {avg_score:.2f}/5.0\n\n"
                
                novelty_section_text += ("Your primary goal for the DFT recommendations should be to propose structures and simulations "
                                    "that can rigorously investigate these novel aspects, with priority given to the highest-scoring claims. "
                                    "Explain the connection between each recommended structure and the specific novel findings it would help investigate.")
                
                novelty_context = novelty_section_text
            else:
                novelty_context = "No high-novelty claims were identified through literature review. Please make DFT recommendations based on the most scientifically interesting aspects of the provided analysis."
            
            # Instantiate a text-only analysis agent for this step
            dft_agent = MicroscopyAnalysisAgent(
                google_api_key=self.google_api_key,
                model_name=self.analysis_model
            )
            
            # Generate DFT recommendations using text-only path
            dft_recommendations_result = dft_agent.analyze_microscopy_image_for_structure_recommendations(
                image_path=None,  # Text-only path
                system_info=None,
                additional_prompt_context=novelty_context,
                cached_detailed_analysis=initial_analysis_text
            )
            
            if "error" in dft_recommendations_result:
                return {
                    "status": "error",
                    "message": f"DFT recommendation generation failed: {dft_recommendations_result.get('details', dft_recommendations_result.get('error'))}"
                }
            
            reasoning_text = dft_recommendations_result.get("analysis_summary_or_reasoning", "No reasoning provided")
            recommendations = dft_recommendations_result.get("recommendations", [])
            
            print(f"   ✅ Generated {len(recommendations)} DFT structure recommendations")
            
            self._display_dft_recommendations(reasoning_text, recommendations, high_novel + moderate_novel)

            # Save DFT recommendations
            dft_file = self.output_dir / "dft_recommendations.json"
            dft_output = {
                "reasoning_for_recommendations": reasoning_text,
                "recommendations": recommendations,
                "novelty_context": novelty_context,
                "novelty_scores_used": {
                    "high_novel_count": len(high_novel),
                    "moderate_novel_count": len(moderate_novel),
                    "average_score": novelty_assessment.get("average_novelty_score", 0)
                }
            }
            with open(dft_file, 'w') as f:
                json.dump(dft_output, f, indent=2)
            
            return {
                "status": "success",
                "recommendations": recommendations,
                "reasoning": reasoning_text,
                "dft_file": str(dft_file),
                "total_recommendations": len(recommendations)
            }
            
        except Exception as e:
            return {
                "status": "error",
                "message": f"DFT recommendations failed: {str(e)}"
            }
        
    def _generate_measurement_recommendations(self, 
                                            claims_result: Dict[str, Any],
                                            novelty_assessment: Dict[str, Any],
                                            system_info: Dict[str, Any]) -> Dict[str, Any]:
        """Generate measurement recommendations using the stored analysis agent."""
        
        print(f"🤖 Generating measurement recommendations...")
        
        try:
            # Create novelty context
            novelty_context = self._create_novelty_context(novelty_assessment)
            
            # Use the stored agent that already did the analysis
            if not hasattr(self.analyzer, 'analysis_agent') or self.analyzer.analysis_agent is None:
                return {
                    "status": "error", 
                    "message": "No analysis agent available - analysis may have failed"
                }
            
            agent = self.analyzer.analysis_agent
            
            # The agent already has all stored analysis images and proper context
            recommendations_result = agent.generate_measurement_recommendations(
                analysis_result=claims_result,
                system_info=system_info,
                novelty_context=novelty_context
            )
            
            if "error" in recommendations_result:
                return {"status": "error", "message": recommendations_result["error"]}
            
            # Display recommendations summary
            self._display_measurement_recommendations_summary(recommendations_result)
            
            # Save recommendations
            rec_file = self.output_dir / f"{self.data_type}_measurement_recommendations.json"
            with open(rec_file, 'w') as f:
                json.dump(recommendations_result, f, indent=2)
            
            return {
                "status": "success",
                "total_recommendations": recommendations_result.get("total_recommendations", 0),
                "recommendations_file": str(rec_file)
            }
            
        except Exception as e:
            self.logger.exception("Failed to generate measurement recommendations")
            return {"status": "error", "message": str(e)}
    
    def _create_novelty_context(self, novelty_assessment: Dict[str, Any]) -> str:
        """Create novelty context for measurement recommendations."""
        
        categories = novelty_assessment.get("novelty_categories", {})
        avg_score = novelty_assessment.get("average_novelty_score", 0)
        
        high_novel = categories.get("highly_novel", [])
        moderate_novel = categories.get("moderately_novel", [])
        
        if not high_novel and not moderate_novel:
            return "No high-novelty findings identified. Focus on standard follow-up measurements."
        
        context = f"Literature review indicates significant novelty (average score: {avg_score:.2f}/5.0). "
        context += "Prioritize measurements that can investigate these novel aspects:\n\n"
        
        if high_novel:
            context += "HIGH NOVELTY FINDINGS:\n"
            for i, claim in enumerate(high_novel, 1):
                context += f"{i}. {claim}\n"
            context += "\n"
        
        if moderate_novel:
            context += "MODERATE NOVELTY FINDINGS:\n"
            for i, claim in enumerate(moderate_novel, 1):
                context += f"{i}. {claim}\n"
            context += "\n"
        
        context += "Focus measurements on validating, expanding, or providing complementary evidence."
        return context
    
    def _display_measurement_recommendations_summary(self, recommendations_result: Dict[str, Any]):
        """Display detailed top recommendations and summary for workflow with improved formatting."""
        
        recommendations = recommendations_result.get("measurement_recommendations", [])
        if not recommendations:
            print("   ⚠️  No recommendations generated")
            return
            
        print(f"   🎯 Generated {len(recommendations)} measurement recommendations.")
        
        num_to_show_detail = min(len(recommendations), 3)

        print(f"\n   📋 TOP {num_to_show_detail} RECOMMENDATION{'S' if num_to_show_detail > 1 else ''}")

        # --- Display each of the top recommendations in detail ---
        for i, rec in enumerate(recommendations[:num_to_show_detail], 1):
            # Header for each recommendation
            print(f"\n   {'─' * 70}")
            print(f"   [ {i} ] Recommendation (Priority: {rec.get('priority', 'N/A')})")
            print(f"   {'─' * 70}")

            detail_keys = {
                "category": "Category",
                "description": "Description",
                "target_regions": "Target Regions",
                "scientific_justification": "Justification",
                "expected_outcomes": "Expected Outcomes"
            }
            
            base_indent = "     "
            # Set width based on the longest label to align colons
            label_column_width = max(len(label) for label in detail_keys.values())
            
            keys_to_print = [key for key in detail_keys if rec.get(key)]

            for idx, key in enumerate(keys_to_print):
                label = detail_keys[key]
                value = rec[key]

                # Pad the label, then add the colon and a guaranteed space
                formatted_label = f"{label}:".ljust(label_column_width + 2)
                
                # The prefix for the first line of text
                prefix = base_indent + formatted_label
                
                # The indent for subsequent wrapped lines
                subsequent_indent = ' ' * len(prefix)
                
                wrapped_text = textwrap.fill(
                    str(value),
                    width=80,
                    initial_indent=prefix,
                    subsequent_indent=subsequent_indent
                )
                print(wrapped_text)
                
                # Add a blank line if this is not the last item being printed
                if idx < len(keys_to_print) - 1:
                    print()

        # --- Show a compact summary for any remaining recommendations ---
        if len(recommendations) > num_to_show_detail:
            remaining_count = len(recommendations) - num_to_show_detail
            print(f"\n   {'─' * 70}")
            print(f"   📝 Additional {remaining_count} recommendation{'s' if remaining_count > 1 else ''}:")
            
            for i, rec in enumerate(recommendations[num_to_show_detail:], num_to_show_detail + 1):
                category = rec.get("category", "Unknown")
                priority = rec.get("priority", "N/A")
                print(f"     [{i}] {category} (Priority {priority})")
            
        print(f"\n   📄 See saved JSON file for complete details of all recommendations.")


