API Documentation

Everything you need to integrate TokenSave into your application.

Quick start

TokenSave works as a drop-in replacement for your AI provider's API endpoint. Replace one URL in your code and every request is automatically optimized through caching, smart model routing, and prompt compression.

3-step setup
1.

Sign up at tokensave.vercel.app/login and get your TokenSave API key from the dashboard.

2.

Replace your AI provider URL with https://tokensave.vercel.app/api/proxy

3.

Pass your provider API key in the request body. That's it.

POST /api/proxy

Send AI requests through the TokenSave optimization pipeline.

Request body

ParameterTypeRequiredDescription
providerstringYes"anthropic", "openai", "google", or "groq"
apiKeystringYesYour AI provider API key
messagesarrayYesArray of message objects with role and content
tsKeystringNoYour TokenSave API key for tracking and higher rate limits
modelstringNoOverride auto-routing with a specific model name
qualitystringNo"auto" (default), "max_savings", or "max_quality"
fallbackKeysobjectNoBackup provider keys for auto-fallback on rate limits
tagsobjectNoCustom key-value pairs for filtering and analytics
userIdstringNoYour user ID for per-user analytics tracking
webhookUrlstringNoURL to receive POST notifications on each request

Example — cURL

curl -X POST https://tokensave.vercel.app/api/proxy \
  -H "Content-Type: application/json" \
  -d '{
    "provider": "anthropic",
    "apiKey": "sk-ant-your-key",
    "tsKey": "ts_live_your-tokensave-key",
    "messages": [
      { "role": "user", "content": "What is the capital of France?" }
    ]
  }'

Example — JavaScript

const response = await fetch("https://tokensave.vercel.app/api/proxy", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    provider: "anthropic",
    apiKey: "sk-ant-your-key",
    tsKey: "ts_live_your-tokensave-key",
    messages: [
      { role: "user", content: "What is the capital of France?" }
    ]
  })
});

const data = await response.json();
console.log(data);

Example — Python

import requests

response = requests.post(
    "https://tokensave.vercel.app/api/proxy",
    json={
        "provider": "anthropic",
        "apiKey": "sk-ant-your-key",
        "tsKey": "ts_live_your-tokensave-key",
        "messages": [
            {"role": "user", "content": "What is the capital of France?"}
        ]
    }
)

print(response.json())

Response

The response includes the original AI provider response plus a tokensave_meta object with optimization details.

{
  // Original AI provider response fields...
  "tokensave_meta": {
    "cache_hit": false,
    "model_used": "claude-haiku-4-5-20251001",
    "complexity": "simple",
    "chars_saved": 12,
    "method": "routed_to_cheap",
    "rate_limit_remaining": 55
  }
}

Optimization features

Semantic cache

Identical requests are cached for 30 minutes. When a cache hit occurs, the response is returned instantly with zero API cost. The cache_hit field in tokensave_meta indicates whether the response was served from cache.

Model routing

TokenSave analyzes each request and routes it to the most cost-effective model. Simple queries (short, factual) go to cheaper models; complex queries (coding, analysis, long-form) go to capable models.

ProviderSimple tasksComplex tasks
Anthropicclaude-haiku-4-5claude-sonnet-4
OpenAIgpt-4o-minigpt-4o
Googlegemini-2.0-flash-litegemini-2.0-flash
Groqllama-3.1-8b-instantllama-3.3-70b-versatile

Prompt compression

Filler words, extra whitespace, and redundant phrases are automatically removed from prompts before forwarding. The chars_saved field shows how many characters were compressed.

Rate limits

The API enforces rate limits per TokenSave key (or per IP if no key is provided).

PlanRate limitCache TTL
Free trial60 requests/minute30 minutes
Starter200 requests/minute60 minutes
Growth / EnterpriseUnlimitedConfigurable

Rate limit headers X-RateLimit-Remaining and X-RateLimit-Limit are included in every response.

Error codes

CodeMeaning
400Missing required fields (messages, apiKey)
429Rate limit exceeded. Wait and retry.
500Server error or AI provider error

POST /api/batch

Process multiple prompts in a single request. Maximum 50 prompts per batch.

curl -X POST https://tokensave.vercel.app/api/batch \
  -H "Content-Type: application/json" \
  -d '{
    "provider": "groq",
    "apiKey": "your-key",
    "prompts": [
      "What is 2+2?",
      "Capital of France?",
      "Translate hello to Spanish"
    ]
  }'

Response includes batch_id, success count, cache hits, processing time, and individual results for each prompt.

POST /api/trim-context

Automatically trim old messages from long conversations to fit within token limits.

curl -X POST https://tokensave.vercel.app/api/trim-context \
  -H "Content-Type: application/json" \
  -d '{
    "maxTokens": 4000,
    "messages": [
      {"role": "system", "content": "You are helpful."},
      {"role": "user", "content": "old message 1"},
      {"role": "assistant", "content": "old reply 1"},
      {"role": "user", "content": "latest question"}
    ]
  }'

Keeps system messages and the latest user message. Removes oldest conversation messages first until within the token limit.

POST /api/smart-context

Automatically summarize old messages in long conversations. A 50-message conversation (25,000 tokens) can be reduced to ~3,000 tokens (88% savings) while preserving all important context.

curl -X POST https://tokensave.vercel.app/api/smart-context \
  -H "Content-Type: application/json" \
  -d '{
    "maxTokens": 4000,
    "keepRecent": 6,
    "messages": [
      {"role": "user", "content": "message 1"},
      {"role": "assistant", "content": "reply 1"},
      ... (50 messages)
      {"role": "user", "content": "latest question"}
    ]
  }'

Returns optimized messages with a summary replacing old messages. The most recent messages are kept in full.

Multi-provider fallback

If your primary provider hits a rate limit, TokenSave can automatically switch to another provider. Add fallback API keys to enable this:

fetch("https://tokensave.vercel.app/api/proxy", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    provider: "anthropic",
    apiKey: "your-claude-key",
    fallbackKeys: {
      groq: "your-groq-key",
      openai: "your-openai-key"
    },
    messages: [{ role: "user", content: "Hello" }]
  })
})

If Claude is rate limited, TokenSave automatically tries Groq, then OpenAI. The response includes which provider was used. Your users never see a rate limit error.

Code examples in 8 languages

View ready-to-copy integration examples in JavaScript, Python, Node.js, cURL, Ruby, PHP, Go, and Java.

View Full API Reference →

Support

Questions or issues? Email prathamg200404@gmail.com or try the Playground to test your integration.