File size: 29,822 Bytes
783a952
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# ml_module/tools/evaluation_tools.py
import json
from datetime import datetime
from typing import Optional

import pandas as pd
from agno.tools import Toolkit, tool
from sklearn.metrics import (
    accuracy_score,
    classification_report,
    confusion_matrix,
    f1_score,
    precision_score,
    recall_score,
)
from sklearn.model_selection import train_test_split

from ml_module.services.storage_service import MLStorageService
from ml_module.services.project_service import ProjectService
from ml_module.core.exceptions import FileOperationException
from ml_module.core.constants import ArtifactTypes
from ml_module.core.response_formatter import (
    FormattedResponse,
    Severity,
    make_text_response,
    metric_block,
    simple_table,
    simple_table_with_types,
    visualization_block,
    text_block,
)

class ModelEvaluationToolkit(Toolkit):
    """A toolkit for generating deep evaluation artifacts for trained models with versioning and code generation."""
    
    def __init__(self, storage_service: MLStorageService, user_id: str, project_id: str, project_service: Optional[ProjectService] = None):
        super().__init__(name="model_evaluation_tools")
        self.storage = storage_service
        self.user_id = user_id
        self.project_id = project_id
        self.project_service = project_service

    def _get_base_path(self, subfolder: str = "") -> str:
        return f"{self.user_id}/{self.project_id}/{subfolder}"

    @tool
    def generate_confusion_matrix_data(self, model_path: str, dataset_path: str, target_column: str) -> FormattedResponse:
        """
        Generates and saves the data for a confusion matrix visualization.

        Args:
            model_path (str): The path to the trained .joblib model file (e.g., 'models/RandomForest_model.joblib').
            dataset_path (str): The path to the processed dataset used for training (e.g., 'processed/cleaned_data.csv').
            target_column (str): The name of the column the model predicts.

        Returns:
            FormattedResponse: Structured confusion matrix summary with artifact reference.
        """
        try:
            # Load model and data
            model = self.storage.load_model(self._get_base_path() + "/" + model_path)
            df = self.storage.load_dataframe(self._get_base_path() + "/" + dataset_path)

            # Recreate the exact same test set
            X = df.drop(columns=[target_column])
            y = df[target_column]
            _, X_test, _, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
            
            # Generate predictions and matrix
            y_pred = model.predict(X_test)
            labels = sorted(y.unique().tolist())
            matrix = confusion_matrix(y_test, y_pred, labels=labels)
            
            # Format for frontend rendering
            output_data = {
                "labels": labels,
                "matrix": matrix.tolist()
            }
            
            output_path = f"{self._get_base_path('evaluation')}/confusion_matrix.json"
            info = self.storage.save_json(output_data, output_path)

            rows = [
                {"actual": labels[i], **{str(labels[j]): matrix[i][j] for j in range(len(labels))}}
                for i in range(len(labels))
            ]
            blocks = [
                text_block("Calculated confusion matrix on held-out test set", severity=Severity.SUCCESS),
                simple_table(rows, caption="Confusion matrix", block_id="confusion_matrix"),
                text_block(f"Matrix JSON saved to `{output_path}`"),
            ]

            return FormattedResponse(
                blocks=blocks,
                summary="Generated confusion matrix",
                correlation_id=info.path,
                done=True,
            )
        except Exception as e:
            raise FileOperationException("generate confusion matrix", model_path, e)

    @tool
    def get_feature_importance(self, model_path: str) -> FormattedResponse:
        """
        Extracts and saves the feature importance scores from a model.
        NOTE: This tool is only applicable for models that support feature_importances_,
        such as RandomForest. It will fail for models like LogisticRegression.

        Args:
            model_path (str): The path to the trained .joblib model file.

        Returns:
            FormattedResponse: Structured feature importance summary or warning when unavailable.
        """
        try:
            model = self.storage.load_model(self._get_base_path() + "/" + model_path)
            
            if not hasattr(model, 'feature_importances_'):
                response = make_text_response(
                    "The selected model does not support feature importance extraction.",
                    severity=Severity.WARNING,
                )
                response.summary = "Feature importance unavailable"
                response.done = True
                return response
            
            importances = model.feature_importances_
            feature_names = model.feature_names_in_
            
            importance_data = sorted(
                [{"feature": name, "importance": score} for name, score in zip(feature_names, importances)],
                key=lambda x: x["importance"],
                reverse=True
            )
            
            output_path = f"{self._get_base_path('evaluation')}/feature_importance.json"
            info = self.storage.save_json(importance_data, output_path)

            # Create visualization block for bar chart
            top_features = importance_data[:15]  # Top 15 features for visualization
            
            blocks = [
                text_block("Extracted model feature importances", severity=Severity.SUCCESS),
                visualization_block(
                    top_features,
                    chart_type="bar",
                    title="Top Feature Importances",
                    subtitle=f"Showing top {len(top_features)} most important features",
                    block_id="feature_importance_chart"
                ),
                simple_table_with_types(importance_data[:10], caption="Top features (detailed)", block_id="feature_importance"),
                text_block(f"Feature importance saved to `{output_path}`"),
            ]

            return FormattedResponse(
                blocks=blocks,
                summary="Captured feature importance",
                correlation_id=info.path,
                done=True,
            )
        except Exception as e:
            raise FileOperationException("get feature importance", model_path, e)
    
    def generate_evaluation_code(
        self, 
        model_path: str, 
        dataset_path: str, 
        target_column: str, 
        model_type: str,
        version: int
    ) -> str:
        """
        Generate executable Python code that reproduces the evaluation process.
        
        Args:
            model_path: Path to the trained model
            dataset_path: Path to the processed dataset  
            target_column: Name of the target column
            model_type: Type of model being evaluated
            version: Version number for this evaluation code
            
        Returns:
            str: The generated Python evaluation code
        """
        timestamp = datetime.now().isoformat()
        
        # Generate comprehensive evaluation code
        code = f'''#!/usr/bin/env python3
"""
Generated ML Evaluation Code - Version {version}
Generated on: {timestamp}
Model Type: {model_type}
Target Column: {target_column}
Model Path: {model_path}
Dataset Path: {dataset_path}

This code reproduces the exact evaluation process used by the ML system.
"""

import pandas as pd
import joblib
import json
import numpy as np
from datetime import datetime
from sklearn.model_selection import train_test_split
from sklearn.metrics import (
    confusion_matrix, classification_report, accuracy_score, 
    precision_score, recall_score, f1_score
)

def evaluate_model():
    """Main evaluation function"""
    print("="*50)
    print("πŸ” ML MODEL EVALUATION")
    print("="*50)
    
    try:
        # 1. Load Model and Data
        print("\\n1. Loading model and dataset...")
        model = joblib.load('{model_path}')
        df = pd.read_csv('{dataset_path}')
        print(f"   Model loaded: {model_type}")
        print(f"   Dataset shape: {{df.shape}}")
        
        # 2. Prepare Data (same split as training)
        print("\\n2. Preparing evaluation data...")
        if '{target_column}' not in df.columns:
            raise ValueError(f"Target column '{{target_column}}' not found in dataset")
        
        X = df.drop(columns=['{target_column}'])
        y = df['{target_column}']
        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
        
        print(f"   Test set samples: {{len(X_test)}}")
        print(f"   Features: {{list(X.columns)}}")
        
        # 3. Generate Predictions
        print("\\n3. Generating predictions...")
        y_pred = model.predict(X_test)
        print("   Predictions generated successfully!")
        
        # 4. Calculate Metrics
        print("\\n4. Calculating evaluation metrics...")
        
        # Basic metrics
        accuracy = accuracy_score(y_test, y_pred)
        precision = precision_score(y_test, y_pred, average='weighted')
        recall = recall_score(y_test, y_pred, average='weighted')
        f1 = f1_score(y_test, y_pred, average='weighted')
        
        # Confusion matrix
        labels = sorted(y.unique().tolist())
        cm = confusion_matrix(y_test, y_pred, labels=labels)
        
        # Feature importance (if available)
        feature_importance = None
        if hasattr(model, 'feature_importances_'):
            importance_scores = model.feature_importances_
            feature_names = X.columns.tolist()
            feature_importance = sorted(
                [{{"feature": name, "importance": float(score)}} 
                 for name, score in zip(feature_names, importance_scores)],
                key=lambda x: x["importance"], reverse=True
            )
        
        # 5. Prepare Results
        evaluation_results = {{
            "model_type": "{model_type}",
            "version": {version},
            "timestamp": datetime.now().isoformat(),
            "evaluation_info": {{
                "test_samples": len(X_test),
                "total_features": len(X.columns),
                "target_column": "{target_column}",
                "unique_classes": labels
            }},
            "performance": {{
                "accuracy": float(accuracy),
                "precision": float(precision),
                "recall": float(recall),
                "f1_score": float(f1)
            }},
            "confusion_matrix": {{
                "labels": labels,
                "matrix": cm.tolist()
            }},
            "feature_importance": feature_importance,
            "classification_report": classification_report(y_test, y_pred, output_dict=True)
        }}
        
        # 6. Display Results
        print("\\n" + "="*50)
        print("πŸ“Š EVALUATION RESULTS")
        print("="*50)
        print(f"Accuracy: {{accuracy:.4f}}")
        print(f"Precision: {{precision:.4f}}")
        print(f"Recall: {{recall:.4f}}")
        print(f"F1 Score: {{f1:.4f}}")
        
        if feature_importance:
            print("\\nπŸ” Top 5 Most Important Features:")
            for i, feat in enumerate(feature_importance[:5]):
                print(f"   {{i+1}}. {{feat['feature']}}: {{feat['importance']:.4f}}")
        
        print("\\nπŸ“ˆ Confusion Matrix:")
        print("   Labels:", labels)
        for i, row in enumerate(cm):
            print(f"   {{labels[i]}}: {{row.tolist()}}")
        
        # 7. Save Results
        print("\\n7. Saving evaluation results...")
        
        # Save confusion matrix
        with open(f'confusion_matrix_v{version}.json', 'w') as f:
            json.dump(evaluation_results["confusion_matrix"], f, indent=2)
        print(f"   Confusion matrix saved: confusion_matrix_v{version}.json")
        
        # Save feature importance (if available)
        if feature_importance:
            with open(f'feature_importance_v{version}.json', 'w') as f:
                json.dump(feature_importance, f, indent=2)
            print(f"   Feature importance saved: feature_importance_v{version}.json")
        
        # Save complete evaluation results
        with open(f'evaluation_results_v{version}.json', 'w') as f:
            json.dump(evaluation_results, f, indent=2)
        print(f"   Complete results saved: evaluation_results_v{version}.json")
        
        print("\\nπŸŽ‰ Evaluation completed successfully!")
        return evaluation_results
        
    except Exception as e:
        print(f"\\n❌ Evaluation failed: {{str(e)}}")
        raise e

if __name__ == "__main__":
    # Execute evaluation
    results = evaluate_model()
    print("\\n" + "="*50)
    print("EVALUATION SUMMARY")
    print("="*50)
    print(f"Model Type: {{results['model_type']}}")
    print(f"Version: {{results['version']}}")
    print(f"Accuracy: {{results['performance']['accuracy']:.4f}}")
    print(f"F1 Score: {{results['performance']['f1_score']:.4f}}")
    print("="*50)
'''
        return code
    
    @tool
    def comprehensive_model_evaluation(
        self,
        model_path: str,
        dataset_path: str, 
        target_column: str,
        model_type: str
    ) -> FormattedResponse:
        """
        Perform comprehensive model evaluation with versioned artifacts generation.
        This is the main evaluation tool that creates all evaluation artifacts.
        
        Args:
            model_path (str): Path to the trained model (.joblib file)
            dataset_path (str): Path to the processed dataset used for training
            target_column (str): Name of the target column the model predicts
            model_type (str): Type of model being evaluated (e.g., 'RandomForest')
            
        Returns:
            FormattedResponse: Structured evaluation summary with artifact references
        """
        try:
            # Get current evaluation version
            current_version = 1
            if self.project_service:
                try:
                    current_version = self.project_service.get_latest_version(self.user_id, self.project_id, "evaluation") + 1
                except:
                    pass  # Use version 1 if no previous evaluations
            
            # 1. Generate confusion matrix data
            self.generate_confusion_matrix_data(model_path, dataset_path, target_column)
            
            # Load the generated confusion matrix for versioned storage
            cm_path = f"{self._get_base_path('evaluation')}/confusion_matrix.json"
            confusion_matrix_data = self.storage.load_json(cm_path)
            
            # 2. Generate feature importance (if supported)
            feature_importance_data = None
            try:
                fi_response = self.get_feature_importance(model_path)
                if fi_response.summary != "Feature importance unavailable":
                    fi_path = f"{self._get_base_path('evaluation')}/feature_importance.json"
                    feature_importance_data = self.storage.load_json(fi_path)
            except Exception:
                feature_importance_data = None
            
            # 3. Load model and data for additional metrics
            model = self.storage.load_model(self._get_base_path() + "/" + model_path)
            df = self.storage.load_dataframe(self._get_base_path() + "/" + dataset_path)
            
            # Prepare data (same split as training)
            X = df.drop(columns=[target_column])
            y = df[target_column]
            _, X_test, _, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
            
            # Generate predictions
            y_pred = model.predict(X_test)
            
            # Calculate comprehensive metrics
            accuracy = accuracy_score(y_test, y_pred)
            precision = precision_score(y_test, y_pred, average='weighted')
            recall = recall_score(y_test, y_pred, average='weighted')
            f1 = f1_score(y_test, y_pred, average='weighted')
            
            # Get classification report
            class_report = classification_report(y_test, y_pred, output_dict=True)
            
            # 4. Generate evaluation code
            evaluation_code = self.generate_evaluation_code(
                model_path, dataset_path, target_column, model_type, current_version
            )
            
            # 5. Create comprehensive evaluation report
            report_content = f"""# Model Evaluation Report - Version {current_version}

**Generated on:** {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}  
**Model Type:** {model_type}  
**Target Column:** {target_column}  
**Dataset:** {dataset_path}  

## πŸ“Š Performance Summary

| Metric | Score |
|--------|-------|
| **Accuracy** | {accuracy:.4f} |
| **Precision** | {precision:.4f} |
| **Recall** | {recall:.4f} |
| **F1 Score** | {f1:.4f} |

## πŸ“ˆ Confusion Matrix Analysis

The confusion matrix shows how well the model predicts each class:

**Labels:** {confusion_matrix_data['labels']}

**Matrix:**
```
{self._format_confusion_matrix(confusion_matrix_data['matrix'], confusion_matrix_data['labels'])}
```

### Interpretation:
- **Diagonal values** represent correct predictions
- **Off-diagonal values** represent misclassifications
- **Higher diagonal values** indicate better performance for that class

## πŸ” Feature Importance Analysis

{self._generate_feature_importance_section(feature_importance_data)}

## πŸ“‹ Detailed Classification Report

```json
{json.dumps(class_report, indent=2)}
```

## 🎯 Model Assessment

### Strengths:
- Overall accuracy of {accuracy:.1%}
- {'Strong' if f1 > 0.8 else 'Moderate' if f1 > 0.6 else 'Needs improvement'} F1 score ({f1:.4f})

### Areas for Improvement:
{self._generate_improvement_suggestions(accuracy, precision, recall, f1)}

## πŸ”§ Reproducibility

The evaluation can be reproduced using the generated evaluation code:
- **Evaluation Code:** `evaluation_code_v{current_version}.py`
- **Confusion Matrix Data:** `confusion_matrix_v{current_version}.json`
{f"- **Feature Importance Data:** `feature_importance_v{current_version}.json`" if feature_importance_data else ""}

## πŸ“ Generated Artifacts

All evaluation artifacts have been saved with version {current_version}:

1. **Confusion Matrix:** Contains prediction accuracy breakdown by class
2. **Evaluation Report:** This comprehensive analysis document
3. **Evaluation Code:** Executable Python script to reproduce results
{f"4. **Feature Importance:** Model feature ranking and scores" if feature_importance_data else ""}

---
*This report was generated automatically by the ML Evaluation System.*
"""

            # 6. Save all versioned artifacts using enhanced storage
            cm_info = self.storage.save_evaluation_artifact(
                self.user_id,
                self.project_id,
                'confusion_matrix',
                confusion_matrix_data,
                current_version,
                f"Confusion matrix for {model_type} evaluation",
            )

            fi_info = None
            if feature_importance_data:
                fi_info = self.storage.save_evaluation_artifact(
                    self.user_id,
                    self.project_id,
                    'feature_importance',
                    feature_importance_data,
                    current_version,
                    f"Feature importance for {model_type} evaluation",
                )

            report_info = self.storage.save_evaluation_artifact(
                self.user_id,
                self.project_id,
                'report',
                report_content,
                current_version,
                f"Comprehensive evaluation report for {model_type}",
            )

            code_info = self.storage.save_evaluation_artifact(
                self.user_id,
                self.project_id,
                'code',
                evaluation_code,
                current_version,
                f"Reproducible evaluation code for {model_type}",
            )

            if self.project_service:
                evaluation_meta = {
                    "model_type": model_type,
                    "target_column": target_column,
                    "accuracy": accuracy,
                    "precision": precision,
                    "recall": recall,
                    "f1_score": f1,
                }

                self.project_service.register_artifact(
                    self.user_id,
                    self.project_id,
                    ArtifactTypes.CONFUSION_MATRIX,
                    current_version,
                    cm_info,
                    version_scope="evaluation",
                    extra_metadata={**evaluation_meta, "labels": confusion_matrix_data.get("labels", [])},
                )

                if fi_info:
                    self.project_service.register_artifact(
                        self.user_id,
                        self.project_id,
                        ArtifactTypes.FEATURE_IMPORTANCE,
                        current_version,
                        fi_info,
                        version_scope="evaluation",
                        extra_metadata={**evaluation_meta},
                    )

                self.project_service.register_artifact(
                    self.user_id,
                    self.project_id,
                    ArtifactTypes.EVALUATION_REPORT,
                    current_version,
                    report_info,
                    version_scope="evaluation",
                    extra_metadata={**evaluation_meta},
                )

                self.project_service.register_artifact(
                    self.user_id,
                    self.project_id,
                    ArtifactTypes.EVALUATION_CODE,
                    current_version,
                    code_info,
                    version_scope="evaluation",
                    extra_metadata={**evaluation_meta, "lines_of_code": evaluation_code.count("\n") + 1},
                )
            
            # 7. Return comprehensive structured response
            cm_filename = cm_info.path.split("/")[-1]
            report_filename = report_info.path.split("/")[-1]
            code_filename = code_info.path.split("/")[-1]
            fi_filename = fi_info.path.split("/")[-1] if fi_info else None

            cm_labels = confusion_matrix_data.get("labels", [])
            cm_matrix = confusion_matrix_data.get("matrix", [])
            cm_rows = [
                {
                    "actual": label,
                    **{f"pred_{pred_label}": value for pred_label, value in zip(cm_labels, row)},
                }
                for label, row in zip(cm_labels, cm_matrix)
            ]

            artifact_lines = [
                f"- Confusion matrix: `{cm_filename}`",
                f"- Evaluation report: `{report_filename}`",
                f"- Evaluation code: `{code_filename}`",
            ]
            if fi_filename:
                artifact_lines.append(f"- Feature importance: `{fi_filename}`")

            insights = [
                "- Model shows strong predictive performance" if accuracy > 0.85 else "- Model shows moderate predictive performance",
            ]
            if abs(precision - recall) >= 0.05:
                insights.append("- Precision and recall diverge; inspect class balance")
            else:
                insights.append("- Precision and recall remain balanced")
            if feature_importance_data:
                top_feature = feature_importance_data[0]
                insights.append(f"- Top feature: {top_feature['feature']} ({top_feature['importance']:.4f})")

            next_steps = [
                "Review the evaluation report",
                "Inspect confusion matrix for class-level accuracy",
                "Use generated code to reproduce results",
            ]
            if feature_importance_data:
                next_steps.append("Analyse feature importance for interpretability")

            blocks = [
                text_block(
                    f"Completed evaluation run v{current_version} for `{model_type}`",
                    severity=Severity.SUCCESS,
                ),
                metric_block("Accuracy", accuracy),
                metric_block("Precision", precision),
                metric_block("Recall", recall),
                metric_block("F1 Score", f1),
                visualization_block(
                    [
                        {"metric": "Accuracy", "score": accuracy},
                        {"metric": "Precision", "score": precision},
                        {"metric": "Recall", "score": recall},
                        {"metric": "F1 Score", "score": f1},
                    ],
                    chart_type="bar",
                    title="Model Performance Metrics",
                    subtitle=f"Evaluation v{current_version}",
                    block_id="evaluation_metrics_chart"
                ),
                text_block("\n".join(artifact_lines), severity=Severity.INFO, block_id="evaluation_artifacts"),
                simple_table_with_types(cm_rows, caption="Confusion matrix (actual vs predicted)", block_id="evaluation_confusion_matrix"),
                text_block("**Insights**\n" + "\n".join(insights), severity=Severity.INFO, block_id="evaluation_insights"),
                text_block(
                    "**Next steps**\n" + "\n".join(f"- {step}" for step in next_steps),
                    severity=Severity.INFO,
                    block_id="evaluation_next_steps",
                ),
            ]

            if feature_importance_data:
                # Add chart for feature importance
                blocks.insert(
                    6,
                    visualization_block(
                        feature_importance_data[:10],
                        chart_type="bar",
                        title="Top Feature Importances",
                        subtitle=f"Top 10 features impacting {model_type} predictions",
                        block_id="feature_importance_chart"
                    ),
                )
                blocks.insert(
                    7,
                    simple_table_with_types(
                        feature_importance_data[:5],
                        caption="Top feature importances (detailed)",
                        block_id="feature_importance_top",
                    ),
                )
            else:
                blocks.insert(
                    5,
                    text_block(
                        "Feature importance not available for this model type",
                        severity=Severity.WARNING,
                        block_id="feature_importance_warning",
                    ),
                )

            return FormattedResponse(
                blocks=blocks,
                summary=f"Evaluation complete v{current_version}",
                correlation_id=report_info.path,
                done=True,
            )
            
        except Exception as e:
            raise FileOperationException("comprehensive model evaluation", model_path, e)
    
    def _format_confusion_matrix(self, matrix, labels):
        """Format confusion matrix for markdown display"""
        formatted = "    " + "    ".join(f"{label:>8}" for label in labels) + "\\n"
        for i, row in enumerate(matrix):
            formatted += f"{labels[i]:>8}" + "".join(f"{val:>8}" for val in row) + "\\n"
        return formatted
    
    def _generate_feature_importance_section(self, feature_importance_data):
        """Generate feature importance section for report"""
        if not feature_importance_data:
            return "Feature importance analysis is not available for this model type."
        
        section = "The following features have the most impact on model predictions:\\n\\n"
        section += "| Rank | Feature | Importance Score |\\n"
        section += "|------|---------|------------------|\\n"
        
        for i, feat in enumerate(feature_importance_data[:10]):  # Top 10 features
            section += f"| {i+1} | {feat['feature']} | {feat['importance']:.4f} |\\n"
        
        return section
    
    def _generate_improvement_suggestions(self, accuracy, precision, recall, f1):
        """Generate improvement suggestions based on metrics"""
        suggestions = []
        
        if accuracy < 0.7:
            suggestions.append("- Consider collecting more training data")
            suggestions.append("- Try different model algorithms or hyperparameters")
        
        if precision < recall:
            suggestions.append("- Model may be predicting too many positive cases")
            suggestions.append("- Consider adjusting classification threshold")
        elif recall < precision:
            suggestions.append("- Model may be too conservative in predictions")
            suggestions.append("- Consider feature engineering or data augmentation")
        
        if f1 < 0.6:
            suggestions.append("- Significant model improvement needed")
            suggestions.append("- Review data quality and feature selection")
        
        return "\\n".join(suggestions) if suggestions else "- Model performance appears satisfactory"