Skip to content
TokenSave.

DEVELOPER DOCUMENTATION

From first request to informed decision.

Connect your server, inspect the result, and evaluate TokenSave against your own cost and quality requirements.

01 · Make your first request

  1. Choose a provider: Anthropic, OpenAI, Google or Groq. Create a provider key with an appropriate usage limit.
  2. Store it in your server environment. For this example set OPENAI_API_KEY. Never prefix secrets with NEXT_PUBLIC_ or commit them to source control.
  3. Send the request below from Node.js 20+ on your server. A TokenSave account is not required by the current proxy; provider usage charges can apply.
JavaScript · Node.js 20+
// 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);

A successful OpenAI request returns choices plus tokensave_meta. Check the HTTP status before rendering the answer. The reference also includes Python and cURL examples.

Optional: sign in to explore the dashboard. A tsKey currently supplies a rate-limit identifier, not a verified subscription entitlement.

02 · Know the supported surface

CapabilityCurrent supportIntegration consequence
Text messagesSupporteduser, assistant and system string messages accepted by the proxy; each provider still has role restrictions.
Provider responsesNative JSONParse the response for your selected provider. Fallback may change its shape.
Streaming / SSENot supportedWait for a complete JSON response.
Tool calling, images, audio, structured-output optionsNot forwardedUse the direct provider for workflows requiring these capabilities.
Provider parametersLimitedmodel is supported. temperature, max_tokens and other extra fields are not forwarded; Anthropic output limit is fixed at 1024.
Context endpointsSeparate operationsCall trim-context or smart-context explicitly, review the returned messages, then send them to proxy.

03 · Understand the request path

  1. Validate and clean: messages and key are validated, control characters stripped. Proxy accepts up to 100 messages and 100,000 characters per message. Declared body sizes above 500,000 bytes are rejected.
  2. Rate limit: a Redis-backed 60-request window of 60 seconds uses tsKey or client IP. It currently does not vary by paid plan. Redis failure can disable enforcement.
  3. Look up cached content: eligible responses are stored for 30 minutes when Redis is available. Matching uses a hash of cleaned roles and content, not semantic similarity.
  4. Route and compress on a miss: complexity rules choose a model, or your model override is used. Except in max_quality, the final message may have whitespace and filler phrases removed.
  5. Call a provider: eligible rate/quota failures can attempt supplied fallback credentials. All providers can still fail; return errors to your application.
  6. Return metadata: inspect cache status, selected model and timing. Cost figures are estimates.

Compression can remove line breaks and meaningful formatting. Validate code, JSON, quoted text and formatting-sensitive tasks. max_quality skips compression on a cache miss.

04 · Choose your quality tradeoff

Provider identifierSimple pathCapable path
anthropicclaude-haiku-4-5-20251001claude-sonnet-4-6
openaigpt-4o-minigpt-4o
googlegemini-2.0-flash-litegemini-2.0-flash
groqllama-3.1-8b-instantllama-3.3-70b-versatile

These are model IDs configured in this repository, not a guarantee of current availability for your provider account. Confirm access with your provider before evaluating.

ModeRoutingCompression
autoRule-based simple/complex classificationEnabled for the final message when applicable.
max_savingsCurrently identical to autoCurrently identical to auto.
max_qualityCapable path unless model overrides itSkipped. Cache is still checked first.

Fallback tries configured credentials in Groq → Anthropic → OpenAI → Google order, excluding the primary. It uses complexity-based model selection and may not preserve the primary model override or max_quality intent. Parse according to the returned provider.

05 · Handle failures deliberately

StatusMeaningClient action
400Proxy input validation failedCorrect the body; do not retry unchanged.
413Declared request body exceeds 500,000 bytesReduce the request size.
429TokenSave limit or upstream rate/quota failureFor proxy limits honor Retry-After (60 seconds). Use bounded backoff with jitter; stop when your retry budget is exhausted.
Provider 4xx / 5xxUpstream error forwarded after eligible fallback attemptsInspect status; fix credentials or model access for auth/configuration failures.
500Parsing, transport or unexpected proxy failureRecord safe diagnostics; consider a bounded retry or a direct-provider recovery path.

Set a client timeout. A timeout does not prove the provider stopped processing; retrying can incur another charge. The current API does not provide idempotency keys. Do not log credentials, raw prompts or sensitive provider errors.

Success and proxy-rate-limit responses include X-RateLimit-Limit and X-RateLimit-Remaining. They are not guaranteed on every error path. There is no stable universal error envelope; error can be a string or provider object.

06 · Prove the benefit on your workload

  1. Collect representative synthetic tasks and define an acceptable answer for each.
  2. Run a direct-provider baseline with your real production model and record provider-reported usage, latency and task success.
  3. Run an optimized evaluation, separating first requests from repeated/cache-hit requests. Account for the cache-matching limitation above.
  4. Compare answer quality, provider invoices and latency distributions. Include retries, fallback calls and integration effort.
  5. Calculate net benefit: actual provider savings − TokenSave subscription − other operating costs. Explore a pricing scenario.

Token estimates use character counts; output estimates use a truncated serialized provider payload. Cache-hit logs include fixed savings placeholders. Neither dashboard totals nor savings_percent are measured billing evidence. No public reproducible savings benchmark is published yet.

07 · Prepare for a production evaluation

Confirm authentication and tenant isolation, credential/log redaction, cache behavior, retention and deletion, provider availability, monitoring and recovery. Agree support and commercial terms before purchasing. No standard SLA or compliance certification is established by these docs.