| """ |
| Spec-Agent: Llama-3 based agentic molecular structure prediction with self-correction. |
| |
| This module implements a ReAct-style agent that: |
| 1. Generates candidate SMILES using Llama-3 |
| 2. Validates SMILES syntax using RDKit |
| 3. Checks mass accuracy against target spectrum |
| 4. Iteratively refines predictions based on error feedback |
| """ |
|
|
| from __future__ import annotations |
|
|
| import json |
| import re |
| from typing import Any, Dict, List, Optional |
| from pathlib import Path |
|
|
| try: |
| from typing import TypedDict |
| except ImportError: |
| try: |
| from typing_extensions import TypedDict |
| except ImportError: |
| TypedDict = dict |
|
|
| try: |
| from unsloth import FastLanguageModel |
| from unsloth.chat_templates import get_chat_template |
| UNSLOTH_AVAILABLE = True |
| except ImportError: |
| UNSLOTH_AVAILABLE = False |
| FastLanguageModel = None |
|
|
| from transformers import AutoTokenizer, AutoModelForCausalLM |
| import torch |
|
|
| try: |
| from huggingface_hub import InferenceClient |
| HF_API_AVAILABLE = True |
| except ImportError: |
| HF_API_AVAILABLE = False |
| InferenceClient = None |
|
|
| from .agent_tools import ( |
| validate_smiles, |
| calculate_mass_error, |
| get_tool_descriptions, |
| selfies_to_smiles, |
| smiles_to_selfies, |
| SELFIES_AVAILABLE, |
| ) |
|
|
|
|
| class AgentState(TypedDict): |
| """State maintained throughout the agentic loop.""" |
| messages: List[Dict[str, str]] |
| candidate_smiles: Optional[str] |
| spectrum_embedding: Optional[torch.Tensor] |
| rag_context: List[str] |
| target_mass: Optional[float] |
| iteration: int |
| status: str |
| error_history: List[str] |
|
|
|
|
| class SpecAgent: |
| """ |
| Self-correcting agent for molecular structure prediction from mass spectra. |
| |
| Uses Llama-3 with tool calling to iteratively generate and refine SMILES predictions. |
| """ |
| |
| def __init__( |
| self, |
| model_name: str = "meta-llama/Meta-Llama-3-8B-Instruct", |
| use_unsloth: bool = False, |
| use_api: bool = False, |
| api_token: str | None = None, |
| max_iterations: int = 5, |
| mass_tolerance_ppm: float = 10.0, |
| device: str = "cuda" if torch.cuda.is_available() else "cpu", |
| load_in_4bit: bool = True, |
| use_selfies: bool = True, |
| ): |
| """ |
| Initialize Spec-Agent. |
| |
| Args: |
| model_name: HuggingFace model name or path |
| use_unsloth: Whether to use Unsloth for fast inference |
| use_api: Whether to use HuggingFace Inference API (no local model needed) |
| api_token: HuggingFace API token (if None, uses HF_TOKEN env var) |
| max_iterations: Maximum number of refinement iterations |
| mass_tolerance_ppm: Mass tolerance in ppm for validation |
| device: Device to run model on (ignored if use_api=True) |
| load_in_4bit: Load model in 4-bit quantization (ignored if use_api=True) |
| use_selfies: Use SELFIES format instead of SMILES (guarantees validity) |
| """ |
| self.model_name = model_name |
| self.use_unsloth = use_unsloth and UNSLOTH_AVAILABLE |
| self.use_api = use_api and HF_API_AVAILABLE |
| self.api_token = api_token |
| self.max_iterations = max_iterations |
| self.mass_tolerance_ppm = mass_tolerance_ppm |
| self.device = device |
| self.load_in_4bit = load_in_4bit |
| self.use_selfies = use_selfies and SELFIES_AVAILABLE |
| |
| if use_selfies and not SELFIES_AVAILABLE: |
| print("⚠ SELFIES requested but not available. Install with: pip install selfies") |
| print("⚠ Falling back to SMILES format") |
| self.use_selfies = False |
| |
| if self.use_api: |
| |
| if not HF_API_AVAILABLE: |
| raise ImportError("huggingface_hub is required for API mode. Install with: pip install huggingface_hub") |
| self._init_api_client() |
| else: |
| |
| self._load_model() |
| |
| |
| self.tools = { |
| "validate_smiles": validate_smiles, |
| "calculate_mass_error": calculate_mass_error, |
| } |
| if self.use_selfies and SELFIES_AVAILABLE: |
| self.tools["selfies_to_smiles"] = selfies_to_smiles |
| |
| def _init_api_client(self): |
| """Initialize HuggingFace Inference API client.""" |
| import os |
| token = self.api_token or os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACE_HUB_TOKEN") |
| if not token: |
| raise ValueError( |
| "HuggingFace API token required. Set HF_TOKEN env var or pass --api-token" |
| ) |
| |
| |
| try: |
| self.client = InferenceClient(model=self.model_name, token=token) |
| print(f"✓ Initialized HuggingFace Inference API client for {self.model_name}") |
| except Exception as e: |
| print(f"⚠ Warning: Could not initialize InferenceClient: {e}") |
| print("⚠ Will use direct API calls with router endpoint") |
| self.client = None |
| |
| def _load_model(self): |
| """Load Llama-3 model with Unsloth (if available) or standard transformers.""" |
| print(f"Loading model: {self.model_name}") |
| |
| if self.use_unsloth: |
| try: |
| |
| self.model, self.tokenizer = FastLanguageModel.from_pretrained( |
| model_name=self.model_name, |
| max_seq_length=4096, |
| dtype=None, |
| load_in_4bit=True, |
| ) |
| |
| FastLanguageModel.for_inference(self.model) |
| print("✓ Loaded with Unsloth (4-bit quantized)") |
| except Exception as e: |
| print(f"⚠ Unsloth loading failed: {e}. Falling back to transformers.") |
| self.use_unsloth = False |
| |
| if not self.use_unsloth: |
| |
| self.tokenizer = AutoTokenizer.from_pretrained(self.model_name) |
| if self.tokenizer.pad_token is None: |
| self.tokenizer.pad_token = self.tokenizer.eos_token |
| |
| |
| from transformers import BitsAndBytesConfig |
| quantization_config = None |
| if self.load_in_4bit and self.device == "cuda": |
| try: |
| quantization_config = BitsAndBytesConfig( |
| load_in_4bit=True, |
| bnb_4bit_compute_dtype=torch.float16, |
| bnb_4bit_use_double_quant=True, |
| bnb_4bit_quant_type="nf4", |
| ) |
| print("✓ Using 4-bit quantization") |
| except Exception as e: |
| print(f"⚠ 4-bit quantization not available: {e}. Using full precision.") |
| quantization_config = None |
| |
| self.model = AutoModelForCausalLM.from_pretrained( |
| self.model_name, |
| quantization_config=quantization_config, |
| torch_dtype=torch.float16 if self.device == "cuda" and not quantization_config else torch.float32, |
| device_map="auto" if self.device == "cuda" else None, |
| trust_remote_code=True, |
| ) |
| if self.device == "cpu": |
| self.model = self.model.to(self.device) |
| print("✓ Loaded with transformers") |
| |
| def _build_system_prompt( |
| self, |
| spectrum_peaks: Optional[List[float] | List[tuple[float, float]]] = None, |
| rag_context: Optional[List[str]] = None, |
| target_mass: Optional[float] = None, |
| ) -> str: |
| """ |
| Build system prompt with context about spectrum, RAG references, and tools. |
| |
| Args: |
| spectrum_peaks: List of major m/z peaks (optional) |
| rag_context: List of retrieved SMILES from RAG (optional) |
| target_mass: Target molecular mass (optional) |
| |
| Returns: |
| System prompt string |
| """ |
| if self.use_selfies: |
| format_instruction = """You are an expert mass spectrometrist and computational chemist specializing in de novo molecular structure elucidation from mass spectrometry data. |
| |
| TASK: Predict the complete molecular structure from mass spectrum data. |
| |
| CRITICAL REQUIREMENTS (in priority order): |
| 1. MOLECULAR SIZE: Generate COMPLEX molecules (30-100 atoms). The target mass indicates a large, complex structure - NOT simple molecules like methane (CH4), ethanol (C2H6O), or acetone (C3H6O). |
| 2. STRUCTURAL TEMPLATE: Use the provided reference molecules as your PRIMARY structural template. They are retrieved because they are structurally similar to your target. Start with one of them and modify it to match the target mass and spectrum peaks. |
| 3. MASS MATCHING: Your prediction MUST match the target molecular mass within 10 Da. If the mass is wrong, the structure is wrong. |
| 4. SPECTRUM PEAKS: The major peaks indicate key fragments. Use them to validate your structure - if a peak at m/z 134 appears, your structure should be able to fragment to produce that ion. |
| 5. OUTPUT FORMAT: Output ONLY valid SELFIES format, nothing else. |
| |
| VALID SELFIES TOKENS (use only these): |
| - Atoms: [C], [N], [O], [S], [P], [F], [Cl], [Br], [I], [H] |
| - Bonds: [=C], [=N], [=O], [#C], [#N] (double/triple bonds) |
| - Branches: [Branch1], [Branch2], [Ring1], [Ring2] |
| - Do NOT use: [M], [MOL], [ATOM], [BOND], or any other invalid tokens |
| |
| SELFIES Format Rules: |
| 1. Each atom must be in square brackets: [C], [N], [O] |
| 2. Double bonds: [=C], [=N], [=O] |
| 3. Triple bonds: [#C], [#N] |
| 4. Branches: [Branch1], [Branch2] |
| 5. Rings: [Ring1], [Ring2] |
| |
| WORKFLOW: |
| 1. Look at the target mass - this tells you the molecule size (e.g., 800 Da ≈ 50-60 atoms) |
| 2. Examine the reference molecules - pick the one closest in size/structure |
| 3. Modify the reference molecule to match the target mass (add/remove atoms as needed) |
| 4. Verify the structure can produce the observed spectrum peaks |
| 5. Output the complete SELFIES string |
| |
| Output Format: |
| - Output ONLY the SELFIES string, nothing else |
| - No explanations, no markdown, no "SELFIES:" prefix |
| - Generate the COMPLETE structure matching the target mass |
| |
| """ |
| else: |
| format_instruction = """You are an expert mass spectrometrist and computational chemist specializing in de novo molecular structure elucidation from mass spectrometry data. |
| |
| TASK: Predict the complete molecular structure (SMILES) from mass spectrum data. |
| |
| CRITICAL REQUIREMENTS (in priority order): |
| 1. MOLECULAR SIZE: Generate COMPLEX molecules (30-100 atoms). The target mass indicates a large, complex structure - NOT simple molecules like methane (CH4), ethanol (C2H6O), or acetone (C3H6O). |
| 2. STRUCTURAL TEMPLATE: Use the provided reference molecules as your PRIMARY structural template. They are retrieved because they are structurally similar to your target. Start with one of them and modify it to match the target mass and spectrum peaks. |
| 3. MASS MATCHING: Your prediction MUST match the target molecular mass within 10 Da. If the mass is wrong, the structure is wrong. |
| 4. SPECTRUM PEAKS: The major peaks indicate key fragments. Use them to validate your structure - if a peak at m/z 134 appears, your structure should be able to fragment to produce that ion. |
| 5. OUTPUT FORMAT: Output ONLY valid SMILES strings. No explanations, no markdown, just the SMILES. |
| |
| WORKFLOW: |
| Step 1: Analyze the target mass |
| - Mass 200-400 Da → ~20-30 atoms |
| - Mass 400-600 Da → ~30-45 atoms |
| - Mass 600-800 Da → ~45-60 atoms |
| - Mass 800+ Da → ~60-100 atoms |
| |
| Step 2: Select the best reference molecule |
| - Compare reference molecules to target mass (masses are provided) |
| - Pick the one closest in size/structure |
| - Use it as your starting template |
| |
| Step 3: Modify the template |
| - Adjust atoms/rings to match target mass |
| - Ensure structure can produce observed peaks |
| - Maintain chemical validity |
| |
| Step 4: Validate and refine |
| - Use validate_smiles() to check syntax |
| - Use calculate_mass_error() to verify mass (must be < 10 Da) |
| - If mass error > 50 Da, you need significant structural changes |
| - If mass error < 50 Da, make minor adjustments |
| |
| Common fixes: |
| - Unclosed rings: Check ring closure numbers (e.g., C1CCCC1 for cyclopentane) |
| - Valence errors: Ensure atoms have correct number of bonds |
| - Mass too small (>50 Da error): Add rings, peptide bonds, or large functional groups. Use reference molecules as size guide. |
| - Mass too large (>50 Da error): Remove atoms or simplify rings |
| |
| KEY PRINCIPLES: |
| 1. NEVER generate simple molecules (CH4, C2H6O, C3H6O) - these are wrong |
| 2. ALWAYS start from a reference molecule - modify it, don't create from scratch |
| 3. Match the target mass EXACTLY - mass error > 50 Da means wrong structure |
| 4. Use spectrum peaks to validate - your structure must be able to fragment to produce them |
| |
| Remember: The reference molecules show you the expected complexity. Your prediction should be similar in size and structure. |
| |
| """ |
| |
| prompt = format_instruction |
| |
| if target_mass: |
| prompt += f"Target molecular mass: {target_mass:.4f} Da\n" |
| |
| if spectrum_peaks and len(spectrum_peaks) > 0: |
| |
| |
| peak_strings = [] |
| for p in spectrum_peaks: |
| if isinstance(p, (list, tuple)) and len(p) >= 2: |
| |
| mz, intensity = float(p[0]), float(p[1]) |
| peak_strings.append(f'{mz:.2f} (intensity: {intensity:.3f})') |
| else: |
| |
| peak_strings.append(f'{float(p):.2f}') |
| |
| peaks_str = ', '.join(peak_strings) |
| prompt += f"Major spectrum peaks (m/z with relative intensity): {peaks_str}\n" |
| else: |
| |
| import sys |
| if hasattr(sys, '_getframe'): |
| pass |
| |
| if rag_context: |
| format_label = "SELFIES format" if self.use_selfies else "SMILES format" |
| prompt += f"\n{'='*60}\n" |
| prompt += f"REFERENCE MOLECULES (STRUCTURAL TEMPLATES) - {format_label}\n" |
| prompt += f"{'='*60}\n" |
| prompt += "These molecules were retrieved because they are STRUCTURALLY SIMILAR to your target.\n" |
| prompt += "STRATEGY: Pick the reference molecule closest to the target mass, then modify it.\n\n" |
| |
| |
| ref_masses = [] |
| try: |
| from rdkit import Chem |
| from rdkit.Chem import Descriptors |
| for smiles in rag_context[:5]: |
| try: |
| mol = Chem.MolFromSmiles(smiles) |
| if mol: |
| mass = Descriptors.ExactMolWt(mol) |
| ref_masses.append(mass) |
| else: |
| ref_masses.append(None) |
| except: |
| ref_masses.append(None) |
| except ImportError: |
| |
| ref_masses = [None] * min(5, len(rag_context)) |
| |
| for i, (smiles, ref_mass) in enumerate(zip(rag_context[:5], ref_masses), 1): |
| |
| if self.use_selfies and SELFIES_AVAILABLE: |
| success, selfies_str = smiles_to_selfies(smiles) |
| if success: |
| mass_info = f" (mass: {ref_mass:.2f} Da)" if ref_mass else "" |
| prompt += f" Template {i}{mass_info}:\n {selfies_str}\n" |
| else: |
| mass_info = f" (mass: {ref_mass:.2f} Da)" if ref_mass else "" |
| prompt += f" Template {i}{mass_info}:\n {smiles} (SMILES)\n" |
| else: |
| mass_info = f" (mass: {ref_mass:.2f} Da)" if ref_mass else "" |
| prompt += f" Template {i}{mass_info}:\n {smiles}\n" |
| |
| if target_mass: |
| |
| if ref_masses and any(m for m in ref_masses if m): |
| valid_masses = [(i+1, m) for i, m in enumerate(ref_masses) if m] |
| if valid_masses: |
| closest = min(valid_masses, key=lambda x: abs(x[1] - target_mass)) |
| prompt += f"\nRECOMMENDATION: Template {closest[0]} is closest to target mass ({closest[1]:.2f} Da vs {target_mass:.4f} Da). Start with this one.\n" |
| |
| prompt += f"\n{'='*60}\n" |
| prompt += "YOUR TASK: Modify one of these templates to match the target mass and spectrum.\n" |
| prompt += "Your prediction should be similar in SIZE and STRUCTURE to these references.\n" |
| |
| prompt += "\n" + get_tool_descriptions() |
| |
| |
| return prompt |
| |
| def _extract_smiles_from_response(self, response: str) -> Optional[str]: |
| """ |
| Extract SMILES or SELFIES string from LLM response. |
| If SELFIES is used, convert to SMILES. |
| |
| Handles various formats: |
| - Plain SMILES/SELFIES: "CCO" or "[C][C][O]" |
| - Markdown code blocks: "```smiles\nCCO\n```" |
| - JSON: '{"smiles": "CCO"}' |
| - Text with SMILES/SELFIES: "The molecule is CCO" |
| |
| Args: |
| response: LLM response text |
| |
| Returns: |
| Extracted SMILES string (converted from SELFIES if needed) or None |
| """ |
| |
| response = re.sub(r'```[a-z]*\n?', '', response) |
| response = re.sub(r'```', '', response) |
| response = response.strip() |
| |
| |
| try: |
| data = json.loads(response) |
| if isinstance(data, dict): |
| if "smiles" in data: |
| return data["smiles"] |
| if "selfies" in data: |
| if self.use_selfies: |
| success, smiles = selfies_to_smiles(data["selfies"]) |
| return smiles if success else None |
| return None |
| except: |
| pass |
| |
| |
| if self.use_selfies: |
| |
| |
| selfies_pattern = r'\[[^\]]+\](?:\[[^\]]+\])+' |
| matches = re.findall(selfies_pattern, response) |
| |
| |
| invalid_tokens = ['[M]', '[MOL]', '[ATOM]', '[BOND]', '[SMILES]', '[SELFIES]', '[Output]', '[Answer]'] |
| |
| for match in matches: |
| |
| if any(inv_token in match for inv_token in invalid_tokens): |
| continue |
| |
| if 3 <= len(match) <= 500: |
| |
| try: |
| success, smiles = selfies_to_smiles(match) |
| if success and smiles: |
| return smiles |
| except Exception: |
| continue |
| |
| |
| if response.startswith('[') and ']' in response: |
| |
| if not any(inv_token in response for inv_token in invalid_tokens): |
| try: |
| success, smiles = selfies_to_smiles(response) |
| if success and smiles: |
| return smiles |
| except Exception: |
| pass |
| |
| |
| |
| for prefix in ['smiles(', 'selfies(', 'Output:', 'Answer:', 'Result:', 'The molecule is']: |
| if prefix.lower() in response.lower(): |
| idx = response.lower().find(prefix.lower()) |
| remaining = response[idx + len(prefix):].strip() |
| |
| remaining = re.sub(r'[)\].]+$', '', remaining) |
| if remaining.startswith('['): |
| |
| if not any(inv_token in remaining for inv_token in invalid_tokens): |
| try: |
| success, smiles = selfies_to_smiles(remaining) |
| if success and smiles: |
| return smiles |
| except Exception: |
| pass |
| |
| |
| smiles_pattern = r'[A-Za-z0-9@+\-\[\]()=#\\/]+' |
| matches = re.findall(smiles_pattern, response) |
| |
| |
| for match in matches: |
| if 3 <= len(match) <= 200: |
| |
| if any(atom in match for atom in ['C', 'N', 'O', 'S', 'P', 'F', 'Cl', 'Br']): |
| |
| validation = validate_smiles(match) |
| if validation["valid"] == "True": |
| return match |
| |
| |
| |
| if self.use_selfies: |
| return None |
| |
| |
| validation = validate_smiles(response.strip()) |
| if validation["valid"] == "True": |
| return response.strip() |
| |
| return None |
| |
| def _call_tool(self, tool_name: str, **kwargs) -> Dict[str, Any]: |
| """Call a tool function by name.""" |
| if tool_name not in self.tools: |
| return {"error": f"Unknown tool: {tool_name}"} |
| return self.tools[tool_name](**kwargs) |
| |
| def _format_messages_for_model(self, messages: List[Dict[str, str]]) -> str: |
| """Format messages according to model's expected format.""" |
| model_lower = self.model_name.lower() |
| |
| |
| if "qwen" in model_lower: |
| prompt = "" |
| for msg in messages: |
| role = msg.get("role", "user") |
| content = msg.get("content", "") |
| if role == "system": |
| prompt += f"<|im_start|>system\n{content}<|im_end|>\n" |
| elif role == "user": |
| prompt += f"<|im_start|>user\n{content}<|im_end|>\n" |
| elif role == "assistant": |
| prompt += f"<|im_start|>assistant\n{content}<|im_end|>\n" |
| prompt += "<|im_start|>assistant\n" |
| return prompt |
| |
| |
| |
| |
| if "chemllm" in model_lower or "ai4chem" in model_lower: |
| |
| if "1_5" in model_lower or "1.5" in model_lower or "dpo" in model_lower: |
| |
| |
| if hasattr(self, 'tokenizer') and hasattr(self.tokenizer, "apply_chat_template"): |
| try: |
| return self.tokenizer.apply_chat_template( |
| messages, |
| tokenize=False, |
| add_generation_prompt=True, |
| ) |
| except: |
| pass |
| |
| prompt = "" |
| for msg in messages: |
| role = msg.get("role", "") |
| content = msg.get("content", "") |
| if role == "system": |
| prompt += f"<|im_start|>system\n{content}<|im_end|>\n" |
| elif role == "user": |
| prompt += f"<|im_start|>user\n{content}<|im_end|>\n" |
| elif role == "assistant": |
| prompt += f"<|im_start|>assistant\n{content}<|im_end|>\n" |
| prompt += "<|im_start|>assistant\n" |
| return prompt |
| else: |
| |
| |
| if hasattr(self, 'tokenizer') and hasattr(self.tokenizer, "apply_chat_template"): |
| try: |
| return self.tokenizer.apply_chat_template( |
| messages, |
| tokenize=False, |
| add_generation_prompt=True, |
| ) |
| except: |
| pass |
| |
| prompt = "" |
| for msg in messages: |
| role = msg.get("role", "") |
| content = msg.get("content", "") |
| if role == "system": |
| prompt += f"<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\n{content}<|eot_id|>\n" |
| elif role == "user": |
| prompt += f"<|start_header_id|>user<|end_header_id|>\n\n{content}<|eot_id|>\n" |
| elif role == "assistant": |
| prompt += f"<|start_header_id|>assistant<|end_header_id|>\n\n{content}<|eot_id|>\n" |
| prompt += "<|start_header_id|>assistant<|end_header_id|>\n\n" |
| return prompt |
| |
| |
| if hasattr(self, 'tokenizer') and hasattr(self.tokenizer, "apply_chat_template"): |
| try: |
| return self.tokenizer.apply_chat_template( |
| messages, |
| tokenize=False, |
| add_generation_prompt=True, |
| ) |
| except: |
| pass |
| |
| |
| prompt = "" |
| for msg in messages: |
| role = msg.get("role", "") |
| content = msg.get("content", "") |
| if role == "system": |
| prompt += f"System: {content}\n\n" |
| elif role == "user": |
| prompt += f"User: {content}\n\n" |
| elif role == "assistant": |
| prompt += f"Assistant: {content}\n\n" |
| prompt += "Assistant: " |
| return prompt |
| |
| def _generate_candidate(self, state: AgentState) -> str: |
| """ |
| Generate candidate SMILES using Llama-3. |
| |
| Args: |
| state: Current agent state |
| |
| Returns: |
| Generated SMILES string |
| """ |
| |
| messages = state["messages"].copy() |
| |
| |
| if self.use_api: |
| |
| |
| api_messages = [] |
| for msg in messages: |
| role = msg["role"] |
| content = msg["content"] |
| |
| if role == "system": |
| |
| if not api_messages or api_messages[-1]["role"] != "user": |
| api_messages.append({"role": "user", "content": content}) |
| else: |
| api_messages[-1]["content"] = content + "\n\n" + api_messages[-1]["content"] |
| elif role in ["user", "assistant"]: |
| api_messages.append({"role": role, "content": content}) |
| |
| if not api_messages: |
| return "" |
| |
| |
| if self.client is None: |
| |
| raise AttributeError("InferenceClient not available") |
| |
| try: |
| |
| |
| if hasattr(self.client, 'chat_completion'): |
| response = self.client.chat_completion( |
| messages=api_messages, |
| max_tokens=256, |
| temperature=0.7, |
| ) |
| elif hasattr(self.client, 'chat'): |
| |
| response = self.client.chat( |
| messages=api_messages, |
| max_tokens=256, |
| temperature=0.7, |
| ) |
| else: |
| raise AttributeError("No chat_completion or chat method available on InferenceClient") |
| |
| |
| if hasattr(response, 'choices') and len(response.choices) > 0: |
| return response.choices[0].message.content.strip() |
| elif isinstance(response, dict): |
| if "choices" in response and len(response["choices"]) > 0: |
| return response["choices"][0].get("message", {}).get("content", "").strip() |
| return response.get("generated_text", "").strip() |
| else: |
| return str(response).strip() |
| except (Exception, AttributeError) as e: |
| |
| print(f"⚠ chat_completion failed: {e}, trying text_generation") |
| try: |
| |
| prompt_text = self._format_messages_for_model(messages) |
| if not prompt_text: |
| |
| prompt_parts = [] |
| for msg in api_messages: |
| role = msg["role"] |
| content = msg["content"] |
| if role == "user": |
| prompt_parts.append(f"User: {content}") |
| elif role == "assistant": |
| prompt_parts.append(f"Assistant: {content}") |
| prompt_text = "\n".join(prompt_parts) + "\nAssistant:" |
| |
| response = self.client.text_generation( |
| prompt_text, |
| max_new_tokens=256, |
| temperature=0.7, |
| return_full_text=False, |
| ) |
| return response.strip() if isinstance(response, str) else str(response).strip() |
| except Exception as e2: |
| |
| print(f"⚠ text_generation failed: {e2}, trying direct API call") |
| try: |
| import requests |
| import os |
| token = self.api_token or os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACE_HUB_TOKEN") |
| if not token: |
| raise ValueError("No API token available") |
| |
| |
| api_url = f"https://router.huggingface.co/models/{self.model_name}" |
| headers = { |
| "Authorization": f"Bearer {token}", |
| "Content-Type": "application/json", |
| } |
| |
| |
| |
| endpoints_to_try = [ |
| (f"https://router.huggingface.co/models/{self.model_name}/v1/chat/completions", { |
| "model": self.model_name, |
| "messages": api_messages, |
| "max_tokens": 256, |
| "temperature": 0.7, |
| }), |
| |
| (f"https://router.huggingface.co/models/{self.model_name}", { |
| "inputs": self._format_messages_for_model(messages) or "\n".join([f"{m['role']}: {m['content']}" for m in api_messages]) + "\nassistant:", |
| "parameters": { |
| "max_new_tokens": 256, |
| "temperature": 0.7, |
| "return_full_text": False, |
| } |
| }), |
| |
| (f"https://api-inference.huggingface.co/models/{self.model_name}", { |
| "inputs": self._format_messages_for_model(messages) or "\n".join([f"{m['role']}: {m['content']}" for m in api_messages]) + "\nassistant:", |
| "parameters": { |
| "max_new_tokens": 256, |
| "temperature": 0.7, |
| "return_full_text": False, |
| } |
| }), |
| ] |
| |
| for endpoint_url, payload in endpoints_to_try: |
| try: |
| response = requests.post( |
| endpoint_url, |
| headers=headers, |
| json=payload, |
| timeout=60, |
| ) |
| |
| if response.status_code == 200: |
| result = response.json() |
| |
| if "choices" in result and len(result["choices"]) > 0: |
| return result["choices"][0]["message"]["content"].strip() |
| |
| elif isinstance(result, list) and len(result) > 0: |
| if isinstance(result[0], dict): |
| return result[0].get("generated_text", "").strip() |
| return str(result[0]).strip() |
| elif isinstance(result, dict): |
| if "generated_text" in result: |
| return result["generated_text"].strip() |
| |
| for key in ["text", "output", "response"]: |
| if key in result: |
| return str(result[key]).strip() |
| return str(result).strip() |
| elif response.status_code == 503: |
| |
| import time |
| time.sleep(5) |
| continue |
| except Exception as endpoint_error: |
| |
| continue |
| |
| |
| error_msg = ( |
| f"All API endpoints failed for model {self.model_name}.\n" |
| f"This model may not be available via HuggingFace Inference API.\n" |
| f"Options:\n" |
| f" 1. Try loading the model locally with --load-in-4bit (requires GPU)\n" |
| f" 2. Check if the model requires special access or gating\n" |
| f" 3. Use a different model that supports Inference API (e.g., meta-llama/Meta-Llama-3-8B-Instruct, Qwen/Qwen2.5-7B-Instruct)" |
| ) |
| print(f"✗ {error_msg}") |
| raise RuntimeError(error_msg) |
| |
| if response.status_code == 200: |
| result = response.json() |
| if isinstance(result, list) and len(result) > 0: |
| if isinstance(result[0], dict): |
| return result[0].get("generated_text", "").strip() |
| return str(result[0]).strip() |
| elif isinstance(result, dict): |
| return result.get("generated_text", "").strip() |
| return str(result).strip() |
| else: |
| error_msg = f"API request failed with status {response.status_code}" |
| try: |
| error_detail = response.json() |
| error_msg += f": {error_detail}" |
| except: |
| error_msg += f": {response.text[:200]}" |
| print(f"⚠ {error_msg}") |
| return "" |
| except ImportError: |
| print("⚠ requests library not available for fallback API call") |
| return "" |
| except Exception as e3: |
| print(f"⚠ Direct API call failed: {e3}") |
| return "" |
| elif self.use_unsloth: |
| |
| try: |
| inputs = self.tokenizer.apply_chat_template( |
| messages, |
| tokenize=True, |
| add_generation_prompt=True, |
| return_tensors="pt" |
| ).to(self.device) |
| except: |
| |
| prompt = self._format_messages_for_model(messages) |
| inputs = self.tokenizer(prompt, return_tensors="pt").to(self.device) |
| |
| outputs = self.model.generate( |
| inputs, |
| max_new_tokens=256, |
| temperature=0.7, |
| do_sample=True, |
| pad_token_id=self.tokenizer.eos_token_id, |
| ) |
| |
| response = self.tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True) |
| else: |
| |
| try: |
| inputs = self.tokenizer.apply_chat_template( |
| messages, |
| tokenize=True, |
| add_generation_prompt=True, |
| return_tensors="pt" |
| ).to(self.device) |
| except: |
| |
| prompt = self._format_messages_for_model(messages) |
| inputs = self.tokenizer(prompt, return_tensors="pt").to(self.device) |
| |
| with torch.no_grad(): |
| outputs = self.model.generate( |
| inputs, |
| max_new_tokens=256, |
| temperature=0.7, |
| do_sample=True, |
| pad_token_id=self.tokenizer.eos_token_id, |
| ) |
| |
| response = self.tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True) |
| |
| return response |
| |
| def predict( |
| self, |
| spectrum_peaks: Optional[List[float] | List[tuple[float, float]]] = None, |
| rag_context: Optional[List[str]] = None, |
| target_mass: Optional[float] = None, |
| initial_prompt: Optional[str] = None, |
| ) -> Dict[str, Any]: |
| """ |
| Run the agentic prediction loop. |
| |
| Args: |
| spectrum_peaks: List of major m/z peaks |
| rag_context: List of retrieved SMILES from RAG |
| target_mass: Target molecular mass |
| initial_prompt: Optional initial user prompt |
| |
| Returns: |
| Dictionary with: |
| - "smiles": Final predicted SMILES (or None if failed) |
| - "status": "success", "failed", or "max_iterations" |
| - "iterations": Number of iterations used |
| - "history": List of states at each iteration |
| """ |
| |
| state: AgentState = { |
| "messages": [], |
| "candidate_smiles": None, |
| "spectrum_embedding": None, |
| "rag_context": rag_context or [], |
| "target_mass": target_mass, |
| "iteration": 0, |
| "status": "draft", |
| "error_history": [], |
| } |
| |
| |
| system_prompt = self._build_system_prompt( |
| spectrum_peaks=spectrum_peaks, |
| rag_context=rag_context, |
| target_mass=target_mass, |
| ) |
| |
| state["messages"].append({"role": "system", "content": system_prompt}) |
| |
| |
| if initial_prompt: |
| user_prompt = initial_prompt |
| else: |
| if target_mass: |
| |
| estimated_atoms = int(target_mass / 14) |
| user_prompt = ( |
| f"Predict the molecular structure (SMILES) for this mass spectrum.\n\n" |
| f"Target mass: {target_mass:.4f} Da (estimated {estimated_atoms} atoms)\n\n" |
| f"WORKFLOW:\n" |
| f"1. Select the reference molecule closest to {target_mass:.4f} Da\n" |
| f"2. Modify it to match the target mass exactly\n" |
| f"3. Ensure the structure can produce the observed spectrum peaks\n" |
| f"4. Output the complete SMILES string\n\n" |
| f"CRITICAL: Generate a COMPLEX molecule ({estimated_atoms}±10 atoms), NOT a simple molecule." |
| ) |
| else: |
| user_prompt = ( |
| "Predict the molecular structure (SMILES) for this mass spectrum.\n\n" |
| "WORKFLOW:\n" |
| "1. Select the most appropriate reference molecule as template\n" |
| "2. Modify it to match the spectrum peaks and target mass\n" |
| "3. Output the complete SMILES string\n\n" |
| "CRITICAL: Generate a COMPLEX molecule, NOT a simple molecule." |
| ) |
| state["messages"].append({"role": "user", "content": user_prompt}) |
| |
| history = [] |
| |
| |
| for iteration in range(self.max_iterations): |
| state["iteration"] = iteration + 1 |
| state["status"] = "draft" |
| |
| |
| response = self._generate_candidate(state) |
| candidate = self._extract_smiles_from_response(response) |
| |
| if candidate is None: |
| |
| format_name = "SELFIES" if self.use_selfies else "SMILES" |
| error_msg = f"Iteration {iteration + 1}: Could not extract valid {format_name} from response: {response[:100]}" |
| state["error_history"].append(error_msg) |
| state["messages"].append({ |
| "role": "assistant", |
| "content": response |
| }) |
| format_instruction = "SELFIES" if self.use_selfies else "SMILES" |
| state["messages"].append({ |
| "role": "user", |
| "content": f"Please output a valid {format_instruction} string. No explanations, just the {format_instruction}." |
| }) |
| history.append(state.copy()) |
| continue |
| |
| state["candidate_smiles"] = candidate |
| state["status"] = "validating" |
| |
| |
| validation = validate_smiles(candidate) |
| |
| if validation["valid"] == "False": |
| |
| error_msg = f"Invalid SMILES: {validation['message']}" |
| state["error_history"].append(error_msg) |
| state["messages"].append({ |
| "role": "assistant", |
| "content": candidate |
| }) |
| state["messages"].append({ |
| "role": "user", |
| "content": f"Error: {validation['message']}. Please fix the SMILES syntax and try again." |
| }) |
| state["status"] = "retry" |
| history.append(state.copy()) |
| continue |
| |
| |
| if target_mass is not None: |
| state["status"] = "checking_mass" |
| mass_check = calculate_mass_error(candidate, target_mass, self.mass_tolerance_ppm) |
| |
| if mass_check["matches"] == "False": |
| |
| error_msg = mass_check["message"] |
| error_da = mass_check.get("error_da", "unknown") |
| |
| |
| try: |
| if isinstance(error_da, str): |
| error_da_val = float(error_da.replace(" Da", "")) |
| else: |
| error_da_val = float(error_da) |
| except: |
| error_da_val = None |
| |
| |
| if error_da_val and abs(error_da_val) > 50: |
| if error_da_val < 0: |
| |
| guidance = f"Mass error: {error_msg}\n\nYour prediction is {abs(error_da_val):.1f} Da SMALLER than the target. This indicates your molecule is too simple. You need to:\n1. Add more atoms, rings, or functional groups\n2. Use the reference molecules as templates - they show the expected complexity\n3. Generate a COMPLEX structure (30-100 atoms), not a simple molecule like methane or ethanol" |
| else: |
| |
| guidance = f"Mass error: {error_msg}\n\nYour prediction is {error_da_val:.1f} Da LARGER than the target. Simplify the structure by removing atoms or functional groups." |
| else: |
| guidance = f"Mass error detected: {error_msg}. Please adjust the structure to match the target mass of {target_mass:.4f} Da." |
| |
| state["error_history"].append(error_msg) |
| state["messages"].append({ |
| "role": "assistant", |
| "content": candidate |
| }) |
| state["messages"].append({ |
| "role": "user", |
| "content": guidance |
| }) |
| state["status"] = "retry" |
| history.append(state.copy()) |
| continue |
| |
| |
| state["status"] = "success" |
| history.append(state.copy()) |
| |
| return { |
| "smiles": candidate, |
| "status": "success", |
| "iterations": iteration + 1, |
| "history": history, |
| } |
| |
| |
| return { |
| "smiles": state["candidate_smiles"], |
| "status": "max_iterations", |
| "iterations": self.max_iterations, |
| "history": history, |
| } |
|
|