tlc-agent-scientifique / pattern_detector.py
Gilbra's picture
chnage provider
ed78f98
Raw
History Blame Contribute Delete
2.3 kB
from typing import Dict, Any, List
import json
from utils import (
call_llm,
safe_json_loads,
validate_ir
)
# =====================================================
# FALLBACK
# =====================================================
def fallback_patterns(
num_proposals: int
):
return [
{
"name": f"Pattern {i+1}",
"description": "Pattern détecté automatiquement"
}
for i in range(num_proposals)
]
# =====================================================
# PATTERN DETECTION
# =====================================================
def detect_patterns(
ir: Dict[str, Any],
num_proposals: int = 3,
provider: str = "openai"
) -> List[Dict[str, str]]:
if not validate_ir(ir):
return fallback_patterns(num_proposals)
ir_text = json.dumps(
ir,
indent=2,
ensure_ascii=False
)
prompt = f"""
Tu es un expert en graphes mathématiques
et compilation scientifique.
Analyse cette IR.
Détecte EXACTEMENT {num_proposals}
patterns mathématiques importants.
Exemples possibles :
- produit scalaire
- convolution
- pipeline tensoriel
- réduction
- propagation
- matrice creuse
- calcul distribué
- accumulation
- normalisation
- opération SIMD
IMPORTANT :
- retourne UNIQUEMENT du JSON valide
- aucune balise markdown
- aucun texte hors JSON
FORMAT STRICT :
[
{{
"name": "Convolution",
"description": "Détection d'un motif convolutionnel"
}}
]
IR :
{ir_text}
"""
response = call_llm(
prompt,
provider=provider,
max_tokens=1800
)
parsed = safe_json_loads(response)
valid_patterns = []
if isinstance(parsed, list):
for item in parsed:
if not isinstance(item, dict):
continue
name = item.get(
"name",
"Unknown Pattern"
)
description = item.get(
"description",
"Description indisponible"
)
valid_patterns.append({
"name": str(name),
"description": str(description)
})
if len(valid_patterns) > 0:
return valid_patterns[:num_proposals]
return fallback_patterns(num_proposals)