Package Exports
- rootrouter
Readme
πΏ RootRouter
Algebraic Agent Infrastructure for AI Swarms
Cut your agent's LLM costs 40β70% with root-pair telemetry, interaction graphs, and symmetry-aware context filtering.
Verifiable on-chain analytics on Celo Β· ERC-8004 compatible
The Problem
AI agents are expensive. Every autonomous agent burns tokens sending full conversation history on every LLM call. A typical agent session accumulates 50K+ tokens of context, but most of it is irrelevant to the current query.
OpenRouter routes between models but doesn't optimize what gets sent. Agent frameworks orchestrate tasks but don't structure the data. Nobody uses the mathematical properties of the interaction space itself.
The result: agents waste 40β70% of their token budget on irrelevant context, use expensive models for simple tasks, and have no way to verify their decision-making on-chain.
The Solution
RootRouter is middleware that sits between your agents and their LLM providers. It does three things:
1. π‘ Root-Pair Telemetry
Every interaction produces a root pair: the gap between what was intended (query embedding) and what was executed (response embedding). The root vector r = intent β execution measures how well the agent fulfilled the request. Collect enough root pairs and geometric structure emerges β the interaction space has preferred directions, natural regions, and algebraic symmetry.
2. π¬ Algebraic Context Filtering
Using PCA, we find the root directions β principal axes of variation in the interaction space. These define chambers (regions where the agent performs similarly). For context retrieval, we use three strategies:
- Chamber retrieval: only include history from the same/adjacent chambers
- Graph retrieval: traverse the interaction knowledge graph for related context
- Reflection retrieval: algebraically reflect the query through root direction hyperplanes to find complementary information
This replaces "send everything" with "send exactly what's relevant."
3. π§ Intelligent Model Routing
Each chamber has a historical difficulty score (average root norm). Easy chambers route to fast cheap models. Hard chambers route to powerful expensive models. For swarms, the agent topology graph tracks which agent specializes in which chamber β tasks are routed to the specialist, not broadcast to everyone.
All telemetry is logged on Celo for verifiable, auditable agent infrastructure.
Results
Metric Baseline RootRouter Savings
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Total Cost ~$1.00 ~$0.51 ~49%
Context Tokens 27,245 filtered 36,317 saved
Quality (norm) 1.3043 1.3043 ~same
Active Chambers β ~19 auto-discovered
Root Directions β 5 ~50% variance
Graph Edges β ~81 ~4.0 avg degreeRun npx tsx demo/benchmark.ts to reproduce. Numbers from 50-query benchmark, TF-IDF embeddings, simulated LLM. Cost savings vary Β±5% between runs due to random output token simulation. Quality measured by root norm (intent-execution alignment) β lower is better, same means no quality loss.
Quick Start
# Clone and install
git clone https://github.com/gerryalvarez/rootrouter.git
cd rootrouter
npm install
# Run the demo (works offline β no API keys needed!)
npx tsx demo/basic.ts
# Run the benchmark
npx tsx demo/benchmark.ts
# Run the multi-agent swarm demo
npx tsx demo/swarm.tsTo see live telemetry from Celo, use the dashboard (see Dashboard below).
Configuration
- Offline demos: No API keys required; demos use a simulated LLM.
- Real LLM + Celo: Copy
.env.exampleto.envand set at least:LLM_BASE_URL,LLM_API_KEY(e.g. OpenAI or OpenRouter)CELO_RPC_URL,CELO_PRIVATE_KEY,TELEMETRY_CONTRACT_ADDRESSFor mainnet, useCELO_RPC_URL_MAINNET,CELO_PRIVATE_KEY_MAINNET, andTELEMETRY_CONTRACT_ADDRESS_MAINNET. Deployed mainnet contract:0x91aB56AbB4577B2B61Eed9A727cCb0D39896f0Ab.
Lighter / cheaper runs: Set DEMO_QUICK=true to reduce interactions (basic: 15, benchmark: 15, swarm: 21). Use a single cheap model for all tiers (e.g. MODEL_FAST=gpt-4o-mini, MODEL_BALANCED=gpt-4o-mini, MODEL_POWERFUL=gpt-4o-mini) to keep real-LLM tests affordable.
Using both xAI and OpenAI: RootRouter uses a single LLM endpoint (e.g. OpenRouter). To route easy tasks to xAI and hard tasks to OpenAI, set OpenRouter as LLM_BASE_URL and pick models per tier in .env, for example:
MODEL_FAST=x-ai/grok-3-mini(or another fast xAI model)MODEL_BALANCED=openai/gpt-4o-miniMODEL_POWERFUL=openai/gpt-4oOpenRouterβs single API key will proxy to both providers; RootRouter then selects the tier (and thus the model) by chamber difficulty.
Use in Your Agent
Install from the repo (e.g. npm install /path/to/RootRouter or from GitHub), run npm run build in RootRouter to generate dist/, then in your bot:
import { RootRouter } from 'rootrouter';
const router = new RootRouter({
llmBaseUrl: 'https://openrouter.ai/api/v1',
llmApiKey: process.env.OPENROUTER_KEY,
celoRpcUrl: process.env.CELO_RPC_URL,
celoPrivateKey: process.env.CELO_PRIVATE_KEY,
telemetryContractAddress: process.env.TELEMETRY_CONTRACT_ADDRESS,
});
// Wrap your existing chat calls
const result = await router.chat({
agentId: 'my-agent',
messages: [{ role: 'user', content: 'Write a sorting algorithm' }],
});
console.log(result.response);
console.log(`Saved ${result.telemetry.tokensSaved} tokens ($${result.telemetry.costSaved.toFixed(4)})`);
console.log(`Chamber: ${result.telemetry.chamberUsed}, Model: ${result.telemetry.modelUsed}`);SDK as NPM package
The library is publishable to NPM. Build and publish:
npm run build # emits dist/ (tsconfig.build.json)
npm publish # prepublishOnly runs build; only dist/ and README.md are in the tarballConsumers can install with npm install rootrouter (or a scoped name like @your-org/rootrouter if you publish under a scope). The package exposes main, types, and exports for both CommonJS and ESM resolution.
Dashboard
Run the Next.js dashboard to view on-chain telemetry:
npm run dashboardOpen http://localhost:3000, enter the agent address (wallet that sends telemetry, e.g. your deployer address), and click Load from Celo to fetch stats and recent entries from the contract.
Convex (optional backend): The dashboard uses Convex to store run snapshots for the Topology view (chambers, agent graph, vector space). To enable it:
- Run
npx convex devonce β log in if prompted, then it will create.env.localwithNEXT_PUBLIC_CONVEX_URLand generate the Convex backend. - Restart the dashboard (
npm run dashboard). Open Topology in the nav to see run snapshots. - To push a snapshot from a demo: set
DASHBOARD_URL=http://localhost:3000in.env, start the dashboard, then run e.g.npm run demo:basic. The script will POST the run state to the dashboard; refresh the Topology page to see it.
Architecture
ββββββββββββββββ
β User/Agent β
ββββββββ¬ββββββββ
β query
ββββββββΌββββββββ
β RootRouter β
β Orchestratorβ
ββββββββ¬ββββββββ
β
βββββββββββββββββββΌββββββββββββββββββ
β β β
ββββββββΌβββββββ ββββββββΌβββββββ ββββββββΌβββββββ
β Embed & β β Classify β β Filter β
β Compute β β into Weyl β β Context β
β Root Pair β β Chamber β β(Chamber+ β
β β β (PCA sign β β Graph+ β
β TF-IDF or β β patterns) β β Reflection) β
β API embed β β β β β
βββββββββββββββ βββββββββββββββ ββββββββ¬βββββββ
β
ββββββββΌβββββββ
β Route to β
β Optimal β
β Model β
ββββββββ¬βββββββ
β
ββββββββββββββββββββΌβββββββββββββββββββ
β β β
ββββββββΌβββ ββββββββΌβββ ββββββββΌβββββββ
β Fast β βBalanced β β Powerful β
β (Haiku) β β(Sonnet) β β (Opus) β
βββββββββββ βββββββββββ βββββββββββββββ
β
ββββββββΌβββββββ
β Telemetry ββββ Celo (on-chain)
βββββββββββββββKey Components
| Component | What It Does | Why It Matters |
|---|---|---|
| Root Pair Collector | Records intent/execution vectors for every interaction | The raw telemetry data |
| Structured Vector Space | PCA β root directions β chambers via sign patterns | Algebraic structure of interaction space |
| Interaction Graph | Knowledge graph of interaction relationships | Relational context beyond vector similarity |
| Agent Topology Graph | Tracks agent specializations and delegation patterns | Swarm coordination and task routing |
| Context Filter | Chamber + Graph + Reflection retrieval | The money-saving mechanism |
| Model Router | Chamber difficulty β model tier selection | Pay for quality only when needed |
| Celo Telemetry | On-chain performance logging | Verifiable, auditable agent infra |
The Math
RootRouter is inspired by root systems from Lie algebra β mathematical structures that describe symmetry in physics. The key insight:
- Root vectors (intent β execution) live in a high-dimensional space
- PCA finds the principal directions of variation β "simple roots"
- Sign patterns relative to these directions define chambers β "Weyl chambers"
- Reflections through root direction hyperplanes find complementary information
- The interaction graph captures relational structure that geometry alone misses
This gives us a principled way to decompose the agent interaction space β not arbitrary k-means clusters, but algebraically-motivated regions with well-defined adjacency and reflection operations.
For the full mathematical treatment, see:
- Alvarez, G. (2026). Algebraic Structures of Collective Consciousness. Working Paper.
- Alvarez, G. (2026). Root-Structured Intelligence: An E8 Framework for Symmetry-Aware AI. Working Paper.
Celo Integration
RootRouter logs telemetry on Celo for three reasons:
- Verifiability: Other agents can audit RootRouter's performance on-chain
- Cost efficiency: Celo's sub-cent fees make high-frequency logging practical
- ERC-8004: RootRouter registers as a Trustless Agent, discoverable by the ecosystem
On-Chain Data
- Chamber classification for each interaction
- Root norm (performance metric)
- Model tier used
- Tokens saved
ERC-8004 Registration
RootRouter registers on the ERC-8004 Identity Registry on Celo, with capabilities:
context-optimization: Algebraic context filteringmodel-routing: Chamber-based model selectiontelemetry-logging: Verifiable performance analytics
Tech Stack
- TypeScript β zero external ML libraries, all math from scratch
- PCA, K-Means β implemented with power iteration, no NumPy/sklearn
- TF-IDF β local embeddings that work offline (API embeddings optional)
- ethers.js β Celo blockchain interaction
- Solidity β RootRouterTelemetry contract (contracts/)
Project Structure
src/
βββ types.ts # All type definitions
βββ config.ts # Configuration with sensible defaults
βββ math/ # Pure math (vectors, PCA, k-means)
βββ embeddings/ # TF-IDF (local) + API embeddings
βββ core/ # Collector, VectorSpace, Graph, AgentGraph,
β # ContextFilter, Router
βββ celo/ # On-chain telemetry + ERC-8004
βββ rootRouter.ts # Main orchestrator
βββ index.ts # Public API
app/ # Next.js dashboard (live Celo telemetry)
βββ layout.tsx
βββ page.tsx
βββ globals.css
demo/
βββ basic.ts # 40 interactions, single agent
βββ swarm.ts # Multi-agent swarm coordination
βββ benchmark.ts # Baseline vs RootRouter comparison
contracts/
βββ RootRouterTelemetry.sol # On-chain telemetry contractRun npm run build to produce dist/ for the library; required when installing RootRouter as a dependency in another project.
Roadmap
| Phase | What |
|---|---|
| 1. Open Source | Core library, demos, Celo integration β |
| 2. Dashboard | Next.js app for live on-chain telemetry (chambers, model routing, recent entries) β |
| 3. Router-as-a-Service | Drop-in replacement for OpenRouter with algebraic routing |
| 4. Enterprise | Root system analytics for any paired data streams |
Team
Gerry Alvarez β Independent researcher in systems psychology and applied mathematics. Mexico City. Building MotusDAO (decentralized mental health) and the E8 Systems Framework (algebraic models of collective intelligence).
License
MIT β use it, fork it, build on it.