AI

How to Use GLM-5.4 with Claude Code, Codex and Cursor

Z.ai sells GLM-5.4 behind three doors, namely a pay-per-token API, a monthly Coding Plan and resale through OpenRouter. Claude Code, Codex and Cursor each speak a different protocol to a different Z.ai URL, and each fails in its own way when the key or the URL is wrong. Codex is the worst of them, because it reports a dropped stream when the real problem is a rejected key. This guide wires each tool to the right endpoint, proves the traffic reaches Z.ai, and prices a long thinking loop at $1.4 in and $4.4 out per million tokens.

Original content from computingforgeeks.com - post 201704

The GLM Claude Code setup gets the most space because it needs the most care, with model aliases, a 1M context suffix and an effort setting that all change the bill. I confirmed the Claude Code and Codex configs below loading on Ubuntu 26.04 against Z.ai’s live endpoints in December 2026, with Claude Code 2.1.334 and Codex CLI 0.173.0, using a demo key, so every request ended in Z.ai’s 401 rather than a GLM-5.4 answer, which is exactly how each tool reports a bad key. The Cursor and OpenRouter sections follow those vendors’ own documented steps, and the matrix at the end marks what each check covered.

Pick the right Z.ai endpoint and key

Z.ai runs four base URLs, and every tool talks to exactly one of them. The GLM-5.4 coding tools page lists them, and we hit each one from the lab before writing a single config. Get this table right and most of the errors later in the guide never happen, because a wrong pairing is the usual reason an agent hangs or retries.

ToolProtocolBase URL
Claude Code (also Goose)Anthropic Messageshttps://api.z.ai/api/anthropic
Codex CLIOpenAI Responseshttps://api.z.ai/api/v1
Cursor and other OpenAI-style tools on the Coding PlanOpenAI Chat Completionshttps://api.z.ai/api/coding/paas/v4
Your own scripts on pay-per-token billingOpenAI Chat Completionshttps://api.z.ai/api/paas/v4

The key matters as much as the URL. Z.ai’s API key notice, published on 16 October 2026, splits keys into three kinds: a Standard API Key billed from your account balance, a Personal Coding Plan key and a Team Plan key. They are not interchangeable, and for keys created since that date the key type decides the billing, not the endpoint. A Standard key pasted into Claude Code bills your balance per token even on the coding URL.

A quick probe tells you whether a URL is alive and how it rejects a bad key. We posted a tiny request to all four with a wrong key on purpose, because the shape of the rejection is what you will be reading later in the logs:

K=your_zai_api_key
for u in https://api.z.ai/api/anthropic/v1/messages https://api.z.ai/api/v1/responses https://api.z.ai/api/coding/paas/v4/chat/completions https://api.z.ai/api/paas/v4/chat/completions; do
echo "== POST $u"
curl -s -w "\nHTTP %{http_code}  total %{time_total}s\n" -X POST "$u" -H "Authorization: Bearer $K" -H "x-api-key: $K" -H "anthropic-version: 2023-06-01" -H "content-type: application/json" -d "{\"model\":\"glm-5.4\",\"max_tokens\":16,\"messages\":[{\"role\":\"user\",\"content\":\"ping\"}],\"input\":\"ping\"}"
echo; done

Three endpoints answer with HTTP 401. The Responses endpoint that Codex uses answers with HTTP 200 and puts the 401 inside the JSON body:

curl probe of four Z.ai endpoints with an invalid key, three return HTTP 401 and the Responses endpoint returns HTTP 200 with a 401 body

That HTTP 200 matters later, because Codex does not read a JSON error out of a successful status, so a rejected key shows up as a broken stream instead of an auth failure. All four round trips took about 0.17 seconds from a Google Cloud VM in Belgium, so latency to the gateway is not your bottleneck.

Compare the API, the Coding Plan and OpenRouter

Before wiring any tool, decide who bills you. The three paths cost very different amounts for agent work, mostly because coding agents resend a huge cached context on every turn and the paths price that context differently. All figures here come from Z.ai’s and OpenRouter’s own pages as of 2 December 2026.

