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
- Choose a provider: Anthropic, OpenAI, Google or Groq. Create a provider key with an appropriate usage limit.
- Store it in your server environment. For this example set
OPENAI_API_KEY. Never prefix secrets withNEXT_PUBLIC_or commit them to source control. - 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.
// 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
| Capability | Current support | Integration consequence |
|---|---|---|
| Text messages | Supported | user, assistant and system string messages accepted by the proxy; each provider still has role restrictions. |
| Provider responses | Native JSON | Parse the response for your selected provider. Fallback may change its shape. |
| Streaming / SSE | Not supported | Wait for a complete JSON response. |
| Tool calling, images, audio, structured-output options | Not forwarded | Use the direct provider for workflows requiring these capabilities. |
| Provider parameters | Limited | model is supported. temperature, max_tokens and other extra fields are not forwarded; Anthropic output limit is fixed at 1024. |
| Context endpoints | Separate operations | Call trim-context or smart-context explicitly, review the returned messages, then send them to proxy. |
03 · Understand the request path
- 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.
- 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.
- 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.
- 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.
- Call a provider: eligible rate/quota failures can attempt supplied fallback credentials. All providers can still fail; return errors to your application.
- 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 identifier | Simple path | Capable path |
|---|---|---|
| anthropic | claude-haiku-4-5-20251001 | claude-sonnet-4-6 |
| openai | gpt-4o-mini | gpt-4o |
| gemini-2.0-flash-lite | gemini-2.0-flash | |
| groq | llama-3.1-8b-instant | llama-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.
| Mode | Routing | Compression |
|---|---|---|
| auto | Rule-based simple/complex classification | Enabled for the final message when applicable. |
| max_savings | Currently identical to auto | Currently identical to auto. |
| max_quality | Capable path unless model overrides it | Skipped. 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
| Status | Meaning | Client action |
|---|---|---|
| 400 | Proxy input validation failed | Correct the body; do not retry unchanged. |
| 413 | Declared request body exceeds 500,000 bytes | Reduce the request size. |
| 429 | TokenSave limit or upstream rate/quota failure | For proxy limits honor Retry-After (60 seconds). Use bounded backoff with jitter; stop when your retry budget is exhausted. |
| Provider 4xx / 5xx | Upstream error forwarded after eligible fallback attempts | Inspect status; fix credentials or model access for auth/configuration failures. |
| 500 | Parsing, transport or unexpected proxy failure | Record 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
- Collect representative synthetic tasks and define an acceptable answer for each.
- Run a direct-provider baseline with your real production model and record provider-reported usage, latency and task success.
- Run an optimized evaluation, separating first requests from repeated/cache-hit requests. Account for the cache-matching limitation above.
- Compare answer quality, provider invoices and latency distributions. Include retries, fallback calls and integration effort.
- 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.