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

# Python SDKをUnslothに接続する

公式の OpenAI または Anthropic SDK を使って、ストリーミング、ビジョン、関数呼び出し、Unsloth の組み込みサーバーサイドツールを含め、Python から Unsloth のローカル API を呼び出すためのガイド。

Unsloth は同じベース URL で、OpenAI 互換の 3 種類の API 形式に対応しています。Chat Completions、Responses、Anthropic Messages を利用できるため、主要な Python SDK はどれもそのまま使えます。\
\
クライアントで変更するのは `base_url` と `api_key`  だけです。それ以外（ストリーミング、ツール呼び出し、画像入力、構造化出力）は、SDK のドキュメントどおりに動作します。このページでは、多くの開発者がまず利用する 2 つの公式 SDK、 **OpenAI Python SDK** と公式の **Anthropic Python SDK**.

{% hint style="info" %}
を取り上げます。使用する URL、キー、モデル名がわからない場合は、まず API 概要をお読みください。起動方法、モデルの読み込み方法、 `sk-unsloth-…` キーの作成方法を説明しています。
{% endhint %}

### 🔑 前提条件

以下のコード例を実行する前に、次のものが必要です。

* **モデルを読み込んだ状態で Unsloth をローカルで起動しておくこと** （ポートを確認してください。通常は `8000` または `8888`).
* **Unsloth で作成した `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",              # your unsloth port + /v1
    api_key=os.environ["UNSLOTH_STUDIO_AUTH_TOKEN"],     # your sk-unsloth-… key
)
```

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

```python
response = client.chat.completions.create(
    model="default",                               # the name you gave the model in unsloth or default
    messages=[
        {"role": "user", "content": "Give me two facts about Paris"}
    ],
)
print(response.choices[0].message.content)
```

<figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FZkxVYS7fcvwXZ8AxvaBF%2FScreenshot%202026-04-22%20at%202.38.44%E2%80%AFAM.png?alt=media&amp;token=06dece4e-dade-4c2d-bcdb-7c946cdd1290" alt=""><figcaption></figcaption></figure>

#### ストリーミング

設定し `stream=True` 、返されたジェネレーターを反復処理します。

```python
stream = client.chat.completions.create(
    model="qwen-local",
    messages=[{"role": "user", "content": "Write a haiku about locally-run LLMs."}],
    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="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2F0eItNT5zanSB8rXY4QHn%2Fopenai_streaming.png?alt=media&amp;token=2922bbf3-69da-409f-b954-76b6259233f8" 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": "What's in this image?"},
            ],
        }
    ],
)
print(response.choices[0].message.content)
```

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

<figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FTNCX4qEMj8zFSAsOJw2Y%2Fopenai_sdk_vision_test.png?alt=media&amp;token=caa22501-66fc-4e3c-b4a0-636ebe5af4bf" alt=""><figcaption></figcaption></figure>

#### 関数呼び出し（OpenAI ツール）

OpenAI 形式の `tools` と（任意で） `tool_choice` を渡すと、Unsloth がバックエンドに転送します。各ツール呼び出しを実行し、次のターンで結果を返すのはクライアントの役割です。

