File size: 15,311 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
# ml_module/tools/model_training_tools.py
import io
from datetime import datetime
from typing import Optional

import joblib
import pandas as pd
from agno.tools import Toolkit, tool
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, 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,
    ProgressBlock,
    ProgressStatus,
    Severity,
    make_text_response,
    metric_block,
    simple_table,
    simple_table_with_types,
    visualization_block,
    text_block,
)

class ModelTrainingToolkit(Toolkit):
    """A toolkit for safely training and evaluating pre-approved scikit-learn models with code generation."""
    def __init__(self, storage_service: MLStorageService, user_id: str, project_id: str, project_service: Optional[ProjectService] = None):
        super().__init__(name="model_training_tools")
        self.storage = storage_service
        self.project_service = project_service
        self.user_id = user_id
        self.project_id = project_id

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

    def generate_training_code(
        self,
        input_path: str,
        target_column: str,
        model_type: str,
        version: int
    ) -> str:
        """
        Generates executable Python code that reproduces the training process.
        
        Args:
            input_path (str): The path to the processed dataset
            target_column (str): The name of the target column
            model_type (str): The type of model to train
            version (int): The version number for this training code
            
        Returns:
            str: The generated Python code
        """
        # Model configuration mapping
        model_configs = {
            'RandomForest': {
                'import': 'from sklearn.ensemble import RandomForestClassifier',
                'init': 'RandomForestClassifier(random_state=42)',
                'params': 'random_state=42'
            },
            'LogisticRegression': {
                'import': 'from sklearn.linear_model import LogisticRegression',
                'init': 'LogisticRegression(random_state=42)',
                'params': 'random_state=42'
            }
        }
        
        if model_type not in model_configs:
            raise ValueError(f"Unsupported model type: {model_type}")
        
        config = model_configs[model_type]
        timestamp = datetime.now().isoformat()
        
        # Generate the training code
        code = f'''#!/usr/bin/env python3
"""
Generated ML Training Code - Version {version}
Generated on: {timestamp}
Model Type: {model_type}
Target Column: {target_column}
Input Data: {input_path}

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

import pandas as pd
import joblib
from sklearn.model_selection import train_test_split
{config['import']}
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
import json
import os
from datetime import datetime

def train_model():
    """Main training function that reproduces the ML workflow."""
    try:
        print(f"Starting training process for {{model_type}} model...")
        print(f"Timestamp: {{datetime.now().isoformat()}}")
        
        # 1. Load Data
        print("\\n1. Loading dataset...")
        input_file = "{input_path}"
        if not os.path.exists(input_file):
            raise FileNotFoundError(f"Input file not found: {{input_file}}")
        
        df = pd.read_csv(input_file)
        print(f"   Loaded dataset with {{len(df)}} rows and {{len(df.columns)}} columns")
        
        # 2. Prepare Data (Train-Test Split)
        print("\\n2. Preparing data...")
        target_column = "{target_column}"
        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"   Training set: {{len(X_train)}} samples")
        print(f"   Testing set: {{len(X_test)}} samples")
        print(f"   Features: {{list(X.columns)}}")
        
        # 3. Initialize and Train Model
        print("\\n3. Training model...")
        model = {config['init']}
        print(f"   Model configuration: {config['params']}")
        model.fit(X_train, y_train)
        print("   Model training completed successfully!")
        
        # 4. Evaluate Model
        print("\\n4. Evaluating model performance...")
        y_pred = model.predict(X_test)
        
        metrics = {{
            "model_type": "{model_type}",
            "version": {version},
            "timestamp": datetime.now().isoformat(),
            "data_info": {{
                "total_samples": len(df),
                "training_samples": len(X_train),
                "testing_samples": len(X_test),
                "features": list(X.columns)
            }},
            "performance": {{
                "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_score": f1_score(y_test, y_pred, average='weighted')
            }}
        }}
        
        print("   Model Performance:")
        for metric, value in metrics["performance"].items():
            print(f"   - {{metric.title()}}: {{value:.4f}}")
        
        # 5. Save Artifacts
        print("\\n5. Saving model artifacts...")
        model_filename = f"{model_type}_model_v{version}.joblib"
        metrics_filename = f"{model_type}_metrics_v{version}.json"
        
        # Save model
        joblib.dump(model, model_filename)
        print(f"   Model saved: {{model_filename}}")
        
        # Save metrics
        with open(metrics_filename, 'w') as f:
            json.dump(metrics, f, indent=2)
        print(f"   Metrics saved: {{metrics_filename}}")
        
        print("\\n🎉 Training completed successfully!")
        return metrics
        
    except Exception as e:
        print(f"\\n❌ Training failed: {{str(e)}}")
        raise e

if __name__ == "__main__":
    # Execute training
    results = train_model()
    print("\\n" + "="*50)
    print("TRAINING 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 train_sklearn_classifier(
        self,
        input_path: str,
        target_column: str,
        model_type: str
    ) -> FormattedResponse:
        """
        Trains a specified classification model, evaluates its performance, saves
        both the model artifact and metrics, and generates reproducible training code.

        Args:
            input_path (str): The path to the processed dataset (e.g., 'processed/cleaned_data.csv').
            target_column (str): The name of the column to be predicted.
            model_type (str): The type of model to train. Must be one of: 'RandomForest', 'LogisticRegression'.

        Returns:
            FormattedResponse: Structured confirmation with metrics and artifact references.
        """
        supported_models = {
            'RandomForest': RandomForestClassifier(random_state=42),
            'LogisticRegression': LogisticRegression(random_state=42)
        }
        if model_type not in supported_models:
            response = make_text_response(
                f"Model type '{model_type}' is not supported. Choose from {list(supported_models.keys())}.",
                severity=Severity.ERROR,
            )
            response.summary = "Unsupported model type"
            response.done = True
            return response

        try:
            # Get current model version
            current_version = 1
            if self.project_service:
                current_version = self.project_service.get_latest_version(
                    self.user_id, self.project_id, "model"
                ) + 1
            
            # 1. Load Data
            source_path = self._get_base_path() + "/" + input_path
            df = self.storage.load_dataframe(source_path)
            
            # 2. Prepare Data (Train-Test Split)
            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)
            
            # 3. Train Model
            model = supported_models[model_type]
            model.fit(X_train, y_train)
            
            # 4. Evaluate Model
            y_pred = model.predict(X_test)
            metrics = {
                "model_type": model_type,
                "version": current_version,
                "timestamp": datetime.now().isoformat(),
                "data_info": {
                    "total_samples": len(df),
                    "training_samples": len(X_train),
                    "testing_samples": len(X_test),
                    "features": list(X.columns),
                    "target_column": target_column
                },
                "performance": {
                    "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_score": f1_score(y_test, y_pred, average='weighted')
                }
            }
            
            # 5. Generate Training Code
            training_code = self.generate_training_code(
                input_path=input_path,
                target_column=target_column,
                model_type=model_type,
                version=current_version
            )
            
            # 6. Save Artifacts with versioning
            model_path = f"{self._get_base_path('models')}/{model_type}_model_v{current_version}.joblib"
            metrics_path = f"{self._get_base_path('models')}/{model_type}_metrics_v{current_version}.json"
            code_path = f"{self._get_base_path('models')}/training_code_v{current_version}.py"

            model_buffer = io.BytesIO()
            joblib.dump(model, model_buffer)
            model_info = self.storage.save_bytes(
                model_buffer.getvalue(),
                model_path,
                content_type="application/octet-stream",
            )

            metrics_info = self.storage.save_json(metrics, metrics_path)
            metrics_info.metadata.update({"model_type": model_type, "version": current_version})

            code_info = self.storage.save_text(training_code, code_path)
            code_info.metadata.update({"model_type": model_type, "version": current_version})

            # Record artifacts in project registry for lifecycle tracking
            if self.project_service:
                data_info = metrics.get("data_info", {})
                common_metadata = {
                    "model_type": model_type,
                    "target_column": target_column,
                    "features": data_info.get("features", []),
                }
                performance = metrics.get("performance", {})

                self.project_service.register_artifact(
                    self.user_id,
                    self.project_id,
                    ArtifactTypes.MODEL_ARTIFACT,
                    current_version,
                    model_info,
                    version_scope="model",
                    extra_metadata={**common_metadata, "performance": performance},
                )

                self.project_service.register_artifact(
                    self.user_id,
                    self.project_id,
                    ArtifactTypes.MODEL_METRICS,
                    current_version,
                    metrics_info,
                    version_scope="model",
                    extra_metadata={**common_metadata, "performance": performance},
                )

                self.project_service.register_artifact(
                    self.user_id,
                    self.project_id,
                    ArtifactTypes.TRAINING_CODE,
                    current_version,
                    code_info,
                    version_scope="model",
                    extra_metadata={
                        **common_metadata,
                        "lines_of_code": training_code.count("\n") + 1,
                    },
                )
            
            blocks = [
                text_block(
                    f"Trained `{model_type}` model version {current_version}",
                    severity=Severity.SUCCESS,
                ),
                metric_block("Accuracy", metrics["performance"]["accuracy"]),
                metric_block("Precision", metrics["performance"]["precision"]),
                metric_block("Recall", metrics["performance"]["recall"]),
                metric_block("F1 Score", metrics["performance"]["f1_score"]),
                text_block(
                    "**Artifacts saved**\n" + "\n".join(
                        [
                            f"- Model artifact: `{model_path}`",
                            f"- Metrics JSON: `{metrics_path}`",
                            f"- Training code: `{code_path}`",
                        ]
                    ),
                    severity=Severity.INFO,
                    block_id="training_artifacts",
                ),
                simple_table(
                    [
                        {
                            "features": len(metrics["data_info"].get("features", [])),
                            "train_rows": metrics["data_info"].get("training_samples"),
                            "test_rows": metrics["data_info"].get("testing_samples"),
                        }
                    ],
                    caption="Dataset split",
                    block_id="training_dataset_split",
                ),
                text_block(
                    "**Next steps**\n- Review metrics JSON\n- Validate artifacts before deployment",
                    severity=Severity.INFO,
                    block_id="training_next_steps",
                ),
            ]

            return FormattedResponse(
                blocks=blocks,
                summary=f"Trained {model_type} model v{current_version}",
                correlation_id=model_info.path,
                done=True,
            )

        except Exception as e:
            raise FileOperationException(f"train model '{model_type}'", source_path, e)