Spaces:
Sleeping
Sleeping
File size: 11,767 Bytes
8c867c9 | 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 | """
modules/llm_parser.py
Natural language -> formulation constraints parser for IntelliForm.
Priority chain (configurable via LLM_PROVIDER env var):
1. Groq (llama-3.1-8b-instant) β fast, free tier
2. Anthropic (claude-sonnet-4-20250514) β best reasoning
3. OpenAI (gpt-4o-mini) β general fallback
4. Ollama (local, zero cost, privacy-safe)
5. Regex (always works, no API needed)
Set LLM_PROVIDER=groq|anthropic|openai|ollama|auto (default: auto)
Auto mode tries in order: Groq -> Anthropic -> OpenAI -> Ollama -> Regex
"""
import os, re, json, requests
from dataclasses import dataclass
from typing import Optional
from modules.analytics import track
@dataclass
class ParseResult:
max_cost: float
min_bio: float
min_perf: float
application_type: str
reasoning: str
parser_backend: str
raw_input: str
_SYSTEM_PROMPT = """You are an advanced materials and chemistry formulation assistant for OrbitChem / IntelliForm.
Extract formulation constraints from a customer request.
Respond ONLY with valid JSON β no markdown, no preamble.
JSON schema:
{
"max_cost": <float, USD/kg, default 5.0>,
"min_bio": <float, bio-based %, default 95>,
"min_perf": <float, performance score 0-100, default 82>,
"application_type":<string: cosmetics|personal_care|industrial|food_safe|textile|agricultural|pharmaceutical|aerospace|unknown>,
"reasoning": <string, 1-2 sentences>
}
Rules:
- "mild" or "skin" -> min_perf >= 85
- "foaming" or "surfactant" -> min_perf >= 88
- "industrial" or "degreaser" -> min_perf >= 85, set application_type=industrial
- "agricultural" or "crop" -> application_type=agricultural
- "pharma" or "pharmaceutical" -> application_type=pharmaceutical, min_bio >= 90
- "aerospace", "satellite", "space", "vacuum", "radiation", "outgassing", "spacecraft", "LEO", "GEO", "orbital", "thermal cycling", "ASTM E595", "NASA", "ESA" -> application_type=aerospace, min_perf >= 88
- For aerospace: do NOT enforce high min_bio (space materials are often synthetic β keep default 0); instead max_cost can be high (space-grade)
- "98%","99%","100%","fully bio" -> min_bio >= 98
- Extract cost from "under $4/kg", "max $3.50", "budget $5", "$200/kg", "up to $X/kg"
- Never set min_bio < 80 or min_perf < 65 UNLESS application_type=aerospace (bio% irrelevant for space materials)"""
_USER_PROMPT = 'Customer request: """{text}"""'
# ββ Groq ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _parse_with_groq(text: str) -> Optional[ParseResult]:
api_key = os.getenv("GROQ_API_KEY", "")
if not api_key:
return None
try:
from groq import Groq
client = Groq(api_key=api_key)
model = os.getenv("GROQ_MODEL", "llama-3.1-8b-instant")
response = client.chat.completions.create(
model=model,
messages=[{"role": "system", "content": _SYSTEM_PROMPT},
{"role": "user", "content": _USER_PROMPT.format(text=text)}],
temperature=0.1, max_tokens=300,
response_format={"type": "json_object"}
)
data = json.loads(response.choices[0].message.content)
return _build_result(data, f"groq/{model}", text)
except Exception as e:
print(f"[llm_parser] Groq failed: {e}")
return None
# ββ Anthropic βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _parse_with_anthropic(text: str) -> Optional[ParseResult]:
api_key = os.getenv("ANTHROPIC_API_KEY", "")
if not api_key:
return None
try:
import anthropic
client = anthropic.Anthropic(api_key=api_key)
model = os.getenv("ANTHROPIC_MODEL", "claude-sonnet-4-6")
response = client.messages.create(
model=model,
max_tokens=300,
system=_SYSTEM_PROMPT + "\nYou MUST respond with only valid JSON, nothing else.",
messages=[{"role": "user", "content": _USER_PROMPT.format(text=text)}]
)
raw = response.content[0].text.strip()
# Strip markdown fences if present
if raw.startswith("```"):
raw = re.sub(r"```(?:json)?", "", raw).strip()
data = json.loads(raw)
return _build_result(data, f"anthropic/{model}", text)
except Exception as e:
import traceback
err = f"[llm_parser] Anthropic failed: {type(e).__name__}: {e}\n{traceback.format_exc()}"
print(err)
# Write to a temp file so we can read it from Streamlit
try:
with open("/tmp/intelliform_llm_errors.txt", "a") as f:
f.write(err + "\n---\n")
except Exception:
pass
return None
# ββ OpenAI ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _parse_with_openai(text: str) -> Optional[ParseResult]:
api_key = os.getenv("OPENAI_API_KEY", "")
if not api_key:
return None
try:
from openai import OpenAI
client = OpenAI(api_key=api_key)
model = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
response = client.chat.completions.create(
model=model,
messages=[{"role": "system", "content": _SYSTEM_PROMPT},
{"role": "user", "content": _USER_PROMPT.format(text=text)}],
temperature=0.1, max_tokens=300,
response_format={"type": "json_object"}
)
data = json.loads(response.choices[0].message.content)
return _build_result(data, f"openai/{model}", text)
except Exception as e:
import traceback
err = f"[llm_parser] OpenAI failed: {type(e).__name__}: {e}\n{traceback.format_exc()}"
print(err)
try:
with open("/tmp/intelliform_llm_errors.txt", "a") as f:
f.write(err + "\n---\n")
except Exception:
pass
return None
# ββ Ollama ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _parse_with_ollama(text: str) -> Optional[ParseResult]:
host = os.getenv("OLLAMA_HOST", "http://localhost:11434")
model = os.getenv("OLLAMA_MODEL", "llama3")
try:
resp = requests.post(
f"{host}/api/generate",
json={"model": model,
"prompt": f"{_SYSTEM_PROMPT}\n\n{_USER_PROMPT.format(text=text)}",
"stream": False, "format": "json"},
timeout=20
)
resp.raise_for_status()
data = json.loads(resp.json().get("response", ""))
return _build_result(data, f"ollama/{model}", text)
except Exception as e:
print(f"[llm_parser] Ollama failed: {e}")
return None
# ββ Regex fallback ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _parse_with_regex(text: str) -> ParseResult:
t = text.lower()
m = re.search(r'(?:under|max|budget|below)\s*\$?\s*(\d+\.?\d*)\s*(?:/kg)?', t)
max_cost = float(m.group(1)) if m else 5.0
min_bio = 98.0 if any(x in t for x in ['100%','99%','98%','fully bio','fully natural']) else 95.0
_aerospace_kw = ['aerospace','satellite','space','vacuum','radiation','outgassing',
'spacecraft','leo','geo','orbital','thermal cycling','astm e595','nasa','esa',
'ablative','kapton','pfpe','lubricant','low-outgassing']
if any(x in t for x in _aerospace_kw): min_perf = 88.0
elif any(x in t for x in ['foaming','high foam','surfactant']): min_perf = 88.0
elif any(x in t for x in ['skin','cosmetics','personal care','mild','pharma']): min_perf = 85.0
elif any(x in t for x in ['industrial','degreaser','cleaner','solvent']): min_perf = 85.0
else: min_perf = 82.0
if any(x in t for x in _aerospace_kw): app = "aerospace"; min_bio = 0.0 # bio% irrelevant
elif any(x in t for x in ['cosmetics','skin','personal care','lotion','cream']): app = "cosmetics"
elif any(x in t for x in ['food','edible','fda','flavour','flavor']): app = "food_safe"
elif any(x in t for x in ['textile','fabric','laundry']): app = "textile"
elif any(x in t for x in ['industrial','degreaser','metal','automotive','workshop']): app = "industrial"
elif any(x in t for x in ['agricultural','crop','pesticide','adjuvant','farm']): app = "agricultural"
elif any(x in t for x in ['pharma','pharmaceutical','drug','excipient']): app = "pharmaceutical"
else: app = "unknown"
return ParseResult(max_cost=max_cost, min_bio=min_bio, min_perf=min_perf,
application_type=app,
reasoning="Extracted using regex fallback (no LLM API key configured).",
parser_backend="regex", raw_input=text)
# ββ Shared builder ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _build_result(data: dict, backend: str, raw_input: str) -> ParseResult:
return ParseResult(
max_cost=float(data.get("max_cost", 5.0)),
min_bio=float(data.get("min_bio", 95)),
min_perf=float(data.get("min_perf", 82)),
application_type=str(data.get("application_type", "unknown")),
reasoning=str(data.get("reasoning", "")),
parser_backend=backend,
raw_input=raw_input
)
# ββ Router ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def parse_request(text: str, llm_provider: str = None) -> ParseResult:
"""
Parse a customer NL request into formulation constraints.
Routing logic:
- llm_provider arg takes precedence over LLM_PROVIDER env var
- LLM_PROVIDER=groq|anthropic|openai|ollama -> use only that provider
- LLM_PROVIDER=auto (default) -> try all in order, fall back to regex
"""
provider = (llm_provider or os.getenv("LLM_PROVIDER", "auto")).lower()
if provider == "groq":
result = _parse_with_groq(text) or _parse_with_regex(text)
elif provider == "anthropic":
result = _parse_with_anthropic(text) or _parse_with_regex(text)
elif provider == "openai":
result = _parse_with_openai(text) or _parse_with_regex(text)
elif provider == "ollama":
result = _parse_with_ollama(text) or _parse_with_regex(text)
else:
# Auto mode β try all in priority order
result = (
_parse_with_groq(text) or
_parse_with_anthropic(text) or
_parse_with_openai(text) or
_parse_with_ollama(text) or
_parse_with_regex(text)
)
track("llm_parser_used", {
"parser_backend": result.parser_backend,
"application_type": result.application_type,
"max_cost": result.max_cost,
"min_bio": result.min_bio,
"min_perf": result.min_perf,
"input_length": len(text),
"llm_provider_env": provider,
})
return result
|