API OpenAI-compatible
Sử dụng các route OpenAI-compatible cho API văn bản, hình ảnh, âm thanh, embedding, Realtime, Rerank, Moderations và Responses khi đã được cấu hình.
POST /v1/chat/completions
Thay <MODEL_ID> bằng ID của mô hình mà khóa API của bạn có thể gọi và có hỗ trợ điểm cuối tương ứng.
Với GPT-5.6 Luna (gpt-5.6-luna) và GPT-6 Luna (gpt-6-luna), dùng reasoning_effort để đặt mức suy luận. Hãy bỏ qua 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
Để dùng chế độ suy luận thích ứng của Claude Fable 5, hãy đặt reasoning_effort thành low, medium hoặc high. Giá trị none được chỉ định rõ sẽ dùng low. Nếu bỏ qua trường, mô hình dùng giá trị mặc định. Giá trị reasoning.max_tokens dương được ưu tiên và quy đổi thành mức suy luận. Chat bỏ qua temperature, top_p và top_k cho mô hình này. Hãy dùng khóa API có quyền truy cập mô hình.
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
Completions dùng cùng đường dẫn relay văn bản token168 với các trường hướng theo 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
Trên trang dành cho Trung Quốc đại lục, các mô hình Kimi không hỗ trợ POST /v1/responses. Hãy dùng POST /v1/chat/completions cho Kimi.
Responses hỗ trợ envelope response OpenAI-compatible cho mảng đầu vào, tool, reasoning, caching và tùy chọn streaming.
Với Claude Fable 5, đặt reasoning.effort thành high để suy luận sâu hơn. Giá trị none được chỉ định rõ sẽ dùng mức thấp nhất là low.
Khi tiếp tục lượt gọi công cụ của Claude Fable 5, hãy gửi ID lượt gọi ban đầu và kết quả của công cụ. Bản tóm tắt suy luận do Responses trả về có thể được gửi như lịch sử hiển thị.
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
Chọn mô hình có hỗ trợ Compact. Truyền nguyên vẹn toàn bộ mảng output làm input cho yêu cầu /v1/responses tiếp theo.
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."}]
}'
Tạo và chỉnh sửa bằng Image 2.5
Dùng gpt-image-2.5-flare hoặc gpt-image-2.5-sunburst. Ảnh được trả về trong data[].b64_json; giải mã để lưu thành PNG. Không gửi 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"
}'
Khi chỉnh sửa, gửi images dạng JSON với tham chiếu image_url. Thay URL nguồn bên dưới bằng địa chỉ ảnh có thể truy cập. Có thể chọn một trong hai mẫu 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"
}'
Tạo ảnh với ảnh tham chiếu tùy chọn trong Seedream 5.5
Khi khóa API có quyền dùng Seedream 5.5, hãy gửi JSON bằng POST /v1/images/generations. Bỏ image nếu chỉ dùng văn bản hoặc gửi một URL HTTPS, một URI dữ liệu Base64 hoặc mảng có thứ tự tối đa 10 ảnh tham chiếu.
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
}'
Chọn 1K, 1.5K, 2K (mặc định) hoặc chiều rộng và chiều cao cụ thể. Chọn url (mặc định) hoặc b64_json và PNG (mặc định) hoặc JPEG. Mỗi yêu cầu trả về một ảnh. Ảnh đầu vào và đầu ra được tính phí riêng. Bậc phí đầu ra dựa trên số điểm ảnh thực tế. Nếu cần đối soát, hãy lưu ID và kiểm tra yêu cầu gốc trước khi gửi lại.
POST /v1/images/generations
Để tạo ảnh, gửi model và prompt bằng application/json. Dùng /v1/images/edits để sửa ảnh tham chiếu. Với GPT Image, dùng output_format và bỏ response_format. Giải mã data[].b64_json để đọc ảnh.
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
Để chỉnh sửa ảnh bằng JSON, gửi model, prompt và images bằng application/json. Mỗi phần tử images là một đối tượng có image_url truy cập được. Với tệp cục bộ, dùng image[] với multipart/form-data. Với gpt-image-2, bỏ input_fidelity và response_format. Khi không truyền luồng, giải mã 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'
Đặt stream=true để nhận sự kiện từ máy chủ. Đọc đến image_edit.completed rồi giải mã b64_json trong sự kiện để lấy ảnh cuối cùng.
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 đã đăng ký trong relay router, nhưng mã nguồn hiện tại xác định route này là RelayModeEdits và kiểm tra trường instruction của text-edits cũ. Route tiếp tục bị tắt cho đến khi có quyết định của owner hoặc xác minh bản vá 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."
}'
Route tương thích đang bị tắt
/v1/edits không được ghi tài liệu hoặc kiểm thử như đường dẫn chỉnh sửa ảnh multipart thành công. Hãy dùng /v1/images/edits để chỉnh sửa ảnh.
POST /v1/embeddings
Embeddings chấp nhận model, input, số chiều đầu ra, encoding và các trường metadata lấy mẫu/người dùng tùy chọn.
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/*
Các route âm thanh OpenAI-compatible đang hoạt động gồm speech, transcription và translation. Speech dùng body JSON; transcription và translation thường dùng tải lên multipart.
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"
| Đường dẫn | Phương thức | Trạng thái |
|---|---|---|
| /v1/audio/transcriptions | POST | Đang hoạt động |
| /v1/audio/translations | POST | Đang hoạt động |
| /v1/audio/speech | POST | Đang hoạt động |
POST /v1/rerank
Rerank chấp nhận truy vấn, tài liệu và các điều khiển kết quả.
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 dùng envelope relay OpenAI-compatible để kiểm tra an toàn nội dung khi có mô hình tương thích được cấu hình.
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 tại Singapore sử dụng giao thức sự kiện gốc. Chọn mô hình có nhãn qwen-realtime trong danh mục, thay MODEL trong ví dụ và xác thực bằng API Key Token168. Ví dụ gửi một lượt thoại hoàn chỉnh từ WAV PCM đơn kênh 16kHz, 16bit (input.wav) và lưu âm thanh trả lời 24kHz (answer.wav). Lượt thoại hoàn chỉnh và ngữ cảnh nhiều lượt đã được kiểm chứng; hủy phản hồi và ngắt lời tự động chưa được kiểm chứng.
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)