> For the complete documentation index, see [llms.txt](https://unsloth.ai/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://unsloth.ai/docs/jp/tong-he/python-sdkwounslothni.md).

# Python SDKをUnslothに接続

Unsloth は、同じベース URL で OpenAI 互換の 3 つの方言を提供します。Chat Completions、Responses、そして Anthropic Messages なので、主要な Python SDK はすべてそのまま使えます。\n\n変更するのは `base_url` および `api_key`  クライアント側の api\_key だけを変更します。その他すべて（ストリーミング、ツール呼び出し、ビジョン、構造化出力）は SDK のドキュメントどおりに動作します。このページでは、ほとんどの開発者が最初に使う 2 つの SDK、公式の **OpenAI Python SDK** および公式の **Anthropic Python SDK**.

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

### 🔑 前提条件

以下のスニペットを実行する前に、次のものが必要です:

* **ローカルで Unsloth が実行されていること** モデルが読み込まれていること（ポートに注意: 通常は `8000` または `8888`).
* **1 つの `sk-unsloth-…` API キー** から作成された **Settings → API**.
* **モデル名。** Unsloth 内の GGUF モデルの名前（例: `qwen-local`, `unsloth/Qwen3.6-27B-GGUF`）。忘れた場合は、次を実行してください:

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

  そして `id` フィールドをコピーしてください。

キーを環境変数として設定しておけば、コードに貼り付ける必要がなくなります:

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

#### 🤖 OpenAI SDK

Unsloth の `/v1/chat/completions` エンドポイントは OpenAI Python SDK のドロップイン置換です。クライアントは Unsloth を他の OpenAI 互換プロバイダと同じように扱います。

**1. SDK をインストールします:**

```bash
pip install openai
```

**2. クライアントを作成します** Unsloth を指すようにします:

```python
import os
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8888/v1",              # あなたの Unsloth のポート + /v1
    api_key=os.environ["UNSLOTH_STUDIO_AUTH_TOKEN"],     # あなたの sk-unsloth-… キー
)
```

#### 基本的なチャット補完

```python
response = client.chat.completions.create(
    model="default",                               # Unsloth でモデルに付けた名前、または default
    messages=[
        {"role": "user", "content": "パリについて 2 つの事実を教えて"}
    ],
)
print(response.choices[0].message.content)
```

<figure><img src="/files/012867ddd668cfd33718609f5f885239e5b81a50" alt=""><figcaption></figcaption></figure>

#### ストリーミング

設定して `stream=True` 返されるジェネレータを反復処理します:

```python
stream = client.chat.completions.create(
    model="qwen-local",
    messages=[{"role": "user", "content": "ローカルで実行される LLM について俳句を書いてください。"}],
    stream=True,
)
for chunk in stream:
    if chunk.choices:
        delta = chunk.choices[0].delta.content
        if delta:
            print(delta, end="", flush=True)
```

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

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

画像を `image_url` コンテンツ部分。Unsloth は HTTP(S) URL または `data:` base64 URI を受け付けます:

```python
import base64
from pathlib import Path

img_b64 = base64.b64encode(Path("test.jpg").read_bytes()).decode()

response = client.chat.completions.create(
    model="default",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {"url": f"data:image/jpeg;base64,{img_b64}"},
                },
                {"type": "text", "text": "この画像には何が写っていますか？"},
            ],
        }
    ],
)
print(response.choices[0].message.content)
```

{% hint style="info" %}
読み込まれたモデルはマルチモーダルである必要があります。テキスト専用モデルを読み込んだ場合、ビジョンリクエストは構造上は成功しますが、モデルは画像を「見る」ことができません。
{% endhint %}

<figure><img src="/files/998d4fc1ac5337df1cc0264011a3d6ccf65dd2c2" alt=""><figcaption></figcaption></figure>

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

OpenAI スタイルの `tools` と（任意で） `tool_choice` そして Unsloth はそれらをバックエンドに転送します。各ツール呼び出しを実行し、次のターンで結果を返す責任はクライアント側にあります:

```python
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "都市の現在の天気を取得します",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "都市名、例: 'Paris'"},
                },
                "required": ["city"],
            },
        },
    }
]

response = client.chat.completions.create(
    model="default",
    messages=[{"role": "user", "content": "今のパースの天気は？"}],
    tools=tools,
    tool_choice="auto",
)

tool_call = response.choices[0].message.tool_calls[0]
print(tool_call.function.name, tool_call.function.arguments)
```

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

#### Unsloth のサーバー側ツール（省略形）

