This document provides comprehensive API documentation for SandGraphX.
- Core Workflow
- LLM Interface
- RL Framework
- SandBox
- Monitoring
- LLM Frozen & Adaptive
- AReaL KV Cache
- Enhanced RL Algorithms
Main workflow class for managing DAG-based execution.
from sandgraph.core.sg_workflow import SG_Workflow, WorkflowMode, NodeType
class SG_Workflow:
def __init__(self, name: str, mode: WorkflowMode, llm_manager)
def add_node(self, node_type: NodeType, name: str, config: Dict[str, Any])
def add_edge(self, from_node: str, to_node: str)
def execute_full_workflow(self) -> Dict[str, Any]
def execute_step(self) -> Dict[str, Any]
def get_node(self, name: str) -> EnhancedWorkflowNode
def get_all_nodes(self) -> Dict[str, EnhancedWorkflowNode]
def validate_workflow(self) -> boolParameters:
name: Workflow namemode: Workflow mode (TRADITIONAL, ADVANCED)llm_manager: LLM manager instance
Methods:
add_node(): Add a node to the workflowadd_edge(): Connect two nodesexecute_full_workflow(): Execute the entire workflowexecute_step(): Execute one step of the workflowget_node(): Get a specific nodeget_all_nodes(): Get all nodesvalidate_workflow(): Validate workflow structure
Enumeration of workflow modes.
class WorkflowMode(Enum):
TRADITIONAL = "traditional"
ADVANCED = "advanced"Enumeration of node types.
class NodeType(Enum):
SANDBOX = "sandbox"
LLM = "llm"
RL = "rl"
CONDITIONAL = "conditional"
AGGREGATOR = "aggregator"Enhanced workflow node with advanced features.
class EnhancedWorkflowNode:
def __init__(self, name: str, node_type: NodeType,
condition: NodeCondition = None,
limits: NodeLimits = None,
**kwargs)
def execute(self, input_data: Any) -> Any
def get_state(self) -> Dict[str, Any]
def set_state(self, state: Dict[str, Any])
def validate_input(self, input_data: Any) -> bool
def get_metadata(self) -> Dict[str, Any]Parameters:
name: Node namenode_type: Type of nodecondition: Execution conditionslimits: Resource limits**kwargs: Additional configuration
Conditions for node execution.
class NodeCondition:
def __init__(self, max_executions: int = None,
time_limit: float = None,
success_rate_threshold: float = None)
def check(self, node_state: Dict[str, Any]) -> bool
def update(self, execution_result: Dict[str, Any])Resource limits for nodes.
class NodeLimits:
def __init__(self, max_memory_mb: int = None,
max_cpu_percent: float = None,
max_execution_time: float = None)
def check_limits(self, current_usage: Dict[str, Any]) -> boolFactory function to create LLM manager.
from sandgraph.core.llm_interface import create_shared_llm_manager
def create_shared_llm_manager(
model_name: str = "mistralai/Mistral-7B-Instruct-v0.2",
backend: str = "huggingface",
temperature: float = 0.7,
max_tokens: int = 512,
**kwargs
) -> SharedLLMManagerParameters:
model_name: Name of the LLM modelbackend: Backend to use (huggingface, openai, etc.)temperature: Sampling temperaturemax_tokens: Maximum tokens to generate**kwargs: Additional model parameters
Shared LLM manager for multi-node workflows.
class SharedLLMManager:
def __init__(self, model_name: str, backend: str, **kwargs)
def register_node(self, node_name: str, config: Dict[str, Any])
def generate_for_node(self, node_name: str, prompt: str) -> LLMResponse
def get_model_info(self) -> Dict[str, Any]
def update_config(self, node_name: str, config: Dict[str, Any])
def list_registered_nodes(self) -> List[str]Methods:
register_node(): Register a node for LLM generationgenerate_for_node(): Generate response for specific nodeget_model_info(): Get model informationupdate_config(): Update node configurationlist_registered_nodes(): List all registered nodes
Response from LLM generation.
class LLMResponse:
def __init__(self, text: str, metadata: Dict[str, Any] = None)
@property
def text(self) -> str
@property
def metadata(self) -> Dict[str, Any]
def to_dict(self) -> Dict[str, Any]Reinforcement learning trainer.
from sandgraph.core.rl_algorithms import RLTrainer, RLConfig
class RLTrainer:
def __init__(self, config: RLConfig, llm_manager: SharedLLMManager = None)
def add_experience(self, state: Dict[str, Any], action: str,
reward: float, done: bool, next_state: Dict[str, Any] = None)
def update_policy(self) -> Dict[str, Any]
def get_policy(self) -> Dict[str, Any]
def save_checkpoint(self, path: str)
def load_checkpoint(self, path: str)
def reset(self)Methods:
add_experience(): Add experience to replay bufferupdate_policy(): Update policy using collected experiencesget_policy(): Get current policysave_checkpoint(): Save training checkpointload_checkpoint(): Load training checkpointreset(): Reset trainer state
Configuration for RL trainer.
class RLConfig:
def __init__(self, algorithm: str = "PPO",
learning_rate: float = 0.001,
batch_size: int = 32,
buffer_size: int = 10000,
**kwargs)Parameters:
algorithm: RL algorithm (PPO, DQN, A2C, etc.)learning_rate: Learning ratebatch_size: Training batch sizebuffer_size: Replay buffer size
Base class for environment subsets.
from sandgraph.core.sandbox import SandBox
class SandBox:
def __init__(self)
def execute(self, action: Any) -> Tuple[Any, float, bool]
def get_state(self) -> Any
def reset(self) -> Any
def is_done(self) -> bool
def get_action_space(self) -> Any
def get_state_space(self) -> AnyMethods:
execute(): Execute an action and return (next_state, reward, done)get_state(): Get current statereset(): Reset environmentis_done(): Check if episode is doneget_action_space(): Get action spaceget_state_space(): Get state space
Monitor for social network metrics.
from sandgraph.core.monitoring import SocialNetworkMonitor, MonitoringConfig
class SocialNetworkMonitor:
def __init__(self, config: MonitoringConfig)
def start_monitoring(self)
def stop_monitoring(self)
def update_metrics(self, metrics: SocialNetworkMetrics)
def log_metrics(self, metrics: Dict[str, Any])
def get_current_metrics(self) -> Dict[str, Any]
def export_metrics(self, format: str = "json") -> strMethods:
start_monitoring(): Start monitoringstop_monitoring(): Stop monitoringupdate_metrics(): Update metricslog_metrics(): Log metrics to backendsget_current_metrics(): Get current metricsexport_metrics(): Export metrics in specified format
Configuration for monitoring.
class MonitoringConfig:
def __init__(self, enable_wandb: bool = False,
enable_tensorboard: bool = False,
wandb_project_name: str = "sandgraph",
log_interval: float = 1.0,
alert_thresholds: Dict[str, float] = None)Metrics for social network monitoring.
class SocialNetworkMetrics:
def __init__(self, total_users: int, active_users: int,
engagement_rate: float, content_quality_score: float,
network_density: float, viral_spread_rate: float,
response_time_avg: float, error_rate: float)
def to_dict(self) -> Dict[str, Any]
def validate(self) -> boolManager for LLM parameter freezing and adaptive updates.
from sandgraph.core.llm_frozen_adaptive import FrozenAdaptiveManager, UpdateStrategy
class FrozenAdaptiveManager:
def __init__(self)
def register_model(self, model_name: str, model_config: Dict[str, Any])
def set_update_strategy(self, model_name: str, strategy: UpdateStrategy)
def freeze_parameters(self, model_name: str, layer_names: List[str])
def unfreeze_parameters(self, model_name: str, layer_names: List[str])
def update_parameters(self, model_name: str, updates: Dict[str, Any])
def get_model_stats(self, model_name: str) -> Dict[str, Any]
def list_models(self) -> List[str]
def save_checkpoint(self, model_name: str, path: str)
def load_checkpoint(self, model_name: str, path: str)Methods:
register_model(): Register a model for managementset_update_strategy(): Set update strategy for modelfreeze_parameters(): Freeze specific parametersunfreeze_parameters(): Unfreeze specific parametersupdate_parameters(): Update model parametersget_model_stats(): Get model statisticslist_models(): List all managed modelssave_checkpoint(): Save model checkpointload_checkpoint(): Load model checkpoint
Enumeration of update strategies.
class UpdateStrategy(Enum):
FROZEN = "frozen"
ADAPTIVE = "adaptive"
SELECTIVE = "selective"
INCREMENTAL = "incremental"
GRADUAL = "gradual"Factory function to create frozen configuration.
def create_frozen_config(
strategy: UpdateStrategy = UpdateStrategy.ADAPTIVE,
learning_rate: float = 0.001,
freeze_layers: List[str] = None,
importance_threshold: float = 0.1
) -> Dict[str, Any]Factory function to create AReaL-style trainer.
from sandgraph.core.areal_kv_cache import create_areal_style_trainer
def create_areal_style_trainer(
kv_cache_size: int = 5000,
max_memory_gb: float = 4.0,
rollout_batch_size: int = 16,
enable_streaming: bool = True,
cache_policy: str = "lru",
**kwargs
) -> AReaLStyleTrainerParameters:
kv_cache_size: Size of KV cachemax_memory_gb: Maximum memory usage in GBrollout_batch_size: Batch size for rolloutsenable_streaming: Enable streaming generationcache_policy: Cache replacement policy (lru, lfu, priority)
AReaL-style trainer with KV cache optimization.
class AReaLStyleTrainer:
def __init__(self, kv_cache_size: int, max_memory_gb: float, **kwargs)
def add_trajectory(self, trajectory: List[Dict[str, Any]])
def update_policy(self, batch_size: int = None) -> Dict[str, Any]
def get_stats(self) -> Dict[str, Any]
def clear_cache(self)
def set_cache_policy(self, policy: str)
def get_cache_stats(self) -> Dict[str, Any]Methods:
add_trajectory(): Add trajectory dataupdate_policy(): Update policy using PPOget_stats(): Get comprehensive statisticsclear_cache(): Clear KV cacheset_cache_policy(): Set cache replacement policyget_cache_stats(): Get cache statistics
Factory function to create enhanced PPO trainer.
from sandgraph.core.enhanced_rl_algorithms import create_enhanced_ppo_trainer
def create_enhanced_ppo_trainer(
llm_manager: SharedLLMManager,
learning_rate: float = 0.001,
enable_caching: bool = True,
cache_size: int = 10000,
**kwargs
) -> EnhancedPPOTrainerEnhanced PPO trainer with advanced features.
class EnhancedPPOTrainer:
def __init__(self, llm_manager: SharedLLMManager, **kwargs)
def add_experience(self, state: Dict[str, Any], action: str,
reward: float, done: bool, next_state: Dict[str, Any] = None)
def update_policy(self) -> Dict[str, Any]
def get_performance_stats(self) -> Dict[str, Any]
def enable_caching(self, cache_size: int = 10000)
def disable_caching(self)
def get_cache_stats(self) -> Dict[str, Any]from sandgraph.core.llm_interface import create_shared_llm_manager
from sandgraph.core.sg_workflow import SG_Workflow, WorkflowMode, NodeType
# Create LLM manager
llm_manager = create_shared_llm_manager("mistralai/Mistral-7B-Instruct-v0.2")
# Create workflow
workflow = SG_Workflow("my_workflow", WorkflowMode.TRADITIONAL, llm_manager)
# Add nodes
workflow.add_node(NodeType.SANDBOX, "env", {"sandbox": MySandbox()})
workflow.add_node(NodeType.LLM, "decision", {"role": "Decision Maker"})
# Execute
result = workflow.execute_full_workflow()from sandgraph.core.monitoring import SocialNetworkMonitor, MonitoringConfig
# Create monitor
monitor = SocialNetworkMonitor(
MonitoringConfig(
enable_wandb=True,
enable_tensorboard=True,
wandb_project_name="my-project"
)
)
# Start monitoring
monitor.start_monitoring()
# Update metrics
metrics = SocialNetworkMetrics(
total_users=1000,
active_users=800,
engagement_rate=0.75,
content_quality_score=0.8,
network_density=0.1,
viral_spread_rate=0.3,
response_time_avg=1.2,
error_rate=0.01
)
monitor.update_metrics(metrics)
# Stop monitoring
monitor.stop_monitoring()from sandgraph.core.areal_kv_cache import create_areal_style_trainer
# Create AReaL trainer
trainer = create_areal_style_trainer(
kv_cache_size=10000,
max_memory_gb=8.0,
rollout_batch_size=32,
enable_streaming=True
)
# Add trajectory
trajectory = [
{"state": {"user_count": 100}, "action": "CREATE_POST", "reward": 1.0},
{"state": {"user_count": 101}, "action": "LIKE_POST", "reward": 0.5}
]
trainer.add_trajectory(trajectory)
# Update policy
result = trainer.update_policy(batch_size=32)
print(f"Policy loss: {result['losses']['policy_loss']:.4f}")class SandGraphError(Exception):
"""Base exception for SandGraphX"""
pass
class WorkflowError(SandGraphError):
"""Workflow-related errors"""
pass
class LLMError(SandGraphError):
"""LLM-related errors"""
pass
class RLError(SandGraphError):
"""RL-related errors"""
pass
class MonitoringError(SandGraphError):
"""Monitoring-related errors"""
passtry:
result = workflow.execute_full_workflow()
except WorkflowError as e:
print(f"Workflow error: {e}")
except LLMError as e:
print(f"LLM error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")