Skip to content
TokenSave.

HTTP API · IMPLEMENTATION REFERENCE

Every request, explained.

Schemas, responses and operational limits for the current text API. Base URL: https://www.tokensave.in.

Conventions & limits

TopicCurrent behaviorWhat to do
Content typeJSON request/response; no streamingSend Content-Type: application/json.
CredentialsapiKey in proxy/batch bodyUse provider keys from server environment variables. Never log request bodies.
TokenSave keyOptional tsKey rate-limit identifierNot a verified authentication or paid-plan entitlement.
Proxy rate window60 requests per 60-second Redis windowtsKey bucket, or client IP if absent. No paid-tier differentiation; Redis errors can disable enforcement.
Size limits100 messages; 100,000 characters per content; declared body limit 500,000 bytesTreat provider context limits separately.
API versionNo versioned URL contractDiscovery reports version 3.1.0. Check changelog and retest before upgrades.
RetriesNo idempotency key supportSet a timeout and bounded retry budget. Repeated calls can cost money.
Errorserror may be string or objectCheck HTTP status first. Validation: 400; size: 413; rate: 429; unexpected failure: 500; upstream statuses can pass through.

See detailed error and retry guidance →

A complete first request

Examples run on your server and use an environment variable. They perform a real provider request when executed and can incur charges.

Node.js 20+ · server
// Node.js 20+ / server only. Never expose these keys in client code.
const apiKey = process.env.OPENAI_API_KEY;
if (!apiKey) throw new Error("Set OPENAI_API_KEY on your server");
const response = await fetch("https://www.tokensave.in/api/proxy", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  signal: AbortSignal.timeout(30000),
  body: JSON.stringify({
    provider: "openai",
    apiKey,
    ...(process.env.TOKENSAVE_KEY ? { tsKey: process.env.TOKENSAVE_KEY } : {}),
    messages: [{ role: "user", content: "What is the capital of Japan?" }],
    quality: "auto"
  })
});
const data = await response.json();
if (!response.ok) {
  // Do not log request bodies, credentials or private provider errors.
  throw new Error("TokenSave HTTP " + response.status);
}
// This example selects OpenAI. Other providers have different response shapes.
console.log(data.choices?.[0]?.message?.content);
console.log(data.tokensave_meta);

POST/api/proxy

Optimize a text request

Returns the selected provider's JSON payload with tokensave_meta. Responses are not normalized across providers. No streaming, images, tools or arbitrary provider options are forwarded.

FieldType / requirementBehavior
messagesarray · required1–100 messages. Each needs role (user, assistant or system) and non-empty string content, at most 100,000 characters per message. At least one non-system message is required. Unsupported stream/tools/temperature/max_tokens/maxTokens parameters return 400.
apiKeystring · requiredYour selected provider credential, 10–500 characters. Sent in the JSON body; keep it in server environment variables.
providerstring · optionalanthropic (default), openai, google or groq.
tsKeystring · optionalValidated TokenSave key associating requests with an account and account rate limit. Without it, the budget is scoped to the provider credential. Does not activate a paid plan.
modelstring · optionalOverrides automatic model selection. The provider validates availability. Other optimization steps still apply; this is not a cache bypass.
qualitystring · optionalauto (default), max_savings or max_quality. max_savings currently follows auto. max_quality skips compression and selects the capable model unless model is supplied; cache lookup happens first.
fallbackKeysobject · optionalProvider-name → credential mapping. Only supplied providers are attempted for eligible rate/quota failures, in groq → anthropic → openai → google order, excluding the primary.
tagsobject · optionalUp to 20 non-empty string values, names up to 50 and values up to 200 characters. Invalid tags return 400. Avoid private information.
userIdstring · optionalCaller-supplied analytics identifier. Does not authenticate a user or establish tenant isolation.
webhookUrlstring · optionalOutbound webhook callbacks are disabled; supplying this field returns 400.
/api/proxy request body
{
  "provider": "openai",
  "apiKey": "YOUR_PROVIDER_KEY",
  "messages": [
    {
      "role": "user",
      "content": "What is the capital of Japan?"
    }
  ],
  "quality": "auto"
}

Response · HTTP 200

/api/proxy response · illustrative JSON
{
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "Tokyo."
      }
    }
  ],
  "tokensave_meta": {
    "request_id": "req_example",
    "cache_hit": false,
    "model_used": "gpt-4o-mini",
    "complexity": "simple",
    "chars_saved": 0,
    "quality_mode": "auto",
    "latency_ms": 420,
    "method": "routed_to_cheap",
    "cost": 0.000003,
    "cost_source": "published_rate_estimate",
    "usage_source": "provider",
    "currency": "USD",
    "pricing_version": "2026-10-30",
    "savings_basis": "unmeasured_baseline",
    "cost_without_optimization": null,
    "savings_percent": null,
    "input_tokens": 8,
    "output_tokens": 3,
    "tags": {}
  }
}

