/{mode}/api/{tags,chat,generate,version,show,ps} beside the OpenAI surface.
forge path is a raw proxy (forge is Ollama); the cloud fallback is translated
both ways — NDJSON frames byte-compatible with Ollama's, tool calls round-trip
with synthesised ids, format mapped, think→reasoning_effort (forced to none
with tools: OpenAI rejects the combination on gpt-5.4-mini). Tags never wait
on a model load (HA's list() has a 5 s timeout). local-strict still 503s in
Ollama's error shape; the OpenAI dialect is untouched.
Home Assistant (Lounge, 2026.9.2) configured through its REST config flow and
proven with a real conversation. HA's VLAN cannot reach the k8s ingress, so
it uses forgeway.dmz.lounge.falkvinge.net through the entrance HAProxy
(RFC1918-fenced vhost); the .services. alias needs a pfSense rule from Rick.
22/22 in-cluster checks on both sites. scripts/ha_setup_ollama.py is
idempotent and ends with a real answer; local-smoke-ollama.sh uses the exact
client HA pins.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
140 lines
6.3 KiB
Python
140 lines
6.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Configure Home Assistant's Ollama integration against forgeway and PROVE it
|
|
with a real conversation, entirely through HA's own REST API.
|
|
|
|
ha_setup_ollama.py <ha_base_url> <forgeway_url> [--name NAME] [--assist]
|
|
|
|
The long-lived token is read from `pass hassio/lounge-token` inside this process
|
|
and only ever travels as an Authorization header. Idempotent: an existing entry
|
|
for the same URL, and an existing conversation subentry of the same name, are
|
|
reused rather than duplicated.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
|
|
class HA:
|
|
def __init__(self, base: str):
|
|
self.base = base.rstrip("/")
|
|
self.token = subprocess.run(["pass", "hassio/lounge-token"], capture_output=True, text=True, check=True).stdout.strip()
|
|
|
|
def call(self, method: str, path: str, body: dict | None = None) -> tuple[int, dict | list | str]:
|
|
req = urllib.request.Request(
|
|
f"{self.base}{path}",
|
|
data=json.dumps(body).encode() if body is not None else None,
|
|
headers={"Authorization": f"Bearer {self.token}", "Content-Type": "application/json"},
|
|
method=method,
|
|
)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=120) as r:
|
|
raw = r.read().decode()
|
|
try:
|
|
return r.status, json.loads(raw)
|
|
except ValueError:
|
|
return r.status, raw
|
|
except urllib.error.HTTPError as e:
|
|
raw = e.read().decode("utf-8", "replace")
|
|
try:
|
|
return e.code, json.loads(raw)
|
|
except ValueError:
|
|
return e.code, raw
|
|
|
|
|
|
def main() -> int:
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("ha_base")
|
|
ap.add_argument("forgeway_url")
|
|
ap.add_argument("--name", default="forgeway optimistic")
|
|
ap.add_argument("--assist", action="store_true", help="also grant the Assist API (device control)")
|
|
ap.add_argument("--question", default="In one short sentence, what is Home Assistant?")
|
|
args = ap.parse_args()
|
|
ha = HA(args.ha_base)
|
|
|
|
# ---- 1. parent entry: the server URL ---------------------------------
|
|
st, entries = ha.call("GET", "/api/config/config_entries/entry")
|
|
existing = [e for e in entries if e["domain"] == "ollama" and e.get("title") == args.forgeway_url]
|
|
if existing:
|
|
entry = existing[0]
|
|
print(f"[entry] reusing existing Ollama entry {entry['entry_id'][:8]} state={entry['state']}")
|
|
else:
|
|
st, flow = ha.call("POST", "/api/config/config_entries/flow", {"handler": "ollama"})
|
|
if st != 200 or flow.get("type") != "form":
|
|
print(f"[entry] could not start config flow: {st} {flow}")
|
|
return 1
|
|
st, res = ha.call("POST", f"/api/config/config_entries/flow/{flow['flow_id']}", {"url": args.forgeway_url})
|
|
if res.get("type") != "create_entry":
|
|
# HA validated the URL by calling /api/tags with a 5 s timeout; errors land here
|
|
print(f"[entry] config flow did not create an entry: {st} {json.dumps(res)[:400]}")
|
|
return 1
|
|
entry = res["result"]
|
|
print(f"[entry] created Ollama entry {entry['entry_id'][:8]} for {args.forgeway_url}")
|
|
|
|
# ---- 2. conversation subentry: model + options -----------------------
|
|
entry_id = entry["entry_id"]
|
|
st, full = ha.call("GET", "/api/config/config_entries/entry")
|
|
entry = next(e for e in full if e["entry_id"] == entry_id)
|
|
subs = entry.get("subentries") or []
|
|
sub = next((s for s in subs if s.get("subentry_type") == "conversation" and s.get("title") == args.name), None)
|
|
if sub:
|
|
print(f"[subentry] reusing conversation subentry '{args.name}'")
|
|
else:
|
|
st, flow = ha.call("POST", "/api/config/config_entries/subentries/flow", {"handler": [entry_id, "conversation"]})
|
|
if st != 200 or flow.get("type") != "form":
|
|
print(f"[subentry] could not start subentry flow: {st} {json.dumps(flow)[:300]}")
|
|
return 1
|
|
models = [o["value"] for f in flow.get("data_schema", []) if f.get("name") == "model"
|
|
for o in (f.get("selector", {}).get("select", {}).get("options") or []) if isinstance(o, dict)]
|
|
print(f"[subentry] HA listed models from forgeway: {[m for m in models if 'gpt-oss' in m] or models[:3]}")
|
|
data = {
|
|
"name": args.name,
|
|
"model": "gpt-oss:120b",
|
|
"num_ctx": 8192,
|
|
"max_history": 20,
|
|
"keep_alive": -1,
|
|
"think": False,
|
|
}
|
|
if args.assist:
|
|
data["llm_hass_api"] = ["assist"]
|
|
st, res = ha.call("POST", f"/api/config/config_entries/subentries/flow/{flow['flow_id']}", data)
|
|
if res.get("type") != "create_entry":
|
|
print(f"[subentry] flow did not create an entry: {st} {json.dumps(res)[:400]}")
|
|
return 1
|
|
print(f"[subentry] created conversation subentry '{args.name}' (model gpt-oss:120b, think=False, assist={args.assist})")
|
|
|
|
# ---- 3. find the conversation entity ---------------------------------
|
|
entity_id = None
|
|
for _ in range(30):
|
|
st, states = ha.call("GET", "/api/states")
|
|
for s in states:
|
|
if s["entity_id"].startswith("conversation.") and s["attributes"].get("friendly_name") == args.name:
|
|
entity_id = s["entity_id"]
|
|
if entity_id:
|
|
break
|
|
time.sleep(2)
|
|
if not entity_id:
|
|
print("[entity] conversation entity did not appear")
|
|
return 1
|
|
print(f"[entity] {entity_id}")
|
|
|
|
# ---- 4. PROVE: a real conversation through HA ------------------------
|
|
started = time.perf_counter()
|
|
st, res = ha.call("POST", "/api/conversation/process", {"text": args.question, "agent_id": entity_id, "language": "en"})
|
|
took = time.perf_counter() - started
|
|
speech = (((res.get("response") or {}).get("speech") or {}).get("plain") or {}).get("speech") if isinstance(res, dict) else None
|
|
rtype = (res.get("response") or {}).get("response_type") if isinstance(res, dict) else None
|
|
print(f"[conversation] HTTP {st} response_type={rtype} took={took:.1f}s")
|
|
print(f"[conversation] Q: {args.question}")
|
|
print(f"[conversation] A: {speech!r}")
|
|
return 0 if st == 200 and speech and rtype != "error" else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|