refactor: replace SessionDep with explicit Annotated[Session, Depends(get_session)] across all routers

- Replace SessionDep type alias with explicit Annotated[Session, Depends(get_session)]
- Add missing imports for Session and Annotated types
- Update all endpoint function signatures to use explicit dependency annotation
- Apply changes consistently across all router files (admin, agent, marketplace, etc.)
- Add marketplace_gpu router to main.py router includes
This commit is contained in:
oib
2026-03-07 15:11:42 +01:00
parent a24e160b67
commit 93aae0edb3
61 changed files with 542 additions and 419 deletions

View File

@@ -1,3 +1,4 @@
from typing import Annotated
"""
Adaptive Learning Service Health Check Router
Provides health monitoring for reinforcement learning frameworks
@@ -10,7 +11,7 @@ import sys
import psutil
from typing import Dict, Any
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..services.adaptive_learning import AdaptiveLearningService
from ..logging import get_logger
@@ -19,7 +20,7 @@ router = APIRouter()
@router.get("/health", tags=["health"], summary="Adaptive Learning Service Health")
async def adaptive_learning_health(session: SessionDep) -> Dict[str, Any]:
async def adaptive_learning_health(session: Annotated[Session, Depends(get_session)] = Depends()) -> Dict[str, Any]:
"""
Health check for Adaptive Learning Service (Port 8005)
"""
@@ -104,7 +105,7 @@ async def adaptive_learning_health(session: SessionDep) -> Dict[str, Any]:
@router.get("/health/deep", tags=["health"], summary="Deep Adaptive Learning Service Health")
async def adaptive_learning_deep_health(session: SessionDep) -> Dict[str, Any]:
async def adaptive_learning_deep_health(session: Annotated[Session, Depends(get_session)] = Depends()) -> Dict[str, Any]:
"""
Deep health check with learning framework validation
"""

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, status, Request, Header
from sqlmodel import select
from slowapi import Limiter
@@ -6,7 +8,7 @@ from datetime import datetime
from ..deps import require_admin_key
from ..services import JobService, MinerService
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..utils.cache import cached, get_cache_config
from ..config import settings
from aitbc.logging import get_logger
@@ -46,7 +48,7 @@ async def test_key(
@cached(**get_cache_config("job_list")) # Cache admin stats for 1 minute
async def get_stats(
request: Request,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
api_key: str = Header(default=None, alias="X-Api-Key")
) -> dict[str, int]: # type: ignore[arg-type]
# Temporary debug: bypass dependency and validate directly
@@ -79,7 +81,7 @@ async def get_stats(
@router.get("/jobs", summary="List jobs")
async def list_jobs(session: SessionDep, admin_key: str = Depends(require_admin_key())) -> dict[str, list[dict]]: # type: ignore[arg-type]
async def list_jobs(session: Annotated[Session, Depends(get_session)] = Depends(), admin_key: str = Depends(require_admin_key())) -> dict[str, list[dict]]: # type: ignore[arg-type]
from ..domain import Job
jobs = session.execute(select(Job).order_by(Job.requested_at.desc()).limit(100)).all()
@@ -98,7 +100,7 @@ async def list_jobs(session: SessionDep, admin_key: str = Depends(require_admin_
@router.get("/miners", summary="List miners")
async def list_miners(session: SessionDep, admin_key: str = Depends(require_admin_key())) -> dict[str, list[dict]]: # type: ignore[arg-type]
async def list_miners(session: Annotated[Session, Depends(get_session)] = Depends(), admin_key: str = Depends(require_admin_key())) -> dict[str, list[dict]]: # type: ignore[arg-type]
miner_service = MinerService(session)
miners = [
{
@@ -121,7 +123,7 @@ async def list_miners(session: SessionDep, admin_key: str = Depends(require_admi
@router.get("/status", summary="Get system status", response_model=None)
async def get_system_status(
request: Request,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
admin_key: str = Depends(require_admin_key())
) -> dict[str, any]: # type: ignore[arg-type]
"""Get comprehensive system status for admin dashboard"""

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
Agent Creativity API Endpoints
REST API for agent creativity enhancement, ideation, and cross-domain synthesis
@@ -9,7 +11,7 @@ from fastapi import APIRouter, HTTPException, Depends, Query, Body
from pydantic import BaseModel, Field
from aitbc.logging import get_logger
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..services.creative_capabilities_service import (
CreativityEnhancementEngine, IdeationAlgorithm, CrossDomainCreativeIntegrator
)
@@ -66,7 +68,7 @@ class SynthesisRequest(BaseModel):
@router.post("/capabilities", response_model=CreativeCapabilityResponse)
async def create_creative_capability(
request: CreativeCapabilityCreate,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
):
"""Initialize a new creative capability for an agent"""
engine = CreativityEnhancementEngine()
@@ -90,7 +92,7 @@ async def create_creative_capability(
async def enhance_creativity(
capability_id: str,
request: EnhanceCreativityRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
):
"""Enhance a specific creative capability using specified algorithm"""
engine = CreativityEnhancementEngine()
@@ -113,7 +115,7 @@ async def enhance_creativity(
async def evaluate_creation(
capability_id: str,
request: EvaluateCreationRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
):
"""Evaluate a creative output and update agent capability metrics"""
engine = CreativityEnhancementEngine()
@@ -153,7 +155,7 @@ async def generate_ideas(request: IdeationRequest):
@router.post("/synthesis/cross-domain")
async def synthesize_cross_domain(
request: SynthesisRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
):
"""Synthesize concepts from multiple domains to create novel outputs"""
integrator = CrossDomainCreativeIntegrator()
@@ -176,7 +178,7 @@ async def synthesize_cross_domain(
@router.get("/capabilities/{agent_id}")
async def list_agent_creative_capabilities(
agent_id: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
):
"""List all creative capabilities for a specific agent"""
try:

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
Agent Integration and Deployment API Router for Verifiable AI Agent Orchestration
Provides REST API endpoints for production deployment and integration management
@@ -14,7 +16,7 @@ from ..services.agent_integration import (
AgentIntegrationManager, AgentDeploymentManager, AgentMonitoringManager, AgentProductionManager,
DeploymentStatus, AgentDeploymentConfig, AgentDeploymentInstance
)
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..deps import require_admin_key
from sqlmodel import Session, select
from datetime import datetime
@@ -29,7 +31,7 @@ async def create_deployment_config(
workflow_id: str,
deployment_name: str,
deployment_config: dict,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Create deployment configuration for agent workflow"""
@@ -64,7 +66,7 @@ async def create_deployment_config(
async def list_deployment_configs(
workflow_id: Optional[str] = None,
status: Optional[DeploymentStatus] = None,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""List deployment configurations with filtering"""
@@ -97,7 +99,7 @@ async def list_deployment_configs(
@router.get("/deployments/configs/{config_id}", response_model=AgentDeploymentConfig)
async def get_deployment_config(
config_id: str,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Get specific deployment configuration"""
@@ -125,7 +127,7 @@ async def get_deployment_config(
async def deploy_workflow(
config_id: str,
target_environment: str = "production",
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Deploy agent workflow to target environment"""
@@ -159,7 +161,7 @@ async def deploy_workflow(
@router.get("/deployments/{config_id}/health")
async def get_deployment_health(
config_id: str,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Get health status of deployment"""
@@ -190,7 +192,7 @@ async def get_deployment_health(
async def scale_deployment(
config_id: str,
target_instances: int,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Scale deployment to target number of instances"""
@@ -224,7 +226,7 @@ async def scale_deployment(
@router.post("/deployments/{config_id}/rollback")
async def rollback_deployment(
config_id: str,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Rollback deployment to previous version"""
@@ -257,7 +259,7 @@ async def list_deployment_instances(
deployment_id: Optional[str] = None,
environment: Optional[str] = None,
status: Optional[DeploymentStatus] = None,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""List deployment instances with filtering"""
@@ -295,7 +297,7 @@ async def list_deployment_instances(
@router.get("/deployments/instances/{instance_id}", response_model=AgentDeploymentInstance)
async def get_deployment_instance(
instance_id: str,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Get specific deployment instance"""
@@ -327,7 +329,7 @@ async def get_deployment_instance(
async def integrate_with_zk_system(
execution_id: str,
verification_level: VerificationLevel = VerificationLevel.BASIC,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Integrate agent execution with ZK proof system"""
@@ -362,7 +364,7 @@ async def integrate_with_zk_system(
async def get_deployment_metrics(
deployment_id: str,
time_range: str = "1h",
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Get metrics for deployment over time range"""
@@ -397,7 +399,7 @@ async def deploy_to_production(
workflow_id: str,
deployment_config: dict,
integration_config: Optional[dict] = None,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Deploy agent workflow to production with full integration"""
@@ -430,7 +432,7 @@ async def deploy_to_production(
@router.get("/production/dashboard")
async def get_production_dashboard(
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Get comprehensive production dashboard data"""
@@ -487,7 +489,7 @@ async def get_production_dashboard(
@router.get("/production/health")
async def get_production_health(
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Get overall production health status"""
@@ -560,7 +562,7 @@ async def get_production_health(
async def get_production_alerts(
severity: Optional[str] = None,
limit: int = 50,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Get production alerts and notifications"""

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
Advanced Agent Performance API Endpoints
REST API for meta-learning, resource optimization, and performance enhancement
@@ -9,7 +11,7 @@ from fastapi import APIRouter, HTTPException, Depends, Query
from pydantic import BaseModel, Field
from aitbc.logging import get_logger
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..services.agent_performance_service import (
AgentPerformanceService, MetaLearningEngine, ResourceManager, PerformanceOptimizer
)
@@ -151,7 +153,7 @@ class CapabilityResponse(BaseModel):
@router.post("/profiles", response_model=PerformanceProfileResponse)
async def create_performance_profile(
profile_request: PerformanceProfileRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> PerformanceProfileResponse:
"""Create agent performance profile"""
@@ -190,7 +192,7 @@ async def create_performance_profile(
@router.get("/profiles/{agent_id}", response_model=Dict[str, Any])
async def get_performance_profile(
agent_id: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Get agent performance profile"""
@@ -216,7 +218,7 @@ async def update_performance_metrics(
agent_id: str,
metrics: Dict[str, float],
task_context: Optional[Dict[str, Any]] = None,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Update agent performance metrics"""
@@ -245,7 +247,7 @@ async def update_performance_metrics(
@router.post("/meta-learning/models", response_model=MetaLearningResponse)
async def create_meta_learning_model(
model_request: MetaLearningRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> MetaLearningResponse:
"""Create meta-learning model"""
@@ -284,7 +286,7 @@ async def adapt_model_to_task(
model_id: str,
task_data: Dict[str, Any],
adaptation_steps: int = Query(default=10, ge=1, le=50),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Adapt meta-learning model to new task"""
@@ -317,7 +319,7 @@ async def list_meta_learning_models(
status: Optional[str] = Query(default=None, description="Filter by status"),
meta_strategy: Optional[str] = Query(default=None, description="Filter by meta strategy"),
limit: int = Query(default=50, ge=1, le=100, description="Number of results"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[Dict[str, Any]]:
"""List meta-learning models"""
@@ -360,7 +362,7 @@ async def list_meta_learning_models(
@router.post("/resources/allocate", response_model=ResourceAllocationResponse)
async def allocate_resources(
allocation_request: ResourceAllocationRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> ResourceAllocationResponse:
"""Allocate resources for agent task"""
@@ -398,7 +400,7 @@ async def get_resource_allocations(
agent_id: str,
status: Optional[str] = Query(default=None, description="Filter by status"),
limit: int = Query(default=20, ge=1, le=100, description="Number of results"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[Dict[str, Any]]:
"""Get resource allocations for agent"""
@@ -443,7 +445,7 @@ async def get_resource_allocations(
@router.post("/optimization/optimize", response_model=PerformanceOptimizationResponse)
async def optimize_performance(
optimization_request: PerformanceOptimizationRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> PerformanceOptimizationResponse:
"""Optimize agent performance"""
@@ -482,7 +484,7 @@ async def get_optimization_history(
status: Optional[str] = Query(default=None, description="Filter by status"),
target_metric: Optional[str] = Query(default=None, description="Filter by target metric"),
limit: int = Query(default=20, ge=1, le=100, description="Number of results"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[Dict[str, Any]]:
"""Get optimization history for agent"""
@@ -530,7 +532,7 @@ async def get_optimization_history(
@router.post("/capabilities", response_model=CapabilityResponse)
async def create_capability(
capability_request: CapabilityRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> CapabilityResponse:
"""Create agent capability"""
@@ -577,7 +579,7 @@ async def get_agent_capabilities(
capability_type: Optional[str] = Query(default=None, description="Filter by capability type"),
domain_area: Optional[str] = Query(default=None, description="Filter by domain area"),
limit: int = Query(default=50, ge=1, le=100, description="Number of results"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[Dict[str, Any]]:
"""Get agent capabilities"""
@@ -629,7 +631,7 @@ async def get_performance_summary(
agent_ids: List[str] = Query(default=[], description="List of agent IDs"),
metric: Optional[str] = Query(default="overall_score", description="Metric to summarize"),
period: str = Query(default="7d", description="Time period"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Get performance summary for agents"""

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
AI Agent API Router for Verifiable AI Agent Orchestration
Provides REST API endpoints for agent workflow management and execution
@@ -14,7 +16,7 @@ from ..domain.agent import (
AgentStatus, VerificationLevel
)
from ..services.agent_service import AIAgentOrchestrator
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..deps import require_admin_key
from sqlmodel import Session, select
@@ -26,7 +28,7 @@ router = APIRouter(prefix="/agents", tags=["AI Agents"])
@router.post("/workflows", response_model=AIAgentWorkflow)
async def create_workflow(
workflow_data: AgentWorkflowCreate,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Create a new AI agent workflow"""
@@ -54,7 +56,7 @@ async def list_workflows(
owner_id: Optional[str] = None,
is_public: Optional[bool] = None,
tags: Optional[List[str]] = None,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""List agent workflows with filtering"""
@@ -91,7 +93,7 @@ async def list_workflows(
@router.get("/workflows/{workflow_id}", response_model=AIAgentWorkflow)
async def get_workflow(
workflow_id: str,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Get a specific agent workflow"""
@@ -118,7 +120,7 @@ async def get_workflow(
async def update_workflow(
workflow_id: str,
workflow_data: AgentWorkflowUpdate,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Update an agent workflow"""
@@ -154,7 +156,7 @@ async def update_workflow(
@router.delete("/workflows/{workflow_id}")
async def delete_workflow(
workflow_id: str,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Delete an agent workflow"""
@@ -186,7 +188,7 @@ async def execute_workflow(
workflow_id: str,
execution_request: AgentExecutionRequest,
background_tasks: BackgroundTasks,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Execute an AI agent workflow"""
@@ -229,7 +231,7 @@ async def execute_workflow(
@router.get("/executions/{execution_id}/status", response_model=AgentExecutionStatus)
async def get_execution_status(
execution_id: str,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Get execution status"""
@@ -263,7 +265,7 @@ async def list_executions(
status: Optional[AgentStatus] = None,
limit: int = 50,
offset: int = 0,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""List agent executions with filtering"""
@@ -321,7 +323,7 @@ async def list_executions(
@router.post("/executions/{execution_id}/cancel")
async def cancel_execution(
execution_id: str,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Cancel an ongoing execution"""
@@ -365,7 +367,7 @@ async def cancel_execution(
@router.get("/executions/{execution_id}/logs")
async def get_execution_logs(
execution_id: str,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Get execution logs"""
@@ -427,7 +429,7 @@ async def test_endpoint():
@router.post("/networks", response_model=dict, status_code=201)
async def create_agent_network(
network_data: dict,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Create a new agent network for collaborative processing"""
@@ -467,7 +469,7 @@ async def create_agent_network(
@router.get("/executions/{execution_id}/receipt")
async def get_execution_receipt(
execution_id: str,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Get verifiable receipt for completed execution"""

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
Agent Security API Router for Verifiable AI Agent Orchestration
Provides REST API endpoints for security management and auditing
@@ -15,7 +17,7 @@ from ..services.agent_security import (
SecurityLevel, AuditEventType, AgentSecurityPolicy, AgentTrustScore, AgentSandboxConfig,
AgentAuditLog
)
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..deps import require_admin_key
from sqlmodel import Session, select
@@ -30,7 +32,7 @@ async def create_security_policy(
description: str,
security_level: SecurityLevel,
policy_rules: dict,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Create a new security policy"""
@@ -56,7 +58,7 @@ async def create_security_policy(
async def list_security_policies(
security_level: Optional[SecurityLevel] = None,
is_active: Optional[bool] = None,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""List security policies with filtering"""
@@ -81,7 +83,7 @@ async def list_security_policies(
@router.get("/policies/{policy_id}", response_model=AgentSecurityPolicy)
async def get_security_policy(
policy_id: str,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Get a specific security policy"""
@@ -104,7 +106,7 @@ async def get_security_policy(
async def update_security_policy(
policy_id: str,
policy_updates: dict,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Update a security policy"""
@@ -146,7 +148,7 @@ async def update_security_policy(
@router.delete("/policies/{policy_id}")
async def delete_security_policy(
policy_id: str,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Delete a security policy"""
@@ -182,7 +184,7 @@ async def delete_security_policy(
@router.post("/validate-workflow/{workflow_id}")
async def validate_workflow_security(
workflow_id: str,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Validate workflow security requirements"""
@@ -222,7 +224,7 @@ async def list_audit_logs(
risk_score_max: Optional[int] = None,
limit: int = 100,
offset: int = 0,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""List audit logs with filtering"""
@@ -265,7 +267,7 @@ async def list_audit_logs(
@router.get("/audit-logs/{audit_id}", response_model=AgentAuditLog)
async def get_audit_log(
audit_id: str,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Get a specific audit log entry"""
@@ -294,7 +296,7 @@ async def list_trust_scores(
max_score: Optional[float] = None,
limit: int = 100,
offset: int = 0,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""List trust scores with filtering"""
@@ -330,7 +332,7 @@ async def list_trust_scores(
async def get_trust_score(
entity_type: str,
entity_id: str,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Get trust score for specific entity"""
@@ -365,7 +367,7 @@ async def update_trust_score(
execution_time: Optional[float] = None,
security_violation: bool = False,
policy_violation: bool = False,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Update trust score based on execution results"""
@@ -411,7 +413,7 @@ async def create_sandbox(
execution_id: str,
security_level: SecurityLevel = SecurityLevel.PUBLIC,
workflow_requirements: Optional[dict] = None,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Create sandbox environment for agent execution"""
@@ -449,7 +451,7 @@ async def create_sandbox(
@router.get("/sandbox/{execution_id}/monitor")
async def monitor_sandbox(
execution_id: str,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Monitor sandbox execution for security violations"""
@@ -468,7 +470,7 @@ async def monitor_sandbox(
@router.post("/sandbox/{execution_id}/cleanup")
async def cleanup_sandbox(
execution_id: str,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Clean up sandbox environment after execution"""
@@ -498,7 +500,7 @@ async def cleanup_sandbox(
async def monitor_execution_security(
execution_id: str,
workflow_id: str,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Monitor execution for security violations"""
@@ -518,7 +520,7 @@ async def monitor_execution_security(
@router.get("/security-dashboard")
async def get_security_dashboard(
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Get comprehensive security dashboard data"""
@@ -586,7 +588,7 @@ async def get_security_dashboard(
@router.get("/security-stats")
async def get_security_statistics(
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Get security statistics and metrics"""

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
Marketplace Analytics API Endpoints
REST API for analytics, insights, reporting, and dashboards
@@ -9,7 +11,7 @@ from fastapi import APIRouter, HTTPException, Depends, Query
from pydantic import BaseModel, Field
from aitbc.logging import get_logger
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..services.analytics_service import MarketplaceAnalytics
from ..domain.analytics import (
MarketMetric, MarketInsight, AnalyticsReport, DashboardConfig,
@@ -109,7 +111,7 @@ class AnalyticsSummaryResponse(BaseModel):
@router.post("/data-collection", response_model=AnalyticsSummaryResponse)
async def collect_market_data(
period_type: AnalyticsPeriod = Query(default=AnalyticsPeriod.DAILY, description="Collection period"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> AnalyticsSummaryResponse:
"""Collect market data for analytics"""
@@ -131,7 +133,7 @@ async def get_market_insights(
insight_type: Optional[str] = Query(default=None, description="Filter by insight type"),
impact_level: Optional[str] = Query(default=None, description="Filter by impact level"),
limit: int = Query(default=20, ge=1, le=100, description="Number of results"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Get market insights and analysis"""
@@ -169,7 +171,7 @@ async def get_market_metrics(
category: Optional[str] = Query(default=None, description="Filter by category"),
geographic_region: Optional[str] = Query(default=None, description="Filter by region"),
limit: int = Query(default=50, ge=1, le=100, description="Number of results"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[MetricResponse]:
"""Get market metrics with filters"""
@@ -213,7 +215,7 @@ async def get_market_metrics(
@router.get("/overview", response_model=MarketOverviewResponse)
async def get_market_overview(
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> MarketOverviewResponse:
"""Get comprehensive market overview"""
@@ -234,7 +236,7 @@ async def create_dashboard(
owner_id: str,
dashboard_type: str = Query(default="default", description="Dashboard type: default, executive"),
name: Optional[str] = Query(default=None, description="Custom dashboard name"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> DashboardResponse:
"""Create analytics dashboard"""
@@ -275,7 +277,7 @@ async def create_dashboard(
@router.get("/dashboards/{dashboard_id}", response_model=DashboardResponse)
async def get_dashboard(
dashboard_id: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> DashboardResponse:
"""Get dashboard configuration"""
@@ -316,7 +318,7 @@ async def list_dashboards(
dashboard_type: Optional[str] = Query(default=None, description="Filter by dashboard type"),
status: Optional[str] = Query(default=None, description="Filter by status"),
limit: int = Query(default=50, ge=1, le=100, description="Number of results"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[DashboardResponse]:
"""List analytics dashboards with filters"""
@@ -361,7 +363,7 @@ async def list_dashboards(
@router.post("/reports", response_model=Dict[str, Any])
async def generate_report(
report_request: ReportRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Generate analytics report"""
@@ -435,7 +437,7 @@ async def generate_report(
async def get_report(
report_id: str,
format: str = Query(default="json", description="Response format: json, csv, pdf"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Get generated analytics report"""
@@ -489,7 +491,7 @@ async def get_analytics_alerts(
severity: Optional[str] = Query(default=None, description="Filter by severity level"),
status: Optional[str] = Query(default="active", description="Filter by status"),
limit: int = Query(default=20, ge=1, le=100, description="Number of results"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[Dict[str, Any]]:
"""Get analytics alerts"""
@@ -534,7 +536,7 @@ async def get_analytics_alerts(
@router.get("/kpi")
async def get_key_performance_indicators(
period_type: AnalyticsPeriod = Query(default=AnalyticsPeriod.DAILY, description="Period type"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Get key performance indicators"""

View File

@@ -1,3 +1,4 @@
from typing import Annotated
"""
Bounty Management API
REST API for AI agent bounty system with ZK-proof verification
@@ -9,7 +10,7 @@ from typing import List, Optional, Dict, Any
from datetime import datetime, timedelta
from pydantic import BaseModel, Field, validator
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..logging import get_logger
from ..domain.bounty import (
Bounty, BountySubmission, BountyStatus, BountyTier,
@@ -162,7 +163,7 @@ class BountyStatsResponse(BaseModel):
tier_distribution: Dict[str, int]
# Dependency injection
def get_bounty_service(session: SessionDep) -> BountyService:
def get_bounty_service(session: Annotated[Session, Depends(get_session)]) -> BountyService:
return BountyService(session)
def get_blockchain_service() -> BlockchainService:
@@ -173,7 +174,7 @@ def get_blockchain_service() -> BlockchainService:
async def create_bounty(
request: BountyCreateRequest,
background_tasks: BackgroundTasks,
session: SessionDep,
session: Annotated[Session, Depends(get_session)],
bounty_service: BountyService = Depends(get_bounty_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
@@ -206,7 +207,7 @@ async def create_bounty(
@router.get("/bounties", response_model=List[BountyResponse])
async def get_bounties(
filters: BountyFilterRequest = Depends(),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
bounty_service: BountyService = Depends(get_bounty_service)
):
"""Get filtered list of bounties"""
@@ -235,7 +236,7 @@ async def get_bounties(
@router.get("/bounties/{bounty_id}", response_model=BountyResponse)
async def get_bounty(
bounty_id: str,
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
bounty_service: BountyService = Depends(get_bounty_service)
):
"""Get bounty details"""
@@ -257,7 +258,7 @@ async def submit_bounty_solution(
bounty_id: str,
request: BountySubmissionRequest,
background_tasks: BackgroundTasks,
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
bounty_service: BountyService = Depends(get_bounty_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
@@ -306,7 +307,7 @@ async def submit_bounty_solution(
@router.get("/bounties/{bounty_id}/submissions", response_model=List[BountySubmissionResponse])
async def get_bounty_submissions(
bounty_id: str,
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
bounty_service: BountyService = Depends(get_bounty_service),
current_user: dict = Depends(get_current_user)
):
@@ -336,7 +337,7 @@ async def verify_bounty_submission(
bounty_id: str,
request: BountyVerificationRequest,
background_tasks: BackgroundTasks,
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
bounty_service: BountyService = Depends(get_bounty_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
@@ -376,7 +377,7 @@ async def dispute_bounty_submission(
bounty_id: str,
request: BountyDisputeRequest,
background_tasks: BackgroundTasks,
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
bounty_service: BountyService = Depends(get_bounty_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
@@ -411,7 +412,7 @@ async def get_my_created_bounties(
status: Optional[BountyStatus] = None,
page: int = Field(default=1, ge=1),
limit: int = Field(default=20, ge=1, le=100),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
bounty_service: BountyService = Depends(get_bounty_service),
current_user: dict = Depends(get_current_user)
):
@@ -435,7 +436,7 @@ async def get_my_submissions(
status: Optional[SubmissionStatus] = None,
page: int = Field(default=1, ge=1),
limit: int = Field(default=20, ge=1, le=100),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
bounty_service: BountyService = Depends(get_bounty_service),
current_user: dict = Depends(get_current_user)
):
@@ -458,7 +459,7 @@ async def get_my_submissions(
async def get_bounty_leaderboard(
period: str = Field(default="weekly", regex="^(daily|weekly|monthly)$"),
limit: int = Field(default=50, ge=1, le=100),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
bounty_service: BountyService = Depends(get_bounty_service)
):
"""Get bounty leaderboard"""
@@ -477,7 +478,7 @@ async def get_bounty_leaderboard(
@router.get("/bounties/stats", response_model=BountyStatsResponse)
async def get_bounty_stats(
period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
bounty_service: BountyService = Depends(get_bounty_service)
):
"""Get bounty statistics"""
@@ -494,7 +495,7 @@ async def get_bounty_stats(
async def expire_bounty(
bounty_id: str,
background_tasks: BackgroundTasks,
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
bounty_service: BountyService = Depends(get_bounty_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
@@ -534,7 +535,7 @@ async def expire_bounty(
@router.get("/bounties/categories")
async def get_bounty_categories(
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
bounty_service: BountyService = Depends(get_bounty_service)
):
"""Get all bounty categories"""
@@ -549,7 +550,7 @@ async def get_bounty_categories(
@router.get("/bounties/tags")
async def get_bounty_tags(
limit: int = Field(default=100, ge=1, le=500),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
bounty_service: BountyService = Depends(get_bounty_service)
):
"""Get popular bounty tags"""
@@ -566,7 +567,7 @@ async def search_bounties(
query: str = Field(..., min_length=1, max_length=100),
page: int = Field(default=1, ge=1),
limit: int = Field(default=20, ge=1, le=100),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
bounty_service: BountyService = Depends(get_bounty_service)
):
"""Search bounties by text"""

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
Certification and Partnership API Endpoints
REST API for agent certification, partnership programs, and badge system
@@ -9,7 +11,7 @@ from fastapi import APIRouter, HTTPException, Depends, Query
from pydantic import BaseModel, Field
from aitbc.logging import get_logger
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..services.certification_service import (
CertificationAndPartnershipService, CertificationSystem, PartnershipManager, BadgeSystem
)
@@ -118,7 +120,7 @@ class AgentCertificationSummary(BaseModel):
@router.post("/certify", response_model=CertificationResponse)
async def certify_agent(
certification_request: CertificationRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> CertificationResponse:
"""Certify an agent at a specific level"""
@@ -162,7 +164,7 @@ async def certify_agent(
async def renew_certification(
certification_id: str,
renewed_by: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Renew an existing certification"""
@@ -195,7 +197,7 @@ async def renew_certification(
async def get_agent_certifications(
agent_id: str,
status: Optional[str] = Query(default=None, description="Filter by status"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[CertificationResponse]:
"""Get certifications for an agent"""
@@ -241,7 +243,7 @@ async def create_partnership_program(
tier_levels: List[str] = Field(default_factory=lambda: ["basic", "premium"]),
max_participants: Optional[int] = Field(default=None, description="Maximum participants"),
launch_immediately: bool = Field(default=False, description="Launch program immediately"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Create a new partnership program"""
@@ -279,7 +281,7 @@ async def create_partnership_program(
@router.post("/partnerships/apply", response_model=PartnershipResponse)
async def apply_for_partnership(
application: PartnershipApplicationRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> PartnershipResponse:
"""Apply for a partnership program"""
@@ -322,7 +324,7 @@ async def get_agent_partnerships(
agent_id: str,
status: Optional[str] = Query(default=None, description="Filter by status"),
partnership_type: Optional[str] = Query(default=None, description="Filter by partnership type"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[PartnershipResponse]:
"""Get partnerships for an agent"""
@@ -365,7 +367,7 @@ async def list_partnership_programs(
partnership_type: Optional[str] = Query(default=None, description="Filter by partnership type"),
status: Optional[str] = Query(default="active", description="Filter by status"),
limit: int = Query(default=50, ge=1, le=100, description="Number of results"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[Dict[str, Any]]:
"""List available partnership programs"""
@@ -406,7 +408,7 @@ async def list_partnership_programs(
@router.post("/badges")
async def create_badge(
badge_request: BadgeCreationRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Create a new achievement badge"""
@@ -444,7 +446,7 @@ async def create_badge(
@router.post("/badges/award", response_model=BadgeResponse)
async def award_badge(
badge_request: BadgeAwardRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> BadgeResponse:
"""Award a badge to an agent"""
@@ -495,7 +497,7 @@ async def get_agent_badges(
category: Optional[str] = Query(default=None, description="Filter by category"),
featured_only: bool = Query(default=False, description="Only featured badges"),
limit: int = Query(default=50, ge=1, le=100, description="Number of results"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[BadgeResponse]:
"""Get badges for an agent"""
@@ -548,7 +550,7 @@ async def list_available_badges(
rarity: Optional[str] = Query(default=None, description="Filter by rarity"),
active_only: bool = Query(default=True, description="Only active badges"),
limit: int = Query(default=50, ge=1, le=100, description="Number of results"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[Dict[str, Any]]:
"""List available badges"""
@@ -596,7 +598,7 @@ async def list_available_badges(
@router.post("/badges/{agent_id}/check-automatic")
async def check_automatic_badges(
agent_id: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Check and award automatic badges for an agent"""
@@ -620,7 +622,7 @@ async def check_automatic_badges(
@router.get("/summary/{agent_id}", response_model=AgentCertificationSummary)
async def get_agent_summary(
agent_id: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> AgentCertificationSummary:
"""Get comprehensive certification and partnership summary for an agent"""
@@ -642,7 +644,7 @@ async def get_verification_records(
verification_type: Optional[str] = Query(default=None, description="Filter by verification type"),
status: Optional[str] = Query(default=None, description="Filter by status"),
limit: int = Query(default=20, ge=1, le=100, description="Number of results"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[Dict[str, Any]]:
"""Get verification records for an agent"""
@@ -682,7 +684,7 @@ async def get_verification_records(
@router.get("/levels")
async def get_certification_levels(
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[Dict[str, Any]]:
"""Get available certification levels and requirements"""
@@ -710,7 +712,7 @@ async def get_certification_levels(
async def get_certification_requirements(
level: Optional[str] = Query(default=None, description="Filter by certification level"),
verification_type: Optional[str] = Query(default=None, description="Filter by verification type"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[Dict[str, Any]]:
"""Get certification requirements"""
@@ -754,7 +756,7 @@ async def get_certification_requirements(
async def get_certification_leaderboard(
category: str = Query(default="highest_level", description="Leaderboard category"),
limit: int = Query(default=50, ge=1, le=100, description="Number of results"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[Dict[str, Any]]:
"""Get certification leaderboard"""

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, status, Request
from slowapi import Limiter
from slowapi.util import get_remote_address
@@ -9,7 +11,7 @@ from ..types import JobState
from ..services import JobService
from ..services.payments import PaymentService
from ..config import settings
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..utils.cache import cached, get_cache_config
limiter = Limiter(key_func=get_remote_address)
@@ -21,7 +23,7 @@ router = APIRouter(tags=["client"])
async def submit_job(
req: JobCreate,
request: Request,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
) -> JobView: # type: ignore[arg-type]
service = JobService(session)
@@ -49,7 +51,7 @@ async def submit_job(
@cached(**get_cache_config("job_list")) # Cache job status for 1 minute
async def get_job(
job_id: str,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
) -> JobView: # type: ignore[arg-type]
service = JobService(session)
@@ -63,7 +65,7 @@ async def get_job(
@router.get("/jobs/{job_id}/result", response_model=JobResult, summary="Get job result")
async def get_job_result(
job_id: str,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
) -> JobResult: # type: ignore[arg-type]
service = JobService(session)
@@ -82,7 +84,7 @@ async def get_job_result(
@router.post("/jobs/{job_id}/cancel", response_model=JobView, summary="Cancel job")
async def cancel_job(
job_id: str,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
) -> JobView: # type: ignore[arg-type]
service = JobService(session)
@@ -101,7 +103,7 @@ async def cancel_job(
@router.get("/jobs/{job_id}/receipt", summary="Get latest signed receipt")
async def get_job_receipt(
job_id: str,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
) -> dict: # type: ignore[arg-type]
service = JobService(session)
@@ -117,7 +119,7 @@ async def get_job_receipt(
@router.get("/jobs/{job_id}/receipts", summary="List signed receipts")
async def list_job_receipts(
job_id: str,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
) -> dict: # type: ignore[arg-type]
service = JobService(session)
@@ -129,7 +131,7 @@ async def list_job_receipts(
@cached(**get_cache_config("job_list")) # Cache job list for 30 seconds
async def list_jobs(
request: Request,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
limit: int = 20,
offset: int = 0,
@@ -169,7 +171,7 @@ async def list_jobs(
@cached(**get_cache_config("job_list")) # Cache job history for 30 seconds
async def get_job_history(
request: Request,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
limit: int = 20,
offset: int = 0,
@@ -225,7 +227,7 @@ async def get_job_history(
@router.get("/blocks", summary="Get blockchain blocks")
async def get_blocks(
request: Request,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
limit: int = 20,
offset: int = 0,

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
Community and Developer Ecosystem API Endpoints
REST API for managing OpenClaw developer profiles, SDKs, solutions, and hackathons
@@ -9,7 +11,7 @@ from fastapi import APIRouter, HTTPException, Depends, Query, Body
from pydantic import BaseModel, Field
from aitbc.logging import get_logger
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..services.community_service import (
DeveloperEcosystemService, ThirdPartySolutionService,
InnovationLabService, CommunityPlatformService
@@ -68,7 +70,7 @@ class HackathonCreateRequest(BaseModel):
# Endpoints - Developer Ecosystem
@router.post("/developers", response_model=DeveloperProfile)
async def create_developer_profile(request: DeveloperProfileCreate, session: SessionDep):
async def create_developer_profile(request: DeveloperProfileCreate, session: Annotated[Session, Depends(get_session)] = Depends()):
"""Register a new developer in the OpenClaw ecosystem"""
service = DeveloperEcosystemService(session)
try:
@@ -84,7 +86,7 @@ async def create_developer_profile(request: DeveloperProfileCreate, session: Ses
raise HTTPException(status_code=500, detail=str(e))
@router.get("/developers/{developer_id}", response_model=DeveloperProfile)
async def get_developer_profile(developer_id: str, session: SessionDep):
async def get_developer_profile(developer_id: str, session: Annotated[Session, Depends(get_session)] = Depends()):
"""Get a developer's profile and reputation"""
service = DeveloperEcosystemService(session)
profile = await service.get_developer_profile(developer_id)
@@ -93,14 +95,14 @@ async def get_developer_profile(developer_id: str, session: SessionDep):
return profile
@router.get("/sdk/latest")
async def get_latest_sdk(session: SessionDep):
async def get_latest_sdk(session: Annotated[Session, Depends(get_session)] = Depends()):
"""Get information about the latest OpenClaw SDK releases"""
service = DeveloperEcosystemService(session)
return await service.get_sdk_release_info()
# Endpoints - Marketplace Solutions
@router.post("/solutions/publish", response_model=AgentSolution)
async def publish_solution(request: SolutionPublishRequest, session: SessionDep):
async def publish_solution(request: SolutionPublishRequest, session: Annotated[Session, Depends(get_session)] = Depends()):
"""Publish a new third-party agent solution to the marketplace"""
service = ThirdPartySolutionService(session)
try:
@@ -120,7 +122,7 @@ async def list_solutions(
return await service.list_published_solutions(category, limit)
@router.post("/solutions/{solution_id}/purchase")
async def purchase_solution(solution_id: str, session: SessionDep, buyer_id: str = Body(embed=True)):
async def purchase_solution(solution_id: str, session: Annotated[Session, Depends(get_session)] = Depends(), buyer_id: str = Body(embed=True)):
"""Purchase or install a third-party solution"""
service = ThirdPartySolutionService(session)
try:
@@ -146,7 +148,7 @@ async def propose_innovation_lab(
raise HTTPException(status_code=500, detail=str(e))
@router.post("/labs/{lab_id}/join")
async def join_innovation_lab(lab_id: str, session: SessionDep, developer_id: str = Body(embed=True)):
async def join_innovation_lab(lab_id: str, session: Annotated[Session, Depends(get_session)] = Depends(), developer_id: str = Body(embed=True)):
"""Join an active innovation lab"""
service = InnovationLabService(session)
try:
@@ -156,7 +158,7 @@ async def join_innovation_lab(lab_id: str, session: SessionDep, developer_id: st
raise HTTPException(status_code=404, detail=str(e))
@router.post("/labs/{lab_id}/fund")
async def fund_innovation_lab(lab_id: str, session: SessionDep, amount: float = Body(embed=True)):
async def fund_innovation_lab(lab_id: str, session: Annotated[Session, Depends(get_session)] = Depends(), amount: float = Body(embed=True)):
"""Provide funding to a proposed innovation lab"""
service = InnovationLabService(session)
try:
@@ -189,7 +191,7 @@ async def get_community_feed(
return await service.get_feed(category, limit)
@router.post("/platform/posts/{post_id}/upvote")
async def upvote_community_post(post_id: str, session: SessionDep):
async def upvote_community_post(post_id: str, session: Annotated[Session, Depends(get_session)] = Depends()):
"""Upvote a community post (rewards author reputation)"""
service = CommunityPlatformService(session)
try:
@@ -215,7 +217,7 @@ async def create_hackathon(
raise HTTPException(status_code=500, detail=str(e))
@router.post("/hackathons/{hackathon_id}/register")
async def register_for_hackathon(hackathon_id: str, session: SessionDep, developer_id: str = Body(embed=True)):
async def register_for_hackathon(hackathon_id: str, session: Annotated[Session, Depends(get_session)] = Depends(), developer_id: str = Body(embed=True)):
"""Register for an upcoming or ongoing hackathon"""
service = CommunityPlatformService(session)
try:

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
Dynamic Pricing API Router
Provides RESTful endpoints for dynamic pricing management
@@ -11,7 +13,7 @@ from fastapi import status as http_status
from pydantic import BaseModel, Field
from sqlmodel import select, func
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..services.dynamic_pricing_engine import (
DynamicPricingEngine,
PricingStrategy,

View File

@@ -1,3 +1,4 @@
from typing import Annotated
"""
Ecosystem Metrics Dashboard API
REST API for developer ecosystem metrics and analytics
@@ -9,7 +10,7 @@ from typing import List, Optional, Dict, Any
from datetime import datetime, timedelta
from pydantic import BaseModel, Field
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..logging import get_logger
from ..domain.bounty import EcosystemMetrics, BountyStats, AgentMetrics
from ..services.ecosystem_service import EcosystemService
@@ -81,14 +82,14 @@ class MetricsFilterRequest(BaseModel):
compare_period: Optional[str] = None
# Dependency injection
def get_ecosystem_service(session: SessionDep) -> EcosystemService:
def get_ecosystem_service(session: Annotated[Session, Depends(get_session)]) -> EcosystemService:
return EcosystemService(session)
# API endpoints
@router.get("/ecosystem/developer-earnings", response_model=DeveloperEarningsResponse)
async def get_developer_earnings(
period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service),
current_user: dict = Depends(get_current_user)
):
@@ -108,7 +109,7 @@ async def get_developer_earnings(
@router.get("/ecosystem/agent-utilization", response_model=AgentUtilizationResponse)
async def get_agent_utilization(
period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
"""Get agent utilization metrics"""
@@ -127,7 +128,7 @@ async def get_agent_utilization(
@router.get("/ecosystem/treasury-allocation", response_model=TreasuryAllocationResponse)
async def get_treasury_allocation(
period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
"""Get DAO treasury allocation metrics"""
@@ -146,7 +147,7 @@ async def get_treasury_allocation(
@router.get("/ecosystem/staking-metrics", response_model=StakingMetricsResponse)
async def get_staking_metrics(
period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
"""Get staking system metrics"""
@@ -165,7 +166,7 @@ async def get_staking_metrics(
@router.get("/ecosystem/bounty-analytics", response_model=BountyAnalyticsResponse)
async def get_bounty_analytics(
period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
"""Get bounty system analytics"""
@@ -184,7 +185,7 @@ async def get_bounty_analytics(
@router.get("/ecosystem/overview", response_model=EcosystemOverviewResponse)
async def get_ecosystem_overview(
period_type: str = Field(default="daily", regex="^(hourly|daily|weekly|monthly)$"),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
"""Get comprehensive ecosystem overview"""
@@ -213,7 +214,7 @@ async def get_ecosystem_metrics(
start_date: Optional[datetime] = None,
end_date: Optional[datetime] = None,
limit: int = Field(default=100, ge=1, le=1000),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
"""Get time-series ecosystem metrics"""
@@ -237,7 +238,7 @@ async def get_ecosystem_metrics(
@router.get("/ecosystem/health-score")
async def get_ecosystem_health_score(
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
"""Get overall ecosystem health score"""
@@ -258,7 +259,7 @@ async def get_ecosystem_health_score(
@router.get("/ecosystem/growth-indicators")
async def get_growth_indicators(
period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
"""Get ecosystem growth indicators"""
@@ -281,7 +282,7 @@ async def get_top_performers(
category: str = Field(default="all", regex="^(developers|agents|stakers|all)$"),
period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"),
limit: int = Field(default=50, ge=1, le=100),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
"""Get top performers in different categories"""
@@ -307,7 +308,7 @@ async def get_top_performers(
async def get_ecosystem_predictions(
metric: str = Field(default="all", regex="^(earnings|staking|bounties|agents|all)$"),
horizon: int = Field(default=30, ge=1, le=365), # days
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
"""Get ecosystem predictions based on historical data"""
@@ -332,7 +333,7 @@ async def get_ecosystem_predictions(
@router.get("/ecosystem/alerts")
async def get_ecosystem_alerts(
severity: str = Field(default="all", regex="^(low|medium|high|critical|all)$"),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
"""Get ecosystem alerts and anomalies"""
@@ -356,7 +357,7 @@ async def get_ecosystem_comparison(
compare_period: str = Field(default="previous", regex="^(previous|same_last_year|custom)$"),
custom_start_date: Optional[datetime] = None,
custom_end_date: Optional[datetime] = None,
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
"""Compare ecosystem metrics between periods"""
@@ -385,7 +386,7 @@ async def export_ecosystem_data(
period_type: str = Field(default="daily", regex="^(hourly|daily|weekly|monthly)$"),
start_date: Optional[datetime] = None,
end_date: Optional[datetime] = None,
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
"""Export ecosystem data in various formats"""
@@ -412,7 +413,7 @@ async def export_ecosystem_data(
@router.get("/ecosystem/real-time")
async def get_real_time_metrics(
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
"""Get real-time ecosystem metrics"""
@@ -431,7 +432,7 @@ async def get_real_time_metrics(
@router.get("/ecosystem/kpi-dashboard")
async def get_kpi_dashboard(
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
ecosystem_service: EcosystemService = Depends(get_ecosystem_service)
):
"""Get KPI dashboard with key performance indicators"""

View File

@@ -1,13 +1,15 @@
from sqlalchemy.orm import Session
from typing import Annotated
from typing import List, Optional
from fastapi import APIRouter, Depends, Query
from ..storage import SessionDep, get_session
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..domain.gpu_marketplace import ConsumerGPUProfile, GPUArchitecture, EdgeGPUMetrics
from ..services.edge_gpu_service import EdgeGPUService
router = APIRouter(prefix="/v1/marketplace/edge-gpu", tags=["edge-gpu"])
def get_edge_service(session: SessionDep) -> EdgeGPUService:
def get_edge_service(session: Annotated[Session, Depends(get_session)] = Depends()) -> EdgeGPUService:
return EdgeGPUService(session)

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
from __future__ import annotations
from fastapi import APIRouter, Depends, Query
@@ -9,19 +11,19 @@ from ..schemas import (
ReceiptListResponse,
)
from ..services import ExplorerService
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
router = APIRouter(prefix="/explorer", tags=["explorer"])
def _service(session: SessionDep) -> ExplorerService:
def _service(session: Annotated[Session, Depends(get_session)] = Depends()) -> ExplorerService:
return ExplorerService(session)
@router.get("/blocks", response_model=BlockListResponse, summary="List recent blocks")
async def list_blocks(
*,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
limit: int = Query(default=20, ge=1, le=200),
offset: int = Query(default=0, ge=0),
) -> BlockListResponse:
@@ -35,7 +37,7 @@ async def list_blocks(
)
async def list_transactions(
*,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
limit: int = Query(default=50, ge=1, le=200),
offset: int = Query(default=0, ge=0),
) -> TransactionListResponse:
@@ -45,7 +47,7 @@ async def list_transactions(
@router.get("/addresses", response_model=AddressListResponse, summary="List address summaries")
async def list_addresses(
*,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
limit: int = Query(default=50, ge=1, le=200),
offset: int = Query(default=0, ge=0),
) -> AddressListResponse:
@@ -55,7 +57,7 @@ async def list_addresses(
@router.get("/receipts", response_model=ReceiptListResponse, summary="List job receipts")
async def list_receipts(
*,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
job_id: str | None = Query(default=None, description="Filter by job identifier"),
limit: int = Query(default=50, ge=1, le=200),
offset: int = Query(default=0, ge=0),

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
Decentralized Governance API Endpoints
REST API for OpenClaw DAO voting, proposals, and governance analytics
@@ -9,7 +11,7 @@ from fastapi import APIRouter, HTTPException, Depends, Query, Body
from pydantic import BaseModel, Field
from aitbc.logging import get_logger
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..services.governance_service import GovernanceService
from ..domain.governance import (
GovernanceProfile, Proposal, Vote, DaoTreasury, TransparencyReport,
@@ -43,7 +45,7 @@ class VoteRequest(BaseModel):
# Endpoints - Profile & Delegation
@router.post("/profiles", response_model=GovernanceProfile)
async def init_governance_profile(request: ProfileInitRequest, session: SessionDep):
async def init_governance_profile(request: ProfileInitRequest, session: Annotated[Session, Depends(get_session)] = Depends()):
"""Initialize a governance profile for a user"""
service = GovernanceService(session)
try:
@@ -54,7 +56,7 @@ async def init_governance_profile(request: ProfileInitRequest, session: SessionD
raise HTTPException(status_code=500, detail=str(e))
@router.post("/profiles/{profile_id}/delegate", response_model=GovernanceProfile)
async def delegate_voting_power(profile_id: str, request: DelegationRequest, session: SessionDep):
async def delegate_voting_power(profile_id: str, request: DelegationRequest, session: Annotated[Session, Depends(get_session)] = Depends()):
"""Delegate your voting power to another DAO member"""
service = GovernanceService(session)
try:
@@ -68,7 +70,7 @@ async def delegate_voting_power(profile_id: str, request: DelegationRequest, ses
# Endpoints - Proposals
@router.post("/proposals", response_model=Proposal)
async def create_proposal(
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
proposer_id: str = Query(...),
request: ProposalCreateRequest = Body(...)
):
@@ -85,7 +87,7 @@ async def create_proposal(
@router.post("/proposals/{proposal_id}/vote", response_model=Vote)
async def cast_vote(
proposal_id: str,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
voter_id: str = Query(...),
request: VoteRequest = Body(...)
):
@@ -105,7 +107,7 @@ async def cast_vote(
raise HTTPException(status_code=500, detail=str(e))
@router.post("/proposals/{proposal_id}/process", response_model=Proposal)
async def process_proposal(proposal_id: str, session: SessionDep):
async def process_proposal(proposal_id: str, session: Annotated[Session, Depends(get_session)] = Depends()):
"""Manually trigger the lifecycle check of a proposal (e.g., tally votes when time ends)"""
service = GovernanceService(session)
try:
@@ -119,7 +121,7 @@ async def process_proposal(proposal_id: str, session: SessionDep):
@router.post("/proposals/{proposal_id}/execute", response_model=Proposal)
async def execute_proposal(
proposal_id: str,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
executor_id: str = Query(...)
):
"""Execute the payload of a succeeded proposal"""
@@ -135,7 +137,7 @@ async def execute_proposal(
# Endpoints - Analytics
@router.post("/analytics/reports", response_model=TransparencyReport)
async def generate_transparency_report(
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
period: str = Query(..., description="e.g., 2026-Q1")
):
"""Generate a governance analytics and transparency report"""

View File

@@ -1,3 +1,4 @@
from typing import Annotated
"""
GPU Multi-Modal Service Health Check Router
Provides health monitoring for CUDA-optimized multi-modal processing
@@ -11,7 +12,7 @@ import psutil
import subprocess
from typing import Dict, Any
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..services.multimodal_agent import MultiModalAgentService
from ..logging import get_logger
@@ -20,7 +21,7 @@ router = APIRouter()
@router.get("/health", tags=["health"], summary="GPU Multi-Modal Service Health")
async def gpu_multimodal_health(session: SessionDep) -> Dict[str, Any]:
async def gpu_multimodal_health(session: Annotated[Session, Depends(get_session)] = Depends()) -> Dict[str, Any]:
"""
Health check for GPU Multi-Modal Service (Port 8003)
"""
@@ -97,7 +98,7 @@ async def gpu_multimodal_health(session: SessionDep) -> Dict[str, Any]:
@router.get("/health/deep", tags=["health"], summary="Deep GPU Multi-Modal Service Health")
async def gpu_multimodal_deep_health(session: SessionDep) -> Dict[str, Any]:
async def gpu_multimodal_deep_health(session: Annotated[Session, Depends(get_session)] = Depends()) -> Dict[str, Any]:
"""
Deep health check with CUDA performance validation
"""

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, Query, Request
@@ -7,7 +9,7 @@ from slowapi.util import get_remote_address
from ..schemas import MarketplaceBidRequest, MarketplaceOfferView, MarketplaceStatsView, MarketplaceBidView
from ..services import MarketplaceService
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..metrics import marketplace_requests_total, marketplace_errors_total
from ..utils.cache import cached, get_cache_config
from ..config import settings
@@ -18,7 +20,7 @@ limiter = Limiter(key_func=get_remote_address)
router = APIRouter(tags=["marketplace"])
def _get_service(session: SessionDep) -> MarketplaceService:
def _get_service(session: Annotated[Session, Depends(get_session)] = Depends()) -> MarketplaceService:
return MarketplaceService(session)
@@ -31,7 +33,7 @@ def _get_service(session: SessionDep) -> MarketplaceService:
async def list_marketplace_offers(
request: Request,
*,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
status_filter: str | None = Query(default=None, alias="status", description="Filter by offer status"),
limit: int = Query(default=100, ge=1, le=500),
offset: int = Query(default=0, ge=0),
@@ -58,7 +60,7 @@ async def list_marketplace_offers(
async def get_marketplace_stats(
request: Request,
*,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> MarketplaceStatsView:
marketplace_requests_total.labels(endpoint="/marketplace/stats", method="GET").inc()
service = _get_service(session)
@@ -78,7 +80,7 @@ async def get_marketplace_stats(
async def submit_marketplace_bid(
request: Request,
payload: MarketplaceBidRequest,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
) -> dict[str, str]:
marketplace_requests_total.labels(endpoint="/marketplace/bids", method="POST").inc()
service = _get_service(session)
@@ -100,7 +102,7 @@ async def submit_marketplace_bid(
)
async def list_marketplace_bids(
*,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
status_filter: str | None = Query(default=None, alias="status", description="Filter by bid status"),
provider_filter: str | None = Query(default=None, alias="provider", description="Filter by provider ID"),
limit: int = Query(default=100, ge=1, le=500),
@@ -125,7 +127,7 @@ async def list_marketplace_bids(
)
async def get_marketplace_bid(
bid_id: str,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
) -> MarketplaceBidView:
marketplace_requests_total.labels(endpoint="/marketplace/bids/{bid_id}", method="GET").inc()
service = _get_service(session)

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
Enhanced Marketplace API Router - Phase 6.5
REST API endpoints for advanced marketplace features including royalties, licensing, and analytics
@@ -11,7 +13,7 @@ from pydantic import BaseModel, Field
from ..domain import MarketplaceOffer
from ..services.marketplace_enhanced import EnhancedMarketplaceService, RoyaltyTier, LicenseType
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..deps import require_admin_key
from ..schemas.marketplace_enhanced import (
RoyaltyDistributionRequest, RoyaltyDistributionResponse,
@@ -29,7 +31,7 @@ router = APIRouter(prefix="/marketplace/enhanced", tags=["Enhanced Marketplace"]
async def create_royalty_distribution(
offer_id: str,
royalty_tiers: RoyaltyDistributionRequest,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Create sophisticated royalty distribution for marketplace offer"""
@@ -67,7 +69,7 @@ async def calculate_royalties(
offer_id: str,
sale_amount: float,
transaction_id: Optional[str] = None,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Calculate and distribute royalties for a sale"""
@@ -99,7 +101,7 @@ async def calculate_royalties(
async def create_model_license(
offer_id: str,
license_request: ModelLicenseRequest,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Create model license and IP protection"""
@@ -140,7 +142,7 @@ async def create_model_license(
async def verify_model(
offer_id: str,
verification_request: ModelVerificationRequest,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Perform advanced model verification"""
@@ -177,7 +179,7 @@ async def verify_model(
async def get_marketplace_analytics(
period_days: int = 30,
metrics: Optional[List[str]] = None,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Get comprehensive marketplace analytics"""

View File

@@ -1,13 +1,15 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
Enhanced Marketplace Service - FastAPI Entry Point
"""
from fastapi import FastAPI
from fastapi import FastAPI, Depends
from fastapi.middleware.cors import CORSMiddleware
from .marketplace_enhanced_simple import router
from .marketplace_enhanced_health import router as health_router
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
app = FastAPI(
title="AITBC Enhanced Marketplace Service",

View File

@@ -1,3 +1,4 @@
from typing import Annotated
"""
Enhanced Marketplace Service Health Check Router
Provides health monitoring for royalties, licensing, verification, and analytics
@@ -10,7 +11,7 @@ import sys
import psutil
from typing import Dict, Any
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..services.marketplace_enhanced import EnhancedMarketplaceService
from ..logging import get_logger
@@ -19,7 +20,7 @@ router = APIRouter()
@router.get("/health", tags=["health"], summary="Enhanced Marketplace Service Health")
async def marketplace_enhanced_health(session: SessionDep) -> Dict[str, Any]:
async def marketplace_enhanced_health(session: Annotated[Session, Depends(get_session)] = Depends()) -> Dict[str, Any]:
"""
Health check for Enhanced Marketplace Service (Port 8006)
"""
@@ -104,7 +105,7 @@ async def marketplace_enhanced_health(session: SessionDep) -> Dict[str, Any]:
@router.get("/health/deep", tags=["health"], summary="Deep Enhanced Marketplace Service Health")
async def marketplace_enhanced_deep_health(session: SessionDep) -> Dict[str, Any]:
async def marketplace_enhanced_deep_health(session: Annotated[Session, Depends(get_session)] = Depends()) -> Dict[str, Any]:
"""
Deep health check with marketplace feature validation
"""

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
Enhanced Marketplace API Router - Simplified Version
REST API endpoints for enhanced marketplace features
@@ -10,7 +12,7 @@ from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel, Field
from ..services.marketplace_enhanced_simple import EnhancedMarketplaceService, RoyaltyTier, LicenseType, VerificationType
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..deps import require_admin_key
from sqlmodel import Session
@@ -48,7 +50,7 @@ class MarketplaceAnalyticsRequest(BaseModel):
async def create_royalty_distribution(
request: RoyaltyDistributionRequest,
offer_id: str,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Create royalty distribution for marketplace offer"""
@@ -72,7 +74,7 @@ async def create_royalty_distribution(
async def calculate_royalties(
offer_id: str,
sale_amount: float,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Calculate royalties for a sale"""
@@ -95,7 +97,7 @@ async def calculate_royalties(
async def create_model_license(
request: ModelLicenseRequest,
offer_id: str,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Create model license for marketplace offer"""
@@ -121,7 +123,7 @@ async def create_model_license(
async def verify_model(
request: ModelVerificationRequest,
offer_id: str,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Verify model quality and performance"""
@@ -143,7 +145,7 @@ async def verify_model(
@router.post("/analytics")
async def get_marketplace_analytics(
request: MarketplaceAnalyticsRequest,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Get marketplace analytics and insights"""

View File

@@ -1,3 +1,4 @@
from typing import Annotated
"""
GPU marketplace endpoints backed by persistent SQLModel tables.
"""
@@ -11,8 +12,9 @@ from fastapi import APIRouter, HTTPException, Query, Depends
from fastapi import status as http_status
from pydantic import BaseModel, Field
from sqlmodel import select, func, col
from sqlalchemy.orm import Session
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..domain.gpu_marketplace import GPURegistry, GPUBooking, GPUReview
from ..services.dynamic_pricing_engine import DynamicPricingEngine, PricingStrategy, ResourceType
from ..services.market_data_collector import MarketDataCollector
@@ -130,7 +132,7 @@ def _get_gpu_or_404(session, gpu_id: str) -> GPURegistry:
@router.post("/marketplace/gpu/register")
async def register_gpu(
request: Dict[str, Any],
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
engine: DynamicPricingEngine = Depends(get_pricing_engine)
) -> Dict[str, Any]:
"""Register a GPU in the marketplace with dynamic pricing."""
@@ -185,7 +187,7 @@ async def register_gpu(
@router.get("/marketplace/gpu/list")
async def list_gpus(
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
available: Optional[bool] = Query(default=None),
price_max: Optional[float] = Query(default=None),
region: Optional[str] = Query(default=None),
@@ -211,7 +213,7 @@ async def list_gpus(
@router.get("/marketplace/gpu/{gpu_id}")
async def get_gpu_details(gpu_id: str, session: SessionDep) -> Dict[str, Any]:
async def get_gpu_details(gpu_id: str, session: Annotated[Session, Depends(get_session)] = Depends()) -> Dict[str, Any]:
"""Get GPU details."""
gpu = _get_gpu_or_404(session, gpu_id)
result = _gpu_to_dict(gpu)
@@ -237,7 +239,7 @@ async def get_gpu_details(gpu_id: str, session: SessionDep) -> Dict[str, Any]:
async def book_gpu(
gpu_id: str,
request: GPUBookRequest,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
engine: DynamicPricingEngine = Depends(get_pricing_engine)
) -> Dict[str, Any]:
"""Book a GPU with dynamic pricing."""
@@ -319,7 +321,7 @@ async def book_gpu(
@router.post("/marketplace/gpu/{gpu_id}/release")
async def release_gpu(gpu_id: str, session: SessionDep) -> Dict[str, Any]:
async def release_gpu(gpu_id: str, session: Annotated[Session, Depends(get_session)] = Depends()) -> Dict[str, Any]:
"""Release a booked GPU."""
gpu = _get_gpu_or_404(session, gpu_id)
@@ -367,7 +369,7 @@ async def release_gpu(gpu_id: str, session: SessionDep) -> Dict[str, Any]:
async def confirm_gpu_booking(
gpu_id: str,
request: GPUConfirmRequest,
session: SessionDep,
session: Session = Depends(get_session),
) -> Dict[str, Any]:
"""Confirm a booking (client ACK)."""
gpu = _get_gpu_or_404(session, gpu_id)
@@ -408,7 +410,7 @@ async def confirm_gpu_booking(
@router.post("/tasks/ollama")
async def submit_ollama_task(
request: OllamaTaskRequest,
session: SessionDep,
session: Session = Depends(get_session),
) -> Dict[str, Any]:
"""Stub Ollama task submission endpoint."""
# Ensure GPU exists and is booked
@@ -434,7 +436,10 @@ async def submit_ollama_task(
@router.post("/payments/send")
async def send_payment(request: PaymentRequest) -> Dict[str, Any]:
async def send_payment(
request: PaymentRequest,
session: Session = Depends(get_session),
) -> Dict[str, Any]:
"""Stub payment endpoint (hook for blockchain processor)."""
if request.amount <= 0:
raise HTTPException(
@@ -460,7 +465,7 @@ async def send_payment(request: PaymentRequest) -> Dict[str, Any]:
@router.get("/marketplace/gpu/{gpu_id}/reviews")
async def get_gpu_reviews(
gpu_id: str,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
limit: int = Query(default=10, ge=1, le=100),
) -> Dict[str, Any]:
"""Get GPU reviews."""
@@ -490,7 +495,7 @@ async def get_gpu_reviews(
@router.post("/marketplace/gpu/{gpu_id}/reviews", status_code=http_status.HTTP_201_CREATED)
async def add_gpu_review(
gpu_id: str, request: GPUReviewRequest, session: SessionDep
gpu_id: str, request: GPUReviewRequest, session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Add a review for a GPU."""
gpu = _get_gpu_or_404(session, gpu_id)
@@ -527,7 +532,7 @@ async def add_gpu_review(
@router.get("/marketplace/orders")
async def list_orders(
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
status: Optional[str] = Query(default=None),
limit: int = Query(default=100, ge=1, le=500),
) -> List[Dict[str, Any]]:
@@ -558,7 +563,7 @@ async def list_orders(
@router.get("/marketplace/pricing/{model}")
async def get_pricing(
model: str,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
engine: DynamicPricingEngine = Depends(get_pricing_engine),
collector: MarketDataCollector = Depends(get_market_collector)
) -> Dict[str, Any]:

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
Router to create marketplace offers from registered miners
"""
@@ -9,14 +11,14 @@ from sqlmodel import Session, select
from ..deps import require_admin_key
from ..domain import MarketplaceOffer, Miner
from ..schemas import MarketplaceOfferView
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
router = APIRouter(tags=["marketplace-offers"])
@router.post("/marketplace/sync-offers", summary="Create offers from registered miners")
async def sync_offers(
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
admin_key: str = Depends(require_admin_key()),
) -> dict[str, Any]:
"""Create marketplace offers from all registered miners"""
@@ -64,7 +66,7 @@ async def sync_offers(
@router.get("/marketplace/miner-offers", summary="List all miner offers", response_model=list[MarketplaceOfferView])
async def list_miner_offers(session: SessionDep) -> list[MarketplaceOfferView]:
async def list_miner_offers(session: Annotated[Session, Depends(get_session)] = Depends()) -> list[MarketplaceOfferView]:
"""List all offers created from miners"""
# Get all offers with miner details

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
Marketplace Performance Optimization API Endpoints
REST API for managing distributed processing, GPU optimization, caching, and scaling
@@ -10,7 +12,7 @@ from fastapi import APIRouter, HTTPException, Depends, Query, BackgroundTasks
from pydantic import BaseModel, Field
from aitbc.logging import get_logger
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), "../../../../../gpu_acceleration"))

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
from datetime import datetime
from typing import Any
@@ -10,7 +12,7 @@ from ..schemas import AssignedJob, JobFailSubmit, JobResultSubmit, JobState, Min
from ..services import JobService, MinerService
from ..services.receipts import ReceiptService
from ..config import settings
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from aitbc.logging import get_logger
logger = get_logger(__name__)
@@ -23,7 +25,7 @@ router = APIRouter(tags=["miner"])
async def register(
req: MinerRegister,
request: Request,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
miner_id: str = Depends(get_miner_id()),
api_key: str = Depends(require_miner_key()),
) -> dict[str, Any]: # type: ignore[arg-type]
@@ -36,7 +38,7 @@ async def register(
async def heartbeat(
req: MinerHeartbeat,
request: Request,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
miner_id: str = Depends(get_miner_id()),
api_key: str = Depends(require_miner_key()),
) -> dict[str, str]: # type: ignore[arg-type]
@@ -51,7 +53,7 @@ async def heartbeat(
@router.post("/miners/poll", response_model=AssignedJob, summary="Poll for next job")
async def poll(
req: PollRequest,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
miner_id: str = Depends(require_miner_key()),
) -> AssignedJob | Response: # type: ignore[arg-type]
job = MinerService(session).poll(miner_id, req.max_wait_seconds)
@@ -64,7 +66,7 @@ async def poll(
async def submit_result(
job_id: str,
req: JobResultSubmit,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
miner_id: str = Depends(require_miner_key()),
) -> dict[str, Any]: # type: ignore[arg-type]
job_service = JobService(session)
@@ -120,7 +122,7 @@ async def submit_result(
async def submit_failure(
job_id: str,
req: JobFailSubmit,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
miner_id: str = Depends(require_miner_key()),
) -> dict[str, str]: # type: ignore[arg-type]
try:
@@ -139,7 +141,7 @@ async def list_miner_jobs(
job_type: str | None = None,
min_reward: float | None = None,
job_status: str | None = None,
session: SessionDep = SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends() = Annotated[Session, Depends(get_session)],
api_key: str = Depends(require_miner_key()),
) -> dict[str, Any]: # type: ignore[arg-type]
"""List jobs assigned to a specific miner"""
@@ -188,7 +190,7 @@ async def get_miner_earnings(
miner_id: str,
from_time: str | None = None,
to_time: str | None = None,
session: SessionDep = SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends() = Annotated[Session, Depends(get_session)],
api_key: str = Depends(require_miner_key()),
) -> dict[str, Any]: # type: ignore[arg-type]
"""Get earnings for a specific miner"""
@@ -223,7 +225,7 @@ async def get_miner_earnings(
async def update_miner_capabilities(
miner_id: str,
req: MinerRegister,
session: SessionDep = SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends() = Annotated[Session, Depends(get_session)],
api_key: str = Depends(require_miner_key()),
) -> dict[str, Any]: # type: ignore[arg-type]
"""Update capabilities for a registered miner"""
@@ -246,7 +248,7 @@ async def update_miner_capabilities(
@router.delete("/miners/{miner_id}", summary="Deregister miner")
async def deregister_miner(
miner_id: str,
session: SessionDep = SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends() = Annotated[Session, Depends(get_session)],
api_key: str = Depends(require_miner_key()),
) -> dict[str, str]: # type: ignore[arg-type]
"""Deregister a miner from the coordinator"""

View File

@@ -1,5 +1,7 @@
from sqlalchemy.orm import Session
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..services.zk_proofs import ZKProofService
from ..services.fhe_service import FHEService

View File

@@ -1,3 +1,4 @@
from typing import Annotated
"""
Modality Optimization Service Health Check Router
Provides health monitoring for specialized modality optimization strategies
@@ -10,7 +11,7 @@ import sys
import psutil
from typing import Dict, Any
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..services.multimodal_agent import MultiModalAgentService
from ..logging import get_logger
@@ -19,7 +20,7 @@ router = APIRouter()
@router.get("/health", tags=["health"], summary="Modality Optimization Service Health")
async def modality_optimization_health(session: SessionDep) -> Dict[str, Any]:
async def modality_optimization_health(session: Annotated[Session, Depends(get_session)] = Depends()) -> Dict[str, Any]:
"""
Health check for Modality Optimization Service (Port 8004)
"""
@@ -97,7 +98,7 @@ async def modality_optimization_health(session: SessionDep) -> Dict[str, Any]:
@router.get("/health/deep", tags=["health"], summary="Deep Modality Optimization Service Health")
async def modality_optimization_deep_health(session: SessionDep) -> Dict[str, Any]:
async def modality_optimization_deep_health(session: Annotated[Session, Depends(get_session)] = Depends()) -> Dict[str, Any]:
"""
Deep health check with optimization strategy validation
"""

View File

@@ -1,3 +1,4 @@
from typing import Annotated
"""
Enhanced Services Monitoring Dashboard
Provides a unified dashboard for all 6 enhanced services
@@ -11,7 +12,7 @@ import asyncio
import httpx
from typing import Dict, Any, List
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..logging import get_logger
logger = get_logger(__name__)
@@ -68,7 +69,7 @@ SERVICES = {
@router.get("/dashboard", tags=["monitoring"], summary="Enhanced Services Dashboard")
async def monitoring_dashboard(request: Request, session: SessionDep) -> Dict[str, Any]:
async def monitoring_dashboard(request: Request, session: Annotated[Session, Depends(get_session)] = Depends()) -> Dict[str, Any]:
"""
Unified monitoring dashboard for all enhanced services
"""

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
Multi-Modal Fusion and Advanced RL API Endpoints
REST API for multi-modal agent fusion and advanced reinforcement learning
@@ -9,7 +11,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, BackgroundTasks, W
from pydantic import BaseModel, Field
from aitbc.logging import get_logger
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..services.multi_modal_fusion import MultiModalFusionEngine
from ..services.advanced_reinforcement_learning import AdvancedReinforcementLearningEngine, MarketplaceStrategyOptimizer, CrossDomainCapabilityIntegrator
from ..domain.agent_performance import (
@@ -138,7 +140,7 @@ class CapabilityIntegrationResponse(BaseModel):
@router.post("/fusion/models", response_model=FusionModelResponse)
async def create_fusion_model(
fusion_request: FusionModelRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> FusionModelResponse:
"""Create multi-modal fusion model"""
@@ -178,7 +180,7 @@ async def create_fusion_model(
async def fuse_modalities(
fusion_id: str,
fusion_request: FusionRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> FusionResponse:
"""Fuse modalities using trained model"""
@@ -211,7 +213,7 @@ async def fuse_modalities(
@router.get("/fusion/models")
async def list_fusion_models(
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
status: Optional[str] = Query(default=None, description="Filter by status"),
fusion_type: Optional[str] = Query(default=None, description="Filter by fusion type"),
limit: int = Query(default=50, ge=1, le=100, description="Number of results")
@@ -261,7 +263,7 @@ async def list_fusion_models(
@router.post("/rl/agents", response_model=RLAgentResponse)
async def create_rl_agent(
agent_request: RLAgentRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> RLAgentResponse:
"""Create RL agent for marketplace strategies"""
@@ -299,7 +301,7 @@ async def create_rl_agent(
async def fuse_modalities_stream(
websocket: WebSocket,
fusion_id: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
):
"""Stream modalities and receive fusion results via WebSocket for high performance"""
await websocket.accept()
@@ -349,7 +351,7 @@ async def fuse_modalities_stream(
@router.get("/rl/agents/{agent_id}")
async def get_rl_agents(
agent_id: str,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
status: Optional[str] = Query(default=None, description="Filter by status"),
algorithm: Optional[str] = Query(default=None, description="Filter by algorithm"),
limit: int = Query(default=20, ge=1, le=100, description="Number of results")
@@ -406,7 +408,7 @@ async def get_rl_agents(
@router.post("/rl/optimize-strategy", response_model=StrategyOptimizationResponse)
async def optimize_strategy(
optimization_request: StrategyOptimizationRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> StrategyOptimizationResponse:
"""Optimize agent strategy using RL"""
@@ -441,7 +443,7 @@ async def optimize_strategy(
async def deploy_strategy(
config_id: str,
deployment_context: Dict[str, Any],
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Deploy trained strategy"""
@@ -466,7 +468,7 @@ async def deploy_strategy(
@router.post("/capabilities/integrate", response_model=CapabilityIntegrationResponse)
async def integrate_capabilities(
integration_request: CapabilityIntegrationRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> CapabilityIntegrationResponse:
"""Integrate capabilities across domains"""
@@ -514,7 +516,7 @@ async def integrate_capabilities(
@router.get("/capabilities/{agent_id}/domains")
async def get_agent_domain_capabilities(
agent_id: str,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
domain: Optional[str] = Query(default=None, description="Filter by domain"),
limit: int = Query(default=50, ge=1, le=100, description="Number of results")
) -> List[Dict[str, Any]]:
@@ -571,7 +573,7 @@ async def get_agent_domain_capabilities(
@router.get("/creative-capabilities/{agent_id}")
async def get_creative_capabilities(
agent_id: str,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
creative_domain: Optional[str] = Query(default=None, description="Filter by creative domain"),
limit: int = Query(default=50, ge=1, le=100, description="Number of results")
) -> List[Dict[str, Any]]:
@@ -624,7 +626,7 @@ async def get_creative_capabilities(
@router.get("/analytics/fusion-performance")
async def get_fusion_performance_analytics(
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
agent_ids: Optional[List[str]] = Query(default=[], description="List of agent IDs"),
fusion_type: Optional[str] = Query(default=None, description="Filter by fusion type"),
period: str = Query(default="7d", description="Time period")
@@ -712,7 +714,7 @@ async def get_fusion_performance_analytics(
@router.get("/analytics/rl-performance")
async def get_rl_performance_analytics(
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
agent_ids: Optional[List[str]] = Query(default=[], description="List of agent IDs"),
algorithm: Optional[str] = Query(default=None, description="Filter by algorithm"),
environment_type: Optional[str] = Query(default=None, description="Filter by environment type"),

View File

@@ -1,3 +1,4 @@
from typing import Annotated
"""
Multi-Modal Agent Service Health Check Router
Provides health monitoring for multi-modal processing capabilities
@@ -10,7 +11,7 @@ import sys
import psutil
from typing import Dict, Any
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..services.multimodal_agent import MultiModalAgentService
from ..logging import get_logger
@@ -19,7 +20,7 @@ router = APIRouter()
@router.get("/health", tags=["health"], summary="Multi-Modal Agent Service Health")
async def multimodal_health(session: SessionDep) -> Dict[str, Any]:
async def multimodal_health(session: Annotated[Session, Depends(get_session)] = Depends()) -> Dict[str, Any]:
"""
Health check for Multi-Modal Agent Service (Port 8002)
"""
@@ -94,7 +95,7 @@ async def multimodal_health(session: SessionDep) -> Dict[str, Any]:
@router.get("/health/deep", tags=["health"], summary="Deep Multi-Modal Service Health")
async def multimodal_deep_health(session: SessionDep) -> Dict[str, Any]:
async def multimodal_deep_health(session: Annotated[Session, Depends(get_session)] = Depends()) -> Dict[str, Any]:
"""
Deep health check with detailed multi-modal processing tests
"""

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
OpenClaw Integration Enhancement API Router - Phase 6.6
REST API endpoints for advanced agent orchestration, edge computing integration, and ecosystem development
@@ -11,7 +13,7 @@ from pydantic import BaseModel, Field
from ..domain import AIAgentWorkflow, AgentExecution, AgentStatus
from ..services.openclaw_enhanced import OpenClawEnhancedService, SkillType, ExecutionMode
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..deps import require_admin_key
from ..schemas.openclaw_enhanced import (
SkillRoutingRequest, SkillRoutingResponse,
@@ -31,7 +33,7 @@ router = APIRouter(prefix="/openclaw/enhanced", tags=["OpenClaw Enhanced"])
@router.post("/routing/skill", response_model=SkillRoutingResponse)
async def route_agent_skill(
routing_request: SkillRoutingRequest,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Sophisticated agent skill routing"""
@@ -59,7 +61,7 @@ async def route_agent_skill(
@router.post("/offloading/intelligent", response_model=JobOffloadingResponse)
async def intelligent_job_offloading(
offloading_request: JobOffloadingRequest,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Intelligent job offloading strategies"""
@@ -88,7 +90,7 @@ async def intelligent_job_offloading(
@router.post("/collaboration/coordinate", response_model=AgentCollaborationResponse)
async def coordinate_agent_collaboration(
collaboration_request: AgentCollaborationRequest,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Agent collaboration and coordination"""
@@ -117,7 +119,7 @@ async def coordinate_agent_collaboration(
@router.post("/execution/hybrid-optimize", response_model=HybridExecutionResponse)
async def optimize_hybrid_execution(
execution_request: HybridExecutionRequest,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Hybrid execution optimization"""
@@ -145,7 +147,7 @@ async def optimize_hybrid_execution(
@router.post("/edge/deploy", response_model=EdgeDeploymentResponse)
async def deploy_to_edge(
deployment_request: EdgeDeploymentRequest,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Deploy agent to edge computing infrastructure"""
@@ -174,7 +176,7 @@ async def deploy_to_edge(
@router.post("/edge/coordinate", response_model=EdgeCoordinationResponse)
async def coordinate_edge_to_cloud(
coordination_request: EdgeCoordinationRequest,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Coordinate edge-to-cloud agent operations"""
@@ -203,7 +205,7 @@ async def coordinate_edge_to_cloud(
@router.post("/ecosystem/develop", response_model=EcosystemDevelopmentResponse)
async def develop_openclaw_ecosystem(
ecosystem_request: EcosystemDevelopmentRequest,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Build comprehensive OpenClaw ecosystem"""

View File

@@ -1,13 +1,15 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
OpenClaw Enhanced Service - FastAPI Entry Point
"""
from fastapi import FastAPI
from fastapi import FastAPI, Depends
from fastapi.middleware.cors import CORSMiddleware
from .openclaw_enhanced_simple import router
from .openclaw_enhanced_health import router as health_router
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
app = FastAPI(
title="AITBC OpenClaw Enhanced Service",

View File

@@ -1,3 +1,4 @@
from typing import Annotated
"""
OpenClaw Enhanced Service Health Check Router
Provides health monitoring for agent orchestration, edge computing, and ecosystem development
@@ -11,7 +12,7 @@ import psutil
import subprocess
from typing import Dict, Any
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..services.openclaw_enhanced import OpenClawEnhancedService
from ..logging import get_logger
@@ -20,7 +21,7 @@ router = APIRouter()
@router.get("/health", tags=["health"], summary="OpenClaw Enhanced Service Health")
async def openclaw_enhanced_health(session: SessionDep) -> Dict[str, Any]:
async def openclaw_enhanced_health(session: Annotated[Session, Depends(get_session)] = Depends()) -> Dict[str, Any]:
"""
Health check for OpenClaw Enhanced Service (Port 8007)
"""
@@ -109,7 +110,7 @@ async def openclaw_enhanced_health(session: SessionDep) -> Dict[str, Any]:
@router.get("/health/deep", tags=["health"], summary="Deep OpenClaw Enhanced Service Health")
async def openclaw_enhanced_deep_health(session: SessionDep) -> Dict[str, Any]:
async def openclaw_enhanced_deep_health(session: Annotated[Session, Depends(get_session)] = Depends()) -> Dict[str, Any]:
"""
Deep health check with OpenClaw ecosystem validation
"""

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
OpenClaw Enhanced API Router - Simplified Version
REST API endpoints for OpenClaw integration features
@@ -10,7 +12,7 @@ from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel, Field
from ..services.openclaw_enhanced_simple import OpenClawEnhancedService, SkillType, ExecutionMode
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..deps import require_admin_key
from sqlmodel import Session
@@ -67,7 +69,7 @@ class EcosystemDevelopmentRequest(BaseModel):
@router.post("/routing/skill")
async def route_agent_skill(
request: SkillRoutingRequest,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Route agent skill to appropriate agent"""
@@ -90,7 +92,7 @@ async def route_agent_skill(
@router.post("/offloading/intelligent")
async def intelligent_job_offloading(
request: JobOffloadingRequest,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Intelligent job offloading strategies"""
@@ -113,7 +115,7 @@ async def intelligent_job_offloading(
@router.post("/collaboration/coordinate")
async def coordinate_agent_collaboration(
request: AgentCollaborationRequest,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Agent collaboration and coordination"""
@@ -136,7 +138,7 @@ async def coordinate_agent_collaboration(
@router.post("/execution/hybrid-optimize")
async def optimize_hybrid_execution(
request: HybridExecutionRequest,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Hybrid execution optimization"""
@@ -158,7 +160,7 @@ async def optimize_hybrid_execution(
@router.post("/edge/deploy")
async def deploy_to_edge(
request: EdgeDeploymentRequest,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Deploy agent to edge computing infrastructure"""
@@ -181,7 +183,7 @@ async def deploy_to_edge(
@router.post("/edge/coordinate")
async def coordinate_edge_to_cloud(
request: EdgeCoordinationRequest,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Coordinate edge-to-cloud agent operations"""
@@ -203,7 +205,7 @@ async def coordinate_edge_to_cloud(
@router.post("/ecosystem/develop")
async def develop_openclaw_ecosystem(
request: EcosystemDevelopmentRequest,
session: Session = Depends(SessionDep),
session: Session = Depends(Annotated[Session, Depends(get_session)]),
current_user: str = Depends(require_admin_key())
):
"""Build OpenClaw ecosystem components"""

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
Partner Router - Third-party integration management
"""
@@ -10,7 +12,7 @@ import secrets
import hashlib
from ..schemas import UserProfile
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from sqlmodel import select
router = APIRouter(tags=["partners"])
@@ -58,7 +60,7 @@ WEBHOOKS_DB = {}
@router.post("/partners/register", response_model=PartnerResponse)
async def register_partner(
partner: PartnerRegister,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> PartnerResponse:
"""Register a new partner application"""
@@ -103,7 +105,7 @@ async def register_partner(
@router.get("/partners/{partner_id}")
async def get_partner(
partner_id: str,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
api_key: str
) -> Dict[str, Any]:
"""Get partner information"""
@@ -127,7 +129,7 @@ async def get_partner(
@router.post("/partners/webhooks", response_model=WebhookResponse)
async def create_webhook(
webhook: WebhookCreate,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
api_key: str
) -> WebhookResponse:
"""Create a webhook subscription"""
@@ -178,7 +180,7 @@ async def create_webhook(
@router.get("/partners/webhooks")
async def list_webhooks(
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
api_key: str
) -> List[WebhookResponse]:
"""List partner webhooks"""
@@ -206,7 +208,7 @@ async def list_webhooks(
@router.delete("/partners/webhooks/{webhook_id}")
async def delete_webhook(
webhook_id: str,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
api_key: str
) -> Dict[str, str]:
"""Delete a webhook"""
@@ -229,7 +231,7 @@ async def delete_webhook(
@router.get("/partners/analytics/usage")
async def get_usage_analytics(
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
api_key: str,
period: str = "24h"
) -> Dict[str, Any]:

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""Payment router for job payments"""
from fastapi import APIRouter, Depends, HTTPException, status
@@ -13,7 +15,7 @@ from ..schemas import (
RefundRequest
)
from ..services.payments import PaymentService
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
router = APIRouter(tags=["payments"])
@@ -21,7 +23,7 @@ router = APIRouter(tags=["payments"])
@router.post("/payments", response_model=JobPaymentView, status_code=status.HTTP_201_CREATED, summary="Create payment for a job")
async def create_payment(
payment_data: JobPaymentCreate,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
) -> JobPaymentView:
"""Create a payment for a job"""
@@ -35,7 +37,7 @@ async def create_payment(
@router.get("/payments/{payment_id}", response_model=JobPaymentView, summary="Get payment details")
async def get_payment(
payment_id: str,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
) -> JobPaymentView:
"""Get payment details by ID"""
@@ -55,7 +57,7 @@ async def get_payment(
@router.get("/jobs/{job_id}/payment", response_model=JobPaymentView, summary="Get payment for a job")
async def get_job_payment(
job_id: str,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
) -> JobPaymentView:
"""Get payment information for a specific job"""
@@ -76,7 +78,7 @@ async def get_job_payment(
async def release_payment(
payment_id: str,
release_data: EscrowRelease,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
) -> dict:
"""Release payment from escrow (for completed jobs)"""
@@ -110,7 +112,7 @@ async def release_payment(
async def refund_payment(
payment_id: str,
refund_data: RefundRequest,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
) -> dict:
"""Refund payment (for failed or cancelled jobs)"""
@@ -143,7 +145,7 @@ async def refund_payment(
@router.get("/payments/{payment_id}/receipt", response_model=PaymentReceipt, summary="Get payment receipt")
async def get_payment_receipt(
payment_id: str,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
) -> PaymentReceipt:
"""Get payment receipt with verification status"""

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
Reputation Management API Endpoints
REST API for agent reputation, trust scores, and economic profiles
@@ -9,7 +11,7 @@ from fastapi import APIRouter, HTTPException, Depends, Query
from pydantic import BaseModel, Field
from aitbc.logging import get_logger
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..services.reputation_service import ReputationService
from ..domain.reputation import (
AgentReputation, CommunityFeedback, ReputationLevel,
@@ -121,7 +123,7 @@ class ReputationMetricsResponse(BaseModel):
@router.get("/profile/{agent_id}", response_model=ReputationProfileResponse)
async def get_reputation_profile(
agent_id: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> ReputationProfileResponse:
"""Get comprehensive reputation profile for an agent"""
@@ -143,7 +145,7 @@ async def get_reputation_profile(
@router.post("/profile/{agent_id}")
async def create_reputation_profile(
agent_id: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Create a new reputation profile for an agent"""
@@ -169,7 +171,7 @@ async def create_reputation_profile(
async def add_community_feedback(
agent_id: str,
feedback_request: FeedbackRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> FeedbackResponse:
"""Add community feedback for an agent"""
@@ -207,7 +209,7 @@ async def add_community_feedback(
@router.post("/job-completion")
async def record_job_completion(
job_request: JobCompletionRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Record job completion and update reputation"""
@@ -240,7 +242,7 @@ async def record_job_completion(
@router.get("/trust-score/{agent_id}", response_model=TrustScoreResponse)
async def get_trust_score_breakdown(
agent_id: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> TrustScoreResponse:
"""Get detailed trust score breakdown for an agent"""
@@ -281,7 +283,7 @@ async def get_reputation_leaderboard(
category: str = Query(default="trust_score", description="Category to rank by"),
limit: int = Query(default=50, ge=1, le=100, description="Number of results"),
region: Optional[str] = Query(default=None, description="Filter by region"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[LeaderboardEntry]:
"""Get reputation leaderboard"""
@@ -303,7 +305,7 @@ async def get_reputation_leaderboard(
@router.get("/metrics", response_model=ReputationMetricsResponse)
async def get_reputation_metrics(
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> ReputationMetricsResponse:
"""Get overall reputation system metrics"""
@@ -376,7 +378,7 @@ async def get_reputation_metrics(
async def get_agent_feedback(
agent_id: str,
limit: int = Query(default=10, ge=1, le=50),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[FeedbackResponse]:
"""Get community feedback for an agent"""
@@ -420,7 +422,7 @@ async def get_agent_feedback(
async def get_reputation_events(
agent_id: str,
limit: int = Query(default=20, ge=1, le=100),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[Dict[str, Any]]:
"""Get reputation change events for an agent"""
@@ -457,7 +459,7 @@ async def get_reputation_events(
async def update_specialization(
agent_id: str,
specialization_tags: List[str],
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Update agent specialization tags"""
@@ -493,7 +495,7 @@ async def update_specialization(
async def update_region(
agent_id: str,
region: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Update agent geographic region"""
@@ -529,7 +531,7 @@ async def update_region(
@router.get("/{agent_id}/cross-chain")
async def get_cross_chain_reputation(
agent_id: str,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
reputation_service: ReputationService = Depends()
) -> Dict[str, Any]:
"""Get cross-chain reputation data for an agent"""
@@ -578,7 +580,7 @@ async def get_cross_chain_reputation(
async def sync_cross_chain_reputation(
agent_id: str,
background_tasks: Any, # FastAPI BackgroundTasks
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
reputation_service: ReputationService = Depends()
) -> Dict[str, Any]:
"""Synchronize reputation across chains for an agent"""
@@ -612,7 +614,7 @@ async def sync_cross_chain_reputation(
async def get_cross_chain_leaderboard(
limit: int = Query(50, ge=1, le=100),
min_score: float = Query(0.0, ge=0.0, le=1.0),
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
reputation_service: ReputationService = Depends()
) -> Dict[str, Any]:
"""Get cross-chain reputation leaderboard"""
@@ -659,7 +661,7 @@ async def get_cross_chain_leaderboard(
async def submit_cross_chain_event(
event_data: Dict[str, Any],
background_tasks: Any, # FastAPI BackgroundTasks
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
reputation_service: ReputationService = Depends()
) -> Dict[str, Any]:
"""Submit a cross-chain reputation event"""
@@ -723,7 +725,7 @@ async def submit_cross_chain_event(
@router.get("/cross-chain/analytics")
async def get_cross_chain_analytics(
chain_id: Optional[int] = Query(None),
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
reputation_service: ReputationService = Depends()
) -> Dict[str, Any]:
"""Get cross-chain reputation analytics"""

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
Reward System API Endpoints
REST API for agent rewards, incentives, and performance-based earnings
@@ -9,7 +11,7 @@ from fastapi import APIRouter, HTTPException, Depends, Query
from pydantic import BaseModel, Field
from aitbc.logging import get_logger
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..services.reward_service import RewardEngine
from ..domain.rewards import (
AgentRewardProfile, RewardTier, RewardType, RewardStatus
@@ -113,7 +115,7 @@ class MilestoneResponse(BaseModel):
@router.get("/profile/{agent_id}", response_model=RewardProfileResponse)
async def get_reward_profile(
agent_id: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> RewardProfileResponse:
"""Get comprehensive reward profile for an agent"""
@@ -135,7 +137,7 @@ async def get_reward_profile(
@router.post("/profile/{agent_id}")
async def create_reward_profile(
agent_id: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Create a new reward profile for an agent"""
@@ -160,7 +162,7 @@ async def create_reward_profile(
@router.post("/calculate-and-distribute", response_model=RewardResponse)
async def calculate_and_distribute_reward(
reward_request: RewardRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> RewardResponse:
"""Calculate and distribute reward for an agent"""
@@ -199,7 +201,7 @@ async def calculate_and_distribute_reward(
@router.get("/tier-progress/{agent_id}", response_model=TierProgressResponse)
async def get_tier_progress(
agent_id: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> TierProgressResponse:
"""Get tier progress information for an agent"""
@@ -299,7 +301,7 @@ async def get_tier_progress(
@router.post("/batch-process", response_model=BatchProcessResponse)
async def batch_process_pending_rewards(
limit: int = Query(default=100, ge=1, le=1000, description="Maximum number of rewards to process"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> BatchProcessResponse:
"""Process pending reward distributions in batch"""
@@ -324,7 +326,7 @@ async def get_reward_analytics(
period_type: str = Query(default="daily", description="Period type: daily, weekly, monthly"),
start_date: Optional[str] = Query(default=None, description="Start date (ISO format)"),
end_date: Optional[str] = Query(default=None, description="End date (ISO format)"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> RewardAnalyticsResponse:
"""Get reward system analytics"""
@@ -357,7 +359,7 @@ async def get_reward_leaderboard(
tier: Optional[str] = Query(default=None, description="Filter by tier"),
period: str = Query(default="weekly", description="Period: daily, weekly, monthly"),
limit: int = Query(default=50, ge=1, le=100, description="Number of results"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[Dict[str, Any]]:
"""Get reward leaderboard"""
@@ -406,7 +408,7 @@ async def get_reward_leaderboard(
@router.get("/tiers")
async def get_reward_tiers(
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[Dict[str, Any]]:
"""Get reward tier configurations"""
@@ -443,7 +445,7 @@ async def get_reward_tiers(
async def get_agent_milestones(
agent_id: str,
include_completed: bool = Query(default=True, description="Include completed milestones"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[MilestoneResponse]:
"""Get milestones for an agent"""
@@ -487,7 +489,7 @@ async def get_reward_distributions(
agent_id: str,
limit: int = Query(default=20, ge=1, le=100),
status: Optional[str] = Query(default=None, description="Filter by status"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[Dict[str, Any]]:
"""Get reward distribution history for an agent"""
@@ -527,7 +529,7 @@ async def get_reward_distributions(
@router.post("/simulate-reward")
async def simulate_reward_calculation(
reward_request: RewardRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Simulate reward calculation without distributing"""

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
Services router for specific GPU workloads
"""
@@ -20,7 +22,7 @@ from ..models.services import (
)
# from ..models.registry import ServiceRegistry, service_registry
from ..services import JobService
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
router = APIRouter(tags=["services"])
@@ -35,7 +37,7 @@ router = APIRouter(tags=["services"])
async def submit_service_job(
service_type: ServiceType,
request_data: Dict[str, Any],
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
user_agent: str = Header(None),
) -> ServiceResponse:
@@ -118,7 +120,7 @@ async def submit_service_job(
)
async def whisper_transcribe(
request: WhisperRequest,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
) -> ServiceResponse:
"""Transcribe audio file using Whisper"""
@@ -153,7 +155,7 @@ async def whisper_transcribe(
)
async def whisper_translate(
request: WhisperRequest,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
) -> ServiceResponse:
"""Translate audio file using Whisper"""
@@ -191,7 +193,7 @@ async def whisper_translate(
)
async def stable_diffusion_generate(
request: StableDiffusionRequest,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
) -> ServiceResponse:
"""Generate images using Stable Diffusion"""
@@ -226,7 +228,7 @@ async def stable_diffusion_generate(
)
async def stable_diffusion_img2img(
request: StableDiffusionRequest,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
) -> ServiceResponse:
"""Image-to-image generation using Stable Diffusion"""
@@ -265,7 +267,7 @@ async def stable_diffusion_img2img(
)
async def llm_inference(
request: LLMRequest,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
) -> ServiceResponse:
"""Run inference on a language model"""
@@ -298,7 +300,7 @@ async def llm_inference(
)
async def llm_stream(
request: LLMRequest,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
):
"""Stream LLM inference response"""
@@ -338,7 +340,7 @@ async def llm_stream(
)
async def ffmpeg_transcode(
request: FFmpegRequest,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
) -> ServiceResponse:
"""Transcode video using FFmpeg"""
@@ -375,7 +377,7 @@ async def ffmpeg_transcode(
)
async def blender_render(
request: BlenderRequest,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
client_id: str = Depends(require_client_key()),
) -> ServiceResponse:
"""Render scene using Blender"""

View File

@@ -1,3 +1,4 @@
from typing import Annotated
"""
Staking Management API
REST API for AI agent staking system with reputation-based yield farming
@@ -9,7 +10,7 @@ from typing import List, Optional, Dict, Any
from datetime import datetime, timedelta
from pydantic import BaseModel, Field, validator
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..logging import get_logger
from ..domain.bounty import (
AgentStake, AgentMetrics, StakingPool, StakeStatus,
@@ -137,7 +138,7 @@ class EarningsDistributionRequest(BaseModel):
distribution_data: Dict[str, Any] = Field(default_factory=dict)
# Dependency injection
def get_staking_service(session: SessionDep) -> StakingService:
def get_staking_service(session: Annotated[Session, Depends(get_session)]) -> StakingService:
return StakingService(session)
def get_blockchain_service() -> BlockchainService:
@@ -148,7 +149,7 @@ def get_blockchain_service() -> BlockchainService:
async def create_stake(
request: StakeCreateRequest,
background_tasks: BackgroundTasks,
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
staking_service: StakingService = Depends(get_staking_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
@@ -189,7 +190,7 @@ async def create_stake(
@router.get("/stake/{stake_id}", response_model=StakeResponse)
async def get_stake(
stake_id: str,
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
staking_service: StakingService = Depends(get_staking_service),
current_user: dict = Depends(get_current_user)
):
@@ -214,7 +215,7 @@ async def get_stake(
@router.get("/stakes", response_model=List[StakeResponse])
async def get_stakes(
filters: StakingFilterRequest = Depends(),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
staking_service: StakingService = Depends(get_staking_service),
current_user: dict = Depends(get_current_user)
):
@@ -243,7 +244,7 @@ async def add_to_stake(
stake_id: str,
request: StakeUpdateRequest,
background_tasks: BackgroundTasks,
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
staking_service: StakingService = Depends(get_staking_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
@@ -286,7 +287,7 @@ async def add_to_stake(
async def unbond_stake(
stake_id: str,
background_tasks: BackgroundTasks,
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
staking_service: StakingService = Depends(get_staking_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
@@ -328,7 +329,7 @@ async def unbond_stake(
async def complete_unbonding(
stake_id: str,
background_tasks: BackgroundTasks,
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
staking_service: StakingService = Depends(get_staking_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
@@ -371,7 +372,7 @@ async def complete_unbonding(
@router.get("/stake/{stake_id}/rewards")
async def get_stake_rewards(
stake_id: str,
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
staking_service: StakingService = Depends(get_staking_service),
current_user: dict = Depends(get_current_user)
):
@@ -406,7 +407,7 @@ async def get_stake_rewards(
@router.get("/agents/{agent_wallet}/metrics", response_model=AgentMetricsResponse)
async def get_agent_metrics(
agent_wallet: str,
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
staking_service: StakingService = Depends(get_staking_service)
):
"""Get agent performance metrics"""
@@ -426,7 +427,7 @@ async def get_agent_metrics(
@router.get("/agents/{agent_wallet}/staking-pool", response_model=StakingPoolResponse)
async def get_staking_pool(
agent_wallet: str,
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
staking_service: StakingService = Depends(get_staking_service)
):
"""Get staking pool information for an agent"""
@@ -447,7 +448,7 @@ async def get_staking_pool(
async def get_agent_apy(
agent_wallet: str,
lock_period: int = Field(default=30, ge=1, le=365),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
staking_service: StakingService = Depends(get_staking_service)
):
"""Get current APY for staking on an agent"""
@@ -471,7 +472,7 @@ async def update_agent_performance(
agent_wallet: str,
request: AgentPerformanceUpdateRequest,
background_tasks: BackgroundTasks,
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
staking_service: StakingService = Depends(get_staking_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
@@ -509,7 +510,7 @@ async def distribute_agent_earnings(
agent_wallet: str,
request: EarningsDistributionRequest,
background_tasks: BackgroundTasks,
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
staking_service: StakingService = Depends(get_staking_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
@@ -552,7 +553,7 @@ async def get_supported_agents(
page: int = Field(default=1, ge=1),
limit: int = Field(default=50, ge=1, le=100),
tier: Optional[PerformanceTier] = None,
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
staking_service: StakingService = Depends(get_staking_service)
):
"""Get list of supported agents for staking"""
@@ -577,7 +578,7 @@ async def get_supported_agents(
@router.get("/staking/stats", response_model=StakingStatsResponse)
async def get_staking_stats(
period: str = Field(default="daily", regex="^(hourly|daily|weekly|monthly)$"),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
staking_service: StakingService = Depends(get_staking_service)
):
"""Get staking system statistics"""
@@ -595,7 +596,7 @@ async def get_staking_leaderboard(
period: str = Field(default="weekly", regex="^(daily|weekly|monthly)$"),
metric: str = Field(default="total_staked", regex="^(total_staked|total_rewards|apy)$"),
limit: int = Field(default=50, ge=1, le=100),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
staking_service: StakingService = Depends(get_staking_service)
):
"""Get staking leaderboard"""
@@ -618,7 +619,7 @@ async def get_my_staking_positions(
agent_wallet: Optional[str] = None,
page: int = Field(default=1, ge=1),
limit: int = Field(default=20, ge=1, le=100),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
staking_service: StakingService = Depends(get_staking_service),
current_user: dict = Depends(get_current_user)
):
@@ -641,7 +642,7 @@ async def get_my_staking_positions(
@router.get("/staking/my-rewards")
async def get_my_staking_rewards(
period: str = Field(default="monthly", regex="^(daily|weekly|monthly)$"),
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
staking_service: StakingService = Depends(get_staking_service),
current_user: dict = Depends(get_current_user)
):
@@ -662,7 +663,7 @@ async def get_my_staking_rewards(
async def claim_staking_rewards(
stake_ids: List[str],
background_tasks: BackgroundTasks,
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
staking_service: StakingService = Depends(get_staking_service),
blockchain_service: BlockchainService = Depends(get_blockchain_service),
current_user: dict = Depends(get_current_user)
@@ -709,7 +710,7 @@ async def claim_staking_rewards(
@router.get("/staking/risk-assessment/{agent_wallet}")
async def get_risk_assessment(
agent_wallet: str,
session: SessionDep = Depends(),
session: Annotated[Session, Depends(get_session)] = Depends(),
staking_service: StakingService = Depends(get_staking_service)
):
"""Get risk assessment for staking on an agent"""

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
P2P Trading Protocol API Endpoints
REST API for agent-to-agent trading, matching, negotiation, and settlement
@@ -9,7 +11,7 @@ from fastapi import APIRouter, HTTPException, Depends, Query
from pydantic import BaseModel, Field
from aitbc.logging import get_logger
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..services.trading_service import P2PTradingProtocol
from ..domain.trading import (
TradeRequest, TradeMatch, TradeNegotiation, TradeAgreement, TradeSettlement,
@@ -154,7 +156,7 @@ class TradingSummaryResponse(BaseModel):
@router.post("/requests", response_model=TradeRequestResponse)
async def create_trade_request(
request_data: TradeRequestRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> TradeRequestResponse:
"""Create a new trade request"""
@@ -216,7 +218,7 @@ async def create_trade_request(
@router.get("/requests/{request_id}", response_model=TradeRequestResponse)
async def get_trade_request(
request_id: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> TradeRequestResponse:
"""Get trade request details"""
@@ -254,7 +256,7 @@ async def get_trade_request(
@router.post("/requests/{request_id}/matches")
async def find_matches(
request_id: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[str]:
"""Find matching sellers for a trade request"""
@@ -274,7 +276,7 @@ async def find_matches(
@router.get("/requests/{request_id}/matches")
async def get_trade_matches(
request_id: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[TradeMatchResponse]:
"""Get trade matches for a request"""
@@ -314,7 +316,7 @@ async def get_trade_matches(
@router.post("/negotiations", response_model=NegotiationResponse)
async def initiate_negotiation(
negotiation_data: NegotiationRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> NegotiationResponse:
"""Initiate negotiation between buyer and seller"""
@@ -352,7 +354,7 @@ async def initiate_negotiation(
@router.get("/negotiations/{negotiation_id}", response_model=NegotiationResponse)
async def get_negotiation(
negotiation_id: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> NegotiationResponse:
"""Get negotiation details"""
@@ -389,7 +391,7 @@ async def get_negotiation(
@router.get("/matches/{match_id}")
async def get_trade_match(
match_id: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> TradeMatchResponse:
"""Get trade match details"""
@@ -430,7 +432,7 @@ async def get_trade_match(
@router.get("/agents/{agent_id}/summary", response_model=TradingSummaryResponse)
async def get_trading_summary(
agent_id: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> TradingSummaryResponse:
"""Get comprehensive trading summary for an agent"""
@@ -452,7 +454,7 @@ async def list_trade_requests(
trade_type: Optional[str] = Query(default=None, description="Filter by trade type"),
status: Optional[str] = Query(default=None, description="Filter by status"),
limit: int = Query(default=50, ge=1, le=100, description="Number of results"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[TradeRequestResponse]:
"""List trade requests with filters"""
@@ -500,7 +502,7 @@ async def list_trade_matches(
min_score: Optional[float] = Query(default=None, description="Minimum match score"),
status: Optional[str] = Query(default=None, description="Filter by status"),
limit: int = Query(default=50, ge=1, le=100, description="Number of results"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[TradeMatchResponse]:
"""List trade matches with filters"""
@@ -556,7 +558,7 @@ async def list_negotiations(
status: Optional[str] = Query(default=None, description="Filter by status"),
strategy: Optional[str] = Query(default=None, description="Filter by strategy"),
limit: int = Query(default=50, ge=1, le=100, description="Number of results"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> List[NegotiationResponse]:
"""List negotiations with filters"""
@@ -607,7 +609,7 @@ async def get_trading_analytics(
period_type: str = Query(default="daily", description="Period type: daily, weekly, monthly"),
start_date: Optional[str] = Query(default=None, description="Start date (ISO format)"),
end_date: Optional[str] = Query(default=None, description="End date (ISO format)"),
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Get P2P trading analytics"""
@@ -671,7 +673,7 @@ async def get_trading_analytics(
@router.post("/simulate-match")
async def simulate_trade_matching(
request_data: TradeRequestRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Simulate trade matching without creating actual request"""

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
User Management Router for AITBC
"""
@@ -10,7 +12,7 @@ import time
import hashlib
from datetime import datetime, timedelta
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
from ..domain import User, Wallet
from ..schemas import UserCreate, UserLogin, UserProfile, UserBalance
@@ -50,7 +52,7 @@ def verify_session_token(token: str) -> Optional[str]:
@router.post("/register", response_model=UserProfile)
async def register_user(
user_data: UserCreate,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Register a new user"""
@@ -103,7 +105,7 @@ async def register_user(
@router.post("/login", response_model=UserProfile)
async def login_user(
login_data: UserLogin,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Login user with wallet address"""
@@ -161,7 +163,7 @@ async def login_user(
@router.get("/users/me", response_model=UserProfile)
async def get_current_user(
token: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Get current user profile"""
@@ -190,7 +192,7 @@ async def get_current_user(
@router.get("/users/{user_id}/balance", response_model=UserBalance)
async def get_user_balance(
user_id: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Get user's AITBC balance"""
@@ -223,7 +225,7 @@ async def logout_user(token: str) -> Dict[str, str]:
@router.get("/users/{user_id}/transactions")
async def get_user_transactions(
user_id: str,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""Get user's transaction history"""

View File

@@ -1,3 +1,5 @@
from sqlalchemy.orm import Session
from typing import Annotated
"""
ZK Applications Router - Privacy-preserving features for AITBC
"""
@@ -11,7 +13,7 @@ from datetime import datetime
import json
from ..schemas import UserProfile
from ..storage import SessionDep
from ..storage import Annotated[Session, Depends(get_session)], get_session
router = APIRouter(tags=["zk-applications"])
@@ -48,7 +50,7 @@ class ZKComputationRequest(BaseModel):
@router.post("/zk/identity/commit")
async def create_identity_commitment(
user: UserProfile,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
salt: Optional[str] = None
) -> Dict[str, str]:
"""Create a privacy-preserving identity commitment"""
@@ -72,7 +74,7 @@ async def create_identity_commitment(
@router.post("/zk/membership/verify")
async def verify_group_membership(
request: ZKMembershipRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""
Verify that a user is a member of a group without revealing which user
@@ -111,7 +113,7 @@ async def verify_group_membership(
@router.post("/zk/marketplace/private-bid")
async def submit_private_bid(
request: PrivateBidRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, str]:
"""
Submit a bid to the marketplace without revealing the amount
@@ -137,7 +139,7 @@ async def submit_private_bid(
@router.get("/zk/marketplace/auctions/{auction_id}/bids")
async def get_auction_bids(
auction_id: str,
session: SessionDep,
session: Annotated[Session, Depends(get_session)] = Depends(),
reveal: bool = False
) -> Dict[str, Any]:
"""
@@ -176,7 +178,7 @@ async def get_auction_bids(
@router.post("/zk/computation/verify")
async def verify_computation_proof(
request: ZKComputationRequest,
session: SessionDep
session: Annotated[Session, Depends(get_session)] = Depends()
) -> Dict[str, Any]:
"""
Verify that an AI computation was performed correctly without revealing inputs