```python
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a city",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "City name, e.g. 'Paris'"},
                },
                "required": ["city"],
            },
        },
    }
]

response = client.chat.completions.create(
    model="default",
    messages=[{"role": "user", "content": "What's the weather in Perth right now?"}],
    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="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2F8nzgxHsN8J23B6duQ3Zv%2Fopenai_sdk_function_calling.png?alt=media&amp;token=3551592d-31b2-4fa6-94a9-6a9f0974c21a" alt=""><figcaption></figcaption></figure>

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

OpenAI形式のクライアントサイドツールに加えて、Unslothは **Python**, **ターミナル** （シェルコマンド）と **ウェブ検索** をサーバーサイドで実行し、結果を自動的にストリーミングで返すことができます。 `extra_body` パラメーターを使ってオプトインすると、フィールドがそのままUnslothに渡されます：

```python
stream = client.chat.completions.create(
    model="default",
    messages=[{"role": "user", "content": "What is 123 * 456? Use Python to compute it."}],
    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="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FvdZuLwIh7LT0C8y7AWaR%2FScreenshot%202026-04-22%20at%203.01.06%E2%80%AFAM.png?alt=media&amp;token=35ff3039-d941-406b-b3fc-5e1e564c7651" alt=""><figcaption></figcaption></figure>

<figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FnW60ezYCOJQmTjd52bnu%2FScreenshot%202026-04-22%20at%203.05.23%E2%80%AFAM.png?alt=media&amp;token=f7125db4-cb94-46f7-974d-abe58ec348a7" alt=""><figcaption></figcaption></figure>

The `session_id` は省略可能です。呼び出し間でツールの状態（Python カーネルなど）を保持するには、これを使用します。

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

**モデルの一覧表示**

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

<figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2F6GKdrximwyplotWu3u5s%2FScreenshot%202026-04-22%20at%203.06.57%E2%80%AFAM.png?alt=media&amp;token=48d17278-e4b0-4437-a426-5f12c0c45b1e" 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", # your unsloth port (no /v1 here - the SDK adds it)
    api_key="dummy", # a random none empty value
    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": "Say hello in three languages."}
    ],
)
print(message.content[0].text)
```

<figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fc4yQCiRHjebKomV4H2Eh%2FScreenshot%202026-04-22%20at%202.29.04%E2%80%AFAM.png?alt=media&amp;token=4ad983da-83fd-48c0-8fa8-1fbe92fcfd40" alt=""><figcaption></figcaption></figure>

#### ストリーミング

SDKには、テキストの差分を返すコンテキストマネージャーが用意されています。

```python
with client.messages.stream(
    model="default",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Explain LoRA in two sentences."}],
) 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": "What's in this image?"},
            ],
        }
    ],
)
print(message.content[0].text)
```

<figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FKI75sgbWxmo8BNXQEP6s%2Fanthropic_sdk_vision_test.png?alt=media&amp;token=f72c2dd6-b811-41a7-82bb-a2a6f30513ac" alt=""><figcaption></figcaption></figure>

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

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

```python
tools = [
    {
        "name": "get_weather",
        "description": "Get the current weather for a city",
        "input_schema": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "City name, e.g. 'Tokyo'"},
            },
            "required": ["city"],
        },
    }
]

message = client.messages.create(
    model="default",
    max_tokens=1024,
    tools=tools,
    tool_choice={"type": "auto"},
    messages=[{"role": "user", "content": "What's the weather in Tokyo?"}],
)

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

<figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FWnWPZdZOtV2o1o5FIzlD%2Fanthropic_tool_use_get_weather_tokyo.png?alt=media&amp;token=39587916-f4c0-45cf-8e59-11245b3432b8" 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": "Search for Python 3.13 features and summarize."}],
    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="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2F2wA6aleUHPJN1gAB3ClL%2Fserver_side_tool_call_backend.png?alt=media&amp;token=7440befb-d517-473a-a431-c6b4cb413ca5" alt=""><figcaption></figcaption></figure>

<figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FwcIerVboFjEZPkI2vU0L%2Fserver_side_tool_call_output.png?alt=media&amp;token=33800495-70d1-4a5f-9173-cde144abecb3" alt=""><figcaption></figcaption></figure>

Unslothは、モデルが各ツール呼び出しの出力を確認するためのカスタム `tool_result` SSEイベントを生成します。Anthropic SDKはこれらをイベントストリームで変更せずに転送します。

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

Unslothは、 `response_format`を使ってOpenAI形式の構造化出力に対応しています。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": "Pick a country: Japan, Egypt, or Peru. Explain why in one sentence.",
        },
    ],
    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
# Gemma 4 が JSON を囲む 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="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FmhPxaVA6sxkyF3nFf51f%2FScreenshot%202026-05-05%20at%201.46.44%E2%80%AFPM.png?alt=media&amp;token=50b1600d-9e5a-4d22-819a-274c6bfbf8f7" 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 は同じポートで両方を提供するため、単一の `sk-unsloth-…` キーは両方の認証に使われます。

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

**`401 Unauthorized`**  UNSLOTH\_STUDIO\_AUTH\_TOKEN `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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://unsloth.ai/docs/jp/tong-he/python-sdkwounslothnisuru.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