OpenAI 形式のクライアント側ツールに加えて、Unsloth は **Python**, **bash**、および **ウェブ検索** サーバー側で実行し、結果を自動でストリーミング返却できます。次の `extra_body` パラメータを使うことで、フィールドがそのまま Unsloth に渡ります:

```python
stream = client.chat.completions.create(
    model="default",
    messages=[{"role": "user", "content": "Python を使って 123 * 456 を計算してください。"}],
    stream=True,
    extra_body={
        "enable_tools": True,
        "enabled_tools": ["python", "web_search"],
        "session_id": "my-session",
    },
)
for chunk in stream:
    if chunk.choices:
        delta = chunk.choices[0].delta.content
        if delta:
            print(delta, end="", flush=True)
```

<figure><img src="/files/445309a3e703114c915053551824e25aa7b24fce" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/2758798df66209fa1bef9fed31cbe469c65adf38" alt=""><figcaption></figcaption></figure>

この `session_id` は任意です。たとえば Python カーネルのようなツール状態を呼び出し間で保持するために使います。

{% hint style="info" %}
`enabled_tools` 現在サポートしているのは `"python"`, `"bash"`、および `"web_search"`。ツール結果は `tool_result` イベントとしてストリーミング返却され、モデルは次のターンでそれらを確認できます。
{% endhint %}

**モデル一覧**

```python
models = client.models.list()
for m in models.data:
    print(m.id)
```

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

#### 🧠 Anthropic SDK

Unsloth の `/v1/messages` エンドポイントは Anthropic Python SDK のドロップイン置換です。

**1. SDK をインストールします:**

```bash
pip install anthropic
```

**2. クライアントを作成します** Unsloth を指すようにします:

{% code overflow="wrap" %}

```python
import os
from anthropic import Anthropic

client = Anthropic(
    base_url="http://localhost:8888", # あなたの Unsloth のポート（ここには /v1 は不要です。SDK が追加します）
    api_key="dummy", # 任意の空でない値
    default_headers={"Authorization": f"Bearer {os.environ['UNSLOTH_STUDIO_AUTH_TOKEN']}"} # あなたの sk-unsloth-… キー
)
```

{% endcode %}

#### 基本メッセージ

```python
message = client.messages.create(
    model="default",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "3 つの言語で挨拶してください。"}
    ],
)
print(message.content[0].text)
```

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

#### ストリーミング

SDK は、テキストの差分を返すコンテキストマネージャーを提供します:

```python
with client.messages.stream(
    model="default",
    max_tokens=1024,
    messages=[{"role": "user", "content": "LoRA を 2 文で説明してください。"}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
```

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

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

```python
import base64
from pathlib import Path

img_b64 = base64.standard_b64encode(Path("photo.jpg").read_bytes()).decode()

message = client.messages.create(
    model="default",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "base64",
                        "media_type": "image/jpeg",
                        "data": img_b64,
                    },
                },
                {"type": "text", "text": "この画像には何が写っていますか？"},
            ],
        }
    ],
)
print(message.content[0].text)
```

<figure><img src="/files/73325815d89d5982e7c93357750621f8deedf5e4" alt=""><figcaption></figcaption></figure>

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

Anthropic 形式の `tools` と `input_schema` を指定すると、Unsloth がネイティブに転送します:

```python
tools = [
    {
        "name": "get_weather",
        "description": "都市の現在の天気を取得します",
        "input_schema": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "都市名、例: 'Tokyo'"},
            },
            "required": ["city"],
        },
    }
]

message = client.messages.create(
    model="default",
    max_tokens=1024,
    tools=tools,
    tool_choice={"type": "auto"},
    messages=[{"role": "user", "content": "東京の今の天気は？"}],
)

for block in message.content:
    if block.type == "tool_use":
        print(block.name, block.input)
```

<figure><img src="/files/4308dd60aa7c2b71daebbdedcf7a1fbb898913c8" alt=""><figcaption></figcaption></figure>

#### Unsloth のサーバー側ツール（省略形）

同じ `enable_tools` / `enabled_tools` / `session_id` 省略形は `/v1/messages` それをそのまま渡せば `extra_body`:

```python
with client.messages.stream(
    model="default",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Python 3.13 の機能を検索して要約してください。"}],
    extra_body={
        "enable_tools": True,
        "enabled_tools": ["web_search", "python"],
        "session_id": "my-session",
    },
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
```

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

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

Unsloth は独自の `tool_result` SSE イベントを、各ツール呼び出しの出力に対するモデルの視点として送信します。Anthropic SDK はそれらをイベントストリームで変更せずにそのまま通します。

#### JSON デコード（`response_format`)

Unsloth は OpenAI 形式の構造化出力を `response_format`でサポートします。JSON Schema を渡すと、モデルはそれに一致する JSON を生成するよう制約されます。

