> 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/api.md).

# 如何将 Unsloth 用作 API 端点

你可以运行 **本地 LLM** 搭配以下工具： [Claude Code](/docs/zh/ji-chu/claude-code.md) 和 [Codex](/docs/zh/ji-chu/codex.md) ，方法是将这些工具连接到 Unsloth 的 **兼容 OpenAI 的 API 端点**。这让你可以本地运行诸如 [Qwen](/docs/zh/mo-xing/qwen3.6.md) 和 [Gemma](/docs/zh/mo-xing/gemma-4.md) 之类的模型，用于代理式编码。Unsloth 还具备一些实用功能，例如自我修复的 **工具调用**, **代码执行**，以及 **网页搜索**.

Unsloth 让你轻松部署一个快速的 API 推理端点，提供：

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

{% columns %}
{% column %}
在 Unsloth 中加载的模型（包括 GGUF）会以 **已认证 API** 通过 `llama-server`的形式暴露。出于安全原因，会生成一个较长的 API 密钥，就像 OpenAI 提供的那样。

你的 **本地模型** 随后可以直接在你偏好的 AI 代理、SDK 或聊天客户端中使用。Unsloth 在同一个端口上支持两种协议。二者都支持流式输出、工具调用（OpenAI `工具` / Anthropic `工具`）以及视觉输入：
{% endcolumn %}

{% column %}

