> 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

本分步指南将向你展示如何将开放 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 内存/统一内存设备上运行）。用于推理，我们将使用 [Unsloth Studio](https://github.com/unslothai/unsloth) 和 [`llama.cpp`](https://github.com/ggml-org/llama.cpp) ，它可让你在 macOS、Linux 和 Windows 上运行/提供服务 LLM。你可以替换为任何其他模型，只需在脚本和 Codex 配置中更新模型名称即可。

<a href="/pages/b71ddea7924324c058a771e5e831c3cb6fc75b18#setup-codex" class="button primary" data-icon="openai">设置 Codex</a><a href="/pages/b71ddea7924324c058a771e5e831c3cb6fc75b18#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 Studio 的 `/v1/responses` 端点，等 Unsloth 启动后。

{% 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) （一个网页 UI）和 llama.cpp，它们是用于在你的 Mac、Linux、Windows 设备上运行和提供 LLM 服务的开源框架。

{% columns %}
{% column %}
在开始之前，我们首先需要完成你将要使用的特定模型的设置。我们使用 [Unsloth](/docs/zh/xin/studio.md) （一个网页 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="/files/ce3073a68a308e67d9765fb9106097c0bcdecb1a" alt=""><figcaption></figcaption></figure></div>
{% endcolumn %}
{% endcolumns %}

<a href="/pages/b71ddea7924324c058a771e5e831c3cb6fc75b18#unsloth-tutorial" class="button primary">🦥 Unsloth 教程</a><a href="/pages/b71ddea7924324c058a771e5e831c3cb6fc75b18#llama.cpp-tutorial" class="button primary">🦙 llama.cpp 教程</a>

## 🦥 Unsloth 教程

在本教程中，我们将通过 UI 使用 [Unsloth](https://github.com/unslothai/unsloth)将本地模型提供/连接到 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="/files/f8801eb887a6a996de4f745df66b4617f383d216" 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/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 %}

#### 选择模型

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

<figure><img src="/files/ee716919ab359455030e8acd4d55b5ec13ca328d" 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="/files/b0dfb852351654c29812a5aa23885913432eaa10" alt="" width="563"><figcaption></figcaption></figure>
{% endstep %}
{% endstepper %}

### 模型加载 + API 指南

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

<figure><img src="/files/7d43e8763d1ae72290485151822b1ea2e4fce42a" 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).

### ⚡ 使用 `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 \\
    --chat-template-kwargs '{"reasoning_effort":"medium"}'
```

Unsloth 会自动选择正确的参数，但你仍然可以更改。

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

```bash
unsloth start codex
```

Unsloth 为此次启动创建一个隔离的 Codex 主页和一个由 Unsloth 支持的 Responses 提供方。你的普通 `~/.codex` 配置不会受影响。

默认情况下 Codex 状态是临时的。需要保留时请使用 `--persist` ，以便保留其由 Unsloth 管理的配置和会话：

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

<figure><img src="/files/951194d222c18b87baa7216718fad7c6f9d23889" alt="OpenAI Codex running with a local GGUF model through Unsloth Studio"><figcaption><p>通过 Unsloth Studio Responses 端点连接到本地 GGUF 模型的 Codex。</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" %}
`模型` 必须与你的服务器在 `GET http://localhost:8888/v1/models`中报告的 id 匹配。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` 配置文件只会在你使用 `--profile unsloth_api`启动 Codex 时选择 Unsloth 提供方和模型，因此不会更改你正常的 Codex 设置。Codex 会从名为 `UNSLOTH_STUDIO_AUTH_TOKEN`的环境变量中读取 API 密钥。你会在下一步设置真正的密钥。
{% 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`中写入的相同环境变量名。 `env_key = "UNSLOTH_STUDIO_AUTH_TOKEN"`在你运行 Codex 的同一个终端中，将其设置为： `UNSLOTH_STUDIO_AUTH_TOKEN` 在 MacOS / Linux / WSL 中

{% code title="export UNSLOTH\_STUDIO\_AUTH\_TOKEN=YOUR\_TOKEN" %}

```bash
Windows PowerShell
```

{% endcode %}

{% code title="$env:UNSLOTH\_STUDIO\_AUTH\_TOKEN = "YOUR\_TOKEN"" %}

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

{% endcode %}

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

**会话式 vs 持久式：** 上述命令只适用于当前终端。要持久化：

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

{% hint style="warning" %}
**在 Windows 上使用 Unsloth 的情况下在 WSL 内运行 Codex？** 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="/files/7da155068741d875b0bca7db32447dbe72b9e401" 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 文件，该文件包含你这个 slug 的自定义 `ModelInfo` 条目。
{% endhint %}

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

<figure><img src="/files/41a8451ff5a2020dcc71cf9bd6fd2f08d7693d23" 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="/files/5a701761b8bba389849a6a31fb55036ca4d3dbb8" alt=""><figcaption></figcaption></figure>

### 断开连接或恢复

启动 Codex 时不带 `-p unsloth_api` ，它就会使用默认提供方。或者删除 `[profiles.unsloth_api]` 和 `[model_providers.unsloth_api]` 中的 blocks `~/.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                                         |
| 生成中途内存不足                   | 上下文对于 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 端口** ，所有 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)。如果下载卡住，请参阅 [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 部署用于 agentic 工作负载，我们使用 `llama-server`。我们采用 Google 推荐的采样参数（`temp 1.0`, `top_p 0.95`, `top_k 64`）并启用 `--jinja` 以获得正确的工具调用支持。

在新的终端中运行此命令（使用 `tmux` ，或者打开一个新终端）。下面的配置应该 **轻松适配 24GB GPU（RTX 4090）** ，约占 18GB。 `——可在` 上自动卸载，但如果你看到性能不佳，请降低 `--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="export UNSLOTH\_STUDIO\_AUTH\_TOKEN=YOUR\_TOKEN" %}

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

{% endcode %}

{% code title="$env:UNSLOTH\_STUDIO\_AUTH\_TOKEN = "YOUR\_TOKEN"" %}

```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.