````python
import json
import os
import re
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8888/v1",
    api_key=os.environ["UNSLOTH_STUDIO_AUTH_TOKEN"],
)

response = client.chat.completions.create(
    model="default",
    stream=False,
    temperature=0.0,
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": "Japan、Egypt、Peru のいずれかの国を選んでください。理由を 1 文で説明してください。",
        },
    ],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "country_pick",
            "schema": {
                "type": "object",
                "properties": {
                    "country": {"type": "string", "enum": ["Japan", "Egypt", "Peru"]},
                    "reason":  {"type": "string"},
                },
                "required": ["country", "reason"],
                "additionalProperties": False,
            },
            "strict": True,
        },
    },
)

raw = response.choices[0].message.content
# JSON を囲む Gemma 4 の Markdown フェンスを削除してから、パースします。
cleaned = re.sub(r"^```(?:json)?\\s*", "", raw)
cleaned = re.sub(r"\\s*```$", "", cleaned)
parsed = json.loads(cleaned)

print(json.dumps(parsed, indent=2))
print()
print("country:", parsed["country"])
print("reason :", parsed["reason"])
````

この `strict: True` このフラグにより、Unsloth はモデル自身に従わせるのではなく、デコード中にスキーマを強制します。 `additionalProperties: False` および `required` 標準の JSON Schema と同じように機能します。

ターミナル出力はおおむね次のようになります:

<figure><img src="/files/66a0ec61980b75db7c197b27c2277781bd7cb8b4" alt=""><figcaption></figcaption></figure>

### 🧪 SDK の選択

どちらの SDK も Unsloth で動作します。適切な選択は、既存のスタック次第です:

* リクエストで **OpenAI SDK** コードがすでに OpenAI Python パッケージに依存している場合や、OpenAI 形式の `tools` / `tool_choice`、または Responses API を呼び出す予定がある場合。
* リクエストで **Anthropic SDK** コードがすでに Anthropic パッケージに依存している場合や、Anthropic の `input_schema` ツール形式を好む場合、または Anthropic ネイティブのストリーミングイベント型を使いたい場合。

同じプロジェクトで両方を使えます。Unsloth は同じポートで両方を提供するため、1 つの `sk-unsloth-…` キーで両方を認証できます。

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

**`401 Unauthorized`**  この `UNSLOTH_STUDIO_AUTH_TOKEN` 環境変数が設定されていないか、キーが間違っています。再度エクスポートして、次で確認してください: `echo $UNSLOTH_STUDIO_AUTH_TOKEN`.

**`404 Not Found` OpenAI SDK では** 次を確認してください: `base_url` で終わっていること `/v1`。OpenAI SDK はエンドポイントのパスをベース URL にそのまま追加します。

**`404 Not Found` Anthropic SDK では** 次を確認してください: `base_url` は **終わりません** で `/v1`。Anthropic SDK は `/v1/messages` 自分で追加します。

**`extra_body` フィールドが Unsloth に届いていません** 最新の `openai` / `anthropic` SDK を使っていることを確認してください。古いバージョンでは未知のフィールドが黙って削除されます。次でアップグレードしてください: `pip install -U openai anthropic`.

**ストリーミングが「停止した」ように見え、その後すべてを一度に吐き出す** 出力を包んでいるものがバッファリングしています。スクリプトでは、 `print(..., flush=True)`; ノートブックでは通常問題ありませんが、プロキシの背後ではプロキシ側でレスポンスのバッファリングを無効にしてください。

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

### 任意: サーバーのデフォルトを設定

Python SDK で接続する前に、次を使用する場合はサーバーの既定動作を設定できます: `unsloth run` コマンドに。

```bash
# カスタムデフォルトでサーバーを起動
unsloth run \
  --model unsloth/Qwen3-1.7B-GGUF \
  --reasoning off \
  --temp 0.6 \
  -p 8888
```

使用します `--reasoning off` で思考をオフにするか、 `--reasoning on` で、推論をサポートするモデルの思考をオンにします。

```bash
# ローカルネットワークで API を公開
unsloth run \
  --model unsloth/Qwen3-1.7B-GGUF \
  -H 0.0.0.0 \
  -p 8888
```

これによりサーバーは `0.0.0.0:8888`で起動し、ローカルネットワーク上の他のデバイスが接続できるようになります。

リクエストが独自の生成パラメータを指定しない場合、これらの設定がサーバーのデフォルトになります。

次のようなリクエストレベルの値 `temperature`, `top_p`, `max_tokens`、および `stream` そのリクエストでは、引き続きデフォルトを上書きできます。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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/python-sdkwounslothni.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.
