Transformers documentation
Serve CLI
Serve CLI
CLI transformers serve adalah opsi ringan untuk server lokal atau self-hosted. CLI ini menghindari overhead runtime dan operasional tambahan dari mesin inferensi khusus seperti vLLM. Gunakan untuk evaluasi, eksperimen, dan deployment dengan beban sedang. Fitur seperti continuous batching meningkatkan throughput dan menurunkan latensi.
Untuk deployment produksi berskala besar, gunakan vLLM atau SGLang dengan model Transformer sebagai backend. Pelajari lebih lanjut di panduan Backend inferensi.
Perintah transformers serve menjalankan server lokal yang kompatibel dengan OpenAI SDK. Server ini berfungsi dengan banyak aplikasi pihak ketiga dan mendukung API REST berikut.
/v1/chat/completionsuntuk permintaan teks, gambar, audio, dan video/v1/completionsuntuk pelengkapan teks lama dari prompt bebas/v1/responsesmendukung Responses API/v1/audio/transcriptionsuntuk transkripsi audio/v1/systemonemenjawab pertanyaan bertipe (pilihan, skor, ya/tidak) dengan probabilitas untuk setiap jawaban yang diizinkan/v1/modelsmenampilkan daftar model yang tersedia untuk integrasi pihak ketiga/load_modelmengalirkan progres pemuatan model melalui SSE
Instal dependensi serving.
pip install transformers[serving]
Jalankan transformers serve untuk meluncurkan server. Alamat server default adalah http://localhost:8000.
transformers serve
v1/chat/completions
API v1/chat/completions didasarkan pada Chat Completions API. API ini mendukung permintaan teks, gambar, audio, dan video untuk LLM, VLM, dan model multimodal. Gunakan dengan curl, InferenceClient, atau klien OpenAI.
Penyelesaian berbasis teks
from huggingface_hub import InferenceClient
messages = [{"role": "user", "content": "What is the Transformers library known for?"}]
client = InferenceClient("http://localhost:8000")
result = client.chat_completion(messages, model="Qwen/Qwen2.5-0.5B-Instruct", max_tokens=256)
print(result.choices[0].message.content)InferenceClient mengembalikan string yang dicetak.
The Transformers library is primarily known for its ability to create and manipulate large-scale language models [...]
from huggingface_hub import InferenceClient
messages = [{"role": "user", "content": "What is the Transformers library known for?"}]
client = InferenceClient("http://localhost:8000")
stream = client.chat_completion(messages, model="Qwen/Qwen2.5-0.5B-Instruct", max_tokens=256, stream=True)
for chunk in stream:
token = chunk.choices[0].delta.content
if token:
print(token, end="")InferenceClient mengembalikan string yang dicetak.
The Transformers library is primarily known for its ability to create and manipulate large-scale language models [...]
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<random_string>")
completion = client.chat.completions.create(
model="Qwen/Qwen2.5-0.5B-Instruct",
messages=[
{
"role": "user",
"content": "What is the Transformers library known for?"
}
],
)
print(completion.choices[0].message.content)Klien OpenAI mengembalikan string yang dicetak.
The Transformers library is primarily known for its ability to create and manipulate large-scale language models [...]
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<random_string>")
completion = client.chat.completions.create(
model="Qwen/Qwen2.5-0.5B-Instruct",
messages=[
{
"role": "user",
"content": "What is the Transformers library known for?"
}
],
stream=True,
)
for chunk in completion:
token = chunk.choices[0].delta.content
if token:
print(token, end="")Klien OpenAI mengembalikan string yang dicetak.
The Transformers library is primarily known for its ability to create and manipulate large-scale language models [...]
curl -X POST http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "Qwen/Qwen2.5-0.5B-Instruct",
"messages": [{"role": "user", "content": "What is the Transformers library known for?"}],
"temperature": 0.9,
"max_tokens": 256
}'Perintah mengembalikan string JSON.
{
"id": "ade3578d-e2c3-47ed-b651-c014991a92f6",
"choices": [
{
"finish_reason": "length",
"index": 0,
"message": {
"content": "The Transformers library is primarily known for its ability to create and manipulate large-scale language models [...]",
"role": "assistant"
}
}
],
"created": 1776184004,
"model": "Qwen/Qwen2.5-0.5B-Instruct@main",
"object": "chat.completion",
"usage": {
"completion_tokens": 256,
"prompt_tokens": 37,
"total_tokens": 293
}
}curl -X POST http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "Qwen/Qwen2.5-0.5B-Instruct",
"messages": [{"role": "user", "content": "What is the Transformers library known for?"}],
"temperature": 0.9,
"max_tokens": 256,
"stream": true
}'Perintah mengembalikan aliran potongan data.
data: {"id":"596d3941-754d-43b4-8773-9bf9940049f5","choices":[{"delta":{"role":"assistant"},"index":0}],"created":1776183469,"model":"Qwen/Qwen2.5-0.5B-Instruct@main","object":"chat.completion.chunk","system_fingerprint":""}
data: {"id":"596d3941-754d-43b4-8773-9bf9940049f5","choices":[{"delta":{"content":"The"},"index":0}],"created":1776183469,"model":"Qwen/Qwen2.5-0.5B-Instruct@main","object":"chat.completion.chunk","system_fingerprint":""}
(...)Penyelesaian berbasis gambar
from huggingface_hub import InferenceClient
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": "What's in this image?"},
{
"type": "image_url",
"image_url": {
"url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg",
}
},
],
}
]
client = InferenceClient("http://localhost:8000")
result = client.chat_completion(messages, model="Qwen/Qwen2.5-VL-7B-Instruct", max_tokens=256)
print(result.choices[0].message.content)InferenceClient mengembalikan string yang dicetak.
The image depicts an astronaut in a space suit standing on what appears to be the surface of the moon, given the barren, rocky landscape and the dark sky in the background. The astronaut is holding a large egg that has cracked open, revealing a small creature inside. The scene is imaginative and playful, combining elements of space exploration with a whimsical twist involving the egg and the creature.from huggingface_hub import InferenceClient
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": "What's in this image?"},
{
"type": "image_url",
"image_url": {
"url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg",
}
},
],
}
]
client = InferenceClient("http://localhost:8000")
stream = client.chat_completion(messages, model="Qwen/Qwen2.5-VL-7B-Instruct", max_tokens=256, stream=True)
for chunk in stream:
token = chunk.choices[0].delta.content
if token:
print(token, end="")InferenceClient mengembalikan string yang dicetak.
The image depicts an astronaut in a space suit standing on what appears to be the surface of the moon, given the barren, rocky landscape and the dark sky in the background. The astronaut is holding a large egg that has cracked open, revealing a small creature inside. The scene is imaginative and playful, combining elements of space exploration with a whimsical twist involving the egg and the creature.from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<random_string>")
completion = client.chat.completions.create(
model="Qwen/Qwen2.5-VL-7B-Instruct",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "What's in this image?"},
{
"type": "image_url",
"image_url": {
"url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg",
}
},
],
}
],
)
print(completion.choices[0].message.content)Klien OpenAI mengembalikan string yang dicetak.
The image depicts an astronaut in a space suit standing on what appears to be the surface of the moon, given the barren, rocky landscape and the dark sky in the background. The astronaut is holding a large egg that has cracked open, revealing a small creature inside. The scene is imaginative and playful, combining elements of space exploration with a whimsical twist involving the egg and the creature.from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<random_string>")
completion = client.chat.completions.create(
model="Qwen/Qwen2.5-VL-7B-Instruct",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "What's in this image?"},
{
"type": "image_url",
"image_url": {
"url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg",
}
},
],
}
],
stream=True,
)
for chunk in completion:
token = chunk.choices[0].delta.content
if token:
print(token, end="")Klien OpenAI mengembalikan string yang dicetak.
The image depicts an astronaut in a space suit standing on what appears to be the surface of the moon, given the barren, rocky landscape and the dark sky in the background. The astronaut is holding a large egg that has cracked open, revealing a small creature inside. The scene is imaginative and playful, combining elements of space exploration with a whimsical twist involving the egg and the creature.curl http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "Qwen/Qwen2.5-VL-7B-Instruct",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "What's in this image?"
},
{
"type": "image_url",
"image_url": {
"url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
}
}
]
}
],
"max_tokens": 256
}'Perintah mengembalikan string JSON.
{
"id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"content": "The image depicts an astronaut in a space suit standing on what appears to be the surface of the moon [...]",
"role": "assistant"
}
}
],
"created": 1753366665,
"model": "Qwen/Qwen2.5-VL-7B-Instruct@main",
"object": "chat.completion",
"usage": {
"completion_tokens": 50,
"prompt_tokens": 120,
"total_tokens": 170
}
}curl http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "Qwen/Qwen2.5-VL-7B-Instruct",
"stream": true,
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "What's in this image?"
},
{
"type": "image_url",
"image_url": {
"url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
}
}
]
}
],
"max_tokens": 256
}'Perintah mengembalikan aliran potongan data.
data: {"id":"f47ac10b-58cc-4372-a567-0e02b2c3d479","choices":[{"delta":{"role":"assistant"},"index":0}],"created":1753366665,"model":"Qwen/Qwen2.5-VL-7B-Instruct@main","object":"chat.completion.chunk","system_fingerprint":""}
data: {"id":"f47ac10b-58cc-4372-a567-0e02b2c3d479","choices":[{"delta":{"content":"The "},"index":0}],"created":1753366701,"model":"Qwen/Qwen2.5-VL-7B-Instruct@main","object":"chat.completion.chunk","system_fingerprint":""}
(...)Penyelesaian berbasis audio
Model multimodal seperti Gemma 4 dan Qwen2.5-Omni menerima input audio melalui tipe konten input_audio OpenAI. Lakukan encoding Base64 pada audio dan tentukan formatnya (mp3 atau wav).
import base64
from huggingface_hub.utils import httpx
from huggingface_hub import InferenceClient
audio_url = "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama_first_45_secs.mp3"
audio_b64 = base64.b64encode(httpx.get(audio_url, follow_redirects=True).content).decode()
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": "Transcribe this audio."},
{"type": "input_audio", "input_audio": {"data": audio_b64, "format": "mp3"}},
],
}
]
client = InferenceClient("http://localhost:8000")
result = client.chat_completion(messages, model="google/gemma-4-E2B-it", max_tokens=256)
print(result.choices[0].message.content)InferenceClient mengembalikan string yang dicetak.
This week, I traveled to Chicago to deliver my final farewell address to the nation, following in the tradition of presidents before me. It was an opportunity to say thank you. Whether we've seen eye to eye or rarely agreed at all, my conversations with you, the American people, in living rooms and schools, at farms and on factory floors, at diners, and on distant military outposts, all these conversations are what have kept me honest.import base64
from huggingface_hub.utils import httpx
from huggingface_hub import InferenceClient
audio_url = "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama_first_45_secs.mp3"
audio_b64 = base64.b64encode(httpx.get(audio_url, follow_redirects=True).content).decode()
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": "Transcribe this audio."},
{"type": "input_audio", "input_audio": {"data": audio_b64, "format": "mp3"}},
],
}
]
client = InferenceClient("http://localhost:8000")
stream = client.chat_completion(messages, model="google/gemma-4-E2B-it", max_tokens=256, stream=True)
for chunk in stream:
token = chunk.choices[0].delta.content
if token:
print(token, end="")InferenceClient mengembalikan string yang dicetak.
This week, I traveled to Chicago to deliver my final farewell address to the nation, following in the tradition of presidents before me. It was an opportunity to say thank you. Whether we've seen eye to eye or rarely agreed at all, my conversations with you, the American people, in living rooms and schools, at farms and on factory floors, at diners, and on distant military outposts, all these conversations are what have kept me honest.import base64
from huggingface_hub.utils import httpx
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<random_string>")
audio_url = "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama_first_45_secs.mp3"
audio_b64 = base64.b64encode(httpx.get(audio_url, follow_redirects=True).content).decode()
completion = client.chat.completions.create(
model="google/gemma-4-E2B-it",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "Transcribe this audio."},
{"type": "input_audio", "input_audio": {"data": audio_b64, "format": "mp3"}},
],
}
],
)
print(completion.choices[0].message.content)Klien OpenAI mengembalikan string yang dicetak.
This week, I traveled to Chicago to deliver my final farewell address to the nation, following in the tradition of presidents before me. It was an opportunity to say thank you. Whether we've seen eye to eye or rarely agreed at all, my conversations with you, the American people, in living rooms and schools, at farms and on factory floors, at diners, and on distant military outposts, all these conversations are what have kept me honest.import base64
from huggingface_hub.utils import httpx
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<random_string>")
audio_url = "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama_first_45_secs.mp3"
audio_b64 = base64.b64encode(httpx.get(audio_url, follow_redirects=True).content).decode()
completion = client.chat.completions.create(
model="google/gemma-4-E2B-it",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "Transcribe this audio."},
{"type": "input_audio", "input_audio": {"data": audio_b64, "format": "mp3"}},
],
}
],
stream=True,
)
for chunk in completion:
token = chunk.choices[0].delta.content
if token:
print(token, end="")Klien OpenAI mengembalikan string yang dicetak.
This week, I traveled to Chicago to deliver my final farewell address to the nation, following in the tradition of presidents before me. It was an opportunity to say thank you. Whether we've seen eye to eye or rarely agreed at all, my conversations with you, the American people, in living rooms and schools, at farms and on factory floors, at diners, and on distant military outposts, all these conversations are what have kept me honest.# First, base64-encode the audio file and build the JSON payload
AUDIO_B64=$(curl -sL https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama_first_45_secs.mp3 | base64 -w 0)
cat <<EOF > /tmp/audio_request.json
{
"model": "google/gemma-4-E2B-it",
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": "Transcribe this audio."},
{"type": "input_audio", "input_audio": {"data": "$AUDIO_B64", "format": "mp3"}}
]
}
]
}
EOF
curl http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d @/tmp/audio_request.jsonPerintah mengembalikan string JSON.
{
"id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"content": "This week, I traveled to Chicago to deliver my final farewell address to the nation [...]",
"role": "assistant"
}
}
],
"created": 1753366665,
"model": "google/gemma-4-E2B-it@main",
"object": "chat.completion",
"usage": {
"completion_tokens": 85,
"prompt_tokens": 200,
"total_tokens": 285
}
}# First, base64-encode the audio file and build the JSON payload
AUDIO_B64=$(curl -sL https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama_first_45_secs.mp3 | base64 -w 0)
cat <<EOF > /tmp/audio_request.json
{
"model": "google/gemma-4-E2B-it",
"stream": true,
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": "Transcribe this audio."},
{"type": "input_audio", "input_audio": {"data": "$AUDIO_B64", "format": "mp3"}}
]
}
]
}
EOF
curl http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d @/tmp/audio_request.jsonPerintah mengembalikan aliran potongan data.
data: {"id":"cb997e1d-98b9-414a-be89-1880288610ef","choices":[{"delta":{"role":"assistant"},"index":0}],"created":1776254856,"model":"google/gemma-4-E2B-it@main","object":"chat.completion.chunk","system_fingerprint":""}
data: {"id":"cb997e1d-98b9-414a-be89-1880288610ef","choices":[{"delta":{"content":"This"},"index":0}],"created":1776254856,"model":"google/gemma-4-E2B-it@main","object":"chat.completion.chunk","system_fingerprint":""}
(...)Jenis konten
audio_urladalah ekstensi yang bukan bagian dari standar OpenAI dan dapat berubah pada versi-versi mendatang.
Anda juga dapat mengirim audio melalui URL dengan tipe konten audio_url untuk melewati enkoding base64.
completion = client.chat.completions.create(
model="google/gemma-4-E2B-it",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "Transcribe this audio."},
{"type": "audio_url", "audio_url": {"url": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama_first_45_secs.mp3"}},
],
}
],
)Penyelesaian berbasis video
Jenis konten
video_urladalah ekstensi yang bukan bagian dari standar OpenAI dan dapat berubah pada versi-versi mendatang.
Gunakan tipe konten video_url untuk input video. Jika model mendukung audio (misalnya Gemma 4, Qwen2.5-Omni), server akan mengekstrak trek audio dari video dan memprosesnya bersama bingkai visual.
Pemrosesan video memerlukan torchcodec. Instal dengan
pip install torchcodec.
from huggingface_hub import InferenceClient
messages = [
{
"role": "user",
"content": [
{"type": "video_url", "video_url": {"url": "https://huggingface.co/datasets/merve/vlm_test_images/resolve/main/concert.mp4"}},
{"type": "text", "text": "What is happening in the video and what is the song about?"},
],
}
]
client = InferenceClient("http://localhost:8000")
result = client.chat_completion(messages, model="google/gemma-4-E2B-it", max_tokens=256)
print(result.choices[0].message.content)InferenceClient mengembalikan string yang dicetak.
The video captures a live music performance at a music festival or a large concert. There are several musicians on stage, including a central figure playing an acoustic guitar and singing. The foreground is filled with the backs of the audience, indicating a large crowd watching the show. The stage is dramatically lit with bright spotlights and blue and white stage lighting, with haze and smoke creating an immersive atmosphere.
The lyrics of the song are: "I don't care 'bout street, from that fresh street, 'cause there's no problem, another one I want to be, in the storm..."from huggingface_hub import InferenceClient
messages = [
{
"role": "user",
"content": [
{"type": "video_url", "video_url": {"url": "https://huggingface.co/datasets/merve/vlm_test_images/resolve/main/concert.mp4"}},
{"type": "text", "text": "What is happening in the video and what is the song about?"},
],
}
]
client = InferenceClient("http://localhost:8000")
stream = client.chat_completion(messages, model="google/gemma-4-E2B-it", max_tokens=256, stream=True)
for chunk in stream:
token = chunk.choices[0].delta.content
if token:
print(token, end="")InferenceClient mengembalikan string yang dicetak.
The video captures a live music performance at a music festival or a large concert. There are several musicians on stage, including a central figure playing an acoustic guitar and singing. The foreground is filled with the backs of the audience, indicating a large crowd watching the show. The stage is dramatically lit with bright spotlights and blue and white stage lighting, with haze and smoke creating an immersive atmosphere.
The lyrics of the song are: "I don't care 'bout street, from that fresh street, 'cause there's no problem, another one I want to be, in the storm..."from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<random_string>")
completion = client.chat.completions.create(
model="google/gemma-4-E2B-it",
messages=[
{
"role": "user",
"content": [
{"type": "video_url", "video_url": {"url": "https://huggingface.co/datasets/merve/vlm_test_images/resolve/main/concert.mp4"}},
{"type": "text", "text": "What is happening in the video and what is the song about?"},
],
}
],
max_tokens=256,
)
print(completion.choices[0].message.content)Klien OpenAI mengembalikan string yang dicetak.
The video captures a live music performance at a music festival or a large concert. There are several musicians on stage, including a central figure playing an acoustic guitar and singing. The foreground is filled with the backs of the audience, indicating a large crowd watching the show. The stage is dramatically lit with bright spotlights and blue and white stage lighting, with haze and smoke creating an immersive atmosphere.
The lyrics of the song are: "I don't care 'bout street, from that fresh street, 'cause there's no problem, another one I want to be, in the storm..."from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<random_string>")
completion = client.chat.completions.create(
model="google/gemma-4-E2B-it",
messages=[
{
"role": "user",
"content": [
{"type": "video_url", "video_url": {"url": "https://huggingface.co/datasets/merve/vlm_test_images/resolve/main/concert.mp4"}},
{"type": "text", "text": "What is happening in the video and what is the song about?"},
],
}
],
max_tokens=256,
stream=True,
)
for chunk in completion:
token = chunk.choices[0].delta.content
if token:
print(token, end="")Klien OpenAI mengembalikan string yang dicetak.
The video captures a live music performance at a music festival or a large concert. There are several musicians on stage, including a central figure playing an acoustic guitar and singing. The foreground is filled with the backs of the audience, indicating a large crowd watching the show. The stage is dramatically lit with bright spotlights and blue and white stage lighting, with haze and smoke creating an immersive atmosphere.
The lyrics of the song are: "I don't care 'bout street, from that fresh street, 'cause there's no problem, another one I want to be, in the storm..."curl http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "google/gemma-4-E2B-it",
"messages": [
{
"role": "user",
"content": [
{"type": "video_url", "video_url": {"url": "https://huggingface.co/datasets/merve/vlm_test_images/resolve/main/concert.mp4"}},
{"type": "text", "text": "What is happening in the video and what is the song about?"}
]
}
],
"max_tokens": 256
}'Perintah mengembalikan string JSON.
{
"id": "b2c3d4e5-f6a7-8901-bcde-f12345678901",
"choices": [
{
"finish_reason": "length",
"index": 0,
"message": {
"content": "The video captures a live music performance at a music festival or a large concert [...]",
"role": "assistant"
}
}
],
"created": 1753366665,
"model": "google/gemma-4-E2B-it@main",
"object": "chat.completion",
"usage": {
"completion_tokens": 256,
"prompt_tokens": 350,
"total_tokens": 606
}
}curl http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "google/gemma-4-E2B-it",
"stream": true,
"messages": [
{
"role": "user",
"content": [
{"type": "video_url", "video_url": {"url": "https://huggingface.co/datasets/merve/vlm_test_images/resolve/main/concert.mp4"}},
{"type": "text", "text": "What is happening in the video and what is the song about?"}
]
}
],
"max_tokens": 256
}'Perintah mengembalikan aliran potongan data.
data: {"id":"cb997e1d-98b9-414a-be89-1880288610ef","choices":[{"delta":{"role":"assistant"},"index":0}],"created":1776254856,"model":"google/gemma-4-E2B-it@main","object":"chat.completion.chunk","system_fingerprint":""}
data: {"id":"cb997e1d-98b9-414a-be89-1880288610ef","choices":[{"delta":{"content":"Based"},"index":0}],"created":1776254856,"model":"google/gemma-4-E2B-it@main","object":"chat.completion.chunk","system_fingerprint":""}
(...)Percakapan multi-pusing
Untuk melakukan percakapan multi-turn, sertakan riwayat percakapan lengkap dalam daftar messages dengan peran user dan assistant yang berselang-seling. Seperti semua server yang kompatibel dengan OpenAI, API bersifat stateless, sehingga setiap permintaan harus memuat riwayat percakapan yang lengkap.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<random_string>")
completion = client.chat.completions.create(
model="Qwen/Qwen2.5-0.5B-Instruct",
messages=[
{"role": "user", "content": "What is the capital of France?"},
{"role": "assistant", "content": "The capital of France is Paris."},
{"role": "user", "content": "How many people live there?"},
],
)
print(completion.choices[0].message.content)Pertanyaan lanjutan “Berapa banyak orang yang tinggal di sana?” bergantung pada konteks sebelumnya, sehingga model menjawab tentang Paris.
As of 2021, the population of Paris is approximately 2.2 million people.v1/completions
API v1/completions didasarkan pada legacy Completions API. Berbeda dengan /v1/chat/completions, API ini menerima prompt berupa teks bebas alih-alih pesan chat, dan mengembalikan teks yang dihasilkan di choices[].text. Hal ini berguna untuk model dasar (non-instruct) dan tugas pelengkapan teks di mana template chat tidak diperlukan. API ini juga mendukung suffix untuk sisipan teks di tengah (fill-in-the-middle).
curl -X POST http://localhost:8000/v1/completions \
-H "Content-Type: application/json" \
-d '{
"model": "Qwen/Qwen2.5-0.5B",
"prompt": "The capital of France is",
"max_tokens": 20
}'Perintah mengembalikan respons berikut.
{
"id": "chatcmpl-abc123",
"object": "text_completion",
"created": 1234567890,
"model": "Qwen/Qwen2.5-0.5B@main",
"choices": [
{
"text": " Paris, and the capital of the United States is Washington, D.C.",
"index": 0,
"logprobs": null,
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 5,
"completion_tokens": 16,
"total_tokens": 21
}
}from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<random_string>")
# Non-streaming
completion = client.completions.create(
model="Qwen/Qwen2.5-0.5B",
prompt="The capital of France is",
max_tokens=20,
)
print(completion.choices[0].text)Klien OpenAI mengembalikan hal berikut.
Paris, and the capital of the United States is Washington, D.C.
Streaming juga didukung.
stream = client.completions.create(
model="Qwen/Qwen2.5-0.5B",
prompt="The capital of France is",
max_tokens=20,
stream=True,
)
for chunk in stream:
print(chunk.choices[0].text, end="")v1/responses
Responses API adalah endpoint API terbaru dari OpenAI untuk generasi. API ini mendukung interaksi berstatus (stateful) dan mengintegrasikan alat bawaan untuk memperluas kemampuan model. OpenAI merekomendasikan penggunaan Responses API alih-alih Chat Completions API untuk proyek baru.
API v1/responses mendukung permintaan teks, gambar, audio, dan video melalui perintah curl dan klien OpenAI.
Respons berbasis teks
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<random_string>")
response = client.responses.create(
model="Qwen/Qwen2.5-0.5B-Instruct",
input="Tell me a three sentence bedtime story about a unicorn.",
max_output_tokens=256,
stream=False,
)
print(response.output[0].content[0].text)Klien OpenAI mengembalikan string yang dicetak.
Once upon a time, in a faraway land, there lived a beautiful unicorn named Luna [...]
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<random_string>")
response = client.responses.create(
model="Qwen/Qwen2.5-0.5B-Instruct",
input="Tell me a three sentence bedtime story about a unicorn.",
max_output_tokens=256,
stream=True,
)
for event in response:
if hasattr(event, "delta") and event.delta:
print(event.delta, end="")Klien OpenAI mengembalikan string yang dicetak.
Once upon a time, in a faraway land, there lived a beautiful unicorn named Luna [...]
curl http://localhost:8000/v1/responses \
-H "Content-Type: application/json" \
-d '{
"model": "Qwen/Qwen2.5-0.5B-Instruct",
"input": "Tell me a three sentence bedtime story about a unicorn.",
"max_output_tokens": 256,
"stream": false
}'Perintah mengembalikan string JSON.
{
"id": "resp_8693af9b-b561-4267-bd1a-22d1b43284cb",
"created_at": 1776258580.7114341,
"model": "Qwen/Qwen2.5-0.5B-Instruct@main",
"object": "response",
"output": [
{
"id": "msg_8693af9b-b561-4267-bd1a-22d1b43284cb",
"content": [
{
"annotations": [],
"text": "Once upon a time, in a faraway land, there lived a beautiful unicorn named Luna [...]",
"type": "output_text"
}
],
"role": "assistant",
"status": "completed",
"type": "message"
}
],
"status": "completed"
}curl http://localhost:8000/v1/responses \
-H "Content-Type: application/json" \
-d '{
"model": "Qwen/Qwen2.5-0.5B-Instruct",
"stream": true,
"input": "Tell me a three sentence bedtime story about a unicorn.",
"max_output_tokens": 256
}'Perintah mengembalikan aliran potongan data.
data: {"response":{"id":"resp_req_0","created_at":1754059817.783648,"model":"Qwen/Qwen2.5-0.5B-Instruct@main","object":"response","output":[],"status":"queued"},"sequence_number":0,"type":"response.created"}
data: {"content_index":0,"delta":"Once ","item_id":"msg_req_0","output_index":0,"sequence_number":5,"type":"response.output_text.delta"}
data: {"content_index":0,"delta":"upon ","item_id":"msg_req_0","output_index":0,"sequence_number":6,"type":"response.output_text.delta"}
(...)Respons berbasis gambar
API Respons juga mendukung input gambar, audio, dan video.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<random_string>")
response = client.responses.create(
model="Qwen/Qwen2.5-VL-7B-Instruct",
input=[
{"type": "input_text", "text": "What's in this image?"},
{
"type": "input_image",
"image_url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg",
},
],
max_output_tokens=256,
stream=False,
)
print(response.output[0].content[0].text)Klien OpenAI mengembalikan string yang dicetak.
The image depicts an astronaut in a space suit standing on what appears to be the surface of the moon, given the barren, rocky landscape and the dark sky in the background. The astronaut is holding a large egg that has cracked open, revealing a small creature inside. The scene is imaginative and playful, combining elements of space exploration with a whimsical twist involving the egg and the creature.from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<random_string>")
response = client.responses.create(
model="Qwen/Qwen2.5-VL-7B-Instruct",
input=[
{"type": "input_text", "text": "What's in this image?"},
{
"type": "input_image",
"image_url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg",
},
],
max_output_tokens=256,
stream=True,
)
for event in response:
if hasattr(event, "delta") and event.delta:
print(event.delta, end="")Klien OpenAI mengembalikan string yang dicetak.
The image depicts an astronaut in a space suit standing on what appears to be the surface of the moon, given the barren, rocky landscape and the dark sky in the background. The astronaut is holding a large egg that has cracked open, revealing a small creature inside. The scene is imaginative and playful, combining elements of space exploration with a whimsical twist involving the egg and the creature.curl http://localhost:8000/v1/responses \
-H "Content-Type: application/json" \
-d '{
"model": "Qwen/Qwen2.5-VL-7B-Instruct",
"input": [
{"type": "input_text", "text": "What'\''s in this image?"},
{"type": "input_image", "image_url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"}
],
"max_output_tokens": 256,
"stream": false
}'Perintah mengembalikan string JSON.
{
"id": "resp_f47ac10b-58cc-4372-a567-0e02b2c3d479",
"created_at": 1776258580.7114341,
"model": "Qwen/Qwen2.5-VL-7B-Instruct@main",
"object": "response",
"output": [
{
"id": "msg_f47ac10b-58cc-4372-a567-0e02b2c3d479",
"content": [
{
"annotations": [],
"text": "The image depicts an astronaut in a space suit standing on what appears to be the surface of the moon [...]",
"type": "output_text"
}
],
"role": "assistant",
"status": "completed",
"type": "message"
}
],
"status": "completed"
}curl http://localhost:8000/v1/responses \
-H "Content-Type: application/json" \
-d '{
"model": "Qwen/Qwen2.5-VL-7B-Instruct",
"stream": true,
"input": [
{"type": "input_text", "text": "What'\''s in this image?"},
{"type": "input_image", "image_url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"}
],
"max_output_tokens": 256
}'Perintah mengembalikan aliran potongan data.
data: {"response":{"id":"resp_f47ac10b-58cc-4372-a567-0e02b2c3d479","created_at":1776258580.7114341,"model":"Qwen/Qwen2.5-VL-7B-Instruct@main","object":"response","output":[],"status":"queued"},"sequence_number":0,"type":"response.created"}
data: {"content_index":0,"delta":"The ","item_id":"msg_f47ac10b","output_index":0,"sequence_number":5,"type":"response.output_text.delta"}
(...)Respons berbasis audio
import base64
from huggingface_hub.utils import httpx
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<random_string>")
audio_url = "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama_first_45_secs.mp3"
audio_b64 = base64.b64encode(httpx.get(audio_url, follow_redirects=True).content).decode()
response = client.responses.create(
model="google/gemma-4-E2B-it",
input=[
{"type": "input_text", "text": "Transcribe this audio."},
{"type": "input_audio", "input_audio": {"data": audio_b64, "format": "mp3"}},
],
max_output_tokens=256,
stream=False,
)
print(response.output[0].content[0].text)Klien OpenAI mengembalikan string yang dicetak.
This week, I traveled to Chicago to deliver my final farewell address to the nation, following in the tradition of presidents before me. It was an opportunity to say thank you. Whether we've seen eye to eye or rarely agreed at all, my conversations with you, the American people, in living rooms and schools, at farms and on factory floors, at diners, and on distant military outposts, all these conversations are what have kept me honest.import base64
from huggingface_hub.utils import httpx
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<random_string>")
audio_url = "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama_first_45_secs.mp3"
audio_b64 = base64.b64encode(httpx.get(audio_url, follow_redirects=True).content).decode()
response = client.responses.create(
model="google/gemma-4-E2B-it",
input=[
{"type": "input_text", "text": "Transcribe this audio."},
{"type": "input_audio", "input_audio": {"data": audio_b64, "format": "mp3"}},
],
}
],
max_output_tokens=256,
stream=True,
)
for event in response:
if hasattr(event, "delta") and event.delta:
print(event.delta, end="")Klien OpenAI mengembalikan string yang dicetak.
This week, I traveled to Chicago to deliver my final farewell address to the nation, following in the tradition of presidents before me. It was an opportunity to say thank you. Whether we've seen eye to eye or rarely agreed at all, my conversations with you, the American people, in living rooms and schools, at farms and on factory floors, at diners, and on distant military outposts, all these conversations are what have kept me honest.# First, base64-encode the audio file and build the JSON payload
AUDIO_B64=$(curl -sL https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama_first_45_secs.mp3 | base64 -w 0)
cat <<EOF > /tmp/audio_request.json
{
"model": "google/gemma-4-E2B-it",
"input": [
{"type": "input_text", "text": "Transcribe this audio."},
{"type": "input_audio", "input_audio": {"data": "$AUDIO_B64", "format": "mp3"}}
],
"max_output_tokens": 256,
"stream": false
}
EOF
curl http://localhost:8000/v1/responses \
-H "Content-Type: application/json" \
-d @/tmp/audio_request.jsonPerintah mengembalikan string JSON.
{
"id": "resp_a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"created_at": 1776258580.7114341,
"model": "google/gemma-4-E2B-it@main",
"object": "response",
"output": [
{
"id": "msg_a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"content": [
{
"annotations": [],
"text": "This week, I traveled to Chicago to deliver my final farewell address to the nation [...]",
"type": "output_text"
}
],
"role": "assistant",
"status": "completed",
"type": "message"
}
],
"status": "completed"
}# First, base64-encode the audio file and build the JSON payload
AUDIO_B64=$(curl -sL https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama_first_45_secs.mp3 | base64 -w 0)
cat <<EOF > /tmp/audio_request.json
{
"model": "google/gemma-4-E2B-it",
"stream": true,
"input": [
{"type": "input_text", "text": "Transcribe this audio."},
{"type": "input_audio", "input_audio": {"data": "$AUDIO_B64", "format": "mp3"}}
],
"max_output_tokens": 256
}
EOF
curl http://localhost:8000/v1/responses \
-H "Content-Type: application/json" \
-d @/tmp/audio_request.jsonPerintah mengembalikan aliran potongan data.
data: {"response":{"id":"resp_a1b2c3d4-e5f6-7890-abcd-ef1234567890","created_at":1776258580.7114341,"model":"google/gemma-4-E2B-it@main","object":"response","output":[],"status":"queued"},"sequence_number":0,"type":"response.created"}
data: {"content_index":0,"delta":"This ","item_id":"msg_a1b2c3d4","output_index":0,"sequence_number":5,"type":"response.output_text.delta"}
(...)Jenis konten
audio_urladalah ekstensi yang bukan bagian dari standar OpenAI dan dapat berubah pada versi-versi mendatang.
Anda juga dapat mengirim audio melalui URL dengan tipe konten audio_url untuk melewati enkoding base64.
response = client.responses.create(
model="google/gemma-4-E2B-it",
input=[
{"type": "input_text", "text": "Transcribe this audio."},
{"type": "audio_url", "audio_url": {"url": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama_first_45_secs.mp3"}},
],
max_output_tokens=256,
stream=False,
)Respons berbasis video
Jenis konten
video_urladalah ekstensi yang bukan bagian dari standar OpenAI dan dapat berubah pada versi-versi mendatang.
Pemrosesan video memerlukan torchcodec. Instal dengan
pip install torchcodec.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<random_string>")
response = client.responses.create(
model="google/gemma-4-E2B-it",
input=[
{"type": "input_text", "text": "What is happening in the video and what is the song about?"},
{"type": "video_url", "video_url": {"url": "https://huggingface.co/datasets/merve/vlm_test_images/resolve/main/concert.mp4"}},
],
max_output_tokens=256,
stream=False,
)
print(response.output[0].content[0].text)Klien OpenAI mengembalikan string yang dicetak.
The video captures a live music performance at a music festival or a large concert. There are several musicians on stage, including a central figure playing an acoustic guitar and singing. The foreground is filled with the backs of the audience, indicating a large crowd watching the show. The stage is dramatically lit with bright spotlights and blue and white stage lighting, with haze and smoke creating an immersive atmosphere.
The lyrics of the song are: "I don't care 'bout street, from that fresh street, 'cause there's no problem, another one I want to be, in the storm..."from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<random_string>")
response = client.responses.create(
model="google/gemma-4-E2B-it",
input=[
{"type": "input_text", "text": "What is happening in the video and what is the song about?"},
{"type": "video_url", "video_url": {"url": "https://huggingface.co/datasets/merve/vlm_test_images/resolve/main/concert.mp4"}},
],
max_output_tokens=256,
stream=True,
)
for event in response:
if hasattr(event, "delta") and event.delta:
print(event.delta, end="")Klien OpenAI mengembalikan string yang dicetak.
The video captures a live music performance at a music festival or a large concert. There are several musicians on stage, including a central figure playing an acoustic guitar and singing. The foreground is filled with the backs of the audience, indicating a large crowd watching the show. The stage is dramatically lit with bright spotlights and blue and white stage lighting, with haze and smoke creating an immersive atmosphere.
The lyrics of the song are: "I don't care 'bout street, from that fresh street, 'cause there's no problem, another one I want to be, in the storm..."curl http://localhost:8000/v1/responses \
-H "Content-Type: application/json" \
-d '{
"model": "google/gemma-4-E2B-it",
"input": [
{"type": "input_text", "text": "What is happening in the video and what is the song about?"},
{"type": "video_url", "video_url": {"url": "https://huggingface.co/datasets/merve/vlm_test_images/resolve/main/concert.mp4"}}
],
"max_output_tokens": 256,
"stream": false
}'Perintah mengembalikan string JSON.
{
"id": "resp_b2c3d4e5-f6a7-8901-bcde-f12345678901",
"created_at": 1776258580.7114341,
"model": "google/gemma-4-E2B-it@main",
"object": "response",
"output": [
{
"id": "msg_b2c3d4e5-f6a7-8901-bcde-f12345678901",
"content": [
{
"annotations": [],
"text": "The video captures a live music performance at a music festival or a large concert [...]",
"type": "output_text"
}
],
"role": "assistant",
"status": "completed",
"type": "message"
}
],
"status": "completed"
}curl http://localhost:8000/v1/responses \
-H "Content-Type: application/json" \
-d '{
"model": "google/gemma-4-E2B-it",
"stream": true,
"input": [
{"type": "input_text", "text": "What is happening in the video and what is the song about?"},
{"type": "video_url", "video_url": {"url": "https://huggingface.co/datasets/merve/vlm_test_images/resolve/main/concert.mp4"}}
],
"max_output_tokens": 256
}'Perintah mengembalikan aliran potongan data.
data: {"response":{"id":"resp_b2c3d4e5-f6a7-8901-bcde-f12345678901","created_at":1776258580.7114341,"model":"google/gemma-4-E2B-it@main","object":"response","output":[],"status":"queued"},"sequence_number":0,"type":"response.created"}
data: {"content_index":0,"delta":"Based ","item_id":"msg_b2c3d4e5","output_index":0,"sequence_number":5,"type":"response.output_text.delta"}
(...)Percakapan multi-pusing
Untuk percakapan multi-turn, berikan daftar pesan dengan kunci role di field input. Seperti semua server yang kompatibel dengan OpenAI, API bersifat stateless, sehingga setiap permintaan harus memuat riwayat percakapan lengkap.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<random_string>")
response = client.responses.create(
model="Qwen/Qwen2.5-0.5B-Instruct",
input=[
{"role": "user", "content": "What is the capital of France?"},
{"role": "assistant", "content": "The capital of France is Paris."},
{"role": "user", "content": "How many people live there?"},
],
max_output_tokens=256,
stream=False,
)
print(response.output[0].content[0].text)Pertanyaan lanjutan “Berapa banyak orang yang tinggal di sana?” bergantung pada konteks sebelumnya, sehingga model menjawab tentang Paris.
As of 2021, Paris has a population of approximately 2.8 million people.v1/systemone
Endpoint v1/systemone menjawab pertanyaan bertipe tentang state bersama, mengikuti System One API dari TypeSafe. Gunakan endpoint ini untuk pengambilan keputusan seperti merutekan tiket dukungan, menilai tingkat urgensi, atau memilih tindakan.
Model menilai jawaban yang diizinkan dalam satu langkah forward batched tanpa menghasilkan teks. Endpoint ini mendukung model autoregresif dengan template chat;
Kirim model, state yang akan dievaluasi, dan pertanyaan yang dikey berdasarkan nama:
curl http://localhost:8000/v1/systemone \
-H "Content-Type: application/json" \
-d '{
"model": "Qwen/Qwen2.5-1.5B-Instruct",
"state": "Our integration has been failing for 3 days and we are losing sales!",
"questions": {
"team": {
"type": "choice",
"instructions": "Which team handles this?",
"criteria": {"billing": null, "technical": "Bugs or integration problems"}
},
"urgency": {
"type": "score",
"instructions": "How urgent is this ticket?",
"criteria": ["low", "medium", "high"]
},
"upset": {"type": "noul", "instructions": "Is the customer upset?"}
}
}'Instal TypeSafe SDK untuk Node.js 20 atau yang lebih baru:
npm install @typesafe-ai/sdk
Set baseURL ke root server; SDK akan menambahkan /v1/systemone. SDK memerlukan API key, tetapi placeholder dapat berfungsi dengan server lokal.
import { choice, noul, score, TypeSafeClient } from "@typesafe-ai/sdk";
const client = new TypeSafeClient({
baseURL: "http://localhost:8000",
apiKey: "<random_string>",
});
const response = await client.systemOne({
model: "Qwen/Qwen2.5-1.5B-Instruct",
state: "Our integration has been failing for 3 days and we are losing sales!",
questions: {
team: choice("Which team handles this?", {
billing: null,
technical: "Bugs or integration problems",
}),
urgency: score("How urgent is this ticket?", ["low", "medium", "high"]),
upset: noul("Is the customer upset?"),
},
});
console.log(response.answers.team.choice);
console.log(response.answers.urgency.score);
console.log(response.answers.upset.noul);Klien mencetak tim yang dipilih, skor urgensi, dan probabilitas bahwa pelanggan sedang kesal. Sebagai contoh:
technical 1.6739138662815094 0.851952850818634
Jawaban menggunakan nama pertanyaan yang sama. Contoh:
{
"model": "Qwen/Qwen2.5-1.5B-Instruct",
"answers": {
"team": {"type": "choice", "choice": "technical", "probabilities": {"billing": 0.000006962256520637311, "technical": 0.999993085861206}, "confidence": 0.9999861717224121},
"urgency": {"type": "score", "score": 1.6739138662815094, "legend": {"0": "low", "1": "medium", "2": "high"}, "probabilities": {"0": 0.0031353600788861513, "1": 0.31981542706489563, "2": 0.6770492196083069}, "confidence": 0.5108707791659981},
"upset": {"type": "noul", "noul": 0.851952850818634}
},
"usage": {"input_tokens": 213, "output_tokens": 0}
}| Jenis pertanyaan | criteria | Jawaban |
|---|---|---|
choice | Nama opsi yang dipetakan ke deskripsi, yang dapat berupa null. | Opsi yang paling mungkin, probabilitas opsi, dan tingkat kepercayaan. |
score | Deskripsi level diurutkan dari terendah hingga tertinggi. | Indeks level berbobot probabilitas, probabilitas, legenda, dan tingkat kepercayaan. |
noul | Deskripsi opsional untuk true dan false. | Probabilitas dari true. |
state, instructions opsional, dan deskripsi dapat berisi teks atau objek dan array JSON. Setiap permintaan menerima hingga 64 pertanyaan, dengan 1–26 pilihan atau tingkat skor per pertanyaan.
Untuk model yang mendukung visi, tambahkan array images dengan hingga empat URL data:image/...;base64,.... Setiap pertanyaan menerima gambar yang sama. Processor dan chat template model harus mendukung gambar; URL gambar jarak jauh tidak diterima.
Konfigurasi keputusan
Model keputusan belum memiliki standar untuk menyimpan prompt, label jawaban, dan pengaturan kalibrasi. Karena hal ini bervariasi di antara implementasi model, --decision-config memungkinkan Anda menyediakannya secara eksplisit. Model dengan kepala keputusan kustom tetap memerlukan implementasi yang kompatibel; file ini hanya mengonfigurasi format prompt dan penilaian token berikutnya.
Secara default, pertanyaan menggunakan prompt cadangan dan template chat model dengan fitur berpikir dinonaktifkan. Label jawaban adalah A–Z untuk pilihan dan skor, serta Yes/No untuk nilai boolean. Probabilitas adalah hasil softmax dari label-label ini pada suhu 1.
Lewati --decision-config untuk menimpa nilai bawaan ini untuk sebuah model:
transformers serve openjev/openjev --decision-config decision.json
File JSON mendukung tiga field opsional:
| Bidang | Arti |
|---|---|
labels | Label jawaban berdasarkan jenis pertanyaan, dalam urutan opsi (true, kemudian false untuk noul). Masing-masing harus berupa token tunggal yang berbeda dan dikenal. |
temperature | Suhu positif berdasarkan jenis pertanyaan, diterapkan sebagai softmax(label_logits / temperature). |
chat_template | Template Jinja inline yang menggantikan prompt lengkap, termasuk format chat dan prefiks asisten. |
Sebagai contoh, untuk mengubah label dan kalibrasi sambil mempertahankan prompt default:
{
"labels": {"noul": ["A", "B"]},
"temperature": {"choice": 0.85, "score": 0.85, "noul": 1.5547129}
}Template kustom menerima messages yang biasa, ditambah bidang mentah state, images, dan question. Pertanyaan mengekspos name, type, instructions, options, labels, descriptions, dan legend; options, labels, dan descriptions berbagi urutan yang sama. Gunakan bidang-bidang ini untuk menggantikan frasa fallback, dan tojson untuk merender nilai terstruktur. Template untuk input gambar harus menyertakan placeholder gambar model.
File dimuat saat startup dan hanya berlaku untuk /v1/systemone. Pengaturan yang diabaikan akan mempertahankan nilai defaultnya; konfigurasi keputusan tidak dibaca secara otomatis dari checkpoint.
v1/audio/transcriptions
Endpoint v1/audio/transcriptions mentranskripsi audio menggunakan model speech-to-text. Endpoint ini mengikuti format Audio transcription API.
curl -X POST http://localhost:8000/v1/audio/transcriptions \ -H "Content-Type: multipart/form-data" \ -F "file=@/path/to/audio.wav" \ -F "model=openai/whisper-large-v3"
Perintah mengembalikan respons berikut.
{
"text": "Transcribed text from the audio file",
}v1/models
Endpoint v1/models memindai cache Hugging Face lokal Anda dan mengembalikan daftar model yang telah diunduh dalam format yang kompatibel dengan OpenAI. Alat pihak ketiga menggunakan endpoint ini untuk menemukan model yang tersedia.
Unduh model sebelum menjalankan transformers serve.
transformers download Qwen/Qwen2.5-0.5B-Instruct
Setelah diunduh, model tersebut muncul dalam respons /v1/models.
curl http://localhost:8000/v1/models
Endpoint mengembalikan objek JSON berisi model yang tersedia.
Memuat model
Endpoint /load_model memuat model secara pra-muat dan mengalirkan progres melalui Server-Sent Events (SSE). CLI transformers chat menggunakannya secara otomatis sehingga pengguna dapat melihat progres unduhan dan pemuatan, bukan prompt yang menggantung. Gunakan endpoint ini untuk menghangatkan model sebelum mengirim permintaan inferensi.
Permintaan
curl -N -X POST http://localhost:8000/load_model \
-H "Content-Type: application/json" \
-d '{"model": "Qwen/Qwen2.5-0.5B-Instruct"}'Bidang model adalah pengidentifikasi model Hugging Face, secara opsional dengan akhiran @revision (Qwen/Qwen2.5-0.5B-Instruct@main). Jika revisi diabaikan, nilai defaultnya adalah main.
Respons
Responsnya adalah aliran SSE (Content-Type: text/event-stream). Setiap frame adalah objek JSON pada baris data:.
data: {"status": "loading", "model": "Qwen/Qwen2.5-0.5B-Instruct@main", "stage": "processor"}Setiap event memuat minimal field status dan model. Field tambahan bergantung pada status.
| Bidang | Ada saat | Deskripsi |
|---|---|---|
status | Selalu | loading, ready, atau error |
model | Selalu | Kanonik model_id@revision |
stage | status == "loading" | Salah satu dari processor, config, download, weights (lihat tahapan di bawah) |
progress | tahap download dan weights | Objek dengan current dan total (integer atau null) |
cached | status == "ready" | true jika model sudah berada di memori |
message | status == "error" | Deskripsi error |
Tahapan
Pemuatan berjalan melalui tahap-tahap berikut secara berurutan. Beberapa tahap dapat dilewati (download dilewati ketika file sudah di-cache secara lokal).
| Tahap | Apakah ada kemajuan? | Deskripsi |
|---|---|---|
processor | Tidak | Memuat tokenizer/processor |
config | Tidak | Memuat konfigurasi model |
download | Ya (byte) | Mengunduh file model |
weights | Ya (item) | Memuat tensor bobot ke dalam memori |
Stream berakhir dengan tepat satu peristiwa terminal, ready (sukses) atau error (gagal).
Timeout
transformers serve menangani permintaan untuk model apa pun. Setiap model dimuat saat dibutuhkan dan tetap berada di memori GPU. Model dimuat keluar secara otomatis setelah 300 detik tidak aktif untuk membebaskan memori GPU. Atur --model-timeout ke nilai lain dalam detik, atau -1 untuk menonaktifkan pemuatan keluar.
transformers serve --model-timeout 400
Memuat contoh
Contoh di bawah ini menunjukkan respons untuk model yang baru diunduh, model yang dimuat dari cache lokal Anda (melewati tahap unduhan), dan model yang sudah ada di memori.
data: {"status": "loading", "model": "org/model@main", "stage": "processor"}
data: {"status": "loading", "model": "org/model@main", "stage": "config"}
data: {"status": "loading", "model": "org/model@main", "stage": "download", "progress": {"current": 0, "total": 269100000}}
data: {"status": "loading", "model": "org/model@main", "stage": "download", "progress": {"current": 134600000, "total": 269100000}}
data: {"status": "loading", "model": "org/model@main", "stage": "download", "progress": {"current": 269100000, "total": 269100000}}
data: {"status": "loading", "model": "org/model@main", "stage": "weights", "progress": {"current": 1, "total": 272}}
data: {"status": "loading", "model": "org/model@main", "stage": "weights", "progress": {"current": 272, "total": 272}}
data: {"status": "ready", "model": "org/model@main", "cached": false}data: {"status": "loading", "model": "org/model@main", "stage": "processor"}
data: {"status": "loading", "model": "org/model@main", "stage": "config"}
data: {"status": "loading", "model": "org/model@main", "stage": "weights", "progress": {"current": 1, "total": 272}}
data: {"status": "loading", "model": "org/model@main", "stage": "weights", "progress": {"current": 272, "total": 272}}
data: {"status": "ready", "model": "org/model@main", "cached": false}data: {"status": "ready", "model": "org/model@main", "cached": true}Pemanggilan alat
Server transformers serve mendukung pemanggilan fungsi bergaya OpenAI. Model yang dilatih untuk penggunaan alat menghasilkan pemanggilan fungsi terstruktur yang dieksekusi oleh aplikasi Anda.
Tool calling berfungsi dengan model apa pun yang tokenizer-nya mendeklarasikan token tool call. Qwen dan Gemma 4 langsung berfungsi tanpa konfigurasi tambahan. Buka issue untuk meminta dukungan terhadap model tertentu.
Definisikan tools sebagai daftar spesifikasi fungsi yang mengikuti format OpenAI.
import json
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<KEY>")
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather in a location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city name, e.g. San Francisco"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "temperature unit"
}
},
"required": ["location"]
}
}
}
]Sesuaikan generasi dengan meneruskan parameter GenerationConfig ke argumen extra_body di create.
generation_config = {
"max_new_tokens": 512,
"temperature": 0.7,
"top_p": 0.9,
"top_k": 50,
"do_sample": True,
"repetition_penalty": 1.1,
"no_repeat_ngram_size": 3,
}
response = client.responses.create(
model="Qwen/Qwen2.5-7B-Instruct",
instructions="You are a helpful weather assistant. Use the get_weather tool to answer questions.",
input="What's the weather like in San Francisco?",
tools=tools,
stream=True,
extra_body={"generation_config": json.dumps(generation_config)}
)
for event in response:
print(event)Pemanggilan alat multi-putaran
Setelah model mengembalikan panggilan alat, jalankan fungsi secara lokal, lalu kirimkan hasilnya kembali dalam permintaan lanjutan untuk mendapatkan jawaban akhir dari model. Pola ini sedikit berbeda antara kedua API tersebut. Lihat panduan pemanggilan fungsi OpenAI untuk spesifikasi lengkapnya.
Contoh di bawah ini menggunakan kembali daftar tools yang didefinisikan di atas.
Lewatkan hasil tool sebagai pesan role: "tool" dengan tool_call_id yang sesuai.
# Model returns a tool call
messages = [{"role": "user", "content": "What's the weather like in San Francisco?"}]
response = client.chat.completions.create(
model="Qwen/Qwen2.5-7B-Instruct",
messages=messages,
tools=tools,
)
assistant_message = response.choices[0].message
# Execute the tool locally
tool_call = assistant_message.tool_calls[0]
result = {"temperature": 22, "condition": "sunny"} # your actual function call here
# Send the tool result back
messages.append(assistant_message)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": json.dumps(result),
})
final_response = client.chat.completions.create(
model="Qwen/Qwen2.5-7B-Instruct",
messages=messages,
tools=tools,
)
print(final_response.choices[0].message.content)Lewatkan hasil tool sebagai item function_call_output dalam daftar input dari permintaan lanjutan.
user_message = {"role": "user", "content": "What's the weather like in San Francisco?"}
response = client.responses.create(
model="Qwen/Qwen2.5-7B-Instruct",
input=[user_message],
tools=tools,
stream=False,
)
tool_call = next(item for item in response.output if item.type == "function_call")
result = {"temperature": 22, "condition": "sunny"}
final_response = client.responses.create(
model="Qwen/Qwen2.5-7B-Instruct",
input=[
user_message,
tool_call.model_dump(exclude_none=True),
{"type": "function_call_output", "call_id": tool_call.call_id, "output": json.dumps(result)},
],
tools=tools,
stream=False,
)
print(final_response.output_text)Penalaran
Model penalaran mengeluarkan rantai pikiran tersembunyi sebelum jawaban akhir. Server mendeteksi rentang berpikir ini, menghapus pembatas dari jawaban yang terlihat, dan menampilkan teks penalaran di bidang khusus agar klien dapat merendernya secara terpisah.
- Chat Completions mengembalikan penalaran sebagai
reasoning_contentpada pesan asisten. - Responses API mengembalikan penalaran sebagai item output
reasoningyang mendahului itemmessage.
Deteksi penalaran bergantung pada template respons, yang memberi tahu server di mana rentang berpikir dimulai dan diakhiri. Server mencari template tersebut di dua tempat, secara berurutan.
- Atribut
response_templatedari tokenizer, jika model menyediakannya. - Fallback bawaan yang cocok dengan arsitektur model, untuk tokenizer yang belum menyertakan template.
Model yang tidak memiliki keduanya disajikan tanpa parsing respons. Teks terdekode mentah dikembalikan sebagai content dan tidak ada field reasoning yang ditampilkan, bahkan jika model mengeluarkan tag <think>...</think>.
Aktifkan penalaran di server
Gunakan --reasoning untuk mengontrol apakah template chat mengeluarkan token berpikir.
| Nilai | Perilaku |
|---|---|
auto (default) | Serahkan ke default template chat. |
on | Aktifkan thinking secara paksa dengan mengatur enable_thinking=True di kwargs template chat. |
off | Matikan fitur thinking dengan mengatur enable_thinking=False. |
transformers serve Qwen/Qwen3-1.7B --reasoning on
Tidak semua model mendukung penalaran.
--reasoninghanya berfungsi ketika template chat model menangani variabelenable_thinking(atau ketika tokenizer-nya menyatakan delimiter berpikir). Untuk model lain, flag ini diabaikan secara diam-diam.
--reasoning on dan --reasoning off bekerja dengan mengatur variabel template chat enable_thinking. Beberapa template chat menggunakan nama variabel yang berbeda untuk mengaktifkan/menonaktifkan thinking, atau menerima variabel tambahan yang mengubah cara prompt dirender. Sampaikan variabel template chat apa pun secara langsung dengan --chat-template-kwargs sebagai objek JSON.
transformers serve Qwen/Qwen3-1.7B \
--chat-template-kwargs '{"enable_thinking": true}'Klien juga dapat mengirim chat_template_kwargs di body permintaan untuk menimpa nilai default server untuk satu permintaan, tanpa perlu memulai ulang server.
Chat Completions
Respons non-streaming menyertakan reasoning_content di samping content pada pesan asisten.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<KEY>")
completion = client.chat.completions.create(
model="Qwen/Qwen3-1.7B",
messages=[{"role": "user", "content": "What is 17 * 23?"}],
)
message = completion.choices[0].message
print("reasoning:", message.reasoning_content)
print("answer:", message.content)Streaming memancarkan delta reasoning_content sebelum delta content. Gabungkan setiap field secara terpisah.
chunks = list(
client.chat.completions.create(
model="Qwen/Qwen3-1.7B",
messages=[{"role": "user", "content": "What is 17 * 23?"}],
stream=True,
)
)
reasoning = "".join(getattr(c.choices[0].delta, "reasoning_content", None) or "" for c in chunks)
content = "".join(c.choices[0].delta.content or "" for c in chunks)curl -X POST http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "Qwen/Qwen3-1.7B",
"messages": [{"role": "user", "content": "What is 17 * 23?"}],
"chat_template_kwargs": {"enable_thinking": true}
}'Respons mencakup reasoning_content pada pesan asisten.
{
"choices": [
{
"message": {
"role": "assistant",
"content": "17 * 23 = 391.",
"reasoning_content": "Let me compute 17 * 23. 17 * 20 = 340, 17 * 3 = 51, so 340 + 51 = 391."
},
"finish_reason": "stop",
"index": 0
}
]
}API Respons
Responses API mengembalikan penalaran sebagai item output reasoning terpisah yang mendahului item message.
response = client.responses.create(
model="Qwen/Qwen3-1.7B",
input="What is 17 * 23?",
stream=False,
)
reasoning_item = next(i for i in response.output if i.type == "reasoning")
message_item = next(i for i in response.output if i.type == "message")
print("reasoning:", reasoning_item.content[0].text)
print("answer:", message_item.content[0].text)Streaming membuka item penalaran terlebih dahulu dan memancarkan event response.reasoning_text.delta, kemudian menutupnya dan membuka item pesan untuk memancarkan event response.output_text.delta.
stream = client.responses.create(
model="Qwen/Qwen3-1.7B",
input="What is 17 * 23?",
stream=True,
)
for event in stream:
if event.type == "response.reasoning_text.delta":
print(event.delta, end="")
elif event.type == "response.output_text.delta":
print(event.delta, end="")Perjalanan bolak-balik multi-pusingan
Untuk percakapan multi-turn, sertakan teks penalaran dari respons sebelumnya dalam permintaan berikutnya. Server meneruskannya ke template chat, yang dapat merendernya sebagai bagian dari giliran asisten sebelumnya sehingga model dapat melihat proses berpikirnya sendiri yang lebih awal.
Lampirkan reasoning_content ke pesan asisten sebelumnya.
first = client.chat.completions.create(
model="Qwen/Qwen3-1.7B",
messages=[{"role": "user", "content": "What is 17 * 23?"}],
).choices[0].message
second = client.chat.completions.create(
model="Qwen/Qwen3-1.7B",
messages=[
{"role": "user", "content": "What is 17 * 23?"},
{
"role": "assistant",
"content": first.content,
"reasoning_content": first.reasoning_content,
},
{"role": "user", "content": "Now multiply that result by 2."},
],
)
print(second.choices[0].message.content)Lewatkan item reasoning sebelumnya sebagai item input sebelum pesan asisten.
first = client.responses.create(
model="Qwen/Qwen3-1.7B",
input="What is 17 * 23?",
stream=False,
)
reasoning_item = next(i for i in first.output if i.type == "reasoning")
message_item = next(i for i in first.output if i.type == "message")
second = client.responses.create(
model="Qwen/Qwen3-1.7B",
input=[
{"role": "user", "content": "What is 17 * 23?"},
reasoning_item.model_dump(exclude_none=True),
{"role": "assistant", "content": message_item.content[0].text},
{"role": "user", "content": "Now multiply that result by 2."},
],
stream=False,
)
print(second.output_text)Forwarding port
Port forwarding memungkinkan Anda menyajikan model dari server jarak jauh. Pastikan Anda memiliki akses SSH ke server, lalu jalankan perintah ini di mesin lokal Anda.
ssh -N -f -L 8000:localhost:8000 your_server_account@your_server_IP -p port_to_ssh_into_your_server
Reprodusibilitas
Lewatkan model sebagai argumen posisional untuk menghindari petunjuk model per permintaan dan menghasilkan eksekusi yang stabil serta dapat diulang.
transformers serve Qwen/Qwen2.5-0.5B-Instruct \
--continuous-batching \
--dtype "bfloat16"