Cache hit · HTTP 200

/api/proxy Cache hit · illustrative JSON
{
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "Tokyo."
      }
    }
  ],
  "tokensave_meta": {
    "request_id": "req_cache_example",
    "cache_hit": true,
    "tokens_saved": 11,
    "cost_saved": 0.000003,
    "savings_percent": 100,
    "savings_basis": "avoided_repeat_at_original_rate",
    "input_tokens": 0,
    "output_tokens": 0,
    "method": "cache",
    "quality_mode": "auto",
    "latency_ms": 12,
    "cost": 0,
    "tags": {}
  }
}

Fallback to Groq · HTTP 200

/api/proxy Fallback to Groq · illustrative JSON
{
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "Tokyo."
      }
    }
  ],
  "tokensave_meta": {
    "request_id": "req_fallback_example",
    "cache_hit": false,
    "model_used": "llama-3.1-8b-instant",
    "complexity": "simple",
    "chars_saved": 0,
    "quality_mode": "auto",
    "method": "fallback",
    "latency_ms": 900,
    "original_provider": "openai",
    "fallback_provider": "groq",
    "cost": null,
    "cost_source": "unavailable",
    "cost_unavailable_reason": "unverified_model_price",
    "cost_without_optimization": null,
    "savings_percent": null,
    "input_tokens": 8,
    "output_tokens": 3,
    "tags": {}
  }
}

Validation error · HTTP 400

/api/proxy Validation error · illustrative JSON
{
  "error": "messages array is required and must not be empty"
}

Declared body too large (middleware) · HTTP 413

/api/proxy Declared body too large (middleware) · illustrative JSON
{
  "error": {
    "message": "Request body too large. Maximum 500KB.",
    "code": 413
  }
}

Proxy rate limit · HTTP 429

/api/proxy Proxy rate limit · illustrative JSON
{
  "error": "Rate limit exceeded. Maximum 60 requests per minute."
}

Upstream authentication failure · HTTP 401

/api/proxy Upstream authentication failure · illustrative JSON
{
  "error": {
    "message": "Invalid API key",
    "type": "invalid_request_error"
  },
  "tokensave_meta": {
    "request_id": "req_error_example",
    "cache_hit": false,
    "model_used": "gpt-4o-mini",
    "complexity": "simple",
    "chars_saved": 0,
    "quality_mode": "auto",
    "latency_ms": 200,
    "is_error": true,
    "tags": {},
    "note": "Error from openai."
  }
}

Unexpected proxy failure · HTTP 500

/api/proxy Unexpected proxy failure · illustrative JSON
{
  "error": "TokenSave proxy error: Example transport failure"
}
Back to examples ↑

POST/api/batch

Process a batch

Validates the whole batch before provider calls, then processes sequentially through the local proxy with a shared 45-second deadline. This is not a provider Batch API discount.

FieldType / requirementBehavior
promptsarray · required1–50 strings, or objects with content. Use non-empty strings.
apiKeystring · requiredProvider credential.
providerstring · optionalanthropic by default; same provider identifiers as proxy.
/api/batch request body
{
  "provider": "openai",
  "apiKey": "YOUR_PROVIDER_KEY",
  "prompts": [
    "What is 2+2?"
  ]
}

Response · HTTP 200

/api/batch response · illustrative JSON
{
  "batch_id": "batch_example",
  "total": 1,
  "successful": 1,
  "cached": 0,
  "processing_time_ms": 900,
  "results": [
    {
      "prompt": "What is 2+2?",
      "status": "success",
      "response": {
        "choices": [
          {
            "message": {
              "content": "4"
            }
          }
        ]
      }
    }
  ]
}
Back to examples ↑

POST/api/trim-context

Trim conversation history

Keeps system messages and the final message, then fits earlier non-system messages from newest to oldest. Returns messages; it does not call an AI provider.

FieldType / requirementBehavior
messagesarray · requiredUse valid text messages, ending with the latest user message.
maxTokensnumber · optionalDefault 4000. Supply a positive integer; estimate uses ceil(characters / 4) per message.
/api/trim-context request body
{
  "messages": [
    {
      "role": "system",
      "content": "Be concise."
    },
    {
      "role": "user",
      "content": "Hello"
    }
  ],
  "maxTokens": 4000
}

Response · HTTP 200

/api/trim-context response · illustrative JSON
{
  "original_messages": 2,
  "trimmed_messages": 2,
  "messages_removed": 0,
  "original_tokens": 5,
  "final_tokens": 5,
  "tokens_saved": 0,
  "trimmed": [
    {
      "role": "system",
      "content": "Be concise."
    },
    {
      "role": "user",
      "content": "Hello"
    }
  ]
}
Back to examples ↑

POST/api/smart-context

Summarize older messages

