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
| Parameter | Type | Required | Description |
| model | string | Yes | Model ID (e.g., "deepseek", "kimi-k3") |
| messages | array | Yes | Array of message objects with role and content |
| temperature | float | No | 0-2, default 0.7 |
| max_tokens | integer | No | Maximum tokens to generate |
| stream | boolean | No | Enable SSE streaming |
| top_p | float | No | Nucleus sampling, 0-1 |
| presence_penalty | float | No | -2.0 to 2.0, default 0 |
| frequency_penalty | float | No | -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 Status | Error Code | Description | Resolution |
| 400 | invalid_request | Malformed request or missing required fields | Check request body format |
| 401 | unauthorized | Invalid or missing API key | Verify Authorization header |
| 402 | payment_required | Insufficient balance or expired subscription | Add balance or renew subscription |
| 403 | forbidden | API key revoked or account suspended | Contact support |
| 404 | model_not_found | Requested model does not exist | Use a valid model ID |
| 429 | rate_limit_exceeded | Too many requests | Reduce request rate, upgrade plan |
| 500 | internal_error | Server error | Retry with exponential backoff |
| 502 | provider_error | Upstream AI provider error | Retry or switch model |
| 503 | service_unavailable | Service temporarily unavailable | Retry 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
| Plan | Requests/min | Tokens/min | Daily Cap |
| Free Trial | 10 | 50,000 | 500,000 |
| Starter | 60 | 300,000 | 5,000,000 |
| Pro | 300 | 1,500,000 | 25,000,000 |
| Enterprise | Unlimited | Unlimited | Custom |
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:
- API Key: Your TokenEase API key
- Base URL:
https://tokenease.io/v1
- Model: Select from available models (deepseek, kimi-k3, etc.)
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
| Field | Type | Description |
| total_users | integer | Total registered users |
| verified_users | integer | Users with verified email |
| active_users_7d | integer | Active users in last 7 days |
| active_users_30d | integer | Active users in last 30 days |
| paid_users | integer | Number of paid subscribers |
| today_tokens | integer | Tokens consumed today |
| today_cost | float | Estimated 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
- Use system prompts to set context and reduce repetitive instructions.
- Choose the right model for your task — DeepSeek for cost-sensitive, Kimi K3 for reasoning.
- Set
max_tokens to prevent unexpectedly long responses.
- Use streaming for real-time UIs to improve perceived performance.
Security Checklist
- Store API keys in environment variables, never in source code.
- Rotate API keys periodically.
- Monitor usage for anomalies.
- Use IP whitelisting if your use case allows.
- Implement request signing for webhook endpoints.
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.