# 将 Curl 和 HTTP 连接到 Unsloth

Unsloth 在 Unsloth 启动时所使用端口的同一基础 URL 上公开了三种与 OpenAI/Anthropic 兼容的线协议格式。它们都接受一个 `Authorization: Bearer sk-unsloth-…` 标头，并根据你是否设置了 `stream`来返回 JSON 或 SSE。 \
\
本页按端点对这些用法进行分组（`/v1/chat/completions`, `/v1/messages`, `/v1/responses`, `/v1/models`），并在最后提供一个关于 Unsloth 内置 **服务端工具**的共享章节，它们可在所有聊天端点中使用。

{% hint style="info" %}
如果你不确定该使用什么 URL / 密钥 / 模型名称，请先阅读 API 概览。它会带你完成启动 Unsloth、加载模型以及创建一个 `sk-unsloth-…` 密钥。
{% endhint %}

### 🔑 身份验证

每个请求都需要一个 `Authorization` 标头：

```
Authorization: Bearer sk-unsloth-xxxxxxxxxxxx
```

为了避免密钥出现在你的 shell 历史记录中，请导出一次密钥并引用该环境变量：

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

下面的代码片段为了清晰起见，直接内联了密钥，写作 `sk-unsloth-xxxxxxxxxxxx` 。在实际使用中，请替换为 `$UNSLOTH_STUDIO_API_KEY`.

### 📋 列出已加载的模型

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

响应：

```json
{
  "object": "list",
  "data": [
    {"id": "unsloth/gemma-3-27b-it-GGUF", "object": "model", "owned_by": "local"}
  ]
}
```

<figure><img src="/files/354965cb5a04443b82a596dcc2418902fc5bf610" alt=""><figcaption></figcaption></figure>

使用 `id` 字段，每当请求需要一个 `"model"` 值时都应如此使用（或者当像 opencode 这样的客户端要求一个 **模型 ID**).

### 💬 聊天补全（`/v1/chat/completions`)

OpenAI Chat Completions 方言。兼容范围最广。可与 OpenAI SDK、opencode、Cursor、Continue、Cline、Open WebUI、SillyTavern 以及大多数兼容 OpenAI 的工具一起使用。

#### 基本请求

```bash
curl http://localhost:8888/v1/chat/completions \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "default",
    "messages": [{"role": "user", "content": "Hello"}]
  }'
```

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

#### 流式传输

添加 `"stream": true` 后，响应会切换为 Server-Sent Events（`text/event-stream`）。告诉 `curl` 在字节到达时立即刷新输出，使用 `--no-buffer` (`-N`):

```bash
curl -N http://localhost:8888/v1/chat/completions \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen-local",
    "messages": [{"role": "user", "content": "写一首关于本地运行 LLM 的俳句。"}],
    "stream": true
  }'
```

响应的每一行看起来都像 `data: {"choices":[{"delta":{"content":"..."}}]}`，最后以 `data: [DONE]`.

<figure><img src="/files/59a0b02ca41beb609be13946dad9b8c262fa0924" alt=""><figcaption></figcaption></figure>

#### 图像（视觉）

将图像作为一个 `image_url` 内容部分附加到用户消息中。URL 可以是 HTTPS，也可以是 base64 `data:` URI：

```bash
# 将本地文件嵌入为 base64（为简洁起见已截断）
IMG=$(base64 -w 0 test.jpg)

cat > /tmp/request.json <<EOF
{
  "model":"default",
  "messages":[{"role":"user","content":[
    {"type":"text","text":"描述这张图片。"},
    {"type":"image_url","image_url":{"url":"data:image/jpeg;base64,$IMG"}}
  ]}],
  "max_tokens":200,
  "stream":false
}
EOF

curl http://localhost:8888/v1/chat/completions \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d @/tmp/request.json
```

{% hint style="info" %}
已加载的模型必须是多模态的。如果你加载的是纯文本模型，请求在结构上会成功，但模型不会处理图像。
{% endhint %}

<figure><img src="/files/6c9f735aab756159ffb3d332327cea57ded73329" alt=""><figcaption></figcaption></figure>

#### 函数调用（OpenAI tools）

传入 OpenAI 风格的 `tools` 以及（可选的） `tool_choice`。你的客户端会运行每个工具调用，并在下一轮返回结果。

