Hermes - Part 04: Roger's brains, LM Studio on Mac and GLM (Z.ai)

In short
  • Two brains for Roger: Qwen3.5 9B (MLX, 8 bits, context of 65,536 tokens) running on LM Studio on a MacBook Pro M4, and GLM via the Coding Lite subscription from Z.ai as a backup.
  • Key considerations for choosing a local model: number of parameters, quantization, context (KV-cache), memory bandwidth, Mixture of Experts (MoE), and "thinking" mode, which is disabled here using the Jinja template.
  • LM Studio only listens on 127.0.0.1 and requires a token. It is located behind an NGINX server using HTTPS (with a certificate from the internal PKI) and the pf firewall, which only allows connections from the virtual machine.
  • Z.ai key of the "Personal Coding Plan" type, with quotas in credits, and both secrets stored in Vault under secret/hermes/roger/.

Introduction

In the previous part, we installed Hashicorp Vault in a hardened version, with a policy and an AppRole dedicated to our "Roger" agent, and then NGINX as the HTTPS frontend for the future dashboard. The secure vault is ready, but it is still empty.

This article discusses the brains of Roger. As announced in the first part, Roger will have two:

  • a local model, running on LM Studio on my MacBook M4 Pro (with 24 GB of unified memory), which will be its default model;
  • a cloud model, GLM, through my GLM Coding Lite subscription with Z.ai, for heavier reasoning and as a fallback if the Mac does not respond.

In the OpenClaw series, the connection between the agent and Ollama was made via HTTP, without encryption or authentication. I had already pointed out this as a limitation. This time, we are going to try to do better. The idea is that LM Studio requires a token and only listens locally on the Mac. Another instance of NGINX, installed on my Apple laptop, will serve as an HTTPS front-end with filtering based on source IP addresses.

At the end of the article, both models will be tested from the virtual machine, and their API access keys will be stored in Vault.

Why LM Studio instead of Ollama

I have previously discussed Ollama in other articles. For this series, it would have been perfectly suitable. Since version 0.40, it even uses MLX by default, Apple's engine optimized for its chips. However, for this use case, LM Studio ticks more boxes:

Criteria LM Studio 0.4 Ollama 0.40
Engine on Apple Silicon MLX (and llama.cpp) MLX by default
API authentication Tokens with permissions None (key ignored)
Context size Adjustable per model when loaded Global setting or Model file
Memory management Model can be loaded without a time limit Variable OLLAMA_KEEP_ALIVE
Provider in Hermes lmstudio native Custom endpoint

The two key factors that made me switch to LM Studio are native authentication and context control. Remember: Hermes refuses to start with a context of less than 64,000 tokens. With Ollama, the default value on a 24GB machine is 4,096 tokens, and forgetting this causes confusing errors. With LM Studio, you set the size when loading the model, and you can see it.

LM Studio on the Mac

Installation

My machine is a MacBook Pro M4 with 24GB of memory, running macOS Tahoe 26.6.2, with a fixed IP address of 192.168.10.105 reserved on my DHCP server. Homebrew, the open-source package manager for Mac, is already installed (we will need it for NGINX).

LM Studio is installed from the official website (lmstudio.ai/download), version 0.4.x. Beware of a pitfall: the download page also offers Bionic, the vendor's new agent application, released in July 2026. That is not the one we need. Bionic is a ready-to-use agent built on the LM Studio engine, whereas we need the LM Studio API server and its token management. Both applications can coexist on the same Mac.

Download page for LM Studio 0.4.26 for macOS on M-series chips, with the installation of llmster below Saving the LM-Studio-0.4.26-4-arm64.dmg image to Downloads Opening the LM Studio disk image: drag the application into Applications LM Studio 0.4.26 installation window with a shortcut to Applications

Click the image to enlarge.

On the first launch, enable advanced settings in Settings > Developer.

First launch of LM Studio 0.4.26: welcome screen for Local AI on your computer Advanced settings screen in LM Studio: Developer Mode and starting the local service at login are enabled Main window of LM Studio with the menus Chat, Model Server, Library, LM Link, and Model Search

Click the image to enlarge.

LM Studio also provides a command-line tool, lms. I add it to the PATH of my Mac's shell for my user:

~/.lmstudio/bin/lms bootstrap
# ouvrir un nouveau terminal, puis :
lms version
lms bootstrap: the LM Studio CLI is already installed for the zsh shell lms version: banner of the LM Studio CLI

Click the image to enlarge.

