Compatível com OpenAI
Use rotas compatíveis com OpenAI para APIs de texto, imagem, áudio, embeddings, tempo real, rerank, moderação e responses quando configuradas.
POST /v1/chat/completions
Substitua <MODEL_ID> pelo ID de um modelo disponível para sua chave de API e compatível com o endpoint.
Para o GPT-5.6 Luna (gpt-5.6-luna) e o GPT-6 Luna (gpt-6-luna), use reasoning_effort para definir o nível de raciocínio. Omita thinking.
curl https://www.token168.cc/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN168_API_KEY" \
-d '{
"model": "<MODEL_ID>",
"messages": [{"role": "user", "content": "Summarize the release notes."}]
}'
Claude Fable 5
Para o raciocínio adaptativo do Claude Fable 5, defina reasoning_effort como low, medium ou high. O valor explícito none usa low. Se o campo for omitido, vale o padrão do modelo. Um reasoning.max_tokens positivo tem prioridade e é convertido em nível de raciocínio. O Chat ignora temperature, top_p e top_k nesse modelo. Use uma chave de API com acesso ao modelo.
curl https://www.token168.cc/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN168_API_KEY" \
-d '{
"model": "claude-fable-5",
"messages": [{"role": "user", "content": "Summarize the release notes."}],
"reasoning_effort": "high",
"max_tokens": 5000
}'
POST /v1/completions
As conclusões usam o mesmo caminho de retransmissão de texto token168 com campos orientados a prompt.
curl https://www.token168.cc/v1/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN168_API_KEY" \
-d '{
"model": "<MODEL_ID>",
"prompt": "Write a one-line changelog entry.",
"prefix": "",
"suffix": "",
"stream": false,
"stream_options": {"include_usage": true},
"max_tokens": 256,
"temperature": 0.3,
"top_p": 0.9,
"top_k": 40,
"stop": ["\n\n"],
"n": 1,
"frequency_penalty": 0,
"presence_penalty": 0,
"seed": 123,
"logprobs": false,
"top_logprobs": 0,
"user": "user_123",
"metadata": {"trace_id": "trace_123"},
"service_tier": "default",
"store": false
}'
POST /v1/responses
No site da China continental, os modelos Kimi não são compatíveis com POST /v1/responses. Use POST /v1/chat/completions para Kimi.
As respostas suportam o envelope de resposta compatível com OpenAI para matrizes de entrada, ferramentas, raciocínio, cache e opções de streaming.
No Claude Fable 5, defina reasoning.effort como high para aprofundar o raciocínio. O valor explícito none usa o nível mínimo low.
Ao continuar uma chamada de ferramenta do Claude Fable 5, inclua o ID original da chamada e o resultado. O resumo de raciocínio retornado por Responses pode ser enviado como histórico de exibição.
curl https://www.token168.cc/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN168_API_KEY" \
-d '{
"model": "<MODEL_ID>",
"input": [{"role": "user", "content": [{"type": "input_text", "text": "Draft a launch checklist."}]}],
"include": ["usage"],
"conversation": {"id": "conv_123"},
"context_management": {"type": "auto"},
"instructions": "Return concise bullets.",
"max_output_tokens": 800,
"top_logprobs": 0,
"metadata": {"trace_id": "trace_123"},
"parallel_tool_calls": true,
"previous_response_id": "resp_previous",
"reasoning": {"effort": "medium"},
"service_tier": "default",
"store": false,
"prompt_cache_key": "launch-checklist",
"prompt_cache_retention": "24h",
"safety_identifier": "safe_user_123",
"stream": false,
"stream_options": {"include_usage": true},
"temperature": 0.4,
"text": {"format": {"type": "text"}},
"tool_choice": "auto",
"tools": [],
"top_p": 0.9,
"truncation": "auto",
"user": "user_123",
"max_tool_calls": 4,
"prompt": {"id": "prompt_123"},
"enable_thinking": true,
"preset": "default"
}'
POST /v1/responses/compact
Escolha um modelo compatível com Compact. Passe o array output completo e sem alterações como input da próxima solicitação a /v1/responses.
curl https://www.token168.cc/v1/responses/compact \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN168_API_KEY" \
-d '{
"model": "<MODEL_ID>",
"input": [{"role": "user", "content": "Compact this conversation."}]
}'
Geração e edição com Image 2.5
Use gpt-image-2.5-flare ou gpt-image-2.5-sunburst. As imagens retornam em data[].b64_json; decodifique-as para salvar um PNG. Não envie response_format.
curl https://www.token168.cc/v1/images/generations \
-H "Authorization: Bearer $TOKEN168_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-image-2.5-flare",
"prompt": "A blue circle on a white background",
"n": 1,
"size": "1024x1024",
"quality": "low",
"output_format": "png"
}'
Para editar, envie images em JSON com referências image_url. Substitua a URL de origem por uma imagem acessível. É possível usar qualquer variante Image 2.5.
curl https://www.token168.cc/v1/images/edits \
-H "Authorization: Bearer $TOKEN168_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-image-2.5-sunburst",
"prompt": "Change the blue circle to red",
"images": [
{
"image_url": "https://your-cdn.example/source.png"
}
],
"n": 1,
"size": "1024x1024",
"quality": "low",
"output_format": "png"
}'
Geração com referências opcionais no Seedream 5.5
Quando sua chave de API tiver acesso ao Seedream 5.5, envie JSON para POST /v1/images/generations. Omita image para usar só texto ou envie uma URL HTTPS, um URI de dados Base64 ou uma lista ordenada com até 10 imagens de referência.
curl https://www.token168.cc/v1/images/generations \
-H "Authorization: Bearer $TOKEN168_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "dola-seedream-5-5-261028",
"prompt": "A blue circle on a white background",
"size": "1024x1024",
"response_format": "b64_json",
"output_format": "png",
"watermark": false
}'
curl https://www.token168.cc/v1/images/generations \
-H "Authorization: Bearer $TOKEN168_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "dola-seedream-5-5-261028",
"prompt": "Keep the composition and turn the blue circle red",
"image": "https://your-cdn.example/source.png",
"size": "1024x1024",
"response_format": "b64_json",
"output_format": "png",
"watermark": false
}'
curl https://www.token168.cc/v1/images/generations \
-H "Authorization: Bearer $TOKEN168_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "dola-seedream-5-5-261028",
"prompt": "Keep the composition and turn the blue circle red",
"image": [
"https://your-cdn.example/source.png",
"https://your-cdn.example/reference.png"
],
"size": "1024x1024",
"response_format": "b64_json",
"output_format": "png",
"watermark": false
}'
Escolha 1K, 1.5K, 2K (padrão) ou largura e altura explícitas. Escolha url (padrão) ou b64_json e PNG (padrão) ou JPEG. A solicitação retorna uma imagem. As imagens de entrada e saída são cobradas separadamente, com a faixa da saída baseada na contagem real de pixels. Se o resultado exigir conciliação, guarde o ID e verifique a solicitação original antes de reenviar.
POST /v1/images/generations
Para gerar uma imagem, envie model e prompt em application/json. Use /v1/images/edits para editar imagens de referência. No GPT Image, use output_format e omita response_format. Decodifique data[].b64_json para ler a imagem.
curl https://www.token168.cc/v1/images/generations \
-H "Authorization: Bearer $TOKEN168_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-image-2",
"prompt": "A blue circle on a white background",
"n": 1,
"size": "1024x1024",
"quality": "low",
"output_format": "png"
}'
POST /v1/images/edits
Para editar em JSON, envie model, prompt e images em application/json. Cada item de images é um objeto com um image_url acessível. Para arquivos locais, use image[] com multipart/form-data. Com gpt-image-2, omita input_fidelity e response_format. Sem streaming, decodifique data[].b64_json.
curl https://www.token168.cc/v1/images/edits \
-H "Authorization: Bearer $TOKEN168_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-image-2",
"prompt": "Change the blue circle to red",
"images": [
{
"image_url": "https://your-cdn.example/source.png"
}
],
"n": 1,
"size": "1024x1024",
"quality": "low",
"output_format": "png"
}'
curl https://www.token168.cc/v1/images/edits \
-H "Authorization: Bearer $TOKEN168_API_KEY" \
-F 'model=gpt-image-2' \
-F 'prompt=Change the blue circle to red' \
-F 'n=1' \
-F 'size=1024x1024' \
-F 'quality=low' \
-F 'output_format=png' \
-F 'image[]=@source.png'
Defina stream=true para receber eventos do servidor. Leia até image_edit.completed e decodifique seu b64_json para obter a imagem final.
curl -N https://www.token168.cc/v1/images/edits \
-H "Authorization: Bearer $TOKEN168_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-image-2",
"prompt": "Change the blue circle to red",
"images": [
{
"image_url": "https://your-cdn.example/source.png"
}
],
"stream": true,
"n": 1,
"size": "1024x1024",
"quality": "low",
"output_format": "png"
}'
POST /v1/edits
/v1/edits está registrado no roteador de retransmissão, mas a fonte atual o identifica como RelayModeEdits e valida um campo de instrução de edição de texto herdado. Ele permanece desativado até a decisão do proprietário ou verificação do patch do fork.
curl https://www.token168.cc/v1/edits \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN168_API_KEY" \
-d '{
"model": "<MODEL_ID>",
"input": "The quik brown fox.",
"instruction": "Fix the spelling mistakes."
}'
Rota de compatibilidade desativada
/v1/edits não deve ser documentado ou testado como um caminho de sucesso para edições de imagens multipartes. Use /v1/images/edits para edições de imagens.
POST /v1/embeddings
Os embeddings aceitam dimensões de modelo, entrada, saída, codificação e campos opcionais de amostragem/metadados do usuário.
curl https://www.token168.cc/v1/embeddings \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN168_API_KEY" \
-d '{
"model": "<MODEL_ID>",
"input": ["Token168 routes native APIs."],
"encoding_format": "float",
"dimensions": 1536,
"user": "user_123",
"seed": 123,
"temperature": 0,
"top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0
}'
POST /v1/audio/*
As rotas de áudio ativas compatíveis com OpenAI são fala, transcrição e tradução. A fala usa um corpo de solicitação JSON; a transcrição e a tradução geralmente usam uploads multiparte.
curl https://www.token168.cc/v1/audio/speech \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN168_API_KEY" \
-d '{
"model": "<MODEL_ID>",
"input": "Token168 unifies native model APIs.",
"voice": "alloy",
"instructions": "Neutral narration.",
"response_format": "mp3",
"speed": 1,
"stream_format": "none",
"metadata": {"trace_id": "trace_123"},
"task_type": "tts",
"language": "en",
"ref_audio": "",
"ref_text": "",
"x_vector_only_mode": false,
"max_new_tokens": 1024,
"initial_codec_chunk_frames": 0
}'
curl https://www.token168.cc/v1/audio/transcriptions \
-H "Authorization: Bearer $TOKEN168_API_KEY" \
-F model="qwen3-asr-flash" \
-F file="@speech.wav" \
-F response_format="json" \
-F language="en"
curl https://www.token168.cc/v1/audio/translations \
-H "Authorization: Bearer $TOKEN168_API_KEY" \
-F model="<MODEL_ID>" \
-F file="@speech.wav" \
-F input="speech.wav" \
-F response_format="json" \
-F language="en" \
-F speed="1"
| Rota | Método | Estado |
|---|---|---|
| /v1/audio/transcriptions | POST | Ativo |
| /v1/audio/translations | POST | Ativo |
| /v1/audio/speech | POST | Ativo |
POST /v1/rerank
A reclassificação aceita consultas, documentos e controles de resultados.
curl https://www.token168.cc/v1/rerank \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN168_API_KEY" \
-d '{
"model": "<MODEL_ID>",
"query": "native model API docs",
"documents": ["OpenAI-compatible docs", "Billing docs", "Console docs"],
"top_n": 2,
"return_documents": true,
"max_chunk_per_doc": 4,
"overlap_tokens": 32
}'
POST /v1/moderations
Moderations usa o envelope de relé compatível com OpenAI para uma verificação de segurança de conteúdo quando um modelo compatível é configurado.
curl https://www.token168.cc/v1/moderations \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN168_API_KEY" \
-d '{
"model": "<MODEL_ID>",
"input": "User-provided content to check",
"user": "user_123",
"metadata": {"trace_id": "trace_123"}
}'
GET /v1/realtime
O Qwen Realtime em Singapura usa seu protocolo nativo de eventos. Selecione no catálogo um modelo marcado como qwen-realtime, substitua MODEL no exemplo e autentique-se com sua API Key do Token168. O exemplo envia um turno de voz completo a partir de um WAV PCM mono de 16 kHz e 16 bits (input.wav) e salva o áudio de resposta a 24 kHz (answer.wav). Turnos completos e contexto entre vários turnos foram verificados; cancelamento e interrupção automática ainda não foram verificados.
wss://service.token168.ai/v1/realtime?model=MODEL_ID
# python3 -m pip install websocket-client==1.9.2
# Set TOKEN168_API_KEY before running. Input: input.wav (16 kHz / 16-bit / mono).
import base64
import json
import os
import time
import wave
from urllib.parse import urlencode
import websocket
MODEL = "qwen3.8-omni-flash-realtime"
# Also verified: qwen3.5-omni-flash-realtime, qwen3.5-omni-plus-realtime.
# Other models with the same qwen-realtime protocol reuse this example.
with wave.open("input.wav", "rb") as source:
assert (source.getframerate(), source.getsampwidth(), source.getnchannels(), source.getcomptype()) == (16000, 2, 1, "NONE")
assert 0 < source.getnframes() <= 8 * 16000 # This example limits input to 8 seconds.
pcm = source.readframes(source.getnframes())
ws = websocket.create_connection(
"wss://service.token168.ai/v1/realtime?" + urlencode({"model": MODEL}),
header={"Authorization": "Bearer " + os.environ["TOKEN168_API_KEY"]},
timeout=10,
)
deadline = time.monotonic() + 45
def send(event):
ws.send(json.dumps(event))
def receive():
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError("Session deadline exceeded; check usage before retrying")
ws.settimeout(min(10, remaining))
event = json.loads(ws.recv())
if event.get("type") == "error" or (not event.get("type") and event.get("code")):
raise RuntimeError(event.get("error", event))
return event
def wait_for(event_type):
while True:
event = receive()
if event.get("type") == event_type:
return event
try:
wait_for("session.created")
send({"type": "session.update", "session": {
"modalities": ["text", "audio"], "input_audio_format": "pcm",
"output_audio_format": "pcm", "turn_detection": None, "max_tokens": 64,
"instructions": "Please answer briefly in Chinese, using at most four characters.",
}})
session = wait_for("session.updated")["session"]
assert session.get("turn_detection") is None and session.get("max_tokens") == 64
for offset in range(0, len(pcm), 16000):
send({"type": "input_audio_buffer.append", "audio": base64.b64encode(pcm[offset:offset + 16000]).decode()})
send({"type": "input_audio_buffer.commit"})
wait_for("input_audio_buffer.committed")
send({"type": "response.create"})
audio = bytearray()
while True:
event = receive()
if event.get("type") == "response.audio.delta":
audio.extend(base64.b64decode(event["delta"]))
elif event.get("type") == "response.audio_transcript.done":
print(event["transcript"])
elif event.get("type") == "response.done":
response = event["response"]
if response.get("status") != "completed" or not response.get("usage"):
raise RuntimeError("Turn not confirmed; check usage before retrying")
print(json.dumps(response["usage"]))
break
assert audio, "No audio returned"
with wave.open("answer.wav", "wb") as output:
output.setnchannels(1)
output.setsampwidth(2)
output.setframerate(24000)
output.writeframes(audio)
finally:
ws.close(timeout=1)