Documentação da API

Acesso unificado aos melhores modelos de AI. API compatível com OpenAI — uma chave para todos os modelos.

URL Base da API

https://tokenhub.store/api/v1

Todas as requisições da API usam esta URL base. Totalmente compatível com SDKs OpenAI.

Início Rápido

Comece em Minutos

  1. Crie uma conta e faça login no seu Dashboard
  2. Acesse API Keys e crie uma nova API key
  3. Visite Cobrança para adicionar Credits à sua conta
  4. Comece a fazer chamadas de API com qualquer model suportado

Models Suportados

Clique em um provider para ver os models disponíveis e exemplos de código.

OpenAI

10 modelos

Empresa líder em pesquisa de AI, criadora da série GPT. Conhecida por models de linguagem de última geração com capacidades excepcionais de raciocínio e programação.

Anthropic

8 modelos

Empresa de segurança em AI conhecida pelos models Claude. Excelente em conversas nuançadas, código e raciocínio complexo, com fortes recursos de segurança.

Google

9 modelos

A família Gemini do Google oferece capacidades multimodais de ponta com janelas de contexto líderes do setor de até 2M Tokens.

xAI

3 modelos

Empresa de AI de Elon Musk. Os models Grok são conhecidos por conhecimento em tempo real, respostas espirituosas e excelente assistência em programação.

Alibaba (Qwen)

3 modelos

A série Qwen da Alibaba oferece models multilíngues poderosos, com ótimo desempenho em tarefas em inglês e chinês.

Zhipu AI (GLM)

3 modelos

A série GLM da Zhipu AI. Models bilíngues avançados em chinês e inglês, com janela de contexto de até 200K.

MiniMax

2 modelos

A série M2 da MiniMax. Contexto ultralongo de 205K com fortes capacidades multilíngues.

Xiaomi (MiMo)

2 modelos

Models MiMo V2 da Xiaomi. Janelas de contexto grandes de até 1M Tokens.

Alibaba (Qwen3)

3 modelos

A série Qwen3 da Alibaba. Massive models MoE com especializações em visão-linguagem e código.

Moonshot AI (Kimi)

2 modelos

A série Kimi K2 da Moonshot AI. Raciocínio forte com janelas de contexto estendidas.

DeepSeek

6 modelos

Os models mais recentes da DeepSeek. Altamente econômicos, com fortes capacidades de raciocínio e código.

ByteDance (Seedance)

2 modelos

Models de geração de vídeo Seedance da ByteDance. Text-to-video com qualidade cinematográfica, image-to-video e edição de vídeo multimodal com suporte a áudio.

ByteDance (Seedream)

2 modelos

Models de geração de imagem Seedream da ByteDance. Text-to-image de alta qualidade com estilos fotorealistas e artísticos.

Kwaivgi (Kling)

2 modelos

Models de geração de vídeo Kling da Kwaivgi. Text-to-video e image-to-video de alta qualidade com modos std/pro. Durações de 3–15s. std: $0.168/s, pro: $0.224/s (sem áudio).

Gemini API

Gemini 3.5–3.8 Flash and Gemini 4 Argon use /chat/completions. For Argon, use model ID google/gemini-4-argon. GET /models lists published models. For an unlisted model configured by your account administrator, use the exact model ID they provide with the same endpoint.

curl "https://tokenhub.store/api/v1/chat/completions" \
  -H "Authorization: Bearer th-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "google/gemini-3.8-flash",
    "messages": [{"role": "user", "content": "Hello"}],
    "reasoning_effort": "low",
    "max_tokens": 1024,
    "stream": true
  }'

Supports streaming, system instructions, function calling, and base64 image data URLs. reasoning_effort accepts low, medium, or high; max_tokens includes thinking tokens.

For multi-turn tools, keep the complete assistant message, including tool_calls.extra_content or content_blocks, so thought signatures are preserved. Native Gemini endpoints are not exposed by TokenHub.

Gemini Flash and Argon output usage includes thinking tokens. Cached input is counted at the configured cache-read rate when available. See the model catalog for current prices; confirm rates for unlisted models with your account administrator.

Streaming e cobrança da Responses API

Em POST /v1/responses, response.completed indica que a resposta foi concluída. Fechar a conexão após esse evento não transforma uma solicitação bem-sucedida em cancelada.

