Spaces:
Sleeping
Sleeping
File size: 14,208 Bytes
4343907 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 |
"""
Hybrid API Endpoints for SAAP OpenRouter Integration
Additional endpoints to support multi-provider functionality
"""
from fastapi import APIRouter, HTTPException, Depends
from typing import Dict, Optional, Any
import logging
from datetime import datetime
from services.agent_manager_hybrid import HybridAgentManagerService
logger = logging.getLogger(__name__)
# Router for hybrid endpoints
hybrid_router = APIRouter(prefix="/api/v1/hybrid", tags=["hybrid"])
def get_hybrid_manager() -> HybridAgentManagerService:
"""Dependency to get hybrid agent manager (if available)"""
# This will be injected by main.py if hybrid mode is enabled
return None
# =====================================================
# PROVIDER COMPARISON & PERFORMANCE ENDPOINTS
# =====================================================
@hybrid_router.post("/agents/{agent_id}/compare")
async def compare_providers(
agent_id: str,
message_data: Dict[str, str],
hybrid_manager: HybridAgentManagerService = Depends(get_hybrid_manager)
):
"""
π Send same message to both colossus and OpenRouter for comparison
Useful for benchmarking performance and cost analysis
"""
if not hybrid_manager:
raise HTTPException(status_code=503, detail="Hybrid mode not enabled")
try:
message = message_data.get("message", "")
if not message:
raise HTTPException(status_code=400, detail="Message content required")
logger.info(f"π Provider comparison requested for {agent_id}")
# Send to both providers
comparison = await hybrid_manager.compare_providers(agent_id, message)
if "error" in comparison:
return {
"success": False,
"error": comparison["error"],
"timestamp": datetime.utcnow().isoformat()
}
logger.info(f"β
Provider comparison completed for {agent_id}")
return {
"success": True,
"comparison": comparison,
"timestamp": datetime.utcnow().isoformat()
}
except Exception as e:
logger.error(f"β Provider comparison error: {e}")
raise HTTPException(status_code=500, detail=f"Comparison failed: {str(e)}")
@hybrid_router.get("/stats/providers")
async def get_provider_statistics(
hybrid_manager: HybridAgentManagerService = Depends(get_hybrid_manager)
):
"""
π Get comprehensive provider performance statistics
Returns success rates, response times, and cost data
"""
if not hybrid_manager:
raise HTTPException(status_code=503, detail="Hybrid mode not enabled")
try:
stats = hybrid_manager.get_provider_stats()
return {
"success": True,
"statistics": stats,
"timestamp": datetime.utcnow().isoformat()
}
except Exception as e:
logger.error(f"β Provider stats error: {e}")
raise HTTPException(status_code=500, detail=f"Statistics failed: {str(e)}")
@hybrid_router.get("/costs/openrouter")
async def get_openrouter_costs(
hybrid_manager: HybridAgentManagerService = Depends(get_hybrid_manager)
):
"""
π° Get OpenRouter cost summary and budget status
"""
if not hybrid_manager:
raise HTTPException(status_code=503, detail="Hybrid mode not enabled")
if not hybrid_manager.openrouter_client:
raise HTTPException(status_code=503, detail="OpenRouter client not available")
try:
cost_summary = hybrid_manager.openrouter_client.get_cost_summary()
return {
"success": True,
"costs": cost_summary,
"timestamp": datetime.utcnow().isoformat()
}
except Exception as e:
logger.error(f"β OpenRouter cost error: {e}")
raise HTTPException(status_code=500, detail=f"Cost summary failed: {str(e)}")
# =====================================================
# PROVIDER SWITCHING & CONFIGURATION
# =====================================================
@hybrid_router.post("/config/primary-provider")
async def set_primary_provider(
config_data: Dict[str, str],
hybrid_manager: HybridAgentManagerService = Depends(get_hybrid_manager)
):
"""
π Switch primary provider (colossus/openrouter)
"""
if not hybrid_manager:
raise HTTPException(status_code=503, detail="Hybrid mode not enabled")
try:
provider = config_data.get("provider", "")
if provider not in ["colossus", "openrouter"]:
raise HTTPException(status_code=400, detail="Provider must be 'colossus' or 'openrouter'")
success = await hybrid_manager.set_primary_provider(provider)
if success:
return {
"success": True,
"message": f"Primary provider set to {provider}",
"provider": provider,
"timestamp": datetime.utcnow().isoformat()
}
else:
raise HTTPException(status_code=400, detail=f"Failed to switch to {provider}")
except HTTPException:
raise
except Exception as e:
logger.error(f"β Provider switch error: {e}")
raise HTTPException(status_code=500, detail=f"Provider switch failed: {str(e)}")
@hybrid_router.get("/config/status")
async def get_hybrid_status(
hybrid_manager: HybridAgentManagerService = Depends(get_hybrid_manager)
):
"""
βΉοΈ Get hybrid system configuration and status
"""
if not hybrid_manager:
return {
"hybrid_enabled": False,
"message": "Hybrid mode not available",
"timestamp": datetime.utcnow().isoformat()
}
try:
# Check provider availability
providers_status = {
"colossus": {
"available": hybrid_manager.colossus_client is not None,
"status": hybrid_manager.colossus_connection_status if hasattr(hybrid_manager, 'colossus_connection_status') else "unknown"
},
"openrouter": {
"available": hybrid_manager.openrouter_client is not None,
"status": "unknown"
}
}
# Test OpenRouter if available
if hybrid_manager.openrouter_client:
try:
or_health = await hybrid_manager.openrouter_client.health_check()
providers_status["openrouter"]["status"] = or_health.get("status", "unknown")
providers_status["openrouter"]["daily_cost"] = or_health.get("daily_cost", 0)
providers_status["openrouter"]["budget_remaining"] = or_health.get("budget_remaining", 0)
except Exception as e:
providers_status["openrouter"]["status"] = f"error: {e}"
return {
"hybrid_enabled": True,
"primary_provider": hybrid_manager.primary_provider,
"failover_enabled": hybrid_manager.enable_failover,
"cost_comparison_enabled": hybrid_manager.enable_cost_comparison,
"providers": providers_status,
"loaded_agents": len(hybrid_manager.agents),
"timestamp": datetime.utcnow().isoformat()
}
except Exception as e:
logger.error(f"β Hybrid status error: {e}")
raise HTTPException(status_code=500, detail=f"Status check failed: {str(e)}")
# =====================================================
# OPTIONAL: DIRECT PROVIDER ENDPOINTS
# =====================================================
@hybrid_router.post("/agents/{agent_id}/chat/colossus")
async def chat_with_colossus(
agent_id: str,
message_data: Dict[str, str],
hybrid_manager: HybridAgentManagerService = Depends(get_hybrid_manager)
):
"""
π€ Direct chat with agent via colossus (bypass primary provider setting)
"""
if not hybrid_manager:
raise HTTPException(status_code=503, detail="Hybrid mode not enabled")
try:
message = message_data.get("message", "")
if not message:
raise HTTPException(status_code=400, detail="Message content required")
# Force colossus provider
response = await hybrid_manager.send_message_to_agent(agent_id, message, "colossus")
if "error" in response:
return {
"success": False,
"error": response["error"],
"provider": "colossus",
"timestamp": datetime.utcnow().isoformat()
}
return {
"success": True,
"agent_id": agent_id,
"message": message,
"response": response,
"provider": "colossus",
"timestamp": datetime.utcnow().isoformat()
}
except Exception as e:
logger.error(f"β colossus chat error: {e}")
raise HTTPException(status_code=500, detail=f"colossus chat failed: {str(e)}")
@hybrid_router.post("/agents/{agent_id}/chat/openrouter")
async def chat_with_openrouter(
agent_id: str,
message_data: Dict[str, str],
hybrid_manager: HybridAgentManagerService = Depends(get_hybrid_manager)
):
"""
π Direct chat with agent via OpenRouter (bypass primary provider setting)
"""
if not hybrid_manager:
raise HTTPException(status_code=503, detail="Hybrid mode not enabled")
if not hybrid_manager.openrouter_client:
raise HTTPException(status_code=503, detail="OpenRouter client not available")
try:
message = message_data.get("message", "")
if not message:
raise HTTPException(status_code=400, detail="Message content required")
# Force OpenRouter provider
response = await hybrid_manager.send_message_to_agent(agent_id, message, "openrouter")
if "error" in response:
return {
"success": False,
"error": response["error"],
"provider": "openrouter",
"timestamp": datetime.utcnow().isoformat()
}
return {
"success": True,
"agent_id": agent_id,
"message": message,
"response": response,
"provider": "openrouter",
"timestamp": datetime.utcnow().isoformat()
}
except Exception as e:
logger.error(f"β OpenRouter chat error: {e}")
raise HTTPException(status_code=500, detail=f"OpenRouter chat failed: {str(e)}")
# =====================================================
# HEALTH CHECK FOR HYBRID SYSTEM
# =====================================================
@hybrid_router.get("/health")
async def hybrid_health_check(
hybrid_manager: HybridAgentManagerService = Depends(get_hybrid_manager)
):
"""
π₯ Comprehensive health check for hybrid system
"""
if not hybrid_manager:
return {
"status": "hybrid_disabled",
"message": "Hybrid mode not enabled - using standard mode",
"timestamp": datetime.utcnow().isoformat()
}
try:
health_status = {
"status": "healthy",
"providers": {},
"agents_loaded": len(hybrid_manager.agents),
"primary_provider": hybrid_manager.primary_provider,
"timestamp": datetime.utcnow().isoformat()
}
# Check colossus
if hybrid_manager.colossus_client:
try:
# Test colossus connection if method available
if hasattr(hybrid_manager, '_test_colossus_connection'):
await hybrid_manager._test_colossus_connection()
health_status["providers"]["colossus"] = {
"status": getattr(hybrid_manager, 'colossus_connection_status', 'unknown'),
"available": True
}
except Exception as e:
health_status["providers"]["colossus"] = {
"status": f"error: {e}",
"available": False
}
else:
health_status["providers"]["colossus"] = {
"status": "not_configured",
"available": False
}
# Check OpenRouter
if hybrid_manager.openrouter_client:
try:
or_health = await hybrid_manager.openrouter_client.health_check()
health_status["providers"]["openrouter"] = {
"status": or_health.get("status", "unknown"),
"available": or_health.get("status") == "healthy",
"daily_cost": or_health.get("daily_cost", 0),
"budget_remaining": or_health.get("budget_remaining", 0)
}
except Exception as e:
health_status["providers"]["openrouter"] = {
"status": f"error: {e}",
"available": False
}
else:
health_status["providers"]["openrouter"] = {
"status": "not_configured",
"available": False
}
# Overall health status
provider_count = sum(1 for p in health_status["providers"].values() if p["available"])
if provider_count == 0:
health_status["status"] = "unhealthy"
health_status["message"] = "No providers available"
elif provider_count == 1:
health_status["status"] = "degraded"
health_status["message"] = "Only one provider available"
else:
health_status["status"] = "healthy"
health_status["message"] = "All providers operational"
return health_status
except Exception as e:
logger.error(f"β Hybrid health check error: {e}")
return {
"status": "error",
"error": str(e),
"timestamp": datetime.utcnow().isoformat()
}
# Export router for main.py integration
__all__ = ["hybrid_router", "get_hybrid_manager"] |