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

# 如何使用 OpenAI Codex 运行本地 LLM

在你的设备本地使用 OpenAI Codex 运行开源模型。

本分步指南将向你展示如何将开放式 LLM 和 API 连接到 OpenAI Codex **完全在本地**，并附带截图。Codex 只需要一个支持 OpenAI Responses API 的本地端点。可使用 Qwen、DeepSeek、Gemma 等任意开放模型运行。

本教程中，我们将使用这些开放模型： [Gemma 4](/docs/zh/mo-xing/gemma-4.md) 和 [Qwen3.5](/docs/zh/mo-xing/qwen3.5.md) 它们都是强大的智能体与编程模型（可在配备 24GB RAM/统一内存的设备上运行）。在推理方面，我们将使用 [Unsloth Studio](https://github.com/unslothai/unsloth) 和 [`llama.cpp`](https://github.com/ggml-org/llama.cpp) 可让你在 macOS、Linux 和 Windows 上运行/提供 LLM 服务。你可以替换为任何其他模型，只需在脚本和 Codex 配置中更新模型名称。

<a href="/docs/zh/ji-chu-zhi-shi/codex.md#setup-codex" class="button primary" data-icon="openai">设置 Codex</a><a href="/docs/zh/ji-chu-zhi-shi/codex.md#quickstart-tutorials" class="button primary">📖 本地模型设置教程</a>

对于模型量化版本，我们将使用 Unsloth [**动态 GGUF**](/docs/zh/ji-chu-zhi-shi/dynamic-3.0-ggufs.md) ，以便在尽可能保留准确性的同时运行量化 GGUF 模型。

{% hint style="info" %}
自 2026 年 1 月以来，Codex 已发生了很大变化。它现在专门使用 [**OpenAI Responses API**](https://platform.openai.com/docs/api-reference/responses) **专门地**，并且 Chat Completions 支持已被弃用。 [Unsloth Studio](#unsloth-tutorial) 同时支持两者，因此我们将使用 `wire_api = "responses"` 贯穿本指南。
{% endhint %}

### <i class="fa-openai">:openai:</i> 设置 Codex

[Codex](https://github.com/openai/codex) 是 OpenAI 官方的本地运行编程智能体。虽然它是为 ChatGPT 设计的，但支持 **自定义 API 端点**，因此可与本地 LLM 配合使用。稍后 Unsloth 启动后，我们将把它指向 Unsloth Studio 的 `/v1/responses` 端点。

{% tabs %}
{% tab title="Linux / WSL" %}
在终端中运行：

```bash
apt update
sudo apt install nodejs npm -y
npm install -g @openai/codex
```

{% endtab %}

{% tab title="Windows" %}
在 Windows PowerShell 中运行：

```powershell
winget install --id OpenAI.Codex
```

{% hint style="info" %}
**更喜欢 Codex 桌面应用？** 从 Microsoft Store 安装：

```powershell
winget install --id 9PLM9XGG6VKS --source msstore
```

或者通过 [Microsoft 应用商店](https://apps.microsoft.com/detail/9plm9xgg6vks)。该应用读取相同的 `%USERPROFILE%\.codex\config.toml`，因此我们稍后设置的提供商配置无论使用哪种方式都适用。
{% endhint %}

{% hint style="info" %}
**更喜欢 WSL？** 以管理员身份打开 PowerShell，运行 `wsl --install`，重启后在 Ubuntu 中按照上面的 Linux 选项卡操作。要从 WSL 访问 Windows 主机上的 Unsloth，需要使用一个小型网络技巧——请参阅“将 Codex 连接到 Unsloth”中的 WSL 提示。
{% endhint %}
{% endtab %}

{% tab title="MacOS" %}
在终端中运行：

<pre class="language-bash"><code class="lang-bash"><strong>bash brew install --cask codex
</strong></code></pre>

{% endtab %}
{% endtabs %}

安装就到这里—— **不要运行 `codex` 还不要**。直接运行它会进入 OpenAI 的“使用 ChatGPT 登录”选择界面（这是一个模态界面——没有退出方式）。配置好本地配置文件后，\
`codex --oss --profile unsloth_api` 或 `codex --oss --profile llama_cpp` 会完全跳过该页面，因为自定义提供商默认设置为 `requires_openai_auth = false`。请先启动本地模型服务器，然后针对它启动 Codex。

## 📖 快速入门教程 <a href="#quickstart-tutorials" id="quickstart-tutorials"></a>

开始前，我们首先需要完成你将使用的特定模型的设置。我们使用 [Unsloth](https://unsloth.ai/docs/new/studio) （一个 Web UI）和 llama.cpp，它们是在你的 Mac、Linux、Windows 设备上运行和提供 LLM 服务的开源框架。

{% columns %}
{% column %}
开始前，我们首先需要完成你将使用的特定模型的设置。我们使用 [Unsloth](/docs/zh/xin/studio.md) （一个 Web UI）和 llama.cpp，它们是在你的 Mac、Linux、Windows 设备上运行和提供 LLM 服务的开源框架。

Unsloth 还具有独特的自修复 [工具调用](/docs/zh/xin/studio/chat.md#auto-healing-tool-calling) 和 [网页搜索](/docs/zh/xin/studio/chat.md#code-execution) 功能。请参阅右侧连接到 Unsloth 的 Claude Code：
{% endcolumn %}

{% column %}

<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%2FEGEKo6oPthjtSf0shavs%2F127.0.0.1_8889_chat%20(2).png?alt=media&amp;token=c59c7110-402c-4d21-96c5-cd96c921a184" alt=""><figcaption></figcaption></figure></div>
{% endcolumn %}
{% endcolumns %}

<a href="/docs/zh/ji-chu-zhi-shi/codex.md#unsloth-tutorial" class="button primary">🦥 Unsloth 教程</a><a href="/pages/b71ddea7924324c058a771e5e831c3cb6fc75b18#llama.cpp-tutorial" class="button primary">🦙 llama.cpp 教程</a>

## 🦥 Unsloth 教程

在本教程中，我们将使用 UI 通过以下方式为 Claude Code 提供/连接本地模型： [Unsloth](https://github.com/unslothai/unsloth)。Unsloth 可在 Windows、WSL、Linux 和 macOS 上运行。

{% columns %}
{% column %}

* 搜索、下载， [运行 GGUF](/docs/zh/xin/studio.md#run-models-locally) 和 safetensor 模型
* [**自修复** 工具调用](/docs/zh/xin/studio.md#execute-code--heal-tool-calling) + **网页搜索**
* [**代码执行**](/docs/zh/xin/studio.md#run-models-locally) （Python、Bash）
* [自动推理](https://unsloth.ai/docs/desktop#feature-deep-dive) 参数调优（温度、top-p 等）
* 通过 llama.cpp 实现快速 CPU + GPU 推理
* [训练 LLM](/docs/zh/xin/studio.md#no-code-training) 速度提升 2 倍，显存使用减少 70%

请参阅以下安装说明：
{% endcolumn %}

{% column %}

<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%2FY3nfB43TEk7k11zcE4wm%2Fthe%20big%20one.gif?alt=media&amp;token=335be087-7375-4f89-9039-71195ee44ab8" alt=""><figcaption><p>在 Unsloth 中运行 Qwen3.6 2 位模型的示例。</p></figcaption></figure></div>
{% endcolumn %}
{% endcolumns %}

{% 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. 在 Mac 上将 Unsloth 拖到 Applications，或在 Windows 上完成设置。
3. 启动应用并等待安装完成
   {% endstep %}

{% step %}

#### 选择模型

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

<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。

* **连接工具：** [Claude Code](/docs/zh/ji-chu-zhi-shi/claude-code.md), [Codex](/docs/zh/ji-chu-zhi-shi/codex.md)、网页搜索， [MCP](/docs/zh/ji-chu-zhi-shi/mcp.md) 等更多功能
* **训练模型：** 微调文本、扩散模型、嵌入模型等
* **生成媒体：** 在本地创建和训练图像、视频、TTS

<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 指南

{% 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 密钥。如果你使用以下命令无头启动 Unsloth： `unsloth run`，密钥也会以以下形式打印到控制台： `sk-unsloth-...`.

<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 %}

### 可选：调整运行时设置

使用以下命令启动模型时，可以传入额外的运行时选项： `unsloth run`.

```bash
# 启用推理并使用更大的上下文窗口
unsloth run \
  --model unsloth/gemma-4-26B-A4B-it-GGUF \
  --reasoning on \
  -c 131072
```

支持推理的模型可以使用以下命令启动： `--reasoning on` 或 `--reasoning off`。 `-c` 标志控制可用的上下文窗口。

```bash
# 在自定义端口上为编程智能体提供服务
unsloth run \
  --model unsloth/gemma-4-26B-A4B-it-GGUF \
  --disable-tools \
  -p 8888
```

使用 `-p` ，如果你需要让 API 在不同端口上运行。

{% hint style="info" %}
驱动外部编程智能体时，添加 `--disable-tools`。这会将 Unsloth Studio 切换为直通模式，使智能体自身的工具被转发并作为工具调用返回以供智能体运行，而不是由 Unsloth 在服务器端执行其内置工具。
{% endhint %}

如需更高级的运行时配置，请参阅主 [API 调优](https://unsloth.ai/docs/basics/api#unsloth-run-command) 部分。

## ⚙️ 连接 Codex

现在我们已为 Codex 设置好本地 LLM，接下来配置 Codex 以配合你的工具使用。你可以轻松地使用 `unsloth start` 如下方式连接，或 [手动](#connect-manually).

### ⚡ 使用以下方式运行 OpenAI Codex： `unsloth start`

要直接使用模型启动 Codex，请运行：

```bash
unsloth start Code \
    --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 \
    --reasoning-effort medium
```

{% hint style="success" %}
如果未设置任何设置/采样标志，Unsloth 会自动为模型选择最佳/推荐设置，包括上下文长度、温度等。
{% endhint %}

在 Unsloth Studio 中加载 GGUF 模型后，打开你的项目文件夹并运行：

```bash
unsloth start codex
```

Unsloth 会为此次启动创建隔离的 Codex 主目录和由 Unsloth 支持的 Responses 提供商。你的常规 `~/.codex` 配置不会受到影响。

Codex 状态默认是临时的。当你希望保留由 Unsloth 管理的配置和会话时，使用 `--persist` ：

```bash
unsloth start codex --persist
unsloth start codex --persist resume --last
```

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FzXhTRRhKnT7tc5A4su0w%2FScreenshot_20260714_150727.png?alt=media&amp;token=1ad76079-1127-443e-8e2b-96545269003e" alt="OpenAI Codex running with a local GGUF model through Unsloth Studio"><figcaption><p>Codex 通过 Unsloth Studio Responses 端点连接到本地 GGUF 模型。</p></figcaption></figure>

> Codex 当前要求通过以下服务的 GGUF 模型： `llama-server` 后端。

查看完整的 `unsloth start` 有关模型加载、持久化和所有包装器选项的参考。

本指南的其余部分将介绍完全手动的 Codex 提供商设置。

#### 🔌 手动连接

本节介绍手动设置；无论你使用 Unsloth Studio、llama.cpp 还是其他兼容 OpenAI 的本地服务器，步骤都相同。Codex 需要三个值： **API 密钥**、 **基础 URL**以及 **模型名称**。以下示例使用 Unsloth Studio；对于 llama.cpp，请在 llama.cpp 部分使用具有相同结构的 `llama_cpp` 配置文件。

{% stepper %}
{% step %}

#### **配置 Unsloth 提供商**

Codex 查找 `~/.codex/config.toml` 在 macOS/Linux/WSL 上，或者 `%USERPROFILE%\.codex\config.toml` 在 Windows 上。创建或编辑它：

{% code title="\~/.codex/config.toml" overflow="wrap" %}

```toml
# 与 `codex --oss` 一起使用的默认本地提供商
oss_provider = "unsloth_api"

[model_providers.unsloth_api]
name                  = "Unsloth Studio"
base_url              = "http://localhost:8888/v1"
env_key               = "UNSLOTH_STUDIO_AUTH_TOKEN"
wire_api              = "responses"
requires_openai_auth  = false
```

{% endcode %}

接下来，为 Unsloth 创建一个 Codex 配置文件：

{% code title="\~/.codex/unsloth\_api.config.toml" overflow="wrap" %}

```toml
model_provider = "unsloth_api"
model = "unsloth/gemma-4-26B-A4B-it-GGUF"
```

{% endcode %}

{% hint style="info" %}
`模型` 必须与服务器在以下地址报告的 ID 相匹配： `GET http://localhost:8888/v1/models`。Unsloth Studio 会公开完整的仓库 ID（例如 `unsloth/gemma-4-26B-A4B-it-GGUF`）。下面的 llama.cpp 部分使用 `--alias "unsloth/gemma-4-26B-A4B"`，因此，当改为将 Codex 指向 llama-server 时，请使用该较短的 ID。
{% endhint %}

{% hint style="info" %}
此配置注册了一个 `unsloth_api` Codex 模型提供商，将其指向 Unsloth Studio，并设置 `unsloth_api` 作为以下命令的默认本地提供商： `codex --oss`。单独的 `unsloth_api` 配置文件仅在你使用以下命令启动 Codex 时选择 Unsloth 提供商和模型： `--profile unsloth_api`，因此你的常规 Codex 设置不会改变。Codex 从名为以下名称的环境变量读取 API 密钥： `UNSLOTH_STUDIO_AUTH_TOKEN`。下一步将设置真实密钥。
{% endhint %}

| 字段                     | 作用                                                                                    |
| ---------------------- | ------------------------------------------------------------------------------------- |
| `base_url`             | 你的本地服务器端点 + `/v1`                                                                     |
| `env_key`              | **名称** ，即 Codex 从中读取 API 密钥的环境变量名称。这不是密钥本身。                                           |
| `wire_api`             | `responses`。Codex 现在只使用 OpenAI 的 Responses API。                                       |
| `requires_openai_auth` | `false` 使 Codex 跳过此提供商的“使用 ChatGPT 登录”页面。默认值已经是 `false`，但请显式设置。                       |
| `模型`                   | 你的服务器公开的模型 ID。访问 `GET <base_url>/models` 以确认准确的字符串。                                   |
| `oss_provider`         | <p>设置 <code>unsloth\_api</code> 为使用以下命令启动 Codex 时的默认本地提供商：<br><code>--oss</code>.</p> |
| `requires_openai_auth` | `false` 使 Codex 跳过此提供商的“使用 ChatGPT 登录”页面。                                             |

{% hint style="warning" %}
OpenAI 已移除 `wire_api = "chat"` 支持。始终使用 `wire_api = "responses"`。如果你设置了 `wire_api = "chat"`，Codex 将拒绝启动，并显示 `` `wire_api = "chat"` 不再受支持。修复方法：在提供商配置中设置 `wire_api = "responses"`。 ``
{% endhint %}

{% hint style="info" %}
你可以创建多个配置文件，每个对应一个你要切换使用的 Unsloth 模型。使用以下命令启动你想要的配置文件： `codex --profile <profile-name>`.
{% endhint %}
{% endstep %}

{% step %}

#### 设置 API 密钥环境变量

使用你在以下位置写入的同一个环境变量名称： `env_key`。在上面的 Unsloth Studio 示例中， `env_key = "UNSLOTH_STUDIO_AUTH_TOKEN"`，因此请设置 `UNSLOTH_STUDIO_AUTH_TOKEN` ，并在将要运行 Codex 的同一终端中执行：

{% code title="macOS / Linux / WSL" %}

```bash
export UNSLOTH_STUDIO_AUTH_TOKEN=YOUR_TOKEN
```

{% endcode %}

{% code title="Windows PowerShell" %}

```powershell
$env:UNSLOTH_STUDIO_AUTH_TOKEN = "YOUR_TOKEN"
```

{% endcode %}

如果你重命名了 `env_key`，也要重命名命令中的变量。例如，使用以下内容的 llama.cpp 配置文件： `env_key = "LLAMA_CPP_API_KEY"` 需要 `LLAMA_CPP_API_KEY`，而不是 `UNSLOTH_STUDIO_AUTH_TOKEN`.

**临时会话与持久化：** 上述命令仅适用于当前终端。要持久化：

* **macOS / Linux / WSL：** 将 `export` 行添加到 `~/.bashrc` （bash）或 `~/.zshrc` （zsh）。
* **Windows：** 运行 `setx UNSLOTH_STUDIO_AUTH_TOKEN "YOUR_TOKEN"` 一次，或将 `$env:` 行添加到你的 PowerShell `$PROFILE`.

{% hint style="warning" %}
**在 WSL 内运行 Codex，而 Unsloth 在 Windows 上运行？** WSL 是独立的网络命名空间，因此 `localhost` 在 WSL 内无法访问 Unsloth。编辑你的 `config.toml` ，改用 Windows 主机 IP：

```bash
# 从 WSL 内获取 Windows 主机 IP
ip route | grep default | awk '{print $3}'
```

然后设置 `base_url = "http://<that-ip>:8888/v1"`。如果你启用了 WSL2 镜像网络（`.wslconfig` → `networkingMode=mirrored`), `localhost` 的工作方式与原生 Windows 相同。
{% endhint %}
{% endstep %}

{% step %}

#### **启动 Codex**

```bash
mkdir my-project && cd my-project
codex --oss --profile unsloth_api
```

{% hint style="info" %}
**在新目录中首次启动** Codex 会询问 *“你信任此目录的内容吗？”* - 选择 *是，继续。* 这是针对每个当前工作目录的信任提示，而不是 ChatGPT 登录提示（后者因 \`requires\_openai\_auth = false\` 而被跳过）。在同一目录中的后续启动会跳过此提示。
{% endhint %}

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FWLWGwxYFup5JCptPghfx%2Fimage.png?alt=media&amp;token=e47961e9-20b6-4ec7-adec-919c819dc740" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
**看到 `模型元数据：` unsloth/gemma-4-26B-A4B `未找到。正在默认使用备用元数据`?** Codex 内置了一个表，其中包含 OpenAI 自有模型的上下文窗口、工具支持和输入模态。对于其他任何模型，它会回退到安全的默认值。对于每个非 OpenAI slug，该警告每个会话会触发一次。一切仍然正常工作，你可以忽略它。

**要修复此问题：** 添加 `model_context_window = 131072` 到以下内容的顶部： `~/.codex/config.toml` ，这样 Codex 就会使用 Gemma 4 实际的 128K 上下文，而不是其备用猜测值。若还想完全控制工具支持和输入模态，请将 `model_catalog_json` 在以下位置内： `[profiles.unsloth_api]` 指向一个 JSON 文件，其中包含自定义的 `ModelInfo` 条目，对应你的 slug。
{% endhint %}

该 `--profile unsloth_api` 该标志会告诉 Codex 加载 `~/.codex/unsloth_api.config.toml`，它会选择 Unsloth Studio 提供方和模型。添加 `--oss` 以通过 Codex 的本地 OSS 提供方流程运行。模型名称会出现在 Codex 的状态栏中。

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2F0EDBeLBbGfnBbW2Osnh9%2Fimage.png?alt=media&amp;token=e96a4905-5816-4c12-bd4d-a3a41500ef29" alt=""><figcaption></figcaption></figure>

添加 `--search` 以启用网页搜索：

```bash
codex --oss --profile unsloth_api --search
```

要绕过所有审批提示 **(注意：这将使 Codex 不经任何审批，按它自己的方式执行并运行代码！)**:

{% code overflow="wrap" %}

```bash
codex --oss --profile unsloth_api --search --dangerously-bypass-approvals-and-sandbox
```

{% endcode %}
{% endstep %}
{% endstepper %}

### 尝试一个真实任务

试试这个提示，来安装并运行一个简单的 Unsloth 微调：

{% code overflow="wrap" %}

```
你只能在当前工作目录 project/ 中工作。不要搜索 AGENTS.md——就在这里。
通过 uv 使用虚拟环境安装 Unsloth。请参见
https://unsloth.ai/docs/get-started/install/pip-install 了解方法（获取并阅读）。
然后执行一个简单的 Unsloth 微调运行，说明见
https://github.com/unslothai/unsloth。你可以使用 1 块 GPU。
```

{% endcode %}

如果我们再多等一会儿，你就会看到一个用 Unsloth 成功微调的模型！

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FFPuzCCHWIIXwuvTloNDh%2Fexport-1778571001272-30fps.gif?alt=media&amp;token=2bcaeaf1-a906-4169-b4ac-f17388ebaebb" alt=""><figcaption></figcaption></figure>

### 断开连接或还原

启动 Codex 时不使用 `-p unsloth_api` 它将使用其默认提供方。或者删除 `[profiles.unsloth_api]` 和 `[model_providers.unsloth_api]` 中的区块 `~/.codex/config.toml`.

```bash
unset UNSLOTH_STUDIO_AUTH_TOKEN
```

你可以让 Unsloth Studio 继续运行，也可以将其关闭。停止后它不会拦截任何内容。

### 故障排除

| 症状                         | 可能原因                                                        | 修复方法                                                                                    |
| -------------------------- | ----------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| `未找到 ... 的模型元数据`           | 非 OpenAI slug，没有内置元数据                                       | 无害警告。若要消除副作用，请设置 `model_context_window = 131072` 在 `~/.codex/config.toml`，或者指向          |
| Codex 说它是 GPT              | Codex 会注入一个引用 OpenAI 的系统提示；本地模型会照搬它                         | 这不是路由错误。请通过 Unsloth 的活动面板验证。覆盖系统提示即可更改其自我报告。                                            |
| `连接被拒绝`                    | Unsloth 未运行或端口错误                                            | 确认 Unsloth 正在 `http://localhost:8888`；检查 `base_url` 在 `config.toml`                     |
| `wire_api = "chat" 已不再受支持` | 旧版 `wire_api = "chat"` 在配置中                                 | 切换到 `wire_api = "responses"`                                                            |
| `未找到模型`                    | 模型 ID 拼写错误                                                  | `GET http://localhost:8888/v1/models` 并复制准确的 ID                                         |
| 生成过程中内存不足（OOM）             | 上下文过大，超出 VRAM                                               | 在 Unsloth 中减少上下文 **设置 → 推理**，或者使用更小的量化版本                                                |
| Codex 显示“使用 ChatGPT 登录”选择器 | <p>以裸模式启动 <code>codex</code> （没有<br><code>--oss</code>)</p> | 退出（Ctrl+C），然后使用以下方式重新启动 `codex --oss --profile unsloth_api`。自定义提供方会跳过这一步                |
| 工具调用不可靠                    | 需要自我修复回退                                                    | Unsloth 的 [自我修复工具调用](file:///1382377/new/studio/#execute-code--heal-tool-calling) 默认已启用 |
| WSL： `连接被拒绝` 到 `localhost` | WSL 网络命名空间                                                  | 在其中使用 Windows 主机 IP `base_url`，或者启用 WSL2 镜像网络                                           |

## 🦙 Llama.cpp 教程

我们也可以直接使用 `llama.cpp` 。我们需要部署 `llama-server` 这是一个开源框架，可在 Mac、Linux 和 Windows 设备上高效运行并提供 LLM 服务。模型将部署在 **8001 端口** ，所有智能体工具调用都将通过这个单一的 OpenAI 兼容端点路由。

{% hint style="info" %}
llama.cpp 端点将位于 **8001 端口** 而不是 `8888` （Unsloth Studio 的默认值）。相应调整你的 Codex `base_url` 在……中相应地 `~/.codex/config.toml`.
{% endhint %}

{% stepper %}
{% step %}

#### **安装 llama.cpp**

我们需要安装 `llama.cpp` 以部署/提供本地 LLM，供 Codex 使用。我们遵循官方构建说明，以获得正确的 GPU 绑定和最佳性能。将 `-DGGML_CUDA=ON` 到 `-DGGML_CUDA=OFF` 如果你没有 GPU，或者只想使用 CPU 推理。 **对于 Apple Mac / Metal 设备**，设置 `-DGGML_CUDA=OFF` 然后照常继续——Metal 支持默认开启。

```bash
apt-get update
apt-get install pciutils build-essential cmake curl libcurl4-openssl-dev git-all -y
git clone https://github.com/ggml-org/llama.cpp
cmake llama.cpp -B llama.cpp/build \\
    -DBUILD_SHARED_LIBS=OFF -DGGML_CUDA=ON
cmake --build llama.cpp/build --config Release -j --clean-first \\
    --target llama-cli llama-mtmd-cli llama-server llama-gguf-split
cp llama.cpp/build/bin/llama-* llama.cpp
```

{% endstep %}

{% step %}

#### **下载并在本地使用模型**

通过以下方式下载模型： `hf` 命令行工具（`pip install huggingface_hub hf_transfer`）。我们使用 **UD-Q4\_K\_XL** 量化版本，以获得最佳的尺寸/精度平衡。你可以在我们的 [集合中找到所有 Unsloth GGUF 上传](file:///1382377/get-started/unsloth-model-catalog.md)。如果下载卡住，请参见 [https://hugging-face-hub-xet-debugging.md](https://hugging-face-hub-xet-debugging.md "mention").

```bash
hf download unsloth/gemma-4-26B-A4B-it-GGUF \\
    --local-dir unsloth/gemma-4-26B-A4B-it-GGUF \\
    --include "*UD-Q4_K_XL*"
```

{% hint style="info" %}
**想要视觉支持？** 添加 `--include "*mmproj-BF16*"` 以便同时拉取视觉投影器，然后传入 `--mmproj unsloth/gemma-4-26B-A4B-it-GGUF/mmproj-BF16.gguf` 到 `llama-server`。Codex 本身仅支持文本，因此这是可选的。
{% endhint %}

{% hint style="success" %}
我们使用了 `unsloth/gemma-4-26B-A4B-it-GGUF`，但你可以使用任何类似的 `unsloth/Qwen3.6-35B-A3B-GGUF` - 见 [Qwen3.6-35B-A3B](/docs/zh/mo-xing/qwen3.6.md).
{% endhint %}
{% endstep %}

{% step %}

#### **启动 Llama-server**

要为智能体工作负载部署 Gemma-4-26B-A4B，我们使用 `llama-server`。我们采用 Google 推荐的采样参数（`温度 1.0`, `top_p 0.95`, `top_k 64`）并启用 `--jinja` 以获得正确的工具调用支持。

在新的终端中运行此命令（可使用 `tmux` ，或者打开一个新终端）。下面的内容应该 **轻松适配 24GB GPU（RTX 4090）** ，约占 18GB。 `--fit on` 也会自动卸载，但如果你看到性能变差，请减少 `--ctx-size`.

```bash
./llama.cpp/llama-server \\
    --model unsloth/gemma-4-26B-A4B-it-GGUF/gemma-4-26B-A4B-it-UD-Q4_K_XL.gguf \\
    --alias "unsloth/gemma-4-26B-A4B" \\
    --temp 1.0 \
    --top-p 0.95 \
    --top-k 64 \\
    --port 8001 \\
    --kv-unified \\
    --cache-type-k q8_0 --cache-type-v q8_0 \\
    --batch-size 4096 --ubatch-size 1024
```

{% hint style="info" %}
我们使用了 `--cache-type-k q8_0 --cache-type-v q8_0` 用于 KV 缓存量化以减少 VRAM 占用。如果你发现质量下降，请使用 `bf16` 代替（`--cache-type-k bf16 --cache-type-v bf16`），但 VRAM 会翻倍。
{% endhint %}

{% hint style="success" %}
**禁用思考** 可以提升智能体编程任务的性能。Gemma 4 通过聊天模板默认启用思考——要禁用它，请将以下标志添加到 llama-server 命令中：

**macOS / Linux / WSL：**

`--chat-template-kwargs '{"enable_thinking":false}'`

**Windows PowerShell：**

`--chat-template-kwargs "{\"enable_thinking\":false}"`
{% endhint %}
{% endstep %}

{% step %}

#### **将 Codex 指向 8001 端口**

编辑你的 `~/.codex/config.toml` ，使其使用 llama-server 端口：

{% code title="\~/.codex/config.toml" %}

```toml
[model_providers.llama_cpp]
name      = "llama.cpp"
base_url  = "http://localhost:8001/v1"
env_key   = "LLAMA_CPP_API_KEY"
wire_api  = "responses"
```

{% endcode %}

然后使用新的配置文件启动：

```bash
codex --oss llama_cpp
```

由于 llama-server 不需要真实密钥，你可以把认证令牌设置为任意值：

{% code title="macOS / Linux / WSL" %}

```bash
export LLAMA_CPP_API_KEY=sk-no-key-required
```

{% endcode %}

{% code title="Windows PowerShell" %}

```powershell
$env:LLAMA_CPP_API_KEY = "sk-no-key-required"
```

{% endcode %}
{% endstep %}
{% endstepper %}


---

# 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/codex.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.
