ds-agent-cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/bin/ds-agent.js +451 -0
  2. package/ds_agent/__init__.py +8 -0
  3. package/package.json +28 -0
  4. package/requirements.txt +126 -0
  5. package/setup.py +35 -0
  6. package/src/__init__.py +7 -0
  7. package/src/_compress_tool_result.py +118 -0
  8. package/src/api/__init__.py +4 -0
  9. package/src/api/app.py +1626 -0
  10. package/src/cache/__init__.py +5 -0
  11. package/src/cache/cache_manager.py +561 -0
  12. package/src/cli.py +2886 -0
  13. package/src/dynamic_prompts.py +281 -0
  14. package/src/orchestrator.py +4799 -0
  15. package/src/progress_manager.py +139 -0
  16. package/src/reasoning/__init__.py +332 -0
  17. package/src/reasoning/business_summary.py +431 -0
  18. package/src/reasoning/data_understanding.py +356 -0
  19. package/src/reasoning/model_explanation.py +383 -0
  20. package/src/reasoning/reasoning_trace.py +239 -0
  21. package/src/registry/__init__.py +3 -0
  22. package/src/registry/tools_registry.py +3 -0
  23. package/src/session_memory.py +448 -0
  24. package/src/session_store.py +370 -0
  25. package/src/storage/__init__.py +19 -0
  26. package/src/storage/artifact_store.py +620 -0
  27. package/src/storage/helpers.py +116 -0
  28. package/src/storage/huggingface_storage.py +694 -0
  29. package/src/storage/r2_storage.py +0 -0
  30. package/src/storage/user_files_service.py +288 -0
  31. package/src/tools/__init__.py +335 -0
  32. package/src/tools/advanced_analysis.py +823 -0
  33. package/src/tools/advanced_feature_engineering.py +708 -0
  34. package/src/tools/advanced_insights.py +578 -0
  35. package/src/tools/advanced_preprocessing.py +549 -0
  36. package/src/tools/advanced_training.py +906 -0
  37. package/src/tools/agent_tool_mapping.py +326 -0
  38. package/src/tools/auto_pipeline.py +420 -0
  39. package/src/tools/autogluon_training.py +1480 -0
  40. package/src/tools/business_intelligence.py +860 -0
  41. package/src/tools/cloud_data_sources.py +581 -0
  42. package/src/tools/code_interpreter.py +390 -0
  43. package/src/tools/computer_vision.py +614 -0
  44. package/src/tools/data_cleaning.py +614 -0
  45. package/src/tools/data_profiling.py +593 -0
  46. package/src/tools/data_type_conversion.py +268 -0
  47. package/src/tools/data_wrangling.py +433 -0
  48. package/src/tools/eda_reports.py +284 -0
  49. package/src/tools/enhanced_feature_engineering.py +241 -0
  50. package/src/tools/feature_engineering.py +302 -0
  51. package/src/tools/matplotlib_visualizations.py +1327 -0
  52. package/src/tools/model_training.py +520 -0
  53. package/src/tools/nlp_text_analytics.py +761 -0
  54. package/src/tools/plotly_visualizations.py +497 -0
  55. package/src/tools/production_mlops.py +852 -0
  56. package/src/tools/time_series.py +507 -0
  57. package/src/tools/tools_registry.py +2133 -0
  58. package/src/tools/visualization_engine.py +559 -0
  59. package/src/utils/__init__.py +42 -0
  60. package/src/utils/error_recovery.py +313 -0
  61. package/src/utils/parallel_executor.py +402 -0
  62. package/src/utils/polars_helpers.py +248 -0
  63. package/src/utils/schema_extraction.py +132 -0
  64. package/src/utils/semantic_layer.py +392 -0
  65. package/src/utils/token_budget.py +411 -0
  66. package/src/utils/validation.py +377 -0
  67. package/src/workflow_state.py +154 -0
