Switching Between a Home LLM and a Free Cloud Model — Safely
A practical setup with llama.cpp + Tailscale + OpenRouter + Hermes Agent
By Matis atelier
About the date of this information
Everything here reflects the state of the software as of August 2026, when I read the Hermes Agent source code directly because I could not find this behavior documented. Official documentation has probably improved since then. Check the current docs first; treat this article as the "why it behaves that way" companion, not as the final word. Config key names may have changed.
All IPs, keys, hostnames and paths below are placeholders.
1. The goal
I run an LLM at home (llama.cpp, Gemma 4 12B) and an agent (Hermes Agent) on a VPS. I wanted:
| Situation | Behavior |
|---|---|
| Home server is up | Use the home LLM |
| Home server is down | Use a free cloud model (OpenRouter) |
| The free model also fails | Retry, and surface an error if it still fails |
Why bother? The home box is not on 24/7 (power schedule), and free cloud models are rate-limited when you need them most. Combining both is cheap and resilient.
Telegram / cron
│
▼
┌──────────────┐ Tailscale (encrypted) ┌────────────────────┐
│ Agent (VPS) │ ────────────────────────► │ Home LLM server │
│ │ Bearer token required │ llama.cpp │
└──────┬───────┘ └────────────────────┘
│ if unreachable / failing
▼
OpenRouter (openrouter/free)
2. Step 1 — Lock down the local server first
A local LLM endpoint is an unauthenticated compute resource unless you protect it.
a) Require an API key in llama.cpp
llama serve -m <model.gguf> --host <bind-address> --port 8080 \
--api-key <long-random-token>
Generate the token with openssl rand -hex 32. In systemd, remember the trailing \ on every continued ExecStart= line, or the flag is silently dropped. Then daemon-reload and restart.
b) Reach it over a private network, not the open internet
Use Tailscale (or WireGuard). Important: both ends need the client installed. I assumed the VPS side already had it; it did not, so every connection timed out until I installed it. Verify with tailscale status on both machines.
c) Don't bind more widely than you need
--host 0.0.0.0 listens on every interface. The API key is a good last line of defense, but prefer binding to the Tailscale address (or firewalling port 8080 to the Tailscale interface) and restricting who can reach it with Tailscale ACLs.
d) Keep secrets out of chat logs, tickets and screenshots. If a token ever lands somewhere public, rotate it.
3. Step 2 — Register the server in the agent (the gotcha that cost me hours)
The obvious config:
model:
provider: custom
base_url: http://<tailscale-ip>:8080/v1
plus OPENAI_API_KEY in the environment. Result: 401 Invalid API Key — while curl with the same key from inside the same container returned 200.
Reading the credential resolver showed why. For a bare provider: custom with a base_url, the generic OPENAI_API_KEY fallback was only used when the host was openai.com / openai.azure.com. For any other host the key was silently dropped and replaced by a "no-key-required" placeholder. This looks like a deliberate guard against leaking a generic key to arbitrary endpoints — sensible, but silent.
Fix: register a named custom provider with an explicit key_env:
model:
default: <model-name-or-path>
provider: "custom:home-llm"
api_mode: chat_completions
providers:
"custom:home-llm":
base_url: http://<tailscale-ip>:8080/v1
key_env: OPENAI_API_KEY # name of the env var that holds the token
default_model: <model-name-or-path>
request_timeout_seconds: 120 # see "Unresolved" below
fallback_model:
provider: openrouter
model: openrouter/free
Named providers resolve the key through the explicit key_env lookup and skip the hostname gate. I used OPENAI_API_KEY as the variable name; the code suggests any name works, but I did not test other names.
Note the model name: llama.cpp reports the model's file path as its ID in /v1/models, so that is what you put in default.
4. Step 3 — The fallback
fallback_model takes a single provider/model (a list is also accepted for a chain). When the primary exhausts its retries on a connection or rate-limit error, the agent switches over automatically. I observed it working:
Max retries (3) exhausted — trying fallback...
Primary model failed — switching to fallback ...
Choosing the fallback model mattered:
- A specific model that was retired (
HTTP 404: No endpoints found) → total failure. - A specific free model that was busy (
HTTP 429) → total failure. -
openrouter/free— OpenRouter's router that picks from currently available free models and filters for features your request needs → far more resilient.
Caveat: free-tier rate limits are account-wide, so openrouter/free reduces, but does not eliminate, 429s. If the free fallback also fails, the request errors out after its retries (it does not wait forever); a scheduled job simply tries again on its next run.
5. Pitfall checklist
| Symptom | Cause | Fix |
|---|---|---|
| Timeouts to the home server | Tailscale missing on one end | Install and join on both machines |
401 with a correct key |
Hostname gate on generic env key | Named provider + key_env
|
.env change ignored |
docker restart does not reload env; compose had no env_file
|
Add env_file: .env, then docker compose up -d --force-recreate
|
Key looks like it ends in \r
|
docker exec -it pseudo-TTY adds it to output |
Re-check without -t; the value was fine |
systemd flag has no effect |
Missing trailing \ in ExecStart=
|
Fix continuation lines |
| Every request times out with long prompts | Draft-model / speculative decoding overhead and small context | I removed the draft model and raised -c to 65536 |
6. Step 4 — Don't wait minutes when the server is powered off
When the home machine is powered off, nothing answers the TCP SYN, so there is no quick "connection refused". Each attempt waited roughly 30 seconds, and with retries plus an extra primary retry round, switching took about 3 minutes. Painful for every message sent while the box is off.
(request_timeout_seconds did not seem to change this. See "Unresolved".)
A fixed-time schedule is fragile: boot takes a while before the model is ready, and shutdown (mine is triggered by a power-consumption watchdog) is not at a precise time. So instead of trusting the clock, health-check the server and let reality drive the switch.
The agent CLI can change config at runtime — no container recreation:
hermes config set model.provider "custom:home-llm"
hermes config set model.default "<model-name-or-path>"
Both keys must move together; changing only the provider leaves a local file path as the model name, which the cloud provider rejects.
Watchdog (run from cron every 3 minutes):
#!/bin/bash
# home-llm-watchdog.sh
set -u
source /etc/home-llm-watchdog.env # chmod 600; defines HOME_LLM_URL, HOME_LLM_KEY, LOCAL_MODEL
STATE_FILE=/var/lib/home-llm-watchdog.state
LOG_FILE=/var/log/home-llm-watchdog.log
CURRENT=dead
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 3 \
-H "Authorization: Bearer ${HOME_LLM_KEY}" "${HOME_LLM_URL}/models" 2>/dev/null)
[ "$code" = "200" ] && CURRENT=alive
PREVIOUS=$(cat "$STATE_FILE" 2>/dev/null || echo unknown)
if [ "$CURRENT" != "$PREVIOUS" ]; then
if [ "$CURRENT" = alive ]; then
docker exec hermes-agent hermes config set model.provider "custom:home-llm" >>"$LOG_FILE" 2>&1
docker exec hermes-agent hermes config set model.default "$LOCAL_MODEL" >>"$LOG_FILE" 2>&1
else
docker exec hermes-agent hermes config set model.provider "openrouter" >>"$LOG_FILE" 2>&1
docker exec hermes-agent hermes config set model.default "openrouter/free" >>"$LOG_FILE" 2>&1
fi
echo "[$(date '+%F %T')] $PREVIOUS -> $CURRENT" >>"$LOG_FILE"
echo "$CURRENT" >"$STATE_FILE"
fi
*/3 * * * * /usr/local/bin/home-llm-watchdog.sh
Design notes:
- State file → only acts when the state flips; no log noise or needless writes.
- Keep the built-in fallback too. If the server is supposed to be up but crashed, the watchdog still detects it, and the retry-then-fallback path remains a safety net in between checks.
- The secret lives in a
600file instead of the script. (The first version I ran had it inline; don't copy that.)
Verified end-to-end: the machine powered on by its timer, and within 3 minutes the agent switched back to the local model by itself.
7. Security checklist
- [ ] API key required on the local server
- [ ] Private network (Tailscale/WireGuard), installed on both ends
- [ ] Bind address / firewall narrower than
0.0.0.0on the open internet - [ ] Tailscale ACL limits which nodes can reach the port
- [ ] Secrets in
600files, never in scripts, chat logs or screenshots - [ ] Rotate any token that was exposed
- [ ] Prefer explicit
key_envper provider over a generic key that could be sent to the wrong host
8. Unresolved
-
request_timeout_secondsappeared to have no effect on the effective wait; I did not find the cause. Renaming theproviderskey to matchcustom:<name>did not change it. Newer versions may differ. - A harmless warning about missing endpoint credentials appeared from an auxiliary (non-chat) task; it did not affect normal conversations.
- Selecting which local model (e.g. Gemma vs. Qwen) is a separate layer from this up/down switch; I kept this to liveness only.
Summary
- Secure the local server (token + private network), on both ends.
- Register it as a named custom provider with
key_env. - Use
openrouter/freeas the fallback. - If the box is power-scheduled, add a health-check watchdog that flips config with
hermes config set.
Hermes Agent behavior described here was observed in August 2026. Check current official docs before relying on it.
自宅のローカルLLMと無料クラウドモデルを安全に切り替える
llama.cpp + Tailscale + OpenRouter + Hermes Agent で作る実践構成
Matis atelier
この情報の時点について
本記事の内容は 2026年8月時点 のものです。公式ドキュメントに該当の記述が見つからなかったため、Hermes Agent のソースコードを直接読んで挙動を確認しました。その後、公式情報は充実している可能性が高いです。まず最新の公式ドキュメントを確認してください。 本記事は「なぜそう動くのか」を補う読み物として使い、設定キー名などは変わっている可能性がある点にご注意ください。
文中のIP・キー・ホスト名・パスはすべてダミーです。
1. 目的
自宅でLLM(llama.cpp / Gemma 4 12B)を動かし、VPS上のエージェント(Hermes Agent)から使います。やりたいことは次の通りです。
| 状況 | 動作 |
|---|---|
| 自宅サーバーが起動している | 自宅のLLMを使う |
| 自宅サーバーが止まっている | 無料のクラウドモデル(OpenRouter)を使う |
| 無料モデルも失敗した | リトライし、それでもダメならエラーを返す |
自宅サーバーは電気代節約のため常時起動ではなく、無料クラウドモデルは混雑すると429で弾かれます。両方を組み合わせると、安く、かつ止まりにくくなります。
Telegram / cron
│
▼
┌──────────────┐ Tailscale(暗号化) ┌────────────────────┐
│ エージェント │ ──────────────────────► │ 自宅LLMサーバー │
│ (VPS) │ Bearerトークン必須 │ llama.cpp │
└──────┬───────┘ └────────────────────┘
│ 到達できない/失敗したとき
▼
OpenRouter(openrouter/free)
2. 手順1:まずローカルサーバーを守る
ローカルLLMのエンドポイントは、保護しなければ「誰でも使える計算資源」になってしまいます。
a) llama.cpp にAPIキーを要求させる
llama serve -m <model.gguf> --host <待ち受けアドレス> --port 8080 \
--api-key <長いランダムなトークン>
トークンは openssl rand -hex 32 で生成します。systemdで複数行の ExecStart= を書く場合は、継続行の行末に \ が必要です。抜けると、そのオプションが黙って無視されます。編集後は daemon-reload と再起動を行ってください。
b) 公開インターネットではなく、閉じたネットワークで繋ぐ
Tailscale(またはWireGuard)を使います。重要なのは 両端にクライアントが必要 という点です。私は「VPS側にもTailscaleが入っている」と思い込んでいて、実際は未インストールでした。そのせいで接続がずっとタイムアウトしていました。両方のマシンで tailscale status を確認しましょう。
c) 必要以上に広く待ち受けない
--host 0.0.0.0 は全インターフェースで待ち受けます。APIキーは最後の砦として有効ですが、できればTailscaleのアドレスに限定するか、ファイアウォールで8080番をTailscaleインターフェースだけに絞ってください。TailscaleのACLで、到達できるノードも制限できます。
d) 秘密情報をチャットログ・チケット・スクリーンショットに残さない。 もし公開の場に出てしまったら、トークンを再発行してください。
3. 手順2:エージェントにサーバーを登録する(数時間ハマったポイント)
最初に書いた、ありがちな設定はこうです。
model:
provider: custom
base_url: http://<tailscale-ip>:8080/v1
これに加えて環境変数 OPENAI_API_KEY を設定しました。結果は 401 Invalid API Key。ところが、同じコンテナの中から同じキーで curl すると 200 が返ります。
認証情報を解決するコードを読んで理由が分かりました。provider: custom と base_url だけを書いた場合、汎用の OPENAI_API_KEY は ホストが openai.com / openai.azure.com のときにしか使われません。それ以外のホストでは、キーが黙って捨てられ、"no-key-required" というプレースホルダーに置き換わります。これは「汎用キーが無関係な接続先に漏れないようにする」ための意図的なガードだと思われます。理屈は妥当ですが、何も警告が出ない点が厄介です。
対処:key_env を明示した「名前付き」カスタムプロバイダーとして登録します。
model:
default: <モデル名またはパス>
provider: "custom:home-llm"
api_mode: chat_completions
providers:
"custom:home-llm":
base_url: http://<tailscale-ip>:8080/v1
key_env: OPENAI_API_KEY # トークンを入れた環境変数の「名前」
default_model: <モデル名またはパス>
request_timeout_seconds: 120 # 後述「未解決」を参照
fallback_model:
provider: openrouter
model: openrouter/free
名前付きプロバイダーは key_env の明示的な参照でキーを解決するため、ホスト名によるガードを通りません。環境変数名は OPENAI_API_KEY を使いましたが、コード上は任意の名前で動きそうです(他の名前は未検証です)。
モデル名にも注意してください。llama.cpp は /v1/models でモデルの ファイルパスをそのままIDとして返す ので、default にはそれを書きます。
4. 手順3:フォールバックの設定
fallback_model には1組のプロバイダー/モデルを書きます(リスト形式でチェーンにもできます)。メインがリトライを使い切って、接続エラーやレート制限になると、自動で切り替わります。実際にログで確認できました。
Max retries (3) exhausted — trying fallback...
Primary model failed — switching to fallback ...
フォールバック先の選び方で、結果が大きく変わりました。
- 提供終了したモデルを指定 →
HTTP 404: No endpoints foundで全滅 - 特定の無料モデルを指定 → 混雑して
HTTP 429で全滅 -
openrouter/freeを指定 → OpenRouterのルーターが、その時使える無料モデルから、リクエストに必要な機能(画像入力やツール呼び出しなど)を満たすものを選ぶ。圧倒的に安定
注意点として、無料枠のレート制限はアカウント単位なので、openrouter/free でも429が完全になくなるわけではありません。無料フォールバックも失敗した場合は、リトライ後にエラーになります(永遠に待つわけではありません)。定期ジョブなら、次回の実行で再挑戦されます。
5. ハマりどころ一覧
| 症状 | 原因 | 対処 |
|---|---|---|
| 自宅サーバーへの接続がタイムアウトする | 片方にTailscaleが未インストール | 両方に入れてネットワークに参加させる |
キーが正しいのに 401
|
汎用環境変数キーのホスト名ガード | 名前付きプロバイダー + key_env
|
.env の変更が反映されない |
docker restart は環境変数を再読込しない/composeに env_file が無い |
env_file: .env を追加し、docker compose up -d --force-recreate
|
キーの末尾に \r が付いて見える |
docker exec -it の疑似TTYが出力に付けていた |
-t を外して再確認。値自体は正常だった |
| systemdのオプションが効かない |
ExecStart= の継続行の \ 漏れ |
継続行を直す |
| 長いプロンプトで毎回タイムアウト | ドラフトモデル(投機的デコード)の負荷、コンテキスト不足 | ドラフトモデルを外し、-c を65536に増やした |
6. 手順4:電源が切れている間、何分も待たされないようにする
自宅マシンの 電源が落ちている と、TCPのSYNに誰も応答しないため、「接続拒否」がすぐに返ってきません。1回の試行で約30秒待たされ、リトライや追加のリトライラウンドも重なって、切り替わるまで約3分 かかっていました。電源が落ちている間は、メッセージを送るたびにこれが発生します。
(request_timeout_seconds はこの待ち時間に効いていないようでした。「未解決」を参照。)
時刻で固定的に切り替える方式は脆いです。起動後、モデルが使えるようになるまで時間がかかりますし、シャットダウンも(私の環境では消費電力監視で)ぴったりの時刻に行われません。そこで、時計を信用せず、サーバーの生死を実際に確認して、その結果で切り替えます。
エージェントのCLIには、実行中に設定を書き換えるコマンドがあり、コンテナの再作成は不要でした。
hermes config set model.provider "custom:home-llm"
hermes config set model.default "<モデル名またはパス>"
2つのキーは 必ずセットで 変えます。プロバイダーだけ変えると、ローカルのファイルパスがモデル名として残り、クラウド側に拒否されます。
ウォッチドッグ(cronで3分おきに実行):
#!/bin/bash
# home-llm-watchdog.sh
set -u
source /etc/home-llm-watchdog.env # chmod 600。HOME_LLM_URL, HOME_LLM_KEY, LOCAL_MODEL を定義
STATE_FILE=/var/lib/home-llm-watchdog.state
LOG_FILE=/var/log/home-llm-watchdog.log
CURRENT=dead
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 3 \
-H "Authorization: Bearer ${HOME_LLM_KEY}" "${HOME_LLM_URL}/models" 2>/dev/null)
[ "$code" = "200" ] && CURRENT=alive
PREVIOUS=$(cat "$STATE_FILE" 2>/dev/null || echo unknown)
if [ "$CURRENT" != "$PREVIOUS" ]; then
if [ "$CURRENT" = alive ]; then
docker exec hermes-agent hermes config set model.provider "custom:home-llm" >>"$LOG_FILE" 2>&1
docker exec hermes-agent hermes config set model.default "$LOCAL_MODEL" >>"$LOG_FILE" 2>&1
else
docker exec hermes-agent hermes config set model.provider "openrouter" >>"$LOG_FILE" 2>&1
docker exec hermes-agent hermes config set model.default "openrouter/free" >>"$LOG_FILE" 2>&1
fi
echo "[$(date '+%F %T')] $PREVIOUS -> $CURRENT" >>"$LOG_FILE"
echo "$CURRENT" >"$STATE_FILE"
fi
*/3 * * * * /usr/local/bin/home-llm-watchdog.sh
設計のポイント:
- 状態ファイルで、状態が変わったときだけ動作します。無駄な書き込みやログの増加を避けられます。
- 標準のフォールバックも残す。 「起動しているはずの時間帯に落ちた」場合も、ウォッチドッグが検知しますし、検知までの間は従来のリトライ→フォールバックが安全網になります。
- 秘密情報はスクリプトに直書きせず、
600のファイルに置きます。(私が最初に実行したスクリプトは直書きでした。真似しないでください。)
実機で確認できました。電源タイマーでマシンが起動し、3分以内にエージェントが自動でローカルモデルへ戻りました。
7. セキュリティチェックリスト
- [ ] ローカルサーバーにAPIキーを要求させている
- [ ] 閉じたネットワーク(Tailscale/WireGuard)を 両端 に入れている
- [ ] 待ち受けを
0.0.0.0のままにせず、バインドアドレスかファイアウォールで絞っている - [ ] TailscaleのACLで、到達できるノードを制限している
- [ ] 秘密情報は
600のファイルに置き、スクリプト・チャットログ・スクショに載せない - [ ] 露出してしまったトークンは再発行する
- [ ] 誤った接続先に送られうる汎用キーより、プロバイダーごとの明示的な
key_envを使う
8. 未解決の点
-
request_timeout_secondsが実際の待ち時間に効いていないように見えましたが、原因は特定できていません。providersのキー名をcustom:<name>に合わせても変化はありませんでした。新しいバージョンでは挙動が違う可能性があります。 - 補助タスク(チャット以外の処理)で「エンドポイントの認証情報が見つからない」という警告が出ましたが、通常の会話には影響しませんでした。
- どのローカルモデル(GemmaかQwenか)を使うかは、今回の生死切り替えとは別のレイヤーです。今回は生死判定だけに絞りました。
まとめ
- ローカルサーバーを守る(トークン + 閉じたネットワーク)。しかも 両端 に。
-
名前付き カスタムプロバイダーとして
key_env付きで登録する。 - フォールバックには
openrouter/freeを使う。 - 電源スケジュールがあるなら、生死判定のウォッチドッグで
hermes config setを使って切り替える。
本記事のHermes Agentの挙動は2026年8月時点で確認したものです。利用の際は最新の公式ドキュメントを確認してください。
Top comments (0)