Z.ai pay-per-token APIZ.ai Coding PlanOpenRouter z-ai/glm-5.4
Price$1.4 input, $0.26 cached input, $4.4 output per 1M tokensFrom $18 a month (Lite, Pro, Max)$1.40 input, $0.26 cache read, $4.40 output on most providers
Cached inputReads $0.26 per 1M, storage limited-time freeReads metered at a 1.1 credit multiplier$0.26 per 1M cache read on most providers
LimitsYour balanceCredits per 5 hours and per weekYour credit balance
KeyStandard API KeyCoding Plan keyOpenRouter key
Best forBursty use, scriptsDaily agent sessionsOne bill for many models

The Coding Plan meters in credits, not tokens. Z.ai’s Coding Plan overview gives Lite 2,000 credits per 5 hours and 10,000 per week, Pro 12,000 and 60,000, and Max 28,000 and 140,000. GLM-5.4 burns them with multipliers of 4.6 for input, 1.1 for cached input and 16 for output. Off-peak use costs half, and peak runs Monday to Friday, 14:00 to 18:00 Singapore time.

Z.ai estimates that at a 95% cache hit rate, Lite covers 72 to 146 million GLM-5.4 tokens a week, Pro 440 to 870 million and Max 1,014 to 2,028 million. If you run an agent most working days, the plan wins. For a few sessions a month, the pay-per-token key is cheaper. OpenRouter matches Z.ai’s list price on most providers, and one provider undercuts it at $0.40 in and $2.464 out.

Install Claude Code and Codex

Both CLIs ship on npm and need a recent Node.js. Ubuntu 26.04’s own packages gave us Node v22.22.1 and npm 9.2.0, which both tools accept. We point npm’s global prefix at the home directory so the install needs no sudo and later updates don’t touch system files:

sudo apt-get update
sudo apt-get install -y nodejs npm
mkdir -p ~/.npm-global
npm config set prefix ~/.npm-global
echo 'export PATH=$HOME/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc

Then install both agents in one go:

npm install -g @anthropic-ai/claude-code @openai/codex

Check both versions afterwards. Z.ai lists Claude Code 2.0.14 among the versions it verified, and tells you to upgrade to the latest release if the [1m] model suffix comes back as an unknown model:

claude --version
codex --version

Our VM printed these versions after the install finished:

npm install of Claude Code 2.1.334 and Codex CLI 0.173.0 on Ubuntu 26.04

Claude Code 2.1.334 and Codex CLI 0.173.0 are what every capture in this guide came from. If you already run either tool against its own vendor, keep that setup. The switch-back section shows how to move the Z.ai wiring aside so Claude Code returns to your normal Anthropic login.

Point Claude Code at the Z.ai Anthropic endpoint

Claude Code reads environment overrides from the env block of ~/.claude/settings.json, so the whole switch lives in one file. Putting it there instead of in your shell profile keeps the Z.ai key out of every other program’s environment and makes switching back a one-line rename. Open the file:

mkdir -p ~/.claude
vim ~/.claude/settings.json

Paste the block below and replace your_zai_api_key with your key. This is the exact file we ran. If the file already holds permissions or hooks, don’t replace it: add these keys to its existing env object, as Z.ai’s page also advises.

{
  "env": {
    "ANTHROPIC_AUTH_TOKEN": "your_zai_api_key",
    "ANTHROPIC_BASE_URL": "https://api.z.ai/api/anthropic",
    "ANTHROPIC_DEFAULT_HAIKU_MODEL": "glm-5.3-flash[1m]",
    "ANTHROPIC_DEFAULT_SONNET_MODEL": "glm-5.4[1m]",
    "ANTHROPIC_DEFAULT_OPUS_MODEL": "glm-5.4[1m]",
    "CLAUDE_CODE_AUTO_COMPACT_WINDOW": "1000000",
    "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
    "API_TIMEOUT_MS": "3000000"
  }
}

