Multi-Modal Pre-Inference Optimization Gateway for LLMs & Vision APIs
Slash LLM API costs by 70% – 88% before sending a single token over the wire.
TokenShield is a lightweight, local pre-inference optimization engine designed to dismantle the largest bottleneck in artificial intelligence: Token Consumption & API Overbilling.
Current AI proxies (LiteLLM, Portkey, Helicone) simply route raw requests directly to model providers. TokenShield acts as an intelligent optimization firewall — stripping out redundant boilerplate, intelligently cropping oversized high-res imagery, and matching perceptual visual hashes locally in milliseconds to achieve zero-token responses.
[USER / CLIENT REQUEST]
(Prompt + High-Res Image)
│
▼
┌───────────────────────────────────────────────────────────┐
│ TOKENSHIELD GATEWAY │
│ │
│ [ENGINE 1: Dynamic Context Aliasing (Text - CADVS)] │
│ Repeated Entities ──► Compact Registry ($V1, $V2) │
│ │
│ [ENGINE 3: Perceptual Visual Hash Cache (PV-Cache)] │
│ 64-bit dHash ──► Hamming Match (≤4) ──► 0 TOKENS HIT! │
│ │ (Cache Miss) │
│ ▼ │
│ [ENGINE 2: Saliency-Based ROI Cropper (ASVPP)] │
│ 1080p Image ──► Strip Blank Margins ──► 512x512 ROI │
└─────────────────────────────┬─────────────────────────────┘
│
▼ (70% - 88% Fewer Tokens!)
[LLM API: Claude / GPT-4o / Gemini]
$V1, $V2), and replaces all body occurrences in-place.Tested against real PostgreSQL enterprise migration scripts and live 1080p Full HD terminal screenshots:
| Engine / Component | Real-World Input | Original Cost | Optimized Cost | Net Savings | Execution Speed |
|---|---|---|---|---|---|
| Engine 1 (Text CADVS) | PostgreSQL Schema Migration (1,728 chars) | 432 Tokens | 281 Tokens | 34.95% Cut | 0.23 ms |
| Engine 2 (Vision ASVPP) | 1080p Full HD Fatal Error Screenshot | 2,125 Tokens | 595 Tokens | 72.00% Cut | 25.98 ms |
| Engine 3 (PV-Cache) | Distorted 40% JPEG (WhatsApp simulation) | 2,125 Tokens | 0 Tokens | 100.00% FREE | 6.33 ms |
| Engine 3 (PV-Cache) | 70% Scaled Mobile Image | 2,125 Tokens | 0 Tokens | 100.00% FREE | 5.80 ms |
| False-Positive Gate | Unrelated Imagery Check | N/A | Correct Pass-through | 0.0% Error Rate | Safe Forwarding |
git clone https://github.com/harshitpratap1113-glitch/tokenshield.git
cd tokenshield
⚠️ Important: Always make sure you run
cd tokenshieldbefore running any scripts! If you try to runpython cli.pyoutside this directory, Python will reportNo such file or directory.
pip install -r requirements.txt
(Optional: Run pip install -e . if you want to use the global tokenshield-cli command from any folder on your machine!)
You can optimize prompts or generate agent API keys directly from your terminal:
# 1. Generate an Instant API Key for an Agent / App:
python cli.py --create-key "MyCustomAgent"
# 2. Optimize a long repetitive text prompt:
python cli.py --text "SELECT * FROM UserProfileService JOIN UserProfileService..."
# 3. Optimize an image or screenshot (Saliency ROI Crop + Visual Cache):
python cli.py --image "path/to/screenshot.png"
# 4. Check TokenShield engine status:
python cli.py --status
💡 Global Shortcut (Run from ANY folder without typing python or cd): If you installed with
pip install -e ., you can run anywhere:tokenshield-cli --create-key "cloud"
# Run verified benchmark with real enterprise database queries and 1080p screenshots
python real_world_benchmark.py
from gateway import TokenShieldGateway
# Initialize Gateway
gateway = TokenShieldGateway()
# 1. Optimize Text Prompt
optimized_text = gateway.optimize_text("Your long repetitive database prompt...")
print(optimized_text["compressed_text"])
print(f"Saved: {optimized_text['savings_pct']}% tokens")
# 2. Optimize Vision Input (Cache Check -> Saliency Crop)
optimized_vision = gateway.optimize_vision("path/to/screenshot_1080p.png")
if optimized_vision.get("source") == "VISUAL_CACHE_HIT":
print("⚡ ZERO TOKENS! Cached response:", optimized_vision["cached_response"])
else:
print(f"Cropped to ROI! Saved: {optimized_vision['savings_pct']}% vision tokens")
Nobody wants to manually edit JSON files. TokenShield includes an intelligent cross-platform auto-installer:
Simply double-click 1_CLICK_INSTALL_WINDOWS.bat. It automatically:
python auto_setup.py
Output: Automatically detects your OS, finds your
claude_desktop_config.json, injects the configuration, and confirms setup!
proxy_server.py)Want to optimize any existing Python/Node.js AI app with zero code changes?
Launch the local reverse proxy:
python proxy_server.py
# Running on http://127.0.0.1:8765/v1
In your application code (OpenAI SDK, LangChain, Cursor, LlamaIndex), just point base_url:
from openai import OpenAI
# Simply change base_url to TokenShield Proxy!
client = OpenAI(
base_url="http://127.0.0.1:8765/v1",
api_key="your-api-key"
)
# TokenShield intercepts prompts and images, optimizes them, and logs savings!
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Your long repetitive prompt or image..."}]
)
api_server.py)TokenShield provides a dedicated, high-performance REST API with live Swagger documentation for web apps, frontends, and backend services!
python api_server.py
# Server running at http://127.0.0.1:8765
# Interactive Swagger UI: http://127.0.0.1:8765/docs
curl -X POST "http://127.0.0.1:8765/api/v1/optimize/text" \
-H "Content-Type: application/json" \
-d '{"prompt": "Query CustomerOrderDatabaseSchema and update CustomerOrderDatabaseSchema"}'
curl -X POST "http://127.0.0.1:8765/api/v1/optimize/vision" \
-F "file=@screenshot_1080p.png"
curl "http://127.0.0.1:8765/api/v1/status"
universal_agent_api.py)Designed specifically for autonomous AI agents (LangChain, CrewAI, AutoGen, LlamaIndex, Custom Bots).
Secured with Bearer API Keys (ts_live_...), featuring single mega-endpoint /v1/agent/optimize and live telemetry!
python universal_agent_api.py
# Master API Key: ts_live_master_2026_godmode
import requests
# Send prompts, chat history array, and images in 1 call!
resp = requests.post(
"http://127.0.0.1:8765/v1/agent/optimize",
headers={"Authorization": "Bearer ts_live_master_2026_godmode"},
json={
"messages": [
{"role": "user", "content": "Query CustomerOrderDatabaseSchema and update CustomerOrderDatabaseSchema"}
],
"enable_aliasing": True
}
)
optimized_data = resp.json()
print("Tokens Saved:", optimized_data["telemetry"]["net_tokens_saved"])
print("Clean Messages for LLM:", optimized_data["optimized_messages"])
curl -X POST "http://127.0.0.1:8765/v1/agent/optimize" \
-H "Authorization: Bearer ts_live_master_2026_godmode" \
-H "Content-Type: application/json" \
-d '{"prompt": "Analyze CustomerOrderDatabaseSchema and CustomerOrderDatabaseSchema"}'
TokenShield is 100% platform-agnostic. Use the exact 1-liner or configuration for your preferred AI client below:
Option A: 1-Click Smithery CLI
npx -y @smithery/cli install harshitpratap1113-glitch/tokenshield --client claude
Option B: Global uvx (In claude_desktop_config.json)
{
"mcpServers": {
"tokenshield": {
"command": "uvx",
"args": ["--from", "git+https://github.com/harshitpratap1113-glitch/tokenshield", "tokenshield"]
}
}
}
Option A: 1-Click Smithery CLI
npx -y @smithery/cli install harshitpratap1113-glitch/tokenshield --client cursor
Option B: 1-Click SSE URL
python mcp_server.py --sseSettings -> Features -> MCP):
TokenShieldSSEhttp://localhost:8000/ssenpx -y @smithery/cli install harshitpratap1113-glitch/tokenshield --client windsurf
npx -y @smithery/cli install harshitpratap1113-glitch/tokenshield --client cline
npx -y @smithery/cli install harshitpratap1113-glitch/tokenshield --client zed
In your ~/.continue/config.json:
{
"experimental": {
"modelContextProtocolServers": [
{
"transport": {
"type": "sse",
"url": "http://localhost:8000/sse"
}
}
]
}
}
python mcp_server.py --sseSSEhttp://localhost:8000/sseLaunch proxy: python proxy_server.py (Runs on http://127.0.0.1:8765/v1)
from openai import OpenAI
# Just point base_url - works with ANY Python, JS, or cURL request!
client = OpenAI(base_url="http://127.0.0.1:8765/v1", api_key="sk-...")
Launch server: python universal_agent_api.py (Runs on http://127.0.0.1:8765)
TokenShield provides 3 instant ways to generate persistent ts_live_... API keys:
http://127.0.0.1:8765/dashboard (or root http://127.0.0.1:8765/) in any browser.TradingBot-v1).python cli.py --create-key "MyCustomAgent"
ts_live_... key and permanently saves it to the SQLite database.curl -X POST http://127.0.0.1:8765/v1/keys/public-generate \
-H "Content-Type: application/json" \
-d '{"client_name": "AutonomousAgent", "tier": "standard"}'
⚡ Zero-Friction Master Key: For immediate local testing without generating a key, the pre-configured Godmode key
ts_live_master_2026_godmodeworks out-of-the-box on all endpoints.
import requests
resp = requests.post(
"http://127.0.0.1:8765/v1/agent/optimize",
headers={"Authorization": "Bearer ts_live_your_key_here"},
json={
"messages": [
{"role": "system", "content": "You are a financial analyst."},
{"role": "user", "content": "Analyze PostgreSQL migration logs for GlobalFinancialLiquidityLedger..."}
],
"enable_aliasing": True
}
)
print("Tokens Saved:", resp.json()["telemetry"]["net_tokens_saved"])
mcp_server.py) for Claude Desktop & Cursor.proxy_server.py) & Universal SSE Transport.MIT License. Created and maintained by harshitpratap1113-glitch. Contributions welcome!