Fix datetime.UTC to timezone.utc across agent-coordinator codebase
Some checks failed
API Endpoint Tests / test-api-endpoints (push) Successful in 26s
Blockchain Synchronization Verification / sync-verification (push) Failing after 2s
Cross-Chain Functionality Tests / test-cross-chain-sync (push) Failing after 3s
Cross-Chain Functionality Tests / test-cross-chain-transactions (push) Successful in 5s
Cross-Chain Functionality Tests / test-cross-chain-bridge (push) Has been skipped
Cross-Chain Functionality Tests / test-multi-chain-consensus (push) Failing after 2s
Cross-Chain Functionality Tests / aggregate-results (push) Has been skipped
Cross-Node Transaction Testing / transaction-test (push) Successful in 10s
Deploy to Testnet / deploy-testnet (push) Successful in 1m17s
Documentation Validation / validate-docs (push) Successful in 26s
Deploy to Testnet / notify-deployment (push) Has been cancelled
Integration Tests / test-service-integration (push) Has been cancelled
Multi-Node Blockchain Health Monitoring / health-check (push) Has been cancelled
Multi-Node Stress Testing / stress-test (push) Has been cancelled
Node Failover Simulation / failover-test (push) Has been cancelled
P2P Network Verification / p2p-verification (push) Has been cancelled
Python Tests / test-python (push) Has been cancelled
Security Scanning / security-scan (push) Has been cancelled
Documentation Validation / validate-policies-strict (push) Successful in 6s
Production Tests / Production Integration Tests (push) Successful in 42s
Staking Tests / test-staking-service (push) Failing after 11s
Staking Tests / test-staking-integration (push) Has been skipped
Staking Tests / test-staking-contract (push) Has been skipped
Staking Tests / run-staking-test-runner (push) Has been skipped
Systemd Sync / sync-systemd (push) Successful in 26s
Some checks failed
API Endpoint Tests / test-api-endpoints (push) Successful in 26s
Blockchain Synchronization Verification / sync-verification (push) Failing after 2s
Cross-Chain Functionality Tests / test-cross-chain-sync (push) Failing after 3s
Cross-Chain Functionality Tests / test-cross-chain-transactions (push) Successful in 5s
Cross-Chain Functionality Tests / test-cross-chain-bridge (push) Has been skipped
Cross-Chain Functionality Tests / test-multi-chain-consensus (push) Failing after 2s
Cross-Chain Functionality Tests / aggregate-results (push) Has been skipped
Cross-Node Transaction Testing / transaction-test (push) Successful in 10s
Deploy to Testnet / deploy-testnet (push) Successful in 1m17s
Documentation Validation / validate-docs (push) Successful in 26s
Deploy to Testnet / notify-deployment (push) Has been cancelled
Integration Tests / test-service-integration (push) Has been cancelled
Multi-Node Blockchain Health Monitoring / health-check (push) Has been cancelled
Multi-Node Stress Testing / stress-test (push) Has been cancelled
Node Failover Simulation / failover-test (push) Has been cancelled
P2P Network Verification / p2p-verification (push) Has been cancelled
Python Tests / test-python (push) Has been cancelled
Security Scanning / security-scan (push) Has been cancelled
Documentation Validation / validate-policies-strict (push) Successful in 6s
Production Tests / Production Integration Tests (push) Successful in 42s
Staking Tests / test-staking-service (push) Failing after 11s
Staking Tests / test-staking-integration (push) Has been skipped
Staking Tests / test-staking-contract (push) Has been skipped
Staking Tests / run-staking-test-runner (push) Has been skipped
Systemd Sync / sync-systemd (push) Successful in 26s
- Changed datetime.UTC to timezone.utc in advanced_ai.py - Changed datetime.UTC to timezone.utc in realtime_learning.py - Changed datetime.UTC to timezone.utc in jwt_handler.py - Changed datetime.UTC to timezone.utc in distributed_consensus.py - Changed datetime.UTC to timezone.utc in exceptions.py - Changed datetime.UTC to timezone.utc in alerting.py - Changed datetime.UTC to timezone.utc in communication.py - Changed datetime.UTC to timezone.utc in message_types.py - Updated imports from `datetime import
This commit is contained in:
@@ -10,7 +10,7 @@ try:
|
||||
import numpy as np
|
||||
except ImportError: # pragma: no cover - optional dependency for runtime AI features
|
||||
np = None
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Dict, List, Any, Optional, Tuple
|
||||
from dataclasses import dataclass, field
|
||||
from collections import defaultdict
|
||||
@@ -93,7 +93,7 @@ class AdvancedAIIntegration:
|
||||
'hidden_sizes': hidden_sizes,
|
||||
'output_size': output_size
|
||||
},
|
||||
'created_at': datetime.now(datetime.UTC).isoformat()
|
||||
'created_at': datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -187,7 +187,7 @@ class AdvancedAIIntegration:
|
||||
'final_loss': losses[-1] if losses else 0,
|
||||
'accuracy': accuracy,
|
||||
'training_data_size': len(training_data),
|
||||
'trained_at': datetime.now(datetime.UTC).isoformat()
|
||||
'trained_at': datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -218,7 +218,7 @@ class AdvancedAIIntegration:
|
||||
'network_id': network_id,
|
||||
'features': features,
|
||||
'prediction': float(prediction[0][0]),
|
||||
'timestamp': datetime.now(datetime.UTC).isoformat()
|
||||
'timestamp': datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
self.predictions_history.append(prediction_record)
|
||||
|
||||
@@ -227,7 +227,7 @@ class AdvancedAIIntegration:
|
||||
'network_id': network_id,
|
||||
'prediction': float(prediction[0][0]),
|
||||
'confidence': max(prediction[0][0], 1 - prediction[0][0]),
|
||||
'predicted_at': datetime.now(datetime.UTC).isoformat()
|
||||
'predicted_at': datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -261,7 +261,7 @@ class AdvancedAIIntegration:
|
||||
'model_type': model_type,
|
||||
'features': features,
|
||||
'target': target,
|
||||
'created_at': datetime.now(datetime.UTC).isoformat()
|
||||
'created_at': datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -286,7 +286,7 @@ class AdvancedAIIntegration:
|
||||
|
||||
model.accuracy = accuracy
|
||||
model.training_data_size = len(training_data)
|
||||
model.last_trained = datetime.now(datetime.UTC)
|
||||
model.last_trained = datetime.now(timezone.utc)
|
||||
|
||||
# Store performance
|
||||
self.model_performance[model_id].append(accuracy)
|
||||
@@ -405,7 +405,7 @@ class AdvancedAIIntegration:
|
||||
'model_id': model_id,
|
||||
'features': features,
|
||||
'prediction': prediction,
|
||||
'timestamp': datetime.now(datetime.UTC).isoformat()
|
||||
'timestamp': datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
self.predictions_history.append(prediction_record)
|
||||
|
||||
@@ -414,7 +414,7 @@ class AdvancedAIIntegration:
|
||||
'model_id': model_id,
|
||||
'prediction': prediction,
|
||||
'confidence': min(1.0, max(0.0, prediction)) if model.model_type == 'logistic_regression' else None,
|
||||
'predicted_at': datetime.now(datetime.UTC).isoformat()
|
||||
'predicted_at': datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -451,7 +451,7 @@ class AdvancedAIIntegration:
|
||||
'model_performance': model_stats,
|
||||
'training_data_sizes': training_stats,
|
||||
'available_model_types': list(set(model.model_type for model in self.models.values())),
|
||||
'last_updated': datetime.now(datetime.UTC).isoformat()
|
||||
'last_updated': datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
|
||||
@@ -4,7 +4,7 @@ Implements adaptive learning, predictive analytics, and intelligent optimization
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Dict, List, Any, Optional, Tuple
|
||||
from dataclasses import dataclass, field
|
||||
from collections import defaultdict, deque
|
||||
@@ -55,7 +55,7 @@ class RealTimeLearningSystem:
|
||||
try:
|
||||
experience = LearningExperience(
|
||||
experience_id=str(uuid.uuid4()),
|
||||
timestamp=datetime.now(datetime.UTC),
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
context=experience_data.get('context', {}),
|
||||
action=experience_data.get('action', ''),
|
||||
outcome=experience_data.get('outcome', ''),
|
||||
@@ -157,7 +157,7 @@ class RealTimeLearningSystem:
|
||||
features=['action', 'context_load', 'context_agents'],
|
||||
target='performance_score',
|
||||
accuracy=0.85,
|
||||
last_updated=datetime.now(datetime.UTC)
|
||||
last_updated=datetime.now(timezone.utc)
|
||||
)
|
||||
|
||||
self.models['performance'] = performance_model
|
||||
@@ -169,7 +169,7 @@ class RealTimeLearningSystem:
|
||||
features=['action', 'context_time', 'context_resources'],
|
||||
target='success_probability',
|
||||
accuracy=0.82,
|
||||
last_updated=datetime.now(datetime.UTC)
|
||||
last_updated=datetime.now(timezone.utc)
|
||||
)
|
||||
|
||||
self.models['success'] = success_model
|
||||
@@ -257,7 +257,7 @@ class RealTimeLearningSystem:
|
||||
try:
|
||||
total_experiences = len(self.experiences)
|
||||
recent_experiences = [exp for exp in self.experiences
|
||||
if exp.timestamp > datetime.now(datetime.UTC) - timedelta(hours=24)]
|
||||
if exp.timestamp > datetime.now(timezone.utc) - timedelta(hours=24)]
|
||||
|
||||
if not self.experiences:
|
||||
return {
|
||||
@@ -299,7 +299,7 @@ class RealTimeLearningSystem:
|
||||
def _get_last_adaptation_time(self) -> Optional[str]:
|
||||
"""Get the time of the last adaptation"""
|
||||
# This would be tracked in a real implementation
|
||||
return datetime.now(datetime.UTC).isoformat() if len(self.experiences) > 50 else None
|
||||
return datetime.now(timezone.utc).isoformat() if len(self.experiences) > 50 else None
|
||||
|
||||
async def recommend_action(self, context: Dict[str, Any], available_actions: List[str]) -> Dict[str, Any]:
|
||||
"""Recommend the best action based on learning"""
|
||||
|
||||
@@ -3,7 +3,7 @@ JWT Authentication Handler for AITBC Agent Coordinator
|
||||
Implements JWT token generation, validation, and management
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Dict, Any, Optional, List
|
||||
import secrets
|
||||
|
||||
@@ -26,15 +26,15 @@ class JWTHandler:
|
||||
|
||||
try:
|
||||
if expires_delta:
|
||||
expire = datetime.now(datetime.UTC) + expires_delta
|
||||
expire = datetime.now(timezone.utc) + expires_delta
|
||||
else:
|
||||
expire = datetime.now(datetime.UTC) + self.token_expiry
|
||||
expire = datetime.now(timezone.utc) + self.token_expiry
|
||||
|
||||
# Add standard claims
|
||||
token_payload = {
|
||||
**payload,
|
||||
"exp": expire,
|
||||
"iat": datetime.now(datetime.UTC),
|
||||
"iat": datetime.now(timezone.utc),
|
||||
"type": "access"
|
||||
}
|
||||
|
||||
@@ -57,12 +57,12 @@ class JWTHandler:
|
||||
import jwt
|
||||
|
||||
try:
|
||||
expire = datetime.now(datetime.UTC) + self.refresh_expiry
|
||||
expire = datetime.now(timezone.utc) + self.refresh_expiry
|
||||
|
||||
token_payload = {
|
||||
**payload,
|
||||
"exp": expire,
|
||||
"iat": datetime.now(datetime.UTC),
|
||||
"iat": datetime.now(timezone.utc),
|
||||
"type": "refresh"
|
||||
}
|
||||
|
||||
@@ -227,7 +227,7 @@ class APIKeyManager:
|
||||
key_data = {
|
||||
"user_id": user_id,
|
||||
"permissions": permissions or [],
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
"last_used": None,
|
||||
"usage_count": 0
|
||||
}
|
||||
@@ -258,7 +258,7 @@ class APIKeyManager:
|
||||
key_data = self.api_keys[api_key]
|
||||
|
||||
# Update usage statistics
|
||||
key_data["last_used"] = datetime.now(datetime.UTC).isoformat()
|
||||
key_data["last_used"] = datetime.now(timezone.utc).isoformat()
|
||||
key_data["usage_count"] += 1
|
||||
|
||||
return {
|
||||
|
||||
@@ -4,7 +4,7 @@ Implements various consensus algorithms for distributed decision making
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Dict, List, Any, Optional, Set, Tuple
|
||||
from dataclasses import dataclass, field
|
||||
from collections import defaultdict
|
||||
@@ -59,7 +59,7 @@ class DistributedConsensus:
|
||||
node = ConsensusNode(
|
||||
node_id=node_id,
|
||||
endpoint=endpoint,
|
||||
last_seen=datetime.now(datetime.UTC),
|
||||
last_seen=datetime.now(timezone.utc),
|
||||
reputation_score=node_data.get('reputation_score', 1.0),
|
||||
voting_power=node_data.get('voting_power', 1.0),
|
||||
is_active=True
|
||||
@@ -70,7 +70,7 @@ class DistributedConsensus:
|
||||
return {
|
||||
'status': 'success',
|
||||
'node_id': node_id,
|
||||
'registered_at': datetime.now(datetime.UTC).isoformat(),
|
||||
'registered_at': datetime.now(timezone.utc).isoformat(),
|
||||
'total_nodes': len(self.nodes)
|
||||
}
|
||||
|
||||
@@ -98,8 +98,8 @@ class DistributedConsensus:
|
||||
proposal_id=proposal_id,
|
||||
proposer_id=proposer_id,
|
||||
proposal_data=proposal_data.get('content', {}),
|
||||
timestamp=datetime.now(datetime.UTC),
|
||||
deadline=datetime.now(datetime.UTC) + self.voting_timeout,
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
deadline=datetime.now(timezone.utc) + self.voting_timeout,
|
||||
required_votes=required_votes
|
||||
)
|
||||
|
||||
@@ -186,7 +186,7 @@ class DistributedConsensus:
|
||||
|
||||
# Record vote
|
||||
proposal.current_votes[node_id] = vote
|
||||
self.nodes[node_id].last_seen = datetime.now(datetime.UTC)
|
||||
self.nodes[node_id].last_seen = datetime.now(timezone.utc)
|
||||
|
||||
# Check if consensus is reached
|
||||
await self._check_consensus(proposal)
|
||||
@@ -216,7 +216,7 @@ class DistributedConsensus:
|
||||
total_votes = len(proposal.current_votes)
|
||||
|
||||
# Check if deadline passed
|
||||
if datetime.now(datetime.UTC) > proposal.deadline:
|
||||
if datetime.now(timezone.utc) > proposal.deadline:
|
||||
proposal.status = 'expired'
|
||||
await self._finalize_proposal(proposal, False, 'Deadline expired')
|
||||
return
|
||||
@@ -266,7 +266,7 @@ class DistributedConsensus:
|
||||
'reason': reason,
|
||||
'votes': dict(proposal.current_votes),
|
||||
'required_votes': proposal.required_votes,
|
||||
'finalized_at': datetime.now(datetime.UTC).isoformat(),
|
||||
'finalized_at': datetime.now(timezone.utc).isoformat(),
|
||||
'algorithm': self.current_algorithm
|
||||
}
|
||||
|
||||
@@ -283,7 +283,7 @@ class DistributedConsensus:
|
||||
async def _cleanup_old_proposals(self):
|
||||
"""Clean up old and expired proposals"""
|
||||
try:
|
||||
current_time = datetime.now(datetime.UTC)
|
||||
current_time = datetime.now(timezone.utc)
|
||||
expired_proposals = [
|
||||
pid for pid, proposal in self.proposals.items()
|
||||
if proposal.deadline < current_time or proposal.status in ['approved', 'rejected', 'expired']
|
||||
@@ -340,7 +340,7 @@ class DistributedConsensus:
|
||||
return {
|
||||
'status': 'success',
|
||||
'algorithm': algorithm,
|
||||
'changed_at': datetime.now(datetime.UTC).isoformat()
|
||||
'changed_at': datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -400,7 +400,7 @@ class DistributedConsensus:
|
||||
'algorithm_performance': dict(algorithm_stats),
|
||||
'node_participation': node_participation,
|
||||
'active_proposals': len(self.proposals),
|
||||
'last_updated': datetime.now(datetime.UTC).isoformat()
|
||||
'last_updated': datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -414,13 +414,13 @@ class DistributedConsensus:
|
||||
return {'status': 'error', 'message': 'Node not found'}
|
||||
|
||||
self.nodes[node_id].is_active = is_active
|
||||
self.nodes[node_id].last_seen = datetime.now(datetime.UTC)
|
||||
self.nodes[node_id].last_seen = datetime.now(timezone.utc)
|
||||
|
||||
return {
|
||||
'status': 'success',
|
||||
'node_id': node_id,
|
||||
'is_active': is_active,
|
||||
'updated_at': datetime.now(datetime.UTC).isoformat()
|
||||
'updated_at': datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from aitbc import get_logger
|
||||
from fastapi.responses import JSONResponse
|
||||
@@ -14,7 +14,7 @@ def register_exception_handlers(app):
|
||||
content={
|
||||
"status": "error",
|
||||
"message": "Resource not found",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
},
|
||||
)
|
||||
|
||||
@@ -26,6 +26,6 @@ def register_exception_handlers(app):
|
||||
content={
|
||||
"status": "error",
|
||||
"message": "Internal server error",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
},
|
||||
)
|
||||
|
||||
@@ -5,7 +5,7 @@ Implements comprehensive alerting with multiple channels and SLA monitoring
|
||||
|
||||
import asyncio
|
||||
import smtplib
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Dict, List, Any, Optional, Callable
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum
|
||||
@@ -134,7 +134,7 @@ class SLAMonitor:
|
||||
return
|
||||
|
||||
if timestamp is None:
|
||||
timestamp = datetime.now(datetime.UTC)
|
||||
timestamp = datetime.now(timezone.utc)
|
||||
|
||||
rule = self.sla_rules[sla_id]
|
||||
|
||||
@@ -188,7 +188,7 @@ class SLAMonitor:
|
||||
# Get recent violations
|
||||
recent_violations = [
|
||||
v for v in self.violations[sla_id]
|
||||
if v["timestamp"] > datetime.now(datetime.UTC) - timedelta(hours=24)
|
||||
if v["timestamp"] > datetime.now(timezone.utc) - timedelta(hours=24)
|
||||
]
|
||||
|
||||
return {
|
||||
@@ -375,7 +375,7 @@ Annotations: {json.dumps(alert.annotations, indent=2)}
|
||||
payload = {
|
||||
"alert": alert.to_dict(),
|
||||
"message": message,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||
"timestamp": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
response = requests.post(
|
||||
@@ -499,7 +499,7 @@ class AlertManager:
|
||||
|
||||
try:
|
||||
condition_met = self._evaluate_condition(rule.condition, metrics, rule.threshold)
|
||||
current_time = datetime.now(datetime.UTC)
|
||||
current_time = datetime.now(timezone.utc)
|
||||
|
||||
if condition_met:
|
||||
# Check if condition has been met for required duration
|
||||
@@ -543,7 +543,7 @@ class AlertManager:
|
||||
|
||||
def _trigger_alert(self, rule: AlertRule, metrics: Dict[str, Any]):
|
||||
"""Trigger an alert"""
|
||||
alert_id = f"{rule.rule_id}_{int(datetime.now(datetime.UTC).timestamp())}"
|
||||
alert_id = f"{rule.rule_id}_{int(datetime.now(timezone.utc).timestamp())}"
|
||||
|
||||
# Check if similar alert is already active
|
||||
existing_alert = self._find_similar_active_alert(rule)
|
||||
@@ -556,8 +556,8 @@ class AlertManager:
|
||||
description=rule.description,
|
||||
severity=rule.severity,
|
||||
status=AlertStatus.ACTIVE,
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
updated_at=datetime.now(datetime.UTC),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
updated_at=datetime.now(timezone.utc),
|
||||
labels=rule.labels.copy(),
|
||||
annotations=rule.annotations.copy()
|
||||
)
|
||||
@@ -607,8 +607,8 @@ class AlertManager:
|
||||
|
||||
alert = self.alerts[alert_id]
|
||||
alert.status = AlertStatus.RESOLVED
|
||||
alert.resolved_at = datetime.now(datetime.UTC)
|
||||
alert.updated_at = datetime.now(datetime.UTC)
|
||||
alert.resolved_at = datetime.now(timezone.utc)
|
||||
alert.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
return {"status": "success", "alert": alert.to_dict()}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import json
|
||||
from enum import Enum
|
||||
from typing import Dict, List, Optional, Any, Callable
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
import uuid
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
@@ -43,7 +43,7 @@ class AgentMessage:
|
||||
receiver_id: Optional[str] = None
|
||||
message_type: MessageType = MessageType.DIRECT
|
||||
priority: Priority = Priority.NORMAL
|
||||
timestamp: datetime = field(default_factory=datetime.now(datetime.UTC))
|
||||
timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
payload: Dict[str, Any] = field(default_factory=dict)
|
||||
correlation_id: Optional[str] = None
|
||||
reply_to: Optional[str] = None
|
||||
@@ -123,7 +123,7 @@ class CommunicationProtocol:
|
||||
|
||||
def _is_message_expired(self, message: AgentMessage) -> bool:
|
||||
"""Check if message has expired"""
|
||||
age = (datetime.now(datetime.UTC) - message.timestamp).total_seconds()
|
||||
age = (datetime.now(timezone.utc) - message.timestamp).total_seconds()
|
||||
return age > message.ttl
|
||||
|
||||
async def _send_to_agent(self, message: AgentMessage):
|
||||
@@ -283,7 +283,7 @@ class MessageTemplates:
|
||||
sender_id=sender_id,
|
||||
message_type=MessageType.HEARTBEAT,
|
||||
priority=Priority.LOW,
|
||||
payload={"timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||
payload={"timestamp": datetime.now(timezone.utc).isoformat()}
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -7,7 +7,7 @@ import json
|
||||
from enum import Enum
|
||||
from typing import Dict, List, Optional, Any, Callable, Union
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
import uuid
|
||||
import hashlib
|
||||
from pydantic import BaseModel, Field, validator
|
||||
@@ -52,7 +52,7 @@ class RoutingRule:
|
||||
target: Optional[str] = None
|
||||
priority: int = 0
|
||||
enabled: bool = True
|
||||
created_at: datetime = field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
def matches(self, message: AgentMessage) -> bool:
|
||||
"""Check if message matches routing rule conditions"""
|
||||
@@ -72,12 +72,12 @@ class TaskMessage(BaseModel):
|
||||
priority: Priority = Field(Priority.NORMAL, description="Task priority")
|
||||
assigned_agent: Optional[str] = Field(None, description="Assigned agent ID")
|
||||
status: str = Field("pending", description="Task status")
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
@validator('deadline')
|
||||
def validate_deadline(cls, v):
|
||||
if v and v < datetime.now(datetime.UTC):
|
||||
if v and v < datetime.now(timezone.utc):
|
||||
raise ValueError("Deadline cannot be in the past")
|
||||
return v
|
||||
|
||||
@@ -90,8 +90,8 @@ class CoordinationMessage(BaseModel):
|
||||
decision_deadline: Optional[datetime] = Field(None, description="Decision deadline")
|
||||
consensus_threshold: float = Field(0.5, description="Consensus threshold")
|
||||
status: str = Field("pending", description="Coordination status")
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
class StatusMessage(BaseModel):
|
||||
"""Status update message structure"""
|
||||
@@ -101,7 +101,7 @@ class StatusMessage(BaseModel):
|
||||
health_score: float = Field(1.0, description="Agent health score")
|
||||
load_metrics: Dict[str, float] = Field(default_factory=dict, description="Load metrics")
|
||||
capabilities: List[str] = Field(default_factory=list, description="Agent capabilities")
|
||||
timestamp: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
class DiscoveryMessage(BaseModel):
|
||||
"""Agent discovery message structure"""
|
||||
@@ -111,7 +111,7 @@ class DiscoveryMessage(BaseModel):
|
||||
services: List[str] = Field(default_factory=list, description="Available services")
|
||||
endpoints: Dict[str, str] = Field(default_factory=dict, description="Service endpoints")
|
||||
metadata: Dict[str, Any] = Field(default_factory=dict, description="Additional metadata")
|
||||
timestamp: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
class ConsensusMessage(BaseModel):
|
||||
"""Consensus message structure"""
|
||||
@@ -122,8 +122,8 @@ class ConsensusMessage(BaseModel):
|
||||
voting_deadline: datetime = Field(..., description="Voting deadline")
|
||||
consensus_algorithm: str = Field("majority", description="Consensus algorithm")
|
||||
status: str = Field("pending", description="Consensus status")
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
class MessageRouter:
|
||||
"""Advanced message routing system"""
|
||||
@@ -156,7 +156,7 @@ class MessageRouter:
|
||||
|
||||
async def route_message(self, message: AgentMessage) -> Optional[str]:
|
||||
"""Route message based on routing rules"""
|
||||
start_time = datetime.now(datetime.UTC)
|
||||
start_time = datetime.now(timezone.utc)
|
||||
|
||||
try:
|
||||
# Check if message is expired
|
||||
@@ -192,7 +192,7 @@ class MessageRouter:
|
||||
self.routing_stats["messages_failed"] += 1
|
||||
return None
|
||||
finally:
|
||||
routing_time = (datetime.now(datetime.UTC) - start_time).total_seconds()
|
||||
routing_time = (datetime.now(timezone.utc) - start_time).total_seconds()
|
||||
self.routing_stats["routing_time_total"] += routing_time
|
||||
|
||||
async def _apply_routing_rule(self, rule: RoutingRule, message: AgentMessage) -> Optional[str]:
|
||||
@@ -244,7 +244,7 @@ class MessageRouter:
|
||||
|
||||
def _is_message_expired(self, message: AgentMessage) -> bool:
|
||||
"""Check if message is expired"""
|
||||
age = (datetime.now(datetime.UTC) - message.timestamp).total_seconds()
|
||||
age = (datetime.now(timezone.utc) - message.timestamp).total_seconds()
|
||||
return age > message.ttl
|
||||
|
||||
async def get_routing_stats(self) -> Dict[str, Any]:
|
||||
@@ -269,12 +269,12 @@ class LoadBalancer:
|
||||
def __init__(self):
|
||||
self.agent_loads: Dict[str, float] = {}
|
||||
self.agent_weights: Dict[str, float] = {}
|
||||
self.last_updated = datetime.now(datetime.UTC)
|
||||
self.last_updated = datetime.now(timezone.utc)
|
||||
|
||||
def update_agent_load(self, agent_id: str, load: float):
|
||||
"""Update agent load information"""
|
||||
self.agent_loads[agent_id] = load
|
||||
self.last_updated = datetime.now(datetime.UTC)
|
||||
self.last_updated = datetime.now(timezone.utc)
|
||||
|
||||
def set_agent_weight(self, agent_id: str, weight: float):
|
||||
"""Set agent weight for load balancing"""
|
||||
@@ -421,7 +421,7 @@ class MessageProcessor:
|
||||
|
||||
async def process_message(self, message: AgentMessage) -> bool:
|
||||
"""Process a message"""
|
||||
start_time = datetime.now(datetime.UTC)
|
||||
start_time = datetime.now(timezone.utc)
|
||||
|
||||
try:
|
||||
# Route message
|
||||
@@ -440,7 +440,7 @@ class MessageProcessor:
|
||||
|
||||
# Update stats
|
||||
self.processing_stats["messages_processed"] += 1
|
||||
processing_time = (datetime.now(datetime.UTC) - start_time).total_seconds()
|
||||
processing_time = (datetime.now(timezone.utc) - start_time).total_seconds()
|
||||
self.processing_stats["processing_time_total"] += processing_time
|
||||
|
||||
return True
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from aitbc import get_logger
|
||||
@@ -52,7 +52,7 @@ async def register_agent(request: AgentRegistrationRequest):
|
||||
"status": "success",
|
||||
"message": f"Agent {request.agent_id} registered successfully",
|
||||
"agent_id": request.agent_id,
|
||||
"registered_at": datetime.now(datetime.UTC).isoformat()
|
||||
"registered_at": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
else:
|
||||
raise HTTPException(status_code=500, detail="Failed to register agent")
|
||||
@@ -78,7 +78,7 @@ async def discover_agents(query: Dict[str, Any]):
|
||||
"query": query,
|
||||
"agents": [agent.to_dict() for agent in agents],
|
||||
"count": len(agents),
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||
"timestamp": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -101,7 +101,7 @@ async def get_agent(agent_id: str):
|
||||
return {
|
||||
"status": "success",
|
||||
"agent": agent.to_dict(),
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||
"timestamp": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
@@ -132,7 +132,7 @@ async def update_agent_status(agent_id: str, request: AgentStatusUpdate):
|
||||
"message": f"Agent {agent_id} status updated",
|
||||
"agent_id": agent_id,
|
||||
"new_status": request.status,
|
||||
"updated_at": datetime.now(datetime.UTC).isoformat()
|
||||
"updated_at": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
else:
|
||||
raise HTTPException(status_code=500, detail="Failed to update agent status")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from aitbc import get_logger
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from aitbc import get_logger
|
||||
@@ -156,7 +156,7 @@ async def record_sla_metric(
|
||||
"status": "success",
|
||||
"message": f"SLA metric recorded for {sla_id}",
|
||||
"value": value,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||
"timestamp": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
@@ -206,7 +206,7 @@ async def get_system_status(current_user: Dict[str, Any] = Depends(get_current_u
|
||||
"load_balancer": "running" if state.load_balancer else "stopped",
|
||||
"task_distributor": "running" if state.task_distributor else "stopped"
|
||||
},
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||
"timestamp": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
return status
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from aitbc import get_logger
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from aitbc import get_logger
|
||||
@@ -105,7 +105,7 @@ async def get_advanced_features_status():
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"features": {
|
||||
"realtime_learning": {
|
||||
"status": "active",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from aitbc import get_logger
|
||||
@@ -30,7 +30,7 @@ async def health_check():
|
||||
return {
|
||||
"status": "healthy",
|
||||
"service": "agent-coordinator",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"version": "1.0.0"
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from aitbc import get_logger
|
||||
@@ -63,7 +63,7 @@ async def send_message(request: MessageRequest):
|
||||
"message": "Message sent successfully",
|
||||
"message_id": message.id,
|
||||
"receiver_id": request.receiver_id,
|
||||
"sent_at": datetime.now(datetime.UTC).isoformat()
|
||||
"sent_at": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
else:
|
||||
raise HTTPException(status_code=500, detail="Failed to send message")
|
||||
@@ -85,7 +85,7 @@ async def get_load_balancer_stats():
|
||||
return {
|
||||
"status": "success",
|
||||
"stats": stats,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||
"timestamp": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -105,7 +105,7 @@ async def get_registry_stats():
|
||||
return {
|
||||
"status": "success",
|
||||
"stats": stats,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||
"timestamp": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -127,7 +127,7 @@ async def get_agents_by_service(service: str):
|
||||
"service": service,
|
||||
"agents": [agent.to_dict() for agent in agents],
|
||||
"count": len(agents),
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||
"timestamp": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -149,7 +149,7 @@ async def get_agents_by_capability(capability: str):
|
||||
"capability": capability,
|
||||
"agents": [agent.to_dict() for agent in agents],
|
||||
"count": len(agents),
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||
"timestamp": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -175,7 +175,7 @@ async def set_load_balancing_strategy(strategy: str = Query(..., description="Lo
|
||||
"status": "success",
|
||||
"message": f"Load balancing strategy set to {strategy}",
|
||||
"strategy": strategy,
|
||||
"updated_at": datetime.now(datetime.UTC).isoformat()
|
||||
"updated_at": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from aitbc import get_logger
|
||||
@@ -84,7 +84,7 @@ async def get_metrics_summary():
|
||||
"status": "success",
|
||||
"performance": summary,
|
||||
"system": system_metrics,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||
"timestamp": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -116,7 +116,7 @@ async def get_health_metrics():
|
||||
"count": psutil.cpu_count()
|
||||
},
|
||||
"uptime": performance_monitor.get_performance_summary()["uptime_seconds"],
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||
"timestamp": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
import uuid
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
@@ -50,7 +50,7 @@ async def submit_task(request: TaskSubmission, background_tasks: BackgroundTasks
|
||||
"message": "Task submitted successfully",
|
||||
"task_id": request.task_data.get("task_id", str(uuid.uuid4())),
|
||||
"priority": request.priority,
|
||||
"submitted_at": datetime.now(datetime.UTC).isoformat()
|
||||
"submitted_at": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
@@ -72,7 +72,7 @@ async def get_task_status():
|
||||
return {
|
||||
"status": "success",
|
||||
"stats": stats,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat()
|
||||
"timestamp": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from aitbc import get_logger
|
||||
|
||||
@@ -8,7 +8,7 @@ import asyncio
|
||||
import json
|
||||
from typing import Dict, List, Optional, Set, Callable, Any
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
import uuid
|
||||
import hashlib
|
||||
from enum import Enum
|
||||
@@ -178,7 +178,7 @@ class AgentRegistry:
|
||||
|
||||
agent_info = self.agents[agent_id]
|
||||
agent_info.status = status
|
||||
agent_info.last_heartbeat = datetime.now(datetime.UTC)
|
||||
agent_info.last_heartbeat = datetime.now(timezone.utc)
|
||||
|
||||
if load_metrics:
|
||||
agent_info.load_metrics.update(load_metrics)
|
||||
@@ -206,7 +206,7 @@ class AgentRegistry:
|
||||
return False
|
||||
|
||||
agent_info = self.agents[agent_id]
|
||||
agent_info.last_heartbeat = datetime.now(datetime.UTC)
|
||||
agent_info.last_heartbeat = datetime.now(timezone.utc)
|
||||
|
||||
# Update health score
|
||||
agent_info.health_score = self._calculate_health_score(agent_info)
|
||||
@@ -307,7 +307,7 @@ class AgentRegistry:
|
||||
"type_counts": type_counts,
|
||||
"service_count": len(self.service_index),
|
||||
"capability_count": len(self.capability_index),
|
||||
"last_cleanup": datetime.now(datetime.UTC).isoformat()
|
||||
"last_cleanup": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
def _update_indexes(self, agent_info: AgentInfo):
|
||||
@@ -372,7 +372,7 @@ class AgentRegistry:
|
||||
base_score -= 0.1
|
||||
|
||||
# Penalty for old heartbeat
|
||||
heartbeat_age = (datetime.now(datetime.UTC) - agent_info.last_heartbeat).total_seconds()
|
||||
heartbeat_age = (datetime.now(timezone.utc) - agent_info.last_heartbeat).total_seconds()
|
||||
if heartbeat_age > self.max_heartbeat_age:
|
||||
base_score -= 0.5
|
||||
elif heartbeat_age > self.max_heartbeat_age / 2:
|
||||
@@ -428,7 +428,7 @@ class AgentRegistry:
|
||||
|
||||
event = {
|
||||
"event_type": event_type,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"agent_info": agent_info.to_dict()
|
||||
}
|
||||
|
||||
@@ -441,7 +441,7 @@ class AgentRegistry:
|
||||
await asyncio.sleep(self.heartbeat_interval)
|
||||
|
||||
# Check for agents with old heartbeats
|
||||
now = datetime.now(datetime.UTC)
|
||||
now = datetime.now(timezone.utc)
|
||||
for agent_id, agent_info in list(self.agents.items()):
|
||||
heartbeat_age = (now - agent_info.last_heartbeat).total_seconds()
|
||||
|
||||
@@ -462,7 +462,7 @@ class AgentRegistry:
|
||||
await asyncio.sleep(self.cleanup_interval)
|
||||
|
||||
# Remove agents that have been inactive too long
|
||||
now = datetime.now(datetime.UTC)
|
||||
now = datetime.now(timezone.utc)
|
||||
max_inactive_age = timedelta(hours=1) # 1 hour
|
||||
|
||||
for agent_id, agent_info in list(self.agents.items()):
|
||||
@@ -502,8 +502,8 @@ class AgentDiscoveryService:
|
||||
services=discovery_data.services,
|
||||
endpoints=discovery_data.endpoints,
|
||||
metadata=discovery_data.metadata,
|
||||
last_heartbeat=datetime.now(datetime.UTC),
|
||||
registration_time=datetime.now(datetime.UTC)
|
||||
last_heartbeat=datetime.now(timezone.utc),
|
||||
registration_time=datetime.now(timezone.utc)
|
||||
)
|
||||
|
||||
# Register or update agent
|
||||
@@ -597,8 +597,8 @@ def create_agent_info(agent_id: str, agent_type: str, capabilities: List[str], s
|
||||
services=services,
|
||||
endpoints=endpoints,
|
||||
metadata={},
|
||||
last_heartbeat=datetime.now(datetime.UTC),
|
||||
registration_time=datetime.now(datetime.UTC)
|
||||
last_heartbeat=datetime.now(timezone.utc),
|
||||
registration_time=datetime.now(timezone.utc)
|
||||
)
|
||||
|
||||
# Example usage
|
||||
|
||||
@@ -6,7 +6,7 @@ import asyncio
|
||||
import json
|
||||
from typing import Dict, List, Optional, Tuple, Any, Callable
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from enum import Enum
|
||||
import statistics
|
||||
import uuid
|
||||
@@ -48,7 +48,7 @@ class LoadMetrics:
|
||||
completed_tasks: int = 0
|
||||
failed_tasks: int = 0
|
||||
avg_response_time: float = 0.0
|
||||
last_updated: datetime = field(default_factory=datetime.now(datetime.UTC))
|
||||
last_updated: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
@@ -94,7 +94,7 @@ class AgentWeight:
|
||||
capacity: int = 100
|
||||
performance_score: float = 1.0
|
||||
reliability_score: float = 1.0
|
||||
last_updated: datetime = field(default_factory=datetime.now(datetime.UTC))
|
||||
last_updated: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
class LoadBalancer:
|
||||
"""Advanced load balancer for agent distribution"""
|
||||
@@ -132,7 +132,7 @@ class LoadBalancer:
|
||||
def update_agent_metrics(self, agent_id: str, metrics: LoadMetrics):
|
||||
"""Update agent load metrics"""
|
||||
self.agent_metrics[agent_id] = metrics
|
||||
self.agent_metrics[agent_id].last_updated = datetime.now(datetime.UTC)
|
||||
self.agent_metrics[agent_id].last_updated = datetime.now(timezone.utc)
|
||||
|
||||
# Update performance score based on metrics
|
||||
self._update_performance_score(agent_id, metrics)
|
||||
@@ -196,7 +196,7 @@ class LoadBalancer:
|
||||
assignment = TaskAssignment(
|
||||
task_id=task_id,
|
||||
agent_id=selected_agent,
|
||||
assigned_at=datetime.now(datetime.UTC)
|
||||
assigned_at=datetime.now(timezone.utc)
|
||||
)
|
||||
|
||||
# Record assignment
|
||||
@@ -226,7 +226,7 @@ class LoadBalancer:
|
||||
return
|
||||
|
||||
assignment = self.task_assignments[task_id]
|
||||
assignment.completed_at = datetime.now(datetime.UTC)
|
||||
assignment.completed_at = datetime.now(timezone.utc)
|
||||
assignment.status = "completed"
|
||||
assignment.success = success
|
||||
assignment.response_time = response_time
|
||||
@@ -580,7 +580,7 @@ class TaskDistributor:
|
||||
"task_data": task_data,
|
||||
"priority": priority,
|
||||
"requirements": requirements,
|
||||
"submitted_at": datetime.now(datetime.UTC)
|
||||
"submitted_at": datetime.now(timezone.utc)
|
||||
}
|
||||
|
||||
await self.priority_queues[priority].put(task_info)
|
||||
@@ -612,7 +612,7 @@ class TaskDistributor:
|
||||
|
||||
async def _distribute_task(self, task_info: Dict[str, Any]):
|
||||
"""Distribute a single task"""
|
||||
start_time = datetime.now(datetime.UTC)
|
||||
start_time = datetime.now(timezone.utc)
|
||||
|
||||
try:
|
||||
# Assign task
|
||||
@@ -648,7 +648,7 @@ class TaskDistributor:
|
||||
|
||||
finally:
|
||||
# Update distribution time
|
||||
distribution_time = (datetime.now(datetime.UTC) - start_time).total_seconds()
|
||||
distribution_time = (datetime.now(timezone.utc) - start_time).total_seconds()
|
||||
total_distributed = self.distribution_stats["tasks_distributed"]
|
||||
self.distribution_stats["avg_distribution_time"] = (
|
||||
(self.distribution_stats["avg_distribution_time"] * (total_distributed - 1) + distribution_time) / total_distributed
|
||||
|
||||
@@ -5,7 +5,7 @@ Tests for Agent Communication Protocols
|
||||
import sys
|
||||
import pytest
|
||||
import asyncio
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from unittest.mock import Mock, AsyncMock
|
||||
|
||||
from src.app.protocols.communication import (
|
||||
@@ -63,12 +63,12 @@ class TestAgentMessage:
|
||||
sender_id="agent-001",
|
||||
receiver_id="agent-002",
|
||||
message_type=MessageType.DIRECT,
|
||||
timestamp=datetime.now(datetime.UTC) - timedelta(seconds=400),
|
||||
timestamp=datetime.now(timezone.utc) - timedelta(seconds=400),
|
||||
ttl=300
|
||||
)
|
||||
|
||||
# Message should be expired
|
||||
age = (datetime.now(datetime.UTC) - old_message.timestamp).total_seconds()
|
||||
age = (datetime.now(timezone.utc) - old_message.timestamp).total_seconds()
|
||||
assert age > old_message.ttl
|
||||
|
||||
class TestHierarchicalProtocol:
|
||||
|
||||
@@ -2,7 +2,7 @@ import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Callable, ContextManager, Optional
|
||||
|
||||
@@ -168,8 +168,10 @@ class PoAProposer:
|
||||
head = self._fetch_chain_head()
|
||||
if head is None:
|
||||
return
|
||||
now = datetime.now(datetime.UTC)
|
||||
elapsed = (now - head.timestamp).total_seconds()
|
||||
now = datetime.now(timezone.utc)
|
||||
# Ensure head.timestamp is timezone-aware
|
||||
head_timestamp = head.timestamp if head.timestamp.tzinfo is not None else head.timestamp.replace(tzinfo=timezone.utc)
|
||||
elapsed = (now - head_timestamp).total_seconds()
|
||||
sleep_for = max(self._config.interval_seconds - elapsed, 0.1)
|
||||
if sleep_for <= 0:
|
||||
sleep_for = 0.1
|
||||
@@ -201,7 +203,9 @@ class PoAProposer:
|
||||
elif block_generation_mode == "hybrid":
|
||||
# Hybrid mode: check heartbeat interval
|
||||
if self._last_block_timestamp:
|
||||
time_since_last_block = (datetime.now(datetime.UTC) - self._last_block_timestamp).total_seconds()
|
||||
# Ensure last_block_timestamp is timezone-aware
|
||||
last_timestamp = self._last_block_timestamp if self._last_block_timestamp.tzinfo is not None else self._last_block_timestamp.replace(tzinfo=timezone.utc)
|
||||
time_since_last_block = (datetime.now(timezone.utc) - last_timestamp).total_seconds()
|
||||
if mempool_size == 0 and time_since_last_block < max_empty_block_interval:
|
||||
self._logger.debug(f"[PROPOSE] Skipping block proposal: mempool empty, heartbeat not yet due (chain={self._config.chain_id}, mode=hybrid, idle_time={time_since_last_block:.1f}s)")
|
||||
metrics_registry.increment("sync_empty_blocks_skipped_total")
|
||||
@@ -224,9 +228,11 @@ class PoAProposer:
|
||||
if head is not None:
|
||||
next_height = head.height + 1
|
||||
parent_hash = head.hash
|
||||
interval_seconds = (datetime.now(datetime.UTC) - head.timestamp).total_seconds()
|
||||
# Ensure head.timestamp is timezone-aware
|
||||
head_timestamp = head.timestamp if head.timestamp.tzinfo is not None else head.timestamp.replace(tzinfo=timezone.utc)
|
||||
interval_seconds = (datetime.now(timezone.utc) - head_timestamp).total_seconds()
|
||||
|
||||
timestamp = datetime.now(datetime.UTC)
|
||||
timestamp = datetime.now(timezone.utc)
|
||||
|
||||
# Pull transactions from mempool
|
||||
max_txs = self._config.max_txs_per_block
|
||||
|
||||
@@ -2,12 +2,12 @@ import logging
|
||||
import sys
|
||||
from logging.handlers import RotatingFileHandler
|
||||
import json
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
|
||||
class JsonFormatter(logging.Formatter):
|
||||
def format(self, record):
|
||||
log_record = {
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat() + "Z",
|
||||
"timestamp": datetime.now(timezone.utc).isoformat() + "Z",
|
||||
"level": record.levelname,
|
||||
"logger": record.name,
|
||||
"message": record.getMessage()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
import re
|
||||
from typing import List, Optional
|
||||
|
||||
@@ -33,7 +33,7 @@ class Block(SQLModel, table=True):
|
||||
hash: str = Field(index=True, unique=True)
|
||||
parent_hash: str
|
||||
proposer: str
|
||||
timestamp: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
timestamp: datetime = Field(default_factory=datetime.now(timezone.utc), index=True)
|
||||
tx_count: int = 0
|
||||
state_root: Optional[str] = None
|
||||
block_metadata: Optional[str] = Field(default=None)
|
||||
@@ -89,7 +89,7 @@ class Transaction(SQLModel, table=True):
|
||||
default_factory=dict,
|
||||
sa_column=Column(JSON, nullable=False),
|
||||
)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(timezone.utc), index=True)
|
||||
|
||||
# New fields added to schema
|
||||
nonce: int = Field(default=0)
|
||||
@@ -140,7 +140,7 @@ class Receipt(SQLModel, table=True):
|
||||
sa_column=Column(JSON, nullable=False),
|
||||
)
|
||||
minted_amount: Optional[int] = None
|
||||
recorded_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
recorded_at: datetime = Field(default_factory=datetime.now(timezone.utc), index=True)
|
||||
status: str = Field(default="pending", index=True) # pending, claimed, invalid
|
||||
claimed_at: Optional[datetime] = None
|
||||
claimed_by: Optional[str] = None
|
||||
@@ -168,7 +168,7 @@ class Account(SQLModel, table=True):
|
||||
address: str = Field(primary_key=True)
|
||||
balance: int = 0
|
||||
nonce: int = 0
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(timezone.utc))
|
||||
|
||||
class Escrow(SQLModel, table=True):
|
||||
__tablename__ = "escrow"
|
||||
@@ -177,5 +177,5 @@ class Escrow(SQLModel, table=True):
|
||||
buyer: str = Field(foreign_key="account.address")
|
||||
provider: str = Field(foreign_key="account.address")
|
||||
amount: int
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=datetime.now(timezone.utc))
|
||||
released_at: Optional[datetime] = None
|
||||
|
||||
@@ -3,7 +3,7 @@ AI Agent Domain Models for Verifiable AI Agent Orchestration
|
||||
Implements SQLModel definitions for agent workflows, steps, and execution tracking
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -68,8 +68,8 @@ class AIAgentWorkflow(SQLModel, table=True):
|
||||
is_public: bool = Field(default=False)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class AgentStep(SQLModel, table=True):
|
||||
@@ -102,8 +102,8 @@ class AgentStep(SQLModel, table=True):
|
||||
depends_on: str = Field(default="") # JSON string of step IDs
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class AgentExecution(SQLModel, table=True):
|
||||
@@ -141,8 +141,8 @@ class AgentExecution(SQLModel, table=True):
|
||||
completed_steps: int = Field(default=0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class AgentStepExecution(SQLModel, table=True):
|
||||
@@ -180,8 +180,8 @@ class AgentStepExecution(SQLModel, table=True):
|
||||
completed_at: datetime | None = Field(default=None)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class AgentMarketplace(SQLModel, table=True):
|
||||
@@ -219,8 +219,8 @@ class AgentMarketplace(SQLModel, table=True):
|
||||
last_execution_at: datetime | None = Field(default=None)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
# Request/Response Models for API
|
||||
|
||||
@@ -3,7 +3,7 @@ Agent Identity Domain Models for Cross-Chain Agent Identity Management
|
||||
Implements SQLModel definitions for unified agent identity across multiple blockchains
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -80,8 +80,8 @@ class AgentIdentity(SQLModel, table=True):
|
||||
tags: list[str] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Indexes for performance
|
||||
__table_args__ = {
|
||||
@@ -122,8 +122,8 @@ class CrossChainMapping(SQLModel, table=True):
|
||||
transaction_count: int = Field(default=0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Unique constraint
|
||||
__table_args__ = {
|
||||
@@ -162,8 +162,8 @@ class IdentityVerification(SQLModel, table=True):
|
||||
verification_meta_data: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Indexes
|
||||
__table_args__ = {
|
||||
@@ -208,8 +208,8 @@ class AgentWallet(SQLModel, table=True):
|
||||
transaction_count: int = Field(default=0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Indexes
|
||||
__table_args__ = {
|
||||
|
||||
@@ -3,7 +3,7 @@ Advanced Agent Performance Domain Models
|
||||
Implements SQLModel definitions for meta-learning, resource management, and performance optimization
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -102,8 +102,8 @@ class AgentPerformanceProfile(SQLModel, table=True):
|
||||
percentile_rank: float | None = None
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_assessed: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -152,8 +152,8 @@ class MetaLearningModel(SQLModel, table=True):
|
||||
success_rate: float = Field(default=0.0, ge=0, le=1.0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
trained_at: datetime | None = None
|
||||
deployed_at: datetime | None = None
|
||||
|
||||
@@ -205,8 +205,8 @@ class ResourceAllocation(SQLModel, table=True):
|
||||
performance_improvement: float = Field(default=0.0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional data
|
||||
allocation_profile_meta_data: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
@@ -259,8 +259,8 @@ class PerformanceOptimization(SQLModel, table=True):
|
||||
rollback_available: bool = Field(default=True)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
completed_at: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -304,7 +304,7 @@ class AgentCapability(SQLModel, table=True):
|
||||
tool_proficiency: dict[str, float] = Field(default={}, sa_column=Column(JSON))
|
||||
|
||||
# Development history
|
||||
acquired_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
acquired_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_improved: datetime | None = None
|
||||
improvement_count: int = Field(default=0)
|
||||
|
||||
@@ -314,8 +314,8 @@ class AgentCapability(SQLModel, table=True):
|
||||
last_validated: datetime | None = None
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional data
|
||||
capability_profile_meta_data: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
@@ -365,8 +365,8 @@ class FusionModel(SQLModel, table=True):
|
||||
performance_stability: float = Field(default=0.0, ge=0, le=1.0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
trained_at: datetime | None = None
|
||||
deployed_at: datetime | None = None
|
||||
|
||||
@@ -420,8 +420,8 @@ class ReinforcementLearningConfig(SQLModel, table=True):
|
||||
deployment_performance: dict[str, float] = Field(default={}, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
trained_at: datetime | None = None
|
||||
deployed_at: datetime | None = None
|
||||
|
||||
@@ -476,8 +476,8 @@ class CreativeCapability(SQLModel, table=True):
|
||||
last_evaluation: datetime | None = None
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional data
|
||||
creative_profile_meta_data: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
|
||||
@@ -6,7 +6,7 @@ Domain models for agent portfolio management, trading strategies, and risk asses
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from enum import StrEnum
|
||||
|
||||
from sqlalchemy import JSON, Column
|
||||
@@ -47,8 +47,8 @@ class PortfolioStrategy(SQLModel, table=True):
|
||||
rebalance_frequency: int = Field(default=86400) # Rebalancing frequency in seconds
|
||||
volatility_threshold: float = Field(default=15.0) # Volatility threshold for rebalancing
|
||||
is_active: bool = Field(default=True, index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: portfolios: List["AgentPortfolio"] = Relationship(back_populates="strategy")
|
||||
@@ -68,9 +68,9 @@ class AgentPortfolio(SQLModel, table=True):
|
||||
risk_score: float = Field(default=0.0) # Risk score (0-100)
|
||||
risk_tolerance: float = Field(default=50.0) # Risk tolerance percentage
|
||||
is_active: bool = Field(default=True, index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_rebalance: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_rebalance: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: strategy: PortfolioStrategy = Relationship(back_populates="portfolios")
|
||||
@@ -93,8 +93,8 @@ class PortfolioAsset(SQLModel, table=True):
|
||||
current_allocation: float = Field(default=0.0) # Current allocation percentage
|
||||
average_cost: float = Field(default=0.0) # Average cost basis
|
||||
unrealized_pnl: float = Field(default=0.0) # Unrealized profit/loss
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: portfolio: AgentPortfolio = Relationship(back_populates="assets")
|
||||
@@ -116,7 +116,7 @@ class PortfolioTrade(SQLModel, table=True):
|
||||
status: TradeStatus = Field(default=TradeStatus.PENDING, index=True)
|
||||
transaction_hash: str | None = Field(default=None, index=True)
|
||||
executed_at: datetime | None = Field(default=None, index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
|
||||
# Relationships
|
||||
# DISABLED: portfolio: AgentPortfolio = Relationship(back_populates="trades")
|
||||
@@ -140,7 +140,7 @@ class RiskMetrics(SQLModel, table=True):
|
||||
risk_level: RiskLevel = Field(default=RiskLevel.LOW, index=True)
|
||||
overall_risk_score: float = Field(default=0.0) # Overall risk score (0-100)
|
||||
stress_test_results: dict[str, float] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: portfolio: AgentPortfolio = Relationship(back_populates="risk_metrics")
|
||||
@@ -159,7 +159,7 @@ class RebalanceHistory(SQLModel, table=True):
|
||||
trades_executed: int = Field(default=0)
|
||||
rebalance_cost: float = Field(default=0.0) # Cost of rebalancing
|
||||
execution_time_ms: int = Field(default=0) # Execution time in milliseconds
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
|
||||
|
||||
class PerformanceMetrics(SQLModel, table=True):
|
||||
@@ -184,9 +184,9 @@ class PerformanceMetrics(SQLModel, table=True):
|
||||
beta: float = Field(default=0.0) # Beta vs benchmark
|
||||
tracking_error: float = Field(default=0.0) # Tracking error
|
||||
information_ratio: float = Field(default=0.0) # Information ratio
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
period_start: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
period_end: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
period_start: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
period_end: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class PortfolioAlert(SQLModel, table=True):
|
||||
@@ -202,7 +202,7 @@ class PortfolioAlert(SQLModel, table=True):
|
||||
meta_data: dict[str, str] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
is_acknowledged: bool = Field(default=False, index=True)
|
||||
acknowledged_at: datetime | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
resolved_at: datetime | None = Field(default=None)
|
||||
|
||||
|
||||
@@ -223,8 +223,8 @@ class StrategySignal(SQLModel, table=True):
|
||||
meta_data: dict[str, str] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
is_executed: bool = Field(default=False, index=True)
|
||||
executed_at: datetime | None = Field(default=None)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(hours=24))
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc) + timedelta(hours=24))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
|
||||
|
||||
class PortfolioSnapshot(SQLModel, table=True):
|
||||
@@ -243,7 +243,7 @@ class PortfolioSnapshot(SQLModel, table=True):
|
||||
geographic_allocation: dict[str, float] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
risk_metrics: dict[str, float] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
performance_metrics: dict[str, float] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class TradingRule(SQLModel, table=True):
|
||||
@@ -258,8 +258,8 @@ class TradingRule(SQLModel, table=True):
|
||||
parameters: dict[str, str] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
is_active: bool = Field(default=True, index=True)
|
||||
priority: int = Field(default=0) # Rule priority (higher = more important)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class MarketCondition(SQLModel, table=True):
|
||||
@@ -277,5 +277,5 @@ class MarketCondition(SQLModel, table=True):
|
||||
trend_strength: float = Field(default=0.0) # Trend strength
|
||||
support_level: float = Field(default=0.0) # Support level
|
||||
resistance_level: float = Field(default=0.0) # Resistance level
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(hours=24))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc) + timedelta(hours=24))
|
||||
|
||||
@@ -6,7 +6,7 @@ Domain models for automated market making, liquidity pools, and swap transaction
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from enum import StrEnum
|
||||
|
||||
from sqlalchemy import JSON, Column
|
||||
@@ -59,8 +59,8 @@ class LiquidityPool(SQLModel, table=True):
|
||||
is_active: bool = Field(default=True, index=True)
|
||||
status: PoolStatus = Field(default=PoolStatus.ACTIVE, index=True)
|
||||
created_by: str = Field(index=True) # Creator address
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_trade_time: datetime | None = Field(default=None)
|
||||
|
||||
# Relationships
|
||||
@@ -88,8 +88,8 @@ class LiquidityPosition(SQLModel, table=True):
|
||||
fees_earned: float = Field(default=0.0) # Fees earned
|
||||
impermanent_loss: float = Field(default=0.0) # Impermanent loss
|
||||
status: LiquidityPositionStatus = Field(default=LiquidityPositionStatus.ACTIVE, index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_deposit: datetime | None = Field(default=None)
|
||||
last_withdrawal: datetime | None = Field(default=None)
|
||||
|
||||
@@ -121,8 +121,8 @@ class SwapTransaction(SQLModel, table=True):
|
||||
gas_used: int | None = Field(default=None)
|
||||
gas_price: float | None = Field(default=None)
|
||||
executed_at: datetime | None = Field(default=None, index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
deadline: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(minutes=20))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
deadline: datetime = Field(default_factory=lambda: datetime.now(timezone.utc) + timedelta(minutes=20))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: pool: LiquidityPool = Relationship(back_populates="swaps")
|
||||
@@ -149,7 +149,7 @@ class PoolMetrics(SQLModel, table=True):
|
||||
impermanent_loss_24h: float = Field(default=0.0) # 24h impermanent loss
|
||||
liquidity_provider_count: int = Field(default=0) # Number of liquidity providers
|
||||
top_lps: dict[str, float] = Field(default_factory=dict, sa_column=Column(JSON)) # Top LPs by share
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: pool: LiquidityPool = Relationship(back_populates="metrics")
|
||||
@@ -168,10 +168,10 @@ class FeeStructure(SQLModel, table=True):
|
||||
volume_adjustment: float = Field(default=0.0) # Volume-based adjustment
|
||||
liquidity_adjustment: float = Field(default=0.0) # Liquidity-based adjustment
|
||||
time_adjustment: float = Field(default=0.0) # Time-based adjustment
|
||||
adjusted_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(hours=24))
|
||||
adjusted_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc) + timedelta(hours=24))
|
||||
adjustment_reason: str = Field(default="") # Reason for adjustment
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class IncentiveProgram(SQLModel, table=True):
|
||||
@@ -192,10 +192,10 @@ class IncentiveProgram(SQLModel, table=True):
|
||||
maximum_liquidity: float = Field(default=0.0) # Maximum liquidity cap (0 = no cap)
|
||||
vesting_period_days: int = Field(default=0) # Vesting period (0 = no vesting)
|
||||
is_active: bool = Field(default=True, index=True)
|
||||
start_time: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
end_time: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(days=30))
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
start_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
end_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc) + timedelta(days=30))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: pool: LiquidityPool = Relationship(back_populates="incentives")
|
||||
@@ -220,7 +220,7 @@ class LiquidityReward(SQLModel, table=True):
|
||||
claim_transaction_hash: str | None = Field(default=None)
|
||||
vesting_start: datetime | None = Field(default=None)
|
||||
vesting_end: datetime | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
|
||||
# Relationships
|
||||
# DISABLED: program: IncentiveProgram = Relationship(back_populates="rewards")
|
||||
@@ -243,7 +243,7 @@ class FeeClaim(SQLModel, table=True):
|
||||
is_claimed: bool = Field(default=False, index=True)
|
||||
claimed_at: datetime | None = Field(default=None)
|
||||
claim_transaction_hash: str | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
|
||||
# Relationships
|
||||
# DISABLED: position: LiquidityPosition = Relationship(back_populates="fee_claims")
|
||||
@@ -260,8 +260,8 @@ class PoolConfiguration(SQLModel, table=True):
|
||||
config_value: str = Field(default="")
|
||||
config_type: str = Field(default="string") # string, number, boolean, json
|
||||
is_active: bool = Field(default=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class PoolAlert(SQLModel, table=True):
|
||||
@@ -283,8 +283,8 @@ class PoolAlert(SQLModel, table=True):
|
||||
acknowledged_at: datetime | None = Field(default=None)
|
||||
is_resolved: bool = Field(default=False, index=True)
|
||||
resolved_at: datetime | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(hours=24))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc) + timedelta(hours=24))
|
||||
|
||||
|
||||
class PoolSnapshot(SQLModel, table=True):
|
||||
@@ -310,7 +310,7 @@ class PoolSnapshot(SQLModel, table=True):
|
||||
average_slippage: float = Field(default=0.0)
|
||||
average_price_impact: float = Field(default=0.0)
|
||||
impermanent_loss: float = Field(default=0.0)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class ArbitrageOpportunity(SQLModel, table=True):
|
||||
@@ -335,5 +335,5 @@ class ArbitrageOpportunity(SQLModel, table=True):
|
||||
executed_at: datetime | None = Field(default=None)
|
||||
execution_tx_hash: str | None = Field(default=None)
|
||||
actual_profit: float | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(minutes=5))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc) + timedelta(minutes=5))
|
||||
|
||||
@@ -3,7 +3,7 @@ Marketplace Analytics Domain Models
|
||||
Implements SQLModel definitions for analytics, insights, and reporting
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -87,7 +87,7 @@ class MarketMetric(SQLModel, table=True):
|
||||
metric_meta_data: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
recorded_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
recorded_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
period_start: datetime
|
||||
period_end: datetime
|
||||
|
||||
@@ -134,8 +134,8 @@ class MarketInsight(SQLModel, table=True):
|
||||
resolved_at: datetime | None = None
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -184,9 +184,9 @@ class AnalyticsReport(SQLModel, table=True):
|
||||
recipients: list[str] = Field(default=[], sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
generated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
generated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
delivered_at: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -230,8 +230,8 @@ class DashboardConfig(SQLModel, table=True):
|
||||
last_modified_by: str | None = None
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_viewed_at: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -281,8 +281,8 @@ class DataCollectionJob(SQLModel, table=True):
|
||||
cpu_usage: float = Field(default=0.0) # percentage
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional data
|
||||
job_metric_meta_data: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
@@ -331,8 +331,8 @@ class AlertRule(SQLModel, table=True):
|
||||
trigger_count: int = Field(default=0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional data
|
||||
rule_metric_meta_data: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
@@ -383,8 +383,8 @@ class AnalyticsAlert(SQLModel, table=True):
|
||||
delivery_status: dict[str, str] = Field(default={}, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -434,8 +434,8 @@ class UserPreference(SQLModel, table=True):
|
||||
anonymous_usage: bool = Field(default=False)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_login: datetime | None = None
|
||||
|
||||
# Additional preferences
|
||||
|
||||
@@ -6,7 +6,7 @@ Domain models for managing trustless cross-chain atomic swaps between agents.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -60,5 +60,5 @@ class AtomicSwapOrder(SQLModel, table=True):
|
||||
|
||||
status: SwapStatus = Field(default=SwapStatus.CREATED, index=True)
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
@@ -4,7 +4,7 @@ Database models for AI agent bounty system with ZK-proof verification
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
@@ -70,7 +70,7 @@ class Bounty(SQLModel, table=True):
|
||||
|
||||
# Timing
|
||||
deadline: datetime = Field(index=True)
|
||||
creation_time: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
creation_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Limits
|
||||
max_submissions: int = Field(default=100)
|
||||
@@ -137,7 +137,7 @@ class BountySubmission(SQLModel, table=True):
|
||||
dispute_resolved: bool = Field(default=False)
|
||||
|
||||
# Timing
|
||||
submission_time: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
submission_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Metadata
|
||||
submission_data: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
@@ -168,13 +168,13 @@ class AgentStake(SQLModel, table=True):
|
||||
# Stake details
|
||||
amount: float = Field(index=True)
|
||||
lock_period: int = Field(default=30) # days
|
||||
start_time: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
start_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
end_time: datetime
|
||||
|
||||
# Status and rewards
|
||||
status: StakeStatus = Field(default=StakeStatus.ACTIVE)
|
||||
accumulated_rewards: float = Field(default=0.0)
|
||||
last_reward_time: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_reward_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# APY and performance
|
||||
current_apy: float = Field(default=5.0) # percentage
|
||||
@@ -226,7 +226,7 @@ class AgentMetrics(SQLModel, table=True):
|
||||
reputation_score: float = Field(default=0.0)
|
||||
|
||||
# Timing
|
||||
last_update_time: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_update_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
first_submission_time: datetime | None = Field(default=None)
|
||||
|
||||
# Additional metrics
|
||||
@@ -271,7 +271,7 @@ class StakingPool(SQLModel, table=True):
|
||||
active_stakers: list[str] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
|
||||
# Distribution
|
||||
last_distribution_time: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_distribution_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
distribution_frequency: int = Field(default=1) # days
|
||||
|
||||
# Pool configuration
|
||||
@@ -309,7 +309,7 @@ class BountyIntegration(SQLModel, table=True):
|
||||
|
||||
# Status and timing
|
||||
status: BountyStatus = Field(default=BountyStatus.CREATED)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
processed_at: datetime | None = Field(default=None)
|
||||
|
||||
# Processing information
|
||||
@@ -393,7 +393,7 @@ class EcosystemMetrics(SQLModel, table=True):
|
||||
metrics_id: str = Field(primary_key=True, default_factory=lambda: f"eco_{uuid.uuid4().hex[:8]}")
|
||||
|
||||
# Time period
|
||||
timestamp: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
period_type: str = Field(default="hourly") # hourly, daily, weekly
|
||||
|
||||
# Developer metrics
|
||||
|
||||
@@ -3,7 +3,7 @@ Agent Certification and Partnership Domain Models
|
||||
Implements SQLModel definitions for certification, verification, and partnership programs
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -80,7 +80,7 @@ class AgentCertification(SQLModel, table=True):
|
||||
|
||||
# Issuance information
|
||||
issued_by: str = Field(index=True) # Who issued the certification
|
||||
issued_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
issued_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime | None = None
|
||||
verification_hash: str = Field(max_length=64) # Blockchain verification hash
|
||||
|
||||
@@ -142,9 +142,9 @@ class CertificationRequirement(SQLModel, table=True):
|
||||
weight: float = Field(default=1.0) # Importance weight
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
effective_date: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
effective_date: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expiry_date: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -167,7 +167,7 @@ class VerificationRecord(SQLModel, table=True):
|
||||
|
||||
# Request information
|
||||
requested_by: str = Field(index=True)
|
||||
requested_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
requested_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
priority: str = Field(default="normal") # low, normal, high, urgent
|
||||
|
||||
# Verification process
|
||||
@@ -242,8 +242,8 @@ class PartnershipProgram(SQLModel, table=True):
|
||||
current_participants: int = Field(default=0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
launched_at: datetime | None = None
|
||||
expires_at: datetime | None = None
|
||||
|
||||
@@ -268,7 +268,7 @@ class AgentPartnership(SQLModel, table=True):
|
||||
current_tier: str = Field(default="basic")
|
||||
|
||||
# Application and approval
|
||||
applied_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
applied_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
approved_by: str | None = None
|
||||
approved_at: datetime | None = None
|
||||
rejection_reasons: list[str] = Field(default=[], sa_column=Column(JSON))
|
||||
@@ -294,8 +294,8 @@ class AgentPartnership(SQLModel, table=True):
|
||||
agreement_expires_at: datetime | None = None
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_activity: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -339,9 +339,9 @@ class AchievementBadge(SQLModel, table=True):
|
||||
current_awards: int = Field(default=0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
available_from: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
available_from: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
available_until: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -363,7 +363,7 @@ class AgentBadge(SQLModel, table=True):
|
||||
|
||||
# Award details
|
||||
awarded_by: str = Field(index=True) # System or user who awarded the badge
|
||||
awarded_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
awarded_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
award_reason: str = Field(default="", max_length=500)
|
||||
|
||||
# Achievement context
|
||||
@@ -391,8 +391,8 @@ class AgentBadge(SQLModel, table=True):
|
||||
congratulation_count: int = Field(default=0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_viewed_at: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -416,7 +416,7 @@ class CertificationAudit(SQLModel, table=True):
|
||||
|
||||
# Audit scheduling
|
||||
scheduled_by: str = Field(index=True)
|
||||
scheduled_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
scheduled_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
started_at: datetime | None = None
|
||||
completed_at: datetime | None = None
|
||||
|
||||
@@ -449,8 +449,8 @@ class CertificationAudit(SQLModel, table=True):
|
||||
evidence_documents: list[str] = Field(default=[], sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional data
|
||||
audit_cert_meta_data: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
|
||||
@@ -4,7 +4,7 @@ Database models for OpenClaw agent community, third-party solutions, and innovat
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
@@ -61,8 +61,8 @@ class DeveloperProfile(SQLModel, table=True):
|
||||
github_handle: str | None = None
|
||||
website: str | None = None
|
||||
|
||||
joined_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_active: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
joined_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_active: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class AgentSolution(SQLModel, table=True):
|
||||
@@ -91,8 +91,8 @@ class AgentSolution(SQLModel, table=True):
|
||||
|
||||
solution_meta_data: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
published_at: datetime | None = None
|
||||
|
||||
|
||||
@@ -116,7 +116,7 @@ class InnovationLab(SQLModel, table=True):
|
||||
milestones: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
publications: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
target_completion: datetime | None = None
|
||||
|
||||
|
||||
@@ -139,8 +139,8 @@ class CommunityPost(SQLModel, table=True):
|
||||
|
||||
parent_post_id: str | None = Field(default=None, foreign_key="community_posts.post_id")
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class Hackathon(SQLModel, table=True):
|
||||
@@ -165,4 +165,4 @@ class Hackathon(SQLModel, table=True):
|
||||
registration_end: datetime
|
||||
event_start: datetime
|
||||
event_end: datetime
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
@@ -6,7 +6,7 @@ Domain models for cross-chain asset transfers, bridge requests, and validator ma
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from enum import StrEnum
|
||||
|
||||
from sqlalchemy import JSON, Column
|
||||
@@ -75,12 +75,12 @@ class BridgeRequest(SQLModel, table=True):
|
||||
required_confirmations: int = Field(default=3) # Required confirmations
|
||||
dispute_reason: str | None = Field(default=None)
|
||||
resolution_action: str | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
confirmed_at: datetime | None = Field(default=None)
|
||||
completed_at: datetime | None = Field(default=None)
|
||||
resolved_at: datetime | None = Field(default=None)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(hours=24))
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc) + timedelta(hours=24))
|
||||
|
||||
# Relationships
|
||||
# transactions: List["BridgeTransaction"] = Relationship(back_populates="bridge_request")
|
||||
@@ -107,8 +107,8 @@ class SupportedToken(SQLModel, table=True):
|
||||
original_token: str | None = Field(default=None) # Original token address for wrapped tokens
|
||||
supported_chains: list[int] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
bridge_contracts: dict[int, str] = Field(default_factory=dict, sa_column=Column(JSON)) # Chain ID -> Contract address
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class ChainConfig(SQLModel, table=True):
|
||||
@@ -135,8 +135,8 @@ class ChainConfig(SQLModel, table=True):
|
||||
is_testnet: bool = Field(default=False)
|
||||
requires_validator: bool = Field(default=True) # Whether validator confirmation is required
|
||||
validator_threshold: float = Field(default=0.67) # Validator threshold percentage
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class Validator(SQLModel, table=True):
|
||||
@@ -162,8 +162,8 @@ class Validator(SQLModel, table=True):
|
||||
is_active: bool = Field(default=True, index=True)
|
||||
supported_chains: list[int] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
val_meta_data: dict[str, str] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# transactions: List["BridgeTransaction"] = Relationship(back_populates="validator")
|
||||
@@ -190,7 +190,7 @@ class BridgeTransaction(SQLModel, table=True):
|
||||
is_successful: bool = Field(default=False)
|
||||
error_message: str | None = Field(default=None)
|
||||
retry_count: int = Field(default=0)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
confirmed_at: datetime | None = Field(default=None)
|
||||
completed_at: datetime | None = Field(default=None)
|
||||
|
||||
@@ -219,8 +219,8 @@ class BridgeDispute(SQLModel, table=True):
|
||||
investigator_address: str | None = Field(default=None)
|
||||
investigation_notes: str | None = Field(default=None)
|
||||
is_resolved: bool = Field(default=False, index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
resolved_at: datetime | None = Field(default=None)
|
||||
|
||||
# Relationships
|
||||
@@ -241,8 +241,8 @@ class MerkleProof(SQLModel, table=True):
|
||||
tree_depth: int = Field(default=0) # Tree depth
|
||||
is_valid: bool = Field(default=False)
|
||||
verified_at: datetime | None = Field(default=None)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(hours=24))
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc) + timedelta(hours=24))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class BridgeStatistics(SQLModel, table=True):
|
||||
@@ -264,7 +264,7 @@ class BridgeStatistics(SQLModel, table=True):
|
||||
unique_users: int = Field(default=0) # Unique users for the day
|
||||
peak_hour_volume: float = Field(default=0.0) # Peak hour volume
|
||||
peak_hour_transactions: int = Field(default=0) # Peak hour transactions
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class BridgeAlert(SQLModel, table=True):
|
||||
@@ -290,8 +290,8 @@ class BridgeAlert(SQLModel, table=True):
|
||||
is_resolved: bool = Field(default=False, index=True)
|
||||
resolved_at: datetime | None = Field(default=None)
|
||||
resolution_notes: str | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(datetime.UTC) + timedelta(hours=24))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc) + timedelta(hours=24))
|
||||
|
||||
|
||||
class BridgeConfiguration(SQLModel, table=True):
|
||||
@@ -305,8 +305,8 @@ class BridgeConfiguration(SQLModel, table=True):
|
||||
config_type: str = Field(default="string") # string, number, boolean, json
|
||||
description: str = Field(default="")
|
||||
is_active: bool = Field(default=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class LiquidityPool(SQLModel, table=True):
|
||||
@@ -323,9 +323,9 @@ class LiquidityPool(SQLModel, table=True):
|
||||
utilized_liquidity: float = Field(default=0.0) # Utilized liquidity
|
||||
utilization_rate: float = Field(default=0.0) # Utilization rate
|
||||
interest_rate: float = Field(default=0.0) # Interest rate
|
||||
last_updated: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_updated: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
is_active: bool = Field(default=True, index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class BridgeSnapshot(SQLModel, table=True):
|
||||
@@ -347,7 +347,7 @@ class BridgeSnapshot(SQLModel, table=True):
|
||||
bridge_utilization: float = Field(default=0.0)
|
||||
top_tokens: dict[str, float] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
top_chains: dict[str, int] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class ValidatorReward(SQLModel, table=True):
|
||||
@@ -365,4 +365,4 @@ class ValidatorReward(SQLModel, table=True):
|
||||
is_claimed: bool = Field(default=False, index=True)
|
||||
claimed_at: datetime | None = Field(default=None)
|
||||
claim_transaction_hash: str | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
|
||||
@@ -3,7 +3,7 @@ Cross-Chain Reputation Extensions
|
||||
Extends the existing reputation system with cross-chain capabilities
|
||||
"""
|
||||
|
||||
from datetime import date, datetime
|
||||
from datetime import date, datetime, timezone
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -38,8 +38,8 @@ class CrossChainReputationConfig(SQLModel, table=True):
|
||||
configuration_data: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class CrossChainReputationAggregation(SQLModel, table=True):
|
||||
@@ -72,8 +72,8 @@ class CrossChainReputationAggregation(SQLModel, table=True):
|
||||
verification_details: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
last_updated: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_updated: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Indexes
|
||||
__table_args__ = {
|
||||
@@ -111,7 +111,7 @@ class CrossChainReputationEvent(SQLModel, table=True):
|
||||
verified: bool = Field(default=False)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
processed_at: datetime | None = None
|
||||
|
||||
# Indexes
|
||||
@@ -153,8 +153,8 @@ class ReputationMetrics(SQLModel, table=True):
|
||||
chain_diversity_score: float = Field(default=0.0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
# Request/Response Models for Cross-Chain API
|
||||
|
||||
@@ -6,7 +6,7 @@ Domain models for managing multi-jurisdictional DAOs, regional councils, and glo
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -46,8 +46,8 @@ class DAOMember(SQLModel, table=True):
|
||||
is_council_member: bool = Field(default=False)
|
||||
council_region: str | None = Field(default=None, index=True)
|
||||
|
||||
joined_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_active: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
joined_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_active: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: votes: List["Vote"] = Relationship(back_populates="member")
|
||||
@@ -76,10 +76,10 @@ class DAOProposal(SQLModel, table=True):
|
||||
|
||||
execution_payload: dict[str, str] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
start_time: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
end_time: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
start_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
end_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: votes: List["Vote"] = Relationship(back_populates="proposal")
|
||||
@@ -98,7 +98,7 @@ class Vote(SQLModel, table=True):
|
||||
weight: float = Field()
|
||||
|
||||
tx_hash: str | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: proposal: DAOProposal = Relationship(back_populates="votes")
|
||||
@@ -120,4 +120,4 @@ class TreasuryAllocation(SQLModel, table=True):
|
||||
purpose: str = Field()
|
||||
|
||||
tx_hash: str | None = Field(default=None)
|
||||
executed_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
executed_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
@@ -6,7 +6,7 @@ Domain models for managing agent memory and knowledge graphs on IPFS/Filecoin.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -55,5 +55,5 @@ class AgentMemoryNode(SQLModel, table=True):
|
||||
# Blockchain Anchoring
|
||||
anchor_tx_hash: str | None = Field(default=None)
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
@@ -6,7 +6,7 @@ Domain models for managing the developer ecosystem, bounties, certifications, an
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -45,8 +45,8 @@ class DeveloperProfile(SQLModel, table=True):
|
||||
skills: list[str] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
|
||||
is_active: bool = Field(default=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: certifications: List["DeveloperCertification"] = Relationship(back_populates="developer")
|
||||
@@ -65,7 +65,7 @@ class DeveloperCertification(SQLModel, table=True):
|
||||
level: CertificationLevel = Field(default=CertificationLevel.BEGINNER)
|
||||
|
||||
issued_by: str = Field() # Could be an agent or a DAO entity
|
||||
issued_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
issued_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime | None = Field(default=None)
|
||||
|
||||
ipfs_credential_cid: str | None = Field(default=None) # Proof of certification
|
||||
@@ -90,7 +90,7 @@ class RegionalHub(SQLModel, table=True):
|
||||
budget_allocation: float = Field(default=0.0)
|
||||
spent_budget: float = Field(default=0.0)
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class BountyTask(SQLModel, table=True):
|
||||
@@ -114,8 +114,8 @@ class BountyTask(SQLModel, table=True):
|
||||
assigned_developer_id: str | None = Field(foreign_key="developer_profile.id", default=None)
|
||||
|
||||
deadline: datetime | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: submissions: List["BountySubmission"] = Relationship(back_populates="bounty")
|
||||
@@ -139,7 +139,7 @@ class BountySubmission(SQLModel, table=True):
|
||||
|
||||
tx_hash_reward: str | None = Field(default=None) # Hash of the reward payout transaction
|
||||
|
||||
submitted_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
submitted_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
reviewed_at: datetime | None = Field(default=None)
|
||||
|
||||
# Relationships
|
||||
|
||||
@@ -6,7 +6,7 @@ Domain models for managing cross-agent knowledge sharing and collaborative model
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -55,8 +55,8 @@ class FederatedLearningSession(SQLModel, table=True):
|
||||
|
||||
global_model_cid: str | None = Field(default=None) # Final aggregated model
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: participants: List["TrainingParticipant"] = Relationship(back_populates="session")
|
||||
@@ -79,8 +79,8 @@ class TrainingParticipant(SQLModel, table=True):
|
||||
reputation_score_at_join: float = Field(default=0.0)
|
||||
earned_reward: float = Field(default=0.0)
|
||||
|
||||
joined_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
joined_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: session: FederatedLearningSession = Relationship(back_populates="participants")
|
||||
@@ -102,7 +102,7 @@ class TrainingRound(SQLModel, table=True):
|
||||
|
||||
metrics: dict[str, float] = Field(default_factory=dict, sa_column=Column(JSON)) # e.g. loss, accuracy
|
||||
|
||||
started_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
started_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
completed_at: datetime | None = Field(default=None)
|
||||
|
||||
# Relationships
|
||||
@@ -125,7 +125,7 @@ class LocalModelUpdate(SQLModel, table=True):
|
||||
is_aggregated: bool = Field(default=False)
|
||||
rejected_reason: str | None = Field(default=None) # e.g. "outlier", "failed zk verification"
|
||||
|
||||
submitted_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
submitted_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: round: TrainingRound = Relationship(back_populates="updates")
|
||||
|
||||
@@ -5,7 +5,7 @@ Domain models for global marketplace operations, multi-region support, and cross
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -71,8 +71,8 @@ class MarketplaceRegion(SQLModel, table=True):
|
||||
error_rate: float = Field(default=0.0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Indexes
|
||||
__table_args__ = {
|
||||
@@ -104,8 +104,8 @@ class GlobalMarketplaceConfig(SQLModel, table=True):
|
||||
allowed_values: list[str] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_modified_by: str | None = Field(default=None)
|
||||
|
||||
# Indexes
|
||||
@@ -153,8 +153,8 @@ class GlobalMarketplaceOffer(SQLModel, table=True):
|
||||
cross_chain_pricing: dict[int, float] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime | None = Field(default=None)
|
||||
|
||||
# Indexes
|
||||
@@ -201,8 +201,8 @@ class GlobalMarketplaceTransaction(SQLModel, table=True):
|
||||
delivery_status: str = Field(default="pending") # pending, delivered, failed
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
confirmed_at: datetime | None = Field(default=None)
|
||||
completed_at: datetime | None = Field(default=None)
|
||||
|
||||
@@ -266,8 +266,8 @@ class GlobalMarketplaceAnalytics(SQLModel, table=True):
|
||||
analytics_data: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Indexes
|
||||
__table_args__ = {
|
||||
@@ -313,9 +313,9 @@ class GlobalMarketplaceGovernance(SQLModel, table=True):
|
||||
version: int = Field(default=1)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
effective_from: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
effective_from: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime | None = Field(default=None)
|
||||
|
||||
# Indexes
|
||||
|
||||
@@ -4,7 +4,7 @@ Database models for OpenClaw DAO, voting, proposals, and governance analytics
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
@@ -51,7 +51,7 @@ class GovernanceProfile(SQLModel, table=True):
|
||||
|
||||
delegate_to: str | None = Field(default=None) # Profile ID they delegate their vote to
|
||||
|
||||
joined_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
joined_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_voted_at: datetime | None = None
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ class Proposal(SQLModel, table=True):
|
||||
snapshot_block: int | None = Field(default=None)
|
||||
snapshot_timestamp: datetime | None = Field(default=None)
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
voting_starts: datetime
|
||||
voting_ends: datetime
|
||||
executed_at: datetime | None = None
|
||||
@@ -102,7 +102,7 @@ class Vote(SQLModel, table=True):
|
||||
power_at_snapshot: float = Field(default=0.0)
|
||||
delegated_power_at_snapshot: float = Field(default=0.0)
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class DaoTreasury(SQLModel, table=True):
|
||||
@@ -117,7 +117,7 @@ class DaoTreasury(SQLModel, table=True):
|
||||
|
||||
asset_breakdown: dict[str, float] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
last_updated: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_updated: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class TransparencyReport(SQLModel, table=True):
|
||||
@@ -138,4 +138,4 @@ class TransparencyReport(SQLModel, table=True):
|
||||
|
||||
metrics: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
generated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
generated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -36,7 +36,7 @@ class GPURegistry(SQLModel, table=True):
|
||||
capabilities: list = Field(default_factory=list, sa_column=Column(JSON, nullable=False))
|
||||
average_rating: float = Field(default=0.0)
|
||||
total_reviews: int = Field(default=0)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), nullable=False, index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), nullable=False, index=True)
|
||||
|
||||
|
||||
class ConsumerGPUProfile(SQLModel, table=True):
|
||||
@@ -84,8 +84,8 @@ class ConsumerGPUProfile(SQLModel, table=True):
|
||||
edge_premium_multiplier: float = Field(default=1.0)
|
||||
availability_score: float = Field(default=1.0)
|
||||
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class EdgeGPUMetrics(SQLModel, table=True):
|
||||
@@ -119,7 +119,7 @@ class EdgeGPUMetrics(SQLModel, table=True):
|
||||
isp: str | None = Field(default=None)
|
||||
connection_type: str | None = Field(default=None)
|
||||
|
||||
timestamp: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
|
||||
|
||||
class GPUBooking(SQLModel, table=True):
|
||||
@@ -135,9 +135,9 @@ class GPUBooking(SQLModel, table=True):
|
||||
duration_hours: float = Field(default=0.0)
|
||||
total_cost: float = Field(default=0.0)
|
||||
status: str = Field(default="active", index=True) # active, completed, cancelled
|
||||
start_time: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
start_time: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
end_time: datetime | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), nullable=False)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), nullable=False)
|
||||
|
||||
|
||||
class GPUReview(SQLModel, table=True):
|
||||
@@ -151,4 +151,4 @@ class GPUReview(SQLModel, table=True):
|
||||
user_id: str = Field(default="")
|
||||
rating: int = Field(ge=1, le=5)
|
||||
comment: str = Field(default="")
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), nullable=False, index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), nullable=False, index=True)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -20,8 +20,8 @@ class Job(SQLModel, table=True):
|
||||
constraints: Dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON, nullable=False))
|
||||
|
||||
ttl_seconds: int = Field(default=900)
|
||||
requested_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
expires_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
requested_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
assigned_miner_id: str | None = Field(default=None, index=True)
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import JSON, Column
|
||||
@@ -15,4 +15,4 @@ class JobReceipt(SQLModel, table=True):
|
||||
job_id: str = Field(index=True, foreign_key="job.id")
|
||||
receipt_id: str = Field(index=True)
|
||||
payload: dict = Field(sa_column=Column(JSON, nullable=False))
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import JSON, Column
|
||||
@@ -17,7 +17,7 @@ class MarketplaceOffer(SQLModel, table=True):
|
||||
price: float = Field(default=0.0, nullable=False)
|
||||
sla: str = Field(default="")
|
||||
status: str = Field(default="open", max_length=20)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), nullable=False, index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), nullable=False, index=True)
|
||||
attributes: dict = Field(default_factory=dict, sa_column=Column(JSON, nullable=False))
|
||||
# GPU-specific fields
|
||||
gpu_model: str | None = Field(default=None, index=True)
|
||||
@@ -38,4 +38,4 @@ class MarketplaceBid(SQLModel, table=True):
|
||||
price: float = Field(default=0.0, nullable=False)
|
||||
notes: str | None = Field(default=None)
|
||||
status: str = Field(default="pending", nullable=False)
|
||||
submitted_at: datetime = Field(default_factory=datetime.now(datetime.UTC), nullable=False, index=True)
|
||||
submitted_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), nullable=False, index=True)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict
|
||||
|
||||
from sqlalchemy import JSON, Column
|
||||
@@ -18,7 +18,7 @@ class Miner(SQLModel, table=True):
|
||||
status: str = Field(default="ONLINE", index=True)
|
||||
inflight: int = Field(default=0)
|
||||
extra_metadata: Dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON, nullable=False))
|
||||
last_heartbeat: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
last_heartbeat: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
session_token: str | None = None
|
||||
last_job_at: datetime | None = Field(default=None, index=True)
|
||||
jobs_completed: int = Field(default=0)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import JSON, Column, Numeric
|
||||
@@ -33,8 +33,8 @@ class JobPayment(SQLModel, table=True):
|
||||
refund_transaction_hash: str | None = Field(default=None, max_length=100)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
escrowed_at: datetime | None = None
|
||||
released_at: datetime | None = None
|
||||
refunded_at: datetime | None = None
|
||||
@@ -67,7 +67,7 @@ class PaymentEscrow(SQLModel, table=True):
|
||||
is_refunded: bool = Field(default=False)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
released_at: datetime | None = None
|
||||
refunded_at: datetime | None = None
|
||||
expires_at: datetime | None = None
|
||||
|
||||
@@ -5,7 +5,7 @@ SQLModel definitions for pricing history, strategies, and market metrics
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -92,8 +92,8 @@ class PricingHistory(SQLModel, table=True):
|
||||
recommendation_followed: bool | None = None
|
||||
|
||||
# Metadata
|
||||
timestamp: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional context
|
||||
competitor_prices: list[float] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
@@ -157,8 +157,8 @@ class ProviderPricingStrategy(SQLModel, table=True):
|
||||
strategy_effectiveness_score: float = Field(default=0.0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_applied: datetime | None = None
|
||||
expires_at: datetime | None = None
|
||||
|
||||
@@ -225,8 +225,8 @@ class MarketMetrics(SQLModel, table=True):
|
||||
completeness_score: float
|
||||
|
||||
# Timestamps
|
||||
timestamp: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional metrics
|
||||
custom_metrics: dict[str, float] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
@@ -278,7 +278,7 @@ class PriceForecast(SQLModel, table=True):
|
||||
market_conditions_at_forecast: dict[str, float] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
target_timestamp: datetime = Field(index=True) # When forecast is for
|
||||
evaluated_at: datetime | None = None # When forecast was evaluated
|
||||
|
||||
@@ -344,8 +344,8 @@ class PricingOptimization(SQLModel, table=True):
|
||||
recommendations: list[str] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
completed_at: datetime | None = None
|
||||
|
||||
# Audit trail
|
||||
@@ -406,9 +406,9 @@ class PricingAlert(SQLModel, table=True):
|
||||
customer_impact_estimate: str | None = None
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
first_seen: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_seen: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
first_seen: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_seen: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
acknowledged_at: datetime | None = None
|
||||
resolved_at: datetime | None = None
|
||||
|
||||
@@ -470,8 +470,8 @@ class PricingRule(SQLModel, table=True):
|
||||
business_impact: float | None = None
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime | None = None
|
||||
|
||||
# Audit trail
|
||||
@@ -534,8 +534,8 @@ class PricingAuditLog(SQLModel, table=True):
|
||||
ip_address: str | None = None
|
||||
|
||||
# Timestamps
|
||||
timestamp: datetime = Field(default_factory=datetime.now(datetime.UTC), index=True)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional metadata
|
||||
meta_data: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
@@ -4,7 +4,7 @@ Defines various pricing strategies and their configurations for dynamic pricing
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
@@ -92,7 +92,7 @@ class StrategyRule:
|
||||
action: str # Action to take when condition is met
|
||||
priority: StrategyPriority
|
||||
enabled: bool = True
|
||||
created_at: datetime = field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Rule execution tracking
|
||||
execution_count: int = 0
|
||||
@@ -124,8 +124,8 @@ class PricingStrategyConfig:
|
||||
regions: list[str] = field(default_factory=list)
|
||||
|
||||
# Performance tracking
|
||||
created_at: datetime = field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_applied: datetime | None = None
|
||||
|
||||
# Strategy effectiveness metrics
|
||||
@@ -515,7 +515,7 @@ class StrategyOptimizer:
|
||||
if strategy_id not in self.performance_history:
|
||||
self.performance_history[strategy_id] = []
|
||||
|
||||
self.performance_history[strategy_id].append({"timestamp": datetime.now(datetime.UTC), "performance": performance_data})
|
||||
self.performance_history[strategy_id].append({"timestamp": datetime.now(timezone.utc), "performance": performance_data})
|
||||
|
||||
# Apply optimization rules
|
||||
optimized_config = self._apply_optimization_rules(strategy_config, performance_data)
|
||||
|
||||
@@ -3,7 +3,7 @@ Agent Reputation and Trust System Domain Models
|
||||
Implements SQLModel definitions for agent reputation, trust scores, and economic metrics
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -66,9 +66,9 @@ class AgentReputation(SQLModel, table=True):
|
||||
specialization_tags: list[str] = Field(default=[], sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_activity: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_activity: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional metadata
|
||||
reputation_history: list[dict[str, Any]] = Field(default=[], sa_column=Column(JSON))
|
||||
@@ -103,7 +103,7 @@ class TrustScoreCalculation(SQLModel, table=True):
|
||||
confidence_level: float = Field(default=0.8, ge=0, le=1.0)
|
||||
|
||||
# Timestamps
|
||||
calculated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
calculated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
effective_period: int = Field(default=86400) # seconds
|
||||
|
||||
# Additional data
|
||||
@@ -140,7 +140,7 @@ class ReputationEvent(SQLModel, table=True):
|
||||
verification_status: str = Field(default="pending") # pending, verified, rejected
|
||||
|
||||
# Timestamps
|
||||
occurred_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
occurred_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
processed_at: datetime | None = None
|
||||
expires_at: datetime | None = None
|
||||
|
||||
@@ -176,8 +176,8 @@ class AgentEconomicProfile(SQLModel, table=True):
|
||||
liquidity_score: float = Field(default=0.0, ge=0, le=100.0)
|
||||
|
||||
# Timestamps
|
||||
profile_date: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_updated: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
profile_date: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_updated: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Historical data
|
||||
earnings_history: list[dict[str, Any]] = Field(default=[], sa_column=Column(JSON))
|
||||
@@ -217,8 +217,8 @@ class CommunityFeedback(SQLModel, table=True):
|
||||
moderator_notes: str = Field(default="", max_length=500)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
helpful_votes: int = Field(default=0)
|
||||
|
||||
# Additional metadata
|
||||
@@ -247,8 +247,8 @@ class ReputationLevelThreshold(SQLModel, table=True):
|
||||
fee_discount: float = Field(default=0.0, ge=0, le=100.0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
is_active: bool = Field(default=True)
|
||||
|
||||
# Additional configuration
|
||||
|
||||
@@ -3,7 +3,7 @@ Agent Reward System Domain Models
|
||||
Implements SQLModel definitions for performance-based rewards, incentives, and distributions
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -71,8 +71,8 @@ class RewardTierConfig(SQLModel, table=True):
|
||||
support_level: str = Field(default="basic")
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
is_active: bool = Field(default=True)
|
||||
|
||||
# Additional configuration
|
||||
@@ -112,9 +112,9 @@ class AgentRewardProfile(SQLModel, table=True):
|
||||
longest_streak: int = Field(default=0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_activity: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_activity: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional metadata
|
||||
reward_preferences: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
@@ -148,12 +148,12 @@ class RewardCalculation(SQLModel, table=True):
|
||||
|
||||
# Calculation metadata
|
||||
calculation_period: str = Field(default="daily") # daily, weekly, monthly
|
||||
reference_date: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
reference_date: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
trust_score_at_calculation: float = Field(ge=0, le=1000)
|
||||
performance_metrics: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
calculated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
calculated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -192,8 +192,8 @@ class RewardDistribution(SQLModel, table=True):
|
||||
error_message: str | None = None
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
scheduled_at: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -228,7 +228,7 @@ class RewardEvent(SQLModel, table=True):
|
||||
verification_status: str = Field(default="pending") # pending, verified, rejected
|
||||
|
||||
# Timestamps
|
||||
occurred_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
occurred_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
processed_at: datetime | None = None
|
||||
expires_at: datetime | None = None
|
||||
|
||||
@@ -266,8 +266,8 @@ class RewardMilestone(SQLModel, table=True):
|
||||
claimed_at: datetime | None = None
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime | None = None
|
||||
|
||||
# Additional data
|
||||
@@ -314,8 +314,8 @@ class RewardAnalytics(SQLModel, table=True):
|
||||
average_processing_time: float = Field(default=0.0) # milliseconds
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional analytics data
|
||||
analytics_data: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
|
||||
@@ -3,7 +3,7 @@ Agent-to-Agent Trading Protocol Domain Models
|
||||
Implements SQLModel definitions for P2P trading, matching, negotiation, and settlement
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -101,10 +101,10 @@ class TradeRequest(SQLModel, table=True):
|
||||
best_match_score: float = Field(default=0.0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime | None = None
|
||||
last_activity: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_activity: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional metadata
|
||||
tags: list[str] = Field(default=[], sa_column=Column(JSON))
|
||||
@@ -151,8 +151,8 @@ class TradeMatch(SQLModel, table=True):
|
||||
initial_terms: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
expires_at: datetime | None = None
|
||||
last_interaction: datetime | None = None
|
||||
|
||||
@@ -202,8 +202,8 @@ class TradeNegotiation(SQLModel, table=True):
|
||||
auto_accept_threshold: float = Field(default=85.0, ge=0, le=100)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
started_at: datetime | None = None
|
||||
completed_at: datetime | None = None
|
||||
expires_at: datetime | None = None
|
||||
@@ -260,9 +260,9 @@ class TradeAgreement(SQLModel, table=True):
|
||||
completion_percentage: float = Field(default=0.0, ge=0, le=100)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
signed_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
signed_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
starts_at: datetime | None = None
|
||||
ends_at: datetime | None = None
|
||||
completed_at: datetime | None = None
|
||||
@@ -314,7 +314,7 @@ class TradeSettlement(SQLModel, table=True):
|
||||
|
||||
# Status and timestamps
|
||||
status: TradeStatus = Field(default=TradeStatus.SETTLING)
|
||||
initiated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
initiated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
processed_at: datetime | None = None
|
||||
completed_at: datetime | None = None
|
||||
refunded_at: datetime | None = None
|
||||
@@ -365,8 +365,8 @@ class TradeFeedback(SQLModel, table=True):
|
||||
moderator_notes: str = Field(default="", max_length=500)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
trade_completed_at: datetime
|
||||
|
||||
# Additional data
|
||||
@@ -421,8 +421,8 @@ class TradingAnalytics(SQLModel, table=True):
|
||||
repeat_trade_rate: float = Field(default=0.0, ge=0, le=100.0)
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Additional analytics data
|
||||
analytics_data: dict[str, Any] = Field(default={}, sa_column=Column(JSON))
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
User domain models for AITBC
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import JSON
|
||||
from sqlmodel import Column, Field, SQLModel
|
||||
@@ -18,8 +18,8 @@ class User(SQLModel, table=True):
|
||||
email: str = Field(unique=True, index=True)
|
||||
username: str = Field(unique=True, index=True)
|
||||
status: str = Field(default="active", max_length=20)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_login: datetime | None = None
|
||||
|
||||
# Relationships
|
||||
@@ -37,8 +37,8 @@ class Wallet(SQLModel, table=True):
|
||||
user_id: str = Field(foreign_key="users.id")
|
||||
address: str = Field(unique=True, index=True)
|
||||
balance: float = Field(default=0.0)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: user: User = Relationship(back_populates="wallets")
|
||||
@@ -60,7 +60,7 @@ class Transaction(SQLModel, table=True):
|
||||
fee: float = Field(default=0.0)
|
||||
description: str | None = None
|
||||
tx_metadata: str | None = Field(default=None, sa_column=Column(JSON))
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
confirmed_at: datetime | None = None
|
||||
|
||||
# Relationships
|
||||
@@ -78,5 +78,5 @@ class UserSession(SQLModel, table=True):
|
||||
user_id: str = Field(foreign_key="users.id")
|
||||
token: str = Field(unique=True, index=True)
|
||||
expires_at: datetime
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_used: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
last_used: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
@@ -6,7 +6,7 @@ Domain models for managing agent wallets across multiple blockchain networks.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
|
||||
from sqlalchemy import JSON, Column
|
||||
@@ -41,8 +41,8 @@ class AgentWallet(SQLModel, table=True):
|
||||
encrypted_private_key: str | None = Field(default=None) # Only if managed internally
|
||||
kms_key_id: str | None = Field(default=None) # Reference to external KMS
|
||||
meta_data: dict[str, str] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: balances: List["TokenBalance"] = Relationship(back_populates="wallet")
|
||||
@@ -78,7 +78,7 @@ class TokenBalance(SQLModel, table=True):
|
||||
token_address: str = Field(index=True) # "native" for native currency
|
||||
token_symbol: str = Field()
|
||||
balance: float = Field(default=0.0)
|
||||
last_updated: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
last_updated: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: wallet: AgentWallet = Relationship(back_populates="balances")
|
||||
@@ -109,8 +109,8 @@ class WalletTransaction(SQLModel, table=True):
|
||||
nonce: int | None = Field(default=None)
|
||||
status: TransactionStatus = Field(default=TransactionStatus.PENDING, index=True)
|
||||
error_message: str | None = Field(default=None)
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
# Relationships
|
||||
# DISABLED: wallet: AgentWallet = Relationship(back_populates="transactions")
|
||||
|
||||
@@ -11,7 +11,13 @@ from .agent_identity import router as agent_identity
|
||||
from .blockchain import router as blockchain
|
||||
from .cache_management import router as cache_management
|
||||
from .client import router as client
|
||||
from .edge_gpu import router as edge_gpu
|
||||
|
||||
try:
|
||||
from .edge_gpu import router as edge_gpu
|
||||
except ImportError:
|
||||
edge_gpu = None
|
||||
print("WARNING: Edge GPU router not available (missing module)")
|
||||
|
||||
from .exchange import router as exchange
|
||||
from .explorer import router as explorer
|
||||
from .marketplace import router as marketplace
|
||||
|
||||
@@ -6,7 +6,7 @@ Provides health monitoring for reinforcement learning frameworks
|
||||
"""
|
||||
|
||||
import sys
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import psutil
|
||||
@@ -40,7 +40,7 @@ async def adaptive_learning_health(session: Annotated[Session, Depends(get_sessi
|
||||
"status": "healthy",
|
||||
"service": "adaptive-learning",
|
||||
"port": 8011,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||||
# System metrics
|
||||
"system": {
|
||||
@@ -97,7 +97,7 @@ async def adaptive_learning_health(session: Annotated[Session, Depends(get_sessi
|
||||
"status": "unhealthy",
|
||||
"service": "adaptive-learning",
|
||||
"port": 8011,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Health check failed",
|
||||
}
|
||||
|
||||
@@ -177,7 +177,7 @@ async def adaptive_learning_deep_health(session: Annotated[Session, Depends(get_
|
||||
"status": "healthy",
|
||||
"service": "adaptive-learning",
|
||||
"port": 8011,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"algorithm_tests": algorithm_tests,
|
||||
"safety_tests": safety_tests,
|
||||
"overall_health": (
|
||||
@@ -196,6 +196,6 @@ async def adaptive_learning_deep_health(session: Annotated[Session, Depends(get_
|
||||
"status": "unhealthy",
|
||||
"service": "adaptive-learning",
|
||||
"port": 8011,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Deep health check failed",
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Request
|
||||
@@ -55,7 +55,7 @@ async def create_test_miner(
|
||||
if existing_miner:
|
||||
# Update existing miner to ONLINE
|
||||
existing_miner.status = "ONLINE"
|
||||
existing_miner.last_heartbeat = datetime.now(datetime.UTC)
|
||||
existing_miner.last_heartbeat = datetime.now(timezone.utc)
|
||||
existing_miner.session_token = session_token
|
||||
session.add(existing_miner)
|
||||
session.commit()
|
||||
@@ -79,7 +79,7 @@ async def create_test_miner(
|
||||
session_token=session_token,
|
||||
status="ONLINE",
|
||||
inflight=0,
|
||||
last_heartbeat=datetime.now(datetime.UTC),
|
||||
last_heartbeat=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
session.add(miner)
|
||||
@@ -223,7 +223,7 @@ async def get_system_status(
|
||||
|
||||
# Get system info
|
||||
import sys
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import psutil
|
||||
|
||||
@@ -232,7 +232,7 @@ async def get_system_status(
|
||||
"memory_percent": psutil.virtual_memory().percent,
|
||||
"disk_percent": psutil.disk_usage("/").percent,
|
||||
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -275,7 +275,7 @@ async def create_agent_network(network_data: dict) -> dict:
|
||||
raise HTTPException(status_code=400, detail="Agent list is required")
|
||||
|
||||
# Create network record (simplified for now)
|
||||
network_id = f"network_{datetime.now(datetime.UTC).strftime('%Y%m%d_%H%M%S')}"
|
||||
network_id = f"network_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}"
|
||||
|
||||
network_response = {
|
||||
"id": network_id,
|
||||
@@ -284,7 +284,7 @@ async def create_agent_network(network_data: dict) -> dict:
|
||||
"agents": network_data["agents"],
|
||||
"coordination_strategy": network_data.get("coordination", "centralized"),
|
||||
"status": "active",
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
"owner_id": "temp_user",
|
||||
}
|
||||
|
||||
@@ -315,11 +315,11 @@ async def get_execution_receipt(execution_id: str) -> dict:
|
||||
{
|
||||
"coordinator_id": "coordinator_1",
|
||||
"signature": "0xmock_attestation_1",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
],
|
||||
"minted_amount": 1000,
|
||||
"recorded_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"recorded_at": datetime.now(timezone.utc).isoformat(),
|
||||
"verified": True,
|
||||
"block_hash": "0xmock_block_hash",
|
||||
"transaction_hash": "0xmock_tx_hash",
|
||||
|
||||
@@ -3,11 +3,12 @@ Agent Identity API Router
|
||||
REST API endpoints for agent identity management and cross-chain operations
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlmodel import Session
|
||||
|
||||
from ..agent_identity.manager import AgentIdentityManager
|
||||
from ..domain.agent_identity import (
|
||||
@@ -85,7 +86,7 @@ async def deactivate_agent_identity(
|
||||
success = await manager.deactivate_agent_identity(agent_id, reason)
|
||||
if not success:
|
||||
raise HTTPException(status_code=400, detail="Deactivation failed")
|
||||
return {"agent_id": agent_id, "deactivated": True, "reason": reason, "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||
return {"agent_id": agent_id, "deactivated": True, "reason": reason, "timestamp": datetime.now(timezone.utc).isoformat()}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
@@ -164,7 +165,7 @@ async def update_cross_chain_mapping(
|
||||
"chain_id": chain_id,
|
||||
"new_address": new_address,
|
||||
"updated": True,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
except HTTPException:
|
||||
raise
|
||||
@@ -255,7 +256,7 @@ async def get_wallet_balance(agent_id: str, chain_id: int, manager: AgentIdentit
|
||||
"agent_id": agent_id,
|
||||
"chain_id": chain_id,
|
||||
"balance": str(balance),
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=400, detail="Failed to create agent identity")
|
||||
@@ -427,7 +428,7 @@ async def cleanup_expired_verifications(manager: AgentIdentityManager = Depends(
|
||||
"""Clean up expired verification records"""
|
||||
try:
|
||||
cleaned_count = await manager.registry.cleanup_expired_verifications()
|
||||
return {"cleaned_verifications": cleaned_count, "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||
return {"cleaned_verifications": cleaned_count, "timestamp": datetime.now(timezone.utc).isoformat()}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail="Operation failed")
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ Advanced Agent Performance API Endpoints
|
||||
REST API for meta-learning, resource optimization, and performance enhancement
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
@@ -319,7 +319,7 @@ async def adapt_model_to_task(
|
||||
"success": True,
|
||||
"model_id": model_id,
|
||||
"adaptation_results": results,
|
||||
"adapted_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"adapted_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except ValueError as e:
|
||||
@@ -554,7 +554,7 @@ async def create_capability(
|
||||
skill_level=capability_request.skill_level,
|
||||
specialization_areas=capability_request.specialization_areas,
|
||||
proficiency_score=min(1.0, capability_request.skill_level / 10.0),
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
session.add(capability)
|
||||
@@ -718,7 +718,7 @@ async def health_check() -> Dict[str, Any]:
|
||||
|
||||
return {
|
||||
"status": "healthy",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"version": "1.0.0",
|
||||
"services": {
|
||||
"meta_learning_engine": "operational",
|
||||
|
||||
@@ -7,7 +7,7 @@ AI Agent API Router for Verifiable AI Agent Orchestration
|
||||
Provides REST API endpoints for agent workflow management and execution
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
|
||||
@@ -142,7 +142,7 @@ async def update_workflow(
|
||||
for field, value in update_data.items():
|
||||
setattr(workflow, field, value)
|
||||
|
||||
workflow.updated_at = datetime.now(datetime.UTC)
|
||||
workflow.updated_at = datetime.now(timezone.utc)
|
||||
session.commit()
|
||||
session.refresh(workflow)
|
||||
|
||||
@@ -352,7 +352,7 @@ async def cancel_execution(
|
||||
|
||||
# Cancel execution
|
||||
state_manager = AgentStateManager(session)
|
||||
await state_manager.update_execution_status(execution_id, status=AgentStatus.CANCELLED, completed_at=datetime.now(datetime.UTC))
|
||||
await state_manager.update_execution_status(execution_id, status=AgentStatus.CANCELLED, completed_at=datetime.now(timezone.utc))
|
||||
|
||||
logger.info(f"Cancelled agent execution: {execution_id}")
|
||||
return {"message": "Execution cancelled successfully"}
|
||||
@@ -425,7 +425,7 @@ async def get_execution_logs(
|
||||
@router.get("/test")
|
||||
async def test_endpoint() -> dict[str, str]:
|
||||
"""Test endpoint to verify router is working"""
|
||||
return {"message": "Agent router is working", "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||
return {"message": "Agent router is working", "timestamp": datetime.now(timezone.utc).isoformat()}
|
||||
|
||||
|
||||
@router.post("/networks", response_model=dict, status_code=201)
|
||||
@@ -445,7 +445,7 @@ async def create_agent_network(
|
||||
raise HTTPException(status_code=400, detail="Agent list is required")
|
||||
|
||||
# Create network record (simplified for now)
|
||||
network_id = f"network_{datetime.now(datetime.UTC).strftime('%Y%m%d_%H%M%S')}"
|
||||
network_id = f"network_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}"
|
||||
|
||||
network_response = {
|
||||
"id": network_id,
|
||||
@@ -454,7 +454,7 @@ async def create_agent_network(
|
||||
"agents": network_data["agents"],
|
||||
"coordination_strategy": network_data.get("coordination", "centralized"),
|
||||
"status": "active",
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
"owner_id": current_user,
|
||||
}
|
||||
|
||||
@@ -488,11 +488,11 @@ async def get_execution_receipt(
|
||||
{
|
||||
"coordinator_id": "coordinator_1",
|
||||
"signature": "0xmock_attestation_1",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
],
|
||||
"minted_amount": 1000,
|
||||
"recorded_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"recorded_at": datetime.now(timezone.utc).isoformat(),
|
||||
"verified": True,
|
||||
"block_hash": "0xmock_block_hash",
|
||||
"transaction_hash": "0xmock_tx_hash",
|
||||
|
||||
@@ -125,7 +125,7 @@ async def update_security_policy(
|
||||
if hasattr(policy, field):
|
||||
setattr(policy, field, value)
|
||||
|
||||
policy.updated_at = datetime.now(datetime.UTC)
|
||||
policy.updated_at = datetime.now(timezone.utc)
|
||||
session.commit()
|
||||
session.refresh(policy)
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ Marketplace Analytics API Endpoints
|
||||
REST API for analytics, insights, reporting, and dashboards
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
@@ -552,7 +552,7 @@ async def get_key_performance_indicators(
|
||||
|
||||
try:
|
||||
# Get latest metrics for KPIs
|
||||
end_time = datetime.now(datetime.UTC)
|
||||
end_time = datetime.now(timezone.utc)
|
||||
|
||||
if period_type == AnalyticsPeriod.DAILY:
|
||||
start_time = end_time - timedelta(days=1)
|
||||
|
||||
@@ -5,14 +5,14 @@ Bounty Management API
|
||||
REST API for AI agent bounty system with ZK-proof verification
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field, validator
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..app_logging import get_logger
|
||||
from aitbc import get_logger
|
||||
from ..auth import get_current_user
|
||||
from ..domain.bounty import (
|
||||
Bounty,
|
||||
@@ -38,7 +38,7 @@ class BountyCreateRequest(BaseModel):
|
||||
performance_criteria: Dict[str, Any] = Field(default_factory=dict)
|
||||
min_accuracy: float = Field(default=90.0, ge=0, le=100)
|
||||
max_response_time: Optional[int] = Field(default=None, gt=0)
|
||||
deadline: datetime = Field(..., gt=datetime.now(datetime.UTC))
|
||||
deadline: datetime = Field(..., gt=datetime.now(timezone.utc))
|
||||
max_submissions: int = Field(default=100, gt=0, le=1000)
|
||||
requires_zk_proof: bool = Field(default=True)
|
||||
auto_verify_threshold: float = Field(default=95.0, ge=0, le=100)
|
||||
@@ -48,9 +48,9 @@ class BountyCreateRequest(BaseModel):
|
||||
|
||||
@validator('deadline')
|
||||
def validate_deadline(cls, v: datetime) -> datetime:
|
||||
if v <= datetime.now(datetime.UTC):
|
||||
if v <= datetime.now(timezone.utc):
|
||||
raise ValueError('Deadline must be in the future')
|
||||
if v > datetime.now(datetime.UTC) + timedelta(days=365):
|
||||
if v > datetime.now(timezone.utc) + timedelta(days=365):
|
||||
raise ValueError('Deadline cannot be more than 1 year in the future')
|
||||
return v
|
||||
|
||||
@@ -281,7 +281,7 @@ async def submit_bounty_solution(
|
||||
if bounty.status != BountyStatus.ACTIVE:
|
||||
raise HTTPException(status_code=400, detail="Bounty is not active")
|
||||
|
||||
if datetime.now(datetime.UTC) > bounty.deadline:
|
||||
if datetime.now(timezone.utc) > bounty.deadline:
|
||||
raise HTTPException(status_code=400, detail="Bounty deadline has passed")
|
||||
|
||||
# Create submission
|
||||
@@ -519,7 +519,7 @@ async def expire_bounty(
|
||||
if bounty.status != BountyStatus.ACTIVE:
|
||||
raise HTTPException(status_code=400, detail="Bounty is not active")
|
||||
|
||||
if datetime.now(datetime.UTC) <= bounty.deadline:
|
||||
if datetime.now(timezone.utc) <= bounty.deadline:
|
||||
raise HTTPException(status_code=400, detail="Bounty deadline has not passed")
|
||||
|
||||
# Expire bounty
|
||||
|
||||
@@ -7,7 +7,7 @@ Certification and Partnership API Endpoints
|
||||
REST API for agent certification, partnership programs, and badge system
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
@@ -626,7 +626,7 @@ async def check_automatic_badges(
|
||||
"agent_id": agent_id,
|
||||
"badges_awarded": awarded_badges,
|
||||
"total_awarded": len(awarded_badges),
|
||||
"checked_at": datetime.now(datetime.UTC).isoformat()
|
||||
"checked_at": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
||||
@@ -265,7 +265,7 @@ async def create_agent_network(network_data: dict) -> dict:
|
||||
raise HTTPException(status_code=400, detail="Agent list is required")
|
||||
|
||||
# Create network record (simplified for now)
|
||||
network_id = f"network_{datetime.now(datetime.UTC).strftime('%Y%m%d_%H%M%S')}"
|
||||
network_id = f"network_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}"
|
||||
|
||||
network_response = {
|
||||
"id": network_id,
|
||||
@@ -274,7 +274,7 @@ async def create_agent_network(network_data: dict) -> dict:
|
||||
"agents": network_data["agents"],
|
||||
"coordination_strategy": network_data.get("coordination", "centralized"),
|
||||
"status": "active",
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
"owner_id": "temp_user",
|
||||
}
|
||||
|
||||
@@ -302,11 +302,11 @@ async def get_execution_receipt(execution_id: str) -> dict:
|
||||
{
|
||||
"coordinator_id": "coordinator_1",
|
||||
"signature": "0xmock_attestation_1",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
],
|
||||
"minted_amount": 1000,
|
||||
"recorded_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"recorded_at": datetime.now(timezone.utc).isoformat(),
|
||||
"verified": True,
|
||||
"block_hash": "0xmock_block_hash",
|
||||
"transaction_hash": "0xmock_tx_hash",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
API endpoints for confidential transactions
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from aitbc import get_logger
|
||||
@@ -83,13 +83,13 @@ async def create_confidential_transaction(request: ConfidentialTransactionCreate
|
||||
"""Create a new confidential transaction with optional encryption"""
|
||||
try:
|
||||
# Generate transaction ID
|
||||
transaction_id = f"ctx-{datetime.now(datetime.UTC).timestamp()}"
|
||||
transaction_id = f"ctx-{datetime.now(timezone.utc).timestamp()}"
|
||||
|
||||
# Create base transaction
|
||||
transaction = ConfidentialTransaction(
|
||||
transaction_id=transaction_id,
|
||||
job_id=request.job_id,
|
||||
timestamp=datetime.now(datetime.UTC),
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
status="created",
|
||||
amount=request.amount,
|
||||
pricing=request.pricing,
|
||||
@@ -178,7 +178,7 @@ async def access_confidential_data(
|
||||
transaction = ConfidentialTransaction(
|
||||
transaction_id=transaction_id,
|
||||
job_id="test-job",
|
||||
timestamp=datetime.now(datetime.UTC),
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
status="completed",
|
||||
confidential=True,
|
||||
participants=["client-456", "miner-789"],
|
||||
@@ -205,7 +205,7 @@ async def access_confidential_data(
|
||||
return ConfidentialAccessResponse(
|
||||
success=True,
|
||||
data={"amount": "1000", "pricing": {"rate": "0.1"}},
|
||||
access_id=f"access-{datetime.now(datetime.UTC).timestamp()}",
|
||||
access_id=f"access-{datetime.now(timezone.utc).timestamp()}",
|
||||
)
|
||||
|
||||
# Decrypt data
|
||||
@@ -230,7 +230,7 @@ async def access_confidential_data(
|
||||
)
|
||||
|
||||
return ConfidentialAccessResponse(
|
||||
success=True, data=decrypted_data, access_id=f"access-{datetime.now(datetime.UTC).timestamp()}"
|
||||
success=True, data=decrypted_data, access_id=f"access-{datetime.now(timezone.utc).timestamp()}"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
@@ -254,7 +254,7 @@ async def audit_access_confidential_data(
|
||||
transaction = ConfidentialTransaction(
|
||||
transaction_id=transaction_id,
|
||||
job_id="test-job",
|
||||
timestamp=datetime.now(datetime.UTC),
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
status="completed",
|
||||
confidential=True,
|
||||
)
|
||||
@@ -283,7 +283,7 @@ async def audit_access_confidential_data(
|
||||
)
|
||||
|
||||
return ConfidentialAccessResponse(
|
||||
success=True, data=decrypted_data, access_id=f"audit-{datetime.now(datetime.UTC).timestamp()}"
|
||||
success=True, data=decrypted_data, access_id=f"audit-{datetime.now(timezone.utc).timestamp()}"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
@@ -313,7 +313,7 @@ async def register_encryption_key(request: KeyRegistrationRequest, api_key: str
|
||||
success=True,
|
||||
participant_id=request.participant_id,
|
||||
key_version=1, # Would get from storage
|
||||
registered_at=datetime.now(datetime.UTC),
|
||||
registered_at=datetime.now(timezone.utc),
|
||||
error=None,
|
||||
)
|
||||
except:
|
||||
@@ -333,7 +333,7 @@ async def register_encryption_key(request: KeyRegistrationRequest, api_key: str
|
||||
except KeyManagementError as e:
|
||||
logger.error(f"Key registration failed: {e}")
|
||||
return KeyRegistrationResponse(
|
||||
success=False, participant_id=request.participant_id, key_version=0, registered_at=datetime.now(datetime.UTC), error=str(e)
|
||||
success=False, participant_id=request.participant_id, key_version=0, registered_at=datetime.now(timezone.utc), error=str(e)
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to register key: {e}")
|
||||
|
||||
@@ -3,7 +3,7 @@ Cross-Chain Integration API Router
|
||||
REST API endpoints for enhanced multi-chain wallet adapter, cross-chain bridge service, and transaction manager
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -217,7 +217,7 @@ async def verify_signature(
|
||||
"message": message,
|
||||
"address": address,
|
||||
"chain_id": chain_id,
|
||||
"verified_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"verified_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -606,7 +606,7 @@ async def get_cross_chain_health(session: Session = Depends(get_session)) -> dic
|
||||
"transaction_success_rate": tx_stats["success_rate"],
|
||||
"average_processing_time": tx_stats["average_processing_time_minutes"],
|
||||
"active_liquidity_pools": len(await bridge_service.get_liquidity_pools()),
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_updated": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -675,7 +675,7 @@ async def get_cross_chain_config(session: Session = Depends(get_session)) -> dic
|
||||
"transaction_priorities": transaction_priorities,
|
||||
"routing_strategies": routing_strategies,
|
||||
"security_levels": [level.value for level in SecurityLevel],
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_updated": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
|
||||
@@ -3,7 +3,7 @@ Developer Platform API Router
|
||||
REST API endpoints for the developer ecosystem including bounties, certifications, and regional hubs
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
@@ -440,7 +440,7 @@ async def verify_certification(certification_id: str, session: Session = Depends
|
||||
"issued_by": certification.issued_by,
|
||||
"granted_at": certification.granted_at.isoformat(),
|
||||
"is_valid": True,
|
||||
"verification_timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"verification_timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
@@ -746,7 +746,7 @@ async def get_platform_overview(
|
||||
"regions_covered": 12, # Mock data
|
||||
},
|
||||
"staking": {"total_staked": 1000000.0, "active_stakers": 500, "average_apy": 7.5}, # Mock data
|
||||
"generated_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"generated_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -785,7 +785,7 @@ async def get_platform_health(session: Session = Depends(get_session)) -> dict[s
|
||||
"pending_submissions": 8, # Mock data
|
||||
"system_uptime": "99.9%",
|
||||
},
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_updated": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
|
||||
@@ -5,7 +5,7 @@ Dynamic Pricing API Router
|
||||
Provides RESTful endpoints for dynamic pricing management
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
@@ -147,7 +147,7 @@ async def get_price_forecast(
|
||||
accuracy_score=(
|
||||
sum(point.confidence for point in forecast_points) / len(forecast_points) if forecast_points else 0.0
|
||||
),
|
||||
generated_at=datetime.now(datetime.UTC).isoformat(),
|
||||
generated_at=datetime.now(timezone.utc).isoformat(),
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
@@ -197,7 +197,7 @@ async def set_pricing_strategy(
|
||||
provider_id=provider_id,
|
||||
strategy=request.strategy,
|
||||
constraints=request.constraints,
|
||||
set_at=datetime.now(datetime.UTC).isoformat(),
|
||||
set_at=datetime.now(timezone.utc).isoformat(),
|
||||
status="active",
|
||||
)
|
||||
|
||||
@@ -239,7 +239,7 @@ async def get_pricing_strategy(
|
||||
provider_id=provider_id,
|
||||
strategy=strategy.value,
|
||||
constraints=constraints_dict,
|
||||
set_at=datetime.now(datetime.UTC).isoformat(),
|
||||
set_at=datetime.now(timezone.utc).isoformat(),
|
||||
status="active",
|
||||
)
|
||||
|
||||
@@ -531,7 +531,7 @@ async def get_price_history(
|
||||
)
|
||||
|
||||
# Filter history by period
|
||||
cutoff_time = datetime.now(datetime.UTC) - timedelta(days=days)
|
||||
cutoff_time = datetime.now(timezone.utc) - timedelta(days=days)
|
||||
filtered_history = [point for point in engine.pricing_history[resource_id] if point.timestamp >= cutoff_time]
|
||||
|
||||
# Calculate statistics
|
||||
@@ -637,7 +637,7 @@ async def bulk_pricing_update(
|
||||
success_count=success_count,
|
||||
error_count=error_count,
|
||||
results=results,
|
||||
processed_at=datetime.now(datetime.UTC).isoformat(),
|
||||
processed_at=datetime.now(timezone.utc).isoformat(),
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
@@ -691,7 +691,7 @@ async def pricing_health_check(
|
||||
|
||||
return {
|
||||
"status": overall_status,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"services": {
|
||||
"pricing_engine": {
|
||||
"status": engine_status,
|
||||
@@ -710,4 +710,4 @@ async def pricing_health_check(
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Dynamic pricing health check failed: {e}")
|
||||
return {"status": "unhealthy", "timestamp": datetime.now(datetime.UTC).isoformat(), "error": "Health check failed"}
|
||||
return {"status": "unhealthy", "timestamp": datetime.now(timezone.utc).isoformat(), "error": "Health check failed"}
|
||||
|
||||
@@ -5,14 +5,14 @@ Ecosystem Metrics Dashboard API
|
||||
REST API for developer ecosystem metrics and analytics
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..app_logging import get_logger
|
||||
from aitbc import get_logger
|
||||
from ..auth import get_current_user
|
||||
from ..domain.bounty import AgentMetrics, BountyStats, EcosystemMetrics
|
||||
from ..services.ecosystem_service import EcosystemService
|
||||
@@ -345,7 +345,7 @@ async def get_ecosystem_alerts(
|
||||
"alerts": alerts,
|
||||
"severity": severity,
|
||||
"count": len(alerts),
|
||||
"last_updated": datetime.now(datetime.UTC)
|
||||
"last_updated": datetime.now(timezone.utc)
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -422,7 +422,7 @@ async def get_real_time_metrics(
|
||||
real_time_data = await ecosystem_service.get_real_time_metrics()
|
||||
|
||||
return {
|
||||
"timestamp": datetime.now(datetime.UTC),
|
||||
"timestamp": datetime.now(timezone.utc),
|
||||
"metrics": real_time_data,
|
||||
"update_frequency": "60s" # Update frequency in seconds
|
||||
}
|
||||
@@ -442,7 +442,7 @@ async def get_kpi_dashboard(
|
||||
|
||||
return {
|
||||
"kpis": kpi_data,
|
||||
"last_updated": datetime.now(datetime.UTC),
|
||||
"last_updated": datetime.now(timezone.utc),
|
||||
"refresh_interval": 300 # 5 minutes
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ Bitcoin Exchange Router for AITBC
|
||||
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, HTTPException, Request
|
||||
@@ -214,7 +214,7 @@ async def monitor_payment(payment_id: str) -> None:
|
||||
@router.get("/agents/test")
|
||||
async def test_agent_endpoint() -> dict[str, str]:
|
||||
"""Test endpoint to verify agent routes are working"""
|
||||
return {"message": "Agent routes are working", "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||
return {"message": "Agent routes are working", "timestamp": datetime.now(timezone.utc).isoformat()}
|
||||
|
||||
|
||||
@router.post("/agents/networks", response_model=dict, status_code=201)
|
||||
@@ -230,7 +230,7 @@ async def create_agent_network(network_data: dict) -> dict[str, Any]:
|
||||
raise HTTPException(status_code=400, detail="Agent list is required")
|
||||
|
||||
# Create network record (simplified for now)
|
||||
network_id = f"network_{datetime.now(datetime.UTC).strftime('%Y%m%d_%H%M%S')}"
|
||||
network_id = f"network_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}"
|
||||
|
||||
network_response = {
|
||||
"id": network_id,
|
||||
@@ -239,7 +239,7 @@ async def create_agent_network(network_data: dict) -> dict[str, Any]:
|
||||
"agents": network_data["agents"],
|
||||
"coordination_strategy": network_data.get("coordination", "centralized"),
|
||||
"status": "active",
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
"owner_id": "temp_user",
|
||||
}
|
||||
|
||||
@@ -269,11 +269,11 @@ async def get_execution_receipt(execution_id: str) -> dict[str, Any]:
|
||||
{
|
||||
"coordinator_id": "coordinator_1",
|
||||
"signature": "0xmock_attestation_1",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
],
|
||||
"minted_amount": 1000,
|
||||
"recorded_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"recorded_at": datetime.now(timezone.utc).isoformat(),
|
||||
"verified": True,
|
||||
"block_hash": "0xmock_block_hash",
|
||||
"transaction_hash": "0xmock_tx_hash",
|
||||
|
||||
@@ -3,7 +3,7 @@ Global Marketplace API Router
|
||||
REST API endpoints for global marketplace operations, multi-region support, and cross-chain integration
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query
|
||||
@@ -585,7 +585,7 @@ async def get_global_marketplace_health(
|
||||
recent_transactions = (
|
||||
session.execute(
|
||||
select(func.count(GlobalMarketplaceTransaction.id)).where(
|
||||
GlobalMarketplaceTransaction.created_at >= datetime.now(datetime.UTC) - timedelta(hours=24)
|
||||
GlobalMarketplaceTransaction.created_at >= datetime.now(timezone.utc) - timedelta(hours=24)
|
||||
)
|
||||
).scalar()
|
||||
or 0
|
||||
@@ -608,7 +608,7 @@ async def get_global_marketplace_health(
|
||||
"recent_24h": recent_transactions,
|
||||
"activity_rate": transaction_activity,
|
||||
},
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_updated": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
|
||||
@@ -3,7 +3,7 @@ Global Marketplace Integration API Router
|
||||
REST API endpoints for integrated global marketplace with cross-chain capabilities
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
@@ -350,7 +350,7 @@ async def get_marketplace_integration_analytics(
|
||||
"active_regions": len(active_regions),
|
||||
"supported_chains": len(supported_chains),
|
||||
"integration_config": integration_service.integration_config,
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_updated": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -394,7 +394,7 @@ async def get_integration_status(
|
||||
"auto_bridge_execution": config["auto_bridge_execution"],
|
||||
"multi_chain_wallet_support": config["multi_chain_wallet_support"],
|
||||
},
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_updated": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -463,7 +463,7 @@ async def get_integration_config(
|
||||
}
|
||||
for priority in TransactionPriority
|
||||
},
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_updated": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -492,7 +492,7 @@ async def update_integration_config(
|
||||
return {
|
||||
"updated_config": integration_service.integration_config,
|
||||
"updated_keys": list(config_updates.keys()),
|
||||
"updated_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"updated_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except ValueError as e:
|
||||
@@ -554,7 +554,7 @@ async def get_integration_health(
|
||||
if health_status["issues"]:
|
||||
health_status["overall_status"] = "degraded"
|
||||
|
||||
health_status["last_updated"] = datetime.now(datetime.UTC).isoformat()
|
||||
health_status["last_updated"] = datetime.now(timezone.utc).isoformat()
|
||||
|
||||
return health_status
|
||||
|
||||
@@ -571,7 +571,7 @@ async def run_integration_diagnostics(
|
||||
"""Run integration diagnostics"""
|
||||
|
||||
try:
|
||||
diagnostics = {"diagnostic_type": diagnostic_type, "started_at": datetime.now(datetime.UTC).isoformat(), "results": {}}
|
||||
diagnostics = {"diagnostic_type": diagnostic_type, "started_at": datetime.now(timezone.utc).isoformat(), "results": {}}
|
||||
|
||||
if diagnostic_type == "full" or diagnostic_type == "services":
|
||||
# Test services
|
||||
@@ -617,9 +617,9 @@ async def run_integration_diagnostics(
|
||||
"configuration": integration_service.integration_config,
|
||||
}
|
||||
|
||||
diagnostics["completed_at"] = datetime.now(datetime.UTC).isoformat()
|
||||
diagnostics["completed_at"] = datetime.now(timezone.utc).isoformat()
|
||||
diagnostics["duration_seconds"] = (
|
||||
datetime.now(datetime.UTC) - datetime.fromisoformat(diagnostics["started_at"])
|
||||
datetime.now(timezone.utc) - datetime.fromisoformat(diagnostics["started_at"])
|
||||
).total_seconds()
|
||||
|
||||
return diagnostics
|
||||
|
||||
@@ -3,7 +3,7 @@ Enhanced Governance API Router
|
||||
REST API endpoints for multi-jurisdictional DAO governance, regional councils, treasury management, and staking
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
@@ -433,7 +433,7 @@ async def check_compliance_status(
|
||||
"jurisdiction": jurisdiction,
|
||||
"is_compliant": True,
|
||||
"compliance_level": "full",
|
||||
"last_check": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_check": datetime.now(timezone.utc).isoformat(),
|
||||
"requirements_met": {
|
||||
"kyc_verified": True,
|
||||
"aml_screened": True,
|
||||
@@ -441,7 +441,7 @@ async def check_compliance_status(
|
||||
"minimum_stake_met": True,
|
||||
},
|
||||
"restrictions": [],
|
||||
"next_review_date": (datetime.now(datetime.UTC) + timedelta(days=365)).isoformat(),
|
||||
"next_review_date": (datetime.now(timezone.utc) + timedelta(days=365)).isoformat(),
|
||||
}
|
||||
|
||||
return compliance_status
|
||||
@@ -490,7 +490,7 @@ async def get_governance_system_health(
|
||||
"treasury_balance": analytics["treasury"]["total_allocations"],
|
||||
"staking_pools": analytics["staking"]["active_pools"],
|
||||
},
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_updated": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
return health_data
|
||||
@@ -539,7 +539,7 @@ async def get_governance_platform_status(
|
||||
"treasury_utilization": f"{analytics['treasury']['utilization_rate']}%",
|
||||
"staking_apy": f"{analytics['staking']['average_apy']}%",
|
||||
},
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_updated": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
return status_data
|
||||
|
||||
@@ -7,7 +7,7 @@ Provides health monitoring for CUDA-optimized multi-modal processing
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import psutil
|
||||
@@ -37,7 +37,7 @@ async def gpu_multimodal_health(session: Annotated[Session, Depends(get_session)
|
||||
"status": "healthy" if gpu_info["available"] else "degraded",
|
||||
"service": "gpu-multimodal",
|
||||
"port": 8010,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||||
# System metrics
|
||||
"system": {
|
||||
@@ -86,7 +86,7 @@ async def gpu_multimodal_health(session: Annotated[Session, Depends(get_session)
|
||||
"status": "unhealthy",
|
||||
"service": "gpu-multimodal",
|
||||
"port": 8010,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Health check failed",
|
||||
}
|
||||
|
||||
@@ -145,7 +145,7 @@ async def gpu_multimodal_deep_health(session: Annotated[Session, Depends(get_ses
|
||||
"status": "healthy" if gpu_info["available"] else "degraded",
|
||||
"service": "gpu-multimodal",
|
||||
"port": 8010,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"gpu_info": gpu_info,
|
||||
"cuda_tests": cuda_tests,
|
||||
"overall_health": (
|
||||
@@ -161,7 +161,7 @@ async def gpu_multimodal_deep_health(session: Annotated[Session, Depends(get_ses
|
||||
"status": "unhealthy",
|
||||
"service": "gpu-multimodal",
|
||||
"port": 8010,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Deep health check failed",
|
||||
}
|
||||
|
||||
|
||||
@@ -6,14 +6,14 @@ Provides health monitoring for royalties, licensing, verification, and analytics
|
||||
"""
|
||||
|
||||
import sys
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import psutil
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..app_logging import get_logger
|
||||
from aitbc import get_logger
|
||||
from ..services.marketplace_enhanced import EnhancedMarketplaceService
|
||||
from ..storage import get_session
|
||||
|
||||
@@ -41,7 +41,7 @@ async def marketplace_enhanced_health(session: Annotated[Session, Depends(get_se
|
||||
"status": "healthy",
|
||||
"service": "marketplace-enhanced",
|
||||
"port": 8002,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||||
# System metrics
|
||||
"system": {
|
||||
@@ -98,7 +98,7 @@ async def marketplace_enhanced_health(session: Annotated[Session, Depends(get_se
|
||||
"status": "unhealthy",
|
||||
"service": "marketplace-enhanced",
|
||||
"port": 8002,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Health check failed",
|
||||
}
|
||||
|
||||
@@ -173,7 +173,7 @@ async def marketplace_enhanced_deep_health(session: Annotated[Session, Depends(g
|
||||
"status": "healthy",
|
||||
"service": "marketplace-enhanced",
|
||||
"port": 8002,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"feature_tests": feature_tests,
|
||||
"overall_health": "pass" if all(test.get("status") == "pass" for test in feature_tests.values()) else "degraded",
|
||||
}
|
||||
@@ -184,6 +184,6 @@ async def marketplace_enhanced_deep_health(session: Annotated[Session, Depends(g
|
||||
"status": "unhealthy",
|
||||
"service": "marketplace-enhanced",
|
||||
"port": 8002,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Deep health check failed",
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ GPU marketplace endpoints backed by persistent SQLModel tables.
|
||||
"""
|
||||
|
||||
import statistics
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -157,7 +157,7 @@ async def register_gpu(request: dict[str, Any], session: Annotated[Session, Depe
|
||||
|
||||
# Create GPU registry record
|
||||
import uuid
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
|
||||
gpu_id = f"gpu_{uuid.uuid4().hex[:8]}"
|
||||
|
||||
@@ -180,7 +180,7 @@ async def register_gpu(request: dict[str, Any], session: Annotated[Session, Depe
|
||||
capabilities=[],
|
||||
average_rating=0.0,
|
||||
total_reviews=0,
|
||||
created_at=datetime.now(datetime.UTC)
|
||||
created_at=datetime.now(timezone.utc)
|
||||
)
|
||||
|
||||
session.add(gpu_record)
|
||||
@@ -259,9 +259,9 @@ async def buy_gpu(
|
||||
)
|
||||
|
||||
# Create booking for the purchase
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
|
||||
start_time = datetime.now(datetime.UTC)
|
||||
start_time = datetime.now(timezone.utc)
|
||||
end_time = start_time + timedelta(hours=request.duration_hours)
|
||||
|
||||
# Calculate total cost
|
||||
@@ -411,7 +411,7 @@ async def sell_gpu(
|
||||
"listing_price": request.listing_price,
|
||||
"status": "listed",
|
||||
"description": request.description,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat() + "Z",
|
||||
"timestamp": datetime.now(timezone.utc).isoformat() + "Z",
|
||||
}
|
||||
|
||||
|
||||
@@ -442,7 +442,7 @@ async def book_gpu(
|
||||
status_code=http_status.HTTP_400_BAD_REQUEST, detail="Booking duration cannot exceed 8760 hours (1 year)"
|
||||
)
|
||||
|
||||
start_time = datetime.now(datetime.UTC)
|
||||
start_time = datetime.now(timezone.utc)
|
||||
end_time = start_time + timedelta(hours=request.duration_hours)
|
||||
|
||||
# Validate booking end time is in the future
|
||||
@@ -593,7 +593,7 @@ async def submit_ollama_task(
|
||||
)
|
||||
|
||||
task_id = f"task_{uuid4().hex[:10]}"
|
||||
submitted_at = datetime.now(datetime.UTC).isoformat() + "Z"
|
||||
submitted_at = datetime.now(timezone.utc).isoformat() + "Z"
|
||||
|
||||
return {
|
||||
"task_id": task_id,
|
||||
@@ -619,7 +619,7 @@ async def send_payment(
|
||||
)
|
||||
|
||||
tx_id = f"tx_{uuid4().hex[:10]}"
|
||||
processed_at = datetime.now(datetime.UTC).isoformat() + "Z"
|
||||
processed_at = datetime.now(timezone.utc).isoformat() + "Z"
|
||||
|
||||
return {
|
||||
"tx_id": tx_id,
|
||||
@@ -920,7 +920,7 @@ async def get_pricing(
|
||||
},
|
||||
"individual_gpu_pricing": dynamic_prices,
|
||||
"market_analysis": market_analysis,
|
||||
"pricing_timestamp": datetime.now(datetime.UTC).isoformat() + "Z",
|
||||
"pricing_timestamp": datetime.now(timezone.utc).isoformat() + "Z",
|
||||
}
|
||||
|
||||
|
||||
@@ -935,5 +935,5 @@ async def bid_gpu(request: dict[str, Any], session: Session = Depends(get_sessio
|
||||
"gpu_id": request.get("gpu_id"),
|
||||
"bid_amount": request.get("bid_amount"),
|
||||
"duration_hours": request.get("duration_hours"),
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat() + "Z",
|
||||
"timestamp": datetime.now(timezone.utc).isoformat() + "Z",
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Annotated, Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
|
||||
@@ -87,7 +87,7 @@ async def submit_result(
|
||||
metrics = dict(req.metrics or {})
|
||||
duration_ms = metrics.get("duration_ms")
|
||||
if duration_ms is None and job.requested_at:
|
||||
duration_ms = int((datetime.now(datetime.UTC) - job.requested_at).total_seconds() * 1000)
|
||||
duration_ms = int((datetime.now(timezone.utc) - job.requested_at).total_seconds() * 1000)
|
||||
metrics["duration_ms"] = duration_ms
|
||||
|
||||
receipt = receipt_service.create_receipt(job, miner_id, req.result, metrics)
|
||||
|
||||
@@ -6,7 +6,7 @@ Provides health monitoring for specialized modality optimization strategies
|
||||
"""
|
||||
|
||||
import sys
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import psutil
|
||||
@@ -33,7 +33,7 @@ async def modality_optimization_health(session: Annotated[Session, Depends(get_s
|
||||
"status": "healthy",
|
||||
"service": "modality-optimization",
|
||||
"port": 8004,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||||
# System metrics
|
||||
"system": {
|
||||
@@ -86,7 +86,7 @@ async def modality_optimization_health(session: Annotated[Session, Depends(get_s
|
||||
"status": "unhealthy",
|
||||
"service": "modality-optimization",
|
||||
"port": 8004,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Health check failed",
|
||||
}
|
||||
|
||||
@@ -148,7 +148,7 @@ async def modality_optimization_deep_health(session: Annotated[Session, Depends(
|
||||
"status": "healthy",
|
||||
"service": "modality-optimization",
|
||||
"port": 8004,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"optimization_tests": optimization_tests,
|
||||
"overall_health": (
|
||||
"pass" if all(test.get("status") == "pass" for test in optimization_tests.values()) else "degraded"
|
||||
@@ -161,6 +161,6 @@ async def modality_optimization_deep_health(session: Annotated[Session, Depends(
|
||||
"status": "unhealthy",
|
||||
"service": "modality-optimization",
|
||||
"port": 8004,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Deep health check failed",
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ Provides a unified dashboard for all 6 enhanced services
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter
|
||||
@@ -75,7 +75,7 @@ async def monitoring_dashboard() -> dict[str, Any]:
|
||||
overall_metrics = calculate_overall_metrics(health_data)
|
||||
|
||||
dashboard_data = {
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"overall_status": overall_metrics["overall_status"],
|
||||
"services": health_data,
|
||||
"metrics": overall_metrics,
|
||||
@@ -84,7 +84,7 @@ async def monitoring_dashboard() -> dict[str, Any]:
|
||||
"healthy_services": len([s for s in health_data.values() if s.get("status") == "healthy"]),
|
||||
"degraded_services": len([s for s in health_data.values() if s.get("status") == "degraded"]),
|
||||
"unhealthy_services": len([s for s in health_data.values() if s.get("status") == "unhealthy"]),
|
||||
"last_updated": datetime.now(datetime.UTC).strftime("%Y-%m-%d %H:%M:%S UTC"),
|
||||
"last_updated": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC"),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -98,7 +98,7 @@ async def monitoring_dashboard() -> dict[str, Any]:
|
||||
logger.error(f"Failed to generate monitoring dashboard: {e}")
|
||||
return {
|
||||
"error": "Failed to generate dashboard",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"services": SERVICES,
|
||||
"overall_status": "error",
|
||||
"summary": {
|
||||
@@ -106,7 +106,7 @@ async def monitoring_dashboard() -> dict[str, Any]:
|
||||
"healthy_services": 0,
|
||||
"degraded_services": 0,
|
||||
"unhealthy_services": len(SERVICES),
|
||||
"last_updated": datetime.now(datetime.UTC).strftime("%Y-%m-%d %H:%M:%S UTC"),
|
||||
"last_updated": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC"),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -119,7 +119,7 @@ async def services_summary() -> dict[str, Any]:
|
||||
try:
|
||||
health_data = await collect_all_health_data()
|
||||
|
||||
summary = {"timestamp": datetime.now(datetime.UTC).isoformat(), "services": {}}
|
||||
summary = {"timestamp": datetime.now(timezone.utc).isoformat(), "services": {}}
|
||||
|
||||
for service_id, service_info in SERVICES.items():
|
||||
health = health_data.get(service_id, {})
|
||||
@@ -136,7 +136,7 @@ async def services_summary() -> dict[str, Any]:
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to generate services summary: {e}")
|
||||
return {"error": "Failed to generate summary", "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||
return {"error": "Failed to generate summary", "timestamp": datetime.now(timezone.utc).isoformat()}
|
||||
|
||||
|
||||
@router.get("/dashboard/metrics", tags=["monitoring"], summary="System Metrics")
|
||||
@@ -156,7 +156,7 @@ async def system_metrics() -> dict[str, Any]:
|
||||
network = psutil.net_io_counters()
|
||||
|
||||
metrics = {
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"system": {
|
||||
"cpu_percent": cpu_percent,
|
||||
"cpu_count": psutil.cpu_count(),
|
||||
@@ -184,7 +184,7 @@ async def system_metrics() -> dict[str, Any]:
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to collect system metrics: {e}")
|
||||
return {"error": "Failed to collect metrics", "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||
return {"error": "Failed to collect metrics", "timestamp": datetime.now(timezone.utc).isoformat()}
|
||||
|
||||
|
||||
async def collect_all_health_data() -> dict[str, Any]:
|
||||
@@ -206,7 +206,7 @@ async def collect_all_health_data() -> dict[str, Any]:
|
||||
health_data[service_id] = {
|
||||
"status": "unhealthy",
|
||||
"error": str(result),
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
else:
|
||||
health_data[service_id] = result
|
||||
@@ -225,7 +225,7 @@ async def check_service_health(service_name: str, service_config: dict[str, Any]
|
||||
return {
|
||||
"status": "healthy",
|
||||
"response_time": 0.1, # Placeholder - would be measured
|
||||
"last_check": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_check": datetime.now(timezone.utc).isoformat(),
|
||||
"details": response,
|
||||
}
|
||||
except NetworkError as e:
|
||||
@@ -233,11 +233,11 @@ async def check_service_health(service_name: str, service_config: dict[str, Any]
|
||||
return {
|
||||
"status": "unhealthy",
|
||||
"error": str(e),
|
||||
"last_check": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_check": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
return {"status": "unhealthy", "error": "connection refused", "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||
return {"status": "unhealthy", "error": "connection refused", "timestamp": datetime.now(timezone.utc).isoformat()}
|
||||
except Exception as e:
|
||||
return {"status": "unhealthy", "error": str(e), "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||
return {"status": "unhealthy", "error": str(e), "timestamp": datetime.now(timezone.utc).isoformat()}
|
||||
|
||||
|
||||
def calculate_overall_metrics(health_data: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
@@ -6,7 +6,7 @@ Provides health monitoring for multi-modal processing capabilities
|
||||
"""
|
||||
|
||||
import sys
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import psutil
|
||||
@@ -38,7 +38,7 @@ async def multimodal_health(session: Annotated[Session, Depends(get_session)]) -
|
||||
"status": "healthy",
|
||||
"service": "multimodal-agent",
|
||||
"port": 8002,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||||
# System metrics
|
||||
"system": {
|
||||
@@ -81,7 +81,7 @@ async def multimodal_health(session: Annotated[Session, Depends(get_session)]) -
|
||||
"status": "unhealthy",
|
||||
"service": "multimodal-agent",
|
||||
"port": 8002,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Health check failed",
|
||||
}
|
||||
|
||||
@@ -129,7 +129,7 @@ async def multimodal_deep_health(session: Annotated[Session, Depends(get_session
|
||||
"status": "healthy",
|
||||
"service": "multimodal-agent",
|
||||
"port": 8002,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"modality_tests": modality_tests,
|
||||
"overall_health": "pass" if all(test.get("status") == "pass" for test in modality_tests.values()) else "degraded",
|
||||
}
|
||||
@@ -140,6 +140,6 @@ async def multimodal_deep_health(session: Annotated[Session, Depends(get_session
|
||||
"status": "unhealthy",
|
||||
"service": "multimodal-agent",
|
||||
"port": 8002,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Deep health check failed",
|
||||
}
|
||||
|
||||
@@ -44,13 +44,13 @@ async def detailed_health() -> dict[str, Any]:
|
||||
try:
|
||||
import psutil
|
||||
import logging
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
|
||||
return {
|
||||
"status": "healthy",
|
||||
"service": "openclaw-enhanced",
|
||||
"port": 8014,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"python_version": "3.13.5",
|
||||
"system": {
|
||||
"cpu_percent": psutil.cpu_percent(),
|
||||
|
||||
@@ -6,7 +6,7 @@ Provides health monitoring for agent orchestration, edge computing, and ecosyste
|
||||
"""
|
||||
|
||||
import sys
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import psutil
|
||||
@@ -43,7 +43,7 @@ async def openclaw_enhanced_health(session: Annotated[Session, Depends(get_sessi
|
||||
"status": "healthy" if edge_status["available"] else "degraded",
|
||||
"service": "openclaw-enhanced",
|
||||
"port": 8007,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
|
||||
# System metrics
|
||||
"system": {
|
||||
@@ -95,7 +95,7 @@ async def openclaw_enhanced_health(session: Annotated[Session, Depends(get_sessi
|
||||
"status": "unhealthy",
|
||||
"service": "openclaw-enhanced",
|
||||
"port": 8007,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Health check failed",
|
||||
}
|
||||
|
||||
@@ -162,7 +162,7 @@ async def openclaw_enhanced_deep_health(session: Annotated[Session, Depends(get_
|
||||
"status": "healthy" if edge_status["available"] else "degraded",
|
||||
"service": "openclaw-enhanced",
|
||||
"port": 8007,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"feature_tests": feature_tests,
|
||||
"edge_computing": edge_status,
|
||||
"overall_health": (
|
||||
@@ -178,7 +178,7 @@ async def openclaw_enhanced_deep_health(session: Annotated[Session, Depends(get_
|
||||
"status": "unhealthy",
|
||||
"service": "openclaw-enhanced",
|
||||
"port": 8007,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"error": "Deep health check failed",
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Partner Router - Third-party integration management
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
@@ -91,7 +91,7 @@ async def register_partner(partner: PartnerRegister, session: Annotated[Session,
|
||||
"api_key": api_key,
|
||||
"api_secret_hash": hashlib.sha256(api_secret.encode()).hexdigest(),
|
||||
"rate_limit": rate_limits.get(partner.integration_type, rate_limits["other"]),
|
||||
"created_at": datetime.now(datetime.UTC),
|
||||
"created_at": datetime.now(timezone.utc),
|
||||
"status": "active",
|
||||
}
|
||||
|
||||
@@ -162,7 +162,7 @@ async def create_webhook(
|
||||
"events": webhook.events,
|
||||
"secret": webhook.secret,
|
||||
"status": "active",
|
||||
"created_at": datetime.now(datetime.UTC),
|
||||
"created_at": datetime.now(timezone.utc),
|
||||
}
|
||||
|
||||
return WebhookResponse(
|
||||
|
||||
@@ -7,7 +7,7 @@ Reputation Management API Endpoints
|
||||
REST API for agent reputation, trust scores, and economic profiles
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
@@ -272,7 +272,7 @@ async def get_trust_score_breakdown(
|
||||
security_score=security_score,
|
||||
economic_score=economic_score,
|
||||
reputation_level=reputation_level.value,
|
||||
calculated_at=datetime.now(datetime.UTC).isoformat()
|
||||
calculated_at=datetime.now(timezone.utc).isoformat()
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
@@ -348,7 +348,7 @@ async def get_reputation_metrics(
|
||||
]
|
||||
|
||||
# Recent activity (last 24 hours)
|
||||
recent_cutoff = datetime.now(datetime.UTC) - timedelta(days=1)
|
||||
recent_cutoff = datetime.now(timezone.utc) - timedelta(days=1)
|
||||
recent_events = session.execute(
|
||||
select(func.count(ReputationEvent.id)).where(
|
||||
ReputationEvent.occurred_at >= recent_cutoff
|
||||
@@ -474,7 +474,7 @@ async def update_specialization(
|
||||
raise HTTPException(status_code=404, detail="Reputation profile not found")
|
||||
|
||||
reputation.specialization_tags = specialization_tags
|
||||
reputation.updated_at = datetime.now(datetime.UTC)
|
||||
reputation.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
session.commit()
|
||||
session.refresh(reputation)
|
||||
@@ -510,7 +510,7 @@ async def update_region(
|
||||
raise HTTPException(status_code=404, detail="Reputation profile not found")
|
||||
|
||||
reputation.geographic_region = region
|
||||
reputation.updated_at = datetime.now(datetime.UTC)
|
||||
reputation.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
session.commit()
|
||||
session.refresh(reputation)
|
||||
@@ -568,7 +568,7 @@ async def get_cross_chain_reputation(
|
||||
"last_updated": reputation.updated_at.isoformat()
|
||||
}
|
||||
},
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat()
|
||||
"last_updated": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
@@ -601,7 +601,7 @@ async def sync_cross_chain_reputation(
|
||||
"agent_id": agent_id,
|
||||
"sync_status": "completed",
|
||||
"chains_synced": [1],
|
||||
"sync_timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"sync_timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"message": "Cross-chain reputation synchronized successfully"
|
||||
}
|
||||
|
||||
@@ -651,7 +651,7 @@ async def get_cross_chain_leaderboard(
|
||||
"total_count": len(agents),
|
||||
"limit": limit,
|
||||
"min_score": min_score,
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat()
|
||||
"last_updated": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -691,7 +691,7 @@ async def submit_cross_chain_event(
|
||||
new_score = max(0, min(1000, old_score + (impact * 1000)))
|
||||
|
||||
reputation.trust_score = new_score
|
||||
reputation.updated_at = datetime.now(datetime.UTC)
|
||||
reputation.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
# Update reputation level if needed
|
||||
if new_score >= 900:
|
||||
@@ -708,13 +708,13 @@ async def submit_cross_chain_event(
|
||||
session.commit()
|
||||
|
||||
return {
|
||||
"event_id": f"event_{datetime.now(datetime.UTC).strftime('%Y%m%d%H%M%S')}",
|
||||
"event_id": f"event_{datetime.now(timezone.utc).strftime('%Y%m%d%H%M%S')}",
|
||||
"agent_id": agent_id,
|
||||
"event_type": event_data['event_type'],
|
||||
"impact_score": impact,
|
||||
"old_score": old_score / 1000.0,
|
||||
"new_score": new_score / 1000.0,
|
||||
"processed_at": datetime.now(datetime.UTC).isoformat()
|
||||
"processed_at": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
@@ -785,7 +785,7 @@ async def get_cross_chain_analytics(
|
||||
"average_consistency_score": 1.0,
|
||||
"chain_diversity_score": 0.0 # No cross-chain diversity yet
|
||||
},
|
||||
"generated_at": datetime.now(datetime.UTC).isoformat()
|
||||
"generated_at": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
|
||||
@@ -7,7 +7,7 @@ Reward System API Endpoints
|
||||
REST API for agent rewards, incentives, and performance-based earnings
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
@@ -368,13 +368,13 @@ async def get_reward_leaderboard(
|
||||
try:
|
||||
# Calculate date range based on period
|
||||
if period == "daily":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=1)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=1)
|
||||
elif period == "weekly":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=7)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=7)
|
||||
elif period == "monthly":
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=30)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=30)
|
||||
else:
|
||||
start_date = datetime.now(datetime.UTC) - timedelta(days=7)
|
||||
start_date = datetime.now(timezone.utc) - timedelta(days=7)
|
||||
|
||||
# Query reward profiles
|
||||
query = select(AgentRewardProfile).where(
|
||||
|
||||
@@ -5,14 +5,14 @@ Staking Management API
|
||||
REST API for AI agent staking system with reputation-based yield farming
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field, validator
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..app_logging import get_logger
|
||||
from aitbc import get_logger
|
||||
from ..auth import get_current_user
|
||||
from ..domain.bounty import AgentMetrics, AgentStake, EcosystemMetrics, PerformanceTier, StakeStatus, StakingPool
|
||||
from ..services.blockchain_service import BlockchainService
|
||||
@@ -303,7 +303,7 @@ async def unbond_stake(
|
||||
if stake.status != StakeStatus.ACTIVE:
|
||||
raise HTTPException(status_code=400, detail="Stake is not active")
|
||||
|
||||
if datetime.now(datetime.UTC) < stake.end_time:
|
||||
if datetime.now(timezone.utc) < stake.end_time:
|
||||
raise HTTPException(status_code=400, detail="Lock period has not ended")
|
||||
|
||||
# Initiate unbonding
|
||||
|
||||
@@ -7,7 +7,7 @@ P2P Trading Protocol API Endpoints
|
||||
REST API for agent-to-agent trading, matching, negotiation, and settlement
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
@@ -634,9 +634,9 @@ async def get_trading_analytics(
|
||||
end_dt = datetime.fromisoformat(end_date)
|
||||
|
||||
if not start_dt:
|
||||
start_dt = datetime.now(datetime.UTC) - timedelta(days=30)
|
||||
start_dt = datetime.now(timezone.utc) - timedelta(days=30)
|
||||
if not end_dt:
|
||||
end_dt = datetime.now(datetime.UTC)
|
||||
end_dt = datetime.now(timezone.utc)
|
||||
|
||||
# Get analytics data (mock implementation)
|
||||
# In real implementation, this would query TradingAnalytics table
|
||||
|
||||
@@ -9,7 +9,7 @@ User Management Router for AITBC
|
||||
import hashlib
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
@@ -70,8 +70,8 @@ async def register_user(user_data: UserCreate, session: Annotated[Session, Depen
|
||||
id=str(uuid.uuid4()),
|
||||
email=user_data.email,
|
||||
username=user_data.username,
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
last_login=datetime.now(datetime.UTC),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
last_login=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
session.add(user)
|
||||
@@ -79,7 +79,7 @@ async def register_user(user_data: UserCreate, session: Annotated[Session, Depen
|
||||
session.refresh(user)
|
||||
|
||||
# Create wallet for user
|
||||
wallet = Wallet(user_id=user.id, address=f"aitbc_{user.id[:8]}", balance=0.0, created_at=datetime.now(datetime.UTC))
|
||||
wallet = Wallet(user_id=user.id, address=f"aitbc_{user.id[:8]}", balance=0.0, created_at=datetime.now(timezone.utc))
|
||||
|
||||
session.add(wallet)
|
||||
session.commit()
|
||||
@@ -112,8 +112,8 @@ async def login_user(login_data: UserLogin, session: Annotated[Session, Depends(
|
||||
id=str(uuid.uuid4()),
|
||||
email=f"{login_data.wallet_address}@aitbc.local",
|
||||
username=f"user_{login_data.wallet_address[-8:]}_{str(uuid.uuid4())[:8]}",
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
last_login=datetime.now(datetime.UTC),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
last_login=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
session.add(user)
|
||||
@@ -121,14 +121,14 @@ async def login_user(login_data: UserLogin, session: Annotated[Session, Depends(
|
||||
session.refresh(user)
|
||||
|
||||
# Create wallet
|
||||
wallet = Wallet(user_id=user.id, address=login_data.wallet_address, balance=0.0, created_at=datetime.now(datetime.UTC))
|
||||
wallet = Wallet(user_id=user.id, address=login_data.wallet_address, balance=0.0, created_at=datetime.now(timezone.utc))
|
||||
|
||||
session.add(wallet)
|
||||
session.commit()
|
||||
else:
|
||||
# Update last login
|
||||
user = session.execute(select(User).where(User.id == wallet.user_id)).first()
|
||||
user.last_login = datetime.now(datetime.UTC)
|
||||
user.last_login = datetime.now(timezone.utc)
|
||||
session.commit()
|
||||
|
||||
# Create session token
|
||||
|
||||
@@ -8,7 +8,7 @@ ZK Applications Router - Privacy-preserving features for AITBC
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
@@ -67,7 +67,7 @@ async def create_identity_commitment(
|
||||
commitment_input = f"{user.email}:{salt}"
|
||||
commitment = hashlib.sha256(commitment_input.encode()).hexdigest()
|
||||
|
||||
return {"commitment": commitment, "salt": salt, "user_id": user.user_id, "created_at": datetime.now(datetime.UTC).isoformat()}
|
||||
return {"commitment": commitment, "salt": salt, "user_id": user.user_id, "created_at": datetime.now(timezone.utc).isoformat()}
|
||||
|
||||
|
||||
@router.post("/zk/membership/verify")
|
||||
@@ -104,7 +104,7 @@ async def verify_group_membership(
|
||||
"group_id": request.group_id,
|
||||
"verified": True,
|
||||
"nullifier": request.nullifier,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
|
||||
@@ -127,7 +127,7 @@ async def submit_private_bid(request: PrivateBidRequest, session: Annotated[Sess
|
||||
"auction_id": request.auction_id,
|
||||
"commitment": request.bid_commitment,
|
||||
"status": "submitted",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
|
||||
@@ -172,7 +172,7 @@ async def verify_computation_proof(
|
||||
"result_hash": request.result_hash,
|
||||
"public_inputs": request.public_inputs,
|
||||
"verification_key": "demo_vk_12345",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
return verification_result
|
||||
@@ -197,7 +197,7 @@ async def create_private_receipt(
|
||||
"user_address": user_address,
|
||||
"commitment": commitment,
|
||||
"privacy_level": privacy_level,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"verified": True,
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
Access control service for confidential transactions
|
||||
"""
|
||||
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
@@ -216,7 +216,7 @@ class AccessController:
|
||||
|
||||
def _is_business_hours(self) -> bool:
|
||||
"""Check if current time is within business hours"""
|
||||
now = datetime.now(datetime.UTC)
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
# Monday-Friday, 9 AM - 5 PM UTC
|
||||
if now.weekday() >= 5: # Weekend
|
||||
@@ -229,7 +229,7 @@ class AccessController:
|
||||
|
||||
def _check_retention_period(self, transaction: dict, role: str | None) -> bool:
|
||||
"""Check if data is within retention period for role"""
|
||||
transaction_date = transaction.get("timestamp", datetime.now(datetime.UTC))
|
||||
transaction_date = transaction.get("timestamp", datetime.now(timezone.utc))
|
||||
|
||||
# Different retention periods for different roles
|
||||
if role == "regulator":
|
||||
@@ -243,7 +243,7 @@ class AccessController:
|
||||
|
||||
expiry_date = transaction_date + timedelta(days=retention_days)
|
||||
|
||||
return datetime.now(datetime.UTC) <= expiry_date
|
||||
return datetime.now(timezone.utc) <= expiry_date
|
||||
|
||||
def _get_participant_info(self, participant_id: str) -> dict | None:
|
||||
"""Get participant information"""
|
||||
@@ -274,8 +274,8 @@ class AccessController:
|
||||
"transaction_miner_id": "miner-789",
|
||||
"miner_id": "miner-789",
|
||||
"purpose": "settlement",
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"expires_at": (datetime.now(datetime.UTC) + timedelta(hours=1)).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
"expires_at": (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(),
|
||||
"metadata": {"job_id": "job-123", "amount": "1000", "currency": "AITBC"},
|
||||
}
|
||||
if transaction_id.startswith("ctx-"):
|
||||
@@ -286,8 +286,8 @@ class AccessController:
|
||||
"transaction_miner_id": "miner-456",
|
||||
"miner_id": "miner-456",
|
||||
"purpose": "settlement",
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"expires_at": (datetime.now(datetime.UTC) + timedelta(hours=1)).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
"expires_at": (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(),
|
||||
"metadata": {"job_id": "job-456", "amount": "1000", "currency": "AITBC"},
|
||||
}
|
||||
else:
|
||||
@@ -301,7 +301,7 @@ class AccessController:
|
||||
"""Get cached access result"""
|
||||
if cache_key in self._access_cache:
|
||||
cached = self._access_cache[cache_key]
|
||||
if datetime.now(datetime.UTC) - cached["timestamp"] < self._cache_ttl:
|
||||
if datetime.now(timezone.utc) - cached["timestamp"] < self._cache_ttl:
|
||||
return cached
|
||||
else:
|
||||
del self._access_cache[cache_key]
|
||||
@@ -309,20 +309,20 @@ class AccessController:
|
||||
|
||||
def _cache_result(self, cache_key: str, allowed: bool):
|
||||
"""Cache access result"""
|
||||
self._access_cache[cache_key] = {"allowed": allowed, "timestamp": datetime.now(datetime.UTC)}
|
||||
self._access_cache[cache_key] = {"allowed": allowed, "timestamp": datetime.now(timezone.utc)}
|
||||
|
||||
def create_access_policy(
|
||||
self, name: str, participants: list[str], conditions: dict[str, Any], access_level: AccessLevel
|
||||
) -> str:
|
||||
"""Create a new access policy"""
|
||||
policy_id = f"policy_{datetime.now(datetime.UTC).timestamp()}"
|
||||
policy_id = f"policy_{datetime.now(timezone.utc).timestamp()}"
|
||||
|
||||
policy = {
|
||||
"participants": participants,
|
||||
"conditions": conditions,
|
||||
"access_level": access_level,
|
||||
"time_restrictions": conditions.get("time_restrictions"),
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
self.policy_store.add_policy(policy_id, policy)
|
||||
|
||||
@@ -11,7 +11,7 @@ Reinforcement learning frameworks for agent self-improvement
|
||||
from aitbc import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
@@ -380,7 +380,7 @@ class AdaptiveLearningService:
|
||||
"action_space_size": len(environment.action_space),
|
||||
"safety_constraints": len(environment.safety_constraints),
|
||||
"max_episodes": environment.max_episodes,
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -403,7 +403,7 @@ class AdaptiveLearningService:
|
||||
"discount_factor": agent.discount_factor,
|
||||
"exploration_rate": agent.exploration_rate,
|
||||
"status": "created",
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -427,7 +427,7 @@ class AdaptiveLearningService:
|
||||
self.training_sessions[session_id] = {
|
||||
"agent_id": agent_id,
|
||||
"environment_id": environment_id,
|
||||
"start_time": datetime.now(datetime.UTC),
|
||||
"start_time": datetime.now(timezone.utc),
|
||||
"config": training_config,
|
||||
"status": "running",
|
||||
}
|
||||
@@ -438,7 +438,7 @@ class AdaptiveLearningService:
|
||||
|
||||
# Update session
|
||||
self.training_sessions[session_id].update(
|
||||
{"status": "completed", "end_time": datetime.now(datetime.UTC), "results": training_results}
|
||||
{"status": "completed", "end_time": datetime.now(timezone.utc), "results": training_results}
|
||||
)
|
||||
|
||||
return {
|
||||
@@ -626,7 +626,7 @@ class AdaptiveLearningService:
|
||||
"performance_metrics": agent.performance_metrics,
|
||||
"current_exploration_rate": agent.exploration_rate,
|
||||
"policy_size": len(agent.q_table) if hasattr(agent, "q_table") else "neural_network",
|
||||
"last_updated": datetime.now(datetime.UTC).isoformat(),
|
||||
"last_updated": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
async def evaluate_agent(self, agent_id: str, environment_id: str, evaluation_config: dict[str, Any]) -> dict[str, Any]:
|
||||
@@ -678,7 +678,7 @@ class AdaptiveLearningService:
|
||||
"min_reward": float(min(evaluation_rewards)),
|
||||
"average_episode_length": float(np.mean(evaluation_lengths)),
|
||||
"success_rate": sum(1 for r in evaluation_rewards if r > 0) / len(evaluation_rewards),
|
||||
"evaluation_timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"evaluation_timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
async def create_reward_function(self, reward_id: str, reward_type: RewardType, config: dict[str, Any]) -> dict[str, Any]:
|
||||
@@ -690,7 +690,7 @@ class AdaptiveLearningService:
|
||||
"config": config,
|
||||
"parameters": config.get("parameters", {}),
|
||||
"weights": config.get("weights", {}),
|
||||
"created_at": datetime.now(datetime.UTC).isoformat(),
|
||||
"created_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
self.reward_functions[reward_id] = reward_function
|
||||
|
||||
@@ -7,7 +7,7 @@ Port: 8009
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
@@ -120,7 +120,7 @@ async def health_check():
|
||||
"""Health check endpoint"""
|
||||
return {
|
||||
"status": "healthy",
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"gpu_available": torch.cuda.is_available(),
|
||||
"services": {"rl_engine": "operational", "fusion_engine": "operational", "advanced_learning": "operational"},
|
||||
}
|
||||
@@ -193,7 +193,7 @@ async def process_multi_modal_fusion(request: MultiModalFusionRequest):
|
||||
"""Process multi-modal fusion"""
|
||||
|
||||
try:
|
||||
start_time = datetime.now(datetime.UTC)
|
||||
start_time = datetime.now(timezone.utc)
|
||||
|
||||
# Simulate database session
|
||||
|
||||
@@ -213,13 +213,13 @@ async def process_multi_modal_fusion(request: MultiModalFusionRequest):
|
||||
modal_data=request.modal_data, performance_requirements=request.fusion_config or {}
|
||||
)
|
||||
|
||||
processing_time = (datetime.now(datetime.UTC) - start_time).total_seconds() * 1000
|
||||
processing_time = (datetime.now(timezone.utc) - start_time).total_seconds() * 1000
|
||||
|
||||
return {
|
||||
"fusion_result": result,
|
||||
"processing_time_ms": processing_time,
|
||||
"strategy_used": request.fusion_strategy,
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
@@ -243,7 +243,7 @@ async def optimize_gpu_processing(request: GPUOptimizationRequest):
|
||||
modality_features=request.modality_features, attention_config=request.attention_config
|
||||
)
|
||||
|
||||
return {"optimization_result": result, "timestamp": datetime.now(datetime.UTC).isoformat()}
|
||||
return {"optimization_result": result, "timestamp": datetime.now(timezone.utc).isoformat()}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"GPU optimization failed: {e}")
|
||||
@@ -255,7 +255,7 @@ async def advanced_ai_processing(request: AdvancedAIRequest):
|
||||
"""Unified advanced AI processing endpoint"""
|
||||
|
||||
try:
|
||||
datetime.now(datetime.UTC)
|
||||
datetime.now(timezone.utc)
|
||||
|
||||
if request.request_type == "rl_training":
|
||||
# Convert to RL training request
|
||||
@@ -335,7 +335,7 @@ async def get_performance_metrics():
|
||||
}
|
||||
|
||||
return {
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"gpu_metrics": gpu_metrics,
|
||||
"service_metrics": service_metrics,
|
||||
"system_health": "operational",
|
||||
|
||||
@@ -7,7 +7,7 @@ Real-time analytics dashboard, market insights, and performance metrics
|
||||
import asyncio
|
||||
from collections import defaultdict, deque
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ from aitbc import get_logger
|
||||
logger = get_logger(__name__)
|
||||
import json
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
@@ -231,8 +231,8 @@ class AdvancedLearningService:
|
||||
performance_metrics={},
|
||||
training_data_size=0,
|
||||
validation_data_size=0,
|
||||
created_at=datetime.now(datetime.UTC),
|
||||
last_updated=datetime.now(datetime.UTC),
|
||||
created_at=datetime.now(timezone.utc),
|
||||
last_updated=datetime.now(timezone.utc),
|
||||
status=LearningStatus.INITIALIZING,
|
||||
)
|
||||
|
||||
@@ -251,7 +251,7 @@ class AdvancedLearningService:
|
||||
computation_efficiency=0.0,
|
||||
learning_rate=self.default_learning_rate,
|
||||
convergence_speed=0.0,
|
||||
last_evaluation=datetime.now(datetime.UTC),
|
||||
last_evaluation=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
logger.info(f"Model created: {model_id} for agent {agent_id}")
|
||||
@@ -298,7 +298,7 @@ class AdvancedLearningService:
|
||||
model_id=model_id,
|
||||
agent_id=model.agent_id,
|
||||
learning_type=model.learning_type,
|
||||
start_time=datetime.now(datetime.UTC),
|
||||
start_time=datetime.now(timezone.utc),
|
||||
end_time=None,
|
||||
status=LearningStatus.INITIALIZING,
|
||||
training_data=training_data,
|
||||
@@ -316,7 +316,7 @@ class AdvancedLearningService:
|
||||
|
||||
# Update model status
|
||||
model.status = LearningStatus.TRAINING
|
||||
model.last_updated = datetime.now(datetime.UTC)
|
||||
model.last_updated = datetime.now(timezone.utc)
|
||||
|
||||
# Start training
|
||||
asyncio.create_task(self._execute_learning_session(session_id))
|
||||
@@ -349,7 +349,7 @@ class AdvancedLearningService:
|
||||
model_id=model.id,
|
||||
agent_id=agent_id,
|
||||
learning_type=LearningType.META_LEARNING,
|
||||
start_time=datetime.now(datetime.UTC),
|
||||
start_time=datetime.now(timezone.utc),
|
||||
end_time=None,
|
||||
status=LearningStatus.TRAINING,
|
||||
training_data=meta_data["training"],
|
||||
@@ -400,7 +400,7 @@ class AdvancedLearningService:
|
||||
model_id=model_id,
|
||||
agent_id="federated",
|
||||
learning_type=LearningType.FEDERATED,
|
||||
start_time=datetime.now(datetime.UTC),
|
||||
start_time=datetime.now(timezone.utc),
|
||||
end_time=None,
|
||||
status=LearningStatus.TRAINING,
|
||||
training_data=[],
|
||||
@@ -443,16 +443,16 @@ class AdvancedLearningService:
|
||||
if model.status != LearningStatus.ACTIVE:
|
||||
raise ValueError(f"Model {model_id} not active")
|
||||
|
||||
start_time = datetime.now(datetime.UTC)
|
||||
start_time = datetime.now(timezone.utc)
|
||||
|
||||
# Simulate inference
|
||||
prediction = await self._simulate_inference(model, input_data)
|
||||
|
||||
# Update analytics
|
||||
inference_time = (datetime.now(datetime.UTC) - start_time).total_seconds()
|
||||
inference_time = (datetime.now(timezone.utc) - start_time).total_seconds()
|
||||
analytics = self.learning_analytics[model_id]
|
||||
analytics.total_inference_time += inference_time
|
||||
analytics.last_evaluation = datetime.now(datetime.UTC)
|
||||
analytics.last_evaluation = datetime.now(timezone.utc)
|
||||
|
||||
logger.info(f"Prediction made with model {model_id}")
|
||||
return prediction
|
||||
@@ -480,7 +480,7 @@ class AdvancedLearningService:
|
||||
|
||||
# Update model performance
|
||||
model.accuracy = adaptation_results.get("accuracy", model.accuracy)
|
||||
model.last_updated = datetime.now(datetime.UTC)
|
||||
model.last_updated = datetime.now(timezone.utc)
|
||||
|
||||
# Update analytics
|
||||
analytics = self.learning_analytics[model_id]
|
||||
@@ -573,7 +573,7 @@ class AdvancedLearningService:
|
||||
# Update model
|
||||
model.accuracy = optimization_results.get("accuracy", model.accuracy)
|
||||
model.inference_time = optimization_results.get("inference_time", model.inference_time)
|
||||
model.last_updated = datetime.now(datetime.UTC)
|
||||
model.last_updated = datetime.now(timezone.utc)
|
||||
|
||||
logger.info(f"Model optimized: {model_id}")
|
||||
return True
|
||||
@@ -625,12 +625,12 @@ class AdvancedLearningService:
|
||||
model.recall = np.random.uniform(0.7, 0.95)
|
||||
model.f1_score = np.random.uniform(0.7, 0.95)
|
||||
model.loss = session.results.get(f"epoch_{session.iterations}", {}).get("loss", 0.1)
|
||||
model.training_time = (datetime.now(datetime.UTC) - session.start_time).total_seconds()
|
||||
model.training_time = (datetime.now(timezone.utc) - session.start_time).total_seconds()
|
||||
model.inference_time = np.random.uniform(0.01, 0.1)
|
||||
model.status = LearningStatus.ACTIVE
|
||||
model.last_updated = datetime.now(datetime.UTC)
|
||||
model.last_updated = datetime.now(timezone.utc)
|
||||
|
||||
session.end_time = datetime.now(datetime.UTC)
|
||||
session.end_time = datetime.now(timezone.utc)
|
||||
session.status = LearningStatus.COMPLETED
|
||||
|
||||
# Update analytics
|
||||
@@ -673,9 +673,9 @@ class AdvancedLearningService:
|
||||
# Update model with meta-learning results
|
||||
model.accuracy = np.random.uniform(0.8, 0.98)
|
||||
model.status = LearningStatus.ACTIVE
|
||||
model.last_updated = datetime.now(datetime.UTC)
|
||||
model.last_updated = datetime.now(timezone.utc)
|
||||
|
||||
session.end_time = datetime.now(datetime.UTC)
|
||||
session.end_time = datetime.now(timezone.utc)
|
||||
session.status = LearningStatus.COMPLETED
|
||||
|
||||
logger.info(f"Meta-learning completed: {session_id}")
|
||||
@@ -713,9 +713,9 @@ class AdvancedLearningService:
|
||||
# Update model
|
||||
model.accuracy = np.random.uniform(0.75, 0.92)
|
||||
model.status = LearningStatus.ACTIVE
|
||||
model.last_updated = datetime.now(datetime.UTC)
|
||||
model.last_updated = datetime.now(timezone.utc)
|
||||
|
||||
session.end_time = datetime.now(datetime.UTC)
|
||||
session.end_time = datetime.now(timezone.utc)
|
||||
session.status = LearningStatus.COMPLETED
|
||||
|
||||
logger.info(f"Federated learning completed: {session_id}")
|
||||
@@ -811,7 +811,7 @@ class AdvancedLearningService:
|
||||
|
||||
while True:
|
||||
try:
|
||||
current_time = datetime.now(datetime.UTC)
|
||||
current_time = datetime.now(timezone.utc)
|
||||
|
||||
for session_id, session in self.learning_sessions.items():
|
||||
if session.status == LearningStatus.TRAINING:
|
||||
@@ -862,7 +862,7 @@ class AdvancedLearningService:
|
||||
|
||||
while True:
|
||||
try:
|
||||
current_time = datetime.now(datetime.UTC)
|
||||
current_time = datetime.now(timezone.utc)
|
||||
inactive_sessions = []
|
||||
|
||||
for session_id, session in self.learning_sessions.items():
|
||||
@@ -905,7 +905,7 @@ class AdvancedLearningService:
|
||||
"models": {k: asdict(v) for k, v in self.models.items()},
|
||||
"sessions": {k: asdict(v) for k, v in self.learning_sessions.items()},
|
||||
"analytics": {k: asdict(v) for k, v in self.learning_analytics.items()},
|
||||
"export_timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"export_timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
if format.lower() == "json":
|
||||
|
||||
@@ -5,7 +5,7 @@ Phase 5.1: Advanced AI Capabilities Enhancement
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -616,7 +616,7 @@ class AdvancedReinforcementLearningEngine:
|
||||
rl_config.success_rate_history = training_results["success_rate_history"]
|
||||
rl_config.convergence_episode = training_results["convergence_episode"]
|
||||
rl_config.status = "ready"
|
||||
rl_config.trained_at = datetime.now(datetime.UTC)
|
||||
rl_config.trained_at = datetime.now(timezone.utc)
|
||||
rl_config.training_progress = 1.0
|
||||
|
||||
session.commit()
|
||||
@@ -1329,7 +1329,7 @@ class MarketplaceStrategyOptimizer:
|
||||
rl_config.deployment_performance = deployment_performance
|
||||
rl_config.deployment_count += 1
|
||||
rl_config.status = "deployed"
|
||||
rl_config.deployed_at = datetime.now(datetime.UTC)
|
||||
rl_config.deployed_at = datetime.now(timezone.utc)
|
||||
|
||||
session.commit()
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ logger = get_logger(__name__)
|
||||
import hashlib
|
||||
import json
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
@@ -199,7 +199,7 @@ class AgentCommunicationService:
|
||||
messages_sent=0,
|
||||
messages_received=0,
|
||||
active_channels=0,
|
||||
last_activity=datetime.now(datetime.UTC),
|
||||
last_activity=datetime.now(timezone.utc),
|
||||
average_response_time=0.0,
|
||||
delivery_rate=0.0,
|
||||
)
|
||||
@@ -346,11 +346,11 @@ class AgentCommunicationService:
|
||||
encryption_key=encryption_key,
|
||||
encryption_type=encryption_type,
|
||||
size=len(content_bytes),
|
||||
timestamp=datetime.now(datetime.UTC),
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
status=MessageStatus.PENDING,
|
||||
price=price,
|
||||
metadata=metadata or {},
|
||||
expires_at=datetime.now(datetime.UTC) + timedelta(seconds=self.message_timeout),
|
||||
expires_at=datetime.now(timezone.utc) + timedelta(seconds=self.message_timeout),
|
||||
reply_to=reply_to,
|
||||
thread_id=thread_id,
|
||||
)
|
||||
@@ -395,7 +395,7 @@ class AgentCommunicationService:
|
||||
raise ValueError(f"Message {message_id} not pending")
|
||||
|
||||
message.status = MessageStatus.DELIVERED
|
||||
message.delivery_timestamp = datetime.now(datetime.UTC)
|
||||
message.delivery_timestamp = datetime.now(timezone.utc)
|
||||
|
||||
# Update stats
|
||||
await self._update_message_stats(message.sender, message.recipient, "delivered")
|
||||
@@ -426,7 +426,7 @@ class AgentCommunicationService:
|
||||
|
||||
# Mark as read
|
||||
message.status = MessageStatus.READ
|
||||
message.read_timestamp = datetime.now(datetime.UTC)
|
||||
message.read_timestamp = datetime.now(timezone.utc)
|
||||
|
||||
# Update stats
|
||||
await self._update_message_stats(message.sender, message.recipient, "read")
|
||||
@@ -495,8 +495,8 @@ class AgentCommunicationService:
|
||||
agent2=agent2,
|
||||
channel_type=channel_type,
|
||||
is_active=True,
|
||||
created_timestamp=datetime.now(datetime.UTC),
|
||||
last_activity=datetime.now(datetime.UTC),
|
||||
created_timestamp=datetime.now(timezone.utc),
|
||||
last_activity=datetime.now(timezone.utc),
|
||||
message_count=0,
|
||||
participants=[agent1, agent2],
|
||||
encryption_enabled=encryption_enabled,
|
||||
@@ -814,17 +814,17 @@ class AgentCommunicationService:
|
||||
if sender in self.communication_stats:
|
||||
self.communication_stats[sender].total_messages += 1
|
||||
self.communication_stats[sender].messages_sent += 1
|
||||
self.communication_stats[sender].last_activity = datetime.now(datetime.UTC)
|
||||
self.communication_stats[sender].last_activity = datetime.now(timezone.utc)
|
||||
|
||||
elif action == "delivered":
|
||||
if recipient in self.communication_stats:
|
||||
self.communication_stats[recipient].total_messages += 1
|
||||
self.communication_stats[recipient].messages_received += 1
|
||||
self.communication_stats[recipient].last_activity = datetime.now(datetime.UTC)
|
||||
self.communication_stats[recipient].last_activity = datetime.now(timezone.utc)
|
||||
|
||||
elif action == "read":
|
||||
if recipient in self.communication_stats:
|
||||
self.communication_stats[recipient].last_activity = datetime.now(datetime.UTC)
|
||||
self.communication_stats[recipient].last_activity = datetime.now(timezone.utc)
|
||||
|
||||
async def _process_message_queue(self):
|
||||
"""Process message queue for delivery"""
|
||||
@@ -848,7 +848,7 @@ class AgentCommunicationService:
|
||||
|
||||
while True:
|
||||
try:
|
||||
current_time = datetime.now(datetime.UTC)
|
||||
current_time = datetime.now(timezone.utc)
|
||||
expired_messages = []
|
||||
|
||||
for message_id, message in self.messages.items():
|
||||
@@ -875,7 +875,7 @@ class AgentCommunicationService:
|
||||
|
||||
while True:
|
||||
try:
|
||||
current_time = datetime.now(datetime.UTC)
|
||||
current_time = datetime.now(timezone.utc)
|
||||
inactive_channels = []
|
||||
|
||||
for channel_id, channel in self.channels.items():
|
||||
@@ -958,7 +958,7 @@ class AgentCommunicationService:
|
||||
"messages": {k: asdict(v) for k, v in self.messages.items()},
|
||||
"channels": {k: asdict(v) for k, v in self.channels.items()},
|
||||
"templates": {k: asdict(v) for k, v in self.message_templates.items()},
|
||||
"export_timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"export_timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
||||
if format.lower() == "json":
|
||||
|
||||
@@ -6,7 +6,7 @@ Integrates agent orchestration with existing ML ZK proof system and provides dep
|
||||
from aitbc import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
from datetime import datetime, UTC
|
||||
from datetime import datetime, timezone
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -104,8 +104,8 @@ class AgentDeploymentConfig(SQLModel, table=True):
|
||||
last_health_check: datetime | None = Field(default=None)
|
||||
|
||||
# Metadata
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class AgentDeploymentInstance(SQLModel, table=True):
|
||||
@@ -149,8 +149,8 @@ class AgentDeploymentInstance(SQLModel, table=True):
|
||||
health_check_history: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON))
|
||||
|
||||
# Timestamps
|
||||
created_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
updated_at: datetime = Field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class AgentIntegrationManager:
|
||||
@@ -380,7 +380,7 @@ class AgentDeploymentManager:
|
||||
|
||||
# Update deployment status
|
||||
config.status = DeploymentStatus.DEPLOYING
|
||||
config.deployment_time = datetime.now(datetime.UTC)
|
||||
config.deployment_time = datetime.now(timezone.utc)
|
||||
self.session.commit()
|
||||
|
||||
deployment_result = {
|
||||
@@ -469,7 +469,7 @@ class AgentDeploymentManager:
|
||||
instance.status = DeploymentStatus.DEPLOYED
|
||||
instance.health_status = "healthy"
|
||||
instance.endpoint_url = f"http://localhost:{instance.port}"
|
||||
instance.last_health_check = datetime.now(datetime.UTC)
|
||||
instance.last_health_check = datetime.now(timezone.utc)
|
||||
|
||||
self.session.commit()
|
||||
|
||||
@@ -554,11 +554,11 @@ class AgentDeploymentManager:
|
||||
|
||||
# Update instance health status
|
||||
instance.health_status = health_status
|
||||
instance.last_health_check = datetime.now(datetime.UTC)
|
||||
instance.last_health_check = datetime.now(timezone.utc)
|
||||
|
||||
# Add to health check history
|
||||
health_check_record = {
|
||||
"timestamp": datetime.now(datetime.UTC).isoformat(),
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"status": health_status,
|
||||
"response_time": response_time,
|
||||
}
|
||||
@@ -582,7 +582,7 @@ class AgentDeploymentManager:
|
||||
|
||||
# Mark as unhealthy
|
||||
instance.health_status = "unhealthy"
|
||||
instance.last_health_check = datetime.now(datetime.UTC)
|
||||
instance.last_health_check = datetime.now(timezone.utc)
|
||||
instance.consecutive_failures += 1
|
||||
self.session.commit()
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ from aitbc import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, UTC, timedelta
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
@@ -58,7 +58,7 @@ class AgentCapability:
|
||||
performance_score: float # 0-1
|
||||
cost_per_hour: float
|
||||
reliability_score: float # 0-1
|
||||
last_updated: datetime = field(default_factory=datetime.now(datetime.UTC))
|
||||
last_updated: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -102,7 +102,7 @@ class OrchestrationPlan:
|
||||
resource_requirements: dict[ResourceType, int]
|
||||
estimated_cost: float
|
||||
confidence_score: float
|
||||
created_at: datetime = field(default_factory=datetime.now(datetime.UTC))
|
||||
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class AgentOrchestrator:
|
||||
@@ -360,7 +360,7 @@ class AgentOrchestrator:
|
||||
|
||||
# Process each execution stage
|
||||
for stage_idx, stage_sub_tasks in enumerate(decomposition.execution_plan):
|
||||
stage_start = datetime.now(datetime.UTC) + timedelta(hours=stage_idx * 2) # Estimate 2 hours per stage
|
||||
stage_start = datetime.now(timezone.utc) + timedelta(hours=stage_idx * 2) # Estimate 2 hours per stage
|
||||
|
||||
for sub_task_id in stage_sub_tasks:
|
||||
# Find sub-task
|
||||
@@ -368,7 +368,7 @@ class AgentOrchestrator:
|
||||
|
||||
# Create assignment (will be filled during execution)
|
||||
assignment = AgentAssignment(
|
||||
sub_task_id=sub_task_id, agent_id="", assigned_at=datetime.now(datetime.UTC) # Will be assigned during execution
|
||||
sub_task_id=sub_task_id, agent_id="", assigned_at=datetime.now(timezone.utc) # Will be assigned during execution
|
||||
)
|
||||
assignments.append(assignment)
|
||||
|
||||
@@ -469,7 +469,7 @@ class AgentOrchestrator:
|
||||
sub_task_id=sub_task_id,
|
||||
resource_type=ResourceType.GPU,
|
||||
allocated_amount=1,
|
||||
allocated_at=datetime.now(datetime.UTC),
|
||||
allocated_at=datetime.now(timezone.utc),
|
||||
expected_duration=requirements.estimated_duration,
|
||||
)
|
||||
allocations.append(gpu_allocation)
|
||||
@@ -480,7 +480,7 @@ class AgentOrchestrator:
|
||||
sub_task_id=sub_task_id,
|
||||
resource_type=ResourceType.MEMORY,
|
||||
allocated_amount=requirements.memory_requirement,
|
||||
allocated_at=datetime.now(datetime.UTC),
|
||||
allocated_at=datetime.now(timezone.utc),
|
||||
expected_duration=requirements.estimated_duration,
|
||||
)
|
||||
allocations.append(memory_allocation)
|
||||
@@ -568,7 +568,7 @@ class AgentOrchestrator:
|
||||
# For now, assume agents are healthy if they have recent updates
|
||||
|
||||
capability = self.agent_capabilities[agent_id]
|
||||
time_since_update = datetime.now(datetime.UTC) - capability.last_updated
|
||||
time_since_update = datetime.now(timezone.utc) - capability.last_updated
|
||||
|
||||
if time_since_update > timedelta(minutes=5):
|
||||
if self.agent_status[agent_id] != AgentStatus.OFFLINE:
|
||||
@@ -619,7 +619,7 @@ class AgentOrchestrator:
|
||||
|
||||
# Adjust for deadline
|
||||
if deadline:
|
||||
time_to_deadline = (deadline - datetime.now(datetime.UTC)).total_seconds() / 3600
|
||||
time_to_deadline = (deadline - datetime.now(timezone.utc)).total_seconds() / 3600
|
||||
if time_to_deadline < decomposition.estimated_total_duration:
|
||||
confidence *= 0.6
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user