```bash
curl http://localhost:8888/v1/chat/completions \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model":"default",
    "input":[{"role":"user","content":"巴黎的天气怎么样？"}],
    "tools":[{
      "type":"function",
      "name":"get_weather",
      "description":"获取某个城市的当前天气。",
      "parameters":{
        "type":"object",
        "properties":{"city":{"type":"string"}},
        "required":["city"]
      }
    }],
    "tool_choice":"required"
  }' | jq '.output, .usage'
```

<figure><img src="/files/98ed488230113b528f6659e7b310ca50b8eca5e9" alt=""><figcaption></figcaption></figure>

### 📨 Anthropic Messages（`/v1/messages`)

Unsloth 与 Anthropic 兼容的方言，被 Claude Code、Anthropic SDK、OpenClaw 以及任何使用 Messages API 的客户端所使用。

#### 基本请求

```bash
curl http://localhost:8888/v1/messages \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "default",
    "max_tokens": 1024,
    "messages": [{"role": "user", "content": "Hello"}]
  }'
```

{% hint style="warning" %}
`max_tokens` 是必需的，在 `/v1/messages` （而它在 `/v1/chat/completions`).
{% endhint %}

<figure><img src="/files/801c9aef0a134c2eca7b7b1172251e568ad36487" alt=""><figcaption></figcaption></figure>

#### 流式传输

```bash
curl -N http://localhost:8888/v1/messages \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen-local",
    "max_tokens": 1024,
    "messages": [{"role": "user", "content": "用两句话解释 LoRA。"}],
    "stream": true
  }'
```

事件遵循 Anthropic 的 SSE 结构： `message_start`, `content_block_start`, `content_block_delta`, `content_block_stop`, `message_delta`, `message_stop`，再加上 Unsloth 自定义的 `tool_result` 事件，用于服务端工具输出。

#### 图像（视觉）

Anthropic 风格的图像内容使用一个 `source` 块，其中包含 base64 数据：

```bash
IMG=$(base64 -w 0 test.jpg)

cat > /tmp/request.json <<EOF
{
  "messages":[{"role":"user","content":[
    {"type":"text","text":"描述这张图片。"},
    {"type":"image","source":{"type":"base64","media_type":"image/jpeg","data":"$IMG"}}
  ]}],
  "max_tokens":200,
  "stream":true
}
EOF

curl -s http://3.128.175.236:8888/v1/messages \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxx" \
  -H "Content-Type: application/json" \
  -d @/tmp/request.json
```

<figure><img src="/files/3b7230897a4383dbe5ce873392d3c45f468b48c8" alt=""><figcaption></figcaption></figure>

#### 工具调用（Anthropic tools）

```bash
curl http://localhost:8888/v1/messages \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen-local",
    "max_tokens": 1024,
    "messages": [{"role": "user", "content": "东京的天气怎么样？"}],
    "tools": [
      {
        "name": "get_weather",
        "description": "获取某个城市的当前天气",
        "input_schema": {
          "type": "object",
          "properties": {
            "city": {"type": "string"}
          },
          "required": ["city"]
        }
      }
    ],
    "tool_choice": {"type": "auto"}
  }'
```

`tool_choice` 这些值映射到 OpenAI 方言的方式如下：Anthropic `auto` → OpenAI `auto`，Anthropic `any` → OpenAI `required`，Anthropic `{type: "tool", name: "x"}` → OpenAI `{type: "function", function: {name: "x"}}`，Anthropic `none` → OpenAI `none`.

<figure><img src="/files/3e52951e7dca2070edb066d75aa3e105cbd9e4d2" alt=""><figcaption></figcaption></figure>

### 🧬 Responses（`/v1/responses`)

Unsloth 还支持更新的 **OpenAI Responses API**, ，这是 Codex 和其他近期 OpenAI 客户端已迁移到的协议。

```bash
curl http://localhost:8888/v1/responses \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen-local",
    "input": "写一句问候语。"
  }'
```

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

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

流式传输的工作方式与 Chat Completions 相同。添加 `"stream": true` 并通过以下方式管道传递 `-N`.

### 🧰 Unsloth 服务端工具（简写）

