API Documentation

Complete reference for the TokenEase API. Drop-in compatible with OpenAI's API format.

1. Authentication

All API requests require an Authorization header with your API key.

Authorization: Bearer YOUR_API_KEY

Get your API key from the registration page. Free trial users receive $1 credit (1,000,000 tokens) valid for 14 days upon registration.

Security Tip: Never expose your API key in client-side code or public repositories. Use environment variables or secret managers.

2. Available Models

kimi-k3

$3.50 / $18.00
Moonshot Kimi K3. Top MMLU-Pro performer. Input / Output per 1M tokens.

deepseek

$0.13
DeepSeek V4 Flash. Excellent cost-performance. Per 1M tokens.

qwen-plus

$0.30
Alibaba Qwen Plus. Strong multilingual capabilities. Per 1M tokens.

glm-5.1

$0.80
Zhipu GLM-5.1. Advanced reasoning. Per 1M tokens.

doubao

$0.10
ByteDance Doubao Pro 32k. Best value for Chinese. Per 1M tokens.

tencent-hy

$0.15
Tencent Hunyuan. Enterprise-grade reliability. Per 1M tokens.

3. Chat Completions

POST /v1/chat/completions

Create a chat completion. Compatible with OpenAI's format.

Request Body

ParameterTypeRequiredDescription
modelstringYesModel ID (e.g., "deepseek", "kimi-k3")
messagesarrayYesArray of message objects with role and content
temperaturefloatNo0-2, default 0.7
max_tokensintegerNoMaximum tokens to generate
streambooleanNoEnable SSE streaming
top_pfloatNoNucleus sampling, 0-1
presence_penaltyfloatNo-2.0 to 2.0, default 0
frequency_penaltyfloatNo-2.0 to 2.0, default 0

cURL Example

curl -X POST https://tokenease.io/v1/chat/completions \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "deepseek", "messages": [{"role": "user", "content": "Hello, world!"}], "temperature": 0.7, "max_tokens": 512 }'

Response

{ "id": "chatcmpl-xxx", "object": "chat.completion", "created": 1699999999, "model": "deepseek", "choices": [{ "index": 0, "message": {"role": "assistant", "content": "Hello! How can I help you today?"}, "finish_reason": "stop" }], "usage": {"prompt_tokens": 12, "completion_tokens": 9, "total_tokens": 21} }

4. Error Codes

HTTP StatusError CodeDescriptionResolution
400invalid_requestMalformed request or missing required fieldsCheck request body format
401unauthorizedInvalid or missing API keyVerify Authorization header
402payment_requiredInsufficient balance or expired subscriptionAdd balance or renew subscription
403forbiddenAPI key revoked or account suspendedContact support
404model_not_foundRequested model does not existUse a valid model ID
429rate_limit_exceededToo many requestsReduce request rate, upgrade plan
500internal_errorServer errorRetry with exponential backoff
502provider_errorUpstream AI provider errorRetry or switch model
503service_unavailableService temporarily unavailableRetry after a few seconds

Error Response Format

{ "error": { "code": "rate_limit_exceeded", "message": "Rate limit exceeded. Retry after 60 seconds.", "type": "rate_limit_error" } }

5. Rate Limits

PlanRequests/minTokens/minDaily Cap
Free Trial1050,000500,000
Starter60300,0005,000,000
Pro3001,500,00025,000,000
EnterpriseUnlimitedUnlimitedCustom
Rate limits are applied per API key. Exceeding limits returns HTTP 429 with a Retry-After header.

6. Python SDK

Use the official OpenAI Python client with TokenEase's base URL.

pip install openai
from openai import OpenAI client = OpenAI( api_key="YOUR_TOKENEASE_API_KEY", base_url="https://tokenease.io/v1" ) response = client.chat.completions.create( model="deepseek", messages=[{"role": "user", "content": "Hello!"}], temperature=0.7, max_tokens=512 ) print(response.choices[0].message.content)

Async Usage