As contagens de tokens do provedor, inclusive zero, têm prioridade sobre estimativas. Apenas valores ausentes são estimados. Cancelar antes da conclusão pode gerar cobrança pelos tokens já processados.

Endpoints da API

POST /chat/completions

Crie uma conclusão de chat com suporte a streaming

Cabeçalhos

headers
Authorization: Bearer th-your-api-key
Content-Type: application/json

Corpo da Solicitação

json
{
  "model": "openai/gpt-4.1",
  "messages": [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Hello!"}
  ],
  "temperature": 0.7,
  "max_tokens": 1000,
  "stream": false
}

POST /responses

Encaminhar uma solicitação nativa da OpenAI Responses com passthrough JSON e SSE

Cabeçalhos

headers
Authorization: Bearer th-your-api-key
Content-Type: application/json

Corpo da Solicitação

json
{
  "model": "openai/gpt-5.6-terra",
  "input": "Explain why the sky is blue in one sentence.",
  "reasoning": { "effort": "medium" },
  "max_output_tokens": 256,
  "stream": false
}

POST /videos/generations

Gere um vídeo a partir de um prompt de texto ou imagem (models Seedance & Wan 2.2)

Cabeçalhos

headers
Authorization: Bearer th-your-api-key
Content-Type: application/json

Corpo da Solicitação

json
{
  "model": "bytedance/doubao-seedance-2.0",
  "prompt": "A golden retriever running on a sunny beach",
  "duration": 5,
  "resolution": "720p",
  "aspect_ratio": "16:9"
}

Corpo da Solicitação (array de content — first_frame & last_frame)

json
{
  "model": "bytedance/doubao-seedance-2.0",
  "prompt": "Hand picks a fresh apple from the tree, the scene smoothly transitions to a hand holding an apple smoothie drink, cinematic lighting in an orchard",
  "content": [
    {
      "type": "image_url",
      "image_url": { "url": "https://ark-project.tos-cn-beijing.volces.com/doc_image/r2v_tea_pic1.jpg" },
      "role": "first_frame"
    },
    {
      "type": "image_url",
      "image_url": { "url": "https://ark-project.tos-cn-beijing.volces.com/doc_image/r2v_tea_pic2.jpg" },
      "role": "last_frame"
    }
  ],
  "duration": 5,
  "resolution": "720p"
}

Parâmetros

content (opcional): Array de assets de mídia. Cada item tem:

  • type: "image_url"
  • image_url.url: URL da imagem
  • role: <firstFrame/> (máx. 1), <lastFrame/> (máx. 1), <refImage/>, <refVideo/>, <refAudio/>

GET /videos/generations/{id}

Consultar o status de uma tarefa de geração de vídeo

Cabeçalhos

headers
Authorization: Bearer th-your-api-key

Resposta

json
{
  "id": "tsk-xxx",
  "object": "video.generation.task",
  "model": "bytedance/doubao-seedance-2.0",
  "status": "succeeded",  // "queued" | "running" | "succeeded" | "failed"
  "data": [
    {
      "video_url": "https://..."
    }
  ]
}

POST /images/generations

Gere imagens a partir de prompts de texto (modelos Seedream)

Cabeçalhos

headers
Authorization: Bearer th-your-api-key
Content-Type: application/json

Corpo da requisição

json
{
  "model": "bytedance/doubao-seedream-5.0",
  "prompt": "A serene mountain landscape at sunset",
  "n": 1,
  "size": "2048x2048"
}

GET /models

Liste todos os modelos disponíveis

Consulte os modelos e preços publicados. Essas páginas são atualizadas automaticamente.

Account management API

Generate an access token in Settings → Account information. Send Authorization: Bearer YOUR_ACCESS_TOKEN and TokenHub-User: YOUR_USER_ID. New-Api-User is also accepted; if both user headers are supplied, they must match. Open settings

Access tokens manage your account. Continue using th- API keys for model requests.

HTTPEndpointDescription
GET/api/balanceAccount credit balance (1 credit = 1 USD)
GET / POST/api/keysList keys or create a key
GET / PATCH / DELETE/api/keys/{id}Get a key, edit its name/status/budget, or delete it
GET/api/keys/{id}/discountsRead the effective discounts for your key
GET / PATCH/api/user/profileRead account details or update your name
GET/api/usageRequest details and usage totals, filterable by key, model, and time
GET/api/v1/billing/usageRequest details and usage totals, filterable by key, model, and time
GET/api/v1/billing/spendingAccount spending trends
GET/api/v1/billing/invoicesList invoices
GET / POST/api/v1/billing/budgetRead or configure account budgets
export TOKENHUB_ACCESS_TOKEN="YOUR_ACCESS_TOKEN"
export TOKENHUB_USER_ID="YOUR_USER_ID"