There is also a version without a graphical interface, llmster, which can be installed with a script (curl -fsSL https://lmstudio.ai/install.sh | bash) and launched with lms daemon up. This is the ideal target for a server. On a Mac that I also use daily, I prefer to keep the application: token management is simpler and more visual.

Some concepts to consider before making a choice

Three concepts influence the choice of model. It is very important to understand them well and to understand their impact.

The number of parameters: A model with 9 billion parameters (9B) is a set of 9 billion numbers. These numbers represent the possible parameters of the model. The more parameters there are, the better the model usually performs, but it occupies more memory and can be slower to execute. That's why both the amount of memory and its speed are important, which explains the impact of Apple architectures like M series, where the shared memory between the CPU and GPU is extremely fast and therefore well-suited for running models. This is also true for graphics cards, where the memory bus is much faster between the GPU and the memory compared to the memory bus between the CPU and traditional memory modules.

To give you some points of comparison, even though the major players in the market don't always communicate very explicitly about the size of their parameters, keep in mind that GPT3 (2020) was around 175B, while estimates for GPT5 (professional version) range between 2000B and 5000B... Fable 5 is estimated to be between 5000B and 10000B... We are talking about memory usage sizes of between 5TB and 20TB... and that doesn't include the storage of conversation context.

Diagram showing the evolution of model sizes on a logarithmic scale, from GPT-2 (2019, 1.5B) to GPT-3 (2020, 175B), PaLM (2022, 540B), GPT-4 (2023, approximately 1.8 trillion), GPT-5 pro (2025, estimated at 2,000 to 5,000 billion) and Fable 5 (2026, estimated at 5,000 to 10,000 billion), followed by the open-weight Llama 3.1 405B, DeepSeek-V3, Kimi K2, Qwen3.5-397B, Kimi K3 (2.8 trillion) and Qwen3.5 9B models, along with the memory occupied by their weights

Click the image to enlarge.

In terms of speed, the memory bandwidth of a standard PC with DDR-5 is between 77 and 90 GB/s, which is 13 to 15 tokens/s (a token roughly represents three-quarters of a word). A chip like the one in my Mac offers a speed of 273 GB/s, or 40 to 45 tokens/s. A GPU like an RTX 5070 Ti reaches 896 GB/s for 130 to 150 tokens/s... When using a specialized GPU in a data center, such as an NVIDIA B200, it's 8000 GB/s, or over 1200 tokens/s

Diagram of memory bandwidth and generation speed, from PCs using DDR4 (51 GB/s) and DDR5 (77 to 90 GB/s) to the MacBook Pro M4 Pro (273 GB/s), RTX Spark, M4 Max, RTX 5070 Ti (896 GB/s), RTX 5090, H100, H200, B200 (8,000 GB/s) and Vera Rubin (19,200 GB/s), with the associated tokens per second limit

Click the image to enlarge.

I still find it important to have some reference points in mind, even though the figures quoted remain approximations; this helps to understand the challenges involved... Now, the size of the model is not everything, as we will see in the definition of the following concept.

Quantization: Each parameter is stored using a certain number of bits. Originally, this is 16 bits. Quantizing a model to 8 bits halves its size, with a quality loss that is usually imperceptible; at 4 bits, it divides the size by four, with a more noticeable loss, especially in the accuracy of tool calls. For an agent that needs to produce well-formed tool calls, it's best not to go below 8 bits when memory allows. In short, quantization allows you to keep the same number of parameters but requires less storage space... at the cost of reducing the precision of responses and increasing the risk of hallucinations. Be careful with quantization, as some market players are not always very "forthcoming" about this. For example, when NVIDIA offers its recent RTX Spark processor for laptops, which is derived from the DGX Spark that I mentioned earlier, they advertise model execution capabilities up to 120 billion parameters (120B)... yes, but in 4 bits 😊

Diagram of quantization: a parameter originally stored on 16 bits, dividing the size by two when using 8 bits, and by four when using 4 bits; Qwen3.5 9B goes from 18 GB to 9 GB and then 4.5 GB, staying below the 24 GB of Roger's Mac; a 120B model goes from 240 GB to 120 GB and then 60 GB, comfortably fitting within the 128 GB of the RTX Spark when using 4 bits

Click the image to enlarge.

Context: This is the amount of text the model can take into account in each exchange: the SOUL.md instructions, the conversation history, the tool responses. It is also measured in tokens. Context has a memory cost that adds to the model's, and this cost grows with its size. And an agent consumes a huge amount of context: a single response from the Xen Orchestra MCP server can contain thousands of tokens. That's why Hermes requires at least 64,000 tokens. This additional memory usage physically takes the form of the KV cache and is specific to each conversation... Here too, a few orders of magnitude are worth knowing. As you can learn in my favorite podcast, à la french, which I strongly encourage you to watch, for a specialized server costing €500,000, with a model of about 500B loaded in memory, the KV cache leaves room in the remaining memory for only about 10 simultaneous users. Finally, 100,000 tokens of context, once considered a rare case (analyzing a large PDF in a RAG (Retrieval-Augmented Generation) setup, for example), have become an everyday standard in agentic AI.

To clarify the term MLX: it is Apple's "AI-dedicated" computing engine, optimized for its chips. On a Mac, it fully utilizes the unified memory shared between the processor and the GPU, which allows you to load larger models, as explained earlier. This is what makes a 24GB MacBook interesting for local AI (and, generally, why Apple computers are of interest to those who want to do AI locally, in fact, I even bypassed my principles to buy a Mac just for that...).

Finally, to conclude this section of the article, please note that to generate a token, all active parameters must be processed. Therefore, the maximum theoretical token generation speed can be calculated using:

Max speed (tokens/s) ≈ Memory bandwidth (GB/s) Size of active parameters in memory (GB)

There are now optimizations to this constraint, where models with billions of parameters do not necessarily activate all of them, but only those needed for the problem at hand: this is called MoE (Mixture of Experts). It is notably around these optimizations, now adopted by everyone, that companies like Mistral (cocorico!) and DeepSeek made their name.

As mentioned earlier, it is important to keep all your fundamentals in mind when you need to choose a model for your agent.

Choosing the model

It is not possible here to use models from OpenAI or Anthropic. They are closed-source and can only be used within the context of a subscription and usually within their own applications. However, there are so-called OpenWeight models, which should not be confused with open-source models. Most often Chinese, these are LLMs trained in data centers and then made available to the public for internal use. Their particularity is that their final parameters are configurable and adaptable, allowing for multiple variations, ranging from the largest model to much lighter ones. (Be careful! You usually don't know how the model was trained or the details of its creation.)

OpenWeight models tend to catch up with the so-called "frontier" models that are specific to market leaders. Even if they never quite match (or at least not yet) the current top performers, they can be perfectly adequate for many use cases.

Ranking by the Artificial Analysis Intelligence Index for proprietary and open-weight models: Claude Fable 5.2 is at the top with 65, Kimi K3.1 Pro is the first open-weight model with 46, and GLM-5.3 has 32

Source: Artificial Analysis, Intelligence Index v5.0.1 (proprietary / open weight).

Click the image to enlarge.

However, just because Kimi K3 is available for free doesn't mean you can run it with its 2800 billion parameters in its basic version... Since its weights are open, you will have to resort to versions with significantly fewer parameters.

On my Mac, with 24 GB of memory shared between macOS, applications, and the model, you need to be reasonable. The constraint of Hermes (64,000 tokens minimum) is significant: a context of that size already occupies several gigabytes in addition to the model's weights.

Therefore, I settled on Qwen3.5 9B in MLX format, quantized to 8 bits (lmstudio-community/Qwen3.5-9B-MLX-8bit). It's the same family as the one used with OpenClaw; it handles tool calls and natively supports very long contexts. This model, published by Alibaba Cloud, comes in a wide range of LLMs, up to 397 billion parameters, with many variations. It serves as the basis for many derivatives depending on the desired purpose. In our case, Qwen3.5 9B is a good compromise for a conversational agent responsible for simple tasks.

We download the model. A small subtlety: with an identifier of the form owner/name, lms get searches the LM Studio catalog and answers that the model does not exist. To fetch it from Hugging Face, the largest LLM model library in the world, you have to give it the full URL of the repository:

lms get https://huggingface.co/lmstudio-community/Qwen3.5-9B-MLX-8bit

lms announces the download size (10.45 GB for the 8-bit version) and asks for confirmation before starting.

lms get: download of Qwen3.5 9B 8bit completed

Click the image to enlarge.

Once the download is complete, be careful: LM Studio does not save the model under the name of the Hugging Face repository, but under a short key that is specific to it. You can find it with lms ls:

For me, the key is qwen3.5-9b-mlx. This is the one you need to use with lms load. With the name of the repository, lms responds that it cannot find the model and offers to choose it from a list.

lms ls: the qwen3.5-9b-mlx model (10.45 GB) and the nomic embedding model

Click the image to enlarge.

Next, we ask LM Studio for an estimate of the memory required with the desired context, before actually loading the model:

lms load qwen3.5-9b-mlx --context-length 65536 --estimate-only
lms load --estimate-only: estimation of 13.63 GB for 65,536 context tokens

Click the image to enlarge.

On my machine, LM Studio estimates the requirement at 13.63 GiB: a little under 10 GiB for the model itself, the rest for the 65,536 context tokens. Out of 24 GB, that leaves about 10 GB for macOS and my applications, which is comfortable. Note the Confidence: LOW: it is an estimate, not a measurement.

If the estimated requirement exceeds what your Mac (or your hardware) can comfortably allocate (keep at least 6 to 8 GB for macOS and your applications), switch to the 4-bit version.

Loading and server

We load the model with a context of 65,536 tokens and a short identifier. This is the identifier that Hermes will use to refer to the model:

lms load qwen3.5-9b-mlx \
  --context-length 65536 --identifier qwen3.5-9b-mlx-8bit
lms ps

We see our identifier, the 65,536 token context, and no time-to-live (TTL) value. The displayed size of 10.45 GB corresponds to the model's weights; the context memory is added as data is exchanged. The PARALLEL column indicates that LM Studio can process up to 4 requests simultaneously.

Without a lifespan option (--ttl), a model loaded with lms load remains in memory. This is intentional: in the OpenClaw series, I noticed that the initial conversation was slow because Ollama reloaded the model. Here, it remains loaded continuously.

lms load of qwen3.5-9b-mlx with the identifier qwen3.5-9b-mlx-8bit, loading in progress lms ps: qwen3.5-9b-mlx-8bit loaded with a context of 65,536, 4 parallel requests and no TTL

Click the image to enlarge.

Without a lifespan option (--ttl), a model loaded with lms load remains in memory. This is intentional: in the OpenClaw series, I noticed that the initial conversation was slow because Ollama reloaded the model. Here, it remains loaded continuously.

Server settings are not found in the application's preferences. They can be found in the sidebar, under the Developer section. Open "Local Server" (the page is titled "Model Server"), and then click the "Server Settings" button at the top of the page:

  • "Server Port": 1234;
  • "Require Authentication" enabled;
  • "Serve on Local Network" disabled: LM Studio only listens on 127.0.0.1 (this is the address displayed in "The local server is reachable at"), and NGINX will expose the service;
  • "Allow per-request MCPs" disabled, as well as "Allow calling servers from mcp.json": Roger has its own MCP servers on the Hermes side; it has no reason to ask LM Studio to call other ones;
  • "Just-in-Time Model Loading" disabled: without this option, a client cannot request another model to be loaded on demand. Only the model that we have loaded ourselves will respond, and the Mac's memory remains under control.
LM Studio, Model Server page and Server Settings panel: port 1234, Require Authentication, Serve on Local Network, MCP and Just-in-Time Model Loading

Click the image to enlarge.

Finally, there is the API key. Still in "Server Settings", under "Require Authentication", the "Manage Tokens" button opens the "LM Studio API Tokens" window. Click "Create new token" and name it roger.

Manage Tokens button under Require Authentication, no API key active LM Studio API Tokens window is empty with the Create new token button

Click the image to enlarge.

LM Studio does not offer very fine-grained permissions (but it is still better than Ollama): a token always provides basic access to the API ("Baseline access"). The only adjustable permissions concern the MCP servers, and we set both of them to Deny:

  • "Allow per-request remote MCP servers": Deny;
  • "Allow calling servers from mcp.json": Deny.

Be careful, the default value for the first option is "Allow". It's a good habit to adopt: when a permission is not needed, disable it.

Create new permission token window with the name roger and both MCP permissions

Click the image to enlarge.

The token (in the format sk-lm-…) is only displayed once, in the "Token Created" window. Copy it using the "Copy" button and keep it handy for the duration of this article: we will store it in Vault later.

Token Created window from LM Studio, token value masked

Click the image to enlarge.

We start the server and check that it only listens locally:

lms server start
lms server status
lsof -nP -iTCP:1234 -sTCP:LISTEN

The last command should show a listen on 127.0.0.1:1234, and not on *:1234.

lms server start and status, lsof showing LM Studio listening on 127.0.0.1:1234

Click the image to enlarge.

Local tests

We test the OpenAI-compatible API, first without a token (which should fail), then with a token:

read -rs LMS_TOKEN && export LMS_TOKEN   # coller le jeton, rien ne s'affiche
curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:1234/v1/models
curl -s http://127.0.0.1:1234/v1/models -H "Authorization: Bearer $LMS_TOKEN" | jq -r '.data[].id'

We expect a 401 code for the first command, then the identifier qwen3.5-9b-mlx-8bit in the list.

Masked input of the LM Studio token in the LMS_TOKEN variable Request without a token to /v1/models: code 401 Request with a token to /v1/models: qwen3.5-9b-mlx-8bit

Click the image to enlarge.

An agent spends its time calling tools. Therefore, we check that the model can produce a tool call, using a fictitious function:

curl -s http://127.0.0.1:1234/v1/chat/completions \
  -H "Authorization: Bearer $LMS_TOKEN" -H "Content-Type: application/json" \
  -d '{
    "model": "qwen3.5-9b-mlx-8bit",
    "messages": [{"role": "user", "content": "Combien de VMs tournent sur le pool ?"}],
    "tools": [{
      "type": "function",
      "function": {
        "name": "count_running_vms",
        "description": "Retourne le nombre de VMs démarrées sur le pool Xen Orchestra",
        "parameters": {"type": "object", "properties": {}, "required": []}
      }
    }]
  }' | jq '.choices[0].message.tool_calls, .usage'

The response should contain a tool_calls to count_running_vms, and not an invented response. This is a good indicator of the model's ability to function as the brain of an agent.

JSON response from Qwen3.5 containing a tool_calls to count_running_vms and usage details

Click the image to enlarge.

To get an idea of the speed, we time a slightly longer generation and look at the number of tokens produced:

time curl -s http://127.0.0.1:1234/v1/chat/completions   -H "Authorization: Bearer $LMS_TOKEN" -H "Content-Type: application/json"   -d '{"model":"qwen3.5-9b-mlx-8bit","messages":[{"role":"user","content":"Explique en 200 mots ce qu un hyperviseur de type 1."}]}'   | jq '.usage'

And here's the first surprise. On my system, the command took more than five minutes to complete:

LM Studio server logs: 7,273 tokens in the response, including 6,969 tokens of reasoning New tool call test followed by timed generation: over 7000 tokens produced

Click the image to enlarge.

More than 7,000 tokens for a 200-word response, including nearly 7,000 of reasoning_tokens. The model is not slow; it thinks too much. Qwen3.5 works by default in "thinking" mode: before responding, it produces a long internal reasoning process. For an agent that chains tool calls, this is unacceptable: each turn would take minutes and consume the context.

This incident highlights the notion of thinking, or reasoning. It is one more concept to grasp: the model's ability to generate a draft of internal reflection before giving you the answer to your question. (It's the "think twice before you speak" principle applied to AI.)

