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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import joblib
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import streamlit as st
|
| 8 |
+
import torch
|
| 9 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# ============================================================
|
| 13 |
+
# APP CONFIGURATION
|
| 14 |
+
# ============================================================
|
| 15 |
+
|
| 16 |
+
st.set_page_config(
|
| 17 |
+
page_title="Intelligent Predictive Maintenance System",
|
| 18 |
+
page_icon="π",
|
| 19 |
+
layout="wide",
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
MODEL_PATH = Path(__file__).parent / "predictive_maintenance_rf_pipeline.pkl"
|
| 23 |
+
LLM_MODEL_ID = "Qwen/Qwen2.5-0.5B-Instruct"
|
| 24 |
+
|
| 25 |
+
FAILURE_THRESHOLD = 0.50
|
| 26 |
+
MEDIUM_RISK_THRESHOLD = 0.40
|
| 27 |
+
HIGH_RISK_THRESHOLD = 0.70
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# ============================================================
|
| 31 |
+
# LIGHT UI STYLING
|
| 32 |
+
# ============================================================
|
| 33 |
+
|
| 34 |
+
st.markdown(
|
| 35 |
+
"""
|
| 36 |
+
<style>
|
| 37 |
+
.main-title {
|
| 38 |
+
font-size: 2.2rem;
|
| 39 |
+
font-weight: 750;
|
| 40 |
+
margin-bottom: 0.1rem;
|
| 41 |
+
}
|
| 42 |
+
.sub-title {
|
| 43 |
+
color: #6b7280;
|
| 44 |
+
margin-bottom: 1.25rem;
|
| 45 |
+
}
|
| 46 |
+
.agent-box {
|
| 47 |
+
border: 1px solid #d1d5db;
|
| 48 |
+
border-radius: 12px;
|
| 49 |
+
padding: 14px 16px;
|
| 50 |
+
margin-bottom: 12px;
|
| 51 |
+
}
|
| 52 |
+
.status-ok {
|
| 53 |
+
font-weight: 700;
|
| 54 |
+
}
|
| 55 |
+
.small-note {
|
| 56 |
+
font-size: 0.88rem;
|
| 57 |
+
color: #6b7280;
|
| 58 |
+
}
|
| 59 |
+
</style>
|
| 60 |
+
""",
|
| 61 |
+
unsafe_allow_html=True,
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# ============================================================
|
| 66 |
+
# LOAD TRAINED RANDOM FOREST PIPELINE
|
| 67 |
+
# ============================================================
|
| 68 |
+
|
| 69 |
+
@st.cache_resource
|
| 70 |
+
def load_predictive_model():
|
| 71 |
+
return joblib.load(MODEL_PATH)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
# ============================================================
|
| 75 |
+
# LOAD LOCAL QWEN MODEL
|
| 76 |
+
# ============================================================
|
| 77 |
+
|
| 78 |
+
@st.cache_resource
|
| 79 |
+
def load_reasoning_model():
|
| 80 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 81 |
+
|
| 82 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 83 |
+
LLM_MODEL_ID
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 87 |
+
LLM_MODEL_ID,
|
| 88 |
+
torch_dtype=torch.float16 if device == "cuda" else torch.float32,
|
| 89 |
+
low_cpu_mem_usage=True,
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
model.to(device)
|
| 93 |
+
model.eval()
|
| 94 |
+
|
| 95 |
+
return tokenizer, model, device
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# ============================================================
|
| 99 |
+
# AGENT 1 β IoT DATA AGENT
|
| 100 |
+
# ============================================================
|
| 101 |
+
|
| 102 |
+
def iot_data_agent(
|
| 103 |
+
product_type,
|
| 104 |
+
air_temperature,
|
| 105 |
+
process_temperature,
|
| 106 |
+
rotational_speed,
|
| 107 |
+
torque,
|
| 108 |
+
tool_wear,
|
| 109 |
+
):
|
| 110 |
+
"""
|
| 111 |
+
Validates and packages incoming IoT-style machine readings.
|
| 112 |
+
"""
|
| 113 |
+
|
| 114 |
+
errors = []
|
| 115 |
+
|
| 116 |
+
if product_type not in {"L", "M", "H"}:
|
| 117 |
+
errors.append("Product Type must be L, M or H.")
|
| 118 |
+
|
| 119 |
+
if air_temperature <= 0:
|
| 120 |
+
errors.append("Air temperature must be greater than 0 K.")
|
| 121 |
+
|
| 122 |
+
if process_temperature <= 0:
|
| 123 |
+
errors.append("Process temperature must be greater than 0 K.")
|
| 124 |
+
|
| 125 |
+
if rotational_speed <= 0:
|
| 126 |
+
errors.append("Rotational speed must be greater than 0 rpm.")
|
| 127 |
+
|
| 128 |
+
if torque < 0:
|
| 129 |
+
errors.append("Torque cannot be negative.")
|
| 130 |
+
|
| 131 |
+
if tool_wear < 0:
|
| 132 |
+
errors.append("Tool wear cannot be negative.")
|
| 133 |
+
|
| 134 |
+
if errors:
|
| 135 |
+
return None, errors
|
| 136 |
+
|
| 137 |
+
sensor_record = pd.DataFrame(
|
| 138 |
+
[
|
| 139 |
+
{
|
| 140 |
+
"Type": product_type,
|
| 141 |
+
"Air temperature [K]": float(air_temperature),
|
| 142 |
+
"Process temperature [K]": float(process_temperature),
|
| 143 |
+
"Rotational speed [rpm]": float(rotational_speed),
|
| 144 |
+
"Torque [Nm]": float(torque),
|
| 145 |
+
"Tool wear [min]": float(tool_wear),
|
| 146 |
+
}
|
| 147 |
+
]
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
return sensor_record, []
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
# ============================================================
|
| 154 |
+
# AGENT 2 β ML PREDICTION AGENT
|
| 155 |
+
# ============================================================
|
| 156 |
+
|
| 157 |
+
def prediction_agent(sensor_record):
|
| 158 |
+
"""
|
| 159 |
+
Calls the trained Random Forest pipeline as a prediction tool.
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
model = load_predictive_model()
|
| 163 |
+
|
| 164 |
+
failure_probability = float(
|
| 165 |
+
model.predict_proba(sensor_record)[0, 1]
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
prediction = int(
|
| 169 |
+
failure_probability >= FAILURE_THRESHOLD
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
if failure_probability >= HIGH_RISK_THRESHOLD:
|
| 173 |
+
risk_level = "HIGH"
|
| 174 |
+
elif failure_probability >= MEDIUM_RISK_THRESHOLD:
|
| 175 |
+
risk_level = "MEDIUM"
|
| 176 |
+
else:
|
| 177 |
+
risk_level = "LOW"
|
| 178 |
+
|
| 179 |
+
return {
|
| 180 |
+
"prediction": prediction,
|
| 181 |
+
"failure_probability": failure_probability,
|
| 182 |
+
"risk_level": risk_level,
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
# ============================================================
|
| 187 |
+
# AGENT 3 β ENGINEERING REASONING AGENT
|
| 188 |
+
# ============================================================
|
| 189 |
+
|
| 190 |
+
def build_engineering_prompt(sensor_record, ml_result):
|
| 191 |
+
row = sensor_record.iloc[0]
|
| 192 |
+
|
| 193 |
+
system_prompt = """
|
| 194 |
+
You are an engineering maintenance reasoning assistant in an educational
|
| 195 |
+
predictive-maintenance prototype.
|
| 196 |
+
|
| 197 |
+
A trained Random Forest model has already produced the machine-failure
|
| 198 |
+
probability. Do not replace or contradict the ML prediction.
|
| 199 |
+
|
| 200 |
+
Use only the supplied sensor readings and ML result. Do not invent
|
| 201 |
+
manufacturer limits, maintenance history, measurements, failure codes,
|
| 202 |
+
or engineering standards that were not provided.
|
| 203 |
+
|
| 204 |
+
Give a concise engineering interpretation suitable for final-year
|
| 205 |
+
engineering students.
|
| 206 |
+
|
| 207 |
+
Return exactly these headings:
|
| 208 |
+
|
| 209 |
+
### Engineering Assessment
|
| 210 |
+
### Evidence from Current Readings
|
| 211 |
+
### Possible Engineering Concern
|
| 212 |
+
### Recommended Next Action
|
| 213 |
+
### Preventive Maintenance Suggestion
|
| 214 |
+
|
| 215 |
+
Always state that the recommendation requires validation by a qualified
|
| 216 |
+
engineer before any real maintenance, shutdown, or repair decision.
|
| 217 |
+
""".strip()
|
| 218 |
+
|
| 219 |
+
user_prompt = f"""
|
| 220 |
+
Machine readings:
|
| 221 |
+
Product Type: {row['Type']}
|
| 222 |
+
Air Temperature: {row['Air temperature [K]']:.1f} K
|
| 223 |
+
Process Temperature: {row['Process temperature [K]']:.1f} K
|
| 224 |
+
Rotational Speed: {row['Rotational speed [rpm]']:.0f} rpm
|
| 225 |
+
Torque: {row['Torque [Nm]']:.1f} Nm
|
| 226 |
+
Tool Wear: {row['Tool wear [min]']:.0f} min
|
| 227 |
+
|
| 228 |
+
Random Forest result:
|
| 229 |
+
Failure Probability: {ml_result['failure_probability']:.1%}
|
| 230 |
+
Risk Level: {ml_result['risk_level']}
|
| 231 |
+
Prediction: {'Failure Risk' if ml_result['prediction'] == 1 else 'Healthy'}
|
| 232 |
+
|
| 233 |
+
Explain what this result means from a predictive-maintenance perspective.
|
| 234 |
+
""".strip()
|
| 235 |
+
|
| 236 |
+
return [
|
| 237 |
+
{"role": "system", "content": system_prompt},
|
| 238 |
+
{"role": "user", "content": user_prompt},
|
| 239 |
+
]
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def engineering_reasoning_agent(sensor_record, ml_result):
|
| 243 |
+
"""
|
| 244 |
+
Uses Qwen to interpret the ML output and sensor readings.
|
| 245 |
+
"""
|
| 246 |
+
|
| 247 |
+
tokenizer, model, device = load_reasoning_model()
|
| 248 |
+
messages = build_engineering_prompt(sensor_record, ml_result)
|
| 249 |
+
|
| 250 |
+
prompt_text = tokenizer.apply_chat_template(
|
| 251 |
+
messages,
|
| 252 |
+
tokenize=False,
|
| 253 |
+
add_generation_prompt=True,
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
inputs = tokenizer(
|
| 257 |
+
prompt_text,
|
| 258 |
+
return_tensors="pt",
|
| 259 |
+
truncation=True,
|
| 260 |
+
max_length=1536,
|
| 261 |
+
).to(device)
|
| 262 |
+
|
| 263 |
+
with torch.inference_mode():
|
| 264 |
+
output_ids = model.generate(
|
| 265 |
+
**inputs,
|
| 266 |
+
max_new_tokens=220,
|
| 267 |
+
do_sample=False,
|
| 268 |
+
repetition_penalty=1.05,
|
| 269 |
+
pad_token_id=tokenizer.eos_token_id,
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
generated_tokens = output_ids[
|
| 273 |
+
0,
|
| 274 |
+
inputs["input_ids"].shape[1]:
|
| 275 |
+
]
|
| 276 |
+
|
| 277 |
+
response = tokenizer.decode(
|
| 278 |
+
generated_tokens,
|
| 279 |
+
skip_special_tokens=True,
|
| 280 |
+
).strip()
|
| 281 |
+
|
| 282 |
+
return response
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
# ============================================================
|
| 286 |
+
# AGENT 4 β MAINTENANCE ACTION AGENT
|
| 287 |
+
# ============================================================
|
| 288 |
+
|
| 289 |
+
def maintenance_agent(sensor_record, ml_result):
|
| 290 |
+
"""
|
| 291 |
+
Creates a structured action/work-order record from the ML result.
|
| 292 |
+
The engineering reasoning text is generated separately by Qwen.
|
| 293 |
+
"""
|
| 294 |
+
|
| 295 |
+
probability = ml_result["failure_probability"]
|
| 296 |
+
risk = ml_result["risk_level"]
|
| 297 |
+
|
| 298 |
+
if risk == "HIGH":
|
| 299 |
+
priority = "P1 - Immediate Engineering Review"
|
| 300 |
+
action = "Inspect the equipment before continued operation."
|
| 301 |
+
elif risk == "MEDIUM":
|
| 302 |
+
priority = "P2 - Priority Inspection"
|
| 303 |
+
action = "Schedule a maintenance inspection and increase monitoring."
|
| 304 |
+
else:
|
| 305 |
+
priority = "P3 - Routine Monitoring"
|
| 306 |
+
action = "Continue monitoring under the normal maintenance plan."
|
| 307 |
+
|
| 308 |
+
work_order_id = datetime.now().strftime("PM-%Y%m%d-%H%M%S")
|
| 309 |
+
|
| 310 |
+
return {
|
| 311 |
+
"work_order_id": work_order_id,
|
| 312 |
+
"work_order_type": "AI-Assisted Predictive Maintenance",
|
| 313 |
+
"priority": priority,
|
| 314 |
+
"failure_probability": f"{probability:.1%}",
|
| 315 |
+
"risk_level": risk,
|
| 316 |
+
"recommended_action": action,
|
| 317 |
+
"assigned_team": "Reliability / Maintenance Engineering",
|
| 318 |
+
"approval_status": "Pending Human Engineer Approval",
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
# ============================================================
|
| 323 |
+
# ORCHESTRATOR
|
| 324 |
+
# ============================================================
|
| 325 |
+
|
| 326 |
+
def run_agentic_workflow(
|
| 327 |
+
product_type,
|
| 328 |
+
air_temperature,
|
| 329 |
+
process_temperature,
|
| 330 |
+
rotational_speed,
|
| 331 |
+
torque,
|
| 332 |
+
tool_wear,
|
| 333 |
+
):
|
| 334 |
+
sensor_record, errors = iot_data_agent(
|
| 335 |
+
product_type,
|
| 336 |
+
air_temperature,
|
| 337 |
+
process_temperature,
|
| 338 |
+
rotational_speed,
|
| 339 |
+
torque,
|
| 340 |
+
tool_wear,
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
if errors:
|
| 344 |
+
return {
|
| 345 |
+
"success": False,
|
| 346 |
+
"errors": errors,
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
ml_result = prediction_agent(sensor_record)
|
| 350 |
+
|
| 351 |
+
reasoning = engineering_reasoning_agent(
|
| 352 |
+
sensor_record,
|
| 353 |
+
ml_result,
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
work_order = maintenance_agent(
|
| 357 |
+
sensor_record,
|
| 358 |
+
ml_result,
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
return {
|
| 362 |
+
"success": True,
|
| 363 |
+
"sensor_record": sensor_record,
|
| 364 |
+
"ml_result": ml_result,
|
| 365 |
+
"reasoning": reasoning,
|
| 366 |
+
"work_order": work_order,
|
| 367 |
+
}
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
# ============================================================
|
| 371 |
+
# SIDEBAR
|
| 372 |
+
# ============================================================
|
| 373 |
+
|
| 374 |
+
with st.sidebar:
|
| 375 |
+
st.header("About the Prototype")
|
| 376 |
+
st.write(
|
| 377 |
+
"""
|
| 378 |
+
This application demonstrates how a trained Machine Learning
|
| 379 |
+
model can be used as a tool inside an Agentic AI workflow.
|
| 380 |
+
"""
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
st.markdown(
|
| 384 |
+
"""
|
| 385 |
+
**Architecture**
|
| 386 |
+
|
| 387 |
+
1. π‘ IoT Data Agent
|
| 388 |
+
2. π€ ML Prediction Agent
|
| 389 |
+
3. π§ Engineering Reasoning Agent
|
| 390 |
+
4. π§ Maintenance Action Agent
|
| 391 |
+
5. π¨βπ§ Human Approval
|
| 392 |
+
"""
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
st.caption(
|
| 396 |
+
"Educational prototype only. Not intended for real industrial safety decisions."
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
# ============================================================
|
| 401 |
+
# MAIN PAGE
|
| 402 |
+
# ============================================================
|
| 403 |
+
|
| 404 |
+
st.markdown(
|
| 405 |
+
'<div class="main-title">π Intelligent Predictive Maintenance System</div>',
|
| 406 |
+
unsafe_allow_html=True,
|
| 407 |
+
)
|
| 408 |
+
|
| 409 |
+
st.markdown(
|
| 410 |
+
'<div class="sub-title">Random Forest + Local Qwen Reasoning + Agentic AI Workflow</div>',
|
| 411 |
+
unsafe_allow_html=True,
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
st.info(
|
| 415 |
+
"Workflow: IoT Data β Random Forest Prediction β Qwen Engineering Reasoning β Maintenance Action β Human Approval"
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
input_col, result_col = st.columns([1, 1.25], gap="large")
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
# ============================================================
|
| 422 |
+
# INPUT PANEL
|
| 423 |
+
# ============================================================
|
| 424 |
+
|
| 425 |
+
with input_col:
|
| 426 |
+
st.subheader("π‘ IoT Machine Parameters")
|
| 427 |
+
|
| 428 |
+
product_type = st.selectbox(
|
| 429 |
+
"Product Type",
|
| 430 |
+
options=["L", "M", "H"],
|
| 431 |
+
index=0,
|
| 432 |
+
help="L = Low, M = Medium, H = High product quality type used in the AI4I dataset.",
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
air_temperature = st.slider(
|
| 436 |
+
"Air Temperature [K]",
|
| 437 |
+
min_value=295.0,
|
| 438 |
+
max_value=305.0,
|
| 439 |
+
value=300.0,
|
| 440 |
+
step=0.1,
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
process_temperature = st.slider(
|
| 444 |
+
"Process Temperature [K]",
|
| 445 |
+
min_value=305.0,
|
| 446 |
+
max_value=315.0,
|
| 447 |
+
value=310.0,
|
| 448 |
+
step=0.1,
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
rotational_speed = st.slider(
|
| 452 |
+
"Rotational Speed [rpm]",
|
| 453 |
+
min_value=1100,
|
| 454 |
+
max_value=2900,
|
| 455 |
+
value=1500,
|
| 456 |
+
step=10,
|
| 457 |
+
)
|
| 458 |
+
|
| 459 |
+
torque = st.slider(
|
| 460 |
+
"Torque [Nm]",
|
| 461 |
+
min_value=3.0,
|
| 462 |
+
max_value=80.0,
|
| 463 |
+
value=45.0,
|
| 464 |
+
step=0.5,
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
tool_wear = st.slider(
|
| 468 |
+
"Tool Wear [min]",
|
| 469 |
+
min_value=0,
|
| 470 |
+
max_value=253,
|
| 471 |
+
value=150,
|
| 472 |
+
step=5,
|
| 473 |
+
)
|
| 474 |
+
|
| 475 |
+
run_button = st.button(
|
| 476 |
+
"π Run Agentic AI Workflow",
|
| 477 |
+
type="primary",
|
| 478 |
+
use_container_width=True,
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
# ============================================================
|
| 483 |
+
# OUTPUT PANEL
|
| 484 |
+
# ============================================================
|
| 485 |
+
|
| 486 |
+
with result_col:
|
| 487 |
+
st.subheader("π€ Machine Intelligence")
|
| 488 |
+
|
| 489 |
+
if not run_button:
|
| 490 |
+
st.write(
|
| 491 |
+
"Enter the operating parameters and run the workflow to see the agents collaborate."
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
if run_button:
|
| 495 |
+
with st.status(
|
| 496 |
+
"Running collaborative AI workflow...",
|
| 497 |
+
expanded=True,
|
| 498 |
+
) as status:
|
| 499 |
+
|
| 500 |
+
st.write("π‘ **Agent 1 β IoT Data Agent:** Validating sensor readings...")
|
| 501 |
+
|
| 502 |
+
sensor_record, errors = iot_data_agent(
|
| 503 |
+
product_type,
|
| 504 |
+
air_temperature,
|
| 505 |
+
process_temperature,
|
| 506 |
+
rotational_speed,
|
| 507 |
+
torque,
|
| 508 |
+
tool_wear,
|
| 509 |
+
)
|
| 510 |
+
|
| 511 |
+
if errors:
|
| 512 |
+
for error in errors:
|
| 513 |
+
st.error(error)
|
| 514 |
+
status.update(
|
| 515 |
+
label="Input validation failed",
|
| 516 |
+
state="error",
|
| 517 |
+
)
|
| 518 |
+
st.stop()
|
| 519 |
+
|
| 520 |
+
st.write("β
Sensor validation complete.")
|
| 521 |
+
|
| 522 |
+
st.write("π€ **Agent 2 β ML Prediction Agent:** Calling trained Random Forest model...")
|
| 523 |
+
|
| 524 |
+
try:
|
| 525 |
+
ml_result = prediction_agent(sensor_record)
|
| 526 |
+
except Exception as exc:
|
| 527 |
+
st.error(f"Unable to load or run the trained ML model: {exc}")
|
| 528 |
+
st.info(
|
| 529 |
+
"Ensure predictive_maintenance_rf_pipeline.pkl is in the same folder as app.py "
|
| 530 |
+
"and that scikit-learn==1.6.1 is installed."
|
| 531 |
+
)
|
| 532 |
+
status.update(
|
| 533 |
+
label="ML prediction failed",
|
| 534 |
+
state="error",
|
| 535 |
+
)
|
| 536 |
+
st.stop()
|
| 537 |
+
|
| 538 |
+
st.write("β
Random Forest prediction complete.")
|
| 539 |
+
|
| 540 |
+
st.write("π§ **Agent 3 β Engineering Reasoning Agent:** Qwen is interpreting the result...")
|
| 541 |
+
|
| 542 |
+
try:
|
| 543 |
+
reasoning = engineering_reasoning_agent(
|
| 544 |
+
sensor_record,
|
| 545 |
+
ml_result,
|
| 546 |
+
)
|
| 547 |
+
except Exception as exc:
|
| 548 |
+
reasoning = (
|
| 549 |
+
"The local language model could not generate an engineering explanation. "
|
| 550 |
+
f"Technical message: {exc}"
|
| 551 |
+
)
|
| 552 |
+
|
| 553 |
+
st.write("β
Engineering interpretation complete.")
|
| 554 |
+
|
| 555 |
+
st.write("π§ **Agent 4 β Maintenance Action Agent:** Creating maintenance action...")
|
| 556 |
+
|
| 557 |
+
work_order = maintenance_agent(
|
| 558 |
+
sensor_record,
|
| 559 |
+
ml_result,
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
st.write("β
Maintenance work order generated.")
|
| 563 |
+
|
| 564 |
+
status.update(
|
| 565 |
+
label="Agentic AI workflow completed",
|
| 566 |
+
state="complete",
|
| 567 |
+
)
|
| 568 |
+
|
| 569 |
+
probability = ml_result["failure_probability"]
|
| 570 |
+
prediction_text = (
|
| 571 |
+
"FAILURE RISK"
|
| 572 |
+
if ml_result["prediction"] == 1
|
| 573 |
+
else "HEALTHY"
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
metric1, metric2, metric3 = st.columns(3)
|
| 577 |
+
|
| 578 |
+
metric1.metric(
|
| 579 |
+
"Machine Status",
|
| 580 |
+
prediction_text,
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
metric2.metric(
|
| 584 |
+
"Failure Probability",
|
| 585 |
+
f"{probability:.1%}",
|
| 586 |
+
)
|
| 587 |
+
|
| 588 |
+
metric3.metric(
|
| 589 |
+
"Risk Level",
|
| 590 |
+
ml_result["risk_level"],
|
| 591 |
+
)
|
| 592 |
+
|
| 593 |
+
st.progress(
|
| 594 |
+
min(max(probability, 0.0), 1.0),
|
| 595 |
+
text=f"Predicted failure probability: {probability:.1%}",
|
| 596 |
+
)
|
| 597 |
+
|
| 598 |
+
with st.expander(
|
| 599 |
+
"π‘ Agent 1 β IoT Data Agent",
|
| 600 |
+
expanded=False,
|
| 601 |
+
):
|
| 602 |
+
st.dataframe(
|
| 603 |
+
sensor_record,
|
| 604 |
+
use_container_width=True,
|
| 605 |
+
hide_index=True,
|
| 606 |
+
)
|
| 607 |
+
|
| 608 |
+
with st.expander(
|
| 609 |
+
"π€ Agent 2 β ML Prediction Agent",
|
| 610 |
+
expanded=True,
|
| 611 |
+
):
|
| 612 |
+
st.write(
|
| 613 |
+
"The trained Random Forest pipeline was called as an ML prediction tool."
|
| 614 |
+
)
|
| 615 |
+
st.json(
|
| 616 |
+
{
|
| 617 |
+
"prediction": prediction_text,
|
| 618 |
+
"failure_probability": round(probability, 4),
|
| 619 |
+
"risk_level": ml_result["risk_level"],
|
| 620 |
+
}
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
with st.expander(
|
| 624 |
+
"π§ Agent 3 β Engineering Reasoning Agent",
|
| 625 |
+
expanded=True,
|
| 626 |
+
):
|
| 627 |
+
st.markdown(reasoning)
|
| 628 |
+
st.caption(
|
| 629 |
+
f"Local reasoning model: {LLM_MODEL_ID}"
|
| 630 |
+
)
|
| 631 |
+
|
| 632 |
+
with st.expander(
|
| 633 |
+
"π§ Agent 4 β Maintenance Action Agent",
|
| 634 |
+
expanded=True,
|
| 635 |
+
):
|
| 636 |
+
st.json(work_order)
|
| 637 |
+
|
| 638 |
+
st.warning(
|
| 639 |
+
"π¨βπ§ Human-in-the-loop: A qualified engineer must validate the recommendation "
|
| 640 |
+
"before any real maintenance, repair, or shutdown action."
|
| 641 |
+
)
|
| 642 |
+
|
| 643 |
+
report = {
|
| 644 |
+
"sensor_readings": sensor_record.iloc[0].to_dict(),
|
| 645 |
+
"ml_prediction": {
|
| 646 |
+
"prediction": prediction_text,
|
| 647 |
+
"failure_probability": probability,
|
| 648 |
+
"risk_level": ml_result["risk_level"],
|
| 649 |
+
},
|
| 650 |
+
"engineering_reasoning": reasoning,
|
| 651 |
+
"maintenance_work_order": work_order,
|
| 652 |
+
}
|
| 653 |
+
|
| 654 |
+
st.download_button(
|
| 655 |
+
"β¬οΈ Download AI Maintenance Report",
|
| 656 |
+
data=json.dumps(report, indent=2),
|
| 657 |
+
file_name="predictive_maintenance_report.json",
|
| 658 |
+
mime="application/json",
|
| 659 |
+
use_container_width=True,
|
| 660 |
+
)
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
# ============================================================
|
| 664 |
+
# EXPLANATION TAB AREA
|
| 665 |
+
# ============================================================
|
| 666 |
+
|
| 667 |
+
st.divider()
|
| 668 |
+
|
| 669 |
+
with st.expander("π How this Agentic AI system works"):
|
| 670 |
+
st.markdown(
|
| 671 |
+
"""
|
| 672 |
+
### 1. Random Forest is the prediction intelligence
|
| 673 |
+
The model was trained separately using the AI4I predictive-maintenance dataset.
|
| 674 |
+
It calculates the probability of machine failure from the current machine readings.
|
| 675 |
+
|
| 676 |
+
### 2. The Prediction Agent uses the RF model as a tool
|
| 677 |
+
The agent does not ask the language model to guess whether the machine will fail.
|
| 678 |
+
|
| 679 |
+
### 3. Qwen provides engineering interpretation
|
| 680 |
+
The local instruction-tuned model receives both the sensor readings and the
|
| 681 |
+
Random Forest prediction and explains the result in natural language.
|
| 682 |
+
|
| 683 |
+
### 4. The Maintenance Agent converts intelligence into action
|
| 684 |
+
It creates a structured maintenance work-order record.
|
| 685 |
+
|
| 686 |
+
### 5. Human approval remains mandatory
|
| 687 |
+
Agentic AI supports engineering decisions; it does not replace engineering accountability.
|
| 688 |
+
"""
|
| 689 |
+
)
|