-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsci_data_copilot.py
More file actions
712 lines (610 loc) · 28 KB
/
sci_data_copilot.py
File metadata and controls
712 lines (610 loc) · 28 KB
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
# -*- coding: utf-8 -*-
"""
SciDataCopilot: multi-agents Architecture for Scientific Data Processing
Four-agent architecture: Intent Parsing → Data Access → Data Processing → Data Integration
Enhanced with:
- Knowledge Base: Data Lake (D), Tool Lake (T), Case Lake (C)
- Structured Requirements: R = {Obj, Var, Con, Task}
- Integration Constraints: γ_k = (R_k, S_k)
- State Machine Workflow: 5-phase processing
- Unified Workflow Router: Auto-detect data type from user_prompt
"""
import os
import sys
import yaml
import logging
from pathlib import Path
from datetime import datetime
from typing import Dict, Any, List, TypedDict, Optional
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, END
# Add parent directory to path for imports
sys.path.insert(0, str(Path(__file__).parent.parent))
from agents.base_agent import BaseAgent, AgentRole, AgentContext
from health.health_scorer import HealthScorer
# Knowledge Base imports
from knowledge_base import KnowledgeBase
from tools.tool_lake import ToolLake, get_tool_lake, initialize_tool_lake
# Workflow Router for unified data type handling
from tools.workflow_router import WorkflowRouter, WorkflowDecision
class SciDataCopilotState(TypedDict):
"""State for multi-agents workflow"""
# User inputs
user_prompt: str
header_path: str
data_path: str
data_type: str # Auto-detected: "tabular", "signal", "document", "api"
# Workflow routing (auto-detected)
workflow_decision: Dict[str, Any] # WorkflowDecision from router
# Intent Parsing Agent outputs (enhanced)
parsed_intent: Dict[str, Any]
processing_plan: Dict[str, Any]
processing_plan_text: str
structured_requirement: Dict[str, Any] # R = {Obj, Var, Con, Task}
retrieved_case: Dict[str, Any] # Retrieved similar case
case_adaptation: Dict[str, Any] # Case adaptation result
plan_review: Dict[str, Any] # Plan review result
# Data Access Agent outputs (with Data Perception)
data_profile: Dict[str, Any]
data_profiles: List[Dict[str, Any]] # For multi-source integration
header_profile: Dict[str, Any]
quality_baseline: Dict[str, float]
perception_report: str
data_access_success: bool
user_followup_message: str
scan_result: Dict[str, Any] # Enhanced exploration
exploration_plan: Dict[str, Any] # Enhanced exploration
# Data Processing Agent outputs (enhanced)
code: str
execution_log: str
iteration: int
error: str
processing_success: bool
analysis_report: Dict[str, Any] # From Analyzer
workflow_phases: Dict[str, Any] # State machine phases
# Data Integration Agent outputs (enhanced)
output_files: List[str]
quality_current: Dict[str, float]
quality_improvement: float
analysis: str
recommendations: List[str]
strategy_analysis: Dict[str, Any] # Integration strategy
integration_pipeline: Dict[str, Any] # Integration pipeline
integration_constraints: List[Dict[str, Any]] # γ_k = (R_k, S_k)
# Global state
success: bool
current_exp_dir: str
# Feature flags
use_enhanced_exploration: bool
use_state_machine: bool
use_enhanced_integration: bool
class SciDataCopilot:
"""
SciDataCopilot with multi-agents Architecture
Architecture:
1. Intent Parsing Agent - Parse user requirements, extract R={Obj,Var,Con,Task}
2. Data Access Agent - Access data + perception, FolderWalker exploration
3. Data Processing Agent - Generate and execute code, 5-phase state machine
4. Data Integration Agent - Integrate results + constraint analysis
Knowledge Base:
- Data Lake (D): Dataset entities and data units
- Tool Lake (T): Available tools and capabilities
- Case Lake (C): Historical cases for retrieval
"""
def __init__(
self,
data_type: str = None, # Optional: auto-detected if not provided
config_path: str = None,
header_path: str = None,
data_path: str = None,
user_prompt: str = None,
use_enhanced_features: bool = False
):
"""
Initialize SciDataCopilot
Args:
data_type: Optional data type override (auto-detected from user_prompt if None)
config_path: Path to configuration file
header_path: Path to header file (optional)
data_path: Path to data file or directory
user_prompt: User's processing request
use_enhanced_features: Enable enhanced features (state machine, exploration, etc.)
"""
self.use_enhanced_features = use_enhanced_features
if data_type == "general":
data_type = "generic"
self._explicit_data_type = data_type # Store explicit override
# Load configuration
self.config = self._load_config(config_path)
# Set up paths from config or arguments
self.header_path = header_path or self.config.get("header_path")
self.data_path = data_path or self.config.get("data_path")
self.user_prompt = user_prompt or self.config.get("user_prompt", "Process data")
# Initialize LLM
self.llm = self._init_llm()
# Set up logging
self._setup_logging()
# Initialize Knowledge Base (D, T, C)
self.knowledge_base = self._init_knowledge_base()
# Try to load paths from Data Lake if not provided
if not self.data_path or not self.header_path:
self._load_paths_from_data_lake()
# Initialize Workflow Router for auto data type detection
self.workflow_router = WorkflowRouter(
knowledge_base=self.knowledge_base,
llm=self.llm
)
# Route workflow: auto-detect data type or use explicit override
if self._explicit_data_type:
# Use explicit data type - prompts should match the explicit type, not detected type
self.data_type = self._explicit_data_type
self.workflow_decision = self.workflow_router.route(
user_prompt=self.user_prompt,
data_path=self.data_path,
header_path=self.header_path
)
# Always use prompts for the explicit data type (not the detected type)
self.prompts = self._load_prompts_for_type(self._explicit_data_type)
self.logger.info(f"Using prompts for explicit data_type: {self._explicit_data_type}")
else:
# Auto-detect data type from user_prompt
self.workflow_decision = self.workflow_router.route(
user_prompt=self.user_prompt,
data_path=self.data_path,
header_path=self.header_path
)
# Map to legacy data_type for backward compatibility
self.data_type = self.workflow_router.get_legacy_data_type(self.workflow_decision)
self.prompts = self.workflow_decision.prompts
self.logger.info(f"Auto-detected data_type: {self.workflow_decision.data_type} "
f"-> legacy: {self.data_type}")
self.logger.info(f"Workflow: {self.workflow_decision.workflow_type}, "
f"confidence: {self.workflow_decision.confidence:.2f}")
# Create experiment directory
self.exp_dir = self._create_exp_dir()
# Initialize agents with Knowledge Base
from agents.intent_parsing_agent import IntentParsingAgent
from agents.data_access_agent import DataAccessAgent
from agents.data_processing_agent import DataProcessingAgent
from agents.data_integration_agent import DataIntegrationAgent
self.intent_parsing_agent = IntentParsingAgent(
llm=self.llm,
data_type=self.data_type,
prompts=self.prompts,
knowledge_base=self.knowledge_base
)
self.data_access_agent = DataAccessAgent(
llm=self.llm,
data_type=self.data_type,
prompts=self.prompts,
tool_lake=self.knowledge_base.tool_lake,
knowledge_base=self.knowledge_base
)
self.data_processing_agent = DataProcessingAgent(
llm=self.llm,
data_type=self.data_type,
prompts=self.prompts,
max_iterations=self.config.get("max_iterations", 5),
tool_lake=self.knowledge_base.tool_lake,
knowledge_base=self.knowledge_base
)
self.data_integration_agent = DataIntegrationAgent(
llm=self.llm,
data_type=self.data_type,
prompts=self.prompts,
tool_lake=self.knowledge_base.tool_lake,
knowledge_base=self.knowledge_base
)
# Build workflow
self.workflow = self._build_workflow()
self.logger.info(f"SciDataCopilot initialized with multi-agents architecture (data_type={self.data_type})")
self.logger.info(f"Knowledge Base: Data Lake={self.knowledge_base.data_lake is not None}, "
f"Tool Lake={self.knowledge_base.tool_lake is not None}, "
f"Case Lake={self.knowledge_base.case_lake is not None}")
def _init_knowledge_base(self) -> KnowledgeBase:
"""Initialize Knowledge Base with Data Lake, Tool Lake, and Case Lake"""
from knowledge_base.knowledge_base import KnowledgeBaseConfig
# Initialize Tool Lake
tool_lake = get_tool_lake()
if tool_lake is None:
tool_lake = initialize_tool_lake()
# Register default tools
try:
from tools.tool_registry import register_default_tools
register_default_tools(tool_lake)
except ImportError:
self.logger.warning("Could not register default tools")
# Configure Knowledge Base paths
kb_data_path = Path(__file__).parent / "knowledge_base" / "data"
kb_data_path.mkdir(parents=True, exist_ok=True)
config = KnowledgeBaseConfig(
data_lake_path=str(kb_data_path / "data_lake.json"),
case_lake_path=str(kb_data_path / "case_lake.json"),
auto_save=True
)
# Create Knowledge Base (DataLake and CaseLake are created internally)
knowledge_base = KnowledgeBase(
config=config,
tool_lake=tool_lake
)
# Load existing data from persistence (if available)
try:
knowledge_base.load_all()
self.logger.info(f"Loaded Knowledge Base from {kb_data_path}")
except Exception as e:
self.logger.warning(f"Could not load Knowledge Base (may be new): {e}")
return knowledge_base
def _load_paths_from_data_lake(self):
"""Load data paths from Data Lake if not provided via arguments/config.
This allows the system to use pre-registered datasets from the Knowledge Base.
"""
if not self.knowledge_base or not self.knowledge_base.data_lake:
return
data_lake = self.knowledge_base.data_lake
prompt_lower = self.user_prompt.lower() if self.user_prompt else ""
# Skip loading paths for acquire/api type requests (they don't need pre-registered data)
acquire_keywords = ["uniprot", "ncbi", "pubmed", "search", "download",
"query protein", "query gene", "paper", "api"]
if any(kw in prompt_lower for kw in acquire_keywords):
self.logger.info("Skipping Data Lake path loading for acquire/api request")
return
# Try to find a dataset based on user_prompt keywords or data_type
target_domain = None
# Detect domain from user prompt
if any(kw in prompt_lower for kw in ["polar", "polar", "meteorological"]):
target_domain = "polar_science"
elif any(kw in prompt_lower for kw in ["eeg", "neuroscience", "brain"]):
target_domain = "neuroscience"
# Search for matching dataset
for dataset_id, dataset in data_lake.datasets.items():
# Match by domain
if target_domain and dataset.domain == target_domain:
self._extract_paths_from_dataset(dataset)
return
# Match by tags
if self._explicit_data_type:
if self._explicit_data_type in dataset.tags:
self._extract_paths_from_dataset(dataset)
return
# If no match found and explicit data_type is polar, use first available dataset
# Note: EEG typically uses MNE built-in datasets, so don't fallback for eeg
if self._explicit_data_type == "polar" and data_lake.datasets:
first_dataset = list(data_lake.datasets.values())[0]
self._extract_paths_from_dataset(first_dataset)
def _extract_paths_from_dataset(self, dataset):
"""Extract header_path and data_path from a dataset's data units."""
for unit_id, unit in dataset.data_units.items():
file_path = unit.file_path
if not file_path:
continue
# Check if it's a header file
if "header" in unit_id.lower() or "header" in unit.name.lower():
if not self.header_path:
self.header_path = file_path
self.logger.info(f"Loaded header_path from Data Lake: {file_path}")
else:
# It's a data file
if not self.data_path:
self.data_path = file_path
self.logger.info(f"Loaded data_path from Data Lake: {file_path}")
def _load_config(self, config_path: str = None) -> Dict[str, Any]:
"""Load configuration from YAML file"""
if config_path is None:
config_path = Path(__file__).parent / "config" / "config.yaml"
if Path(config_path).exists():
with open(config_path, 'r', encoding='utf-8') as f:
config = yaml.safe_load(f)
return config
else:
# Default configuration
return {
"model_name": "gpt-4o",
"temperature": 0.0,
"max_iterations": 5,
"quality_threshold": 0.6
}
def _init_llm(self) -> ChatOpenAI:
"""Initialize LLM"""
import os
# Get API key from config or environment
api_key = self.config.get("openai_api_key")
if api_key:
os.environ["OPENAI_API_KEY"] = api_key
# Get base URL - try both config keys for compatibility
base_url = self.config.get("openai_base_url") or self.config.get("openai_api_base")
if not base_url:
base_url = "https://api.boyuerichdata.opensphereai.com/v1"
llm_kwargs = {
"model": self.config.get("model_name", "gpt-4o"),
"temperature": self.config.get("temperature", 0.0),
"base_url": base_url
}
return ChatOpenAI(**llm_kwargs)
def _load_prompts_for_type(self, data_type: str) -> Dict[str, str]:
"""Load prompts based on data type"""
if data_type == "general":
data_type = "generic"
if data_type == "polar":
from prompts.polar_prompts import (
POLAR_INTENT_PARSING_PROMPT,
POLAR_DATA_PROCESSING_PROMPT,
POLAR_INTEGRATION_PROMPT
)
return {
"intent_parsing": POLAR_INTENT_PARSING_PROMPT,
"data_processing": POLAR_DATA_PROCESSING_PROMPT,
"integration": POLAR_INTEGRATION_PROMPT
}
elif data_type == "eeg":
from prompts.eeg_prompts import (
EEG_INTENT_PARSING_PROMPT,
EEG_DATA_ACCESS_PROMPT,
EEG_DATA_PROCESSING_PROMPT,
EEG_INTEGRATION_PROMPT
)
return {
"intent_parsing": EEG_INTENT_PARSING_PROMPT,
"data_access": EEG_DATA_ACCESS_PROMPT,
"data_processing": EEG_DATA_PROCESSING_PROMPT,
"integration": EEG_INTEGRATION_PROMPT
}
elif data_type == "acquire":
from prompts.acquire_prompts import (
ACQUIRE_INTENT_PARSING_PROMPT,
ACQUIRE_DATA_ACCESS_PROMPT,
ACQUIRE_DATA_PROCESSING_PROMPT,
ACQUIRE_INTEGRATION_PROMPT
)
return {
"intent_parsing": ACQUIRE_INTENT_PARSING_PROMPT,
"data_access": ACQUIRE_DATA_ACCESS_PROMPT,
"data_processing": ACQUIRE_DATA_PROCESSING_PROMPT,
"integration": ACQUIRE_INTEGRATION_PROMPT
}
elif data_type == "generic":
if hasattr(self, "workflow_router") and self.workflow_router:
try:
return self.workflow_router.prompt_templates.get("generic", {}) or {}
except Exception:
pass
from prompts.intent_prompts import GENERAL_INTENT_PARSING_PROMPT
return {
"intent_parsing": GENERAL_INTENT_PARSING_PROMPT,
"data_processing": "Generate code for generic data processing",
"integration": "Integrate results for generic data"
}
else:
# Generic prompts for other data types
return {
"intent_parsing": "Parse user intent for {data_type} data",
"data_processing": "Generate code for {data_type} data processing",
"integration": "Integrate results for {data_type} data"
}
def _setup_logging(self):
"""Set up logging"""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
self.logger = logging.getLogger(__name__)
def _create_exp_dir(self) -> str:
"""Create experiment directory"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
# Keep experiment outputs under the current project directory by default.
# If save_dir is relative (e.g. "./exp"), resolve it from repository root.
project_root = Path(__file__).resolve().parent
save_dir = self.config.get("save_dir", "exp")
save_dir_path = Path(save_dir)
if not save_dir_path.is_absolute():
save_dir_path = (project_root / save_dir_path).resolve()
exp_dir = save_dir_path / f"{self.data_type}_exp_{timestamp}"
exp_dir.mkdir(parents=True, exist_ok=True)
self.logger.info(f"Created experiment directory: {exp_dir}")
return str(exp_dir)
def _build_workflow(self):
"""Build LangGraph workflow with 4 agents"""
graph = StateGraph(SciDataCopilotState)
# Add 4 agent nodes
graph.add_node("intent_parsing", self.intent_parsing_node)
graph.add_node("data_access", self.data_access_node)
graph.add_node("data_processing", self.data_processing_node)
graph.add_node("data_integration", self.data_integration_node)
# Set entry point
graph.set_entry_point("intent_parsing")
# Add edges
graph.add_edge("intent_parsing", "data_access")
graph.add_edge("data_access", "data_processing")
graph.add_conditional_edges("data_processing", self.after_processing_route)
graph.add_edge("data_integration", END)
return graph.compile()
def intent_parsing_node(self, state: SciDataCopilotState) -> Dict[str, Any]:
"""Intent Parsing Agent node"""
result = self.intent_parsing_agent.process_state(state)
return result
def data_access_node(self, state: SciDataCopilotState) -> Dict[str, Any]:
"""Data Access Agent node"""
result = self.data_access_agent.process_state(state)
return result
def data_processing_node(self, state: SciDataCopilotState) -> Dict[str, Any]:
"""Data Processing Agent node"""
result = self.data_processing_agent.process_state(state)
return result
def data_integration_node(self, state: SciDataCopilotState) -> Dict[str, Any]:
"""Data Integration Agent node"""
result = self.data_integration_agent.process_state(state)
return result
def after_processing_route(self, state: SciDataCopilotState) -> str:
"""Route after data processing"""
# If processing succeeded, go to integration
if state.get("processing_success"):
return "data_integration"
# If failed but can retry, loop back to processing
elif state.get("iteration", 0) < self.config.get("max_iterations", 5):
return "data_processing"
# Max iterations reached, go to integration anyway
else:
return "data_integration"
def run(self) -> Dict[str, Any]:
"""
Run the multi-agents workflow
Returns:
Dict with results including success status, quality scores, etc.
"""
self.logger.info("=" * 60)
self.logger.info("Starting SciDataCopilot multi-agents Workflow")
self.logger.info(f"Enhanced features: {self.use_enhanced_features}")
self.logger.info("=" * 60)
# Initialize state with enhanced fields
initial_state = {
# User inputs
"user_prompt": self.user_prompt,
"header_path": self.header_path,
"data_path": self.data_path,
"data_type": self.data_type,
"current_exp_dir": self.exp_dir,
# Workflow routing (auto-detected)
"workflow_decision": self.workflow_decision.to_dict() if self.workflow_decision else {},
# Intent Parsing Agent outputs
"parsed_intent": {},
"processing_plan": {},
"processing_plan_text": "",
"structured_requirement": {},
"retrieved_case": None,
"case_adaptation": None,
"plan_review": None,
# Data Access Agent outputs
"data_profile": {},
"data_profiles": [],
"header_profile": {},
"quality_baseline": {},
"perception_report": "",
"data_access_success": False,
"user_followup_message": "",
"scan_result": {},
"exploration_plan": {},
# Data Processing Agent outputs
"code": "",
"execution_log": "",
"iteration": 0,
"error": "",
"processing_success": False,
"analysis_report": {},
"workflow_phases": {},
# Data Integration Agent outputs
"output_files": [],
"quality_current": {},
"quality_improvement": 0.0,
"analysis": "",
"recommendations": [],
"strategy_analysis": {},
"integration_pipeline": {},
"integration_constraints": [],
# Global state
"success": False,
# Feature flags
"use_enhanced_exploration": self.use_enhanced_features,
"use_state_machine": self.use_enhanced_features,
"use_enhanced_integration": self.use_enhanced_features
}
# Run workflow
try:
final_state = self.workflow.invoke(initial_state)
self.logger.info("=" * 60)
self.logger.info("SciDataCopilot multi-agents Workflow Completed")
self.logger.info("=" * 60)
# Save Knowledge Base after successful run
if final_state.get("success", False):
self._save_case_to_lake(final_state)
self._save_knowledge_base()
return {
"success": final_state.get("success", False),
"exp_dir": self.exp_dir,
"output_files": final_state.get("output_files", []),
"quality_baseline": final_state.get("quality_baseline", {}),
"quality_current": final_state.get("quality_current", {}),
"quality_improvement": final_state.get("quality_improvement", 0.0),
"iteration": final_state.get("iteration", 0),
"analysis": final_state.get("analysis", ""),
"recommendations": final_state.get("recommendations", []),
"user_followup_message": final_state.get("user_followup_message", ""),
# Enhanced outputs
"structured_requirement": final_state.get("structured_requirement", {}),
"retrieved_case": final_state.get("retrieved_case"),
"strategy_analysis": final_state.get("strategy_analysis", {}),
"integration_pipeline": final_state.get("integration_pipeline", {}),
"workflow_phases": final_state.get("workflow_phases", {})
}
except Exception as e:
self.logger.error(f"Workflow execution failed: {e}")
import traceback
traceback.print_exc()
return {
"success": False,
"error": str(e),
"exp_dir": self.exp_dir
}
def _save_knowledge_base(self):
"""Save Knowledge Base to persistence"""
try:
self.knowledge_base.save_all()
self.logger.info("Saved Knowledge Base")
except Exception as e:
self.logger.warning(f"Could not save Knowledge Base: {e}")
def _save_case_to_lake(self, final_state: Dict[str, Any]):
"""Save successful workflow as a case to Case Lake for future retrieval."""
try:
from knowledge_base.case_lake import Case, DataUnitPipeline
# Create case from workflow
case = Case(
case_id=f"case_{datetime.now().strftime('%Y%m%d_%H%M%S')}",
name=f"Workflow: {self.user_prompt[:50]}",
description=self.user_prompt,
objective=final_state.get("structured_requirement", {}).get("objective", ""),
variables=final_state.get("structured_requirement", {}).get("variables", []),
task_type=self.data_type,
domain=self.workflow_decision.sub_type if self.workflow_decision else "",
data_types=[self.data_type],
success=True,
quality_score=final_state.get("quality_improvement", 0.0)
)
# Add to case lake
self.knowledge_base.case_lake.add_case(case)
self.logger.info(f"Saved case to Case Lake: {case.case_id}")
except Exception as e:
self.logger.warning(f"Could not save case to Case Lake: {e}")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="SciDataCopilot - Scientific Data Processing")
parser.add_argument("--data-type", "-t", default=None,
choices=["polar", "eeg", "acquire", "generic", "general", None],
help="Type of data to process (auto-detected if not specified)")
parser.add_argument("--data-path", "-d", help="Path to data file or directory")
parser.add_argument("--header-path", "-H", help="Path to header file")
parser.add_argument("--prompt", "-p", help="Processing prompt (required for auto-detection)")
parser.add_argument("--enhanced", "-e", action="store_true",
help="Enable enhanced features (state machine, exploration, etc.)")
parser.add_argument("--config", "-c", help="Path to config file")
args = parser.parse_args()
# Initialize and run
copilot = SciDataCopilot(
data_type=args.data_type,
data_path=args.data_path,
header_path=args.header_path,
user_prompt=args.prompt,
config_path=args.config,
use_enhanced_features=args.enhanced
)
result = copilot.run()
print("\n" + "=" * 60)
print("SciDataCopilot Result Summary")
print("=" * 60)
print(f"Data Type: {copilot.data_type} (auto-detected: {copilot.workflow_decision is not None})")
print(f"Success: {result.get('success', False)}")
print(f"Experiment Directory: {result.get('exp_dir', 'N/A')}")
print(f"Output Files: {len(result.get('output_files', []))}")
print(f"Quality Improvement: {result.get('quality_improvement', 0):.3f}")
print(f"Iterations: {result.get('iteration', 0)}")
if result.get("recommendations"):
print("\nRecommendations:")
for rec in result["recommendations"]:
print(f" - {rec}")