Each line has a job. Here is what the block wires, in the order Claude Code uses it:

  1. ANTHROPIC_AUTH_TOKEN sends your Z.ai key as a bearer token, so Claude Code never asks you to log in.
  2. ANTHROPIC_BASE_URL sends every request to Z.ai instead of Anthropic. It has no trailing /v1, because Claude Code appends /v1/messages itself.
  3. The three ANTHROPIC_DEFAULT_*_MODEL lines map Claude Code’s Opus, Sonnet and Haiku slots to GLM models. The [1m] suffix asks for the 1M token context window.
  4. CLAUDE_CODE_AUTO_COMPACT_WINDOW stops Claude Code from compacting at its default window, so the 1M context actually gets used.
  5. API_TIMEOUT_MS at 50 minutes gives each attempt that long to receive response headers, which covers slow first tokens on long turns at peak hours.

Z.ai’s Claude Code page adds three more keys to this block, and we left all three out of the file above:

  • "DISABLE_TELEMETRY": "1"
  • "CLAUDE_CODE_SIMPLE_SYSTEM_PROMPT": "0"
  • "CLAUDE_CODE_MAX_CONTEXT_TOKENS": "1000000"

The routing still came up on Z.ai without them, so add them only if you want to match the vendor’s block exactly. Z.ai’s newer GLM-5.4 page also maps Haiku to glm-5.4[1m], which costs more per background call but keeps every task Claude Code spawns on the same model and the same behaviour.

Verify Claude Code really talks to Z.ai

Start claude in a project folder and run /status. This is the check Z.ai itself recommends, and it is the only screen that proves which URL and which credential the session uses. Broken JSON gets a settings error at startup, but a misspelled key name is silently ignored, so don’t skip it.

Claude Code /status showing ANTHROPIC_AUTH_TOKEN, the api.z.ai/api/anthropic base URL and model glm-5.4[1m]

Three lines tell you the wiring is right. Auth token reads ANTHROPIC_AUTH_TOKEN, Anthropic base URL reads https://api.z.ai/api/anthropic, and Model reads Default (glm-5.4[1m]) with User settings as the source. The panel also says managed settings were not fetched because of the custom base URL, and lists features such as /advisor that stay off while nonessential traffic is disabled.

Next open /model. The picker shows how Claude Code mapped its slots, and it exposes a gap in Z.ai’s published block:

Claude Code model picker listing glm-5.4[1m] as custom Opus and Sonnet, glm-5.3-flash as Haiku, and Fable left unmapped

Opus, Sonnet and Haiku all point at GLM models, but entry 3 still offers Fable 5.2 at Anthropic’s $8 and $40 per million tokens. Z.ai’s block has no line for that slot. Picking it sends an Anthropic model name to Z.ai, which cannot serve it. If you or a teammate is likely to click it, add "ANTHROPIC_DEFAULT_FABLE_MODEL": "glm-5.4[1m]" to the block so every slot resolves to GLM. The Claude Code cheat sheet covers the rest of the slash commands used here.

Set the effort level and budget the thinking

GLM-5.4 thinks before it answers, and that thinking is billed as output at $4.4 per million tokens. Claude Code’s /effort command controls how much of it you buy. Z.ai maps Claude Code’s levels onto three of its own. Thinking disabled and the minimal, light and low levels become low, medium and high become high, and xhigh, max and ultra all become max. Our /model picker showed High effort as the default, while Z.ai’s page says the default is max, so check yours.

Z.ai’s own GLM-5.4 model page warns that the model “tends to get caught in overly long ‘marathon thinking’ loops”. The table below is an estimate, not a metered run: it prices one agent turn with Z.ai’s published rates. The turn resends 100,000 tokens of context, 95% of it cached, which is ordinary for a mid-sized repo. Only the thinking length changes between rows.

Estimated turn shapeCached input (95K)Fresh input (5K)OutputTurn cost
Short answer, 3K output$0.0247$0.0070$0.0132$0.045
Normal thinking, 10K output$0.0247$0.0070$0.0440$0.076
Marathon loop, 40K output$0.0247$0.0070$0.1760$0.208

