# CurlとHTTPをUnslothに接続

Unsloth は、Unsloth が起動したポートの同じベース URL 上で、OpenAI/Anthropic 互換の 3 つのワイヤーフォーマットを公開しています。これらはすべて、 `Authorization: Bearer sk-unsloth-…` ヘッダーを受け取り、設定するかどうかに応じて JSON または SSE を返します `stream`。 \
\
このページでは、レシピをエンドポイントごとにまとめています（`/v1/chat/completions`, `/v1/messages`, `/v1/responses`, `/v1/models`）そして最後に、Unsloth に組み込まれている共通セクションとして **server-side tools**を紹介します。これらはすべてのチャットエンドポイントで動作します。

{% hint style="info" %}
どの URL / キー / モデル名を使えばよいかわからない場合は、まず API 概要を読んでください。そこでは Unsloth の起動、モデルの読み込み、そして `sk-unsloth-…` キーの作成について順を追って説明しています。
{% endhint %}

### 🔑 認証

すべてのリクエストには `Authorization` ヘッダーが必要です:

```
Authorization: Bearer sk-unsloth-xxxxxxxxxxxx
```

キーをシェルの履歴に残さないために、一度キーを export して環境変数を参照してください:

```bash
export UNSLOTH_STUDIO_AUTH_TOKEN=sk-unsloth-xxxxxxxxxxxx
```

以下のスニペットでは、わかりやすさのためにキーを `sk-unsloth-xxxxxxxxxxxx` として直接書いています。実際には、 `$UNSLOTH_STUDIO_API_KEY`.

### 📋 読み込まれているモデルを一覧表示

```bash
curl http://localhost:8888/v1/models \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxxxx"
```

レスポンス:

```json
{
  "object": "list",
  "data": [
    {"id": "unsloth/gemma-3-27b-it-GGUF", "object": "model", "owned_by": "local"}
  ]
}
```

<figure><img src="/files/b42b361f2bc271b628e0484e7b43cb7afe782af3" alt=""><figcaption></figcaption></figure>

リクエストで `id` フィールドが `"model"` 値を必要とする場合は常にこれを使ってください（または opencode のようなクライアントが **Model ID**).

### 💬 Chat Completions（`/v1/chat/completions`)

OpenAI Chat Completions 方言です。最も広い互換性を持つインターフェースです。OpenAI SDK、opencode、Cursor、Continue、Cline、Open WebUI、SillyTavern、および大半の OpenAI 互換ツールで動作します。

#### 基本的なリクエスト

```bash
curl http://localhost:8888/v1/chat/completions \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "default",
    "messages": [{"role": "user", "content": "Hello"}]
  }'
```

<figure><img src="/files/418734e6ab34f2e5512fa7f98fd44c7327b0719a" alt=""><figcaption></figcaption></figure>

#### ストリーミング

追加します `"stream": true` すると、レスポンスは Server-Sent Events（`text/event-stream`）に切り替わります。 `curl` には、バイトが到着したらすぐにフラッシュするよう `--no-buffer` (`-N`):

```bash
curl -N http://localhost:8888/v1/chat/completions \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen-local",
    "messages": [{"role": "user", "content": "ローカルで実行される LLM について俳句を書いてください。"}],
    "stream": true
  }'
```

レスポンスの各行は次のようになります `data: {"choices":[{"delta":{"content":"..."}}]}`、最後は `data: [DONE]`.

<figure><img src="/files/b44828078e25a81b1e2f5986819bd42ac8870e52" alt=""><figcaption></figcaption></figure>

#### 画像（ビジョン）

画像を `image_url` としてユーザーメッセージ内の content パートに添付します。URL には HTTPS または base64 の `data:` URI:

```bash
# ローカルファイルを base64 として埋め込む（簡潔さのため一部省略）
IMG=$(base64 -w 0 test.jpg)

cat > /tmp/request.json <<EOF
{
  "model":"default",
  "messages":[{"role":"user","content":[
    {"type":"text","text":"画像を説明してください。"},
    {"type":"image_url","image_url":{"url":"data:image/jpeg;base64,$IMG"}}
  ]}],
  "max_tokens":200,
  "stream":false
}
EOF

curl http://localhost:8888/v1/chat/completions \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d @/tmp/request.json
```

{% hint style="info" %}
読み込まれたモデルはマルチモーダルである必要があります。テキスト専用モデルを読み込んだ場合、リクエスト自体は構造上成功しても、モデルは画像を処理しません。
{% endhint %}

<figure><img src="/files/5fb512a832980ec06bd71b3c8c7ceb35f67ea4e7" alt=""><figcaption></figcaption></figure>

#### 関数呼び出し（OpenAI tools）