Initially, models incorporating this principle of operation were distinct from those without it. However, the reasoning capability is now included in many models, but it can be adjusted according to the desired level (low, medium, high) or disabled. Activating the highest level of reasoning for a model allows you to refine responses and avoid errors, but it consumes tokens and time that can be very significant, even counterproductive when asking the model to perform simple tasks.

In my case, Roger will not need to solve advanced mathematical problems or try to predict the results of French elections… but simply answer basic questions like "how many VMs are running". Therefore, the 'thinking' mode is completely unsuitable in my case, and even detrimental.

Disable the "thinking" feature and adjust inference

LM Studio does not offer a switch to disable the 'thinking' feature for Qwen3.5, and the parameters that could be sent in the request are not taken into account. The solution involves modifying the prompt template (the Jinja template) of the model.

In the sidebar, open Library, then click on the gear icon next to the model qwen3.5-9b-mlx. The right panel displays its default configuration. In the Inference tab, in the Prompt Template section, add this line at the top of the template (in the "Template (Jinja)" tab):

{%- set enable_thinking = false %}

The model will then change to a "Customized" status.

LM Studio, Library, Qwen3.5-9B-MLX-8bit in Customized mode, Inference tab and Prompt Template section Jinja template for the model starting with the line set enable_thinking = false

