# Serve CLI

`transformers serve` CLI, yerel veya kendi barındırılan sunucular için hafif bir seçenektir. vLLM gibi özel çıkarım motorlarının getirdiği ek çalışma zamanı ve operasyonel yükten kaçınır. Değerlendirme, deneysel çalışmalar ve orta düzey yük dağıtımları için kullanın. [kesintisiz toplu işleme](../continuous_batching) gibi özellikler, verimliliği artırır ve gecikmeyi düşürür.

> [!TIP]
> Büyük ölçekli üretim dağıtımları için, arka uç olarak bir Transformer modeliyle birlikte vLLM veya SGLang kullanın. Daha fazla bilgi için [Inference backends](../community_integrations/transformers_as_backend) kılavuzuna göz atın.

`transformers serve` komutu, [OpenAI SDK](https://platform.openai.com/docs/overview) ile uyumlu yerel bir sunucu başlatır. Sunucu birçok üçüncü taraf uygulama ile çalışır ve aşağıdaki REST API'lerini destekler.

- metin, görüntü, ses ve video istekleri için `/v1/chat/completions`
- Serbest biçimli bir istemden gelen geleneksel metin tamamlamaları için `/v1/completions`
- `/v1/responses`, [Responses API](https://platform.openai.com/docs/api-reference/responses) destekler
- ses transkripsiyonları için `/v1/audio/transcriptions`
- `/v1/systemone`, izin verilen her cevap için bir olasılık vererek yazılı soruları (seçmeli, puanlı, evet/hayır) yanıtlar
- `/v1/models`, üçüncü taraf entegrasyonları için kullanılabilir modelleri listeler
- `/load_model`, model yükleme ilerlemesini SSE üzerinden iletir

Sunum bağımlılıklarını yükleyin.

```bash
pip install transformers[serving]
```

`transformers serve` komutunu çalıştırarak bir sunucu başlatın. Varsayılan sunucu adresi http://localhost:8000'dir.

```shell
transformers serve
```

## v1/chat/completions

`v1/chat/completions` API'si, [Chat Completions API](https://platform.openai.com/docs/api-reference/chat) üzerine kuruludur. LLM'ler, VLM'ler ve çok modlu modeller için metin, görüntü, ses ve video isteklerini destekler. `curl`, [InferenceClient](https://huggingface.co/docs/huggingface_hub/main/en/package_reference/inference_client#huggingface_hub.InferenceClient) veya [OpenAI](https://platform.openai.com/docs/quickstart) istemcisiyle kullanabilirsiniz.

### Metin tabanlı tamamlamalar

```python
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](https://huggingface.co/docs/huggingface_hub/main/en/package_reference/inference_client#huggingface_hub.InferenceClient) yazdırılmış bir dize döndürür.

```shell
The Transformers library is primarily known for its ability to create and manipulate large-scale language models [...]
```

```python
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](https://huggingface.co/docs/huggingface_hub/main/en/package_reference/inference_client#huggingface_hub.InferenceClient) yazdırılmış bir dize döndürür.

```shell
The Transformers library is primarily known for its ability to create and manipulate large-scale language models [...]
```

```python
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)
```

[OpenAI](https://platform.openai.com/docs/quickstart) istemcisi yazdırılmış bir dize döndürür.

```shell
The Transformers library is primarily known for its ability to create and manipulate large-scale language models [...]
```

```python
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="")
```

[OpenAI](https://platform.openai.com/docs/quickstart) istemcisi yazdırılmış bir dize döndürür.

```shell
The Transformers library is primarily known for its ability to create and manipulate large-scale language models [...]
```

```shell
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
  }'
```

Komut bir JSON dizesi döndürür.

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

```shell
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
  }'
```

Komut, parçacıkların bir akışını döndürür.

```shell
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":""}

(...)
```

### Görüntü tabanlı tamamlamalar

```python
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](https://huggingface.co/docs/huggingface_hub/main/en/package_reference/inference_client#huggingface_hub.InferenceClient) yazdırılmış bir dize döndürür.

```xmp
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.
```

```python
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](https://huggingface.co/docs/huggingface_hub/main/en/package_reference/inference_client#huggingface_hub.InferenceClient) yazdırılmış bir dize döndürür.

```xmp
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.
```

```python
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)
```

[OpenAI](https://platform.openai.com/docs/quickstart) istemcisi yazdırılmış bir dize döndürür.

```xmp
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.
```

```python
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="")
```

[OpenAI](https://platform.openai.com/docs/quickstart) istemcisi yazdırılmış bir dize döndürür.

```xmp
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.
```

```shell
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
  }'
```

Komut bir JSON dizesi döndürür.

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

```shell
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
  }'
```

Komut, parçacıkların bir akışını döndürür.

```shell
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":""}

(...)
```

### Ses tabanlı tamamlamalar

[Gemma 4](https://huggingface.co/google/gemma-4-E2B-it) ve [Qwen2.5-Omni](https://huggingface.co/Qwen/Qwen2.5-Omni-3B) gibi çok modlu modeller, OpenAI `input_audio` içerik türü üzerinden ses girdisi kabul eder. Sesi Base64 ile kodlayın ve biçimi (`mp3` veya `wav`) belirtin.

```python
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](https://huggingface.co/docs/huggingface_hub/main/en/package_reference/inference_client#huggingface_hub.InferenceClient) yazdırılmış bir dize döndürür.

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

```python
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](https://huggingface.co/docs/huggingface_hub/main/en/package_reference/inference_client#huggingface_hub.InferenceClient) yazdırılmış bir dize döndürür.

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

```python
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)
```

[OpenAI](https://platform.openai.com/docs/quickstart) istemcisi yazdırılmış bir dize döndürür.

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

```python
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="")
```

[OpenAI](https://platform.openai.com/docs/quickstart) istemcisi yazdırılmış bir dize döndürür.

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

```shell
# 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.json
```

Komut bir JSON dizesi döndürür.

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

```shell
# 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.json
```

Komut, parçacıkların bir akışını döndürür.

```shell
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":""}

(...)
```

> [!WARNING]
> `audio_url` içerik türü, OpenAI standardının bir parçası olmayan bir uzantıdır ve gelecekteki sürümlerde değişebilir.

Ayrıca, base64 kodlamayı atlamak için ses dosyasını `audio_url` içerik türüyle URL üzerinden de iletebilirsiniz.

```python
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"}},
            ],
        }
    ],
)
```

### Video tabanlı tamamlamalar

> [!WARNING]
> `video_url` içerik türü, OpenAI standardının bir parçası olmayan bir uzantıdır ve gelecekteki sürümlerde değişebilir.

Video girişi için `video_url` içerik türünü kullanın. Model ses destekliyorsa (ör. Gemma 4, Qwen2.5-Omni), sunucu videodan ses kaydını çıkarır ve görsel karelerle birlikte işler.

> [!TIP]
> Video işleme [torchcodec](https://github.com/pytorch/torchcodec) gerektirir. `pip install torchcodec` komutuyla yükleyin.

```python
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](https://huggingface.co/docs/huggingface_hub/main/en/package_reference/inference_client#huggingface_hub.InferenceClient) yazdırılmış bir dize döndürür.

```
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..."
```

```python
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](https://huggingface.co/docs/huggingface_hub/main/en/package_reference/inference_client#huggingface_hub.InferenceClient) yazdırılmış bir dize döndürür.

```
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..."
```

```python
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)
```

[OpenAI](https://platform.openai.com/docs/quickstart) istemcisi yazdırılmış bir dize döndürür.

```
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..."
```

```python
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="")
```

[OpenAI](https://platform.openai.com/docs/quickstart) istemcisi yazdırılmış bir dize döndürür.

```
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..."
```

```shell
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
  }'
```

Komut bir JSON dizesi döndürür.

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

```shell
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
  }'
```

Komut, parçacıkların bir akışını döndürür.

```shell
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":""}

(...)
```

### Çok turlu sohbetler[[completions]]

Çok turlu bir sohbet için, `messages` listesine `user` ve `assistant` rolleriyle sırayla değişen tam sohbet geçmişini ekleyin. Tüm OpenAI uyumlu sunucularda olduğu gibi API durumdan bağımsızdır (stateless), bu nedenle her istek tam sohbet geçmişini içermelidir.

```python
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)
```

Takip sorusu "Orada kaç kişi yaşıyor?" önceki bağlama dayanır, bu yüzden model Paris hakkında yanıt verir.

```
As of 2021, the population of Paris is approximately 2.2 million people.
```

## v1/completions

`v1/completions` API’si, [eski Completions API’sine](https://platform.openai.com/docs/api-reference/completions) dayanır. `/v1/chat/completions`’ün aksine, sohbet mesajları yerine serbest biçimli bir `prompt` alır ve üretilen metni `choices[].text` içinde döndürür. Bu, sohbet şablonuna ihtiyaç duyulmayan temel (non-instruct) modeller ve metin tamamlama görevleri için faydalıdır. Ayrıca, ortadan doldurma (fill-in-the-middle) metin ekleme işlemleri için `suffix` parametresini de destekler.

```shell
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
  }'
```

Komut aşağıdaki yanıtı döndürür.

```json
{
  "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
  }
}
```

```python
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)
```

[OpenAI](https://platform.openai.com/docs/quickstart) istemcisi aşağıdakileri döndürür.

```shell
 Paris, and the capital of the United States is Washington, D.C.
```

Ayrıca Streaming de desteklenmektedir.

```python
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](https://platform.openai.com/docs/api-reference/responses), OpenAI'nin üretim için en yeni API uç noktasıdır. Durumlu etkileşimleri destekler ve bir modelin yeteneklerini genişletmek için yerleşik araçları entegre eder. OpenAI, yeni projeler için Chat Completions API yerine Responses API kullanmayı [önerir](https://platform.openai.com/docs/guides/migrate-to-responses).

`v1/responses` API'si, `curl` komutu ve [OpenAI](https://platform.openai.com/docs/quickstart) istemcisi aracılığıyla metin, görüntü, ses ve video isteklerini destekler.

### Metin tabanlı yanıtlar

```python
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)
```

[OpenAI](https://platform.openai.com/docs/quickstart) istemcisi yazdırılmış bir dize döndürür.

```shell
Once upon a time, in a faraway land, there lived a beautiful unicorn named Luna [...]
```

```python
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="")
```

[OpenAI](https://platform.openai.com/docs/quickstart) istemcisi yazdırılmış bir dize döndürür.

```shell
Once upon a time, in a faraway land, there lived a beautiful unicorn named Luna [...]
```

```shell
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
  }'
```

Komut bir JSON dizesi döndürür.

```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"
}
```

```shell
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
  }'
```

Komut, parçacıkların bir akışını döndürür.

```shell
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"}

(...)
```

### Görüntü tabanlı yanıtlar

Responses API ayrıca görüntü, ses ve video girdilerini de destekler.

```python
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)
```

[OpenAI](https://platform.openai.com/docs/quickstart) istemcisi yazdırılmış bir dize döndürür.

```xmp
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.
```

```python
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="")
```

[OpenAI](https://platform.openai.com/docs/quickstart) istemcisi yazdırılmış bir dize döndürür.

```xmp
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.
```

```shell
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
  }'
```

Komut bir JSON dizesi döndürür.

```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"
}
```

```shell
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
  }'
```

Komut, parçacıkların bir akışını döndürür.

```shell
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"}

(...)
```

### Ses tabanlı yanıtlar

```python
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)
```

[OpenAI](https://platform.openai.com/docs/quickstart) istemcisi yazdırılmış bir dize döndürür.

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

```python
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="")
```

[OpenAI](https://platform.openai.com/docs/quickstart) istemcisi yazdırılmış bir dize döndürür.

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

```shell
# 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.json
```

Komut bir JSON dizesi döndürür.

```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"
}
```

```shell
# 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.json
```

Komut, parçacıkların bir akışını döndürür.

```shell
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"}

(...)
```

> [!WARNING]
> `audio_url` içerik türü, OpenAI standardının bir parçası olmayan bir uzantıdır ve gelecekteki sürümlerde değişebilir.

Ayrıca, base64 kodlamayı atlamak için ses dosyasını `audio_url` içerik türüyle URL üzerinden de iletebilirsiniz.

```python
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,
)
```

### Video tabanlı yanıtlar

> [!WARNING]
> `video_url` içerik türü, OpenAI standardının bir parçası olmayan bir uzantıdır ve gelecekteki sürümlerde değişebilir.

> [!TIP]
> Video işleme [torchcodec](https://github.com/pytorch/torchcodec) gerektirir. `pip install torchcodec` komutuyla yükleyin.

```python
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)
```

[OpenAI](https://platform.openai.com/docs/quickstart) istemcisi yazdırılmış bir dize döndürür.

```
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..."
```

```python
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="")
```

[OpenAI](https://platform.openai.com/docs/quickstart) istemcisi yazdırılmış bir dize döndürür.

```
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..."
```

```shell
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
  }'
