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

本指南将引导您将开放式大语言模型本地连接到 Codex CLI **完全本地**。它可与任何 OpenAI 或兼容 API 的本地模型设置一起使用，包括：DeepSeek、Qwen、Gemma 等。

在本教程中，我们将使用 [GLM-4.7-Flash](https://open-2v.gitbook.com/url/preview/site_mXXTe/~/revisions/NYG3pIjIP3JF6zgJgfjl/models/glm-4.7-flash) （一个 30B MoE、具有代理能力和编码能力的模型），它可以很好地在 24GB RAM/统一内存设备上运行，以使用 [Unsloth](https://github.com/unslothai/unsloth)。更喜欢其他模型？请替换为 [任何其他模型](https://open-2v.gitbook.com/url/preview/site_mXXTe/~/revisions/NYG3pIjIP3JF6zgJgfjl/models/tutorials) ，只需在脚本中更新模型名称。

<a href="#openai-codex-cli-tutorial" class="button primary" data-icon="openai">OpenAI Codex 教程</a>

对于模型量化，我们将使用 Unsloth [动态 GGUFs](https://open-2v.gitbook.com/url/preview/site_mXXTe/~/revisions/NYG3pIjIP3JF6zgJgfjl/basics/unsloth-dynamic-2.0-ggufs) ，这样您可以在尽可能保持质量的同时运行量化的 GGUF 模型。

我们将使用 [`llama.cpp`](https://github.com/ggml-org/llama.cpp)，这是一个用于在 macOS、Linux 和 Windows 上运行大语言模型的开源运行时。它的 `llama-server` 组件让您可以通过单一 **兼容 OpenAI 的** HTTP 端点高效地提供模型。在此设置中，模型在 **端口 8001**上提供，所有代理工具调用都通过该端点路由。

### 📖 #1：设置教程

{% 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
```

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2F4DmycqgjxOz6TOQd9PLJ%2Fimage.png?alt=media&#x26;token=c94db0b5-8e4a-4043-b2a3-c68bad93213e" alt="" width="563"><figcaption></figcaption></figure>
{% endstep %}

{% step %}

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

通过以下方式下载模型 `huggingface_hub` 在 Python 中（在通过以下命令安装之后 `pip install huggingface_hub hf_transfer`）。我们使用 **UD-Q4\_K\_XL** 量化以获得最佳的大小/准确性平衡。您可以在我们的 [集合在此处](https://unsloth.ai/docs/zh/kai-shi-shi-yong/unsloth-model-catalog)找到所有 Unsloth GGUF 上传。如果下载卡住，参见 [hugging-face-hub-xet-debugging](https://unsloth.ai/docs/zh/ji-chu/troubleshooting-and-faqs/hugging-face-hub-xet-debugging "mention")

{% hint style="success" %}
我们使用了 `unsloth/GLM-4.7-Flash-GGUF` ，但您可以使用任何类似的模型，例如 `unsloth/Qwen3-Coder-Next-GGUF`  - 参见 [qwen3-coder-next](https://unsloth.ai/docs/zh/mo-xing/qwen3-coder-next "mention")
{% endhint %}

```python
import os
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
from huggingface_hub import snapshot_download

snapshot_download(
    repo_id = "unsloth/GLM-4.7-Flash-GGUF",
    local_dir = "unsloth/GLM-4.7-Flash-GGUF",
    allow_patterns = ["*UD-Q4_K_XL*"],
)
```

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FxlIrQGQ0cevb1ckkSFy5%2Fimage.png?alt=media&#x26;token=b1a42562-927a-4ad2-85f8-29c2993c46aa" alt="" width="563"><figcaption></figcaption></figure>
{% endstep %}

{% step %}

#### 启动 Llama-server

为了部署 GLM-4.7-Flash 用于具有代理能力的工作负载，我们使用 `llama-server`。我们应用 Z.ai 推荐的采样参数（`temp 1.0`, `top_p 0.95`）并启用 `--jinja` 以支持正确的工具调用。

在新终端中运行此命令（使用 `tmux` 或打开新的终端）。下面的命令应当 **完美适配 24GB GPU（RTX 4090）（使用 23GB）** `--fit on` 也会自动卸载，但如果您看到性能不佳，请减少 `--ctx-size` 。我们使用了 `--cache-type-k q8_0 --cache-type-v q8_0` 用于 KV 缓存量化以减少显存使用。

```bash
./llama.cpp/llama-server \
    --model unsloth/GLM-4.7-Flash-GGUF/GLM-4.7-Flash-UD-Q4_K_XL.gguf \
    --alias "unsloth/GLM-4.7-Flash" \
    --temp 1.0 \
    --top-p 0.95 \
    --min-p 0.01 \
    --port 8001 \
    --kv-unified \
    --cache-type-k q8_0 --cache-type-v q8_0 \
    --flash-attn on \
    --batch-size 4096 --ubatch-size 1024 \
    --ctx-size 131072
```

{% hint style="success" %}
您也可以禁用 GLM-4.7-Flash 的 thinking（思考）以提高面向代理的编码任务的性能。要在 llama.cpp 中禁用 thinking，请将此项添加到 llama-server 命令：

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

<img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FyKf6guCV8snRaAV16Zxc%2FG_16XLgXUAEnSWH.jpg?alt=media&#x26;token=3b557c6d-3f6f-4515-ba9f-4cc8b50bcef1" alt="" data-size="original">
{% endhint %}
{% endstep %}
{% endstepper %}

## <i class="fa-openai">:openai:</i> OpenAI Codex CLI 教程

[Codex ](https://github.com/openai/codex)是 OpenAI 官方在本地运行的编码代理。尽管为 ChatGPT 设计，但它支持自定义 API 端点，使其非常适合本地 LLM。对于在 [Windows](https://developers.openai.com/codex/windows/) 上安装——最好使用 WSL。

#### **安装**

**Mac（Homebrew）：**

```bash
brew install --cask codex
```

**通用（NPM）适用于 Linux**

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

**配置**

首次运行 `codex` 以登录并设置，然后在以下位置创建或编辑配置文件 `~/.codex/config.toml` （Mac/Linux）或 `%USERPROFILE%\.codex\config.toml` （Windows）。

使用 `cat > ~/.codex/config.toml` 用于 Linux / Mac：

```toml
[model_providers.llama_cpp]
name = "llama_cpp API"
base_url = "http://localhost:8001/v1"
wire_api = "responses"
stream_idle_timeout_ms = 10000000
```

导航到您的项目文件夹（`mkdir project ; cd project`）并运行：

```bash
codex --model unsloth/GLM-4.7-Flash -c model_provider=llama_cpp --search
```

或者允许执行任何代码。 **（注意：这将使 Codex 在没有任何批准的情况下随意执行代码！）**

{% code overflow="wrap" %}

```bash
codex --model unsloth/GLM-4.7-Flash -c model_provider=llama_cpp --search --dangerously-bypass-approvals-and-sandbox
```

{% endcode %}

您将看到：

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FiTjL7DtyNg0GREwR7p54%2Fimage.png?alt=media&#x26;token=9f793df2-e91b-4631-a7c8-00e659fd1a07" alt=""><figcaption></figcaption></figure>

{% hint style="warning" %}
OpenAI 的 Codex 正在移除 `wire_api = "chat"` 支持——看起来如此，但截至 2026 年 1 月 29 日仍能工作。我们应该切换到 `wire_api = "responses"` 但它不断报错： `{"error":{"code":400,"message":"'type' of tool must be 'function'","type":"invalid_request_error"}}`
{% endhint %}

尝试此提示以安装并运行一个简单的 Unsloth 微调：

{% code overflow="wrap" %}

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

{% endcode %}

然后您将看到：

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fg2R9WPuNRNUUFnPRXE2F%2Fimage.png?alt=media&#x26;token=686f4be8-7a50-4f6b-86cb-327cec36de81" alt=""><figcaption></figcaption></figure>

如果我们再等一会儿，最终我们会看到：

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FHTKt5sGFpkYzS8DlM9E7%2Fimage.png?alt=media&#x26;token=f4fa2e27-10d7-4c4e-8af0-448170336af9" alt=""><figcaption></figcaption></figure>


---

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