Click the image to enlarge.

While you're there, adjust the generation parameters, still in the Inference tab. The default values in LM Studio are quite different from those recommended by Qwen for the mode without 'thinking':

Setting Default value Qwen recommendation
Temperature 0.1 0.7
Top K Sampling 100 20
Top P Sampling disabled enabled, 0.8
Repeat Penalty enabled, 1.1 disabled
Inference parameters being modified: Temperature 0.7 and Top K Sampling 20 Saving the configuration as a preset named hermes

Click the image to enlarge.

I can't go into the exact details of what these parameters mean here, and to be honest, it was my AI friend, OPUS 5.5, that suggested these values to me. The temperature setting is particularly interesting because it defines the degree of randomness (or creativity) in the model when choosing tokens. It doesn't affect the speed or memory usage, but it does influence the model's choice based on the probability associated with your question. Setting the temperature to 0 means the model will always choose the word that has the highest probability of matching the meaning of the sentence. As you get closer to 1, you allow the LLM to consider words that are further away from the word with the highest probability score, which leads to more creativity. You might be tempted to set it to zero all the time, especially for tasks like coding, but combining this with 'thinking' can create an infinite loop where the model is constantly searching for the absolute highest probability level. By accepting a higher temperature, you allow the model to explore multiple potential solutions.