```

Komut bir JSON dizesi döndürür.

```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"
}
```

```shell
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
  }'
```

Komut, parçacıkların bir akışını döndürür.

```shell
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"}

(...)
```

### Çok turlu sohbetler[[responses]]

Çok turlu sohbetler için, `input` alanına `role` anahtarlarına sahip bir mesaj listesi iletin. Tüm OpenAI uyumlu sunucularda olduğu gibi API durumdan bağımsızdır (stateless), bu nedenle her istek tam sohbet geçmişini içermelidir.

```python
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)
```

Takip sorusu "Orada kaç kişi yaşıyor?" önceki bağlama dayanır, bu yüzden model Paris hakkında yanıt verir.

```
As of 2021, Paris has a population of approximately 2.8 million people.
```

## v1/systemone

`v1/systemone` uç noktası, [TypeSafe’in System One API’sini](https://api.typesafe.ai/openapi.json) izleyerek paylaşılan bir `state` hakkında tipli soruları yanıtlar. Destek biletini yönlendirme, aciliyet derecelendirme veya bir eylem seçme gibi kararlar için kullanın.

Model, metin üretmeden, izin verilen yanıtları tek bir toplu ileri geçişte puanlar. Bu uç nokta, sohbet şablonu olan otoregresif modelleri destekler;

Bir model, değerlendirilecek durumu ve isimle eşleştirilmiş soruları gönderin:

```shell
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?"}
    }
  }'
