TokenGuardAI
Sourav-02121996/TokenGuardAI
The purpose of the app is to help users track, control, and limit token/cost usage across AI providers and coding agents such as OpenAI/ChatGPT API, Anthropic Claude API, Perplexity API, Claude Code, Codex, Cursor-like agents, and custom AI agents.
Instalação
npx convez-ai Sourav-02121996/TokenGuardAI1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.
Métricas
README
A tradução para o português deste README ainda está na fila.
TokenGuard AI
An AI usage governance & budget control platform. Track, control, and limit token/cost usage across AI providers and coding agents (OpenAI/ChatGPT, Anthropic Claude, Perplexity, Claude Code, Codex, Cursor-like agents, and custom agents).
This is a production-quality MVP: real app structure, database models, auth, dashboards, forms, and a simulated AI-gateway enforcement engine — built so the mock provider connectors can be swapped for real API integrations later.
This is not a chatbot and not a static dashboard. It is a usage-governance control plane.
Two modes
- Monitor Mode — track and display AI usage. Limits are evaluated and alerts are raised, but requests are never blocked.
- Control Mode — act as an AI gateway/proxy that blocks, pauses, or holds requests when usage limits are exceeded.
Mode is set per provider account, so you can monitor one provider while enforcing another.
Tech stack
| Layer | Choice |
|---|---|
| Framework | Next.js 14 (App Router) + TypeScript |
| Database | Prisma ORM + SQLite (swap to Postgres/MySQL) |
| Auth | Custom email/password — bcrypt + JWT httpOnly cookie (jose) |
| Styling | Tailwind CSS (modern SaaS dashboard) |
| Charts | Recharts |
| Validation | Zod |
| Secrets | API keys encrypted at rest with AES-256-GCM |
Quick start
npm install
npm run setup # prisma generate + db push + seed sample data
npm run dev # http://localhost:3000
Demo login: demo@tokenguard.ai / password123
(Or sign up for a fresh, empty account.)
Useful scripts:
npm run db:seed # re-seed sample data
npm run db:reset # wipe + recreate + seed
npm run build # production build
npm start # run the production build
Environment (.env)
DATABASE_URL="file:./dev.db" # swap for a Postgres/MySQL URL in prod
AUTH_SECRET="..." # signs session JWTs — CHANGE in prod
ENCRYPTION_KEY="<64-char hex>" # AES-256 key for API keys — CHANGE in prod
Features → where to find them
| Requirement | Page / file |
|---|---|
| Sign up / log in / per-user isolation | /login, /signup, src/lib/auth.ts, src/lib/session.ts |
| Provider accounts (masked API keys) | /providers, src/components/ProviderForm.tsx |
| Agents (Claude Code, Codex, …) | /agents, src/components/AgentForm.tsx |
| Dashboard (counters, 6 charts, filters) | /dashboard, src/lib/stats.ts, src/components/Charts.tsx |
| Usage logs (append-only, search/filter) | /usage-logs |
| Usage limits (5 scopes, 3 types, 3 periods, 4 actions, 4 thresholds) | /limits, src/components/LimitForm.tsx |
| Alerts (acknowledge / resolve) | /alerts |
| Settings (fail-open/closed, gateway status, retention) | /settings |
| Policy enforcement engine | src/lib/policy.ts |
| Simulate AI Request | src/components/SimulateModal.tsx (Dashboard & Usage Logs) |
How enforcement works (src/lib/policy.ts)
When a request is simulated (or, later, proxied for real), the engine runs a fast policy check:
- Availability — checks provider status, provider health, and gateway status.
- Provider disabled/down → request
FAILED. - Gateway
DOWN→ follow the user's fail-open / fail-closed setting.
- Provider disabled/down → request
- Aggregate usage for every limit whose scope matches the request
(
PROVIDER/AGENT/MODEL/USER/PROJECT) over its period (DAILY/WEEKLY/MONTHLY). OnlyALLOWEDevents count toward usage. - Compare projected usage vs. limit value.
- Crossing 50/80/90/100% thresholds raises alerts (Info → Warning → Critical).
- Exceeding a hard limit applies the configured action (
WARN,PAUSE_AGENT,BLOCK,MANUAL_APPROVAL) — but only when the provider is in Control Mode.
- Persist an append-only
UsageEvent, anyAlerts, agent status changes, and anAuditLogentry — atomically in one transaction.
The decision (status, block reason, per-limit trace, simulated policy-check latency) is shown right in the Simulate AI Request modal.
Non-functional design notes
- Low latency — limit checks are simple indexed aggregations; the simulated policy-check
latency (
policyCheckMs) is recorded and displayed. - Durability —
UsageEventrecords are append-only and never deleted by default; limit changes and enforcement actions writeAuditLogrecords. - Availability — per-provider health (
ProviderHealth) and a gateway status banner; down providers fail requests; degraded gateway shows a warning banner. - Security — API keys are AES-256-GCM encrypted at rest and only ever shown as
••••last4. All data is scoped to the authenticated user.
Data model (prisma/schema.prisma)
User, UserSettings, ProviderAccount, Agent, UsageEvent, UsageLimit, Alert,
ProviderHealth, AuditLog. Enum-like fields are stored as strings (SQLite) and validated in
src/lib/constants.ts.
Python connector layer (python/)
A separate Python package — with its own virtual environment — connects to real providers and forwards normalized usage to the gateway. See python/README.md.
cd python
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements-core.txt # mock mode; or requirements.txt for real SDKs
python run_connector.py --provider OPENAI --model gpt-4o --prompt "hi" --mock
python -m pytest -q # 11 tests
Connectors run in mock mode offline and switch to live API calls when a key + SDK are
present. They post to the POST /api/ingest endpoint (src/app/api/ingest/route.ts), which
runs the same policy engine as the in-app simulator and returns the allow/block decision.
Replacing the mock with real providers
The simulator, the Python connectors, and the real path all share one entry point:
evaluate() then recordUsageEvent(). To go live:
- Use a
python/connector (or implement one) that calls the real API and returns aUsageResult—{ inputTokens, outputTokens, cachedTokens, reasoningTokens, latencyMs, cost }. - Decrypt the stored key with
decryptApiKey()(src/lib/crypto.ts) at call time, or pass it to the connector via the provider's env var. - Forward through
/api/ingest(Python) or callevaluate()/recordUsageEvent()directly (TypeScript) — exactly assimulateRequest()does insrc/app/(app)/actions.ts.
Nothing else in the UI, dashboards, limits, or alerts has to change.