除了客户端侧函数调用之外，Unsloth 还可以在服务端执行 **Python**, **bash**，以及 **网页搜索** ，并将结果作为自定义 `tool_result` 事件流式返回。这项功能让 Unsloth 开箱即用时就像一个“真正的”代理，无需通过你的客户端来回传递工具调用。

通过向 **任一** `/v1/chat/completions` 或 `/v1/messages`:

| 字段                | 类型              | 说明                                            |
| ----------------- | --------------- | --------------------------------------------- |
| `enable_thinking` | `布尔值`           | `false` 以禁用思考。 `true` 默认                      |
| `enable_tools`    | `布尔值`           | `true` 以启用服务端工具执行。                            |
| `enabled_tools`   | `array<string>` | 模型可以调用哪些工具。支持 `python`, `bash`, `web_search`. |
| `session_id`      | `字符串`           | 可选。可在多次调用之间持久化工具状态（例如 Python 内核）。             |

#### 思考模式

思考模式默认启用。&#x20;

```bash
curl http://localhost:8888/v1/chat/completions \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "default",
    "messages": [{"role": "user", "content": "用一句话总结量子隧穿"}],
    "stream": false,
  }'
```

模型会先思考再给出答案。

<figure><img src="/files/2087a6de6dda1c4ac950bf11e6e6c1a6d5930400" alt=""><figcaption></figcaption></figure>

要禁用思考，请传递 `enable_thinking: false` 在你的请求中。模型将不经过先思考而直接给出答案。

<figure><img src="/files/9e5df032c743b4fccfd6dc3247157c9554a6361f" alt=""><figcaption></figcaption></figure>

#### Python 执行

```bash
curl http://localhost:8888/v1/chat/completions \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen-local",
    "messages": [{"role": "user", "content": "123 * 456 等于多少？请使用代码计算。"}],
    "stream": false,
    "enable_tools": true,
    "enabled_tools": ["python"],
    "session_id": "my-session"
  }'
```

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

#### 网页搜索 + Python（流式）

```bash
curl http://localhost:8888/v1/chat/completions \
  -H "Authorization: Bearer sk-unsloth-xxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen-local",
    "messages": [{"role": "user", "content": "搜索 Python 3.13 的特性"}],
    "stream": true,
    "enable_tools": true,
    "enabled_tools": ["web_search", "python"],
    "session_id": "my-session"
  }'
```

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

#### 在 `/v1/messages`

同样的简写也适用于 Anthropic Messages 端点：

```bash
curl http://localhost:8888/v1/messages \
  -H "Authorization: Bearer sk-unsloth-xxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen-local",
    "max_tokens": 1024,
    "messages": [{"role": "user", "content": "搜索 Python 3.13 的特性"}],
    "stream": true,
    "enable_tools": true,
    "enabled_tools": ["web_search", "python"],
    "session_id": "my-session"
  }'
```

<figure><img src="/files/769636884b4ba8eaaf002cf9373578429f1192f0" alt=""><figcaption></figcaption></figure>

Unsloth 会流式传输它自己的 `tool_result` SSE 事件，此外还会传输标准 Anthropic / OpenAI 事件类型，模型会在下一轮看到每个工具的输出。

### ❔ 故障排查

**`401 未授权`** **-** 该 `Authorization` 标头缺失或密钥错误。请再次检查： `Authorization: Bearer sk-unsloth-…`.

**`curl` 流式请求时挂起 -** 添加 `-N` （与 `--no-buffer`相同）。没有它， `curl` 会缓冲 SSE 流，直到结束你才会看到输出。

**不同操作系统之间的 Base64 编码不同** **-** Linux 的 `base64` 默认会换行，而 macOS / BSD 不会。请在 Linux 上使用 `base64 -w 0` ，在 macOS 上使用 `base64` ，或者将输出通过管道传递给 `tr -d '\n'`.

**shell 中的 JSON 转义** **-** Heredoc（`-d @file.json`）在请求体变复杂后比内联字符串更清晰。示例： `curl ... -d @body.json`.

**`max_tokens` 报错于 `/v1/messages`** **-** Anthropic 方言要求它。请添加 `"max_tokens": 1024` （或你想要的任何限制）。

对于端点级别的问题（模型未加载、连接断开、端口错误），请参阅 API 概览页面。


---

# Agent Instructions: 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/zh/ji-cheng/jiang-curl-he-http-lian-jie-dao-unsloth.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.
