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

对于模型量化版本，我们将使用 Unsloth [**动态 GGUF**](/docs/zh/ji-chu/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 选项卡操作。你需要一个小型网络技巧才能访问 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/codex.md#unsloth-tutorial" class="button primary">🦥 Unsloth 教程</a><a href="/pages/b71ddea7924324c058a771e5e831c3cb6fc75b18#llama.cpp-tutorial" class="button primary">🦙 llama.cpp 教程</a>

## 🦥 Unsloth 教程

在本教程中，我们将通过使用 [Unsloth](https://github.com/unslothai/unsloth)，经由 UI 将本地模型托管/连接到 Claude Code。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) 参数调优（temp、top-p 等）
* 通过 llama.cpp 实现快速 CPU + GPU 推理
* [训练 LLM](/docs/zh/xin/studio.md#no-code-training) 速度快 2 倍，VRAM 占用减少 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-bit 的示例。</p></figcaption></figure></div>
{% endcolumn %}
{% endcolumns %}

{% stepper %}
{% step %}

#### 下载 Unsloth

最简单的入门方式是安装 [Unsloth Desktop](/docs/zh/desktop.md) 应用。它支持 [macOS](/docs/zh/kai-shi-shi-yong/install/mac.md)、Linux、 [Windows](/docs/zh/kai-shi-shi-yong/install/windows-installation.md), [NVIDIA](/docs/zh/kai-shi-shi-yong/install/pip-install.md), [AMD](/docs/zh/kai-shi-shi-yong/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 拖到“应用程序”，或在 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。

* **连接工具：** [Claude Code](/docs/zh/ji-chu/claude-code.md), [Codex](/docs/zh/ji-chu/codex.md)、网页搜索、 [MCP](/docs/zh/ji-chu/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 目前需要一个通过 `llama-server` 后端提供的 GGUF 模型。

查看完整 `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 <配置文件名称>`.
{% endhint %}
{% endstep %}

{% step %}

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

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

{% 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]` 中指向一个包含自定义 `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" %}

```
你只能在 cwd 项目/ 中工作。不要搜索 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 的系统提示；本地模型会照搬它                        | 这不是路由 bug。请通过 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 网络命名空间                                                 | 在 `base_url`中使用 Windows 主机 IP，或启用 WSL2 镜像网络                                             |

## 🦙 Llama.cpp 教程

我们也可以直接使用 `llama.cpp` 。我们需要部署 `llama-server` ，这是一个开源框架，可在 Mac、Linux 和 Windows 设备上高效运行和提供 LLM 服务。模型将托管在 **8001 端口** ，所有 agent 工具调用都将通过这一个兼容 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` CLI（`pip install huggingface_hub hf_transfer`）。我们使用 **UD-Q4\_K\_XL** 量化，以获得最佳尺寸/准确度平衡。你可以在我们的 [此处的合集](file:///1382377/get-started/unsloth-model-catalog.md)中找到所有 Unsloth GGUF 上传。如果下载卡住，请参见 [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**

要为 agentic 工作负载部署 Gemma-4-26B-A4B，我们使用 `llama-server`。我们采用 Google 推荐的采样参数（`temp 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" %}
**禁用思考** 可以提升 agentic 编码任务的性能。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 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/codex.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.
