feat(core-api): add AI stats widget with proxy endpoints

Implements Phase 2 of AI performance monitoring - creating a visual
dashboard widget for Organizr to display real-time AI metrics.

New Components:
- src/clients/ai_client.py: HTTP client for Core-AI service
  - Async HTTP requests to core-ai:8086
  - Fetches metrics, errors, and tool failures
  - Health check and metrics reset operations

- src/controllers/ai_controller.py: Proxy controller for AI metrics
  - GET /ai/health - Core-AI health check
  - GET /ai/metrics - Comprehensive performance metrics (proxied)
  - GET /ai/metrics/errors - Recent request errors (proxied)
  - GET /ai/metrics/tool-failures - Tool execution failures (proxied)
  - POST /ai/metrics/reset - Reset all metrics (admin)

- static/widgets/ai-stats.html: Performance dashboard widget
  - 4-panel grid layout: Agent, Tools, Memory, Health
  - Real-time metrics with 10-second auto-refresh
  - Color-coded performance indicators (excellent/good/warning/critical)
  - Response time thresholds: <1s excellent, <3s good, <10s warning
  - Success rate thresholds: >99% excellent, >95% good, >90% warning
  - Top 5 tools display with call counts and success rates
  - Transparent background for Organizr dark theme
  - Responsive design with mobile support

