> 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/de/integrationen/python-sdk-mit-unsloth-verbinden.md).

# Python SDK mit Unsloth verbinden

Anleitung zum Aufrufen der lokalen API von Unsloth aus Python mit den offiziellen OpenAI- oder Anthropic-SDKs, einschließlich Streaming, Vision, Funktionsaufrufen und den integrierten serverseitigen Tools von Unsloth.

Unsloth stellt unter derselben Basis-URL drei OpenAI-kompatible Schnittstellen bereit: Chat Completions, Responses und Anthropic Messages. Damit funktionieren alle gängigen Python-SDKs. \
\
Sie ändern lediglich `base_url` und `api_key`  am Client; alles andere (Streaming, Tool-Aufrufe, Bildverarbeitung und strukturierte Ausgabe) funktioniert wie in der SDK-Dokumentation beschrieben. Diese Seite behandelt die beiden SDKs, zu denen die meisten Entwickler zuerst greifen: das offizielle **OpenAI Python SDK** und das offizielle **Anthropic Python SDK**.

{% hint style="info" %}
Wenn Sie nicht sicher sind, welche URL, welchen Schlüssel oder welchen Modellnamen Sie verwenden sollen, lesen Sie zuerst die API-Übersicht. Sie erklärt, wie Sie Unsloth starten, ein Modell laden und einen `sk-unsloth-…` API-Schlüssel erstellen.
{% endhint %}

### 🔑 Voraussetzungen

Bevor Sie die folgenden Codebeispiele ausführen, benötigen Sie:

* **Eine lokal laufende Unsloth-Instanz** mit geladenem Modell (beachten Sie den Port: üblicherweise `8000` oder `8888`).
* **Einen `sk-unsloth-…` API-Schlüssel,** erstellt unter **Einstellungen → API**.
* **Einen Modellnamen.** Den Namen des GGUF-Modells in Unsloth (z. B. `qwen-local`, `unsloth/Qwen3.6-27B-GGUF`). Falls Sie ihn vergessen haben, führen Sie Folgendes aus:

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

  und kopieren Sie den Wert des Felds `id` .

Legen Sie den Schlüssel als Umgebungsvariable fest, damit Sie ihn nicht in den Code einfügen müssen:

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

#### 🤖 OpenAI SDK

Der `/v1/chat/completions` Endpunkt von Unsloth kann direkt mit dem OpenAI Python SDK verwendet werden. Der Client behandelt Unsloth wie jeden anderen OpenAI-kompatiblen Anbieter.

**1. Installieren Sie das SDK:**

```bash
pip install openai
```

**2. Erstellen Sie einen Client,** der auf Unsloth verweist:

```python
import os
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8888/v1",              # Ihr Unsloth-Port + /v1
    api_key=os.environ["UNSLOTH_STUDIO_AUTH_TOKEN"],     # Ihr sk-unsloth-…-Schlüssel
)
```

#### Einfache Chat-Completion

```python
response = client.chat.completions.create(
    model="default",                               # der Name, den Sie dem Modell in Unsloth gegeben haben, oder default
    messages=[
        {"role": "user", "content": "Give me two facts about Paris"}
    ],
)
print(response.choices[0].message.content)
```

<figure><img src="https://797013937-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>

#### Streaming

Setzen Sie `stream=True` und durchlaufen Sie den zurückgegebenen Generator:

```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://797013937-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>

#### Bilder (Vision)

Fügen Sie ein Bild als `image_url` Inhaltsteil hinzu. Unsloth akzeptiert entweder eine HTTP(S)-URL oder einen `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" %}
Das geladene Modell muss multimodal sein. Wenn Sie ein reines Textmodell laden, wird die Vision-Anfrage zwar strukturell erfolgreich verarbeitet, aber das Modell kann das Bild nicht „sehen“.
{% endhint %}

<figure><img src="https://797013937-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>

#### Funktionsaufrufe (OpenAI-Tools)

Übergeben Sie OpenAI-kompatible `tools` und optional `tool_choice` Unsloth leitet diese Parameter an das Backend weiter. Sie sind dafür verantwortlich, jeden Tool-Aufruf auszuführen und das Ergebnis im nächsten Durchgang zurückzugeben:

```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://797013937-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-Tools auf der Serverseite (Kurzform)

Zusätzlich zu clientseitigen Tools im OpenAI-Stil kann Unsloth **Python**, **Terminal** (Shell-Befehle) und **Websuche** serverseitig ausführen und die Ergebnisse automatisch zurückstreamen. Aktivieren Sie die Funktion über den `extra_body` Parameter, damit die Felder direkt an Unsloth weitergereicht werden:

```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://797013937-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://797013937-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>

Die `session_id` ist optional. Verwenden Sie ihn, um den Tool-Zustand (z. B. einen Python-Kernel) über mehrere Aufrufe hinweg beizubehalten.

{% hint style="info" %}
`enabled_tools` unterstützt derzeit `"python"`, `"terminal"` und `"web_search"`. Tool-Ergebnisse werden als `tool_result` -Ereignisse zurückgestreamt, sodass das Modell sie in seinem nächsten Schritt sehen kann.
{% endhint %}

**Modelle auflisten**

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

<figure><img src="https://797013937-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

Der `/v1/messages` -Endpunkt von Unsloth ist ein direkter Ersatz für das Anthropic-Python-SDK.

**1. Installieren Sie das SDK:**

```bash
pip install anthropic
```

**2. Erstellen Sie einen Client,** der auf Unsloth verweist:

{% 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']}"} # your sk-unsloth-… key
)
```

{% endcode %}

#### Einfache Nachricht

```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://797013937-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>

#### Streaming

Das SDK stellt einen Kontextmanager bereit, der Text-Deltas liefert:

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

#### Bilder (Vision)

Anthropic-artige Bildinhalte verwenden einen `source` Block mit Base64-Daten:

```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://797013937-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>

#### Tool-Aufrufe (Anthropic-Tools)

Übergib Anthropic-artige `tools` mit einem `input_schema` und Unsloth leitet sie unverändert weiter:

```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://797013937-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-Tools auf der Serverseite (Kurzform)

Die gleiche `enable_tools` / `enabled_tools` / `session_id` Kurzform funktioniert auch mit `/v1/messages` gib es über `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://797013937-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://797013937-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 gibt benutzerdefinierte `tool_result` SSE-Ereignisse mit der Sicht des Modells auf die Ausgabe jedes Tool-Aufrufs aus. Das Anthropic SDK leitet diese unverändert über seinen Ereignisstream weiter.

#### JSON-Decodierung (`response_format`)

Unsloth unterstützt strukturierte Ausgaben im OpenAI-Stil über `response_format`. Übergib ein JSON-Schema, und das Modell wird darauf beschränkt, dazu passendes JSON zu erzeugen.

````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
# Strip the markdown fence Gemma 4 wraps around the JSON, then parse.
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"])
````

Die `strict: True` -Option weist Unsloth an, das Schema während des Decodierens durchzusetzen, anstatt sich darauf zu verlassen, dass das Modell es von selbst einhält. `additionalProperties: False` und `required` funktionieren wie im standardmäßigen JSON Schema.

Die Terminalausgabe sollte ungefähr so aussehen:

<figure><img src="https://797013937-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>

### 🧪 Ein SDK auswählen

Beide SDKs funktionieren mit Unsloth. Welche Wahl die richtige ist, hängt vom Rest deines Stacks ab:

* Verwende das **OpenAI SDK** wenn dein Code bereits vom OpenAI-Python-Paket abhängt, du OpenAI-ähnliche `tools` / `tool_choice`verwenden möchtest oder die Responses API aufrufen willst.
* Verwende das **Anthropic SDK** wenn dein Code bereits vom Anthropic-Paket abhängt, du das Anthropic-typische `input_schema` Tool-Format bevorzugst oder die nativen Anthropic-Streaming-Ereignistypen verwenden möchtest.

Du kannst beide im selben Projekt verwenden. Unsloth stellt sie am selben Port bereit, sodass ein einzelner `sk-unsloth-…` -Schlüssel beide authentifiziert.

### ❔ Fehlerbehebung

**`401 Unauthorized`**  Die `UNSLOTH_STUDIO_AUTH_TOKEN` Umgebungsvariable ist nicht gesetzt oder der Schlüssel ist falsch. Exportiere sie erneut und überprüfe sie mit `echo $UNSLOTH_STUDIO_AUTH_TOKEN`.

**`404 Not Found` vom OpenAI SDK** Prüfen Sie, ob `base_url` mit `/v1`endet. Das OpenAI-SDK hängt die Endpunktpfade unverändert an die Basis-URL an.

**`404 Not Found` vom Anthropic-SDK** Prüfen Sie, ob `base_url` … tut **nicht** mit `/v1`. Das Anthropic-SDK fügt `/v1/messages` selbst hinzu.

**`extra_body` Felder nicht bei Unsloth ankommen** Stelle sicher, dass du eine aktuelle Version von `openai` / `anthropic` SDK. Ältere Versionen verwerfen unbekannte Felder stillschweigend. Aktualisieren Sie mit `pip install -U openai anthropic`.

**Streaming „hängt“ und gibt dann alles auf einmal aus** Was auch immer Ihre Ausgabe umschließt, puffert sie. Verwenden Sie in einem Skript `print(..., flush=True)`; in einem Notebook ist das normalerweise kein Problem; hinter einem Proxy deaktivieren Sie das Puffern von Antworten auf dem Proxy.

Informationen zu Problemen auf Endpunktebene (falscher Port, Modell wird nicht geladen, Verbindungsabbruch usw.) finden Sie auf der API-Übersichtsseite.

### Optional: Serverstandardwerte festlegen

Sie können das Standardverhalten des Servers konfigurieren, bevor Sie mit dem Python-SDK eine Verbindung herstellen, wenn Sie Folgendes verwenden `unsloth run` Befehl.

```bash
# Server mit benutzerdefinierten Standardwerten starten
unsloth run \
  --model unsloth/Qwen3-1.7B-GGUF \
  --reasoning off \
  --temp 0.6 \
  -p 8888
```

Verwenden Sie `--reasoning off` um das Denken auszuschalten, oder `--reasoning on` um es für Modelle einzuschalten, die Reasoning unterstützen.

```bash
# Die API im lokalen Netzwerk bereitstellen
unsloth run \
  --model unsloth/Qwen3-1.7B-GGUF \
  -H 0.0.0.0 \
  -p 8888
```

Dadurch wird der Server gestartet auf `0.0.0.0:8888`, sodass andere Geräte in Ihrem lokalen Netzwerk eine Verbindung herstellen können.

Diese Einstellungen werden zu den Standardwerten des Servers, wenn Anfragen keine eigenen Generierungsparameter angeben.

Anfragebezogene Werte wie `temperature`, `top_p`, `max_tokens` und `stream` können für diese Anfrage weiterhin die Standardwerte überschreiben.


---

# 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/de/integrationen/python-sdk-mit-unsloth-verbinden.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.
