Python SDK
Python SDK
Section titled “Python SDK”The Hyra Network Python SDK provides a comprehensive toolkit for developers to interact with the Hyra Network, enabling AI model deployment, task processing, and network participation.
Installation
Section titled “Installation”Prerequisites
Section titled “Prerequisites”- Python 3.8 or higher
- pip package manager
- Git (for development)
Install from PyPI
Section titled “Install from PyPI”pip install hyra-networkInstall from Source
Section titled “Install from Source”git clone https://github.com/hyra-network/hyra-python-sdk.gitcd hyra-python-sdkpip install -e .Development Installation
Section titled “Development Installation”git clone https://github.com/hyra-network/hyra-python-sdk.gitcd hyra-python-sdkpip install -e ".[dev]"Quick Start
Section titled “Quick Start”Basic Setup
Section titled “Basic Setup”from hyra_network import HyraClientfrom hyra_network.config import Config
# Initialize clientconfig = Config( network_url="https://testnet.hyra.network", private_key="your_private_key", wallet_address="your_wallet_address")
client = HyraClient(config)Connect to Network
Section titled “Connect to Network”# Check network connectionif client.is_connected(): print("Connected to Hyra Network")else: print("Failed to connect to network")Core Features
Section titled “Core Features”Task Management
Section titled “Task Management”Create a Task
Section titled “Create a Task”from hyra_network.tasks import Task
# Create a new tasktask = Task( description="Train a sentiment analysis model", reward=1000, # HYRA tokens deadline=86400, # 24 hours data_hash="0x1234567890abcdef")
task_id = client.create_task(task)print(f"Task created with ID: {task_id}")Claim a Task
Section titled “Claim a Task”# Get available tasksavailable_tasks = client.get_available_tasks()print(f"Found {len(available_tasks)} available tasks")
# Claim a taskif available_tasks: task = available_tasks[0] success = client.claim_task(task.id) if success: print(f"Successfully claimed task {task.id}")Process a Task
Section titled “Process a Task”# Process claimed taskdef process_task(task_data): # Your AI processing logic here result = your_ai_model.predict(task_data) return result
# Get task datatask_data = client.get_task_data(task_id)
# Process taskresult = process_task(task_data)
# Submit resultclient.submit_task_result(task_id, result)AI Model Management
Section titled “AI Model Management”Register a Model
Section titled “Register a Model”from hyra_network.models import Model
# Create model instancemodel = Model( name="Sentiment Analysis Model", description="A model for sentiment analysis", category="NLP", framework="PyTorch", architecture="BERT", parameters=110000000, # 110M parameters input_format="text", output_format="sentiment_score")
# Register modelmodel_id = client.register_model(model)print(f"Model registered with ID: {model_id}")Deploy a Model
Section titled “Deploy a Model”# Deploy model for inferencedeployment = client.deploy_model( model_id=model_id, deployment_config={ "replicas": 3, "resources": { "cpu": "2", "memory": "4Gi", "gpu": "1" } })
print(f"Model deployed with ID: {deployment.id}")Use a Model
Section titled “Use a Model”# Use deployed model for inferenceresult = client.infer( model_id=model_id, input_data="This is a great product!", deployment_id=deployment.id)
print(f"Sentiment score: {result.sentiment_score}")Network Participation
Section titled “Network Participation”Register as Compute Node
Section titled “Register as Compute Node”from hyra_network.nodes import ComputeNode
# Create compute nodenode = ComputeNode( capabilities=["AI", "ML", "NLP"], max_load=10, resources={ "cpu": "8", "memory": "16Gi", "gpu": "2" })
# Register nodenode_id = client.register_node(node)print(f"Node registered with ID: {node_id}")Start Processing
Section titled “Start Processing”# Start processing tasksdef task_processor(task): # Process task result = process_task(task.data) return result
# Start processing loopclient.start_processing(task_processor)Advanced Features
Section titled “Advanced Features”Custom AI Models
Section titled “Custom AI Models”Create Custom Model
Section titled “Create Custom Model”from hyra_network.models import CustomModelimport torchimport torch.nn as nn
class MyCustomModel(nn.Module): def __init__(self): super().__init__() self.linear = nn.Linear(10, 1)
def forward(self, x): return self.linear(x)
# Create custom modelmodel = CustomModel( name="Custom Model", model_class=MyCustomModel, training_data="path/to/training/data", hyperparameters={ "learning_rate": 0.001, "batch_size": 32, "epochs": 100 })
# Register custom modelmodel_id = client.register_custom_model(model)Train Model
Section titled “Train Model”# Train model on Hyra Networktraining_job = client.train_model( model_id=model_id, training_data="path/to/training/data", training_config={ "epochs": 100, "batch_size": 32, "learning_rate": 0.001 })
# Monitor training progresswhile not training_job.is_complete(): progress = training_job.get_progress() print(f"Training progress: {progress.percentage}%") time.sleep(10)
print("Training completed!")Federated Learning
Section titled “Federated Learning”Setup Federated Learning
Section titled “Setup Federated Learning”from hyra_network.federated import FederatedLearning
# Create federated learning sessionfl = FederatedLearning( model_id=model_id, participants=["node1", "node2", "node3"], aggregation_method="fedavg", communication_rounds=10)
# Start federated learningfl.start()Participate in Federated Learning
Section titled “Participate in Federated Learning”# Join federated learning sessiondef local_training(data): # Your local training logic return trained_model
# Participate in federated learningfl.participate(local_training)Privacy-Preserving AI
Section titled “Privacy-Preserving AI”Homomorphic Encryption
Section titled “Homomorphic Encryption”from hyra_network.privacy import HomomorphicEncryption
# Setup homomorphic encryptionhe = HomomorphicEncryption()
# Encrypt dataencrypted_data = he.encrypt(data)
# Process encrypted dataencrypted_result = he.process(encrypted_data, model)
# Decrypt resultresult = he.decrypt(encrypted_result)Differential Privacy
Section titled “Differential Privacy”from hyra_network.privacy import DifferentialPrivacy
# Setup differential privacydp = DifferentialPrivacy(epsilon=1.0, delta=1e-5)
# Add noise to datanoisy_data = dp.add_noise(data)
# Process with privacyresult = model.predict(noisy_data)Configuration
Section titled “Configuration”Environment Variables
Section titled “Environment Variables”# Set environment variablesexport HYRA_NETWORK_URL="https://testnet.hyra.network"export HYRA_PRIVATE_KEY="your_private_key"export HYRA_WALLET_ADDRESS="your_wallet_address"Configuration File
Section titled “Configuration File”network: url: "https://testnet.hyra.network" chain_id: 1
wallet: private_key: "your_private_key" address: "your_wallet_address"
logging: level: "INFO" file: "hyra.log"Load Configuration
Section titled “Load Configuration”from hyra_network.config import load_config
# Load from fileconfig = load_config("config.yaml")
# Load from environmentconfig = load_config()
# Create client with configclient = HyraClient(config)Error Handling
Section titled “Error Handling”Exception Handling
Section titled “Exception Handling”from hyra_network.exceptions import ( HyraNetworkError, TaskNotFoundError, ModelNotFoundError, InsufficientFundsError)
try: # Your code here result = client.process_task(task_id)except TaskNotFoundError: print("Task not found")except InsufficientFundsError: print("Insufficient funds")except HyraNetworkError as e: print(f"Network error: {e}")Retry Logic
Section titled “Retry Logic”from hyra_network.utils import retry
@retry(max_attempts=3, delay=1.0)def process_task_with_retry(task_id): return client.process_task(task_id)
# Use retry decoratorresult = process_task_with_retry(task_id)Testing
Section titled “Testing”Unit Tests
Section titled “Unit Tests”import unittestfrom hyra_network import HyraClientfrom hyra_network.config import Config
class TestHyraClient(unittest.TestCase): def setUp(self): self.config = Config( network_url="https://testnet.hyra.network", private_key="test_private_key", wallet_address="test_wallet_address" ) self.client = HyraClient(self.config)
def test_connection(self): self.assertTrue(self.client.is_connected())
def test_create_task(self): task = Task( description="Test task", reward=100, deadline=3600, data_hash="0x123" ) task_id = self.client.create_task(task) self.assertIsNotNone(task_id)
if __name__ == "__main__": unittest.main()Integration Tests
Section titled “Integration Tests”import pytestfrom hyra_network import HyraClient
@pytest.fixturedef client(): config = Config( network_url="https://testnet.hyra.network", private_key="test_private_key", wallet_address="test_wallet_address" ) return HyraClient(config)
def test_task_lifecycle(client): # Create task task = Task(description="Test", reward=100, deadline=3600, data_hash="0x123") task_id = client.create_task(task)
# Claim task success = client.claim_task(task_id) assert success
# Process task result = client.process_task(task_id) assert result is not None
# Submit result success = client.submit_task_result(task_id, result) assert successPerformance Optimization
Section titled “Performance Optimization”Async Operations
Section titled “Async Operations”import asynciofrom hyra_network.async_client import AsyncHyraClient
async def process_tasks_async(): client = AsyncHyraClient(config)
# Get available tasks tasks = await client.get_available_tasks()
# Process tasks concurrently results = await asyncio.gather(*[ client.process_task(task.id) for task in tasks ])
return results
# Run async operationsresults = asyncio.run(process_tasks_async())Batch Operations
Section titled “Batch Operations”# Batch create taskstasks = [ Task(description=f"Task {i}", reward=100, deadline=3600, data_hash=f"0x{i}") for i in range(10)]
task_ids = client.batch_create_tasks(tasks)print(f"Created {len(task_ids)} tasks")
# Batch process tasksresults = client.batch_process_tasks(task_ids)print(f"Processed {len(results)} tasks")Monitoring and Analytics
Section titled “Monitoring and Analytics”Performance Metrics
Section titled “Performance Metrics”from hyra_network.monitoring import MetricsCollector
# Setup metrics collectionmetrics = MetricsCollector()
# Track performancewith metrics.track("task_processing"): result = client.process_task(task_id)
# Get metricsperformance_metrics = metrics.get_metrics()print(f"Average processing time: {performance_metrics.avg_processing_time}")Logging
Section titled “Logging”import loggingfrom hyra_network.logging import setup_logging
# Setup loggingsetup_logging(level=logging.INFO, file="hyra.log")
# Use loggerlogger = logging.getLogger("hyra_network")logger.info("Processing task %s", task_id)Best Practices
Section titled “Best Practices”Security
Section titled “Security”# Use secure configurationconfig = Config( network_url="https://mainnet.hyra.network", private_key=os.getenv("HYRA_PRIVATE_KEY"), # Never hardcode wallet_address=os.getenv("HYRA_WALLET_ADDRESS"))
# Validate inputsdef validate_task(task): if not task.description: raise ValueError("Task description required") if task.reward <= 0: raise ValueError("Task reward must be positive") return TrueResource Management
Section titled “Resource Management”# Use context managerswith client.task_context(task_id) as task: result = process_task(task.data) task.submit_result(result)
# Cleanup resourcesclient.cleanup()Error Recovery
Section titled “Error Recovery”def robust_task_processing(task_id): max_retries = 3 for attempt in range(max_retries): try: result = client.process_task(task_id) return result except Exception as e: if attempt == max_retries - 1: raise time.sleep(2 ** attempt) # Exponential backoffAPI Reference
Section titled “API Reference”HyraClient
Section titled “HyraClient”class HyraClient: def __init__(self, config: Config): """Initialize Hyra client with configuration."""
def create_task(self, task: Task) -> str: """Create a new task."""
def get_available_tasks(self) -> List[Task]: """Get available tasks."""
def claim_task(self, task_id: str) -> bool: """Claim a task."""
def process_task(self, task_id: str) -> Any: """Process a task."""
def submit_task_result(self, task_id: str, result: Any) -> bool: """Submit task result."""class Task: def __init__(self, description: str, reward: int, deadline: int, data_hash: str): """Initialize task."""
@property def id(self) -> str: """Get task ID."""
@property def status(self) -> str: """Get task status."""class Model: def __init__(self, name: str, description: str, category: str, **kwargs): """Initialize model."""
def register(self, client: HyraClient) -> str: """Register model."""
def deploy(self, client: HyraClient, config: dict) -> str: """Deploy model."""Examples
Section titled “Examples”Complete Example
Section titled “Complete Example”from hyra_network import HyraClient, Task, Modelfrom hyra_network.config import Config
def main(): # Setup config = Config( network_url="https://testnet.hyra.network", private_key="your_private_key", wallet_address="your_wallet_address" ) client = HyraClient(config)
# Register model model = Model( name="Sentiment Analysis", description="Sentiment analysis model", category="NLP" ) model_id = client.register_model(model)
# Create task task = Task( description="Analyze sentiment of customer reviews", reward=1000, deadline=86400, data_hash="0x1234567890abcdef" ) task_id = client.create_task(task)
# Process task result = client.process_task(task_id) print(f"Task result: {result}")
if __name__ == "__main__": main()