from openai import AsyncOpenAI client = AsyncOpenAI( api_key="YOUR_TOKENEASE_API_KEY", base_url="https://tokenease.io/v1" ) async def chat(): response = await client.chat.completions.create( model="kimi-k3", messages=[{"role": "user", "content": "Explain quantum computing"}] ) return response.choices[0].message.content

Streaming in Python

response = client.chat.completions.create( model="deepseek", messages=[{"role": "user", "content": "Write a poem"}], stream=True ) for chunk in response: if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end="")

Error Handling in Python

from openai import OpenAI, APIError, RateLimitError client = OpenAI(api_key="YOUR_KEY", base_url="https://tokenease.io/v1") try: response = client.chat.completions.create( model="deepseek", messages=[{"role": "user", "content": "Hello!"}] ) except RateLimitError as e: print(f"Rate limited. Retry after: {e.headers.get('retry-after', 'unknown')}") except APIError as e: print(f"API error: {e.code} - {e.message}")

7. Node.js SDK

Use the official OpenAI Node.js client with TokenEase's base URL.

npm install openai
import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'YOUR_TOKENEASE_API_KEY', baseURL: 'https://tokenease.io/v1' }); const response = await client.chat.completions.create({ model: 'deepseek', messages: [{ role: 'user', content: 'Hello!' }], temperature: 0.7, max_tokens: 512 }); console.log(response.choices[0].message.content);

Streaming in Node.js

const stream = await client.chat.completions.create({ model: 'deepseek', messages: [{ role: 'user', content: 'Tell me a story' }], stream: true }); for await (const chunk of stream) { process.stdout.write(chunk.choices[0]?.delta?.content || ''); }

Error Handling in Node.js

try { const response = await client.chat.completions.create({ model: 'deepseek', messages: [{ role: 'user', content: 'Hello!' }] }); } catch (error) { if (error.status === 429) { console.log('Rate limited. Please slow down.'); } else if (error.status === 402) { console.log('Insufficient balance. Please recharge.'); } else { console.error('Error:', error.message); } }

8. LangChain Integration

TokenEase works seamlessly with LangChain using the ChatOpenAI wrapper.

pip install langchain-openai
from langchain_openai import ChatOpenAI llm = ChatOpenAI( model="deepseek", openai_api_key="YOUR_TOKENEASE_API_KEY", openai_api_base="https://tokenease.io/v1", temperature=0.7 ) result = llm.invoke("What is the capital of France?") print(result.content)

LangChain with Streaming

from langchain_openai import ChatOpenAI llm = ChatOpenAI( model="kimi-k3", openai_api_key="YOUR_TOKENEASE_API_KEY", openai_api_base="https://tokenease.io/v1", streaming=True ) for chunk in llm.stream("Explain neural networks"): print(chunk.content, end="")

LangChain Chains

from langchain import LLMChain, PromptTemplate from langchain_openai import ChatOpenAI llm = ChatOpenAI( model="deepseek", openai_api_key="YOUR_TOKENEASE_API_KEY", openai_api_base="https://tokenease.io/v1" ) template = """You are a helpful assistant. Answer the following question concisely. Question: {question} Answer:""" prompt = PromptTemplate(template=template, input_variables=["question"]) chain = LLMChain(llm=llm, prompt=prompt) result = chain.run("What is machine learning?") print(result)

9. LlamaIndex Integration

Use TokenEase as the LLM backend for LlamaIndex RAG applications.

pip install llama-index llama-index-llms-openai
from llama_index.llms.openai import OpenAI from llama_index.core import Settings llm = OpenAI( model="deepseek", api_key="YOUR_TOKENEASE_API_KEY", api_base="https://tokenease.io/v1", temperature=0.1 ) Settings.llm = llm from llama_index.core import VectorStoreIndex, SimpleDirectoryReader documents = SimpleDirectoryReader("data").load_data() index = VectorStoreIndex.from_documents(documents) query_engine = index.as_query_engine() response = query_engine.query("Summarize the main points") print(response)

10. Cursor Integration

Use TokenEase in Cursor IDE for AI-powered coding.

Go to Cursor Settings > Models > OpenAI API Key and configure:

