Transformers documentation

Serve CLI

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

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/completions untuk permintaan teks, gambar, audio, dan video
  • /v1/completions untuk pelengkapan teks lama dari prompt bebas
  • /v1/responses mendukung Responses API
  • /v1/audio/transcriptions untuk transkripsi audio
  • /v1/systemone menjawab pertanyaan bertipe (pilihan, skor, ya/tidak) dengan probabilitas untuk setiap jawaban yang diizinkan
  • /v1/models menampilkan daftar model yang tersedia untuk integrasi pihak ketiga
  • /load_model mengalirkan 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

huggingface_hub
huggingface_hub (stream)
openai
openai (stream)
curl
curl (stream)
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 [...]

Penyelesaian berbasis gambar

huggingface_hub
huggingface_hub (stream)
openai
openai (stream)
curl
curl (stream)
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.

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).

huggingface_hub
huggingface_hub (stream)
openai
openai (stream)
curl
curl (stream)
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.

Jenis konten audio_url adalah 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_url adalah 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.

huggingface_hub
huggingface_hub (stream)
openai
openai (stream)
curl
curl (stream)
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..."

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
openai
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
  }
}

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

openai
openai (stream)
curl
curl (stream)
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 [...]

Respons berbasis gambar

API Respons juga mendukung input gambar, audio, dan video.

openai
openai (stream)
curl
curl (stream)
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.

Respons berbasis audio

openai
openai (stream)
curl
curl (stream)
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.

Jenis konten audio_url adalah 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_url adalah ekstensi yang bukan bagian dari standar OpenAI dan dapat berubah pada versi-versi mendatang.

Pemrosesan video memerlukan torchcodec. Instal dengan pip install torchcodec.

openai
openai (stream)
curl
curl (stream)
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..."

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
TypeSafe (TypeScript)
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?"}
    }
  }'

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 pertanyaancriteriaJawaban
choiceNama opsi yang dipetakan ke deskripsi, yang dapat berupa null.Opsi yang paling mungkin, probabilitas opsi, dan tingkat kepercayaan.
scoreDeskripsi level diurutkan dari terendah hingga tertinggi.Indeks level berbobot probabilitas, probabilitas, legenda, dan tingkat kepercayaan.
noulDeskripsi 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:

BidangArti
labelsLabel jawaban berdasarkan jenis pertanyaan, dalam urutan opsi (true, kemudian false untuk noul). Masing-masing harus berupa token tunggal yang berbeda dan dikenal.
temperatureSuhu positif berdasarkan jenis pertanyaan, diterapkan sebagai softmax(label_logits / temperature).
chat_templateTemplate 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.

BidangAda saatDeskripsi
statusSelaluloading, ready, atau error
modelSelaluKanonik model_id@revision
stagestatus == "loading"Salah satu dari processor, config, download, weights (lihat tahapan di bawah)
progresstahap download dan weightsObjek dengan current dan total (integer atau null)
cachedstatus == "ready"true jika model sudah berada di memori
messagestatus == "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).

TahapApakah ada kemajuan?Deskripsi
processorTidakMemuat tokenizer/processor
configTidakMemuat konfigurasi model
downloadYa (byte)Mengunduh file model
weightsYa (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.

fresh load
file yang di-cache
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}

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.

v1/chat/completions
v1/responses

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)

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_content pada pesan asisten.
  • Responses API mengembalikan penalaran sebagai item output reasoning yang mendahului item message.

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.

  1. Atribut response_template dari tokenizer, jika model menyediakannya.
  2. 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.

NilaiPerilaku
auto (default)Serahkan ke default template chat.
onAktifkan thinking secara paksa dengan mengatur enable_thinking=True di kwargs template chat.
offMatikan fitur thinking dengan mengatur enable_thinking=False.
transformers serve Qwen/Qwen3-1.7B --reasoning on

Tidak semua model mendukung penalaran. --reasoning hanya berfungsi ketika template chat model menangani variabel enable_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.

openai
openai (stream)
curl
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)

API Respons

Responses API mengembalikan penalaran sebagai item output reasoning terpisah yang mendahului item message.

openai
openai (stream)
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)

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.

v1/chat/completions
v1/responses

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)

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"
Update on GitHub