""" Tool functions for Spec-Agent: Chemical validation and mass calculation. These tools are called by the LLM agent during the ReAct loop. """ from typing import Dict, Optional, Tuple from rdkit import Chem from rdkit.Chem import Descriptors try: import selfies as sf SELFIES_AVAILABLE = True except ImportError: SELFIES_AVAILABLE = False sf = None def validate_smiles(smiles: str) -> Dict[str, str]: """ Validate a SMILES string and return detailed error information if invalid. Args: smiles: SMILES string to validate Returns: Dictionary with: - "valid": "True" or "False" - "message": Detailed error message if invalid, "Valid SMILES" if valid - "error_type": Type of error (e.g., "Unclosed ring", "Invalid atom", etc.) """ if not smiles or not isinstance(smiles, str): return { "valid": "False", "message": f"Invalid input: expected string, got {type(smiles)}", "error_type": "TypeError" } # Try to parse SMILES mol = Chem.MolFromSmiles(smiles) if mol is None: # Try to get more detailed error information try: # Attempt to sanitize to get specific error mol = Chem.MolFromSmiles(smiles, sanitize=False) if mol is None: return { "valid": "False", "message": f"SMILES '{smiles}' cannot be parsed. Check for syntax errors (unmatched brackets, invalid characters).", "error_type": "ParseError" } # Try sanitization to get specific error try: Chem.SanitizeMol(mol) except Exception as e: error_msg = str(e) if "Unclosed ring" in error_msg or "ring" in error_msg.lower(): return { "valid": "False", "message": f"Unclosed ring detected in SMILES '{smiles}'. Check ring closure numbers.", "error_type": "RingError" } elif "valence" in error_msg.lower(): return { "valid": "False", "message": f"Valence error in SMILES '{smiles}'. Atom has incorrect number of bonds.", "error_type": "ValenceError" } else: return { "valid": "False", "message": f"Sanitization error: {error_msg}", "error_type": "SanitizationError" } except Exception as e: return { "valid": "False", "message": f"Cannot parse SMILES '{smiles}': {str(e)}", "error_type": "ParseError" } # SMILES is valid return { "valid": "True", "message": "Valid SMILES", "error_type": "None" } def calculate_mass_error(smiles: str, target_mass: float, tolerance_ppm: float = 10.0) -> Dict[str, str]: """ Calculate the mass error between a SMILES molecule and target mass. Args: smiles: SMILES string target_mass: Target molecular mass (Da) tolerance_ppm: Mass tolerance in parts per million (default: 10 ppm) Returns: Dictionary with: - "matches": "True" or "False" - "predicted_mass": Calculated mass - "target_mass": Target mass - "error_da": Absolute error in Da - "error_ppm": Error in ppm - "message": Human-readable message with suggestions """ # First validate SMILES validation = validate_smiles(smiles) if validation["valid"] == "False": return { "matches": "False", "predicted_mass": "0.0", "target_mass": str(target_mass), "error_da": "N/A", "error_ppm": "N/A", "message": f"Cannot calculate mass: {validation['message']}" } # Calculate exact mass mol = Chem.MolFromSmiles(smiles) predicted_mass = Descriptors.ExactMolWt(mol) # Calculate errors error_da = abs(predicted_mass - target_mass) error_ppm = (error_da / target_mass) * 1e6 if target_mass > 0 else float('inf') # Check if within tolerance matches = error_ppm <= tolerance_ppm # Generate helpful message if matches: message = f"Mass matches! Predicted: {predicted_mass:.4f} Da, Target: {target_mass:.4f} Da (Error: {error_ppm:.2f} ppm)" else: diff = predicted_mass - target_mass suggestions = [] # Common mass differences and their meanings common_diffs = { 1.0078: "Missing H+ (protonation)", -1.0078: "Extra H+", 15.9949: "Missing O (oxygen)", -15.9949: "Extra O", 14.0157: "Missing CH2 (methylene)", -14.0157: "Extra CH2", 18.0106: "Missing H2O (water)", -18.0106: "Extra H2O", 28.0313: "Missing C2H4 (ethylene)", -28.0313: "Extra C2H4", } # Find closest common difference for common_diff, meaning in common_diffs.items(): if abs(diff - common_diff) < 0.1: suggestions.append(meaning) if not suggestions: if diff > 0: if abs(diff) > 200: suggestions.append(f"Predicted mass is {diff:.2f} Da too high. Remove significant structural elements (rings, large functional groups).") elif abs(diff) > 50: suggestions.append(f"Predicted mass is {diff:.2f} Da too high. Remove multiple atoms or simplify rings.") else: suggestions.append(f"Predicted mass is {diff:.2f} Da too high. Consider removing atoms or groups.") else: if abs(diff) > 200: suggestions.append(f"Predicted mass is {abs(diff):.2f} Da too low. Add significant structural elements (rings, peptide bonds, large functional groups). Use reference molecules as templates.") elif abs(diff) > 50: suggestions.append(f"Predicted mass is {abs(diff):.2f} Da too low. Add multiple atoms or rings. The molecule needs to be larger and more complex.") else: suggestions.append(f"Predicted mass is {abs(diff):.2f} Da too low. Consider adding atoms or groups.") message = ( f"Mass mismatch! Predicted: {predicted_mass:.4f} Da, Target: {target_mass:.4f} Da. " f"Error: {error_ppm:.2f} ppm (tolerance: {tolerance_ppm} ppm). " f"Suggestions: {', '.join(suggestions)}" ) return { "matches": "True" if matches else "False", "predicted_mass": f"{predicted_mass:.4f}", "target_mass": f"{target_mass:.4f}", "error_da": f"{error_da:.4f}", "error_ppm": f"{error_ppm:.2f}", "message": message } def selfies_to_smiles(selfies_str: str) -> Tuple[bool, str]: """ Convert SELFIES string to SMILES. SELFIES guarantees validity. Args: selfies_str: SELFIES string Returns: Tuple of (success: bool, smiles: str) """ if not SELFIES_AVAILABLE: return False, "SELFIES library not available" try: smiles = sf.decoder(selfies_str) return True, smiles except Exception as e: return False, f"SELFIES decode error: {str(e)}" def smiles_to_selfies(smiles: str) -> Tuple[bool, str]: """ Convert SMILES string to SELFIES. Args: smiles: SMILES string Returns: Tuple of (success: bool, selfies: str) """ if not SELFIES_AVAILABLE: return False, "SELFIES library not available" try: # First validate SMILES mol = Chem.MolFromSmiles(smiles) if mol is None: return False, "Invalid SMILES" selfies_str = sf.encoder(smiles) return True, selfies_str except Exception as e: return False, f"SELFIES encode error: {str(e)}" def get_tool_descriptions() -> str: """ Get formatted tool descriptions for LLM prompt. Returns: String describing available tools and their usage """ desc = """ Available Tools: 1. validate_smiles(smiles: str) -> dict Validates a SMILES string and returns detailed error information. Returns: {"valid": "True"/"False", "message": str, "error_type": str} 2. calculate_mass_error(smiles: str, target_mass: float, tolerance_ppm: float = 10.0) -> dict Calculates mass error between predicted and target mass. Returns: {"matches": "True"/"False", "predicted_mass": str, "target_mass": str, "error_da": str, "error_ppm": str, "message": str} """ if SELFIES_AVAILABLE: desc += """ 3. selfies_to_smiles(selfies: str) -> tuple Converts SELFIES string to SMILES. SELFIES guarantees validity. Returns: (success: bool, smiles: str) IMPORTANT: Use SELFIES format for generation! SELFIES guarantees valid molecular structures. Any SELFIES string can be converted to valid SMILES. Example: [C][C][O] for ethanol. """ else: desc += """ Note: SELFIES support not available. Install with: pip install selfies """ desc += """ Usage Example: validation = validate_smiles("CCO") if validation["valid"] == "False": # Fix the error based on validation["message"] mass_check = calculate_mass_error("CCO", 46.0419, tolerance_ppm=10.0) if mass_check["matches"] == "False": # Adjust structure based on mass_check["message"] """ return desc