In general, it is often necessary to "tweak" the configuration of an open-weight model to run it locally. You often have to test and iterate to find the right settings for the trade-off you want between answer quality and execution speed. For that, a frontier AI is a good help in refining your local AI settings... You have to know how to combine the best of both worlds to make the most of AI 😊

We continue by ejecting the model (using the "Eject" button on the Model Server page), then reloading it with the same command lms load as before, and running the test again:

Test of generation after disabling thinking: reasoning_tokens is 0 and duration is approximately 11 seconds

Click the image to enlarge.

There are no reasoning tokens left, 313 response tokens, and the result is returned in less than 12 seconds, which is about 27 tokens per second. This is perfectly acceptable for Roger.

The Mac should not go to sleep

A local model is only useful if the Mac is available. However, a MacBook loves nothing more than going to sleep, and a sleeping Mac means that Roger will switch to GLM, or may not respond at all.

For my part, I use Amphetamine, a small free application available on the Mac App Store. It installs in the menu bar and prevents the system from going to sleep, whether plugged in or running on battery, for a chosen duration or indefinitely. The screen can be turned off without any problems; only the system's sleep mode is an issue. This is the most flexible solution for a laptop that I move around and also use daily.

Amphetamine page on the Mac App Store: a free utility that prevents the Mac from going to sleep

Click the image to enlarge.

If you'd rather do without an application, pmset does the same job from the command line, but only on AC power (option -c):

sudo pmset -c sleep 0 disksleep 0 displaysleep 10
pmset -g | grep -E ' sleep|displaysleep|disksleep'

To ensure that the model is automatically reloaded after a restart, enable the server startup option in LM Studio's settings when logging in, and add a small launch agent that reloads the model with the correct context (an idea from AI 😊):

mkdir -p ~/bin ~/Library/LaunchAgents
cat > ~/bin/lms-load-roger.sh <<'EOF'
#!/bin/zsh
# Recharge le modèle de Roger avec 64K de contexte au démarrage de la session
LMS="$HOME/.lmstudio/bin/lms"
for i in {1..30}; do "$LMS" server status >/dev/null 2>&1 && break; sleep 10; done
"$LMS" ps | grep -q qwen3.5-9b-mlx-8bit || \
  "$LMS" load qwen3.5-9b-mlx --context-length 65536 --identifier qwen3.5-9b-mlx-8bit
EOF
chmod +x ~/bin/lms-load-roger.sh

cat > ~/Library/LaunchAgents/tech.myprivatelab.lms-load-roger.plist <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>tech.myprivatelab.lms-load-roger</string>
  <key>ProgramArguments</key><array><string>$HOME/bin/lms-load-roger.sh</string></array>
  <key>RunAtLoad</key><true/>
  <key>StandardOutPath</key><string>/tmp/lms-load-roger.log</string>
  <key>StandardErrorPath</key><string>/tmp/lms-load-roger.log</string>
</dict>
</plist>
EOF
launchctl load ~/Library/LaunchAgents/tech.myprivatelab.lms-load-roger.plist
Creation of the lms-load-roger.sh script and the tech.myprivatelab.lms-load-roger.plist agent, then launchctl load

Click the image to enlarge.

This requires an open user session at Mac startup (automatic login), which is acceptable on a personal machine at home, but clearly not in a corporate environment.

Exposing the model properly

DNS and certificate

Now is the time to create the second DNS entry mentioned: llmmac.coolcorp.priv, an A record pointing to the Mac's address, 192.168.10.105. I prefer a name that identifies the machine rather than the service; tomorrow, another source of models might appear and it will simply have its own name alongside it. I am particularly thinking of my NVIDIA RTX 5070 Ti card and its 16 GB of VRAM, which I used with OpenClaw. For now, it is reserved for another project, about which I may tell you one day on this site if it succeeds.

Windows DNS console, new A record llmmac pointing to 192.168.10.105 with its PTR pointer

Click the image to enlarge.

For the certificate, we proceed as in part 03, but directly on the Mac. The OpenSSL provided by macOS is actually LibreSSL; I use the one from Homebrew to remain consistent with the VM:

brew install openssl@3 nginx
OPENSSL="$(brew --prefix openssl@3)/bin/openssl"
mkdir -p ~/pki && cd ~/pki
cat > llmmac.cnf <<'EOF'
[req]
default_bits       = 4096
prompt             = no
distinguished_name = dn
req_extensions     = ext

[dn]
CN = llmmac.coolcorp.priv
O  = COOLCORP
C  = FR