Cursor will automatically use your TokenEase account for all AI features including chat, code completion, and inline edits.

11. Streaming (Server-Sent Events)

Enable streaming by setting stream: true in your request. The API returns Server-Sent Events (SSE) with partial content.

curl -X POST https://tokenease.io/v1/chat/completions \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "deepseek", "messages": [{"role": "user", "content": "Count to 10"}], "stream": true }'

Each SSE line contains a JSON chunk:

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"delta":{"content":"1"}}]} data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"delta":{"content":", 2"}}]} data: [DONE]

12. Webhooks

TokenEase supports webhook notifications for payment events. Configure your webhook endpoint in your account dashboard.

Payment Success Webhook

POST Your configured webhook URL
{ "event_type": "payment.success", "order_id": "ord_xxx", "plan": "pro", "amount": 29.90, "currency": "USD", "customer_email": "user@example.com", "timestamp": "2026-08-07T04:20:00Z" }

Payment Failure Webhook

POST Your configured webhook URL
{ "event_type": "payment.failed", "order_id": "ord_xxx", "reason": "card_declined", "timestamp": "2026-08-07T04:20:00Z" }

Verifying Webhook Signatures

Webhooks include a signature header for verification:

X-TokenEase-Signature: sha256=...
import hmac import hashlib def verify_webhook(payload, signature, secret): expected = hmac.new( secret.encode(), payload.encode(), hashlib.sha256 ).hexdigest() return hmac.compare_digest(f"sha256={expected}", signature)

13. Usage Statistics

GET /api/stats/segmented

Retrieve detailed usage statistics for your account. Requires API key authentication.

curl -H "Authorization: Bearer YOUR_API_KEY" \ https://tokenease.io/api/stats/segmented

Response Fields

FieldTypeDescription
total_usersintegerTotal registered users
verified_usersintegerUsers with verified email
active_users_7dintegerActive users in last 7 days
active_users_30dintegerActive users in last 30 days
paid_usersintegerNumber of paid subscribers
today_tokensintegerTokens consumed today
today_costfloatEstimated cost today (USD)

14. Best Practices

Retry Strategy

Implement exponential backoff for transient errors (5xx, 429):

import time import random def exponential_backoff(attempt): return min(2 ** attempt + random.random(), 60) for attempt in range(5): try: response = client.chat.completions.create(...) break except Exception as e: if attempt < 4: time.sleep(exponential_backoff(attempt)) else: raise

Token Optimization

Security Checklist

Additional Endpoints

GET /health

Check service and provider health status.

curl https://tokenease.io/health
GET /plans

Retrieve available subscription plans and pricing.

curl https://tokenease.io/plans
For questions or support, contact us at support@tokenease.io or join our Telegram channel @tokenease.

15. Model Capability Comparison

ModelContextStrengthsBest ForLatency
Kimi K3256KReasoning, coding, MMLU-Pro #1Complex analysis, researchMedium
DeepSeek V464KCost efficiency, speedHigh-volume applicationsFast
Qwen Plus128KMultilingual, long contextGlobal apps, translationFast
GLM-5.1128KReasoning, mathSTEM tasksMedium
Doubao Pro32KChinese NLP, valueChinese contentFast
Tencent Hunyuan32KEnterprise reliabilityProduction systemsFast

16. Function Calling

TokenEase supports OpenAI-compatible function calling across all models.

curl -X POST https://tokenease.io/v1/chat/completions \ -H "Authorization: Bearer YOUR_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "deepseek", "messages": [{"role": "user", "content": "What is the weather in Beijing?"}], "tools": [{ "type": "function", "function": { "name": "get_weather", "description": "Get current weather", "parameters": { "type": "object", "properties": { "location": {"type": "string"} }, "required": ["location"] } } }] }'

17. Multi-turn Conversations

Maintain conversation context by including previous messages:

response = client.chat.completions.create( model="deepseek", messages=[ {"role": "system", "content": "You are a helpful coding assistant."}, {"role": "user", "content": "Write a Python function to sort a list."}, {"role": "assistant", "content": "Here is a function using bubble sort..."}, {"role": "user", "content": "Can you optimize it to O(n log n)?"} ] )