OpenAI スタイルの `tools` と（任意で） `tool_choice`を渡します。クライアントは各ツール呼び出しを実行し、次のターンで結果を返します。

```bash
curl http://localhost:8888/v1/chat/completions \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model":"default",
    "input":[{"role":"user","content":"パリの天気はどうですか？"}],
    "tools":[{
      "type":"function",
      "name":"get_weather",
      "description":"都市の現在の天気を取得します。",
      "parameters":{
        "type":"object",
        "properties":{"city":{"type":"string"}},
        "required":["city"]
      }
    }],
    "tool_choice":"required"
  }' | jq '.output, .usage'
```

<figure><img src="/files/d5074fb4ca36311ce10f28b93906466d486023c8" alt=""><figcaption></figcaption></figure>

### 📨 Anthropic Messages（`/v1/messages`)

Claude Code、Anthropic SDK、OpenClaw、および Messages API を話す任意のクライアントで使われる、Unsloth の Anthropic 互換方言です。

#### 基本的なリクエスト

```bash
curl http://localhost:8888/v1/messages \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "default",
    "max_tokens": 1024,
    "messages": [{"role": "user", "content": "Hello"}]
  }'
```

{% hint style="warning" %}
`max_tokens` は `/v1/messages` では必須です（ `/v1/chat/completions`).
{% endhint %}

<figure><img src="/files/511f5d478b13045ad0cf791d036d572a77d25e7e" alt=""><figcaption></figcaption></figure>

#### ストリーミング

```bash
curl -N http://localhost:8888/v1/messages \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen-local",
    "max_tokens": 1024,
    "messages": [{"role": "user", "content": "LoRA を 2 文で説明してください。"}],
    "stream": true
  }'
```

イベントは Anthropic の SSE 形式に従います: `message_start`, `content_block_start`, `content_block_delta`, `content_block_stop`, `message_delta`, `message_stop`、さらに Unsloth 独自の `tool_result` イベントがあり、これはサーバー側ツールの出力用です。

#### 画像（ビジョン）

Anthropic スタイルの画像コンテンツでは、 `source` ブロックに base64 データを使用します:

```bash
IMG=$(base64 -w 0 test.jpg)

cat > /tmp/request.json <<EOF
{
  "messages":[{"role":"user","content":[
    {"type":"text","text":"画像を説明してください。"},
    {"type":"image","source":{"type":"base64","media_type":"image/jpeg","data":"$IMG"}}
  ]}],
  "max_tokens":200,
  "stream":true
}
EOF

curl -s http://3.128.175.236:8888/v1/messages \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxx" \
  -H "Content-Type: application/json" \
  -d @/tmp/request.json
```

<figure><img src="/files/e7a10607c2dfb9258663d54111657edfa6f48629" alt=""><figcaption></figcaption></figure>

#### ツール呼び出し（Anthropic tools）

```bash
curl http://localhost:8888/v1/messages \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen-local",
    "max_tokens": 1024,
    "messages": [{"role": "user", "content": "東京の天気はどうですか？"}],
    "tools": [
      {
        "name": "get_weather",
        "description": "都市の現在の天気を取得します",
        "input_schema": {
          "type": "object",
          "properties": {
            "city": {"type": "string"}
          },
          "required": ["city"]
        }
      }
    ],
    "tool_choice": {"type": "auto"}
  }'
```

`tool_choice` 値は OpenAI 方言では次のように対応します: Anthropic `auto` → OpenAI `auto`, Anthropic `any` → OpenAI `required`, Anthropic `{type: "tool", name: "x"}` → OpenAI `{type: "function", function: {name: "x"}}`, Anthropic `none` → OpenAI `none`.

<figure><img src="/files/05d465dfc1a1eae24a650712c8fc803379434078" alt=""><figcaption></figcaption></figure>

### 🧬 Responses（`/v1/responses`)

Unsloth はさらに新しい **OpenAI Responses API**, にも対応しています。これは Codex や最近の他の OpenAI クライアントが移行したプロトコルです。

```bash
curl http://localhost:8888/v1/responses \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen-local",
    "input": "1 文のあいさつを書いてください。"
  }'
```

<figure><img src="/files/ff7d6c7893c163da26e4e871094cf4cff4f4a696" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/a93b3af4d0fd8e8d69c40f5e47c361c8c634d89a" alt=""><figcaption></figcaption></figure>

ストリーミングは Chat Completions と同じように動作します。追加します `"stream": true` そして次でパイプします `-N`.

### 🧰 Unsloth サーバーサイドツール（簡略記法）

クライアント側の関数呼び出しに加えて、Unsloth は **Python**, **bash**、および **web search** をサーバー側で実行し、その結果をカスタム `tool_result` イベントとしてストリーミングで返せます。これは、ツール呼び出しをクライアント経由で往復させる必要なく、Unsloth を最初から「本物」のエージェントのように感じさせる機能です。