[ext]
subjectAltName = DNS:llmmac.coolcorp.priv
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth
EOF
$OPENSSL req -new -newkey rsa:4096 -nodes -config llmmac.cnf -keyout llmmac.key -out llmmac.csr
chmod 600 llmmac.key
brew install openssl@3 nginx: installation of NGINX 1.31.8 on the Mac OPENSSL variable pointing to the Homebrew OpenSSL Creation of the ~/pki directory and the llmmac.cnf configuration file Generation of the 4096-bit RSA private key and the llmmac.csr request Contents of the ~/pki directory: llmmac.cnf, llmmac.csr, and llmmac.key

Click the image to enlarge.

We submit llmmac.csr to the authority from a Windows machine with the same template:

certreq -submit -attrib "CertificateTemplate:TPL-SRV-WEB-DEFAULT" llmmac.csr llmmac.cer
certreq -submit with the TPL-SRV-WEB-DEFAULT template: certificate issued

Click the image to enlarge.

We bring the file llmmac.cer and the root CA certificate (CA-COOLCORP.crt, identical to the one seen in section 03) into the folder ~/pki on the Mac.

PEM content of the llmmac.cer certificate copied to the Mac ~/pki directory with CA-COOLCORP.crt and llmmac.cer

Click the image to enlarge.

First step: add the CA to the system keychain so that the Mac's tools trust it. A small subtlety is that this cannot be done via SSH. Modifying the trust settings of the system keychain requires confirmation in a macOS window, which an SSH session cannot display: the command security add-trusted-cert fails. Therefore, we use the graphical interface directly on the Mac:

security add-trusted-cert via SSH: authorization denied since no user interaction was possible

Click the image to enlarge.

  • In Finder, double-click the CA-COOLCORP.crt: macOS opens Keychain Access and offers to add the certificate. Choose the System keychain.
  • In Keychain Access, double-click the added certificate, expand the "Trust" section, and choose "Always trust" for "When using this certificate".
  • Close the window and confirm with the administrator password.
macOS Keychain Access: adding CA-COOLCORP.crt to the System keychain

Click the image to enlarge.

Everything else works fine via SSH. We convert and verify the Mac's certificate, then install it for NGINX:

cd ~/pki
$OPENSSL x509 -in llmmac.cer -out llmmac.crt
$OPENSSL verify -CAfile CA-COOLCORP.crt llmmac.crt
NGX="$(brew --prefix)/etc/nginx"
mkdir -p "$NGX/certs"
install -m 644 llmmac.crt "$NGX/certs/llmmac.coolcorp.priv.crt"
install -m 600 llmmac.key "$NGX/certs/llmmac.coolcorp.priv.key"
Conversion of the certificate to llmmac.crt and verification against the CA: OK Installation of the certificate and key in the NGINX certs directory

Click the image to enlarge.

NGINX on macOS

The configuration follows the same principle as the VM, but with two additional precautions: only the VM's address is accepted, and any request without an Authorization header is rejected before even reaching LM Studio. Responses from an LLM can take several minutes and arrive in a stream, hence the long delays and the deactivation of buffering.

cat > "$(brew --prefix)/etc/nginx/servers/llmmac.conf" <<'EOF'
# Termine le TLS devant LM Studio (127.0.0.1:1234) pour l'agent Roger.
server {
    listen 443 ssl;
    http2 on;
    server_name llmmac.coolcorp.priv;

    ssl_certificate     /opt/homebrew/etc/nginx/certs/llmmac.coolcorp.priv.crt;
    ssl_certificate_key /opt/homebrew/etc/nginx/certs/llmmac.coolcorp.priv.key;
    ssl_protocols TLSv1.2 TLSv1.3;

    # Seule la VM de Roger est admise (pf filtre aussi en amont)
    allow 192.168.10.41;
    deny all;

    # Défense en profondeur : pas de jeton, pas de passage
    if ($http_authorization = "") { return 401; }

    location / {
        proxy_pass http://127.0.0.1:1234;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header Authorization $http_authorization;
        proxy_buffering off;
        proxy_read_timeout 900;
        proxy_send_timeout 900;
    }
}
EOF
nginx -t
brew services start nginx
lsof -nP -iTCP:443 -sTCP:LISTEN
Creation of the llmmac.conf file for NGINX on the Mac nginx -t: syntax is correct brew services start nginx: service started lsof: NGINX listening on port 443

Click the image to enlarge.

On an Apple Silicon Mac, Homebrew is installed in /opt/homebrew, which explains the certificate paths. For several versions, macOS allows a regular user to listen on port 443; if the startup still fails, start the service with sudo brew services start nginx.

The macOS firewall

The allow of NGINX is the first barrier, but I prefer that packets from another machine don't even reach NGINX. We use pf, macOS's built-in firewall, with a dedicated anchor:

sudo tee /etc/pf.anchors/llmmac >/dev/null <<'EOF'
# N'accepter le 443 (NGINX -> LM Studio) que depuis la VM Roger
block in quick proto tcp from ! 192.168.10.41 to any port 443
pass  in quick proto tcp from 192.168.10.41 to any port 443
EOF
sudo cp /etc/pf.conf /etc/pf.conf.bak
printf '\nanchor "llmmac"\nload anchor "llmmac" from "/etc/pf.anchors/llmmac"\n' | sudo tee -a /etc/pf.conf
sudo pfctl -vnf /etc/pf.conf      # vérification de la syntaxe sans appliquer
sudo pfctl -f /etc/pf.conf
sudo pfctl -e
sudo pfctl -a llmmac -sr

Be careful of two things. First, a major macOS update can overwrite /etc/pf.conf: remember to check after each update. Second, pf is not always reactivated on reboot; you need to check its status (sudo pfctl -s info) after a reboot and, if necessary, add a LaunchDaemon that executes pfctl -e.