That arithmetic makes the point plainly. Once the context is cached, output dominates, and one runaway thinking loop costs more than four short turns. An agent session of 200 turns lands between about $9 and $42 depending on which row it lives in. For routine edits, drop to /effort high or low and save max for planning and hard debugging.

Wire Codex to the Z.ai Responses endpoint

Codex needs two files, a model catalog that tells it GLM-5.4’s reasoning levels and context size, and a provider entry in its config that points at Z.ai and carries the key. Z.ai publishes the catalog alongside the config, and the config refers to it by path, so create the catalog first:

mkdir -p ~/.codex
vim ~/.codex/models.json

Paste Z.ai’s catalog. This is the exact file from Z.ai’s Codex page that we ran:

{
    "models": [
        {
            "slug": "glm-5.4",
            "display_name": "glm-5.4",
            "description": "Z.ai's latest flagship model",
            "default_reasoning_level": "max",
            "supported_reasoning_levels": [
                {
                    "effort": "low",
                    "description": "Light reasoning"
                },
                {
                    "effort": "high",
                    "description": "Enhanced reasoning"
                },
                {
                    "effort": "max",
                    "description": "Deep reasoning"
                }
            ],
            "shell_type": "shell_command",
            "visibility": "list",
            "supported_in_api": true,
            "priority": 0,
            "base_instructions": "",
            "supports_reasoning_summaries": true,
            "default_reasoning_summary": "none",
            "support_verbosity": false,
            "apply_patch_tool_type": "freeform",
            "truncation_policy": {
                "mode": "bytes",
                "limit": 10000
            },
            "context_window": 1048576,
            "max_context_window": 1048576,
            "effective_context_window_percent": 95,
            "supports_parallel_tool_calls": true,
            "experimental_supported_tools": [],
            "input_modalities": [
                "text",
                "image",
                "audio"
            ]
        }
    ]
}

Now the provider. Z.ai’s page puts the key straight into the file with experimental_bearer_token. We prefer env_key, which makes Codex read the key from an environment variable, so the config can live in a dotfiles repo without leaking a secret. Open the config:

vim ~/.codex/config.toml

Add the provider and make it the default. Both variants loaded in our lab; this is the env_key one:

model_provider = "ZAI"
model = "glm-5.4"
model_reasoning_effort = "max"
model_catalog_json = "~/.codex/models.json"

[model_providers.ZAI]
name = "ZAI"
base_url = "https://api.z.ai/api/v1"
env_key = "ZAI_API_KEY"
wire_api = "responses"

To use Z.ai’s variant instead, replace the env_key line with experimental_bearer_token = "your_zai_api_key". With env_key, export the key in the shell that runs Codex, then send a one-line prompt:

export ZAI_API_KEY=your_zai_api_key
codex exec --skip-git-repo-check "Reply with the word pong"

The header Codex prints before the request is your proof that both files were read. Look for model glm-5.4, provider ZAI and reasoning effort max, which come from the config and the catalog. Our capture used a wrong key, so the reconnect errors below the header are expected:

Codex CLI exec header showing model glm-5.4, provider ZAI and reasoning effort max, followed by reconnect errors

With a valid key, the reconnect lines are replaced by the model’s reply. If the header shows a different provider, Codex did not read ~/.codex/config.toml, usually because CODEX_HOME points somewhere else. Our Codex CLI cheat sheet lists the profile and config flags if you’d rather keep Z.ai as a named profile than as the default.

Add GLM-5.4 to Cursor as a custom model

Cursor has just been renamed. Its homepage now reads “Cursor is now Grok Build”, and its docs redirect to docs.grok.com, so a current build labels the settings screen Grok Build Settings while older installs still say Cursor Settings. The rename also brings a plan gate: Grok Build’s models and pricing page says Plus excludes your own API keys, and its API key page lists own keys for Premium, Super and Ultra plus the legacy Pro, Pro+ and Ultra plans.

