feat: add prometheus token tracking plugin
This commit is contained in:
@@ -0,0 +1,254 @@
|
||||
"""prometheus_token_tracking - Hermes plugin for Prometheus-based LLM token tracking.
|
||||
|
||||
Tracks LLM token usage per room and exposes metrics via Prometheus endpoint.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Dict, Optional
|
||||
from collections import defaultdict
|
||||
from http.server import HTTPServer, BaseHTTPRequestHandler
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
import threading
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Global state for metrics
|
||||
_METRICS_LOCK = threading.Lock()
|
||||
_TOKEN_METRICS: Dict[str, Dict[str, int]] = defaultdict(lambda: defaultdict(int))
|
||||
_COST_METRICS: Dict[str, Dict[str, float]] = defaultdict(lambda: defaultdict(float))
|
||||
_REQUEST_METRICS: Dict[str, Dict[str, int]] = defaultdict(lambda: defaultdict(int))
|
||||
|
||||
# Prometheus metrics format template
|
||||
PROMETHEUS_TEMPLATE = """# HELP room_llm_input_tokens_total Total input tokens consumed by room
|
||||
# TYPE room_llm_input_tokens_total counter
|
||||
{input_metrics}
|
||||
|
||||
# HELP room_llm_output_tokens_total Total output tokens consumed by room
|
||||
# TYPE room_llm_output_tokens_total counter
|
||||
{output_metrics}
|
||||
|
||||
# HELP room_llm_cost_total Total cost in USD by room
|
||||
# TYPE room_llm_cost_total counter
|
||||
{cost_metrics}
|
||||
|
||||
# HELP room_llm_requests_total Total LLM requests by room
|
||||
# TYPE room_llm_requests_total counter
|
||||
{request_metrics}
|
||||
"""
|
||||
|
||||
def _get_env(name: str, default: str = "") -> str:
|
||||
return os.environ.get(name, default).strip()
|
||||
|
||||
def _env_bool(*names: str) -> bool:
|
||||
for name in names:
|
||||
value = _get_env(name).lower()
|
||||
if value:
|
||||
return value in {"1", "true", "yes", "on"}
|
||||
return False
|
||||
|
||||
@dataclass
|
||||
class RoomMetrics:
|
||||
room_id: str
|
||||
model: str
|
||||
provider: str
|
||||
|
||||
def metric_key(self) -> str:
|
||||
return f'room_id="{self.room_id}",model="{self.model}",provider="{self.provider}"'
|
||||
|
||||
def _trace_key(task_id: str, session_id: str) -> str:
|
||||
"""Generate a unique trace key for task/session combination."""
|
||||
return f"{task_id}:{session_id}"
|
||||
|
||||
def _extract_room_context(task_id: str = "", session_id: str = "", platform: str = "") -> Optional[str]:
|
||||
"""Extract room context from session information.
|
||||
|
||||
For Rocket.Chat integration:
|
||||
- Channel rooms: Direct room_id
|
||||
- DM rooms: Mapped to user:<username> virtual rooms
|
||||
"""
|
||||
# Extract real Rocket.Chat room_id from context variable
|
||||
try:
|
||||
# Import the context variable from Rocket.Chat adapter
|
||||
from .adapter import _CURRENT_ORIGIN_ROOM
|
||||
room_id = _CURRENT_ORIGIN_ROOM.get()
|
||||
if room_id:
|
||||
return room_id
|
||||
except (ImportError, AttributeError):
|
||||
pass
|
||||
|
||||
# Fallback to session-based mapping for virtual DM rooms
|
||||
if task_id or session_id:
|
||||
# This maps DM sessions to user-based virtual rooms
|
||||
# Format follows Rocket.Chat adapter pattern: user:<username>
|
||||
return f"user:session_{hash(task_id + session_id) % 1000}"
|
||||
return "default"
|
||||
|
||||
def _calculate_cost(input_tokens: int, output_tokens: int, model: str, provider: str) -> float:
|
||||
"""Calculate cost based on model and provider pricing.
|
||||
|
||||
This is a simplified implementation - in practice would use a pricing database.
|
||||
"""
|
||||
# Simplified pricing model - would be expanded in full implementation
|
||||
pricing = {
|
||||
("gpt-4", "openai"): {"input": 0.03, "output": 0.06}, # per 1K tokens
|
||||
("claude-3", "anthropic"): {"input": 0.015, "output": 0.075}, # per 1K tokens
|
||||
("llama-3", "together"): {"input": 0.0005, "output": 0.0008}, # per 1K tokens
|
||||
}
|
||||
|
||||
model_key = (model, provider)
|
||||
if model_key in pricing:
|
||||
prices = pricing[model_key]
|
||||
input_cost = (input_tokens / 1000.0) * prices["input"]
|
||||
output_cost = (output_tokens / 1000.0) * prices["output"]
|
||||
return input_cost + output_cost
|
||||
|
||||
# Default pricing if not found
|
||||
return (input_tokens + output_tokens) * 0.0001
|
||||
|
||||
def _extract_token_usage(response: Any) -> tuple[int, int]:
|
||||
"""Extract token usage from LLM response.
|
||||
|
||||
Handles various response formats from different providers.
|
||||
"""
|
||||
input_tokens = 0
|
||||
output_tokens = 0
|
||||
|
||||
if hasattr(response, "usage"):
|
||||
usage = response.usage
|
||||
if hasattr(usage, "prompt_tokens"):
|
||||
input_tokens = usage.prompt_tokens
|
||||
if hasattr(usage, "completion_tokens"):
|
||||
output_tokens = usage.completion_tokens
|
||||
elif hasattr(usage, "output_tokens"):
|
||||
output_tokens = usage.output_tokens
|
||||
elif hasattr(usage, "total_tokens") and input_tokens > 0:
|
||||
output_tokens = usage.total_tokens - input_tokens
|
||||
|
||||
# Handle dict responses
|
||||
elif isinstance(response, dict):
|
||||
usage = response.get("usage", {})
|
||||
if isinstance(usage, dict):
|
||||
input_tokens = usage.get("prompt_tokens", 0) or usage.get("input_tokens", 0)
|
||||
output_tokens = usage.get("completion_tokens", 0) or usage.get("output_tokens", 0)
|
||||
if not output_tokens and "total_tokens" in usage and input_tokens > 0:
|
||||
output_tokens = usage["total_tokens"] - input_tokens
|
||||
|
||||
return input_tokens, output_tokens
|
||||
|
||||
def on_pre_api_request(*, task_id: str = "", session_id: str = "", platform: str = "",
|
||||
model: str = "", provider: str = "", **_: Any) -> None:
|
||||
"""Hook called before API request - capture context."""
|
||||
# Pre-request context is captured in post hook with usage data
|
||||
pass
|
||||
|
||||
def on_post_api_request(*, task_id: str = "", session_id: str = "", platform: str = "",
|
||||
model: str = "", provider: str = "", response: Any = None,
|
||||
**_: Any) -> None:
|
||||
"""Hook called after API request - capture token usage."""
|
||||
if response is None:
|
||||
return
|
||||
|
||||
# Extract room context
|
||||
room_id = _extract_room_context(task_id, session_id, platform)
|
||||
if not room_id:
|
||||
return
|
||||
|
||||
# Extract token usage
|
||||
input_tokens, output_tokens = _extract_token_usage(response)
|
||||
if input_tokens == 0 and output_tokens == 0:
|
||||
return
|
||||
|
||||
# Calculate cost
|
||||
cost = _calculate_cost(input_tokens, output_tokens, model, provider)
|
||||
|
||||
# Update metrics atomically
|
||||
metric_key = f'{room_id},{model},{provider}'
|
||||
|
||||
with _METRICS_LOCK:
|
||||
_TOKEN_METRICS["input"][metric_key] += input_tokens
|
||||
_TOKEN_METRICS["output"][metric_key] += output_tokens
|
||||
_COST_METRICS["total"][metric_key] += cost
|
||||
_REQUEST_METRICS["total"][metric_key] += 1
|
||||
|
||||
class PrometheusMetricsHandler(BaseHTTPRequestHandler):
|
||||
"""HTTP handler for Prometheus metrics endpoint."""
|
||||
|
||||
def do_GET(self):
|
||||
"""Handle GET requests to /metrics endpoint."""
|
||||
if self.path != "/metrics":
|
||||
self.send_error(404, "Not Found")
|
||||
return
|
||||
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/plain; version=0.0.4")
|
||||
self.end_headers()
|
||||
|
||||
# Generate Prometheus metrics output
|
||||
with _METRICS_LOCK:
|
||||
# Format input token metrics
|
||||
input_metrics = []
|
||||
for key, value in _TOKEN_METRICS["input"].items():
|
||||
room_id, model, provider = key.split(",", 2)
|
||||
metric_line = f'room_llm_input_tokens_total{{room_id="{room_id}",model="{model}",provider="{provider}"}} {value}'
|
||||
input_metrics.append(metric_line)
|
||||
|
||||
# Format output token metrics
|
||||
output_metrics = []
|
||||
for key, value in _TOKEN_METRICS["output"].items():
|
||||
room_id, model, provider = key.split(",", 2)
|
||||
metric_line = f'room_llm_output_tokens_total{{room_id="{room_id}",model="{model}",provider="{provider}"}} {value}'
|
||||
output_metrics.append(metric_line)
|
||||
|
||||
# Format cost metrics
|
||||
cost_metrics = []
|
||||
for key, value in _COST_METRICS["total"].items():
|
||||
room_id, model, provider = key.split(",", 2)
|
||||
metric_line = f'room_llm_cost_total{{room_id="{room_id}",model="{model}",provider="{provider}"}} {value:.6f}'
|
||||
cost_metrics.append(metric_line)
|
||||
|
||||
# Format request metrics
|
||||
request_metrics = []
|
||||
for key, value in _REQUEST_METRICS["total"].items():
|
||||
room_id, model, provider = key.split(",", 2)
|
||||
metric_line = f'room_llm_requests_total{{room_id="{room_id}",model="{model}",provider="{provider}"}} {value}'
|
||||
request_metrics.append(metric_line)
|
||||
|
||||
# Generate response
|
||||
response = PROMETHEUS_TEMPLATE.format(
|
||||
input_metrics="\n".join(input_metrics) if input_metrics else "# No input token metrics recorded",
|
||||
output_metrics="\n".join(output_metrics) if output_metrics else "# No output token metrics recorded",
|
||||
cost_metrics="\n".join(cost_metrics) if cost_metrics else "# No cost metrics recorded",
|
||||
request_metrics="\n".join(request_metrics) if request_metrics else "# No request metrics recorded"
|
||||
)
|
||||
|
||||
self.wfile.write(response.encode("utf-8"))
|
||||
|
||||
def log_message(self, format, *args):
|
||||
"""Override to use Python logging instead of stderr."""
|
||||
logger.info("%s - - [%s] %s", self.address_string(), self.log_date_time_string(), format % args)
|
||||
|
||||
def _start_metrics_server(port: int = 8000) -> threading.Thread:
|
||||
"""Start Prometheus metrics server in background thread."""
|
||||
server = HTTPServer(("localhost", port), PrometheusMetricsHandler)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
logger.info(f"Prometheus metrics server started on port {port}")
|
||||
return thread
|
||||
|
||||
def register(ctx) -> None:
|
||||
"""Register Prometheus token tracking plugin with Hermes."""
|
||||
# Register for API request hooks
|
||||
ctx.register_hook("pre_api_request", on_pre_api_request)
|
||||
ctx.register_hook("post_api_request", on_post_api_request)
|
||||
|
||||
# Start metrics server
|
||||
metrics_port = int(_get_env("HERMES_PROMETHEUS_PORT", "8000"))
|
||||
_start_metrics_server(metrics_port)
|
||||
|
||||
logger.info("Prometheus token tracking plugin registered")
|
||||
Reference in New Issue
Block a user