Compatible con OpenAI
Usa rutas compatibles con OpenAI para las API de texto, imagen, audio, embeddings, tiempo real, rerank, moderación y responses cuando estén configuradas.
POST /v1/chat/completions
Sustituye <MODEL_ID> por el ID de un modelo disponible para tu clave de API y compatible con el endpoint.
Para GPT-5.6 Luna (gpt-5.6-luna) y GPT-6 Luna (gpt-6-luna), usa reasoning_effort para ajustar el nivel de razonamiento. Omite 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 el razonamiento adaptativo de Claude Fable 5, establece reasoning_effort en low, medium o high. El valor explícito none usa low. Si omites el campo, se aplica el valor predeterminado del modelo. Un valor positivo de reasoning.max_tokens tiene prioridad y se convierte en un nivel de razonamiento. Chat ignora temperature, top_p y top_k en este modelo. Usa una clave de API con acceso al 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
Finalizaciones utiliza la misma ruta de retransmisión de texto token168 con campos orientados a mensajes.
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
En el sitio de China continental, los modelos Kimi no admiten POST /v1/responses. Usa POST /v1/chat/completions para Kimi.
Responses admite el sobre de respuesta compatible con OpenAI para matrices de entrada, herramientas, razonamiento, almacenamiento en caché y opciones de transmisión.
Para Claude Fable 5, configura reasoning.effort en high para un razonamiento más profundo. El valor explícito none usa el nivel mínimo low.
Al continuar una llamada a una herramienta de Claude Fable 5, incluye su ID original y el resultado. Puedes enviar el resumen de razonamiento de Responses como historial de visualización.
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
Selecciona un modelo compatible con Compact. Pasa el array output completo y sin cambios como input de tu próxima solicitud 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."}]
}'
Generación y edición con Image 2.5
Usa gpt-image-2.5-flare o gpt-image-2.5-sunburst. Las imágenes se devuelven en data[].b64_json; decodifícalas para guardar un PNG. No envíes 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, envía images en JSON con referencias image_url. Sustituye la URL de origen por una imagen accesible. Puedes elegir cualquiera de los dos modelos 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"
}'
Generación con referencias opcionales en Seedream 5.5
Si tu clave API tiene acceso a Seedream 5.5, envía JSON con POST /v1/images/generations. Omite image para generar solo con texto o envía una URL HTTPS, una URI de datos Base64 o una lista ordenada de hasta 10 imágenes de referencia.
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
}'
Elige 1K, 1.5K, 2K (predeterminado) o un ancho y alto explícitos. Elige url (predeterminado) o b64_json y PNG (predeterminado) o JPEG. La solicitud devuelve una imagen. Las imágenes de entrada y salida se cobran por separado, con niveles de salida según sus píxeles reales. Si el resultado requiere conciliación, guarda el ID y comprueba la solicitud original antes de volver a enviarla.
POST /v1/images/generations
Para generar una imagen nueva, envía model y prompt con application/json. Usa /v1/images/edits para editar imágenes de referencia. Con GPT Image, usa output_format y omite response_format. Decodifica data[].b64_json para leer la imagen.
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 con JSON, envía model, prompt e images con application/json. Cada elemento de images es un objeto con un image_url accesible. Para archivos locales, usa image[] con multipart/form-data. Con gpt-image-2, omite input_fidelity y response_format. Si no usas streaming, decodifica 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'
Configura stream=true para recibir eventos del servidor. Lee hasta image_edit.completed y decodifica su b64_json para obtener la imagen 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 en el enrutador de retransmisión, pero la fuente actual lo identifica como RelayModeEdits y valida un campo de instrucciones de edición de texto heredado. Permanece deshabilitado hasta la decisión del propietario o la verificación del parche de bifurcación.
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."
}'
Ruta de compatibilidad deshabilitada
/v1/edits no debe documentarse ni probarse como una ruta exitosa de edición de imágenes de varias partes. Utilice /v1/images/edits para editar imágenes.
POST /v1/embeddings
Embeddings acepta model, input, output dimensions, encoding y campos opcionales de muestreo y metadatos de usuario.
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/*
Las rutas de audio activas compatibles con OpenAI son voz, transcripción y traducción. El habla utiliza un cuerpo de solicitud JSON; la transcripción y la traducción suelen utilizar cargas de varias partes.
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"
| Ruta | Método | Estado |
|---|---|---|
| /v1/audio/transcriptions | POST | Activo |
| /v1/audio/translations | POST | Activo |
| /v1/audio/speech | POST | Activo |
POST /v1/rerank
Rerank acepta una consulta, documentos y 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
Moderaciones utiliza el sobre de relé compatible con OpenAI para una verificación de seguridad del contenido cuando se configura un modelo compatible.
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
Qwen Realtime en Singapur utiliza su protocolo de eventos nativo. Seleccione un modelo marcado qwen-realtime en el catálogo, sustituya MODEL en el ejemplo y autentíquese con su API Key de Token168. El ejemplo envía un turno de voz completo con un WAV PCM mono de 16 kHz y 16 bits (input.wav) y guarda el audio de respuesta a 24 kHz (answer.wav). Se han verificado los turnos completos y el contexto entre turnos; la cancelación y la interrupción automática aún no se han verificado.
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)