Configuration:
- src/config.py: Added core_ai_base_url setting
- src/main.py: Registered ai_router for /ai/* endpoints

Architecture:
┌─────────────────────────────────────────────┐
│ Browser (Organizr iFrame)                   │
│ ↓ Fetches /ai/metrics                       │
└─────────────────────────────────────────────┘
         ↓
┌─────────────────────────────────────────────┐
│ core-api:8083 (api.schweitz.net)           │
│ - Serves widget HTML                        │
│ - Proxies metrics requests                  │
└─────────────────────────────────────────────┘
         ↓
┌─────────────────────────────────────────────┐
│ core-ai:8086 (internal)                    │
│ - Collects metrics                          │
│ - Returns JSON data                         │
└─────────────────────────────────────────────┘

Benefits:
- External access via api.schweitz.net (proxy approach)
- No CORS issues (same-origin requests)
- Core-AI remains internal-only
- Single integration point with Organizr

Integration with Organizr:
1. Go to Settings → Customize → Homepage Items
2. Add New Item:
   - Name: "AI Performance Stats"
   - Type: iFrame
   - URL: http://localhost:8083/static/widgets/ai-stats.html
   - Authentication: User
3. Position widget on dashboard

Tested:
 Proxy endpoints responding correctly
 Widget accessible via /static/widgets/
 Metrics data flowing from core-ai → core-api → browser
 Color coding and formatting working
 Auto-refresh functional

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-12-04 08:58:43 +01:00
co-authored by Claude
parent 632b20febe
commit 0ac1128b04
5 changed files with 912 additions and 0 deletions
+197
View File
@@ -0,0 +1,197 @@
"""
Core-AI HTTP Client
Provides interface to Core-AI service for AI performance metrics.
"""
import httpx
from typing import Optional, Dict, List, Any
from src.logging_config import get_logger
from src.config import get_settings
logger = get_logger(__name__)
settings = get_settings()
class CoreAIClient:
"""
HTTP client for Core-AI service
Provides access to AI performance metrics, tool execution stats,
and memory system monitoring.
"""
def __init__(
self,
base_url: Optional[str] = None,
timeout: int = 10
):
"""
Initialize Core-AI client
Args:
base_url: Core-AI base URL (default from settings)
timeout: Request timeout in seconds
"""
self.base_url = (base_url or getattr(settings, 'core_ai_base_url', 'http://core-ai:8086')).rstrip("/")
self.timeout = timeout
self.client = httpx.AsyncClient(timeout=self.timeout)
async def close(self):
"""Close the HTTP client"""
await self.client.aclose()
async def health_check(self) -> bool:
"""
Check if Core-AI service is accessible
Returns:
True if accessible, False otherwise
"""
try:
response = await self.client.get(f"{self.base_url}/health")
return response.status_code == 200
except Exception as e:
logger.error(f"Core-AI health check failed: {e}")
return False
async def get_metrics(self) -> Dict[str, Any]:
"""
Get comprehensive AI performance metrics
Returns:
Dict with agent performance, tool execution, memory stats
Example:
{
"uptime_seconds": 3600,
"timestamp": "2025-12-03T20:00:00Z",
"agent": {
"total_requests": 100,
"avg_response_time_ms": 1250.5,
"p95_response_time_ms": 3200.0,
...
},
"tools": {
"total_calls": 250,
"success_rate": 0.98,
"top_tools": {...}
},
"memory": {
"tier1_hit_rate": 0.85,
...
},
...
}
"""
try:
response = await self.client.get(f"{self.base_url}/metrics")
response.raise_for_status()
return response.json()
except httpx.HTTPStatusError as e:
logger.error(f"Failed to get metrics: HTTP {e.response.status_code}")
raise
except Exception as e:
logger.error(f"Failed to get metrics: {e}")
raise
async def get_recent_errors(self, limit: int = 20) -> List[Dict[str, Any]]:
"""
Get recent request errors
Args:
limit: Maximum number of errors to return
Returns:
List of error records with timestamps
Example:
[
{
"timestamp": "2025-12-03T19:45:12Z",
"agent_type": "pydantic",
"error": "Connection timeout",
"duration_ms": 5000
},
...
]
"""
try:
response = await self.client.get(
f"{self.base_url}/metrics/errors",
params={"limit": limit}
)
response.raise_for_status()
data = response.json()
return data.get("errors", [])
except Exception as e:
logger.error(f"Failed to get recent errors: {e}")
raise
async def get_tool_failures(self, limit: int = 20) -> List[Dict[str, Any]]:
"""
Get recent tool execution failures
Args:
limit: Maximum number of failures to return
Returns:
List of tool failure records
Example:
[
{
"timestamp": "2025-12-03T19:50:30Z",
"tool_name": "list_containers",
"error": "Connection refused",
"duration_ms": 150
},
...
]
"""
try:
response = await self.client.get(
f"{self.base_url}/metrics/tool-failures",
params={"limit": limit}
)
response.raise_for_status()
data = response.json()
return data.get("failures", [])
except Exception as e:
logger.error(f"Failed to get tool failures: {e}")
raise
async def reset_metrics(self) -> bool:
"""
Reset all metrics (admin operation)
Returns:
True if successful
"""
try:
response = await self.client.post(f"{self.base_url}/metrics/reset")
response.raise_for_status()
logger.info("Successfully reset Core-AI metrics")
return True
except Exception as e:
logger.error(f"Failed to reset metrics: {e}")
raise
async def __aenter__(self):
"""Async context manager entry"""
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
"""Async context manager exit"""
await self.close()
# Singleton instance
_ai_client: Optional[CoreAIClient] = None
def get_ai_client() -> CoreAIClient:
"""Get singleton Core-AI client instance"""
global _ai_client
if _ai_client is None:
_ai_client = CoreAIClient()
return _ai_client
+3
View File
@@ -116,6 +116,9 @@ class Settings(BaseSettings):
kuma_password: str = KUMA_PASSWORD
kuma_api_key: str = KUMA_API_KEY
# Core-AI Service (AI performance metrics)
core_ai_base_url: str = "http://core-ai:8086"
# OIDC Authentication (Authentik)
oidc_enabled: bool = False # Set to True to require authentication
oidc_issuer: str = "https://auth.schweitz.net/application/o/core-api/"
@@ -0,0 +1,219 @@
"""
AI Metrics Proxy Controller
Provides proxy endpoints to Core-AI service metrics.
Allows external access to AI performance stats via core-api.
"""
from fastapi import APIRouter, HTTPException
from typing import Dict, List, Any
from src.clients.ai_client import get_ai_client
from src.logging_config import get_logger
logger = get_logger(__name__)
# Create router
router = APIRouter(
prefix="/ai",
tags=["AI Metrics"]
)
@router.get(
"/health",
summary="Check Core-AI service health",
description="Verify that the Core-AI service is accessible and responding"
)
async def ai_health_check():
"""
Check if Core-AI service is healthy
Returns:
Health status and availability
"""
try:
ai_client = get_ai_client()
is_healthy = await ai_client.health_check()
return {
"service": "core-ai",
"status": "healthy" if is_healthy else "unhealthy",
"accessible": is_healthy
}
except Exception as e:
logger.error(f"AI health check failed: {e}")
return {
"service": "core-ai",
"status": "error",
"accessible": False,
"error": str(e)
}
@router.get(
"/metrics",
response_model=Dict[str, Any],
summary="Get comprehensive AI performance metrics",
description="Returns detailed metrics including agent performance, tool execution stats, memory system metrics, and user activity"
)
async def get_ai_metrics():
"""
Proxy endpoint for Core-AI metrics
Returns comprehensive AI performance data:
- Agent request statistics (total, by type, response times)
- Response time percentiles (p50, p95, p99)
- Tool execution metrics (calls, success rates, durations)
- Memory system statistics (cache hits, consolidations)
- User activity tracking
- Concurrency metrics
Returns:
Dict with all collected metrics
Raises:
HTTPException: If Core-AI is unreachable or returns error
"""
try:
ai_client = get_ai_client()
metrics = await ai_client.get_metrics()
return metrics
except Exception as e:
logger.error(f"Failed to fetch AI metrics: {e}")
raise HTTPException(
status_code=503,
detail=f"Core-AI service unavailable: {str(e)}"
)
@router.get(
"/metrics/errors",
response_model=Dict[str, Any],
summary="Get recent request errors",
description="Returns recent AI agent request errors with timestamps and details"
)
async def get_ai_errors(limit: int = 20):
"""
Get recent AI request errors
Args:
limit: Maximum number of errors to return (default: 20)
Returns:
Dict with error list and total count
Example response:
{
"errors": [
{
"timestamp": "2025-12-03T19:45:12Z",
"agent_type": "pydantic",
"error": "Connection timeout",
"duration_ms": 5000
}
],
"total": 1
}
"""
try:
ai_client = get_ai_client()
errors = await ai_client.get_recent_errors(limit=limit)
return {
"errors": errors,
"total": len(errors)
}
except Exception as e:
logger.error(f"Failed to fetch AI errors: {e}")
raise HTTPException(
status_code=503,
detail=f"Core-AI service unavailable: {str(e)}"
)
@router.get(
"/metrics/tool-failures",
response_model=Dict[str, Any],
summary="Get recent tool execution failures",
description="Returns recent tool execution failures with error details"
)
async def get_ai_tool_failures(limit: int = 20):
"""
Get recent tool execution failures
Args:
limit: Maximum number of failures to return (default: 20)
Returns:
Dict with failure list and total count
Example response:
{
"failures": [
{
"timestamp": "2025-12-03T19:50:30Z",
"tool_name": "list_containers",
"error": "Connection refused",
"duration_ms": 150
}
],
"total": 1
}
"""
try:
ai_client = get_ai_client()
failures = await ai_client.get_tool_failures(limit=limit)
return {
"failures": failures,
"total": len(failures)
}
except Exception as e:
logger.error(f"Failed to fetch tool failures: {e}")
raise HTTPException(
status_code=503,
detail=f"Core-AI service unavailable: {str(e)}"
)
@router.post(
"/metrics/reset",
summary="Reset all AI metrics (admin)",
description="Clear all collected metrics. This is an administrative operation that resets all counters and history."
)
async def reset_ai_metrics():
"""
Reset all AI metrics (admin operation)
Clears all collected metrics including:
- Request history
- Tool execution stats
- Memory system metrics
- Error logs
Returns:
Success confirmation
Note:
This is an administrative operation that should be used carefully.
All historical data will be lost.
"""
try:
ai_client = get_ai_client()
await ai_client.reset_metrics()
logger.info("AI metrics reset successfully")
return {
"success": True,
"message": "AI metrics reset successfully"
}
except Exception as e:
logger.error(f"Failed to reset AI metrics: {e}")
raise HTTPException(
status_code=503,
detail=f"Core-AI service unavailable: {str(e)}"
)
+2
View File
@@ -13,6 +13,7 @@ from src.controllers.infrastructure_controller import infrastructure_controller
from src.controllers.tools_controller import tools_controller
from src.controllers.health_controller import health_controller
from src.controllers.static_controller import static_controller
from src.controllers.ai_controller import router as ai_router
from src.security import initialize_oidc
# Initialize settings
@@ -150,6 +151,7 @@ app.include_router(health_controller.router) # / and /health
app.include_router(tools_controller.router) # /web-scraper/scrape
app.include_router(infrastructure_controller.router) # /infrastructure/*
app.include_router(static_controller.router) # /static/*
app.include_router(ai_router) # /ai/*
# Global exception handler
@@ -0,0 +1,491 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Performance Stats</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: transparent;
color: #e0e0e0;
padding: 15px;
}
.container {
max-width: 100%;
}
.error {
background: rgba(245, 101, 101, 0.1);
border: 1px solid rgba(245, 101, 101, 0.4);
color: #f56565;
padding: 12px;
border-radius: 6px;
margin-bottom: 15px;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 15px;
margin-bottom: 20px;
}
.stat-panel {
background: rgba(40, 40, 40, 0.95);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 8px;
padding: 16px;
}
.panel-header {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 12px;
padding-bottom: 8px;
border-bottom: 2px solid rgba(255, 255, 255, 0.1);
}
.panel-icon {
font-size: 20px;
}
.panel-title {
font-size: 16px;
font-weight: 600;
color: #fff;
}
.panel-subtitle {
font-size: 11px;
color: #a0a0a0;
margin-left: auto;
}
.metrics-list {
display: flex;
flex-direction: column;
gap: 10px;
}
.metric-row {
display: flex;
justify-content: space-between;
align-items: center;
padding: 6px 0;
}
.metric-label {
font-size: 13px;
color: #b0b0b0;
}
.metric-value {
font-size: 14px;
font-weight: 600;
color: #fff;
}
.metric-value.excellent {
color: #48bb78;
}
.metric-value.good {
color: #68d391;
}
.metric-value.warning {
color: #ed8936;
}
.metric-value.critical {
color: #f56565;
}
.metric-value.neutral {
color: #a0a0a0;
}
.tools-list {
display: flex;
flex-direction: column;
gap: 6px;
}
.tool-row {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 12px;
padding: 4px 8px;
background: rgba(0, 0, 0, 0.2);
border-radius: 4px;
}
.tool-name {
color: #d0d0d0;
font-family: 'Courier New', monospace;
}
.tool-stats {
display: flex;
gap: 12px;
align-items: center;
}
.tool-calls {
color: #a0a0a0;
}
.tool-success-rate {
font-weight: 600;
}
.bottom-links {
display: flex;
gap: 15px;
justify-content: center;
padding-top: 10px;
}
.link-btn {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 8px 14px;
background: rgba(66, 153, 225, 0.15);
color: #4299e1;
text-decoration: none;
border-radius: 4px;
font-size: 12px;
font-weight: 600;
transition: all 0.2s;
}
.link-btn:hover {
background: rgba(66, 153, 225, 0.25);
transform: translateY(-1px);
}
.loading {
text-align: center;
padding: 30px;
color: #a0a0a0;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.spinner {
display: inline-block;
width: 14px;
height: 14px;
border: 2px solid rgba(255, 255, 255, 0.3);
border-top-color: #fff;
border-radius: 50%;
animation: spin 0.6s linear infinite;
margin-right: 8px;
}
.badge {
display: inline-block;
font-size: 10px;
padding: 2px 6px;
border-radius: 3px;
font-weight: 600;
text-transform: uppercase;
}
.badge.success {
background: rgba(72, 187, 120, 0.2);
color: #48bb78;
}
.badge.error {
background: rgba(245, 101, 101, 0.2);
color: #f56565;
}
/* Responsive design */
@media (max-width: 768px) {
.stats-grid {
grid-template-columns: 1fr;
}
}
</style>
</head>
<body>
<div class="container">
<div id="error-container"></div>
<div id="stats-container" class="loading">
<div class="spinner"></div>Loading AI performance metrics...
</div>
</div>
<script>
// Use relative URL to work in any context
const API_BASE = '';
let metricsData = null;
function formatDuration(ms) {
if (ms < 1000) return `${Math.round(ms)}ms`;
if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
return `${(ms / 60000).toFixed(1)}m`;
}
function formatUptime(seconds) {
if (seconds < 60) return `${seconds}s`;
if (seconds < 3600) return `${Math.floor(seconds / 60)}m`;
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
return `${hours}h ${minutes}m`;
}
function getResponseTimeClass(ms) {
if (ms < 1000) return 'excellent';
if (ms < 3000) return 'good';
if (ms < 10000) return 'warning';
return 'critical';
}
function getSuccessRateClass(rate) {
if (rate >= 0.99) return 'excellent';
if (rate >= 0.95) return 'good';
if (rate >= 0.90) return 'warning';
return 'critical';
}
function getHitRateClass(rate) {
if (rate >= 0.85) return 'excellent';
if (rate >= 0.70) return 'good';
if (rate >= 0.50) return 'warning';
return 'critical';
}
async function fetchMetrics() {
try {
const response = await fetch(`${API_BASE}/ai/metrics`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
metricsData = await response.json();
renderMetrics();
document.getElementById('error-container').innerHTML = '';
} catch (error) {
console.error('Error fetching AI metrics:', error);
document.getElementById('error-container').innerHTML =
`<div class="error">❌ Core-AI service unavailable: ${error.message}</div>`;
document.getElementById('stats-container').innerHTML =
'<div class="loading">Waiting for Core-AI service...</div>';
}
}
function renderMetrics() {
if (!metricsData) return;
const agent = metricsData.agent || {};
const tools = metricsData.tools || {};
const memory = metricsData.memory || {};
const users = metricsData.users || {};
const concurrency = metricsData.concurrency || {};
const html = `
<div class="stats-grid">
<!-- Agent Performance Panel -->
<div class="stat-panel">
<div class="panel-header">
<span class="panel-icon">🤖</span>
<span class="panel-title">Agent Performance</span>
<span class="panel-subtitle">${agent.total_requests || 0} requests</span>
</div>
<div class="metrics-list">
<div class="metric-row">
<span class="metric-label">Avg Response</span>
<span class="metric-value ${getResponseTimeClass(agent.avg_response_time_ms)}">
${formatDuration(agent.avg_response_time_ms || 0)}
</span>
</div>
<div class="metric-row">
<span class="metric-label">P95 Latency</span>
<span class="metric-value ${getResponseTimeClass(agent.p95_response_time_ms)}">
${formatDuration(agent.p95_response_time_ms || 0)}
</span>
</div>
<div class="metric-row">
<span class="metric-label">Requests/min</span>
<span class="metric-value neutral">${(agent.requests_per_minute || 0).toFixed(1)}</span>
</div>
<div class="metric-row">
<span class="metric-label">Errors</span>
<span class="metric-value ${agent.errors_total > 0 ? 'warning' : 'excellent'}">
${agent.errors_total || 0}
</span>
</div>
<div class="metric-row">
<span class="metric-label">Concurrent</span>
<span class="metric-value neutral">
${concurrency.current || 0} / ${concurrency.max || 0} max
</span>
</div>
</div>
</div>
<!-- Tool Execution Panel -->
<div class="stat-panel">
<div class="panel-header">
<span class="panel-icon">🔧</span>
<span class="panel-title">Tool Execution</span>
<span class="panel-subtitle">${tools.total_calls || 0} calls</span>
</div>
<div class="metrics-list">
<div class="metric-row">
<span class="metric-label">Success Rate</span>
<span class="metric-value ${getSuccessRateClass(tools.success_rate || 0)}">
${((tools.success_rate || 0) * 100).toFixed(1)}%
</span>
</div>
<div class="metric-row">
<span class="metric-label">Unique Tools</span>
<span class="metric-value neutral">${tools.total_unique_tools || 0}</span>
</div>
</div>
${renderTopTools(tools.top_tools || {})}
</div>
<!-- Memory System Panel -->
<div class="stat-panel">
<div class="panel-header">
<span class="panel-icon">💾</span>
<span class="panel-title">Memory System</span>
<span class="panel-subtitle">Tier 1 Cache</span>
</div>
<div class="metrics-list">
<div class="metric-row">
<span class="metric-label">Hit Rate</span>
<span class="metric-value ${getHitRateClass(memory.tier1_hit_rate || 0)}">
${((memory.tier1_hit_rate || 0) * 100).toFixed(1)}%
</span>
</div>
<div class="metric-row">
<span class="metric-label">Cache Hits</span>
<span class="metric-value neutral">${memory.tier1_hits || 0}</span>
</div>
<div class="metric-row">
<span class="metric-label">Tier 2 Queries</span>
<span class="metric-value neutral">${memory.tier2_queries || 0}</span>
</div>
<div class="metric-row">
<span class="metric-label">Consolidations</span>
<span class="metric-value neutral">${memory.total_consolidations || 0}</span>
</div>
</div>
</div>
<!-- System Health Panel -->
<div class="stat-panel">
<div class="panel-header">
<span class="panel-icon">📊</span>
<span class="panel-title">System Health</span>
<span class="panel-subtitle">Live Status</span>
</div>
<div class="metrics-list">
<div class="metric-row">
<span class="metric-label">Service Uptime</span>
<span class="metric-value excellent">${formatUptime(metricsData.uptime_seconds || 0)}</span>
</div>
<div class="metric-row">
<span class="metric-label">Active Users</span>
<span class="metric-value neutral">${users.total_active || 0}</span>
</div>
<div class="metric-row">
<span class="metric-label">Streaming</span>
<span class="metric-value neutral">${agent.streaming_requests || 0}</span>
</div>
<div class="metric-row">
<span class="metric-label">Non-Streaming</span>
<span class="metric-value neutral">${agent.non_streaming_requests || 0}</span>
</div>
${renderAgentStatus()}
</div>
</div>
</div>
<div class="bottom-links">
<a href="${API_BASE}/ai/metrics" target="_blank" class="link-btn">
📄 Full Metrics JSON
</a>
<a href="${API_BASE}/ai/health" target="_blank" class="link-btn">
🏥 Health Check
</a>
</div>
`;
document.getElementById('stats-container').innerHTML = html;
}
function renderTopTools(topTools) {
if (!topTools || Object.keys(topTools).length === 0) {
return '<div class="metric-row"><span class="metric-label">No tool calls yet</span></div>';
}
const toolsArray = Object.entries(topTools).slice(0, 5);
const toolsHtml = toolsArray.map(([name, stats]) => {
const successRate = stats.success_rate || 0;
const successClass = getSuccessRateClass(successRate);
return `
<div class="tool-row">
<span class="tool-name">${name}</span>
<div class="tool-stats">
<span class="tool-calls">${stats.calls} calls</span>
<span class="tool-success-rate ${successClass}">
${(successRate * 100).toFixed(0)}%
</span>
</div>
</div>
`;
}).join('');
return `
<div style="margin-top: 8px;">
<div class="metric-label" style="margin-bottom: 6px;">Top 5 Tools:</div>
<div class="tools-list">${toolsHtml}</div>
</div>
`;
}
function renderAgentStatus() {
const agent = metricsData.agent || {};
const hasActivity = (agent.total_requests || 0) > 0;
return `
<div class="metric-row">
<span class="metric-label">Agent Status</span>
<span class="badge ${hasActivity ? 'success' : 'neutral'}">
${hasActivity ? '✓ Active' : 'Idle'}
</span>
</div>
`;
}
// Initial fetch
fetchMetrics();
// Auto-refresh every 10 seconds
setInterval(fetchMetrics, 10000);
</script>
</body>
</html>