18. Batch Requests

For high-throughput scenarios, send multiple independent requests:

import asyncio from openai import AsyncOpenAI client = AsyncOpenAI(api_key="YOUR_KEY", base_url="https://tokenease.io/v1") async def batch_chat(prompts): tasks = [ client.chat.completions.create( model="deepseek", messages=[{"role": "user", "content": p}] ) for p in prompts ] return await asyncio.gather(*tasks) prompts = ["Explain AI", "Explain ML", "Explain DL"] results = asyncio.run(batch_chat(prompts)) for r in results: print(r.choices[0].message.content)

19. Migrating from OpenAI

Switching from OpenAI to TokenEase requires only two changes:

  1. Change base_url to https://tokenease.io/v1
  2. Replace your OpenAI API key with your TokenEase API key

All other code remains identical. Model names change (e.g., gpt-4 becomes deepseek or kimi-k3).

20. Migrating from OpenRouter

TokenEase is up to 40% cheaper than OpenRouter for the same models.

ModelOpenRouterTokenEaseSavings
DeepSeek V4/bin/bash.27/M/bin/bash.13/M52%
Qwen Plus/bin/bash.50/M/bin/bash.30/M40%
GLM-5.1.20/M/bin/bash.80/M33%

See the full comparison for details.

21. API Versioning

TokenEase API follows semantic versioning. The current version is v1. We guarantee backward compatibility within major versions. Breaking changes will be announced 90 days in advance via email and our status page.

22. Supported Languages

Our API accepts and generates content in all major languages. Model-specific strengths:

23. Testing and Sandbox

Use your free trial credits ( / 1M tokens) to test the API without any commitment. Trial credits expire after 14 days. No credit card required.

# Test with a small request response = client.chat.completions.create( model="deepseek", messages=[{"role": "user", "content": "Say hello"}], max_tokens=10 ) print(response.choices[0].message.content)

24. Compliance and Certifications

TokenEase maintains the following standards:

25. Changelog

DateVersionChanges
2026-08-07v1.5Added status page, expanded API docs, new about page
2026-08-05v1.4Added Tencent Hunyuan support
2026-07-25v1.3Added Kimi K3 support, overage billing
2026-07-19v1.2Added free trial system
2026-06-20v1.1Added AI Agent Hub
2026-05-20v1.0Initial release with 4 models
Tip: Bookmark this page. We update documentation frequently as new features and models are added.

26. Community and Support

Join our growing developer community:

27. Frequently Asked Questions

How do I get started?

Register at tokenease.io/register, get your free credit, and make your first API call using the examples above.

Can I use TokenEase with existing OpenAI code?

Yes. TokenEase is fully compatible with OpenAI's API format. Just change the base_url and API key.

What happens when I exceed my quota?

Overage charges apply at your plan's per-million rate. You can also upgrade your plan anytime.

Do you offer refunds?

See our Refund Policy for details. Generally, unused trial credits and billing errors qualify for refunds.

Is my data private?

We do not store the content of your API requests. Logs are kept for 90 days for billing and debugging, then deleted. See our Privacy Policy.

28. Glossary

TermDefinition
TokenA unit of text processing. ~1 English word = 1.3 tokens.
PromptThe input text sent to the AI model.
CompletionThe output text generated by the AI model.
Context WindowThe maximum amount of text a model can process in one request.
TemperatureControls randomness. 0 = deterministic, 2 = very creative.
OverageUsage beyond your plan's included quota.
SSEServer-Sent Events. A protocol for streaming real-time data.

29. Roadmap

Upcoming features on our development roadmap:

30. Legal Notices

TokenEase is an independent API gateway and is not affiliated with OpenAI, DeepSeek, Moonshot AI, Zhipu AI, Alibaba Cloud, ByteDance, or Tencent Cloud. All trademarks belong to their respective owners.

By using the TokenEase API, you agree to our Terms of Service and Privacy Policy.