convez.ai
Agente
Sourav-02121996

TokenGuardAI

Sourav-02121996/TokenGuardAI

Ver no GitHub
InicialPluginScore · de 0 a 100

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/TokenGuardAI

1 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

Estrelas
0
Forks
0
Acompanhando
0
Saúde
28%
Último commit
há 5 meses
Versão
—
Issues abertas
0
Contribuidores
1

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

  1. Monitor Mode — track and display AI usage. Limits are evaluated and alerts are raised, but requests are never blocked.
  2. 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

LayerChoice
FrameworkNext.js 14 (App Router) + TypeScript
DatabasePrisma ORM + SQLite (swap to Postgres/MySQL)
AuthCustom email/password — bcrypt + JWT httpOnly cookie (jose)
StylingTailwind CSS (modern SaaS dashboard)
ChartsRecharts
ValidationZod
SecretsAPI 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

RequirementPage / 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 enginesrc/lib/policy.ts
Simulate AI Requestsrc/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:

  1. 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.
  2. Aggregate usage for every limit whose scope matches the request (PROVIDER / AGENT / MODEL / USER / PROJECT) over its period (DAILY / WEEKLY / MONTHLY). Only ALLOWED events count toward usage.
  3. 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.
  4. Persist an append-only UsageEvent, any Alerts, agent status changes, and an AuditLog entry — 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 — UsageEvent records are append-only and never deleted by default; limit changes and enforcement actions write AuditLog records.
  • 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:

  1. Use a python/ connector (or implement one) that calls the real API and returns a UsageResult — { inputTokens, outputTokens, cachedTokens, reasoningTokens, latencyMs, cost }.
  2. 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.
  3. Forward through /api/ingest (Python) or call evaluate()/recordUsageEvent() directly (TypeScript) — exactly as simulateRequest() does in src/app/(app)/actions.ts.

Nothing else in the UI, dashboards, limits, or alerts has to change.

Ver o original no GitHub

Bom para

Relacionados