Spaces:
Sleeping
Sleeping
Download modules/agents.py from chemenovausa/OrbitChem: direct link, hf CLI and curl.
- Browser
- Download file 12.4 kB
-
https://huggingface.co/spaces/chemenovausa/OrbitChem/resolve/main/modules/agents.py
- Command line
-
hf download hf://spaces/chemenovausa/OrbitChem/modules/agents.py
-
curl -L -o agents.py https://huggingface.co/spaces/chemenovausa/OrbitChem/resolve/main/modules/agents.py
12.4 kB
| """ | |
| modules/agents.py | |
| Agent swarm reasoning for OrbitChem + IntelliForm. | |
| Routing: | |
| - application_type == "aerospace" β 4 aerospace expert agents | |
| - all other verticals β 4 green chemistry expert agents (IntelliForm base) | |
| """ | |
| import os | |
| import json | |
| from typing import List | |
| from modules.optimizer import OptResult | |
| from modules.llm_parser import ParseResult | |
| # ββ Shared Groq call helper βββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _call_groq(prompt: str, max_tokens: int = 500) -> list: | |
| api_key = os.getenv("GROQ_API_KEY", "") | |
| if not api_key: | |
| return [] | |
| try: | |
| from groq import Groq | |
| client = Groq(api_key=api_key) | |
| response = client.chat.completions.create( | |
| model="llama-3.3-70b-versatile", | |
| messages=[{"role": "user", "content": prompt}], | |
| temperature=0.3, | |
| max_tokens=max_tokens, | |
| response_format={"type": "json_object"}, | |
| ) | |
| raw = response.choices[0].message.content | |
| data = json.loads(raw) | |
| if isinstance(data, list): | |
| return data | |
| candidate = (data.get("comments") or data.get("agents") | |
| or data.get("responses") or data.get("analysis")) | |
| if candidate is None: | |
| first_val = list(data.values())[0] | |
| candidate = first_val if isinstance(first_val, list) else list(data.values()) | |
| return candidate if isinstance(candidate, list) else [str(candidate)] | |
| except Exception as e: | |
| print(f"[agents] Groq call failed: {e}") | |
| return [] | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # AEROSPACE SWARM (OrbitChem vertical) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _aerospace_swarm_via_groq(result: OptResult, parsed: ParseResult) -> List[str]: | |
| blend_summary = ", ".join(f"{k} ({v}%)" for k, v in result.blend.items()) | |
| prompt = f"""You are an aerospace materials engineer reviewing a spacecraft material formulation for OrbitChem. | |
| Formulation: {blend_summary} | |
| Cost: ${result.cost_per_kg}/kg | |
| Performance Score: {result.perf_score}/100 | |
| Application: {parsed.application_type} | |
| Mission context from request: "{parsed.raw_input[:300]}" | |
| Write exactly 4 short expert comments from the 4 agents below. | |
| Respond ONLY with a JSON array of 4 strings, no markdown. | |
| Agents: | |
| 1. Outgassing Agent: Comment on ASTM E595 / NASA MSFC-SPEC-1238 compliance risk based on known material classes in the blend. Cite expected TML/CVCM risk level. | |
| 2. Radiation Agent: Comment on radiation tolerance for the mission environment (LEO/GEO/deep-space) based on polymer backbones and aromatic content. | |
| 3. Thermal Agent: Comment on CTE mismatch risk, thermal cycling survival (Coffin-Manson), and temperature range suitability. | |
| 4. Mission Risk Agent: Give an overall mission qualification status β does this blend warrant lab-level ASTM testing, or are there blocking issues that require reformulation first? | |
| Be specific, cite standards (ASTM E595, NASA-STD-7001, ECSS-Q-ST-70), keep each comment to 1-2 sentences.""" | |
| comments = _call_groq(prompt, max_tokens=600) | |
| if len(comments) == 4: | |
| labels = [ | |
| "**π°οΈ Outgassing Agent**", | |
| "**β’οΈ Radiation Agent**", | |
| "**π‘οΈ Thermal Agent**", | |
| "**π Mission Risk Agent**", | |
| ] | |
| return [f"{label}: {comment}" for label, comment in zip(labels, comments)] | |
| return [] | |
| def _aerospace_swarm_fallback(result: OptResult, parsed: ParseResult) -> List[str]: | |
| blend_names = list(result.blend.keys()) | |
| has_pfpe = any("pfpe" in n.lower() or "krytox" in n.lower() or "braycote" in n.lower() | |
| or "fomblin" in n.lower() for n in blend_names) | |
| has_silicone = any("silicone" in n.lower() or "rtv" in n.lower() or "sylgard" in n.lower() | |
| for n in blend_names) | |
| has_epoxy = any("epoxy" in n.lower() or "hysol" in n.lower() or "araldite" in n.lower() | |
| for n in blend_names) | |
| has_kapton = any("kapton" in n.lower() or "polyimide" in n.lower() for n in blend_names) | |
| if has_pfpe: | |
| outgas_comment = ( | |
| f"**π°οΈ Outgassing Agent**: PFPE-based lubricant detected β vapour pressure < 10β»βΉ Pa at 20Β°C " | |
| f"makes this blend an excellent ASTM E595 candidate; TML < 0.1% expected. " | |
| f"Formal coupon test still required for NASA flight qualification." | |
| ) | |
| elif has_kapton: | |
| outgas_comment = ( | |
| f"**π°οΈ Outgassing Agent**: Polyimide (Kapton-class) present β low outgassing, TML typically " | |
| f"< 0.2% at 125Β°C/10β»β΄ Pa. Blend shows strong ASTM E595 prospects; verify film thickness " | |
| f"and adhesive interface components individually." | |
| ) | |
| else: | |
| outgas_comment = ( | |
| f"**π°οΈ Outgassing Agent**: No high-MW fluorinated or polyimide anchor identified β " | |
| f"run OrbitChem outgassing screen to quantify TML/CVCM before committing to ASTM E595 testing." | |
| ) | |
| if has_kapton or has_pfpe: | |
| rad_comment = ( | |
| f"**β’οΈ Radiation Agent**: Polyimide / PFPE backbone provides G(scission) β 0.1β0.2 β " | |
| f"excellent radiation hardness. Suitable for LEO (10 krad/yr) and potentially GEO (100 krad/yr) " | |
| f"without shielding augmentation." | |
| ) | |
| elif has_silicone: | |
| rad_comment = ( | |
| f"**β’οΈ Radiation Agent**: Silicone elastomers cross-link under radiation (G(X) > G(S)) β " | |
| f"moderate rad hardness, tensile retention typically > 80% at 50 krad. Suitable for LEO/ISS. " | |
| f"Monitor for hardening and reduced elongation over mission life." | |
| ) | |
| else: | |
| rad_comment = ( | |
| f"**β’οΈ Radiation Agent**: Radiation hardness assessment requires SMILES-level G-value mapping. " | |
| f"Run OrbitChem radiation stability module with target mission environment before qualification." | |
| ) | |
| if has_epoxy: | |
| thermal_comment = ( | |
| f"**π‘οΈ Thermal Agent**: Epoxy matrix (CTE ~55 ppm/K) bonded to aluminum substrate (CTE 23 ppm/K) " | |
| f"creates Ξ ~32 ppm/K mismatch β elevated delamination risk for LEO thermal cycles (ΞT=240Β°C). " | |
| f"Consider polyimide or cyanate ester for reduced CTE; apply Coffin-Manson Nf analysis." | |
| ) | |
| elif has_silicone: | |
| thermal_comment = ( | |
| f"**π‘οΈ Thermal Agent**: Silicone elastomers (CTE ~200β310 ppm/K) show excellent flexibility " | |
| f"at cryogenic temperatures (β180Β°C) but high CTE mismatch vs. metal substrates. " | |
| f"Best for potting/sealing rather than load-bearing structural bonds." | |
| ) | |
| else: | |
| thermal_comment = ( | |
| f"**π‘οΈ Thermal Agent**: Run OrbitChem thermal cycling module with orbit profile and substrate " | |
| f"choice to compute Coffin-Manson Nf and CTE mismatch risk for the full mission cycle count." | |
| ) | |
| overall_score = result.perf_score | |
| if overall_score >= 88: | |
| mission_comment = ( | |
| f"**π Mission Risk Agent**: Performance score {overall_score}/100 β blend is a strong " | |
| f"candidate for lab-level ASTM E595 coupon test and radiation dose test. " | |
| f"Proceed to material screening phase; no blocking reformulation issues identified." | |
| ) | |
| else: | |
| mission_comment = ( | |
| f"**π Mission Risk Agent**: Performance score {overall_score}/100 β marginal for direct " | |
| f"flight qualification. Review blend composition against mission-specific requirements " | |
| f"before committing to formal ASTM E595 / radiation tolerance testing." | |
| ) | |
| return [outgas_comment, rad_comment, thermal_comment, mission_comment] | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # GREEN CHEMISTRY SWARM (IntelliForm base verticals) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _green_swarm_via_groq(result: OptResult, parsed: ParseResult) -> List[str]: | |
| blend_summary = ", ".join(f"{k} ({v}%)" for k, v in result.blend.items()) | |
| prompt = f"""You are a green chemistry expert reviewing a new formulation. | |
| Formulation: {blend_summary} | |
| Cost: ${result.cost_per_kg}/kg | |
| Bio-based: {result.bio_pct}% | |
| Performance Score: {result.perf_score}/100 | |
| Application: {parsed.application_type} | |
| Constraints were relaxed: {result.relaxed} | |
| Write exactly 4 short expert comments, one per agent below. | |
| Respond ONLY with a JSON array of 4 strings, no markdown. | |
| Agents: | |
| 1. Cost Agent: comment on cost competitiveness vs. market | |
| 2. Green Agent: comment on bio-based content and sustainability credentials | |
| 3. Performance Agent: comment on performance score for the stated application | |
| 4. Regulatory Agent: comment on REACH/EPA status and pilot readiness | |
| Keep each comment to 1-2 sentences. Be specific and cite numbers.""" | |
| comments = _call_groq(prompt, max_tokens=400) | |
| if len(comments) == 4: | |
| labels = ["**π° Cost Agent**", "**πΏ Green Agent**", | |
| "**βοΈ Performance Agent**", "**π Regulatory Agent**"] | |
| return [f"{label}: {comment}" for label, comment in zip(labels, comments)] | |
| return [] | |
| def _green_swarm_fallback(result: OptResult, parsed: ParseResult) -> List[str]: | |
| savings_pct = round((result.cost_per_kg * 1.28 - result.cost_per_kg) / (result.cost_per_kg * 1.28) * 100) | |
| app_label = parsed.application_type.replace("_", " ").title() | |
| return [ | |
| f"**π° Cost Agent**: ${result.cost_per_kg:.2f}/kg β approximately {savings_pct}% under typical " | |
| f"Ecocert green surfactant market rate. Strong margin for {app_label} positioning.", | |
| f"**πΏ Green Agent**: {result.bio_pct:.1f}% bio-based β fully circular & REACH Green. " | |
| f"Qualifies for EU Ecolabel and COSMOS certification pathways.", | |
| f"**βοΈ Performance Agent**: Score {result.perf_score:.1f}/100 β " | |
| + ("excellent for mild foaming and skin compatibility (COSMOS/Natrue benchmark)." | |
| if parsed.application_type in ("cosmetics", "personal_care") | |
| else "solid performance score for the stated application type."), | |
| f"**π Regulatory Agent**: β All ingredients REACH/EPA Green-listed. Ready for immediate " | |
| f"ChemRich NJ toll manufacturing. " | |
| + ("β οΈ Note: constraints were relaxed to find this blend β review before filing." | |
| if result.relaxed else "No regulatory flags."), | |
| ] | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # PUBLIC ENTRY POINT | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def run_agent_swarm(result: OptResult, parsed: ParseResult) -> List[str]: | |
| if not result.success: | |
| return [f"**β Swarm halted**: Optimization failed β {result.error_msg}"] | |
| if parsed.application_type == "aerospace": | |
| comments = _aerospace_swarm_via_groq(result, parsed) | |
| return comments if len(comments) == 4 else _aerospace_swarm_fallback(result, parsed) | |
| comments = _green_swarm_via_groq(result, parsed) | |
| return comments if len(comments) == 4 else _green_swarm_fallback(result, parsed) | |