```

Node.js 20 veya daha yeni sürümler için [TypeSafe SDK](https://github.com/typesafe-ai/typesafe-sdk-js)'yı yükleyin:

```shell
npm install @typesafe-ai/sdk
```

`baseURL` değerini sunucu köküne ayarlayın; SDK `/v1/systemone` ekler. SDK bir API anahtarı gerektirir, ancak yerel sunucuyla bir yer tutucu çalışır.

```typescript
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);
```

İstemci, seçilen ekibi, aciliyet puanını ve müşterinin sinirli olma olasılığını yazdırır. Örneğin:

```shell
technical
1.6739138662815094
0.851952850818634
```

Cevaplar aynı soru adlarını kullanır. Örneğin:

```json
{
  "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}
}
```

| Soru türü | `criteria` | Cevap |
| :--- | :--- | :--- |
| `choice` | `null` olabilecek açıklamalara eşlenen seçenek adları. | En olası seçenek, seçenek olasılıkları ve güven düzeyi. |
| `score` | En düşükten en yükseğe sıralanmış seviye açıklamaları. | Olasılık ağırlıklı seviye indeksi, olasılıklar, bir lejant ve güven düzeyi. |
| `noul` | `true` ve `false` için isteğe bağlı açıklamalar. | `true` olasılığı. |

`state`, isteğe bağlı `instructions` ve açıklamalar metin veya JSON nesneleri ve dizileri içerebilir. Her istek, soru başına 1–26 seçenek veya puan seviyesi ile en fazla 64 soru kabul eder.

Görüntü yeteneğine sahip modeller için, en fazla dört `data:image/...;base64,...` URL'si içeren bir `images` dizisi ekleyin. Her soru aynı görüntüleri alır. Modelin işlemcisi ve sohbet şablonu görüntüleri desteklemelidir; uzak görüntü URL'leri kabul edilmez.

### Karar yapılandırması

Karar modelleri henüz istemleri, yanıt etiketlerini ve kalibrasyon ayarlarını depolamak için ortak bir standarda sahip değildir. Bu ayarlar model uygulamaları arasında farklılık gösterdiğinden, `--decision-config` ile bunları açıkça belirleyebilirsiniz. Özel karar başlıklarına sahip modeller hâlâ uyumlu bir uygulama gerektirir; bu dosya yalnızca istem biçimlendirmesini ve sonraki token puanlamasını yapılandırır.

Varsayılan olarak, sorular yedek bir istem ve düşünme özelliği devre dışı bırakılmış model sohbet şablonunu kullanır. Seçenekler ve puanlar için etiketler `A`–`Z`, boole değerleri için ise `Yes`/`No` şeklindedir. Olasılıklar, bu etiketler üzerinde sıcaklık 1'de hesaplanan softmax'tır.

Bir model için bu varsayılanları geçersiz kılmak için `--decision-config` parametresini iletin:

```shell
transformers serve openjev/openjev --decision-config decision.json
```

JSON dosyası üç isteğe bağlı alanı destekler:

| Alan | Anlam |
| :--- | :--- |
| `labels` | Soru türüne göre, seçenek sırasına göre (`noul` için `true`, ardından `false`) cevap etiketlerini belirtin. Her biri ayrı, bilinen tek bir jeton olmalıdır. |
| `temperature` | Soru türüne göre pozitif sıcaklıklar, `softmax(label_logits / temperature)` olarak uygulanır. |
| `chat_template` | Sohbet biçimlendirmesini ve asistan önekini de içeren, tam istemin yerini alan satır içi Jinja şablonu. |

Örneğin, varsayılan istemciyi koruyarak etiketleri ve kalibrasyonu değiştirmek için:

```json
{
  "labels": {"noul": ["A", "B"]},
  "temperature": {"choice": 0.85, "score": 0.85, "noul": 1.5547129}
}
```

Özel bir şablon, standart `messages` alanının yanı sıra ham `state`, `images` ve `question` alanlarını alır. Soru, `name`, `type`, `instructions`, `options`, `labels`, `descriptions` ve `legend` alanlarını açığa çıkarır; seçenekler, etiketler ve açıklamalar aynı sırayı paylaşır. Yedek ifadelerin yerini almak için bu alanları ve yapılandırılmış değerleri görüntülemek için `tojson` kullanın. Görsel girdiler için şablonlar, modelin görsel yer tutucularını içermelidir.

Dosya, başlangıçta yüklenir ve yalnızca `/v1/systemone` için geçerlidir. Atlanan ayarlar varsayılan değerlerini korur; karar yapılandırması, checkpoint'ten otomatik olarak okunmaz.

## v1/audio/transcriptions

`v1/audio/transcriptions` uç noktası, konuşmadan metne modelleri kullanarak sesleri transkribe eder. [Ses transkripsiyonu API'si](https://platform.openai.com/docs/api-reference/audio/createTranscription) biçimini izler.

```shell
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"
```

Komut aşağıdaki yanıtı döndürür.

```shell
{
  "text": "Transcribed text from the audio file",
}
```

## v1/models

`v1/models` uç noktası, yerel Hugging Face önbelleğinizi tarar ve indirilen modellerin listesini OpenAI ile uyumlu biçimde döndürür. Üçüncü taraf araçlar, kullanılabilir modelleri keşfetmek için bu uç noktayı kullanır.

`transformers serve` komutunu çalıştırmadan önce bir model indirin.

```bash
transformers download Qwen/Qwen2.5-0.5B-Instruct
```

İndirme tamamlandıktan sonra model, `/v1/models` yanıtlarında görünür.

```shell
curl http://localhost:8000/v1/models
```

Uç nokta, kullanılabilir modelleri içeren bir JSON nesnesi döndürür.

## Modellerin yüklenmesi

`/load_model` uç noktası bir modeli önceden yükler ve ilerlemeyi [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) (SSE) üzerinden iletir. `transformers chat` CLI aracı bunu otomatik olarak kullanır; böylece kullanıcılar asılı kalan bir istem yerine indirme ve yükleme ilerlemesini görür. Çıkarım isteklerini göndermeden önce bir modeli ısıtmak için kullanın.

### İstek

```shell
curl -N -X POST http://localhost:8000/load_model \
  -H "Content-Type: application/json" \
  -d '{"model": "Qwen/Qwen2.5-0.5B-Instruct"}'