Creation of the pf anchor /etc/pf.anchors/llmmac Adding the anchor to pf.conf, activating pf, and sudo pfctl -a llmmac -sr showing both rules

Click the image to enlarge.

Tests from the virtual machine

Let's go back to the prdlinage501 VM. The CA is already in the trusted store since Part 03, so curl should accept the certificate without any special options. We test without a token, then with:

dig +short llmmac.coolcorp.priv
curl -s -o /dev/null -w "%{http_code}\n" https://llmmac.coolcorp.priv/v1/models
read -rs LMS_TOKEN && export LMS_TOKEN
curl -s https://llmmac.coolcorp.priv/v1/models -H "Authorization: Bearer $LMS_TOKEN" | jq -r '.data[].id'

We expect 192.168.10.105, then 401, then qwen3.5-9b-mlx-8bit.

Tests using curl from the VM to llmmac.coolcorp.priv: 401 without a token, list of models with a token

The same test from a container in the hermes account, because that's where Roger will make its calls. We mount the CA certificate placed in Part 03 and simply verify that we get a 401 without a token: this proves that DNS, the network path, and TLS are working from a rootless container, without passing any secrets.

# Session hermes (sudo machinectl shell hermes@)
podman run --rm -v ~/vault/tls/ca.crt:/ca.crt:ro docker.io/library/alpine:3.22 sh -c \
  'apk add -q --no-progress curl && curl -s --cacert /ca.crt -o /dev/null -w "%{http_code}\n" https://llmmac.coolcorp.priv/v1/models'
Opening a hermes session with machinectl Test from a rootless Alpine container using the hermes account: 401 without a token

Click the image to enlarge.

Storing the token in Vault

The LM Studio token has served its purpose for testing. We now store it in Vault, with my administrator account, then we remove it from the session:

vault login -method=userpass username=bvivi57
set +o history
vault kv put secret/hermes/roger/lmstudio_api_key value="$LMS_TOKEN"
unset LMS_TOKEN
set -o history
vault kv get -field=value secret/hermes/roger/lmstudio_api_key | wc -c

The last command displays the token length, not its value. This is sufficient to verify that it has been registered.

vault login with the bvivi57 administrator account (token masked). vault kv put of the LM Studio token under secret/hermes/roger/lmstudio_api_key and verification of its length

Click the image to enlarge.

GLM at Z.ai

The subscription and API key

For the cloud, I use the GLM Coding Lite offering from Z.ai, with an annual subscription (150 $ per year). A pleasant surprise when preparing this series: Hermes Agent is listed as one of the officially supported tools by this offering, in the category of general-purpose agents, on a "best effort" basis. Understand that it should work, but without guarantee, and throughput may be limited during peak hours.

I did not use my Anthropic Cloud subscription because it is not permitted to use it with third-party tools... or you have to pay for additional API calls. I chose GLM, which is also available in OpenWeight, due to its good reputation, especially in coding. Since I need performance, I am using the hosted offering where the model is available with many more parameters than I could afford to run locally.