curl "https://tokenhub.store/api/balance" \
  -H "Authorization: Bearer $TOKENHUB_ACCESS_TOKEN" \
  -H "TokenHub-User: $TOKENHUB_USER_ID"

curl "https://tokenhub.store/api/keys" \
  -H "Authorization: Bearer $TOKENHUB_ACCESS_TOKEN" \
  -H "TokenHub-User: $TOKENHUB_USER_ID" \
  -H "Content-Type: application/json" \
  -d '{"name":"My application","spendLimit":10}'

curl --get "https://tokenhub.store/api/v1/billing/usage" \
  -H "Authorization: Bearer $TOKENHUB_ACCESS_TOKEN" \
  -H "TokenHub-User: $TOKENHUB_USER_ID" \
  --data-urlencode "apiKeyId=YOUR_API_KEY_ID" \
  --data-urlencode "model=alibaba/qwen-turbo" \
  --data-urlencode "startDate=2026-09-07T00:00:00Z" \
  --data-urlencode "endDate=2026-09-08T00:00:00Z" \
  --data-urlencode "page=1" \
  --data-urlencode "limit=20"

Usage filters: apiKeyId is the ID returned by /api/keys, not the th- secret. model matches the full model ID exactly. Send startDate and endDate together as ISO timestamps with a timezone (inclusive boundaries). page defaults to 1; limit defaults to 20, maximum 100. Summary covers all matching records. Omit apiKeyId to query the account. An unknown key or a key owned by another account returns 404. API keys retain their existing account-wide billing access. /api/usage also accepts start_date/end_date, one-sided ranges, limit (default 100, maximum 1000), and offset (default 0).

Create: name=My application, spendLimit=10; omit spendLimit for the shared wallet. PATCH accepts name, isActive, and action (set_limit, add_budget, clear_limit, reset_spent); set_limit/add_budget also need a non-negative value. set_limit resets spent; add_budget preserves spent for an existing cap. GET /api/keys/:id returns the full model key. Deleting a key removes its UsageLog association; use isActive:false to retain usage filtering by key.

Busque chaves API por nome ou prefixo e navegue por 20 chaves por página. Novas chaves aparecem na primeira página. Atualize a lista para ver chaves criadas em outra janela ou pela API. API Keys

One active access token per account. It remains valid until regenerated or revoked; the database stores only its hash. Token lifecycle endpoints GET/POST/DELETE /api/user/access-token require a browser login. Tokens cannot manage their own lifecycle or authorize admin, password, account-deletion, or model-generation endpoints. Invalid tokens or mismatched user IDs return 401. Existing browser-session authentication continues to work.

Exemplos de Código

cURL

bash
curl https://tokenhub.store/api/v1/chat/completions \
  -H "Authorization: Bearer th-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4.1",
    "messages": [{"role": "user", "content": "Hello!"}]
  }'

Python (OpenAI SDK)

python
from openai import OpenAI

client = OpenAI(
    api_key="th-your-api-key",
    base_url="https://tokenhub.store/api/v1"
)

# Use any supported model
response = client.chat.completions.create(
    model="openai/gpt-5.4",  # Or any other model
    messages=[{"role": "user", "content": "Hello!"}]
)

print(response.choices[0].message.content)

JavaScript / TypeScript

typescript
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'th-your-api-key',
  baseURL: 'https://tokenhub.store/api/v1',
});

// Use any supported model
const response = await client.chat.completions.create({
  model: 'anthropic/claude-sonnet-4-6',
  messages: [{ role: 'user', content: 'Hello!' }],
});

console.log(response.choices[0].message.content);

Exemplo de Streaming (Python)

python
from openai import OpenAI

client = OpenAI(
    api_key="th-your-api-key",
    base_url="https://tokenhub.store/api/v1"
)

stream = client.chat.completions.create(
    model="google/gemini-2.5-pro",
    messages=[{"role": "user", "content": "Write a short story."}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")

Precisa de ajuda?

Entre em contato: support@tokenhub.store