The editor talks OpenAI Chat Completions, so it uses the Coding Plan’s OpenAI-compatible URL rather than the Anthropic or Responses ones. Z.ai’s Cursor page gives these steps:

  1. Open Cursor Settings (Grok Build Settings on current builds), go to Models and choose Add Custom Model.
  2. Pick the OpenAI protocol and paste your Z.ai key into the OpenAI API Key field.
  3. Turn on Override OpenAI Base URL and enter https://api.z.ai/api/coding/paas/v4.
  4. Add the model name in uppercase, GLM-5.4, as Z.ai’s page specifies, then select it in the chat model picker.

Grok Build’s own API key page doesn’t document the base URL override, and it says every request with your key goes through Grok Build’s servers for prompt building, so check that your build still shows the override field before you rely on this path. Mind the key type as well. The coding URL is meant for a Coding Plan key, and under Z.ai’s 16 October key rules a Standard key used here bills your account balance per token instead of drawing on plan credits. That is fine if you planned for it, and an unpleasant surprise if you didn’t. If you want GLM in a terminal agent rather than an IDE, OpenCode has a built-in Z.AI Coding Plan provider that you pick during opencode auth login, according to Z.ai’s docs.

Route Claude Code through OpenRouter instead

OpenRouter lists the model as z-ai/glm-5.4, and Claude Code is already its top app by tokens on that page. The settings file keeps the same shape as the Z.ai one, and this env block replaces the Z.ai block entirely:

{
  "env": {
    "ANTHROPIC_AUTH_TOKEN": "your_openrouter_api_key",
    "ANTHROPIC_API_KEY": "",
    "ANTHROPIC_BASE_URL": "https://openrouter.ai/api",
    "ANTHROPIC_DEFAULT_OPUS_MODEL": "z-ai/glm-5.4",
    "ANTHROPIC_DEFAULT_SONNET_MODEL": "z-ai/glm-5.4",
    "ANTHROPIC_DEFAULT_HAIKU_MODEL": "z-ai/glm-5.4",
    "ANTHROPIC_DEFAULT_FABLE_MODEL": "z-ai/glm-5.4"
  }
}

OpenRouter’s Claude Code guide sets the base URL to https://openrouter.ai/api without /v1, blanks ANTHROPIC_API_KEY so an old Anthropic key can’t win, and tells you to run /logout if Claude Code is still holding a cached Anthropic login. The same guide says Claude Code through OpenRouter is only guaranteed to work with the Anthropic first-party provider, so treat GLM on this route as best effort. This route rests on that guide. Our only probe of it carried no key, and OpenRouter rejected it with “Missing Authentication header”, which proves the URL answers but says nothing about GLM-5.4 behind it.

Switch Claude Code back to Anthropic

Because the whole Z.ai wiring lives in one file, switching back is a rename. claude auth status shows the state on both sides of the move. With the Z.ai file in place it reports a token login. After the rename Claude Code falls back to whatever Anthropic login the machine had, which on our fresh lab VM was none:

mv ~/.claude/settings.json ~/.claude/settings.zai.json

Here are both reports, before and after the rename:

claude auth status output before and after renaming settings.json to switch Claude Code back from Z.ai

Note that loggedIn flips from true to false and authMethod from oauth_token to none; on a machine with an existing Anthropic login you get that login back instead. Rename the file back to return to GLM, and if Claude Code warns about conflicting credentials, run /logout as OpenRouter’s guide suggests. If you keep other settings in that file, such as permissions or hooks, split them out first, or run Claude Code with --settings ~/.claude/settings.zai.json only when you want Z.ai. We do the same thing for local models in the DeepSeek harness guide.

Every error below came from our lab with a deliberately wrong key or variable, so the text matches what your terminal prints. The first two are the same root cause, a rejected key, reported two very different ways. The last two are a missing variable and a harmless warning that looks worse than it is.

Failed to authenticate. API Error: 401 token expired or incorrect

Claude Code does not fail fast on a bad Z.ai key. In the interactive session it shows a retry counter, and in print mode it stays silent until all ten retries are spent:

✻ 401 token expired or incorrect · retrying in 8s · attempt 6/10

Our claude -p run took 3 minutes 9 seconds before it gave up with the final message:

