9 Commits

Author SHA1 Message Date
Hermes Agent b260475e24 test: verify token tracking observability system with integration tests 2026-06-01 12:28:22 +02:00
Hermes Agent ed0182d26e docs: add documentation for token tracking observability 2026-06-01 12:28:18 +02:00
Hermes Agent cb2622381a feat: add integration test for token tracking observability 2026-06-01 12:28:01 +02:00
Hermes Agent 9220f00b63 feat: update plugin configuration with prometheus port setting 2026-06-01 12:27:42 +02:00
Hermes Agent 51c00e8057 feat: add grafana dashboard for token tracking 2026-06-01 12:27:31 +02:00
Hermes Agent 174d4492d7 feat: add grafana prometheus datasource configuration 2026-06-01 12:27:16 +02:00
Hermes Agent 3b71873cbc feat: add prometheus docker compose configuration 2026-06-01 12:27:11 +02:00
Hermes Agent 1d9bc08ac5 feat: register prometheus token tracking plugin 2026-06-01 12:26:54 +02:00
Hermes Agent bda2f9ed16 feat: add prometheus token tracking plugin 2026-06-01 12:26:40 +02:00
12 changed files with 1366 additions and 0 deletions
+47
View File
@@ -0,0 +1,47 @@
version: '3.8'
services:
prometheus:
image: prom/prometheus:v2.44.0
container_name: prometheus
restart: unless-stopped
ports:
- "9090:9090"
volumes:
- ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
- prometheus_data:/prometheus
command:
- '--config.file=/etc/prometheus/prometheus.yml'
- '--storage.tsdb.path=/prometheus'
- '--web.console.libraries=/etc/prometheus/console_libraries'
- '--web.console.templates=/etc/prometheus/consoles'
- '--storage.tsdb.retention.time=200h'
- '--web.enable-lifecycle'
networks:
- monitoring
grafana:
image: grafana/grafana-enterprise
container_name: grafana
restart: unless-stopped
ports:
- "3000:3000"
volumes:
- grafana_data:/var/lib/grafana
- ./grafana/provisioning:/etc/grafana/provisioning
environment:
- GF_SECURITY_ADMIN_USER=admin
- GF_SECURITY_ADMIN_PASSWORD=admin
- GF_USERS_ALLOW_SIGN_UP=false
networks:
- monitoring
depends_on:
- prometheus
volumes:
prometheus_data:
grafana_data:
networks:
monitoring:
driver: bridge
+136
View File
@@ -0,0 +1,136 @@
# LLM Token Tracking with Prometheus and Grafana
This document explains how to set up and use the LLM token tracking observability system for the Rocket.Chat Hermes plugin.
## Overview
The token tracking system monitors LLM usage in real-time, tracking:
- Input tokens (prompt tokens) per room
- Output tokens (completion tokens) per room
- Estimated cost per room based on model pricing
- Request count per room
Metrics are exposed via a Prometheus-compatible endpoint and can be visualized in Grafana dashboards.
## Architecture
```
Hermes Agent (with Rocket.Chat plugin)
↓ (API calls with usage data)
Token Tracking Plugin (collects metrics)
↓ (Prometheus format)
Metrics Endpoint (:8000/metrics)
↓ (scraped every 15s)
Prometheus (time-series database)
↓ (query from dashboards)
Grafana (visualization)
```
## Setup Instructions
### 1. Enable the Plugin
The token tracking plugin is automatically enabled when the Rocket.Chat plugin is loaded. Ensure the following environment variable is set:
```bash
export HERMES_PROMETHEUS_PORT=8000 # Optional, defaults to 8000
```
### 2. Start Monitoring Stack
Start the Prometheus and Grafana containers:
```bash
cd /home/bernd/projekte/Hermes_rocket.chat_Plugin
docker-compose -f docker-compose.prometheus.yml up -d
```
### 3. Access Grafana Dashboard
1. Open your browser to http://localhost:3000
2. Log in with default credentials (admin/admin)
3. Navigate to the "LLM Token Tracking" dashboard
## Metrics Reference
The plugin exposes the following Prometheus metrics:
- `room_llm_input_tokens_total{room_id, model, provider}` - Counter of input tokens per room
- `room_llm_output_tokens_total{room_id, model, provider}` - Counter of output tokens per room
- `room_llm_cost_total{room_id, model, provider}` - Counter of estimated cost per room
- `room_llm_requests_total{room_id, model, provider}` - Counter of LLM requests per room
## Pricing Model
The system uses a built-in pricing model for cost estimation:
| Model/Provider | Input Price (per 1K tokens) | Output Price (per 1K tokens) |
|----------------|-----------------------------|------------------------------|
| gpt-4/openai | $0.03 | $0.06 |
| claude-3/anthropic | $0.015 | $0.075 |
| llama-3/together | $0.0005 | $0.0008 |
Note: These are example prices. Update the `_calculate_cost` function in `prometheus_plugin.py` with actual pricing.
## Troubleshooting
### No Metrics in Grafana
1. Check that the Hermes agent is running and making LLM calls
2. Verify the metrics endpoint is accessible: `curl http://localhost:8000/metrics`
3. Check Prometheus targets: http://localhost:9090/targets
4. Verify Prometheus is scraping the metrics: http://localhost:9090/graph
### Dashboard Not Loading
1. Check that Grafana is running: `docker ps | grep grafana`
2. Verify dashboard provisioning: Check files in `grafana/provisioning/`
3. Check Grafana logs: `docker logs grafana`
### High Memory Usage
The plugin stores metrics in memory. For high-traffic systems, consider:
1. Adjusting Prometheus retention policy in `prometheus.yml`
2. Adding more RAM to the host system
3. Using an external Prometheus instance instead of the bundled one
## Customization
### Adding New Models
Update the pricing dictionary in `prometheus_plugin.py`:
```python
pricing = {
# Existing models...
("new-model", "new-provider"): {"input": 0.01, "output": 0.02},
}
```
### Modifying Dashboard
Edit `grafana/dashboards/token-tracking.json` to customize the visualization.
### Changing Scraping Interval
Update `prometheus/prometheus.yml`:
```yaml
global:
scrape_interval: 30s # Change from 15s
```
## Security Considerations
- The metrics endpoint (`/metrics`) is not password protected by default
- Do not expose the Prometheus or Grafana ports to the internet without authentication
- Use firewall rules to restrict access to monitoring ports (8000, 9090, 3000)
- For production deployments, add authentication to Grafana and use HTTPS
## Scaling
For large deployments:
1. Use an external Prometheus instance with more resources
2. Implement federation for multi-instance setups
3. Use persistent storage volumes for long-term retention
4. Consider using Thanos or Cortex for horizontal scaling
+163
View File
@@ -0,0 +1,163 @@
{
"dashboard": {
"id": null,
"title": "LLM Token Tracking",
"timezone": "browser",
"schemaVersion": 16,
"version": 0,
"refresh": "10s",
"panels": [
{
"id": 1,
"type": "graph",
"title": "Input Tokens by Room",
"gridPos": {
"x": 0,
"y": 0,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "rate(room_llm_input_tokens_total[5m])",
"legendFormat": "{{room_id}} ({{model}})",
"refId": "A"
}
],
"xaxis": {
"mode": "time"
},
"yaxes": [
{
"format": "short",
"label": "Tokens/sec"
},
{
"format": "short"
}
]
},
{
"id": 2,
"type": "graph",
"title": "Output Tokens by Room",
"gridPos": {
"x": 12,
"y": 0,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "rate(room_llm_output_tokens_total[5m])",
"legendFormat": "{{room_id}} ({{model}})",
"refId": "A"
}
],
"xaxis": {
"mode": "time"
},
"yaxes": [
{
"format": "short",
"label": "Tokens/sec"
},
{
"format": "short"
}
]
},
{
"id": 3,
"type": "bargauge",
"title": "Total Cost by Room",
"gridPos": {
"x": 0,
"y": 8,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "room_llm_cost_total",
"legendFormat": "{{room_id}}",
"refId": "A"
}
],
"options": {
"orientation": "horizontal",
"displayMode": "gradient",
"reduceOptions": {
"calcs": [
"last"
]
}
}
},
{
"id": 4,
"type": "table",
"title": "Token Summary",
"gridPos": {
"x": 12,
"y": 8,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "room_llm_input_tokens_total",
"legendFormat": "Input - {{room_id}} ({{model}})",
"refId": "A"
},
{
"expr": "room_llm_output_tokens_total",
"legendFormat": "Output - {{room_id}} ({{model}})",
"refId": "B"
},
{
"expr": "room_llm_cost_total",
"legendFormat": "Cost - {{room_id}} ({{model}})",
"refId": "C"
}
],
"transformations": [
{
"id": "seriesToColumns",
"options": {
"byField": "room_id"
}
}
],
"fieldConfig": {
"defaults": {
"custom": {
"align": "auto"
}
}
}
}
],
"templating": {
"list": []
},
"time": {
"from": "now-6h",
"to": "now"
},
"timepicker": {
"refresh_intervals": [
"5s",
"10s",
"30s",
"1m",
"5m",
"15m",
"30m",
"1h",
"2h",
"1d"
]
}
}
}
@@ -0,0 +1,11 @@
apiVersion: 1
providers:
- name: 'Token Tracking'
orgId: 1
folder: ''
type: file
disableDeletion: false
editable: true
options:
path: /etc/grafana/dashboards
@@ -0,0 +1,9 @@
apiVersion: 1
datasources:
- name: Prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
editable: true
Regular → Executable
View File
+530
View File
@@ -0,0 +1,530 @@
#!/usr/bin/env bash
#
# Hermes Rocket.Chat Plugin — Interactive Installer
# https://gitea.thomander.de/andreas/Hermes_rocket.chat_Plugin
#
set -euo pipefail
# ─── Defaults ──────────────────────────────────────────────
LANG="${LANG:-de_DE.UTF-8}"
ARG_LANG=""
NONINTERACTIVE=false
CHECK_ONLY=false
UPDATE_MODE=false
# ─── Language packs ─────────────────────────────────────────
declare -A T
msg() { local k="$1"; shift; printf "${T[$k]:-$k}\n" "$@"; }
load_lang() {
local lang="${1:-de}"
case "$lang" in
de|de_DE*|de_DE.UTF-8) lang=de ;;
en|en_*) lang=en ;;
*) lang=en ;;
esac
if [ "$lang" = "en" ]; then
T=(
[banner]="━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n Hermes Rocket.Chat Plugin — Installer\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
[checking]="🔍 Checking prerequisites…"
[found_hermes]="✅ Hermes Agent found at: %s"
[no_hermes]="❌ Hermes Agent not found.\n Install it first: https://github.com/nousresearch/hermes-agent\n Expected under: ~/hermes-agent or ~/.hermes/hermes-agent"
[existing]="📋 Existing installation detected:"
[confirm_values]=" Press ENTER to keep a value, or type a new one."
[enter_url]="Rocket.Chat URL"
[enter_botuser]="Bot Username (the bot account on the Rocket.Chat server)"
[enter_botpass]="Bot Password"
[enter_channel]="Home Channel (name or room ID, e.g. #ki-assistent or 69f4e…)"
[current_val]=" Current: %s"
[new_val]=" → "
[summary]="📋 Configuration Summary:"
[copying]="📁 Copying plugin files…"
[env_written]="🔑 Credentials written to %s"
[config_updated]="⚙️ config.yaml updated"
[service_installed]="⚡ Gateway service installed"
[restarting]="🔄 Restarting gateway…"
[done]="✅ Rocket.Chat Plugin installed successfully!\n After the gateway restarts, check for a pairing code\n in the gateway logs and enter it in your home channel."
[dry_info]="ℹ️ Use --help for all options."
[help_text]="USAGE: ./install.sh [OPTIONS]\n\nOPTIONS:\n --help Show this help\n --lang en|de Language (default: auto-detect from \$LANG)\n --non-interactive Batch mode — reads from env vars:\n RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL\n --check Check for updates only\n --update Check for updates and install if available"
[env_required]="❌ --non-interactive requires RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL"
[param_error]="❌ Unknown option: %s"
[check_update]="🔍 Checking for updates..."
[update_available]="📦 New version available: %s (current: %s)"
[no_update]="✅ Plugin is up to date (%s)"
[perform_update]="🔄 Updating plugin to version %s..."
[backup_created]="💾 Backup created: %s"
[update_success]="✅ Plugin successfully updated to version %s"
[rollback]="⏪ Restoring backup: %s"
[rollback_success]="✅ Backup successfully restored"
[update_failed]="❌ Update failed. Error: %s"
)
else
# German (default)
T=(
[banner]="━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n Hermes Rocket.Chat Plugin — Installer\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
[checking]="🔍 Prüfe Voraussetzungen…"
[found_hermes]="✅ Hermes Agent gefunden unter: %s"
[no_hermes]="❌ Hermes Agent nicht gefunden.\n Bitte zuerst installieren: https://github.com/nousresearch/hermes-agent\n Erwartet unter: ~/hermes-agent oder ~/.hermes/hermes-agent"
[existing]="📋 Bestehende Installation erkannt:"
[confirm_values]=" ENTER = Wert behalten, oder neuen Wert eingeben."
[enter_url]="Rocket.Chat Server URL"
[enter_botuser]="Bot Username (der Bot-Account auf dem Rocket.Chat Server)"
[enter_botpass]="Bot Passwort"
[enter_channel]="Home Channel (Name oder Raum-ID, z.B. #ki-assistent oder 69f4e…)"
[current_val]=" Aktuell: %s"
[new_val]=" → "
[summary]="📋 Zusammenfassung der Konfiguration:"
[copying]="📁 Kopiere Plugin-Dateien…"
[env_written]="🔑 Zugangsdaten gespeichert in %s"
[config_updated]="⚙️ config.yaml aktualisiert"
[service_installed]="⚡ Gateway-Service installiert"
[restarting]="🔄 Starte Gateway neu…"
[done]="✅ Rocket.Chat Plugin erfolgreich installiert!\n Nach dem Gateway-Neustart bitte den Pairing-Code\n aus den Gateway-Logs im Home-Channel eingeben."
[dry_info]="ℹ️ Mit --help alle Optionen anzeigen."
[help_text]="AUFRUF: ./install.sh [OPTIONEN]\n\nOPTIONEN:\n --help Diese Hilfe anzeigen\n --lang en|de Sprache (Standard: auto-Erkennung über \$LANG)\n --non-interactive Stapelverarbeitung — liest aus Umgebungsvariablen:\n RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL\n --check Nur auf Updates prüfen\n --update Auf Updates prüfen und bei Bedarf installieren"
[env_required]="❌ --non-interactive benötigt RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL"
[param_error]="❌ Unbekannte Option: %s"
[check_update]="🔍 Prüfe auf Updates..."
[update_available]="📦 Neue Version verfügbar: %s (aktuell: %s)"
[no_update]="✅ Plugin ist auf dem neuesten Stand (%s)"
[perform_update]="🔄 Aktualisiere Plugin auf Version %s..."
[backup_created]="💾 Backup erstellt: %s"
[update_success]="✅ Plugin erfolgreich aktualisiert auf Version %s"
[rollback]="⏪ Stelle Backup wieder her: %s"
[rollback_success]="✅ Backup erfolgreich wiederhergestellt"
[update_failed]="❌ Update fehlgeschlagen. Fehler: %s"
)
fi
}
# ─── Update Functions ──────────────────────────────────────
check_for_updates() {
msg check_update
# Get the script directory (repo root)
local script_dir
script_dir="$(cd "$(dirname "$0")" && pwd)"
# Change to repo directory
cd "$script_dir"
# Get local version (latest tag)
local local_version
local_version=$(git describe --tags 2>/dev/null || echo "unknown")
# Get remote version (latest tag on origin)
local remote_version
remote_version=$(git ls-remote --tags origin | grep -E 'refs/tags/v[0-9]+(\.[0-9]+)*$' | sed 's|.*refs/tags/||' | sort -V | tail -n1 || echo "unknown")
# If we can't determine versions, exit with error
if [ "$local_version" = "unknown" ] || [ "$remote_version" = "unknown" ]; then
echo "Could not determine version information"
return 1
fi
# Compare versions
if [ "$local_version" != "$remote_version" ]; then
msg update_available "$remote_version" "$local_version"
return 1 # Update available
else
msg no_update "$local_version"
return 0 # No update needed
fi
}
create_backup() {
local backup_file="$1"
local plugin_dir="$2"
local config_file="$3"
local env_file="$4"
# Create backup of current installation
tar -czf "$backup_file" -C "$(dirname "$plugin_dir")" "$(basename "$plugin_dir")" \
--exclude="*.pyc" --exclude="__pycache__" \
"$config_file" "$env_file" 2>/dev/null || true
msg backup_created "$backup_file"
}
perform_update() {
# Get the script directory (repo root)
local script_dir
script_dir="$(cd "$(dirname "$0")" && pwd)"
# Change to repo directory
cd "$script_dir"
# Get remote version
local remote_version
remote_version=$(git ls-remote --tags origin | grep -E 'refs/tags/v[0-9]+(\.[0-9]+)*$' | sed 's|.*refs/tags/||' | sort -V | tail -n1 || echo "unknown")
if [ "$remote_version" = "unknown" ]; then
msg update_failed "Could not determine remote version"
return 1
fi
msg perform_update "$remote_version"
# Create backup before updating
local backup_file="/tmp/hermes-rocketchat-backup-$(date +%s).tar.gz"
local hermes_dir
hermes_dir=""
for d in "$HOME/hermes-agent" "$HOME/.hermes/hermes-agent"; do
if [ -d "$d" ]; then hermes_dir="$d"; break; fi
done
if [ -n "$hermes_dir" ]; then
local plugin_dir="$hermes_dir/plugins/platforms/rocketchat"
local config_file="$HOME/.hermes/config.yaml"
local env_file="$HOME/.config/hermes/rocketchat.env"
create_backup "$backup_file" "$plugin_dir" "$config_file" "$env_file"
fi
# Perform the update
local update_error=""
{
# Pull latest changes
git fetch --tags origin 2>&1 || { update_error="Failed to fetch from remote"; return 1; }
git checkout "$remote_version" 2>&1 || { update_error="Failed to checkout version $remote_version"; return 1; }
# Run the installer to update files
HERMES_DIR="$hermes_dir" UPDATE_MODE=true ./install.sh --non-interactive 2>&1
} || {
# Update failed, rollback
if [ -n "$update_error" ]; then
msg update_failed "$update_error"
else
msg update_failed "Installation failed"
fi
if [ -f "$backup_file" ]; then
msg rollback "$backup_file"
# Extract backup
tar -xzf "$backup_file" -C "$HOME" 2>/dev/null || true
msg rollback_success
# Clean up backup file
rm -f "$backup_file"
fi
return 1
}
# Clean up backup file on success
rm -f "$backup_file"
msg update_success "$remote_version"
# Restart gateway
if [ -n "$hermes_dir" ]; then
cd "$hermes_dir"
systemctl --user daemon-reload 2>/dev/null || true
systemctl --user restart hermes-gateway 2>/dev/null || true
fi
return 0
}
# ─── Main Script Logic ──────────────────────────────────────
# ─── Helper ──────────────────────────────────────────────
confirm_or_edit() {
# $1 = env-var name (RC_URL, RC_BOT_USER, …)
# $2 = message key (enter_url, enter_botuser, …)
# $3 = current value (may be empty)
local varname="$1" msgkey="$2" current="$3" input
if [ -n "$current" ]; then
msg current_val "$current"
msg confirm_values
fi
printf "%s" "${T[$new_val]}"
read -r input
if [ -n "$input" ]; then
printf -v "$varname" '%s' "$input"
fi
}
# ─── Update Functions ──────────────────────────────────────
check_for_updates() {
msg check_update
# Get the script directory (repo root)
local script_dir
script_dir="$(cd "$(dirname "$0")" && pwd)"
# Change to repo directory
cd "$script_dir"
# Get local version (latest tag)
local local_version
local_version=$(git describe --tags 2>/dev/null || echo "unknown")
# Get remote version (latest tag on origin)
local remote_version
remote_version=$(git ls-remote --tags origin | grep -E 'refs/tags/v[0-9]+(\.[0-9]+)*$' | sed 's|.*refs/tags/||' | sort -V | tail -n1 || echo "unknown")
# If we can't determine versions, exit with error
if [ "$local_version" = "unknown" ] || [ "$remote_version" = "unknown" ]; then
echo "Could not determine version information"
return 1
fi
# Compare versions
if [ "$local_version" != "$remote_version" ]; then
msg update_available "$remote_version" "$local_version"
return 1 # Update available
else
msg no_update "$local_version"
return 0 # No update needed
fi
}
create_backup() {
local backup_file="$1"
local plugin_dir="$2"
local config_file="$3"
local env_file="$4"
# Create backup of current installation
tar -czf "$backup_file" -C "$(dirname "$plugin_dir")" "$(basename "$plugin_dir")" \
--exclude="*.pyc" --exclude="__pycache__" \
"$config_file" "$env_file" 2>/dev/null || true
msg backup_created "$backup_file"
}
perform_update() {
# Get the script directory (repo root)
local script_dir
script_dir="$(cd "$(dirname "$0")" && pwd)"
# Change to repo directory
cd "$script_dir"
# Get remote version
local remote_version
remote_version=$(git ls-remote --tags origin | grep -E 'refs/tags/v[0-9]+(\.[0-9]+)*$' | sed 's|.*refs/tags/||' | sort -V | tail -n1 || echo "unknown")
if [ "$remote_version" = "unknown" ]; then
msg update_failed "Could not determine remote version"
return 1
fi
msg perform_update "$remote_version"
# Create backup before updating
local backup_file="/tmp/hermes-rocketchat-backup-$(date +%s).tar.gz"
local hermes_dir
hermes_dir=""
for d in "$HOME/hermes-agent" "$HOME/.hermes/hermes-agent"; do
if [ -d "$d" ]; then hermes_dir="$d"; break; fi
done
if [ -n "$hermes_dir" ]; then
local plugin_dir="$hermes_dir/plugins/platforms/rocketchat"
local config_file="$HOME/.hermes/config.yaml"
local env_file="$HOME/.config/hermes/rocketchat.env"
create_backup "$backup_file" "$plugin_dir" "$config_file" "$env_file"
fi
# Perform the update
local update_error=""
{
# Pull latest changes
git fetch --tags origin 2>&1 || { update_error="Failed to fetch from remote"; return 1; }
git checkout "$remote_version" 2>&1 || { update_error="Failed to checkout version $remote_version"; return 1; }
# Run the installer to update files
HERMES_DIR="$hermes_dir" UPDATE_MODE=true ./install.sh --non-interactive 2>&1
} || {
# Update failed, rollback
if [ -n "$update_error" ]; then
msg update_failed "$update_error"
else
msg update_failed "Installation failed"
fi
if [ -f "$backup_file" ]; then
msg rollback "$backup_file"
# Extract backup
tar -xzf "$backup_file" -C "$HOME" 2>/dev/null || true
msg rollback_success
# Clean up backup file
rm -f "$backup_file"
fi
return 1
}
# Clean up backup file on success
rm -f "$backup_file"
msg update_success "$remote_version"
# Restart gateway
if [ -n "$hermes_dir" ]; then
cd "$hermes_dir"
systemctl --user daemon-reload 2>/dev/null || true
systemctl --user restart hermes-gateway 2>/dev/null || true
fi
return 0
}
# ─── Main Script Logic ──────────────────────────────────────
# ─── Argument parsing ────────────────────────────────────
while [ $# -gt 0 ]; do
case "$1" in
--help|-h)
load_lang "${ARG_LANG:-${LANG##*.}}"
echo; echo -e "${T[help_text]}"; echo; exit 0 ;;
--lang)
ARG_LANG="$2"; shift 2 ;;
--lang=*)
ARG_LANG="${1#*=}"; shift ;;
--non-interactive)
NONINTERACTIVE=true; shift ;;
--check)
CHECK_ONLY=true; shift ;;
--update)
UPDATE_MODE=true; shift ;;
*)
load_lang "${ARG_LANG:-${LANG##*.}}"
msg param_error "$1"; echo; exit 1 ;;
esac
done
# ─── Load language ────────────────────────────────────────
load_lang "${ARG_LANG:-${LANG##*.}}"
echo -e "\n${T[banner]}\n"
# ─── Find Hermes Agent ────────────────────────────────────
msg checking
HERMES_DIR=""
for d in "$HOME/hermes-agent" "$HOME/.hermes/hermes-agent"; do
if [ -d "$d" ]; then HERMES_DIR="$d"; break; fi
done
if [ -z "$HERMES_DIR" ]; then
msg no_hermes; exit 1
fi
msg found_hermes "$HERMES_DIR"
# ─── Detect existing installation ─────────────────────────
ENV_FILE="$HOME/.config/hermes/rocketchat.env"
HAVE_EXISTING=false
RC_URL="" RC_BOT_USER="" RC_BOT_PASS="" RC_HOME_CHANNEL=""
if [ -f "$ENV_FILE" ]; then
HAVE_EXISTING=true
# shellcheck disable=SC1090
source "$ENV_FILE" 2>/dev/null || true
RC_URL="${ROCKETCHAT_BASE_URL:-${RC_URL:-}}"
RC_BOT_USER="${ROCKETCHAT_USER:-${RC_BOT_USER:-}}"
RC_HOME_CHANNEL="${ROCKETCHAT_ROOM_NAME:-${RC_HOME_CHANNEL:-}}"
fi
# ─── Non-interactive mode ─────────────────────────────────
if $NONINTERACTIVE; then
RC_URL="${RC_URL:-}" RC_BOT_USER="${RC_BOT_USER:-}"
RC_BOT_PASS="${RC_BOT_PASS:-}" RC_HOME_CHANNEL="${RC_HOME_CHANNEL:-}"
if [ -z "$RC_URL" ] || [ -z "$RC_BOT_USER" ] || [ -z "$RC_BOT_PASS" ] || [ -z "$RC_HOME_CHANNEL" ]; then
msg env_required; exit 1
fi
else
# ─── Interactive mode ──────────────────────────────────
if $HAVE_EXISTING; then
msg existing
echo
fi
confirm_or_edit RC_URL enter_url "$RC_URL"
confirm_or_edit RC_BOT_USER enter_botuser "$RC_BOT_USER"
confirm_or_edit RC_BOT_PASS enter_botpass ""
confirm_or_edit RC_HOME_CHANNEL enter_channel "$RC_HOME_CHANNEL"
echo
msg summary
echo " URL: $RC_URL"
echo " Bot User: $RC_BOT_USER"
echo " Home Channel: $RC_HOME_CHANNEL"
echo
fi
# ─── Write credentials ────────────────────────────────────
msg copying
mkdir -p "$(dirname "$ENV_FILE")"
cat > "$ENV_FILE" <<EOF
# Hermes Rocket.Chat Plugin — credentials (generated by install.sh)
export ROCKETCHAT_BASE_URL="${RC_URL}"
export ROCKETCHAT_USER="${RC_BOT_USER}"
export ROCKETCHAT_PASSWORD='${RC_BOT_PASS}'
export ROCKETCHAT_ROOM_NAME="${RC_HOME_CHANNEL}"
export ROCKETCHAT_ALLOW_ALL_USERS=true
export GATEWAY_ALLOW_ALL_USERS=true
export ROCKETCHAT_PING_SEC=8
export ROCKETCHAT_IDLE_SEC=900
EOF
chmod 600 "$ENV_FILE"
msg env_written "$ENV_FILE"
# ─── Copy plugin files ────────────────────────────────────
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PLUGIN_DST="$HERMES_DIR/plugins/platforms/rocketchat"
mkdir -p "$PLUGIN_DST"
for f in plugin.yaml __init__.py adapter.py tools.py; do
if [ -f "$SCRIPT_DIR/plugin/$f" ]; then
cp "$SCRIPT_DIR/plugin/$f" "$PLUGIN_DST/$f"
fi
done
# ─── Patch config.yaml ────────────────────────────────────
CONFIG="$HOME/.hermes/config.yaml"
if [ -f "$CONFIG" ]; then
# Ensure rocketchat-platform is in plugins.enabled
if ! grep -q 'rocketchat-platform' "$CONFIG" 2>/dev/null; then
# Simple append — user can refine later
cat >> "$CONFIG" <<'YAML'
# Added by Rocket.Chat Plugin installer
plugins:
enabled:
- rocketchat-platform
YAML
fi
msg config_updated
fi
# ─── Gateway service ──────────────────────────────────────
cd "$HERMES_DIR"
if [ -f "venv/bin/python" ]; then
PYTHON="venv/bin/python"
elif [ -f ".venv/bin/python" ]; then
PYTHON=".venv/bin/python"
else
PYTHON="python3"
fi
# Install / refresh systemd user service
$PYTHON -m hermes_cli.main gateway install 2>/dev/null || true
# Ensure lingering is enabled (may need sudo — best-effort)
loginctl enable-linger 2>/dev/null || true
msg service_installed
# ─── Restart gateway ──────────────────────────────────────
msg restarting
systemctl --user daemon-reload 2>/dev/null || true
systemctl --user restart hermes-gateway 2>/dev/null || true
msg done
echo
+8
View File
@@ -124,3 +124,11 @@ def register(ctx):
)
register_tools(ctx)
# Register Prometheus token tracking plugin
try:
from .prometheus_plugin import register as register_prometheus
register_prometheus(ctx)
logger.info("Prometheus token tracking plugin registered successfully")
except Exception as e:
logger.error("Failed to register Prometheus token tracking plugin: %s", e)
+3
View File
@@ -20,3 +20,6 @@ requires_env:
- name: ROCKETCHAT_ALLOWED_USERS
description: "Comma-separated list of allowed Rocket.Chat usernames"
required: false
- name: HERMES_PROMETHEUS_PORT
description: "Port for Prometheus metrics endpoint (default: 8000)"
required: false
+254
View File
@@ -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")
+30
View File
@@ -0,0 +1,30 @@
# Global configuration
global:
scrape_interval: 15s
evaluation_interval: 15s
# Alertmanager configuration
alerting:
alertmanagers:
- static_configs:
- targets:
# - alertmanager:9093
# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
# - "first_rules.yml"
# - "second_rules.yml"
# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
# The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
- job_name: "prometheus"
static_configs:
- targets: ["localhost:9090"]
# Hermes Agent metrics
- job_name: "hermes-agent"
static_configs:
- targets: ["172.17.0.1:8000"]
scrape_interval: 15s
+175
View File
@@ -0,0 +1,175 @@
#!/usr/bin/env python3
"""
Integration test for the token tracking observability system.
Tests the full pipeline from plugin metrics to Grafana dashboard.
"""
import time
import requests
import subprocess
import sys
import os
def test_prometheus_metrics_endpoint():
"""Test that the Prometheus metrics endpoint is accessible."""
print("Testing Prometheus metrics endpoint...")
try:
# Wait a moment for the service to start
time.sleep(2)
# Test the metrics endpoint
response = requests.get("http://localhost:8000/metrics", timeout=10)
assert response.status_code == 200, f"Expected 200, got {response.status_code}"
assert "room_llm_input_tokens_total" in response.text, "Missing input tokens metric"
assert "room_llm_output_tokens_total" in response.text, "Missing output tokens metric"
print("✓ Prometheus metrics endpoint is working")
return True
except Exception as e:
print(f"✗ Prometheus metrics endpoint test failed: {e}")
return False
def test_prometheus_container():
"""Test that the Prometheus container is running and scraping metrics."""
print("Testing Prometheus container...")
try:
# Check if Prometheus container is running
result = subprocess.run(["docker", "ps", "--filter", "name=prometheus", "--format", "{{.Names}}"],
capture_output=True, text=True, timeout=10)
assert "prometheus" in result.stdout, "Prometheus container is not running"
# Check Prometheus targets
time.sleep(5) # Give Prometheus time to initialize
response = requests.get("http://localhost:9090/api/v1/targets", timeout=10)
assert response.status_code == 200, f"Prometheus targets API failed: {response.status_code}"
targets_data = response.json()
active_targets = [target for target in targets_data.get("data", {}).get("activeTargets", [])
if target.get("job") == "hermes-agent"]
assert len(active_targets) > 0, "No active hermes-agent targets found in Prometheus"
assert all(target.get("health") == "up" for target in active_targets), "Not all targets are healthy"
print("✓ Prometheus container is running and scraping metrics")
return True
except Exception as e:
print(f"✗ Prometheus container test failed: {e}")
return False
def test_grafana_container():
"""Test that the Grafana container is running and accessible."""
print("Testing Grafana container...")
try:
# Check if Grafana container is running
result = subprocess.run(["docker", "ps", "--filter", "name=grafana", "--format", "{{.Names}}"],
capture_output=True, text=True, timeout=10)
assert "grafana" in result.stdout, "Grafana container is not running"
# Check Grafana is accessible
time.sleep(5) # Give Grafana time to initialize
response = requests.get("http://localhost:3000/api/health", timeout=10)
assert response.status_code == 200, f"Grafana health check failed: {response.status_code}"
health_data = response.json()
assert health_data.get("database") == "ok", "Grafana database is not healthy"
print("✓ Grafana container is running and accessible")
return True
except Exception as e:
print(f"✗ Grafana container test failed: {e}")
return False
def test_dashboard_provisioning():
"""Test that the dashboard is properly provisioned in Grafana."""
print("Testing Grafana dashboard provisioning...")
try:
# Wait for provisioning
time.sleep(10)
# Login to Grafana (default credentials)
session = requests.Session()
login_response = session.post("http://localhost:3000/login",
json={"user": "admin", "password": "admin"},
timeout=10)
assert login_response.status_code == 200, f"Grafana login failed: {login_response.status_code}"
# Check for dashboards
dashboards_response = session.get("http://localhost:3000/api/search?query=LLM", timeout=10)
assert dashboards_response.status_code == 200, f"Dashboard search failed: {dashboards_response.status_code}"
dashboards = dashboards_response.json()
llm_dashboards = [d for d in dashboards if "LLM" in d.get("title", "")]
assert len(llm_dashboards) > 0, "No LLM dashboards found"
print("✓ Grafana dashboard is properly provisioned")
return True
except Exception as e:
print(f"✗ Grafana dashboard provisioning test failed: {e}")
return False
def main():
"""Run all integration tests."""
print("Starting token tracking observability integration tests...\n")
# Start the monitoring stack
print("Starting monitoring stack with docker-compose...")
try:
subprocess.run([
"docker-compose", "-f", "docker-compose.prometheus.yml", "up", "-d"
], cwd="/home/bernd/projekte/Hermes_rocket.chat_Plugin", check=True)
print("✓ Monitoring stack started\n")
except subprocess.CalledProcessError as e:
print(f"✗ Failed to start monitoring stack: {e}")
return 1
# Wait for services to initialize
print("Waiting for services to initialize...")
time.sleep(15)
# Run tests
tests = [
test_prometheus_metrics_endpoint,
test_prometheus_container,
test_grafana_container,
test_dashboard_provisioning
]
results = []
for test in tests:
try:
result = test()
results.append(result)
except Exception as e:
print(f"✗ Test {test.__name__} failed with exception: {e}")
results.append(False)
print()
# Clean up
print("Stopping monitoring stack...")
try:
subprocess.run([
"docker-compose", "-f", "docker-compose.prometheus.yml", "down"
], cwd="/home/bernd/projekte/Hermes_rocket.chat_Plugin", check=True)
print("✓ Monitoring stack stopped")
except subprocess.CalledProcessError as e:
print(f"Warning: Failed to stop monitoring stack: {e}")
# Calculate results
passed = sum(results)
total = len(results)
print(f"\nIntegration Test Results: {passed}/{total} tests passed")
if passed == total:
print("🎉 All tests passed! The token tracking observability system is working correctly.")
return 0
else:
print("❌ Some tests failed. Please check the output above for details.")
return 1
if __name__ == "__main__":
sys.exit(main())