A self-hosted LLM operations gateway in one Go binary: an OpenAI-compatible router over local and cloud models, a durable task tracker, a faithfulness eval + drift alert loop, OTel-shaped traces, an MCP server for AI assistants, and an embedded web console.
The repository is still named
AgentOpsso existing links and the release identity keep working; the product is Tower. Seedocs/MARKET.mdΒ§9.1(8) for the decision.
Built solo, on an RTX 4060 (8 GB VRAM), against local Ollama models β informed by how TensorZero, Bifrost, Temporal and Langfuse solve the same problems, but with every core piece written here so it can be explained line by line. Standard library + one dependency (pgx).
βββββββββββββββββββββββββββββ tower (one binary) βββββββββββββββββββββββββββββ
OpenAI clients βββΊ β router: auth (API keys) β Classify β Plan (fail-closed) β Backend β
POST /v1/chat β Ollama /api/chat (stream) Β· any OpenAI-style API Β· health prober β
β ββ Prometheus /metrics (hand-written exposition) β
β ββ 3 spans per chat βββΊ async writer βββΊ Postgres spans β
--run-tracker ββββΊ β tracker: Researcher β Drafter β Reviewer, row-status durability, kill -9 safe β
--score ββββββββββΊ β evals: pgvector top-k β split answer into claims β LLM judge β faithfulness β
β eval_runs + eval_pair_scores β drift report + alert β
Claude Desktop βββΊ β mcp (--mcp): list_models Β· get_stats Β· route_test_request Β· inspect_trace Β· β
β get_drift_report (JSON-RPC 2.0 over stdio) β
browser / ββββββΊ β Tower console: overview Β· traffic Β· backend health Β· trace inspector Β· β
β evals & drift Β· workflows Β· cockpit (embedded, no build step) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Tower, the console embedded in the binary (no build step): the same k6 run seen from the span store β 3,738 requests in the hour, p50 142 ms / p99 261 ms, every request routed with its reason and traceable. The Evals & drift page shows the golden v3 history against the 0.70 alert threshold and the worst-scoring pairs of the latest run.
The provisioned Grafana board during a 5-minute k6 run on 2026-09-19 (2 VUs of short prompts routed to qwen2.5:3b-instruct, 1 VU of long prompts routed to qwen3:8b): 3,737 requests, 1 failure β the quality-tier request that hit the 180 s client timeout, which is the 100 % error step on the yellow line. The 0.972 on the board is the golden v3 suite scored minutes earlier with --score, before the refuted/unmeasurable split; today's gated v3 baseline is 0.914 (8/72 unsolvable, see docs/EVALS.md).
Current release: v1.0.0 - 244 tests, go vet + -race + staticcheck + govulncheck in CI, plus 19 executable policies that fail the build when a rule in docs/RULES.md is broken. See CHANGELOG.md.
| Capability | Where | Proof |
|---|---|---|
| Route chat requests between a fast and a quality local model on a rule you can read, with a cloud fallback that is never used for sensitive data | router/ |
reason on every response; TestSensitiveNeverLeavesBox |
| Speak the OpenAI chat shape, streaming included, to any client library | router/server.go |
TestOpenAIShape, TestStreamSSE; docs/API.md |
Speak the Anthropic Messages API too (/v1/messages, x-api-key, streaming events) |
router/anthropic.go |
TestMessagesReturnsAnthropicShape, TestMessagesStreamsAnthropicEvents β text only; tools is rejected loudly until passthrough lands |
| Virtual API keys with per-minute limits and token budgets | router/keys.go, --create-key |
live 200/429/429/429 on a 2-rpm key |
| Hand-written Prometheus exposition + Tower-native dashboard panels (per-model counts, p50/p99, tokens, error rate) | router/metrics.go, console/ #/overview |
k6: 0/2725 failed at 50 RPS, p99 70 ms |
Keep a multi-step agent alive through kill -9 and resume without repeating work |
tracker/ |
TestKillResume + a recorded live kill |
| Score answers claim-by-claim against retrieved sources, store every run, alert on drift | evals/ |
golden v3 (72 pairs) 0.914 β 8/72 unsolvable (2 retrieval misses + 6 refuted where retrieval hit), 70/72 judged; v2 (48) 1.000 |
One trace per request: trace_id / span_id / parent_id, prompts never stored |
GET /v1/traces/{id}, --trace, MCP |
3 chained spans per chat |
| Let Claude (or any MCP client) ask "which model handled the most traffic?" | mcp/ |
5 tools, live handshake |
| Show it all to a human and let them run an eval or resume a workflow | console/ -> http://localhost:8080 |
nine pages in-app: overview, traces, cockpit, GPU, evals & drift, benchmarks, workflows, metrics, models |
Requirements: Go 1.26.11+ (the patch pin is deliberate; see CHANGELOG), Docker, Ollama with nomic-embed-text and one chat model (qwen2.5:3b-instruct / qwen2.5:7b-instruct-q4_K_M by default, or set FAST_MODEL/QUALITY_MODEL), Python 3 for the corpus cleaner.
docker compose up -d # Postgres 16 + pgvector on :5432
go run . --migrate # migrations/*.sql, tracked in schema_migrations
python scripts/clean_docs.py # corpus/*.md β evals/corpus/clean/*.jsonl
go run . --ingest # embed chunks with nomic-embed-text β pgvector
go run . # gateway + Tower console on :8080 β open http://localhost:8080Or containerised (21 MB distroless image, talks to Ollama on the host):
docker compose --profile app up -d --build # gateway on :8080 + postgres
docker compose run --rm tower --migrate # onceReleases ship tower-vX.Y.Z-{linux,windows,darwin}-{amd64,arm64} binaries built by CI on every v* tag.
Releasing (Track T checklist β all local, CI has no GPU/Postgres):
bash scripts/verify.shgreen.go run . --release-gate(default: last 3 runs of v3 clearEVAL_THRESHOLDon one judge).- Tag
vX.Y.Zand push; CI builds + attaches binaries.
Then:
curl -s localhost:8080/v1/chat/completions -d '{"messages":[{"role":"user","content":"hi"}]}'
# OpenAI shape: {"id":"chatcmpl-β¦","object":"chat.completion","model":"qwen2.5:3b-instruct","choices":[β¦],"usage":{β¦},
# "reason":"short-simple-prompt","backend":"ollama","tier":"fast","candidates":[β¦],"trace_id":"598dβ¦"} β Tower extensions
curl -s -N localhost:8080/v1/chat/completions -d '{"messages":[{"role":"user","content":"hi"}],"stream":true}' # SSE
curl -s localhost:8080/v1/messages -H 'x-api-key: ak_β¦' -d '{"model":"auto","max_tokens":128,"messages":[{"role":"user","content":"hi"}]}' # Anthropic shape
curl -s localhost:8080/v1/models # served models with tier, backend, health
curl -s localhost:8080/v1/traces/598dβ¦ # 3 spans: route.decide β model.generate β router.respond
curl -s localhost:8080/v1/chat/completions -d '{"messages":[{"role":"user","content":"why are you using this model"}]}' # answered by the router: answered_by:"router"
curl -s localhost:8080/metrics # router_*, router_backend_up, router_key_*, eval_faithfulness, gpu_*To require keys: go run . --create-key alice --key-rpm 60 (prints ak_β¦ once), then run with REQUIRE_API_KEY=true and send Authorization: Bearer ak_β¦.
Every mode is a flag on the same binary (go run . --help):
| Flag | What it does |
|---|---|
| (none) | HTTP gateway + Tower console on ADDR (default :8080) |
--mcp |
MCP stdio server for Claude Desktop (config in mcp/README.md) |
--migrate / --ingest / --search "q" |
apply migrations Β· embed the clean corpus into pgvector Β· cosine-search it |
--create-key NAME --key-rpm N --key-budget T |
mint a virtual API key (secret printed once, SHA-256 stored) |
--run-tracker [--tracker-input "q"] / --resume-tracker <id> |
run / resume the 3-step toy agent; kill it mid-step and resume |
--trace <id> |
print redacted spans for a chat or workflow |
--trajectory <id> |
print one workflow's trajectory: steps, done, attempts, retries, and whether it was clean (completed, every step first-try) |
--workflow-verify <id> |
run the verifier (if any) attached to a workflow, store the pass/fail result, and exit |
--workflow-verify-all |
run verifiers for all workflows with a verifier attached, report pass/fail rate, and exit |
--workflow-repeats N (--tracker-input "β¦") |
run the toy workflow N times and print pass^k for k=1..N (the chance all k trials succeed). Reliability of the orchestration, not answer quality β the toy workflow has no ground truth for its content |
--workflow-grade <id> |
grade one workflow's final answer on a 1-5 rubric with JUDGE_MODEL, store it, and show it as a chip on #/workflows. Quality, not groundedness: the workflow does not keep the chunks it retrieved |
| `--workflow-grade-rubric v1 | v2` |
--workflow-grade-all |
with --workflow-grade-rubric: grade all ungraded workflows on the given rubric and exit |
--export-routing-data PATH |
write every route_decisions row as JSONL to PATH (labels and model names only, no prompts) for training the learned router (ml/train_router.py); exits after writing |
--export-evals PATH |
write completed eval runs as Promptfoo-compatible JSONL to PATH and exit |
--import-promptfoo PATH |
import a Promptfoo test file (JSON or YAML) into golden JSONL and exit |
--import-promptfoo-out PATH |
output path for --import-promptfoo (default evals/golden/promptfoo_import.jsonl) |
--advise |
print the static model advisor report (Track K: per-model size/VRAM fit, presence, co-residency verdict) and exit |
--generate-capture-key |
print a new CAPTURE_KEY (base64 32-byte AES-256 key) for opt-in prompt/answer capture and exit |
--draft-golden β review β --freeze-golden |
build a golden set (--golden-version vN): LLM drafts, human reviews, validator rejects unscorable answers, hash frozen |
--score / --drift / --schedule-evals 24h |
run the faithfulness suite, print the drift report, or loop it (--golden-version vN, --golden path; --drift-golden vN picks the version the report and console show); each pair is stored as it is judged and an interrupted suite resumes on the next run, so a judge that dies at pair 66 does not cost the first 66; the suite line also reports misses, refuted, no-claims and unsolvable β the share of the set no router could rescue |
--score-model NAME |
with --score: generate each answer with MODEL (temperature 0, 256 tokens) instead of scoring frozen answers; tags the run for Track L model comparison |
--score-cross-check |
with --score: run the suite twice (primary judge + Groq) and report both scores for cross-validation |
--score-judge2-model NAME |
with --score-cross-check: Groq judge model (default openai/gpt-oss-20b) |
--release-gate (--golden-version vN, --gate-k 3) |
pre-tag check (Track T): exit 0 only if the last k golden-answer runs clear today's EVAL_THRESHOLD on one judge; run locally before tagging, CI has no GPU/Postgres |
--judge-audit (--audit-file, --judge-model, --judge2-model, --judge2-backend, --judge-prompt) |
measure the judge itself against a hand-labelled claim/context set: precision, recall and false-alarm rate for "unsupported", Cohen's ΞΊ between two judges (--judge2-backend groq uses GROQ_API_KEY for a second opinion without a bigger card), and a context-order flip probe that separates label flips from decision flips; exit 1 below recall 0.80 / false alarm 0.20 / decision flips 0.10, 2 when nothing could be judged. `--judge-prompt v2 |
--route-replay (--route-window 720h) |
print the intent/tier decision mix recorded in route_decisions and the baselines a learned router must beat; no quality number until shadow outcomes exist |
--version |
print version, commit and build date |
--version-json |
the same as one line of JSON (version, commit, date, go, module) for scripts and the release checklist |
Environment variables are listed in docs/API.md.
A release is only useful if you can check what you downloaded. Every tagged build is reproducible from source, signed with Sigstore keyless, has an SPDX SBOM, and carries a build-provenance attestation:
sha256sum -c SHA256SUMS
cosign verify-blob --bundle SHA256SUMS.sigstore.json \
--certificate-identity-regexp 'https://github.com/yosrikhiari/AgentOps/.github/workflows/ci.yml@refs/tags/v' \
--certificate-oidc-issuer https://token.actions.githubusercontent.com \
SHA256SUMS
gh attestation verify tower-v1.2.3-linux-amd64 --repo yosrikhiari/AgentOps
tower --version-json # version + the exact commit the signature coversNo Python package, no transitive dependency tree: the gateway installs as one static binary
with one direct dependency (pgx). That is deliberate, and it is the part of this project
that a supply-chain compromise cannot reach through a dependency.
One command (Linux/macOS):
curl -fsSL https://raw.githubusercontent.com/AgentOps/tower/main/install.sh | shHomebrew (macOS/Linux):
brew install AgentOps/tap/towerWindows (winget):
winget install AgentOps.TowerDocker:
docker pull ghcr.io/agentops/tower:latest
docker run -p 8080:8080 ghcr.io/agentops/tower:latestFrom source:
git clone https://github.com/AgentOps/tower
cd tower
go build -o tower .
./tower --migrate
./towerWhat the suite measures, the judge's own measured accuracy, how an interrupted run resumes,
and the current v3 baseline (2026-11-17: faithfulness 0.914, unsolvable 8/72, judge
phi4-mini:3.8b) live in docs/EVALS.md. The number is a baseline to
improve, not a claim of quality β the page says why in the same breath.
Moving from another gateway or proxy? These guides map common configs to Tower env vars, endpoints, and operational checks:
- LiteLLM β Tower β OpenAI-compatible gateway migration, config/env mapping, sovereignty/evals differences.
- TensorZero β Tower β gateway/observability mapping, eval workflow differences, function/variant gaps.
- Helicone β Tower β proxy/observability migration, capture/OTLP options, parallel cutover.
- Open WebUI + Tower β run Open WebUI against Tower's OpenAI-compatible API with Docker Compose, API keys, spend budgets, sovereignty, and optional capture.
main.go wiring: flags β mode; pgx pool + adapters; graceful shutdown
config.go OLLAMA_URL, ADDR, FAST_MODEL, QUALITY_MODEL (all with defaults)
router/ gateway: API keys β classify β plan (fail-closed) β backends (Ollama, OpenAI-style) β metrics β spans
tracker/ workflows/steps row-status durability, spans (Store iface: SQLStore + MemStore)
evals/ corpus ingest, pgvector search, golden validation, judge, retry/backoff, drift, migrations
mcp/ JSON-RPC 2.0 over stdio, 5 tools
console/ Tower web UI (embedded static/) + its JSON endpoints
migrations/ 0001..0015 (applied once each, recorded in schema_migrations)
corpus/ 17 short docs describing this system β the RAG target; golden sets in evals/golden/
load-tests/ router.js (k6: 50 RPS on /health, p99 gate)
lessons/ 33 plain-language HTML lessons on this repo β open lessons/index.html
docs/ MARKET.md (market study + roadmap) Β· RULES.md (engineering rules) Β· API.md Β· VRAM.md Β· adr/ (13 decision records) Β· migrations/ (LiteLLM, TensorZero, Helicone guides) Β· tower-design-system.html (the console design system, live against console/static/tower.css) Β· tower-enhancements.html (20 worked UI/UX enhancements with demos)
policy/ executable policies: tests that fail the build when a rule in docs/RULES.md is broken
AGENTS.md what a coding agent must read first (rules, the Tower design system, the traps). OpenCode/Codex read it natively;
per-tool pointers to it (CLAUDE.md, GEMINI.md, β¦) are local and git-ignored; .github/copilot-instructions.md is tracked
The engineering rules β architecture style, sync vs async, retries, latency and scalability budgets, security requirements, guardrails, testing/experiment rules, static analysis, and the executable policies that enforce them β are in docs/RULES.md. Full decision one-pagers in docs/adr/.
Before every commit, run the gate (Track O β the same script CI runs):
bash scripts/verify.sh # gofmt, vet, tests, build, policy, diff statWindows without bash: run the same five commands by hand (gofmt -l ., go vet ./..., go test -count=1 ./..., go build ./..., go test -count=1 ./policy/). CI adds -race via VERIFY_RACE=1 (needs cgo); on Windows, run powershell -File scripts/test-race-docker.ps1 (Docker + cgo Linux).
- One module, one binary β every mode is a flag; packages reach Postgres through tiny interfaces and never import the driver. (ADR-0001)
- pgvector, not a vector DB β one Postgres for workflows, spans, evals and vectors; HNSW
m=16, ef_construction=128. (ADR-0004) - Postgres-native durability, not DBOS/Temporal β
(workflow_id, seq)idempotency keys +pendingβrunningβdonerows; resume = re-run the same id and skipdone. (ADR-0003) - Scheduler is a flag, not a service β
--schedule-evals 24hloops the samescoreOncethat--scoreand the console call. (ADR-0006) - Per-question eval rows β
eval_pair_scoreslets the drift report name the worst cases without re-running judges. (ADR-0005) - Heuristic router first β a reasoning word (
why,explain,compare,reason) orlen > 200β quality tier; a question about the gateway is answered by the router itself, from the last trace and the roster, with no model call. Oneifyou can explain beats a classifier you can't demo. - Fail-closed on sensitive data β the routing plan is built once; a sensitive request has no cloud candidate, ever. (ADR-0007)
- Judge bias guards β justification before verdict, negative verdicts parsed first, temperature 0, judge model + prompt version logged,
judge_changedflag in the drift report. - Golden answers are standalone propositions β the judge never sees the question, so one-word, list-fragment and "Becauseβ¦" answers score 0 regardless of truth;
--freeze-goldenrejects them. Learned from v1 (0.969) β v2 (1.000). - Telemetry never on the request path β spans go through a 1024-deep channel to one writer goroutine; a dead DB costs a chat nothing (verified: chat stays 200 with Postgres stopped).
- The console is read-mostly and framework-free β three embedded files on the Tower design tokens; abortable fetches, retry on 5xx, inline error + Retry, polling that never replaces a field you are typing in. (ADR-0008)
- 8 GB VRAM: one chat model resident at a time; an eval run and live traffic contend for the GPU (
docs/VRAM.md,EVAL_TIMEOUT). - The API-key rate limiter is per process; usage is charged after the response, so a budget can overshoot by one request.
- Console endpoints are unauthenticated (localhost tool) β proxy them if exposed.
- Tracker: no lease for two concurrent resumers, no
failedterminal state; step spans use the workflow id as parent. - Retrieval is vector-only; hybrid BM25 + RRF is parked.
Roadmap and the full defect log live in docs/PLAN.md (Β§7 backlog, Β§9 v1.0 tracks). Where this sits in the market and what to build next: docs/MARKET.md.
The gateway never stores prompts; sensitive requests never leave the machine β see PRIVACY.md. Licensed under Apache-2.0.