@@ -0,0 +1,448 @@
1
+ """
2
+ Session Memory Manager
3
+ Maintains context across user interactions for intelligent follow-up handling.
4
+
5
+ This module enables the agent to remember previous interactions and resolve
6
+ ambiguous requests like "cross validate it" or "add features to that".
7
+ """
8
+
9
+ import json
10
+ from typing import Dict, Any, Optional, List
11
+ from datetime import datetime
12
+ import uuid
13
+
14
+
15
+ class SessionMemory:
16
+ """
17
+ Manages session-based memory for contextual AI interactions.
18
+
19
+ Features:
20
+ - Stores last dataset, model, target column
21
+ - Tracks workflow history
22
+ - Resolves ambiguous pronouns ("it", "that", "the model")
23
+ - Maintains conversation context
24
+
25
+ Example:
26
+ User: "Train model on earthquake.csv predicting mag"
27
+ Agent stores: last_model="XGBoost", last_dataset="earthquake.csv"
28
+
29
+ User: "Cross validate it"
30
+ Agent resolves: "it" → XGBoost, uses stored context
31
+ """
32
+
33
+ def __init__(self, session_id: Optional[str] = None):
34
+ """
35
+ Initialize session memory.
36
+
37
+ Args:
38
+ session_id: Unique session identifier (auto-generated if None)
39
+ """
40
+ self.session_id = session_id or str(uuid.uuid4())
41
+ self.created_at = datetime.now()
42
+ self.last_active = datetime.now()
43
+
44
+ # Core context - what the agent last worked on
45
+ self.last_dataset: Optional[str] = None
46
+ self.last_target_col: Optional[str] = None
47
+ self.last_model: Optional[str] = None
48
+ self.last_task_type: Optional[str] = None # regression, classification
49
+ self.best_score: Optional[float] = None
50
+
51
+ # Output tracking - where things were saved
52
+ self.last_output_files: Dict[str, str] = {}
53
+
54
+ # Workflow history - what steps were executed
55
+ self.workflow_history: List[Dict[str, Any]] = []
56
+
57
+ # Conversation context - for pronoun resolution
58
+ self.conversation_context: List[Dict[str, str]] = []
59
+
60
+ # Tool results cache - detailed results from last tools
61
+ self.last_tool_results: Dict[str, Any] = {}
62
+
63
+ def update(self, **kwargs):
64
+ """
65
+ Update session context with new information.
66
+
67
+ Args:
68
+ last_dataset: Path to dataset
69
+ last_target_col: Target column name
70
+ last_model: Model name (XGBoost, RandomForest, etc.)
71
+ last_task_type: Task type (regression, classification)
72
+ best_score: Best model score
73
+ last_output_files: Dict of output file paths
74
+
75
+ Example:
76
+ session.update(
77
+ last_dataset="./data/sales.csv",
78
+ last_model="XGBoost",
79
+ best_score=0.92
80
+ )
81
+ """
82
+ self.last_active = datetime.now()
83
+
84
+ for key, value in kwargs.items():
85
+ if hasattr(self, key):
86
+ setattr(self, key, value)
87
+
88
+ def add_workflow_step(self, tool_name: str, result: Dict[str, Any]):
89
+ """
90
+ Add a workflow step to history and extract context.
91
+
92
+ Args:
93
+ tool_name: Name of the tool executed
94
+ result: Tool execution result
95
+ """
96
+ self.workflow_history.append({
97
+ "timestamp": datetime.now().isoformat(),
98
+ "tool": tool_name,
99
+ "result": result
100
+ })
101
+
102
+ # Update context based on tool results
103
+ self._extract_context_from_tool(tool_name, result)
104
+
105
+ def _extract_context_from_tool(self, tool_name: str, result: Dict[str, Any]):
106
+ """
107
+ Extract relevant context from tool execution.
108
+ Automatically updates session state based on what tools did.
109
+
110
+ Args:
111
+ tool_name: Name of the tool
112
+ result: Tool result dictionary
113
+ """
114
+ # Skip if tool failed
115
+ if not result.get("success"):
116
+ return
117
+
118
+ tool_result = result.get("result", {})
119
+
120
+ # Track dataset from profiling
121
+ if tool_name == "profile_dataset":
122
+ # Extract file path from arguments if available
123
+ if "file_path" in result.get("arguments", {}):
124
+ self.last_dataset = result["arguments"]["file_path"]
125
+
126
+ # Track model training results
127
+ if tool_name == "train_baseline_models":
128
+ best_model = tool_result.get("best_model", {})
129
+ if isinstance(best_model, dict):
130
+ self.last_model = best_model.get("name")
131
+ self.best_score = best_model.get("score")
132
+ else:
133
+ self.last_model = best_model
134
+
135
+ self.last_task_type = tool_result.get("task_type")
136
+
137
+ # Extract target column from arguments
138
+ if "target_col" in result.get("arguments", {}):
139
+ self.last_target_col = result["arguments"]["target_col"]
140
+
141
+ # Track hyperparameter tuning results
142
+ if tool_name == "hyperparameter_tuning":
143
+ if "best_score" in tool_result:
144
+ self.best_score = tool_result["best_score"]
145
+ if "model_type" in result.get("arguments", {}):
146
+ self.last_model = result["arguments"]["model_type"]
147
+
148
+ # Track cross-validation results
149
+ if tool_name == "perform_cross_validation":
150
+ if "mean_score" in tool_result:
151
+ # Store CV score separately (could add cv_score attribute)
152
+ pass
153
+
154
+ # Track output files from data processing
155
+ if "output_path" in tool_result:
156
+ tool_category = self._categorize_tool(tool_name)
157
+ self.last_output_files[tool_category] = tool_result["output_path"]
158
+
159
+ # Update last_dataset if this is a data transformation
160
+ if tool_category in ["cleaned", "encoded", "engineered"]:
161
+ self.last_dataset = tool_result["output_path"]
162
+
163
+ # Store tool results for detailed access
164
+ self.last_tool_results[tool_name] = tool_result
165
+
166
+ def _categorize_tool(self, tool_name: str) -> str:
167
+ """
168
+ Categorize tool for output tracking.
169
+
170
+ Args:
171
+ tool_name: Name of the tool
172
+
173
+ Returns:
174
+ Category string (cleaned, encoded, model, etc.)
175
+ """
176
+ if "clean" in tool_name:
177
+ return "cleaned"
178
+ elif "encode" in tool_name:
179
+ return "encoded"
180
+ elif "feature" in tool_name and "engineer" in tool_name:
181
+ return "engineered"
182
+ elif "train" in tool_name or "model" in tool_name:
183
+ return "model"
184
+ elif "plot" in tool_name or "visual" in tool_name:
185
+ return "visualization"
186
+ elif "report" in tool_name:
187
+ return "report"
188
+ else:
189
+ return "other"
190
+
191
+ def add_conversation(self, user_message: str, agent_response: str):
192
+ """
193
+ Add conversation turn to context.
194
+
195
+ Args:
196
+ user_message: User's request
197
+ agent_response: Agent's response/summary
198
+ """
199
+ self.conversation_context.append({
200
+ "timestamp": datetime.now().isoformat(),
201
+ "user": user_message,
202
+ "agent": agent_response
203
+ })
204
+
205
+ # Keep only last 10 turns to avoid memory bloat
206
+ if len(self.conversation_context) > 10:
207
+ self.conversation_context = self.conversation_context[-10:]
208
+
209
+ def resolve_ambiguity(self, task_description: str) -> Dict[str, Any]:
210
+ """
211
+ Resolve ambiguous references in user request.
212
+
213
+ Handles pronouns like "it", "that", "this" by mapping to session context.
214
+
215
+ Args:
216
+ task_description: User's request (may contain "it", "that", etc.)
217
+
218
+ Returns:
219
+ Dict with resolved parameters (file_path, target_col, model_type)
220
+
221
+ Example:
222
+ User: "Cross validate it"
223
+ → Returns: {"file_path": "encoded.csv", "target_col": "mag", "model_type": "xgboost"}
224
+ """
225
+ task_lower = task_description.lower()
226
+ resolved = {}
227
+
228
+ # Pronouns that reference last model/dataset
229
+ ambiguous_refs = ["it", "that", "this", "the model", "the dataset", "the data"]
230
+ has_ambiguous_ref = any(ref in task_lower for ref in ambiguous_refs)
231
+
232
+ # Cross-validation requests
233
+ if "cross validat" in task_lower or "cv" in task_lower or "validate" in task_lower:
234
+ if has_ambiguous_ref or not any(word in task_lower for word in ["file_path=", "target_col=", "model_type="]):
235
+ # Use session context to fill in missing parameters
236
+ if self.last_output_files.get("encoded"):
237
+ resolved["file_path"] = self.last_output_files.get("encoded")
238
+ elif self.last_dataset:
239
+ resolved["file_path"] = self.last_dataset
240
+
241
+ if self.last_target_col:
242
+ resolved["target_col"] = self.last_target_col
243
+
244
+ if self.last_model:
245
+ resolved["model_type"] = self._normalize_model_name(self.last_model)
246
+
247
+ # Hyperparameter tuning requests
248
+ if "tun" in task_lower or "optim" in task_lower or "improve" in task_lower:
249
+ if has_ambiguous_ref or "file_path" not in task_lower:
250
+ if self.last_output_files.get("encoded"):
251
+ resolved["file_path"] = self.last_output_files.get("encoded")
252
+ elif self.last_dataset:
253
+ resolved["file_path"] = self.last_dataset
254
+
255
+ if self.last_target_col:
256
+ resolved["target_col"] = self.last_target_col
257
+
258
+ if self.last_model:
259
+ resolved["model_type"] = self._normalize_model_name(self.last_model)
260
+
261
+ # Visualization requests referencing "the results" or "it"
262
+ if ("plot" in task_lower or "visualiz" in task_lower or "graph" in task_lower) and has_ambiguous_ref:
263
+ if self.last_dataset:
264
+ resolved["file_path"] = self.last_dataset
265
+
266
+ if self.last_target_col:
267
+ resolved["target_col"] = self.last_target_col
268
+
269
+ # "Add feature" or "create feature" requests
270
+ if ("add feature" in task_lower or "create feature" in task_lower or
271
+ "engineer feature" in task_lower or "extract feature" in task_lower):
272
+ if has_ambiguous_ref or "file_path" not in task_lower:
273
+ # Use most recent processed file
274
+ if self.last_output_files.get("encoded"):
275
+ resolved["file_path"] = self.last_output_files.get("encoded")
276
+ elif self.last_output_files.get("cleaned"):
277
+ resolved["file_path"] = self.last_output_files.get("cleaned")
278
+ elif self.last_dataset:
279
+ resolved["file_path"] = self.last_dataset
280
+
281
+ # Generic "use that" or "try it" commands
282
+ if has_ambiguous_ref and not resolved:
283
+ # Fallback: use last dataset and target
284
+ print(f"[DEBUG] Session fallback triggered - has_ambiguous_ref={has_ambiguous_ref}, resolved={resolved}")
285
+ if self.last_dataset:
286
+ resolved["file_path"] = self.last_dataset
287
+ print(f"[DEBUG] Resolved file_path from session: {self.last_dataset}")
288
+ if self.last_target_col:
289
+ resolved["target_col"] = self.last_target_col
290
+ print(f"[DEBUG] Resolved target_col from session: {self.last_target_col}")
291
+
292
+ # 🔥 ULTIMATE FALLBACK: If no file_path resolved and we have session data, use it
293
+ # This handles cases where user doesn't use ambiguous refs but still wants to use session context
294
+ if not resolved.get("file_path") and self.last_dataset:
295
+ resolved["file_path"] = self.last_dataset
296
+ print(f"[DEBUG] Ultimate fallback: Using last_dataset from session: {self.last_dataset}")
297
+
298
+ if not resolved.get("target_col") and self.last_target_col:
299
+ resolved["target_col"] = self.last_target_col
300
+ print(f"[DEBUG] Ultimate fallback: Using last_target_col from session: {self.last_target_col}")
301
+
302
+ print(f"[DEBUG] resolve_ambiguity returning: {resolved}")
303
+ return resolved
304
+
305
+ def _normalize_model_name(self, model_name: Optional[str]) -> Optional[str]:
306
+ """
307
+ Normalize model name for tool compatibility.
308
+
309
+ Different tools may use different naming conventions.
310
+ This maps common variations to standard names.
311
+
312
+ Args:
313
+ model_name: Model name from session (e.g., "XGBoost Classifier")
314
+
315
+ Returns:
316
+ Normalized name (e.g., "xgboost")
317
+ """
318
+ if not model_name:
319
+ return None
320
+
321
+ name_lower = model_name.lower()
322
+
323
+ if "xgb" in name_lower:
324
+ return "xgboost"
325
+ elif "random" in name_lower or "forest" in name_lower:
326
+ return "random_forest"
327
+ elif "ridge" in name_lower:
328
+ return "ridge"
329
+ elif "lasso" in name_lower:
330
+ return "ridge" # Use ridge for lasso (same tool)
331
+ elif "logistic" in name_lower:
332
+ return "logistic"
333
+ elif "gradient boost" in name_lower and "xgb" not in name_lower:
334
+ return "gradient_boosting"
335
+ elif "svm" in name_lower or "support vector" in name_lower:
336
+ return "svm"
337
+ else:
338
+ # Return as-is if unknown
339
+ return model_name.lower().replace(" ", "_")
340
+
341
+ def get_context_summary(self) -> str:
342
+ """
343
+ Generate human-readable context summary.
344
+
345
+ Returns:
346
+ Formatted string describing current session state
347
+
348
+ Example:
349
+ **Session Context:**
350
+ - Dataset: ./data/earthquake.csv
351
+ - Target Column: mag
352
+ - Last Model: XGBoost
353
+ - Best Score: 0.9234
354
+ - Task Type: regression
355
+ """
356
+ if not self.last_dataset and not self.last_model:
357
+ return "No previous context available."
358
+
359
+ summary = "**Session Context:**\n"
360
+
361
+ if self.last_dataset:
362
+ summary += f"- Dataset: {self.last_dataset}\n"
363
+
364
+ if self.last_target_col:
365
+ summary += f"- Target Column: {self.last_target_col}\n"
366
+
367
+ if self.last_model:
368
+ summary += f"- Last Model: {self.last_model}\n"
369
+
370
+ if self.best_score is not None:
371
+ summary += f"- Best Score: {self.best_score:.4f}\n"
372
+
373
+ if self.last_task_type:
374
+ summary += f"- Task Type: {self.last_task_type}\n"
375
+
376
+ if self.last_output_files:
377
+ summary += "- Output Files:\n"
378
+ for category, path in self.last_output_files.items():
379
+ summary += f" - {category}: {path}\n"
380
+
381
+ return summary
382
+
383
+ def to_dict(self) -> Dict[str, Any]:
384
+ """
385
+ Serialize session to dictionary for storage.
386
+
387
+ Returns:
388
+ Dictionary with all session data
389
+ """
390
+ return {
391
+ "session_id": self.session_id,
392
+ "created_at": self.created_at.isoformat(),
393
+ "last_active": self.last_active.isoformat(),
394
+ "last_dataset": self.last_dataset,
395
+ "last_target_col": self.last_target_col,
396
+ "last_model": self.last_model,
397
+ "last_task_type": self.last_task_type,
398
+ "best_score": self.best_score,
399
+ "last_output_files": self.last_output_files,
400
+ "workflow_history": self.workflow_history,
401
+ "conversation_context": self.conversation_context,
402
+ "last_tool_results": self.last_tool_results
403
+ }
404
+
405
+ @classmethod
406
+ def from_dict(cls, data: Dict[str, Any]) -> 'SessionMemory':
407
+ """
408
+ Deserialize session from dictionary.
409
+
410
+ Args:
411
+ data: Dictionary with session data (from to_dict())
412
+
413
+ Returns:
414
+ SessionMemory instance
415
+ """
416
+ session = cls(session_id=data.get("session_id"))
417
+
418
+ # Restore timestamps
419
+ if data.get("created_at"):
420
+ session.created_at = datetime.fromisoformat(data.get("created_at"))
421
+ if data.get("last_active"):
422
+ session.last_active = datetime.fromisoformat(data.get("last_active"))
423
+
424
+ # Restore context
425
+ session.last_dataset = data.get("last_dataset")
426
+ session.last_target_col = data.get("last_target_col")
427
+ session.last_model = data.get("last_model")
428
+ session.last_task_type = data.get("last_task_type")
429
+ session.best_score = data.get("best_score")
430
+ session.last_output_files = data.get("last_output_files", {})
431
+ session.workflow_history = data.get("workflow_history", [])
432
+ session.conversation_context = data.get("conversation_context", [])
433
+ session.last_tool_results = data.get("last_tool_results", {})
434
+
435
+ return session
436
+
437
+ def clear(self):
438
+ """Clear all session context (start fresh)."""
439
+ self.last_dataset = None
440
+ self.last_target_col = None
441
+ self.last_model = None
442
+ self.last_task_type = None
443
+ self.best_score = None
444
+ self.last_output_files = {}
445
+ self.workflow_history = []
446
+ self.conversation_context = []
447
+ self.last_tool_results = {}
448
+ self.last_active = datetime.now()