File size: 50,164 Bytes
db32e07 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 | """
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 # type: ignore
except ImportError:
TypedDict = dict # type: ignore
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]] # Conversation history
candidate_smiles: Optional[str] # Current candidate
spectrum_embedding: Optional[torch.Tensor] # Spectrum embedding (if available)
rag_context: List[str] # Retrieved SMILES from RAG
target_mass: Optional[float] # Target molecular mass
iteration: int # Current iteration number
status: str # "draft", "validating", "checking_mass", "success", "retry", "failed"
error_history: List[str] # History of errors for learning
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:
# Use HuggingFace Inference 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:
# Load local model
self._load_model()
# Tool registry
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"
)
# Use InferenceClient with updated endpoint
# The client should automatically use the correct router endpoint
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:
# Load with Unsloth (4-bit quantized, fast inference)
self.model, self.tokenizer = FastLanguageModel.from_pretrained(
model_name=self.model_name,
max_seq_length=4096,
dtype=None, # Auto-detect
load_in_4bit=True,
)
# Enable fast inference
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:
# Fallback to standard transformers
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
# Load with 4-bit quantization if requested and available
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:
# Convert peaks to string format
# Handle both formats: list of floats (m/z only) or list of tuples (m/z, intensity)
peak_strings = []
for p in spectrum_peaks:
if isinstance(p, (list, tuple)) and len(p) >= 2:
# Format: (m/z, intensity)
mz, intensity = float(p[0]), float(p[1])
peak_strings.append(f'{mz:.2f} (intensity: {intensity:.3f})')
else:
# Format: just m/z
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:
# Debug: log if peaks are missing
import sys
if hasattr(sys, '_getframe'): # Only in debug mode
pass # Could add debug logging here
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"
# Calculate masses for reference molecules to help selection
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:
# RDKit not available, skip mass calculation
ref_masses = [None] * min(5, len(rag_context))
for i, (smiles, ref_mass) in enumerate(zip(rag_context[:5], ref_masses), 1):
# Convert SMILES to SELFIES if using SELFIES format
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:
# Find closest reference by 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()
# print(prompt)
# print("--------------------------------")
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
"""
# Remove markdown code blocks
response = re.sub(r'```[a-z]*\n?', '', response)
response = re.sub(r'```', '', response)
response = response.strip()
# Try JSON format
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 using SELFIES, look for SELFIES pattern first
if self.use_selfies:
# SELFIES pattern: starts with [ and contains brackets
# Match sequences like [C][C][O] or [C][=O][O]
selfies_pattern = r'\[[^\]]+\](?:\[[^\]]+\])+'
matches = re.findall(selfies_pattern, response)
# Filter out invalid SELFIES tokens
invalid_tokens = ['[M]', '[MOL]', '[ATOM]', '[BOND]', '[SMILES]', '[SELFIES]', '[Output]', '[Answer]']
for match in matches:
# Check for invalid tokens
if any(inv_token in match for inv_token in invalid_tokens):
continue
if 3 <= len(match) <= 500: # Reasonable SELFIES length
# Try to convert to SMILES
try:
success, smiles = selfies_to_smiles(match)
if success and smiles:
return smiles
except Exception:
continue
# Try the whole response as SELFIES (if it looks like SELFIES)
if response.startswith('[') and ']' in response:
# Check for invalid tokens
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
# Try to extract SELFIES from text like "smiles([C][C][O])" or "Output: [C][C][O]"
# Look for SELFIES pattern after common prefixes
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()
# Remove trailing parentheses or punctuation
remaining = re.sub(r'[)\].]+$', '', remaining)
if remaining.startswith('['):
# Check for invalid tokens
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
# Try to find SMILES pattern
smiles_pattern = r'[A-Za-z0-9@+\-\[\]()=#\\/]+'
matches = re.findall(smiles_pattern, response)
# Filter: SMILES should have reasonable length and contain atoms
for match in matches:
if 3 <= len(match) <= 200: # Reasonable SMILES length
# Check if it looks like SMILES (contains common atoms)
if any(atom in match for atom in ['C', 'N', 'O', 'S', 'P', 'F', 'Cl', 'Br']):
# Validate it's actually parseable
validation = validate_smiles(match)
if validation["valid"] == "True":
return match
# If using SELFIES and we haven't found anything yet, don't try SMILES validation
# (SELFIES strings will fail SMILES validation)
if self.use_selfies:
return None
# If no valid SMILES found, try the whole response as-is (only for SMILES mode)
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()
# Qwen models use ChatML format
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
# ChemLLM models
# ChemLLM-7B-Chat-1_5-DPO is based on InternLM-2, uses InternLM chat template
# Older ChemLLM versions may use Llama-style template
if "chemllm" in model_lower or "ai4chem" in model_lower:
# Check if it's the 1.5 DPO version (based on InternLM-2)
if "1_5" in model_lower or "1.5" in model_lower or "dpo" in model_lower:
# InternLM-2 chat template format
# Try tokenizer's template first
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
# Fallback: InternLM-2 format
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:
# Older ChemLLM versions (may use Llama-style template)
# Try tokenizer's template first, fallback to Llama format
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
# Fallback: Llama-2/3 style format
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
# For other models, use tokenizer's chat template if available
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
# Fallback: simple formatting
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
"""
# Build messages for chat
messages = state["messages"].copy()
# Generate
if self.use_api:
# Use HuggingFace Inference API
# Prepare messages for chat_completion (preferred method for chat models)
api_messages = []
for msg in messages:
role = msg["role"]
content = msg["content"]
# Convert to API format (skip system messages or include as user message)
if role == "system":
# Some models don't support system role, prepend to first user message
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 ""
# Try chat_completion first (recommended for chat models)
if self.client is None:
# If client initialization failed, skip to direct API calls
raise AttributeError("InferenceClient not available")
try:
# Try chat_completion (OpenAI-compatible format)
# Check if method exists (different versions may have different names)
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'):
# Alternative method name in some versions
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")
# Extract content from response
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:
# Fallback 1: Try text_generation with formatted prompt
print(f"⚠ chat_completion failed: {e}, trying text_generation")
try:
# Format messages according to model type
prompt_text = self._format_messages_for_model(messages)
if not prompt_text:
# Fallback to simple format
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:
# Fallback 2: Use requests library to call API directly
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")
# Use new router endpoint instead of deprecated api-inference endpoint
api_url = f"https://router.huggingface.co/models/{self.model_name}"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
# Try multiple endpoint formats
# Format 1: OpenAI-compatible chat completions via router
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,
}),
# Format 2: Direct inference endpoint
(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,
}
}),
# Format 3: Try inference API endpoint (legacy, but might work for some models)
(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()
# Handle chat completion format
if "choices" in result and len(result["choices"]) > 0:
return result["choices"][0]["message"]["content"].strip()
# Handle inference API format
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()
# Try to extract from any text field
for key in ["text", "output", "response"]:
if key in result:
return str(result[key]).strip()
return str(result).strip()
elif response.status_code == 503:
# Model is loading, wait and retry
import time
time.sleep(5)
continue
except Exception as endpoint_error:
# Try next endpoint
continue
# If all endpoints failed, provide helpful error message
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:
# Unsloth chat template
try:
inputs = self.tokenizer.apply_chat_template(
messages,
tokenize=True,
add_generation_prompt=True,
return_tensors="pt"
).to(self.device)
except:
# Fallback to manual formatting
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:
# Standard transformers
try:
inputs = self.tokenizer.apply_chat_template(
messages,
tokenize=True,
add_generation_prompt=True,
return_tensors="pt"
).to(self.device)
except:
# Fallback to manual formatting
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
"""
# Initialize state
state: AgentState = {
"messages": [],
"candidate_smiles": None,
"spectrum_embedding": None,
"rag_context": rag_context or [],
"target_mass": target_mass,
"iteration": 0,
"status": "draft",
"error_history": [],
}
# Build system prompt
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})
# User prompt with emphasis on complexity and workflow
if initial_prompt:
user_prompt = initial_prompt
else:
if target_mass:
# Estimate atom count from mass
estimated_atoms = int(target_mass / 14) # Rough estimate: ~14 Da per atom
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 = []
# Agentic loop
for iteration in range(self.max_iterations):
state["iteration"] = iteration + 1
state["status"] = "draft"
# Generate candidate
response = self._generate_candidate(state)
candidate = self._extract_smiles_from_response(response)
if candidate is None:
# Could not extract valid structure
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"
# Validate SMILES
validation = validate_smiles(candidate)
if validation["valid"] == "False":
# Invalid SMILES - add error to conversation and retry
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
# SMILES is valid - check mass if target provided
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":
# Mass mismatch - add error and retry with enhanced guidance
error_msg = mass_check["message"]
error_da = mass_check.get("error_da", "unknown")
# Parse error_da if it's a string
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
# Provide specific guidance based on mass error magnitude
if error_da_val and abs(error_da_val) > 50:
if error_da_val < 0:
# Prediction is too small
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:
# Prediction is too large
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
# Success!
state["status"] = "success"
history.append(state.copy())
return {
"smiles": candidate,
"status": "success",
"iterations": iteration + 1,
"history": history,
}
# Max iterations reached
return {
"smiles": state["candidate_smiles"],
"status": "max_iterations",
"iterations": self.max_iterations,
"history": history,
}
|