> 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/zh/ji-chu-zhi-shi/api.md).

# 如何将 Unsloth 用作 API 端点

你可以运行 **本地 LLM** 并使用 [Claude Code](https://unsloth.ai/docs/zh/ji-chu-zhi-shi/claude-code.md) 和 [Codex](https://unsloth.ai/docs/zh/ji-chu-zhi-shi/codex.md) 等工具，只需将这些工具连接到 Unsloth 的 **兼容 OpenAI 的 API 端点**。这样，你就可以在本地运行 [Qwen](https://unsloth.ai/docs/zh/mo-xing/qwen3.6.md) 和 [Gemma](https://unsloth.ai/docs/zh/mo-xing/gemma-4.md) 等模型，用于智能体编程。Unsloth 还提供自我修复等实用功能 **工具调用**, **代码执行**和 **网页搜索**.

Unsloth 可轻松部署快速的 API 推理端点，并提供以下功能：

* [**自我修复工具调用**](https://unsloth.ai/docs/zh/xin/studio/chat.md#auto-healing-tool-calling)，有助于将错误或格式不正确的工具调用减少 50%
* [**代码执行**](https://unsloth.ai/docs/zh/xin/studio/chat.md#code-execution) 支持，可执行 Bash 和 Python，从而生成更准确的代码。
* **高级** [**网页搜索**](https://unsloth.ai/docs/zh/xin/studio/chat.md#advanced-web-search) 会访问网页并实际阅读内容，以收集深入信息。
* [**自动推理** 设置](https://unsloth.ai/docs/zh/xin/studio/chat.md#auto-parameter-tuning) 适用于 GGUF 模型（温度、top-k 等）

{% columns %}
{% column %}
在 Unsloth 中加载的模型（包括 GGUF）会通过 **经过身份验证的 API** 以 `llama-server`的形式对外提供。出于安全考虑，系统会生成一个较长的 API 密钥，类似于 OpenAI 的做法。

随后，你的 **本地模型** 即可直接用于你偏好的 AI 智能体、SDK 或聊天客户端。Unsloth 在同一端口上支持两种协议。两者均支持流式传输、工具调用（OpenAI `tools` / Anthropic `tools`）和视觉输入：
{% endcolumn %}

{% column %}

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FgCthbL3uUmrNgxFBePK5%2Fimage.png?alt=media&amp;token=060dbc41-6fd5-496d-ba00-0ba13fde86ff" alt=""><figcaption></figcaption></figure>
{% endcolumn %}
{% endcolumns %}

无论模型是通过 Unsloth 推理运行，还是使用你自己的远程 OpenAI 兼容端点，你都可以让它使用 Unsloth 的全套工具，包括网页搜索、代码执行、深度研究等。

* **兼容 Anthropic 的 `/v1/messages`**  适用于 Claude Code、OpenClaw、Anthropic SDK，以及任何需要 Messages API 的客户端。
* **兼容 OpenAI 的 `/v1/chat/completions`** 和 **`/v1/responses`** 适用于 OpenAI SDK、OpenCode、Cursor、Continue、Cline、Open WebUI、SillyTavern，以及任何兼容 OpenAI 的工具。

### ⚡ 快速入门

{% stepper %}
{% step %}

#### 下载 Unsloth

开始使用最简单的方法是安装 [Unsloth Desktop](https://unsloth.ai/docs/zh/desktop.md) 应用。它支持 [macOS](https://unsloth.ai/docs/zh/kuai-su-kai-shi/install/mac.md)、Linux、 [Windows](https://unsloth.ai/docs/zh/kuai-su-kai-shi/install/windows-installation.md), [NVIDIA](https://unsloth.ai/docs/zh/kuai-su-kai-shi/install/pip-install.md), [AMD](https://unsloth.ai/docs/zh/kuai-su-kai-shi/install/amd.md)、Intel 和 CPU 配置。

<a href="https://unsloth.ai/download" class="button primary" data-icon="down-to-bracket">下载 Unsloth</a>

* <i class="fa-apple">:apple:</i> [下载 macOS 版](https://unsloth.ai/download/mac)
* <i class="fa-windows">:windows:</i> [下载 Windows 版](https://unsloth.ai/download/windows)
* <i class="fa-linux">:linux:</i> [下载 Linux 版](https://unsloth.ai/download/linux)

或者，如果你更喜欢手动安装：

**macOS、Linux、WSL：**

```bash
curl -fsSL https://unsloth.ai/install.sh | sh
```

**Windows PowerShell：**

```bash
irm https://unsloth.ai/install.ps1 | iex
```

{% endstep %}

{% step %}

#### 安装

1. 打开 Unsloth 安装程序（`.dmg`, `.exe` 文件）
2. 将 Unsloth 拖到 Mac 的“应用程序”文件夹中，或在 Windows 上完成安装。
3. 启动应用并等待安装完成
   {% endstep %}

{% step %}

#### 选择模型

打开顶部的“选择模型”下拉菜单或“模型中心”选项卡，选择适合你设备的模型和量化方式，然后下载。下载完成后即可开始聊天，无需进行任何设置。

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FNCEVgKLJI0goPqjgcg9B%2Fmodel%20hub%20models.png?alt=media&amp;token=533b5e3c-a901-4b33-963e-4a703cc9d5a6" alt="" width="563"><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### Unsloth 已准备就绪

输入消息并按 Enter 键即可开始聊天。

* **创建 API 密钥。** 点击左下角的 **Unsloth** 头像 → **设置** → **API** → 输入密钥名称 → **创建**。复制显示的 `sk-unsloth-…` 值。Unsloth 只会显示一次。
* **将客户端指向 Unsloth。** 使用 `http://localhost:PORT` 作为基础 URL，并使用你的 `sk-unsloth-…` 密钥进行身份验证。请查看下方适用于你所用工具的操作指南。

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FpAGvwjGD0iVMZKBoyu7m%2Fgreeennn.png?alt=media&amp;token=d17a5528-8375-444c-9aff-f9e9f7903bcd" alt="" width="563"><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}

### 🔑 创建 API 密钥

1. 打开侧边栏，点击左下角的 **Unsloth** 头像。
2. 前往 **设置** → **API** （地球 :globe\_with\_meridians: 图标）。
3. 输入一个易于识别的名称（例如 `claude-code-macbook`）。设置过期时间（可选）
4. 点击 **创建**.
5. **复制密钥。** Unsloth 仅存储哈希值，因此之后无法再次查看密钥。

<div data-with-frame="true"><figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FR7fhygHCl5RwG4P1MSoS%2Fimage.png?alt=media&amp;token=e2781a00-7fe5-4831-9fdb-a57234843b34" alt="" width="563"><figcaption></figcaption></figure></div>

所有密钥均以 `sk-unsloth-` 开头。你可以随时在同一页面撤销密钥。使用已撤销密钥发出的请求会返回 `401 Unauthorized`.

{% hint style="warning" %}
请像保护密码一样保护 API 密钥。任何拥有此密钥并能访问网络的用户，都可以向已加载的模型发送请求。
{% endhint %}

### ⏳ 模型加载中

{% stepper %}
{% step %}

#### 选择模型

使用 API 前，请先从聊天页面左上角的 **选择模型** 下拉菜单中加载一个模型。

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FuZqd6tcZ5LgMSh4ZND5x%2Fexport-1778505117710-24fps.gif?alt=media&amp;token=9defec95-5404-4654-9c33-67be967c9820" alt=""><figcaption></figcaption></figure>

本指南将使用：

`unsloth/gemma-4-26B-A4B-it-GGUF` 以及推荐的 `UD-Q4_K_XL` 量化方案。
{% endstep %}

{% step %}

#### 测试模型

使用客户端前，先发送一条简短消息：

<div data-with-frame="true"><figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2F2Ivilke0aJX8AHWDwSmr%2Fimage.png?alt=media&amp;token=9f9380b9-f963-4861-a17b-fd0fe16684d4" alt="" width="563"><figcaption></figcaption></figure></div>

{% hint style="info" %}
这样可以确认模型已正确加载并准备好响应。
{% endhint %}
{% endstep %}

{% step %}

#### **Unsloth API 密钥**

在 Unsloth 中，打开 **设置 → API** 即可查看或创建 API 密钥。

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FAZwaRmBVPpXA2SFhMGW9%2Fexport-1778506924396-30fps.gif?alt=media&amp;token=96f3f1a7-fce4-4508-b1b0-e8b6294dc423" alt=""><figcaption></figcaption></figure>

请像保护密码一样保护 API 密钥，避免在屏幕截图或代码仓库中泄露。
{% endstep %}
{% endstepper %}

### <i class="fa-terminal">:terminal:</i> Unsloth 运行命令

1. **安装或更新 Unsloth Studio。** 较早版本不提供外部 API。请参阅安装说明。
2. **加载 GGUF 模型。** 使用运行命令加载 GGUF 模型。这也会在默认端口启动 UI。端点 URL 和 API 密钥将打印在控制台中，供你与所选客户端配合使用。

   ```bash
   unsloth run --model unsloth/Qwen3.8-27B-GGUF-GGUF:UD-Q4_K_XL
       --temp 1.0 \
       --top-p 0.95 \
       --top-k 20 \
       --min-p 0.0 \
       --chat-template-kwargs '{"reasoning_effort":"medium"}'
   ```

根据需要调整设置。

#### 从命令行界面加载模型

你可以加载模型，并自动创建 API 密钥，方法是使用 `unsloth` CLI 工具。模型加载完成后，终端中会显示端点 URL 和 API 密钥。将它们复制到你选择的客户端中，即可开始使用。

#### 开始之前

请确保使用的是较新版本的 Unsloth Studio，因为较早版本不会公开外部 API。请参阅 [安装](https://unsloth.ai/docs/zh/xin/studio/install.md).

#### 快速开始

打开终端并加载 GGUF 模型：

```bash
unsloth run --model unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_XL
```

这会在默认端口启动服务器、加载 UI，并显示端点 URL 和 API 密钥。

#### 模型名称的用法

指定模型有几种不同的方式。请选择你觉得最简单的一种：

```bash
# 合并写法：在一个字符串中指定仓库和量化变体（推荐——最简短）
unsloth run --model unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_XL

# 分开写法：用两个标志分别指定仓库和变体（较旧的写法，仍然可用）
unsloth run --model unsloth/gemma-4-26B-A4B-it-GGUF --gguf-variant UD-Q4_K_XL

# 使用 -hf / --hf-repo（与 llama.cpp 的写法一致，适合从 llama.cpp 迁移的用户）
unsloth run -hf unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_XL
```

### 调整运行参数（可选）

基本加载无需设置这些参数，但 `unsloth run` 支持许多 llama-server 运行时标志，可用于自定义性能、内存用量、上下文长度、生成行为、网络设置和工具访问。

其他标志会直接传递给底层推理服务器，你设置的值会覆盖 Unsloth 的默认值。如果未设置任何配置或采样标志，Unsloth 会自动为模型选择最佳/推荐设置，包括上下文长度、温度等。

#### 控制推理行为

某些支持推理的模型提供了额外标志，可用于控制思考和推理行为。

```bash
# 禁用推理/思考输出
unsloth run \
  --model unsloth/Qwen3.8-27B-GGUF:UD-Q4_K_XL \
  --reasoning on  \
  --reasoning-effort medium
```

推理力度及其标志取决于模型支持的功能。

#### 调整生成行为

采样设置用于控制模型生成内容时的创造性、专注度或确定性。

```bash
# 降低随机性并提高可复现性
unsloth run \
  --model unsloth/Qwen3-1.7B-GGUF \
  --temp 0.6 \
  --seed 42
```

较低的温度值通常会产生更稳定的输出，而 top-p、top-k、min-p 和重复惩罚设置则可进一步控制 token 选择和重复。

```bash
# 调整 token 选择和重复行为
unsloth run \
  --model unsloth/Qwen3-1.7B-GGUF \
  --top-p 0.95 \
  --top-k 20 \
  --min-p 0.05 \
  --repeat-penalty 1.1
```

#### 增加上下文长度和 CPU 线程数

如果你正在处理大型项目、长对话或需要更多内存的智能体工作流，这些设置会很有用。

```bash
# 使用更大的上下文窗口和更多 CPU 线程
unsloth run \
  --model unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_XL \
  -c 131072 \
  --threads 32
```

#### 在本地网络中公开 API

默认情况下，Unsloth 只在本机运行。你可以通过绑定到以下地址，让网络中的其他设备也能访问 API： `0.0.0.0`.

```bash
# 允许局域网设备连接
unsloth run \
  --model unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_XL \
  -H 0.0.0.0 \
  -p 8888
```

#### 启用或禁用服务器端工具

控制推理服务器是否提供网页搜索和代码执行等工具。

```bash
# 显式启用工具
unsloth run \
  --model unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_XL \
  --enable-tools
```

```bash
# 显式禁用工具
unsloth run \
  --model unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_XL \
  --disable-tools
```

Unsloth 支持大多数 llama-server 运行时标志，包括上下文大小、GPU 层数、线程、采样、网络和工具配置。

完整的受支持运行时标志列表，请参阅 [llama-server](https://github.com/ggml-org/llama.cpp/tree/master/tools/server) 文档。

#### **服务器端工具策略**

服务器端工具会在主机上运行网页搜索、Python 和终端代码。绑定地址不会影响工具策略。

**默认行为（不带标志时）：**

* `unsloth run` / `unsloth studio run`：工具默认开启，包括在 `0.0.0.0`。请求可通过 `"enable_tools": false`选择关闭，UI 在工具开关关闭时也会这样做。
* `unsloth studio` / Desktop：由每个请求的 `enable_tools` 控制访问；省略该参数时默认关闭。

**标志（适用于这两个命令）：**

* `--enable-tools`：强制为 OpenAI 兼容请求启用工具，并覆盖 `"enable_tools": false`.
* `--disable-tools`：在所有端点强制关闭工具；请求无法覆盖此设置。在对外开放 Unsloth 或允许外部代理运行自己的工具时使用。
* `--yes` / `-y`：仅用于兼容性。工具策略不会触发提示。

**Anthropic 兼容接口** `/v1/messages`：必须设置 `"enable_tools": true` 或使用内置服务器工具，例如 `web_search`。CLI 默认设置和 `--enable-tools` 单独使用都无法启用它。 `--disable-tools` 或 `"enable_tools": false` 会将其禁用。

{% hint style="warning" %}
这些工具会以你的用户身份执行代码。请妥善保管 API 密钥：任何拥有该密钥并能访问网络的人都可以使用已启用的工具。对外开放 Unsloth 时，请使用 `--disable-tools` 。
{% endhint %}

<div data-with-frame="true"><figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FZcUxtSPiIJ4cXqe3zCYg%2Funsloth_run_model.lossless.webp?alt=media" alt=""><figcaption></figcaption></figure></div>

### 🌐 端点

Unsloth 会在启动时使用的端口上提供 API，通常为 `http://localhost:8000` 或 `http://localhost:8888`.

使用以下 `Authorization: Bearer sk-unsloth-…` 标头对每个请求进行身份验证。端点是否可用取决于 Unsloth 版本、后端和模型。

**聊天和文本**

| 端点                          | 用途                                                             |
| --------------------------- | -------------------------------------------------------------- |
| `POST /v1/chat/completions` | 兼容 OpenAI 的聊天补全接口，支持流式传输和工具调用。                                 |
| `POST /v1/responses`        | 兼容 OpenAI 的 Responses API，供 Codex 和其他兼容客户端使用。                  |
| `POST /v1/messages`         | 兼容 Anthropic 的 Messages API，供 Claude Code、OpenClaw 和其他兼容客户端使用。 |
| `POST /v1/completions`      | 不带聊天格式的文本补全。需要 GGUF 或 MLX 模型。                                  |

对于 Responses 请求，请在以下字段中发送对话历史： `input`。不支持通过以下字段由服务器管理历史记录： `previous_response_id` 或 `conversation` 。

**模型、嵌入和令牌计数**

| 端点                               | 用途                                        |
| -------------------------------- | ----------------------------------------- |
| `GET /v1/models`                 | 列出已加载和本地可用的模型。检查 `loaded` 以确定当前驻留在内存中的模型。 |
| `GET /v1/models/{model_id}`      | 获取模型元数据。                                  |
| `GET /v1/props`                  | 读取与 llama-server 兼容的服务器属性。                |
| `POST /v1/embeddings`            | 使用已加载的嵌入 GGUF 模型或 Unsloth 配置的嵌入模型生成嵌入。    |
| `POST /v1/chat/count_tokens`     | 统计 OpenAI 格式消息的提示词令牌数。                    |
| `POST /v1/messages/count_tokens` | 统计 Anthropic 格式消息的输入令牌数。                  |

**图像**

| 端点                            | 用途                   |
| ----------------------------- | -------------------- |
| `POST /v1/images/generations` | 使用受支持的扩散模型根据提示词生成图像。 |

**音频**

| 端点                              | 用途                                    |
| ------------------------------- | ------------------------------------- |
| `POST /v1/audio/speech`         | 兼容 OpenAI 的文本转语音接口。                   |
| `POST /v1/audio/generate`       | 根据聊天格式的消息生成语音；返回 base64 编码的 WAV 音频。   |
| `POST /v1/audio/transcriptions` | 转录上传的音频文件。                            |
| `POST /v1/audio/translations`   | 将上传音频文件中的语音翻译成英语。                     |
| `POST /v1/audio/inputs`         | 上传音频以供重复使用。将音频作为原始请求正文发送。             |
| `POST /v1/audio/run`            | 运行音频工作流，具体任务取决于模型，例如克隆、编辑、转换、音乐生成或分离。 |

已存储的音频输入支持 `GET /v1/audio/inputs/{input_id}/file` 和 `DELETE /v1/audio/inputs/{input_id}`.

通过以下接口管理已保存的语音： `GET` 或 `POST /v1/audio/voices`, `PATCH` 或 `DELETE /v1/audio/voices/{voice_id}`以及 `GET /v1/audio/voices/{voice_id}/file`.

**视频**

| 端点                                  | 用途          |
| ----------------------------------- | ----------- |
| `POST /v1/videos`                   | 创建视频生成任务。   |
| `GET /v1/videos`                    | 列出视频任务。     |
| `GET /v1/videos/{video_id}`         | 获取任务状态和元数据。 |
| `GET /v1/videos/{video_id}/content` | 下载已完成的视频。   |
| `DELETE /v1/videos/{video_id}`      | 删除视频任务。     |

图像、音频和视频生成需要使用支持所请求任务的模型。

**结构化决策**

| 端点                   | 用途                       |
| -------------------- | ------------------------ |
| `POST /v1/systemone` | 使用 Decision API 回答结构化问题。 |

先在 **设置 → API** 中启用 Decision API 并选择一个决策模型。请求使用 `state` 以及命名的 `questions`，问题类型可以是 `noul`, `choice`或 `score`.

**探索本地 API**

打开 `http://localhost:8888/docs` 以查看 Unsloth 生成的交互式 API 参考文档，或打开 `/openapi.json` 查看机器可读的架构。请将 `8888` 替换为你的 Unsloth 端口。

此参考文档反映了你安装的版本，并包含 Unsloth 内部路由。部分兼容性路由会被隐藏，手动解析的请求正文可能没有完整的架构。

请参阅 [Curl 和 HTTP](https://unsloth.ai/docs/integrations/connect-curl-and-http-to-unsloth) 了解请求示例。

### 🖇️ 连接客户端

Unsloth 支持通过大多数框架运行本地 LLM，包括 [Claude Code](https://unsloth.ai/docs/zh/ji-chu-zhi-shi/claude-code.md), [Codex](https://unsloth.ai/docs/zh/ji-chu-zhi-shi/codex.md), [OpenClaw](https://unsloth.ai/docs/zh/ji-cheng/openclaw.md), [OpenCode](https://unsloth.ai/docs/zh/ji-cheng/opencode.md) 等。点击下方相应工具，查看使用指南：

{% columns %}
{% column width="50%" %}
{% content-ref url="/pages/1a707991086189a8e5cd8374f3ce1b81915bc159" %}
[Claude Code](https://unsloth.ai/docs/zh/ji-chu-zhi-shi/claude-code.md)
{% endcontent-ref %}

{% content-ref url="/pages/b71ddea7924324c058a771e5e831c3cb6fc75b18" %}
[OpenAI Codex](https://unsloth.ai/docs/zh/ji-chu-zhi-shi/codex.md)
{% endcontent-ref %}

{% content-ref url="/pages/4636d45e7e20328c61211d43c235257fdd7ebc1d" %}
[Curl & HTTP](https://unsloth.ai/docs/zh/ji-cheng/jiang-curl-he-http-lian-jie-dao-unsloth.md)
{% endcontent-ref %}
{% endcolumn %}

{% column width="50%" %}
{% content-ref url="/pages/f1eb04d9bdae8f6dbb3d9ed5d64e060dac5a68ff" %}
[OpenClaw](https://unsloth.ai/docs/zh/ji-cheng/openclaw.md)
{% endcontent-ref %}

{% content-ref url="/pages/124bfded8d8412a9fbc1614fa7467985c0af22da" %}
[OpenCode](https://unsloth.ai/docs/zh/ji-cheng/opencode.md)
{% endcontent-ref %}

{% content-ref url="/pages/010e01be868ae39c13b48ffdf9774e645c6a347f" %}
[Python SDK](https://unsloth.ai/docs/zh/ji-cheng/jiang-python-sdk-lian-jie-dao-unsloth.md)
{% endcontent-ref %}
{% endcolumn %}
{% endcolumns %}

要从另一台机器访问此端点，请使用以下命令启动： `unsloth studio --secure`。Unsloth 仍绑定到 localhost，并通过 Cloudflare 发布一个可用的 HTTPS URL；请将此 URL 用作客户端的基础 URL，替代 `http://127.0.0.1:8888` 。请注意，服务器发送事件无法通过 Cloudflare 快速隧道传输，因此通过此隧道调用时，请设置 `stream: false` 。

### 🧰 工具调用

两个端点都支持原生格式的函数/工具调用，也支持 Unsloth 专用简写，以调用 Unsloth 内置工具。

**OpenAI 风格的工具：** 将 `tools` 和 `tool_choice` 发送到 `/v1/chat/completions` ，用法与 OpenAI 完全相同。Claude Code（通过 `/v1/messages`）、opencode、Cursor、Continue 和 Cline 均可开箱即用。

**Anthropic 风格的工具：** 将 `tools` （包含 `input_schema`）和 `tool_choice` 发送到 `/v1/messages` ，用法与 Claude 完全相同。

Unsloth 服务器端工具：Unsloth 可在服务器端执行 Python、网络搜索和 bash 命令 *服务器端* ，并将结果作为 `tool_result` 事件流式传回。要启用此功能，请向任一端点添加以下额外字段：

```json
{
  "messages": [{"role": "user", "content": "What is 123 * 456? Use Python."}],
  "stream": true,
  "enable_tools": true,
  "enabled_tools": ["python", "web_search","terminal"],
  "session_id": "my-session"
}
```

模型会在下一轮中读取每个工具的输出。有关更深入的介绍（包括架构、流式事件和调用链），请参阅 。

{% hint style="info" %}
如果你使用 Anthropic `/v1/messages` 端点， `tool_choice` 可以直接映射：Anthropic `auto` → OpenAI `auto`，Anthropic `any` → OpenAI `required`，Anthropic `{type: "tool", name: "x"}` → OpenAI `{type: "function", function: {name: "x"}}`，Anthropic `none` → OpenAI `none`.
{% endhint %}

### 📈 API 监控

通过此端点发出的每次调用都会实时显示在 Unsloth 的两个位置：

API 密钥流量一到达，API 监控侧边栏就会自动在角落打开。它会汇总当前使用的模型、实时请求、错误和平均延迟。

<div data-with-frame="true"><figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FqbcbkrU9tnkg5VCnDzCz%2Fimage.png?alt=media&amp;token=733b2b37-4e57-48c6-b826-9f356d648344" alt=""><figcaption></figcaption></figure></div>

点击“展开为完整监控”，或前往“设置”>“API 监控”，打开完整的 **API** 页面；监控中会显示模型加载情况、提示词、响应、令牌数量、首令牌耗时、吞吐量和错误消息。

<div data-with-frame="true"><figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FfjIh57Mb278c072g27nk%2Fimage.png?alt=media&amp;token=3a236c7c-1f00-430b-92f3-42799346aa3c" alt="" width="563"><figcaption></figcaption></figure></div>

### ❔ 故障排除

**`401 Unauthorized`** ：可能是 `Authorization` 请求头缺失或密钥错误。密钥必须以以下形式传递： `Authorization: Bearer sk-unsloth-…`。如果你丢失了密钥，请前往 **设置 → API。** Unsloth 不会在密钥创建后再次显示旧密钥。

**`Lost connection to the model server`** ：Unsloth 无法连接到底层的 llama.cpp 服务器。通常是模型加载完成后崩溃，或是在 Unsloth 中关闭了模型标签页。请从 **新建聊天** 重新加载模型，然后重试。

**Claude Code 显示的是默认 Anthropic 模型，而不是我的本地模型** ：请确认在运行 **同一个** 的 shell 中已导出全部三个环境变量： `claude`:

```bash
echo $ANTHROPIC_BASE_URL
echo $ANTHROPIC_AUTH_TOKEN
echo $ANTHROPIC_MODEL
```

然后在 Claude Code 中运行 `/model` 进行确认。在 Windows PowerShell 中，请使用 `$env:ANTHROPIC_BASE_URL` 等变量。

**`stream: true` 返回的是单个 JSON 数据块，而不是 SSE** ：请确认请求发送到了正确的路径（`/v1/messages` 或 `/v1/chat/completions`），并确认 HTTP 客户端确实在以流的方式接收响应，而不是先将其缓冲起来。

**我找不到要添加到 opencode（或 OpenClaw / 其他客户端）的模型名称** ：请直接咨询 Unsloth。 `GET /v1/models` 会返回你需要填入客户端“模型 ID”字段的确切模型 ID：

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

你会收到如下格式的 JSON 负载： `{"data": [{"id": "gemma-4-26B-A4B-it-GGUF", ...}]}`。复制 `id` 的值；这是 opencode 的 **模型 ID** 字段（左栏）以及 OpenClaw 的 `models[].id` 所需的值。右侧的显示名称可以按需设置，供用户查看。

**工具调用未执行** ：模型需要支持客户端工具调用（`tools` / `tool_choice`）。对于 Unsloth 内置工具，记得设置 `enable_tools: true` **并在** 中列出你想使用的工具 `enabled_tools` （例如 `["python", "web_search"]`).

* **我的客户端报告连接错误。** 打开 API 监控页面。如果没有该调用的记录，说明请求未到达 Unsloth；请将客户端的基础 URL 与该页面顶部显示的 **基础 URL** 进行比较。
* **回复被截断。** 检查 API 监控中该请求的 **已使用上下文** 。如果使用率接近 100%，或停止原因是 `length`，则表示上下文窗口已满，而不是模型运行失败。


---

# 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/zh/ji-chu-zhi-shi/api.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.