Uses heuristic excerpts, not an LLM. Preserves system messages and requested recent turns; inserts a summary as untrusted user content only when it fits the estimated budget. Otherwise trims older content.

FieldType / requirementBehavior
messagesnon-empty array · requiredText messages with role and content.
maxTokensnumber · optionalDefault 4000. Positive integer; triggers summarization when estimated input exceeds the target.
keepRecentnumber · optionalDefault 6. Use a positive integer for recent non-system messages to preserve.
/api/smart-context request body
{
  "messages": [
    {
      "role": "user",
      "content": "Hello"
    }
  ],
  "maxTokens": 4000,
  "keepRecent": 6
}

Response · HTTP 200

/api/smart-context response · illustrative JSON
{
  "optimized": false,
  "reason": "Already within token limit",
  "original_tokens": 2,
  "final_tokens": 2,
  "tokens_saved": 0,
  "percent_saved": 0,
  "messages": [
    {
      "role": "user",
      "content": "Hello"
    }
  ]
}
Back to examples ↑

GET/api/health

Check infrastructure

Checks server/Redis availability. A passing response does not test authentication, billing or provider generation.

No request body.

Response · HTTP 200

/api/health response · illustrative JSON
{
  "status": "healthy",
  "timestamp": "2026-10-21T08:00:00.000Z",
  "version": "3.1.0",
  "services": {
    "redis": {
      "status": "connected",
      "latency_ms": 12
    },
    "proxy": {
      "status": "running"
    }
  }
}

Redis not configured · HTTP 503

/api/health Redis not configured · illustrative JSON
{
  "status": "degraded",
  "timestamp": "2026-10-21T08:00:00.000Z",
  "version": "3.1.0",
  "services": {
    "redis": {
      "status": "not_configured"
    },
    "proxy": {
      "status": "running"
    }
  }
}
Back to examples ↑

GET/api/proxy

Discover proxy capabilities

Lists API version, provider identifiers, models and endpoint links. Treat this page's limitations as part of the integration guide; discovery descriptions may be broader than implemented behavior.

No request body.

Response · HTTP 200

/api/proxy response · illustrative JSON
{
  "status": "active",
  "service": "TokenSave API Proxy",
  "version": "3.1.0",
  "providers": [
    "anthropic",
    "openai",
    "google",
    "groq"
  ],
  "rate_limit": "60 requests/minute"
}
Back to examples ↑

Read tokensave_meta defensively

FieldWhen presentMeaning
request_idProxy response metadataDiagnostic identifier. Not an idempotency key.
cache_hit / methodCache or provider pathcache, fallback, routed_to_cheap or routed_to_smart. Routing labels can differ from the actual overridden model; inspect model_used.
model_used / complexityProvider callsChosen model ID and rule-based simple/complex classification. May be absent on a cache hit.
quality_mode / chars_savedQuality mode; characters on a missCharacters removed are not tokenizer-measured tokens.
latency_msProxy timingServer-side elapsed time at the point measured; not full browser round trip.
cost / cost_without_optimization / savings_percentProvider callsEstimated USD and comparison with a configured expensive model. Not actual savings versus your application baseline.
input_tokens / output_tokensProvider callsCharacter-based estimates, not authoritative provider billing usage.
original_provider / fallback_providerSuccessful fallbackFallback can change response schema and quality behavior.
tokens_savedCache hitString 100% indicates a reused response, not measured account-wide savings.
tags / is_error / noteDepends on pathOptional diagnostic information; do not assume identical metadata on all branches.

Native response paths: OpenAI/Groq choices[0].message.content; Anthropic text blocks in content; Google text parts in candidates. Check the returned shape, especially after fallback.

Dashboard & operational endpoints

Inventory for transparency. These routes exist, but they do not establish a supported, tenant-isolated external management API. Do not build customer authorization or billing on caller-supplied identifiers or service-wide counters.

EndpointPurposeCurrent boundary
GET /api/statsDashboard metricsService-wide seven-day aggregates, recent logs and performance estimates; not isolated customer billing.
GET /api/auditAudit listRequires a Bearer ts_live_ prefix in the current handler; this is not verified ownership or tenant-scoped authorization.
POST /api/generate-keyKey managementCaller-supplied userId, optional email and action: rotate. Not a supported external authentication boundary.
GET/POST /api/teamsTeam managementcreate, invite, remove and get actions; identity/role authorization needs review before production use.
GET/POST /api/webhooksWebhook configurationStores configuration or sends test events. Stored subscriptions do not establish guaranteed delivery; the proxy uses its request-level webhookUrl.
GET/POST /api/analyticsSDK countersReceives requests, cacheHits and tokensSaved counts. Counters are not provider invoices or independently verified usage.
GET /api/batch, /api/trim-context, /api/smart-contextDiscoveryRead-only endpoint usage descriptions. They do not execute optimization.

Review security and data handling before connecting production systems. Inspect route implementations ↗