Failed to authenticate. API Error: 401 token expired or incorrect

real	3m9.141s

In scripts and CI, that silence looks like a hang. Check the key with the curl probe from the first section before blaming the agent: a 401 there settles it in under a second. If the key passes with curl, compare it with the one in settings.json character by character: a trailing space or a pasted newline inside the quotes is enough to get rejected.

stream disconnected before completion: stream closed before response.completed

Codex printed this after five reconnect attempts and exited with status 1 after 11.7 seconds:

ERROR: Reconnecting... 5/5
ERROR: stream disconnected before completion: stream closed before response.completed

It reads like a network fault, but in our lab the cause was the key. Z.ai’s Responses endpoint answers a bad key with HTTP 200 and {"code":401,"msg":"token expired or incorrect","success":false} as plain JSON, even when the request asks for a stream. Codex waits for stream events that never come. Run the curl probe: if the body carries "code":401, fix the key, not the network.

Missing environment variable: `ZAI_API_KEY`

This one is honest. Codex printed it when the config used env_key and the shell had no such variable:

ERROR: Missing environment variable: `ZAI_API_KEY`.

Export the key in the same shell, or add the export to your shell profile. Watch the exit code in scripts: our run returned 0 despite the error, so a wrapper that checks only the exit status will report success. Grep the output for ERROR: if Codex runs unattended.

[claude-code:unrecognized_model] glm-5.4[1m]

Claude Code logs this line in print mode because glm-5.4[1m] is not one of Anthropic’s model names, and the line looks alarming the first time you see it.

[claude-code:unrecognized_model] {"model":"glm-5.4[1m]","query_source":"sdk"}

It is a warning rather than the failure, and the request still went to Z.ai, which is why the 401 followed it. A real “model not found” error is different: Z.ai’s page says older Claude Code builds reject the [1m] suffix, and the fix there is upgrading Claude Code, not changing the model name.

Match each tool to its access path

With the three tools wired, this matrix is the one-page version of the guide. It pairs each agent with the URL, the key and the place the config lives, so you can set up a second machine without rereading every section.

ToolConfigBase URLModel nameVerify withWhat our lab covered
Claude Code on Z.ai~/.claude/settings.jsonhttps://api.z.ai/api/anthropicglm-5.4[1m]/statusConfig load, /status routing, 401 with demo key
Claude Code on OpenRouter~/.claude/settings.jsonhttps://openrouter.ai/apiz-ai/glm-5.4/statusKeyless endpoint probe only, steps from OpenRouter’s guide
Codex CLI~/.codex/config.toml and models.jsonhttps://api.z.ai/api/v1glm-5.4codex exec headerConfig load, exec header, stream error with demo key
Cursor (Grok Build)Settings, Modelshttps://api.z.ai/api/coding/paas/v4GLM-5.4Chat model pickerSteps from Grok Build’s docs, no capture

Z.ai’s Hugging Face organization had no GLM-5.4 weights listed when we checked on 2 December 2026, even though OpenRouter already shows several third-party hosts serving it. To see how it sits next to models you can run yourself, the open source LLM comparison lists context size, license and hardware needs side by side.

Keep reading

Run Amazon Ergo Locally: Hardware Requirements and vLLM Setup AI Run Amazon Ergo Locally: Hardware Requirements and vLLM Setup Open Source LLM Comparison Table (2026) AI Open Source LLM Comparison Table (2026) Ollama Models Cheat Sheet: Best Models by VRAM, Tested (PDF) AI Ollama Models Cheat Sheet: Best Models by VRAM, Tested (PDF) AI NAS Explained: Is Local AI on a NAS Worth It? AI AI NAS Explained: Is Local AI on a NAS Worth It? MedGemma 2 vs Gemma 4 vs MedGemma 1.5: Local Benchmark AI MedGemma 2 vs Gemma 4 vs MedGemma 1.5: Local Benchmark Install Claude Desktop and Claude Code on Linux AI Install Claude Desktop and Claude Code on Linux

Leave a Comment

Press ESC to close