Since October 16, 2026, Z.ai manages "Standard API" keys (pay-as-you-go) and "Coding Plan" keys separately, and it is the type of key that determines billing. Therefore, in the key management page (https://z.ai/manage-apikey), you need to create a "Personal Coding Plan" key, and not a "Standard" key. A standard key would also work on the Coding Plan endpoint, but it would be charged based on usage from your account balance, without affecting the subscription quota. This is the kind of error you discover at the end of the month.

Z.ai console, Personal Coding Plan tab, and creation of an API key named roger

Click the image to enlarge.

The plan gives access to two models: glm-5.3, the full model, which always reasons before answering, and glm-5.3-flash, faster and far less demanding on the quota.

Understanding quotas

The Lite offering does not count in tokens, but in credits: 2,000 credits per rolling five-hour window, and 10,000 per week. The cost of a request depends on the model, with different coefficients for input tokens, cached input tokens, and output tokens. And yes, often, the cost of an input token (the analysis of the request) is not the same as the cost of an output token (the generation of the response)... and as usual, there is some caching in between.

Model Input Cached Input Output
glm-5.3 6,9 1,7 24
glm-5.3-flash 2,3 0,56 8

The cost in credits is the sum of tokens multiplied by their coefficient, divided by 10,000. Off-peak hours (excluding 2 PM to 6 PM Beijing time on weekdays, which is 8 AM to 12 PM in Paris during winter) halve the consumption.

It's time to talk about "turns". In an agent context, a "turn" refers to a complete round of interaction. Each turn increases the context size, as we send back the entirety of the previous turns. After a while, token consumption is entirely consumed by recalling these interactions... knowing that a question can trigger multiple turns.

Let's do a quick calculation for Roger. A typical agent turn, with 20,000 context tokens (90% already in cache) and 1,000 response tokens, costs approximately (2,000 × 6.9 + 18,000 × 1.7 + 1,000 × 24) / 10,000 ≈ 6.8 credits with glm-5.3, and about 2.3 with the Flash version. That's roughly 300 turns with glm-5.3 per five-hour window. This is more than enough for occasional reasoning, but not for running Roger continuously on the large model. This is why the local model is the default.

When the quota is exhausted, the Coding Plan key does not switch to a pay-as-you-go system. The requests simply fail. Hence, it's important to keep the local model as the primary one.

Important point: calculating AI consumption is a real headache... it is one of the major difficulties we face today. The same word does not necessarily translate into the same number of tokens from one model to another. On top of that, providers apply pricing grids that can vary, the distribution model can affect prices, and you often end up with a tangle of figures that makes costs very hard to anticipate. Once again, the solution lies in testing and iterating, combined with permanent monitoring of consumption and safeguards in case of runaway usage. Add to that choosing the right model for the right action... it is one of the key challenges ahead, and more and more solutions are appearing that pre-select a model based on the question asked, to route it to the most suitable (and most cost-effective) model for the need.

Testing the key

The endpoint to use for a Coding Plan key is https://api.z.ai/api/coding/paas/v4, which is compatible with the OpenAI API. Using the standard endpoint with this key results in an insufficient balance error. We are testing from the VM, using the Flash model to conserve quota:

set +o history
read -rs GLM_KEY && export GLM_KEY
curl -s https://api.z.ai/api/coding/paas/v4/chat/completions \
  -H "Authorization: Bearer $GLM_KEY" -H "Content-Type: application/json" \
  -d '{"model":"glm-5.3-flash","messages":[{"role":"user","content":"Réponds uniquement : OK Roger"}]}' \
  | jq -r '.choices[0].message.content, .usage'
Entering the masked GLM key into the GLM_KEY variable, history disabled Response from glm-5.3-flash: "OK Roger" with usage details

Click the image to enlarge.

If the response is correct, we store the key in Vault:

vault kv put secret/hermes/roger/glm_api_key value="$GLM_KEY"
unset GLM_KEY
set -o history
vault kv list secret/hermes/roger
Keys
----
glm_api_key
lmstudio_api_key
vault kv put command to store the GLM key under secret/hermes/roger/glm_api_key vault kv list command for secret/hermes/roger, showing glm_api_key and lmstudio_api_key

Click the image to enlarge.

The routing strategy

Both brains are ready. Here's how Roger will use them, which we will translate into its configuration in Part 06:

model:
  provider: lmstudio
  default: "qwen3.5-9b-mlx-8bit"
  base_url: "https://llmmac.coolcorp.priv/v1"
  context_length: 65536

fallback_providers:
  - provider: zai
    model: glm-5.3-flash

auxiliary:
  compression:
    provider: zai
    model: glm-5.3-flash
  • By default, Roger uses the local model. The data remains on my machine.
  • As a backup, if the Mac is unresponsive (turned off, model unloaded, NGINX stopped), Hermes automatically switches to glm-5.3-flash.
  • The background tasks for context compression run on glm-5.3-flash, so as not to monopolize the Mac.
  • On demand, I can switch Roger to glm-5.3 for more in-depth analysis, using the command /model directly in Telegram.

There is no automatic routing "based on difficulty" in Hermes: the choice remains explicit (at least to my knowledge and at the time of writing this article). When GLM is used, the conversation context goes to Z.ai, including responses from tools. Roger will have an instruction to report this.

The local model's protection chain

Let's take a step back and look at what we've built for the local model. A request from Roger now goes through four successive checks:

  1. The Mac's pf firewall only accepts connections on port 443 from the VM's address.
  2. NGINX in turn checks the source address, terminates TLS with a certificate from the internal PKI, and rejects any request without an authentication header.
  3. LM Studio verifies the token, which only grants inference rights and the ability to list models.
  4. LM Studio only listens locally: even bypassing NGINX, it is impossible to reach it from the network.
Diagram of the local model protection chain: Roger's request from VM 192.168.10.41 passes through the Mac's pf firewall, then NGINX which verifies the address, terminates TLS, and requires the Authorization header. Next, LM Studio verifies the token. LM Studio only listens on 127.0.0.1:1234. Another machine on the LAN is blocked by pf and cannot connect to port 1234

Click the image to enlarge.

This is already a good chain of protection for internal use, at least much better than my first attempt with OpenClaw. We could consider API key rotation, but in my usage, I don't need to go that far.

Archiving

The files on the Mac are not on the VM; we add them to the repository manually (without a private key or certificate, of course):

# Sur la VM, compte bvivi57, après avoir copié les fichiers du Mac dans ~/roger.coolcorp.priv/mac/
cd ~/roger.coolcorp.priv
ls mac/   # llmmac.conf  pf-llmmac  lms-load-roger.sh  tech.myprivatelab.lms-load-roger.plist  llmmac.cnf
git add mac/ && git commit -m "Partie 04 : LM Studio, NGINX et pf sur le Mac" && git push

Conclusion

Roger now has two brains. The local model runs on the Mac with a 64K context, protected by a token, TLS, and a firewall that only accepts connections from the VM. The cloud model is ready, with a key that correctly consumes the subscription quota. Both secrets are in Vault.

The cleartext traffic to the LLM that I regretted in the OpenClaw series is a thing of the past. It takes a bit more work, but it's the kind of detail that makes the difference between a demo and a lasting installation that could be rolled out in a company.

This article was also an opportunity to highlight many important concepts and principles that need to be understood and manipulated when working with AI, especially locally.

The world of hardware is currently very active. The cost of IT equipment is skyrocketing, and choosing between sovereignty and economy has become a major issue for companies adopting AI. For now, a single setup, whether cloud-based or local, cannot meet all needs (or if it does, it's far too expensive for a company). There are many models and implementations available, with an ecosystem that is constantly changing. For those who are concerned about certain jobs, know that while agentic AI may reshape many professions, it is also creating many new areas of expertise. I don't know how all of this will evolve, but as things stand, there is still a lot of work to be done!

In the next article, we will prepare everything that Roger will monitor and use: the Xen Orchestra account and its token, the Telegram bot, and the Obsidian vault. See you in Part 05: Xen Orchestra, Telegram, and Obsidian Dependencies.