次の追加フィールドを **いずれかの** `/v1/chat/completions` または `/v1/messages`:

| フィールド             | 型               | 注記                                                          |
| ----------------- | --------------- | ----------------------------------------------------------- |
| `enable_thinking` | `boolean`       | `false` で thinking を無効にします。 `true` デフォルトで                   |
| `enable_tools`    | `boolean`       | `true` でサーバー側ツール実行を有効にします。                                  |
| `enabled_tools`   | `array<string>` | モデルが呼び出せるツールを指定します。対応しているのは `python`, `bash`, `web_search`. |
| `session_id`      | `string`        | 任意。呼び出し間でツールの状態（例: Python カーネル）を保持します。                      |

#### Thinking モード

Thinking モードはデフォルトで有効です。&#x20;

```bash
curl http://localhost:8888/v1/chat/completions \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "default",
    "messages": [{"role": "user", "content": "量子トンネル効果を 1 文で要約してください"}],
    "stream": false,
  }'
```

モデルは回答を返す前に考えます。

<figure><img src="/files/9a6c58d9b2f23c7df17b83c6ac44a1718ad1e673" alt=""><figcaption></figcaption></figure>

thinking を無効にするには、 `enable_thinking: false` をリクエストに渡します。するとモデルは最初に考えずに回答を返します。

<figure><img src="/files/8de107aa76d7e8ebad3faf15662b74dfe20a7848" alt=""><figcaption></figcaption></figure>

#### Python 実行

```bash
curl http://localhost:8888/v1/chat/completions \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen-local",
    "messages": [{"role": "user", "content": "123 * 456 はいくつですか？コードを使って計算してください。"}],
    "stream": false,
    "enable_tools": true,
    "enabled_tools": ["python"],
    "session_id": "my-session"
  }'
```

<figure><img src="/files/e8d805b5c1edf0f38044484d32ba18d06f2daac0" alt=""><figcaption></figcaption></figure>

#### Web 検索 + Python（ストリーミング）

```bash
curl http://localhost:8888/v1/chat/completions \
  -H "Authorization: Bearer sk-unsloth-xxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen-local",
    "messages": [{"role": "user", "content": "Python 3.13 の機能を検索してください"}],
    "stream": true,
    "enable_tools": true,
    "enabled_tools": ["web_search", "python"],
    "session_id": "my-session"
  }'
```

<figure><img src="/files/b868f933df65b504b7af7c938e0c5a710c42bcb9" alt=""><figcaption></figcaption></figure>

#### On `/v1/messages`

同じ簡略記法は Anthropic Messages エンドポイントでも使えます:

```bash
curl http://localhost:8888/v1/messages \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen-local",
    "max_tokens": 1024,
    "messages": [{"role": "user", "content": "Python 3.13 の機能を検索してください"}],
    "stream": true,
    "enable_tools": true,
    "enabled_tools": ["web_search", "python"],
    "session_id": "my-session"
  }'
```

<figure><img src="/files/d4cd5845f1477f98dc1ebcb2e328d620db8d515f" alt=""><figcaption></figcaption></figure>

Unsloth は独自の `tool_result` SSE イベントを、標準の Anthropic / OpenAI イベントタイプに加えてストリーミングします。モデルは各ツールの出力を次のターンで参照できます。

### ❔ トラブルシューティング

**`401 Unauthorized`** **-** この `Authorization` ヘッダーが欠けているか、キーが間違っています。次を再確認してください: `Authorization: Bearer sk-unsloth-…`.

**`curl` ストリーミングリクエストでハングする -** 追加します `-N` （ `--no-buffer`と同じ）。これがないと、 `curl` が SSE ストリームをバッファし、最後まで何も表示されません。

**Base64 エンコードは OS によって異なります** **-** Linux の `base64` はデフォルトで行を折り返しますが、macOS / BSD ではそうなりません。Linux では `base64 -w 0` を、macOS では `base64` を使うか、出力を `tr -d '\n'`.

**シェルでの JSON エスケープ** **-** Heredoc（`-d @file.json`）は、本文が複雑になってきたらインライン文字列よりもきれいです。例: `curl ... -d @body.json`.

**`max_tokens` でエラーが出る `/v1/messages`** **-** Anthropic 方言ではこれが必須です。 `"max_tokens": 1024` （または 원하는上限）を追加してください。

エンドポイントレベルの問題（モデルが読み込まれない、接続が切れる、ポートが違う）については、API 概要ページを参照してください。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://unsloth.ai/docs/jp/tong-he/curltohttpwounslothni.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