<figure><img src="/files/580b7405ac103da7c1f1bf41f5ba9751f13a3e94" 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](/docs/zh/desktop.md) 应用。它支持 [MacOS](/docs/zh/kuai-su-kai-shi/install/mac.md)、Linux、 [Windows](/docs/zh/kuai-su-kai-shi/install/windows-installation.md), [NVIDIA](/docs/zh/kuai-su-kai-shi/install/pip-install.md), [AMD](/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 的 Applications，或完成 Windows 安装。
3. 启动应用并等待安装完成
   {% endstep %}

{% step %}

#### 选择模型

打开顶部的“选择模型”下拉菜单或“模型中心”标签页，选择适合你的设备的模型和量化方式，然后下载。完成后即可开始聊天——无需额外设置。

<figure><img src="/files/ee716919ab359455030e8acd4d55b5ec13ca328d" 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="/files/b0dfb852351654c29812a5aa23885913432eaa10" 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="/files/109e6e065ed939a02a0ac33b5b8596a121d1851e" alt="" width="563"><figcaption></figcaption></figure></div>

所有密钥都以 `sk-unsloth-` 前缀开头。你可以随时在同一页面吊销密钥。使用已吊销密钥发出的请求将失败并返回 `401 未经授权`.

{% hint style="warning" %}
请像对待密码一样对待你的 API 密钥。任何拥有该密钥并能访问你的 Unsloth 实例网络的人，都可以向你加载的模型发送请求。
{% endhint %}

### ⏳ 模型加载

{% stepper %}
{% step %}

#### 选择模型

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

<figure><img src="/files/e7c1a267b0c4f58689066eddfc57a2c2211f1e13" 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="/files/d1ef1d199c3aee2da86cc3da46a133801d2683ad" alt="" width="563"><figcaption></figcaption></figure></div>

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

{% step %}

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

在 Unsloth 中打开 **设置 → API** 以查看或创建你的 API 密钥。

<figure><img src="/files/7d43e8763d1ae72290485151822b1ea2e4fce42a" alt=""><figcaption></figcaption></figure>

请像对待密码一样对待你的 API 密钥，不要在截图或仓库中暴露它。
{% endstep %}
{% endstepper %}

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

1. **安装或更新 Unsloth Studio。** 较早版本不会暴露外部 API。请参见安装。
2. **加载 GGUF 模型。** 使用 run 命令加载一个 GGUF 模型。这也会在默认端口加载 UI。端点 URL 和 API Key 会打印到控制台，供你在所选客户端中使用。

   ```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"}'
   ```

按需调整设置。

#### 从 CLI 加载模型

你可以使用 `unsloth` CLI 工具来加载模型，并自动为你创建 API 密钥。模型加载完成后，端点 URL 和 API 密钥会打印到你的控制台。将它们复制到你选择的客户端中，即可开始使用。

#### 开始之前

请确保你使用的是较新的 Unsloth Studio 版本，因为较早版本不会暴露外部 API。参见 [安装](/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 的写法一致，如果你从那里迁移过来会很方便）
unsloth run -hf unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_XL
```

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

基础加载不需要这些，但 `unsloth run` 支持许多 llama-server 运行时标志，可用于自定义性能、内存使用、上下文长度、生成行为、网络以及工具访问。

额外标志会直接转发给底层推理服务器，你的设置会覆盖 Unsloth 的默认值。

#### 调整生成行为

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

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

较低的 temperature 值通常会产生更稳定的输出，而 top-p、top-k、min-p 和 repeat penalty 设置可进一步控制 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/Qwen3-1.7B-GGUF \\
  --reasoning off
```

```bash
# 启用推理模式
unsloth run \\
  --model unsloth/Qwen3-1.7B-GGUF \\
  --reasoning on
```

推理支持取决于模型和后端能力。

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

控制诸如网页搜索和代码执行之类的工具是否由推理服务器暴露。

```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) 文档以获取支持的运行时标志完整列表。

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

`unsloth run` 控制推理服务器是否暴露服务器端工具（网页搜索、代码执行等）。默认值取决于绑定地址：

* **`127.0.0.1` （localhost）** — 工具 **默认开启** 。只有你的机器可以访问服务器。
* **`0.0.0.0` 或任何非回环地址** — 工具 **默认关闭** 。如果在暴露于网络的服务器上泄露了 API 密钥，就意味着主机上可能执行任意代码。

**标志：**

* `--enable-tools` / `--disable-tools` — 强制开启或关闭。开启时 `0.0.0.0`, `--enable-tools` 会显示 y/N 安全提示。
* `--yes` / `-y` — 跳过提示（用于自动化）。

解析后的策略是进程级的硬性覆盖——单个请求不能通过 `enable_tools=true` 在请求体中绕过它。

<div data-with-frame="true"><figure><img src="/files/cc987c669523513c4b352410069e817c5d25aeff" alt=""><figcaption></figcaption></figure></div>

### 🌐 **端点**

Unsloth 会在启动所用的端口上暴露这些端点（通常是 `http://localhost:8000` 或 `http://localhost:8888`):

| 端点                          | 兼容项                         | 可从以下客户端使用                                                    |
| --------------------------- | --------------------------- | ------------------------------------------------------------ |
| `POST /v1/messages`         | Anthropic Messages API      | Claude Code、Anthropic SDK、OpenClaw，以及任何支持 Anthropic 协议的工具    |
| `POST /v1/chat/completions` | OpenAI Chat Completions API | OpenAI SDK、opencode、Cursor、Continue、Cline、Open WebUI、curl 等。 |
| `GET /v1/models`            | OpenAI 模型列表                 | 列出当前在 Unsloth 中加载的模型                                         |

使用以下方式进行身份验证： `Authorization: Bearer sk-unsloth-…` 每个请求都要带上此 header。

{% hint style="info" %}
你无需为两种格式运行不同的服务器。Unsloth 在同一个端口上同时处理两者。
{% endhint %}

### 🖇️ 连接你的客户端

Unsloth 让你能够通过包括以下在内的大多数框架运行本地 LLM： [Claude Code](/docs/zh/ji-chu/claude-code.md), [Codex](/docs/zh/ji-chu/codex.md), [OpenClaw](/docs/zh/ji-cheng/openclaw.md), [OpenCode](/docs/zh/ji-cheng/opencode.md) 等。点击下面的具体工具查看指南：

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

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

{% content-ref url="/pages/4636d45e7e20328c61211d43c235257fdd7ebc1d" %}
[Curl & HTTP](/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](/docs/zh/ji-cheng/openclaw.md)
{% endcontent-ref %}

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

{% content-ref url="/pages/010e01be868ae39c13b48ffdf9774e645c6a347f" %}
[Python SDK](/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 替换为 `http://127.0.0.1:8888` 作为你客户端的基础 URL。请注意，服务器发送事件在通过 Cloudflare 快速隧道时无法保留，因此在经由它调用时请设置 `stream: false` 。

### 🧰 工具调用

这两个端点都支持其原生格式的函数 / 工具调用，并提供了一个针对 Unsloth 内置工具的 Unsloth 专用简写。

**OpenAI 风格工具：** 发送 `工具` 和 `tool_choice` 到 `/v1/chat/completions` ，就像你在 OpenAI 中那样。Claude Code（通过 `/v1/messages`）

**、opencode、Cursor、Continue 和 Cline 都可以开箱即用。** 发送 `工具` Anthropic 风格工具： `（带有`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"
}
```

模型会在下一轮看到每个工具的输出。有关更深入的覆盖范围（schema、流式事件、链式调用），请参见。

{% 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 监视器

通过此端点发出的每一次调用都会实时列在 Studio 中，位置有两处：

一旦有 API key 流量到达，API 监视器侧边栏就会自动在角落打开。它会汇总当前活动模型、实时请求、错误和平均延迟。

<div data-with-frame="true"><figure><img src="/files/8e24925ada8adb4c445b8050d3158b0630e1a402" alt=""><figcaption></figcaption></figure></div>

按“展开为完整监视器”或前往 设置>API Monitor，以进入完整 **API** 页面，模型加载、提示词、响应、token 数、首 token 时间、吞吐量和错误消息都会显示在监视器中。

<div data-with-frame="true"><figure><img src="/files/5f3236168068c714be4218be7f6875efdc1b3b9b" alt="" width="563"><figcaption></figcaption></figure></div>

### ❔ 故障排除

**`401 未经授权`** ：  要么是 `Authorization` header 缺失，要么是密钥错误。密钥必须以 `Authorization: Bearer sk-unsloth-…`的形式传递。若你丢失了密钥，请从 **设置 → API。** Unsloth 在创建后不会显示旧密钥。

**`与模型服务器的连接丢失`** ：Unsloth 无法连接到底层的 llama.cpp 服务器。通常是模型已完成加载但崩溃了，或者是在 Unsloth 中关闭了模型标签页。请从以下位置重新加载模型： **新建聊天** 并重试。

**Claude Code 显示的是默认的 Anthropic 模型，而不是我的本地模型** ：请检查这三个环境变量是否都已在以下位置导出： **相同的** shell 中，你运行 `claude`:

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

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

**`stream: true` 返回单个 JSON 数据块，而不是 SSE** ：请确保你访问的是正确的路径（`/v1/messages` 或 `/v1/chat/completions`），并且你的 HTTP 客户端实际上是将响应作为流来消费，而不是缓冲它。

**我找不到要添加到 opencode（或 OpenClaw / 任何其他客户端）的模型名称** ：请直接询问 Unsloth。 `GET /v1/models` 会返回你需要填入客户端“Model 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 的 **Model ID** 字段（左列）以及 OpenClaw 的 `models[].id` 所期望的内容。右侧的显示名称可以是你希望用户看到的任何内容。

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

* **我的客户端报告连接错误。** 打开 API 监视器。若没有该调用对应的行，说明它根本没有到达 Unsloth，请将你的客户端 base URL 与 **Base 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 dynamically by asking a question.

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

```
GET https://unsloth.ai/docs/zh/ji-chu/api.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