```

`model` alanı, isteğe bağlı olarak `@revision` son ekine sahip bir Hugging Face model tanımlayıcısıdır (`Qwen/Qwen2.5-0.5B-Instruct@main`). Revizyon belirtilmezse varsayılan olarak `main` kullanılır.

### Yanıt

Yanıt bir SSE akışıdır (`Content-Type: text/event-stream`). Her çerçeve, bir `data:` satırında JSON nesnesidir.

```
data: {"status": "loading", "model": "Qwen/Qwen2.5-0.5B-Instruct@main", "stage": "processor"}
```

Her olay en azından bir `status` ve `model` alanı içerir. Ek alanlar duruma bağlıdır.

| Alan | Bulunur | Açıklama |
|-------|-------------|-------------|
| `status` | Her zaman | `loading`, `ready` veya `error` |
| `model` | Her zaman | Kanonik `model_id@revision` |
| `stage` | `status == "loading"` | `processor`, `config`, `download`, `weights` (aşağıdaki aşamaları bkz.) |
| `progress` | `download` ve `weights` aşamaları | `current` ve `total` (tamsayı veya null) içeren nesne |
| `cached` | `status == "ready"` | Model zaten bellekteyse `true` |
| `message` | `status == "error"` | Hata açıklaması |

### Aşamalar

Yükleme, bu aşamalardan sırasıyla geçer. Bazıları atlanabilir (yerel olarak önbelleğe alınmışsa `download` atlanır).

| Aşama | İlerleme var mı? | Açıklama |
|-------|---------------|-------------|
| `processor` | Hayır | Tokenizör/işleyiciyi yükleme |
| `config` | Hayır | Model yapılandırmasını yükleme |
| `download` | Evet (bayt) | Model dosyalarını indirme |
| `weights` | Evet (öğeler) | Ağırlık tensörlerini belleğe yükleme |

Akış, tam olarak bir son olayla biter: `ready` (başarı) veya `error` (başarısızlık).

## Zaman aşımı

`transformers serve`, herhangi bir model için gelen istekleri işler. Her model gerektikçe yüklenir ve GPU belleğinde kalır. GPU belleğini boşaltmak için modeller, 300 saniyelik bir hareketsizlikten sonra otomatik olarak boşaltılır. Farklı bir değer (saniye cinsinden) belirlemek için `--model-timeout` parametresini kullanın veya boşaltmayı devre dışı bırakmak için `-1` değerini atayın.

```shell
transformers serve --model-timeout 400
```

### Örnekler yükleniyor

Aşağıdaki örnekler, yeni indirilen bir modelin, yerel önbelleğinizden yüklenen bir modelin (indirme aşamasını atlar) ve zaten bellekte bulunan bir modelin yanıtlarını göstermektedir.

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

## Araç çağrısı

`transformers serve` sunucusu, OpenAI tarzı fonksiyon çağrılarını destekler. Araç kullanımı için eğitilen modeller, uygulamanızın çalıştırdığı yapılandırılmış fonksiyon çağrıları üretir.

> [!NOTE]
> Tool calling, tokenizer'ı tool call token'ları bildiren herhangi bir modelle çalışır. Qwen ve Gemma 4 hazır olarak çalışır. Belirli bir model için destek istemek için bir [issue](https://github.com/huggingface/transformers/issues/new/choose) açın.

Araçları, OpenAI biçimini izleyen bir işlev spesifikasyonları listesi olarak tanımlayın.

```py
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"]
      }
    }
  }
]
```

[create](https://platform.openai.com/docs/api-reference/responses/create) içindeki `extra_body` argümanına [GenerationConfig](/docs/transformers/main/tr/main_classes/text_generation#transformers.GenerationConfig) parametreleri geçirerek üretimi özelleştirin.

```py
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)
```

### Çok turlu araç çağrısı

Model bir araç çağrısı döndürdükten sonra, işlevi yerel olarak çalıştırın ve ardından modelin nihai yanıtını almak için sonucu bir takip isteğinde geri gönderin. Bu desen, iki API arasında hafifçe farklılık gösterir. Tam kullanım kılavuzu için [OpenAI function calling guide](https://developers.openai.com/api/docs/guides/function-calling?api-mode=chat) belgesine bakın.

Aşağıdaki örnekler, yukarıda tanımlanan `tools` listesini yeniden kullanır.

Araç sonucunu, eşleşen `tool_call_id` ile `role: "tool"` mesajı olarak iletin.

```py
# 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)
```

Araç sonucunu, devam isteğindeki `input` listesine bir `function_call_output` öğesi olarak iletin.

```py
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)
```

## Mantık yürütme

Mantık yürütme modelleri, nihai cevaptan önce gizli bir düşünce zinciri üretir. Sunucu bu düşünce aralıklarını algılar, görünür cevaptan ayraçları kaldırır ve istemcilerin bu metni ayrı olarak görüntüleyebilmesi için mantık yürütme metnini ayrı bir alanda sunar.

- Chat Completions, akıl yürütme çıktısını asistan mesajında `reasoning_content` olarak döndürür.
- Responses API, `message` öğesinden önce gelen `reasoning` çıktı öğesi olarak akıl yürütmeyi döndürür.

Mantık yürütme algılama, sunucuya bir düşünme aralığının nerede başladığını ve nerede bittiğini bildiren bir [yanıt şablonuna](../chat_response_parsing) dayanır. Sunucu, sırasıyla iki yerde buna bakar.

1. Model bir `response_template` özniteliği ile birlikte dağıtılıyorsa, tokenizörün `response_template` özniteliği.
2. Henüz bir şablon içermeyen tokenizörler için, model mimarisine göre eşleşen yerleşik bir yedekleme.

Hiçbiri olmayan modeller, yanıt ayrıştırması yapılmadan sunulur. Ham çözümlenmiş metin `content` olarak döndürülür ve model `<think>...</think>` etiketleri üretse bile bir akıl yürütme alanı gösterilmez.

### Sunucuda akıl yürütmeyi etkinleştirin

Düşünme jetonlarının çıkıp çıkmayacağını kontrol etmek için `--reasoning` bayrağını kullanın.

| Değer | Davranış |
|---|---|
| `auto` (varsayılan) | Sohbet şablonunun varsayılanına bırakın. |
| `on` | Sohbet şablonu kwargs'larında `enable_thinking=True` olarak ayarlayarak düşünmeyi zorla etkinleştirin. |
| `off` | `enable_thinking=False` olarak ayarlayarak düşünmeyi devre dışı bırakın. |

```sh
transformers serve Qwen/Qwen3-1.7B --reasoning on
```

> [!WARNING]
> Tüm modeller akıl yürütme (reasoning) desteklemez. `--reasoning` yalnızca modelin sohbet şablonu `enable_thinking` değişkenini işlediğinde (veya tokenizer'ı düşünme ayraçlarını beyan ettiğinde) çalışır. Diğer modellerde bu bayrak sessizce yoksayılır.

`--reasoning on` ve `--reasoning off`, `enable_thinking` sohbet şablonu değişkenini ayarlayarak çalışır. Bazı sohbet şablonları düşünmeyi açmak/kapatmak için farklı bir değişken adı kullanır veya istemin nasıl işlendiğini değiştiren ek değişkenler kabul eder. Herhangi bir sohbet şablonu değişkenini `--chat-template-kwargs` ile JSON nesnesi olarak doğrudan iletebilirsiniz.

```sh
transformers serve Qwen/Qwen3-1.7B \
  --chat-template-kwargs '{"enable_thinking": true}'
