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);
6 matching endpoints. All endpoint details remain available below.
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.
Field
Type / requirement
Behavior
messages
array · required
1–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.
apiKey
string · required
Your selected provider credential, 10–500 characters. Sent in the JSON body; keep it in server environment variables.
provider
string · optional
anthropic (default), openai, google or groq.
tsKey
string · optional
Validated 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.
model
string · optional
Overrides automatic model selection. The provider validates availability. Other optimization steps still apply; this is not a cache bypass.
quality
string · optional
auto (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.
fallbackKeys
object · optional
Provider-name → credential mapping. Only supplied providers are attempted for eligible rate/quota failures, in groq → anthropic → openai → google order, excluding the primary.
tags
object · optional
Up to 20 non-empty string values, names up to 50 and values up to 200 characters. Invalid tags return 400. Avoid private information.
userId
string · optional
Caller-supplied analytics identifier. Does not authenticate a user or establish tenant isolation.
webhookUrl
string · optional
Outbound 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"
}
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.
Field
Type / requirement
Behavior
prompts
array · required
1–50 strings, or objects with content. Use non-empty strings.
apiKey
string · required
Provider credential.
provider
string · optional
anthropic by default; same provider identifiers as proxy.
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.
Field
Type / requirement
Behavior
messages
array · required
Use valid text messages, ending with the latest user message.
maxTokens
number · optional
Default 4000. Supply a positive integer; estimate uses ceil(characters / 4) per message.
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.
Field
Type / requirement
Behavior
messages
non-empty array · required
Text messages with role and content.
maxTokens
number · optional
Default 4000. Positive integer; triggers summarization when estimated input exceeds the target.
keepRecent
number · optional
Default 6. Use a positive integer for recent non-system messages to preserve.
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.
Estimated USD and comparison with a configured expensive model. Not actual savings versus your application baseline.
input_tokens / output_tokens
Provider calls
Character-based estimates, not authoritative provider billing usage.
original_provider / fallback_provider
Successful fallback
Fallback can change response schema and quality behavior.
tokens_saved
Cache hit
String 100% indicates a reused response, not measured account-wide savings.
tags / is_error / note
Depends on path
Optional 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.
Endpoint
Purpose
Current boundary
GET /api/stats
Dashboard metrics
Service-wide seven-day aggregates, recent logs and performance estimates; not isolated customer billing.
GET /api/audit
Audit list
Requires a Bearer ts_live_ prefix in the current handler; this is not verified ownership or tenant-scoped authorization.
POST /api/generate-key
Key management
Caller-supplied userId, optional email and action: rotate. Not a supported external authentication boundary.
GET/POST /api/teams
Team management
create, invite, remove and get actions; identity/role authorization needs review before production use.
GET/POST /api/webhooks
Webhook configuration
Stores configuration or sends test events. Stored subscriptions do not establish guaranteed delivery; the proxy uses its request-level webhookUrl.
GET/POST /api/analytics
SDK counters
Receives requests, cacheHits and tokensSaved counts. Counters are not provider invoices or independently verified usage.
GET /api/batch, /api/trim-context, /api/smart-context
Discovery
Read-only endpoint usage descriptions. They do not execute optimization.