```

İstemciler, sunucuyu yeniden başlatmadan tek bir istek için sunucu varsayılanlarını geçersiz kılmak amacıyla istek gövdesine `chat_template_kwargs` gönderebilir.

### Chat Tamamlamaları

Akış dışı yanıtlar, asistan mesajında `content` ile birlikte `reasoning_content` alanını da içerir.

```python
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, `content` deltalarından önce `reasoning_content` deltalarını yayar. Her alanı ayrı ayrı birleştirin.

```python
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)
```

```shell
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}
  }'
```

Yanıt, asistan mesajında `reasoning_content` içerir.

```json
{
  "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
    }
  ]
}
```

### Responses API

Responses API, `message` öğesinden önce gelen ayrı bir `reasoning` çıktı öğesi olarak akıl yürütmeyi döndürür.

```python
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, akıl yürütme öğesini önce açar ve `response.reasoning_text.delta` olaylarını yayar, ardından bu öğeyi kapatır ve mesaj öğesini açarak `response.output_text.delta` olaylarını yayar.

```python
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="")
```

### Çok turlu gidiş-dönüş

Çok turlu sohbetlerde, önceki yanıtın akıl yürütme metnini bir sonraki isteğe dahil edin. Sunucu bunu sohbet şablonuna iletir; şablon, bunu önceki asistan turunun bir parçası olarak işleyebilir, böylece model kendi önceki düşünce sürecini görür.

Önceki asistan mesajına `reasoning_content` ekleyin.

```python
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)
```

Asistan mesajından önce, önceki `reasoning` öğesini bir girdi öğesi olarak geri iletin.

```python
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)
```

## Port yönlendirme

Port yönlendirme, modelleri uzak bir sunucudan sunmanızı sağlar. Sunucuya SSH erişiminiz olduğundan emin olun, ardından bu komutu yerel makinenizde çalıştırın.

```bash
ssh -N -f -L 8000:localhost:8000 your_server_account@your_server_IP -p port_to_ssh_into_your_server
```

## Tekrarlanabilirlik

Her istekte model ipuçlarını önlemek ve kararlı, tekrarlanabilir çalıştırmalar elde etmek için bir modeli konumsal argüman olarak iletin.

```sh
transformers serve Qwen/Qwen2.5-0.5B-Instruct \
  --continuous-batching \
  --dtype "bfloat16"
```

