0.2.1: native Ollama dialect on both modes; Home Assistant proven end-to-end

/{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>
This commit is contained in:
Dolon (Agent)
2026-09-18 18:39:31 +00:00
co-authored by Claude Fable 5.1
parent 1bec7c784c
commit c37e54c5c2
10 changed files with 1109 additions and 22 deletions
+108 -8
View File
@@ -1,7 +1,8 @@
# forgeway
An OpenAI-compatible LLM router in front of forge's Ollama `gpt-oss:120b`.
One instance runs **per cluster**, not one central service.
An LLM router in front of forge's Ollama `gpt-oss:120b`, speaking **both** the OpenAI
API and Ollama's native API on the same two endpoints. One instance runs **per
cluster**, not one central service.
> **Names (confirmed by Rick, 2026-09-18).** Explicit per-site names
> `forgeway.lounge.falkvinge.net` and `forgeway.serenity.falkvinge.net` (Chalet later:
@@ -17,7 +18,15 @@ One instance runs **per cluster**, not one central service.
| `/local-optimistic/v1` | serves from forge | falls back to OpenAI `gpt-5.4-mini` |
| `/local-strict/v1` | serves from forge | clean HTTP **503**, no fallback, by design |
Both expose `/v1/chat/completions` (including `stream: true`) and `/v1/models`.
Each endpoint speaks two dialects:
| Dialect | Paths | Typical caller |
|---|---|---|
| OpenAI | `/{endpoint}/v1/chat/completions`, `/{endpoint}/v1/models` | scripts, the OpenAI SDK, OpenClaw |
| Ollama (native) | `/{endpoint}/api/chat`, `/api/generate`, `/api/tags`, `/api/version`, `/api/show`, `/api/ps` | Home Assistant's Ollama integration, any Ollama client |
Streaming works in both: SSE for the OpenAI dialect, newline-delimited JSON for the
Ollama one (where `stream` defaults to **true**, as in Ollama itself).
Where they live:
@@ -104,6 +113,95 @@ forgeway-strict/gpt-oss-120b # forge or an error
forgeway-optimistic/gpt-oss-120b # forge, else gpt-5.4-mini
```
## Home Assistant
HA's core *OpenAI Conversation* integration only talks to the official OpenAI endpoint,
so it cannot use forgeway. HA's core **Ollama** integration can: it takes an arbitrary
server URL, and its client keeps the URL path, so an endpoint prefix is a valid server.
**Lounge HA — configured and proven 2026-09-18.** Integration entry
`https://forgeway.dmz.lounge.falkvinge.net/local-optimistic`, conversation agent
**`conversation.forgeway_optimistic`** (model `gpt-oss:120b`, think off, no device
control). A real question through HA's own conversation API came back from forge:
*"Home Assistant is an open-source platform for local home automation and smart-device
control."*
Why that URL and not the `.services.` alias: HA lives on the sandbox VLAN
(`192.168.120.0/22`), which **cannot reach the k8s ingress `172.19.10.11`** — the alias
resolves correctly there and then fails to connect. What that VLAN *can* reach is the
entrance HAProxy, whose certificate covers `*.dmz.lounge.falkvinge.net` and which already
has firewall clearance into the `172.19.10.80-98:80` band. So:
```
forgeway.dmz.lounge.falkvinge.net → entrance HAProxy 172.20.0.101 → 172.19.10.90:80 (HA, and any client HAProxy reaches)
forgeway.services.falkvinge.net → ingress-nginx 172.19.10.11 → forgeway Service (DMZ-side clients, local-first alias)
forgeway.lounge.falkvinge.net → ingress-nginx 172.19.10.11 (explicit per-site name, http)
```
The entrance is a public edge and the router has no authentication, so the HAProxy vhost
is **fenced to RFC1918 sources** (`http-request deny` for anything else); the router's
own raw Service IP stays unreachable from outside as before. If you would rather HA use
the `.services.` alias, the one-line pfSense change is: pass `192.168.120.12` (or the
sandbox net) → `172.19.10.11` TCP 443. Then re-run `scripts/ha_setup_ollama.py` with the
alias URL.
**What HA sends and how it is handled.** `list()` → `/api/tags` with a 5 s timeout, so
tags never wait on a model load (a cold `gpt-oss:120b` takes ~25–30 s); the list is
exactly one model, the local one. `chat(stream=True)` with `keep_alive: -1`,
`options: {num_ctx: 8192}`, `think: false`, and `tools` when the Assist API is enabled —
all passed to forge untouched. HA reads `message.content`, `message.thinking`,
`message.tool_calls`, `done`, `done_reason`; gpt-oss returns `content` and `thinking`
separately regardless of `think`, so a normal answer is never empty. HA shows the
thinking as a collapsible block.
**To make it the default assistant / let it control the house** (your call, in the HA
UI): *Settings → Voice assistants → Assist → Conversation agent → "forgeway optimistic"*;
and on the integration's conversation subentry, tick *Control Home Assistant* to grant
the Assist API (tools). Both were left off deliberately.
Re-run the setup at any time — it is idempotent and ends with a real conversation:
```bash
python3 scripts/ha_setup_ollama.py http://192.168.120.12:8123 \
https://forgeway.dmz.lounge.falkvinge.net/local-optimistic --name "forgeway optimistic" [--assist]
```
## The Ollama dialect, and the cloud fallback through it
forge *is* Ollama, so on the forge path the router is a raw proxy: the response —
including every streamed NDJSON frame — is forge's own, with only the `model` pinned.
Everything below is about the **cloud fallback** (`local-optimistic` only; `local-strict`
returns Ollama's error shape, `{"error": "..."}`, with status 503):
- The Ollama request is translated to an OpenAI chat completion and the answer is
translated back into Ollama's shape, non-streamed or as NDJSON frames byte-compatible
with Ollama's: `model`, `created_at` (nanosecond RFC 3339), `message.role/content`,
`done`, `done_reason` (`stop` / `length`), and the `*_duration` / `*_count` stats
(token counts from usage; durations that OpenAI does not report are 0).
- **Tool calls** round-trip. Ollama messages carry no tool-call ids and OpenAI insists on
them, so ids are synthesised in order and handed to the following `tool` messages in
order; OpenAI's JSON-string arguments become Ollama's objects. On the way out, OpenAI
streams tool calls as fragments; they are reassembled and emitted as one frame.
- `format: "json"` → `response_format: json_object`; a schema → `json_schema`.
- **`think` → `reasoning_effort`**: `false` → `low`, `true` → `medium`, a level → itself.
With **tools present it is forced to `none`**: gpt-5.4-mini rejects any other value
together with function tools on `/v1/chat/completions`, and HA's Assist API always
sends tools. The cloud model's reasoning text is not exposed by that API, so cloud
answers carry no `thinking`.
- `options.num_predict` → `max_completion_tokens`; `num_ctx` and `keep_alive` are
Ollama-only and dropped.
- `/api/generate` is served the same way (`prompt`/`system`/`images` become messages).
`/api/pull`, `/api/push`, `/api/create`, `/api/delete`, `/api/embed` return 400: this
endpoint serves exactly one model and manages none.
**The reasoning trap, decided.** A thinking model with a tiny output budget spends it all
thinking and returns empty `content` — that is what bit the OpenAI dialect at
`max_tokens: 10`. The router does not silently rewrite budgets; instead it makes the
failure visible: a non-streamed answer with thinking but no content gets the header
`x-forgeway-warning: content-starved-by-reasoning` and a log line. HA never sets a
budget, so it never hits this.
## DNS: how the alias finds the local instance
Every `.services.` name in the estate is a CNAME chain ending at a site's ingress-nginx,
@@ -111,9 +209,10 @@ and the authoritative `services.falkvinge.net` zone lives on the Lounge Techniti
at the Lounge nothing special is needed:
```
forgeway.services.falkvinge.net → forgeway.dmz.lounge.falkvinge.net → ingress.dmz.lounge.falkvinge.net → 172.19.10.11
forgeway.lounge.falkvinge.net → forgeway.dmz.lounge.falkvinge.net → … → 172.19.10.11
forgeway.serenity.falkvinge.net → forgeway.dmz.serenity.falkvinge.net → ingress.dmz.serenity.falkvinge.net → 172.24.10.11
forgeway.services.falkvinge.net → ingress.dmz.lounge.falkvinge.net → 172.19.10.11
forgeway.lounge.falkvinge.net → ingress.dmz.lounge.falkvinge.net → 172.19.10.11
forgeway.dmz.lounge.falkvinge.net → entrance.dmz.falkvinge.net → 172.20.0.101 (HAProxy path, see Home Assistant)
forgeway.serenity.falkvinge.net → forgeway.dmz.serenity.falkvinge.net → ingress.dmz.serenity.falkvinge.net → 172.24.10.11
```
Serenity's Pi-holes forward everything under `falkvinge.net` (except `serenity.`) to the
@@ -267,11 +366,12 @@ Then bump the image tag in each cluster repo and push — ArgoCD syncs:
## Verifying
```bash
./scripts/local-smoke.sh # against a real forge, from this VM
./scripts/local-smoke.sh # OpenAI dialect, against a real forge
./scripts/local-smoke-ollama.sh # Ollama dialect, incl. the exact client HA pins
./scripts/verify-cluster.sh ~/.kube/rocinante-admin.yaml lounge
./scripts/verify-cluster.sh ~/.kube/nidavellir.yaml serenity
```
`verify-cluster.sh` runs 13 checks from inside the cluster. It produces the
`verify-cluster.sh` runs 22 checks from inside the cluster (13 OpenAI, 9 Ollama). It produces the
"forge unavailable" case with a throwaway Deployment pointed at a dead upstream —
**it never stops Ollama on forge.**
+97
View File
@@ -259,3 +259,100 @@ the primary's last-change dates. Corrected here and in memory.
| Technitium records | live on `172.19.1.202` and `172.24.1.202` (zone data is not in git by design) |
| LXC Pi-hole override | live on `172.24.1.201` via API (`dns.hosts` + `misc.dnsmasq_lines`) |
| Technitium helper | `scripts/technitium.py` (zones / records / add / resync / logtail) |
---
# Addendum 2, 2026-09-18 evening — native Ollama dialect + Home Assistant
**Done and proven from Home Assistant itself.** forgeway 0.2.1 serves Ollama's native API
on both modes beside the OpenAI one. The Lounge HA (2026.9.2) now has an Ollama
integration entry pointed at forgeway, a conversation agent
`conversation.forgeway_optimistic` on `gpt-oss:120b`, and a real question asked through
HA's own conversation API was answered by forge:
> Q: In one short sentence, what is Home Assistant?
> A: *Home Assistant is an open-source platform for local home automation and smart-device control.*
(64 s including a cold model load; the pod logs show no cloud fallback in the window.)
| | Lounge | Serenity |
|---|---|---|
| Image | `0.2.1` | `0.2.1` |
| Acceptance | **22/22** (13 OpenAI + 9 Ollama) | **22/22** |
| Ollama strict-503 / optimistic cloud fallback / cloud NDJSON stream | 503 / 200 `backend=cloud` / 3 frames, `done:true` | same |
## What HA actually calls — from its source, not guessed
HA 2026.9.2 pins `ollama==0.6.2`. The integration calls **`list()` → `GET /api/tags`**
(setup, config-flow validation, model picker; **5 s timeout**) and
**`chat(stream=True)` → `POST /api/chat`** with `keep_alive: -1`, `options: {num_ctx: 8192}`,
`think: false` (default) and `tools` when the Assist API is on. It calls `pull()` only
for a model absent from tags, which cannot happen (tags list exactly `gpt-oss:120b`). It
reads `message.content`, `message.thinking`, `message.tool_calls`, `done`,
`done_reason`. The client keeps the URL path, so `https://<host>/local-optimistic` is a
valid server URL — verified with the pinned client against the live service.
## The blocker that changed the URL: HA cannot reach the ingress
Rick asked for `https://forgeway.services.falkvinge.net/local-optimistic` pasted into HA.
From HA's VLAN (`192.168.120.0/22`) the alias resolves correctly to `172.19.10.11` and
then **fails to connect** — that VLAN reaches nothing in `172.19.10.x` and not forge;
it does reach the entrance HAProxy and the internet. The magpie jump to pfSense is down
right now, so I could neither read the rule set nor add a rule.
What works today, with a valid certificate and existing firewall openings:
**`https://forgeway.dmz.lounge.falkvinge.net/local-optimistic`** → entrance HAProxy →
`172.19.10.90:80` (the band opened for exactly this). The entrance cert covers
`*.dmz.lounge.falkvinge.net`; it does **not** cover `*.lounge.falkvinge.net`, which
corrects an assumption from this morning. Changes made:
- `lounge-haproxy-config` (`08843be`, `27ce8e4`): vhost `forgeway.dmz.lounge.falkvinge.net`
→ backend `172.19.10.90:80`, `timeout server 600s`, and — because the entrance is a
public edge and the router has no auth — `http-request deny` for non-RFC1918 sources.
Deployed by the autopull. An intermediate commit (`596d68b`) failed `haproxy -c` (ACL
used before declared); the autopull rolled it back as designed and the edge never
stopped serving. Rick can confirm the applied revision in `/var/log/haproxy-autopull.log`.
- Lounge Technitium: `forgeway.services` and `forgeway.lounge` now CNAME straight to the
ingress; `forgeway.dmz.lounge` CNAMEs to `entrance.dmz.falkvinge.net`. The alias and
per-site name are unchanged in effect; only the `.dmz.lounge.` hop moved.
> **If you want HA on the `.services.` alias as originally asked:** pfSense, pass
> `192.168.120.12` (or the sandbox net) → `172.19.10.11` TCP 443. Then
> `scripts/ha_setup_ollama.py … https://forgeway.services.falkvinge.net/local-optimistic`.
> I could not verify the source fence from the public side; it relies on pfSense not
> rewriting inbound sources, which is the default.
## Design points in the dialect
- **forge path = raw proxy.** forge is Ollama; frames are forge's own, model pinned.
- **Cloud fallback translated both ways**, streaming as NDJSON with Ollama's compact
byte shape; tool calls round-trip with synthesised ids; `format` mapped; usage → counts.
- **`think` → `reasoning_effort`**, and **forced to `none` when tools are present**: the
smoke test caught OpenAI rejecting `reasoning_effort` with function tools on
gpt-5.4-mini — precisely the shape HA sends with the Assist API. Fixed before shipping.
- **Reasoning trap**: gpt-oss returns `content` and `thinking` separately whatever
`think` is, and HA sets no output budget, so answers are never empty. Where a caller
does starve content with a tiny `num_predict`, the router flags it
(`x-forgeway-warning: content-starved-by-reasoning`) rather than rewriting budgets.
- **Tags never block on forge** (2.5 s cap, 60 s cache, synthetic entry if unreachable) —
HA's 5 s list timeout would otherwise trip on every cold load.
- **OpenAI dialect untouched**: checks 1–13 identical to this morning.
## For Rick to do (only if wanted)
1. Make it the default assistant: *Settings → Voice assistants → Assist → Conversation
agent → "forgeway optimistic"*. Left as-is on purpose.
2. Let it control the house: on the Ollama integration's "forgeway optimistic" subentry,
tick *Control Home Assistant*. Left off on purpose — that hands device control to an
LLM.
3. Optional: the pfSense rule above, to use the alias instead of the entrance.
## Where (additions)
| | |
|---|---|
| Dialect | `app/ollama_api.py`; shared bits in `app/common.py` |
| HA setup + proof | `scripts/ha_setup_ollama.py` (idempotent; ends with a real conversation) |
| Local smoke | `scripts/local-smoke-ollama.sh` (uses `ollama==0.6.2`, the version HA pins) |
| Edge vhost | `lounge-haproxy-config` `27ce8e4` |
| Cluster repos | `lounge-cluster-config` `c2c2c3e`, `serenity-cluster-config` `f35dc0a` |
+29
View File
@@ -0,0 +1,29 @@
"""Bits shared by the OpenAI and the native-Ollama dialects."""
from __future__ import annotations
from .config import CONFIG
MODE_STRICT = "local-strict"
MODE_OPTIMISTIC = "local-optimistic"
MODES = (MODE_OPTIMISTIC, MODE_STRICT)
def base_headers(mode: str, backend: str, upstream: str | None) -> dict[str, str]:
headers = {
"x-forgeway-service": CONFIG.name,
"x-forgeway-site": CONFIG.site,
"x-forgeway-mode": mode,
"x-forgeway-backend": backend,
}
if upstream:
headers["x-forgeway-upstream"] = upstream
return headers
def strict_unavailable_message() -> str:
return (
f"the local model '{CONFIG.local_model}' is unavailable at this site "
f"({CONFIG.site}). {MODE_STRICT} does not fall back by design; "
f"handle this error or use /{MODE_OPTIMISTIC}."
)
+3
View File
@@ -80,6 +80,9 @@ class Config:
# --- proxying -------------------------------------------------------
request_timeout: float = field(default_factory=lambda: _env_float("FORGEWAY_REQUEST_TIMEOUT", 600.0))
connect_timeout: float = field(default_factory=lambda: _env_float("FORGEWAY_CONNECT_TIMEOUT", 5.0))
# Reported by /{mode}/api/version when forge has never answered (clients may
# gate features on it); replaced by forge's real version once seen.
ollama_version_fallback: str = field(default_factory=lambda: _env("FORGEWAY_OLLAMA_VERSION_FALLBACK", "0.34.0"))
port: int = field(default_factory=lambda: _env_int("FORGEWAY_PORT", 8080))
log_level: str = field(default_factory=lambda: _env("FORGEWAY_LOG_LEVEL", "INFO").upper())
+8 -14
View File
@@ -19,7 +19,9 @@ import httpx
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, StreamingResponse
from .common import MODE_OPTIMISTIC, MODE_STRICT, MODES, base_headers
from .config import CONFIG
from .ollama_api import router as ollama_router
from .upstream import ForgeLocator, UpstreamError
logging.basicConfig(
@@ -28,10 +30,6 @@ logging.basicConfig(
)
log = logging.getLogger("forgeway")
MODE_STRICT = "local-strict"
MODE_OPTIMISTIC = "local-optimistic"
MODES = (MODE_OPTIMISTIC, MODE_STRICT)
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.client = httpx.AsyncClient(
@@ -66,22 +64,14 @@ app = FastAPI(
redoc_url=None,
lifespan=lifespan,
)
app.include_router(ollama_router) # native Ollama dialect: /{mode}/api/...
# --------------------------------------------------------------------------
# helpers
# --------------------------------------------------------------------------
def _base_headers(mode: str, backend: str, upstream: str | None) -> dict[str, str]:
headers = {
"x-forgeway-service": CONFIG.name,
"x-forgeway-site": CONFIG.site,
"x-forgeway-mode": mode,
"x-forgeway-backend": backend,
}
if upstream:
headers["x-forgeway-upstream"] = upstream
return headers
_base_headers = base_headers # shared with the native-Ollama dialect
def _error(
@@ -258,6 +248,10 @@ async def root() -> JSONResponse:
f"/{MODE_STRICT}/v1": "forge or HTTP 503 — callers are expected to handle the error",
},
"health": "/healthz (real completion against forge; 200 up, 503 down)",
"dialects": {
"openai": "/{endpoint}/v1/chat/completions, /{endpoint}/v1/models",
"ollama": "/{endpoint}/api/chat, /api/generate, /api/tags, /api/version (paste /{endpoint} as an Ollama server URL)",
},
}
)
+553
View File
@@ -0,0 +1,553 @@
"""Native Ollama API dialect, served under the same two modes.
/{mode}/api/tags GET what this endpoint serves (never blocks on forge)
/{mode}/api/chat POST forge, else cloud (optimistic) / 503 (strict)
/{mode}/api/generate POST same routing, prompt-style
/{mode}/api/version GET
/{mode}/api/show POST pass-through to forge
/{mode}/api/ps GET pass-through to forge
Home Assistant's Ollama integration speaks exactly this: ``list()`` → tags with
a 5 s timeout, then ``chat(stream=True)``. Its client keeps the URL path, so
``https://<name>/local-optimistic`` is a valid "server URL".
Two things are non-obvious here:
* forge *is* Ollama, so the forge path is a raw proxy — the response, including
the streamed NDJSON frames, is forge's own. Only the cloud fallback needs
translation, in both directions, and that is where most of this file goes.
* Ollama's default for ``stream`` is **true**, the opposite of OpenAI's.
"""
from __future__ import annotations
import json
import logging
import time
from datetime import datetime, timezone
from typing import Any, AsyncIterator
import httpx
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse, Response, StreamingResponse
from .common import MODE_STRICT, MODES, base_headers, strict_unavailable_message
from .config import CONFIG
from .upstream import UpstreamError
log = logging.getLogger("forgeway.ollama")
router = APIRouter()
NDJSON = "application/x-ndjson"
QUICK_TIMEOUT = 2.5 # anything a client may call with a short timeout (HA: 5 s on tags)
STARVED_HEADER = "x-forgeway-warning"
# --------------------------------------------------------------------------
# small helpers
# --------------------------------------------------------------------------
def _now() -> str:
"""RFC 3339 with nanosecond precision, the way Ollama prints created_at."""
dt = datetime.now(timezone.utc)
return dt.strftime("%Y-%m-%dT%H:%M:%S.") + f"{dt.microsecond:06d}000Z"
def _ns(seconds: float) -> int:
return int(seconds * 1_000_000_000)
def _error(status: int, message: str, mode: str, backend: str = "none", upstream: str | None = None) -> JSONResponse:
"""Ollama's error shape: a bare {"error": "..."}; the python client raises ResponseError on it."""
return JSONResponse({"error": message}, status_code=status, headers=base_headers(mode, backend, upstream))
def _bad_mode(mode: str) -> JSONResponse | None:
if mode not in MODES:
return JSONResponse({"error": f"unknown endpoint '{mode}'. Use one of: {', '.join(MODES)}."}, status_code=404)
return None
def _done_reason(finish_reason: str | None) -> str:
return {"stop": "stop", "length": "length", "tool_calls": "stop", "content_filter": "stop"}.get(
finish_reason or "stop", "stop"
)
def _tool_call_to_ollama(index: int, call: dict[str, Any]) -> dict[str, Any]:
fn = call.get("function") or {}
args = fn.get("arguments")
if isinstance(args, str):
try:
args = json.loads(args) if args.strip() else {}
except ValueError:
args = {"_raw": args}
return {
"id": call.get("id") or f"call_fw{index}",
"function": {"index": index, "name": fn.get("name", ""), "arguments": args if isinstance(args, dict) else {}},
}
def _starved(message: dict[str, Any], done_reason: str | None) -> bool:
"""A thinking model spent its whole budget thinking and produced no answer."""
return (
not (message.get("content") or "").strip()
and not message.get("tool_calls")
and (bool(message.get("thinking")) or done_reason == "length")
)
# --------------------------------------------------------------------------
# request translation: Ollama chat → OpenAI chat completion
# --------------------------------------------------------------------------
def _messages_to_openai(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Ollama messages carry no tool-call ids; OpenAI insists on them. Synthesise
ids in order and hand them to the following tool-result messages in order."""
out: list[dict[str, Any]] = []
pending_ids: list[str] = []
counter = 0
for m in messages:
role = m.get("role") or "user"
content = m.get("content") or ""
if role == "assistant":
entry: dict[str, Any] = {"role": "assistant", "content": content or None}
calls = m.get("tool_calls") or []
if calls:
pending_ids = []
entry["tool_calls"] = []
for call in calls:
counter += 1
fn = call.get("function") or {}
cid = call.get("id") or f"call_fw{counter}"
entry["tool_calls"].append(
{
"id": cid,
"type": "function",
"function": {"name": fn.get("name", ""), "arguments": json.dumps(fn.get("arguments") or {})},
}
)
pending_ids.append(cid)
out.append(entry)
elif role == "tool":
cid = pending_ids.pop(0) if pending_ids else f"call_fw{counter or 1}"
out.append({"role": "tool", "tool_call_id": cid, "content": content})
elif role == "user" and m.get("images"):
parts: list[dict[str, Any]] = [{"type": "text", "text": content}]
for img in m["images"]:
if isinstance(img, str):
parts.append({"type": "image_url", "image_url": {"url": f"data:image/png;base64,{img}"}})
out.append({"role": "user", "content": parts})
else:
out.append({"role": role, "content": content})
return out
def _chat_to_openai(body: dict[str, Any], stream: bool) -> dict[str, Any]:
req: dict[str, Any] = {
"model": CONFIG.cloud_model,
"messages": _messages_to_openai(body.get("messages") or []),
"stream": stream,
}
if stream:
req["stream_options"] = {"include_usage": True}
if body.get("tools"):
req["tools"] = body["tools"] # Ollama's tool schema is already OpenAI's
fmt = body.get("format")
if fmt == "json":
req["response_format"] = {"type": "json_object"}
elif isinstance(fmt, dict) and fmt:
req["response_format"] = {"type": "json_schema", "json_schema": {"name": "response", "schema": fmt}}
# Ollama's `think` → OpenAI's reasoning_effort. HA sends False by default;
# "low" keeps the assistant snappy without switching reasoning off outright.
# With tools present it MUST be "none": gpt-5.4-mini rejects any other value
# alongside function tools on /v1/chat/completions (verified 2026-09-18),
# and HA's Assist API always sends tools.
think = body.get("think")
if req.get("tools"):
req["reasoning_effort"] = "none"
elif isinstance(think, bool):
req["reasoning_effort"] = "medium" if think else "low"
elif think in ("low", "medium", "high"):
req["reasoning_effort"] = think
opts = body.get("options") or {}
if isinstance(opts.get("num_predict"), int) and opts["num_predict"] > 0:
req["max_completion_tokens"] = opts["num_predict"]
for key in ("temperature", "top_p"):
if opts.get(key) is not None:
req[key] = opts[key]
return req
# --------------------------------------------------------------------------
# response translation: OpenAI → Ollama
# --------------------------------------------------------------------------
def _stats(usage: dict[str, Any] | None, started: float) -> dict[str, Any]:
usage = usage or {}
return {
"total_duration": _ns(time.perf_counter() - started),
"load_duration": 0,
"prompt_eval_count": int(usage.get("prompt_tokens") or 0),
"prompt_eval_duration": 0,
"eval_count": int(usage.get("completion_tokens") or 0),
"eval_duration": 0,
}
def _openai_to_ollama_chat(data: dict[str, Any], model: str, started: float) -> dict[str, Any]:
choice = (data.get("choices") or [{}])[0]
msg = choice.get("message") or {}
message: dict[str, Any] = {"role": "assistant", "content": msg.get("content") or ""}
if msg.get("tool_calls"):
message["tool_calls"] = [_tool_call_to_ollama(i, c) for i, c in enumerate(msg["tool_calls"])]
return {
"model": model,
"created_at": _now(),
"message": message,
"done": True,
"done_reason": _done_reason(choice.get("finish_reason")),
**_stats(data.get("usage"), started),
}
def _dumps(obj: Any) -> str:
"""Compact, the way Ollama's Go encoder prints — byte-shape parity for naive parsers."""
return json.dumps(obj, separators=(",", ":"), ensure_ascii=False)
def _chat_frame(model: str, message: dict[str, Any], done: bool = False, **extra: Any) -> bytes:
frame: dict[str, Any] = {"model": model, "created_at": _now(), "message": message, "done": done}
frame.update(extra)
return (_dumps(frame) + "\n").encode()
def _generate_frame(model: str, text: str, done: bool = False, **extra: Any) -> bytes:
frame: dict[str, Any] = {"model": model, "created_at": _now(), "response": text, "done": done}
frame.update(extra)
return (_dumps(frame) + "\n").encode()
async def _sse_to_ndjson(resp: httpx.Response, model: str, started: float, shape: str) -> AsyncIterator[bytes]:
"""OpenAI SSE deltas → Ollama NDJSON frames (chat or generate shape).
Tool calls arrive as fragments spread over many deltas; Ollama emits them
whole, so they are accumulated and flushed as one frame before `done`.
"""
usage: dict[str, Any] | None = None
finish: str | None = None
tool_acc: dict[int, dict[str, Any]] = {}
try:
async for raw in resp.aiter_lines():
line = raw.strip()
if not line.startswith("data:"):
continue
payload = line[5:].strip()
if payload == "[DONE]":
break
try:
evt = json.loads(payload)
except ValueError:
continue
if evt.get("usage"):
usage = evt["usage"]
for ch in evt.get("choices") or []:
delta = ch.get("delta") or {}
if delta.get("content"):
if shape == "chat":
yield _chat_frame(model, {"role": "assistant", "content": delta["content"]})
else:
yield _generate_frame(model, delta["content"])
for frag in delta.get("tool_calls") or []:
idx = int(frag.get("index") or 0)
acc = tool_acc.setdefault(idx, {"id": None, "name": "", "arguments": ""})
if frag.get("id"):
acc["id"] = frag["id"]
fn = frag.get("function") or {}
if fn.get("name"):
acc["name"] += fn["name"]
if fn.get("arguments"):
acc["arguments"] += fn["arguments"]
if ch.get("finish_reason"):
finish = ch["finish_reason"]
if tool_acc and shape == "chat":
calls = [
_tool_call_to_ollama(i, {"id": acc["id"], "function": {"name": acc["name"], "arguments": acc["arguments"]}})
for i, acc in sorted(tool_acc.items())
]
yield _chat_frame(model, {"role": "assistant", "content": "", "tool_calls": calls})
stats = _stats(usage, started)
if shape == "chat":
yield _chat_frame(model, {"role": "assistant", "content": ""}, done=True, done_reason=_done_reason(finish), **stats)
else:
yield _generate_frame(model, "", done=True, done_reason=_done_reason(finish), context=[], **stats)
except httpx.HTTPError as exc:
# Mid-stream failure: the client raises on an `error` frame.
yield (_dumps({"error": f"cloud stream failed: {type(exc).__name__}: {exc}"}) + "\n").encode()
finally:
await resp.aclose()
# --------------------------------------------------------------------------
# backends
# --------------------------------------------------------------------------
async def _forge_raw(
request: Request, upstream: str, path: str, payload: dict[str, Any], mode: str, stream: bool
) -> Response:
"""forge is Ollama: forward as-is (model pinned), return its bytes untouched."""
client: httpx.AsyncClient = request.app.state.client
url = f"{upstream}{path}"
if not stream:
try:
resp = await client.post(url, json=payload)
except httpx.HTTPError as exc:
raise UpstreamError(f"{type(exc).__name__}: {exc}") from exc
if resp.status_code >= 400:
raise UpstreamError(f"HTTP {resp.status_code}", resp.status_code, resp.text[:500])
headers = base_headers(mode, "forge", upstream)
try:
data = resp.json()
if path == "/api/chat" and _starved(data.get("message") or {}, data.get("done_reason")):
headers[STARVED_HEADER] = "content-starved-by-reasoning"
log.warning("forge answer had thinking but no content (done_reason=%s)", data.get("done_reason"))
except ValueError:
pass
return Response(resp.content, status_code=resp.status_code, media_type="application/json", headers=headers)
req = client.build_request("POST", url, json=payload)
try:
resp = await client.send(req, stream=True)
except httpx.HTTPError as exc:
raise UpstreamError(f"{type(exc).__name__}: {exc}") from exc
if resp.status_code >= 400:
detail = (await resp.aread())[:500].decode("utf-8", "replace")
await resp.aclose()
raise UpstreamError(f"HTTP {resp.status_code}", resp.status_code, detail)
async def body():
try:
async for chunk in resp.aiter_raw():
yield chunk
finally:
await resp.aclose()
return StreamingResponse(body(), media_type=NDJSON, headers=base_headers(mode, "forge", upstream))
async def _cloud(request: Request, body: dict[str, Any], mode: str, stream: bool, shape: str, model: str) -> Response:
client: httpx.AsyncClient = request.app.state.client
started = time.perf_counter()
payload = _chat_to_openai(body, stream)
url = f"{CONFIG.cloud_base_url}/chat/completions"
headers = {"content-type": "application/json", "authorization": f"Bearer {CONFIG.cloud_api_key}"}
if not stream:
try:
resp = await client.post(url, json=payload, headers=headers)
except httpx.HTTPError as exc:
raise UpstreamError(f"{type(exc).__name__}: {exc}") from exc
if resp.status_code >= 400:
raise UpstreamError(f"HTTP {resp.status_code}", resp.status_code, resp.text[:500])
data = _openai_to_ollama_chat(resp.json(), model, started)
out_headers = base_headers(mode, "cloud", CONFIG.cloud_base_url)
if shape == "generate":
msg = data.pop("message")
data["response"] = msg.get("content", "")
data["context"] = []
elif _starved(data["message"], data.get("done_reason")):
out_headers[STARVED_HEADER] = "content-starved-by-reasoning"
return Response(_dumps(data), media_type="application/json", headers=out_headers)
req = client.build_request("POST", url, json=payload, headers=headers)
try:
resp = await client.send(req, stream=True)
except httpx.HTTPError as exc:
raise UpstreamError(f"{type(exc).__name__}: {exc}") from exc
if resp.status_code >= 400:
detail = (await resp.aread())[:500].decode("utf-8", "replace")
await resp.aclose()
raise UpstreamError(f"HTTP {resp.status_code}", resp.status_code, detail)
return StreamingResponse(
_sse_to_ndjson(resp, model, started, shape),
media_type=NDJSON,
headers=base_headers(mode, "cloud", CONFIG.cloud_base_url),
)
async def _route(request: Request, mode: str, path: str, body: dict[str, Any], shape: str) -> Response:
"""forge if it answers a real completion; else 503 (strict) or cloud (optimistic)."""
stream = bool(body.get("stream", True)) # Ollama's default, unlike OpenAI's
model = body.get("model") or CONFIG.local_model
locator = request.app.state.locator
health = await locator.health()
if health.healthy and health.upstream:
payload = dict(body)
payload["model"] = CONFIG.local_model
try:
return await _forge_raw(request, health.upstream, path, payload, mode, stream)
except UpstreamError as exc:
locator.invalidate()
log.warning("forge %s failed on %s: %s", path, health.upstream, exc)
failure = str(exc)
else:
failure = health.reason
if mode == MODE_STRICT:
return _error(503, f"{strict_unavailable_message()} ({failure})", mode, upstream=health.upstream)
if not CONFIG.cloud_enabled:
return _error(503, f"forge is unavailable ({failure}) and no cloud fallback credential is configured", mode)
log.info("falling back to cloud %s for %s (%s)", CONFIG.cloud_model, path, failure)
if shape == "generate":
# generate → chat: prompt becomes the user turn, `system` the system turn
messages: list[dict[str, Any]] = []
if body.get("system"):
messages.append({"role": "system", "content": body["system"]})
user: dict[str, Any] = {"role": "user", "content": body.get("prompt") or ""}
if body.get("images"):
user["images"] = body["images"]
messages.append(user)
body = {**body, "messages": messages}
try:
return await _cloud(request, body, mode, stream, shape, model)
except UpstreamError as exc:
return _error(502, f"forge unavailable ({failure}) and the cloud fallback also failed: {exc} {exc.body or ''}".strip(), mode)
# --------------------------------------------------------------------------
# endpoints
# --------------------------------------------------------------------------
_tags_cache: dict[str, Any] = {"at": 0.0, "entry": None}
_version_cache: dict[str, Any] = {"value": None}
async def _forge_quick(request: Request, method: str, path: str, json_body: dict | None = None) -> dict | None:
"""Ask the last-known forge something cheap, never waiting on a model load."""
locator = request.app.state.locator
client: httpx.AsyncClient = request.app.state.client
base = locator.sticky or (CONFIG.upstreams[0] if CONFIG.upstreams else None)
if not base:
return None
try:
resp = await client.request(method, f"{base}{path}", json=json_body, timeout=QUICK_TIMEOUT)
return resp.json() if resp.status_code == 200 else None
except (httpx.HTTPError, ValueError):
return None
@router.get("/{mode}/api/tags")
async def api_tags(mode: str, request: Request):
"""What this endpoint serves — exactly one model, the local one, in both modes.
Cloud fallback is a behaviour of the endpoint, not a second model a client
could select: the request's `model` field is ignored either way. Fast on
purpose: HA's list() has a 5 s timeout and a cold model load takes ~25 s."""
invalid = _bad_mode(mode)
if invalid:
return invalid
now = time.time()
if _tags_cache["entry"] is None or now - _tags_cache["at"] > 60:
data = await _forge_quick(request, "GET", "/api/tags")
entry = None
for m in (data or {}).get("models", []):
if m.get("model") == CONFIG.local_model or m.get("name") == CONFIG.local_model:
entry = m
break
if entry:
_tags_cache.update(at=now, entry=entry)
entry = _tags_cache["entry"] or {
"name": CONFIG.local_model,
"model": CONFIG.local_model,
"modified_at": _now(),
"size": 0,
"digest": "",
"details": {"parent_model": "", "format": "", "family": "", "families": [], "parameter_size": "", "quantization_level": ""},
}
return JSONResponse({"models": [entry]}, headers=base_headers(mode, "none", request.app.state.locator.sticky))
@router.get("/{mode}/api/version")
async def api_version(mode: str, request: Request):
invalid = _bad_mode(mode)
if invalid:
return invalid
data = await _forge_quick(request, "GET", "/api/version")
if data and data.get("version"):
_version_cache["value"] = data["version"]
version = _version_cache["value"] or CONFIG.ollama_version_fallback
return JSONResponse({"version": version}, headers=base_headers(mode, "forge" if data else "none", None))
@router.get("/{mode}/api/ps")
async def api_ps(mode: str, request: Request):
invalid = _bad_mode(mode)
if invalid:
return invalid
data = await _forge_quick(request, "GET", "/api/ps")
if data is None:
return _error(503, "forge is not reachable", mode)
return JSONResponse(data, headers=base_headers(mode, "forge", request.app.state.locator.sticky))
@router.post("/{mode}/api/show")
async def api_show(mode: str, request: Request):
invalid = _bad_mode(mode)
if invalid:
return invalid
data = await _forge_quick(request, "POST", "/api/show", {"model": CONFIG.local_model})
if data is None:
return _error(503, "forge is not reachable", mode)
return JSONResponse(data, headers=base_headers(mode, "forge", request.app.state.locator.sticky))
@router.post("/{mode}/api/chat")
async def api_chat(mode: str, request: Request):
invalid = _bad_mode(mode)
if invalid:
return invalid
try:
body = await request.json()
except ValueError:
return _error(400, "request body must be JSON", mode)
if not isinstance(body, dict) or not body.get("messages"):
return _error(400, "'messages' is required", mode)
return await _route(request, mode, "/api/chat", body, "chat")
@router.post("/{mode}/api/generate")
async def api_generate(mode: str, request: Request):
invalid = _bad_mode(mode)
if invalid:
return invalid
try:
body = await request.json()
except ValueError:
return _error(400, "request body must be JSON", mode)
if not isinstance(body, dict):
return _error(400, "request body must be a JSON object", mode)
return await _route(request, mode, "/api/generate", body, "generate")
@router.api_route("/{mode}/api/{rest:path}", methods=["GET", "POST", "DELETE", "HEAD"])
async def api_unsupported(mode: str, rest: str):
invalid = _bad_mode(mode)
if invalid:
return invalid
if rest in ("pull", "push", "create", "copy", "delete", "blobs"):
msg = (
f"{CONFIG.name} does not manage models; this endpoint serves exactly "
f"'{CONFIG.local_model}'. Select it from /api/tags instead of pulling."
)
elif rest in ("embed", "embeddings"):
msg = f"embeddings are not served here ('{CONFIG.local_model}' is not an embedding model)"
else:
msg = f"/api/{rest} is not implemented by {CONFIG.name}"
return JSONResponse({"error": msg}, status_code=400)
+16
View File
@@ -30,3 +30,19 @@ echo "10 readiness, forge UNAVAILABLE ....... HTTP $(j $BAD/healthz/ready)"
echo "11 streaming through forge ............ HTTP $(j -XPOST $GOOD/local-strict/v1/chat/completions -H 'Content-Type: application/json' -d '{"messages":[{"role":"user","content":"count to three"}],"max_tokens":200,"stream":true}') sse_chunks=$(grep -c '^data:' /tmp/b)"
echo "12 bare /v1 guard (expect 404) ........ HTTP $(j $GOOD/v1/models)"
echo "13 unknown mode guard (expect 404) .... HTTP $(j $GOOD/local-wishful/v1/models)"
# ---- native Ollama dialect (what Home Assistant's integration speaks) -------
OCHAT='{"model":"gpt-oss:120b","messages":[{"role":"user","content":"Answer with the single word: PONG"}],"stream":false,"think":false,"keep_alive":"5m","options":{"num_ctx":8192}}'
OSTREAM='{"model":"gpt-oss:120b","messages":[{"role":"user","content":"Answer with the single word: PONG"}],"stream":true,"think":false}'
ocontent() { sed -n 's/.*"message": *{[^}]*"content": *"\([^"]*\)".*/\1/p' /tmp/b | head -1 | cut -c1-40; }
ndjson_summary() { printf 'frames=%s content_frames=%s last_done=%s' "$(wc -l < /tmp/b)" "$(grep -c '"content": *"[^"]' /tmp/b)" "$(tail -1 /tmp/b | grep -o '"done": *true' | head -1)"; }
echo "14 ollama /api/tags (forge up) ........ HTTP $(j $GOOD/local-strict/api/tags) $(grep -o '"model":"[^"]*"' /tmp/b | head -1)"
echo "15 ollama /api/chat non-stream (forge) HTTP $(j -XPOST $GOOD/local-strict/api/chat -H 'Content-Type: application/json' -d "$OCHAT") backend=$(backend) content=[$(ocontent)] $(grep -o '"done_reason":"[^"]*"' /tmp/b | head -1)"
echo "16 ollama /api/chat STREAM (forge) .... HTTP $(j -XPOST $GOOD/local-optimistic/api/chat -H 'Content-Type: application/json' -d "$OSTREAM") $(ndjson_summary) ctype=$(grep -i '^content-type' /tmp/h | tr -d '\r' | awk '{print $2}')"
echo "17 ollama /api/version + /api/generate HTTP $(j $GOOD/local-strict/api/version) $(cut -c1-30 /tmp/b) | generate HTTP $(j -XPOST $GOOD/local-strict/api/generate -H 'Content-Type: application/json' -d '{"model":"gpt-oss:120b","prompt":"Answer with the single word: PONG","stream":false,"think":false}') $(grep -o '"response":"[^"]*"' /tmp/b | head -1)"
echo "18 ollama STRICT chat, forge UNAVAIL .. HTTP $(j -XPOST $BAD/local-strict/api/chat -H 'Content-Type: application/json' -d "$OCHAT") $(cut -c1-90 /tmp/b)"
echo "19 ollama OPTIMISTIC chat, UNAVAIL .... HTTP $(j -XPOST $BAD/local-optimistic/api/chat -H 'Content-Type: application/json' -d "$OCHAT") backend=$(backend) content=[$(ocontent)] $(grep -o '"done_reason":"[^"]*"' /tmp/b | head -1)"
echo "20 ollama OPTIMISTIC STREAM, UNAVAIL .. HTTP $(j -XPOST $BAD/local-optimistic/api/chat -H 'Content-Type: application/json' -d "$OSTREAM") backend=$(backend) $(ndjson_summary)"
echo "21 ollama /api/tags, forge UNAVAIL .... HTTP $(j $BAD/local-optimistic/api/tags) (listing, not liveness)"
echo "22 ollama /api/pull guard (expect 400) HTTP $(j -XPOST $GOOD/local-strict/api/pull -H 'Content-Type: application/json' -d '{"model":"llama3"}')"
+139
View File
@@ -0,0 +1,139 @@
#!/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())
+98
View File
@@ -0,0 +1,98 @@
#!/usr/bin/env bash
# Local smoke for the native-Ollama dialect. Two instances: one at the real
# forge, one at a dead upstream (the fallback / 503 paths). Uses the exact
# client Home Assistant pins (ollama==0.6.2) for the calls HA makes, and curl
# for raw frame shapes. Never touches Ollama on forge.
set -uo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"; PY="$ROOT/.venv/bin/python"
GOOD=http://127.0.0.1:18080; BAD=http://127.0.0.1:18081
start() { FORGEWAY_NAME=forgeway FORGEWAY_SITE="$1" FORGEWAY_UPSTREAMS="$3" FORGEWAY_DISCOVERY_TIMEOUT=3 \
"$PY" -m uvicorn app.main:app --host 127.0.0.1 --port "$2" --no-access-log >"/tmp/forgeway-$1.log" 2>&1 & echo $!; }
cd "$ROOT"
P1=$(start ollama-good 18080 "http://forge.dmz.falkvinge.net:11434"); P2=$(start ollama-bad 18081 "http://127.0.0.1:1")
trap 'kill $P1 $P2 2>/dev/null' EXIT; sleep 4
hdr() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; }
CHAT='{"model":"gpt-oss:120b","messages":[{"role":"user","content":"Reply with exactly: PONG"}],"stream":false,"think":false,"keep_alive":"5m","options":{"num_ctx":8192}}'
hdr "1 HA-pinned client (ollama==0.6.2): list() + chat(stream=True) exactly as HA calls them, forge up"
"$PY" - <<'PY'
import asyncio, ollama
async def main():
c = ollama.AsyncClient(host="http://127.0.0.1:18080/local-optimistic")
print(" list():", [m.model for m in (await c.list()).models])
content = thinking = ""; done = None; n = 0
async for part in await c.chat(model="gpt-oss:120b", messages=[{"role":"user","content":"Reply with exactly: PONG"}],
stream=True, keep_alive=-1, options={"num_ctx": 8192}, think=False):
n += 1; content += part.message.content or ""; thinking += part.message.thinking or ""
if part.done: done = part.done_reason
print(f" chat(stream=True): chunks={n} content={content!r} thinking_chars={len(thinking)} done_reason={done}")
asyncio.run(main())
PY
hdr "2 raw shapes, forge up: /api/chat non-stream, /api/tags, /api/version, /api/ps, /api/show"
curl -s -m 120 -D /tmp/h -X POST $GOOD/local-strict/api/chat -H 'Content-Type: application/json' -d "$CHAT" | python3 -c "
import sys,json; d=json.load(sys.stdin); m=d['message']
print(' chat:', 'content=%r'%m.get('content'), 'thinking=%s' % ('yes' if m.get('thinking') else 'no'), 'done=%s'%d['done'], 'done_reason=%s'%d.get('done_reason'), 'keys_ok=%s' % all(k in d for k in ('model','created_at','message','done','done_reason','total_duration','eval_count')))"
echo " backend: $(grep -i x-forgeway-backend /tmp/h | tr -d '\r')"
echo " tags: $(curl -s -m 10 $GOOD/local-strict/api/tags | python3 -c 'import sys,json; d=json.load(sys.stdin); print([ (m["model"], m.get("details",{}).get("family")) for m in d["models"]])')"
echo " version: $(curl -s -m 10 $GOOD/local-strict/api/version)"
echo " ps: $(curl -s -m 10 -o /dev/null -w '%{http_code}' $GOOD/local-strict/api/ps) show: $(curl -s -m 10 -o /dev/null -w '%{http_code}' -X POST $GOOD/local-strict/api/show -d '{"model":"x"}') pull(400 expected): $(curl -s -m 10 -o /dev/null -w '%{http_code}' -X POST $GOOD/local-strict/api/pull -d '{"model":"llama3"}')"
hdr "3 raw streaming through forge: framing = NDJSON, last frame done=true"
curl -s -N -m 120 -D /tmp/h -X POST $GOOD/local-optimistic/api/chat -H 'Content-Type: application/json' -d "${CHAT/\"stream\":false/\"stream\":true}" > /tmp/s.ndjson
echo " content-type: $(grep -i '^content-type' /tmp/h | tr -d '\r' | awk '{print $2}') frames=$(wc -l < /tmp/s.ndjson) last=$(tail -1 /tmp/s.ndjson | python3 -c 'import sys,json; d=json.load(sys.stdin); print("done=%s reason=%s"%(d["done"],d.get("done_reason")))')"
hdr "4 generate through forge (non-stream)"
curl -s -m 120 -X POST $GOOD/local-strict/api/generate -H 'Content-Type: application/json' -d '{"model":"gpt-oss:120b","prompt":"Reply with exactly: PONG","stream":false,"think":false}' | python3 -c "import sys,json; d=json.load(sys.stdin); print(' response=%r done=%s reason=%s' % (d.get('response'), d.get('done'), d.get('done_reason')))"
hdr "5 DEAD UPSTREAM, strict: /api/chat must be a clean Ollama-shaped 503"
echo " HTTP $(curl -s -m 30 -o /tmp/b -w '%{http_code}' -X POST $BAD/local-strict/api/chat -H 'Content-Type: application/json' -d "$CHAT") body=$(cut -c1-150 /tmp/b)"
echo " tags still 200 (listing, not liveness): $(curl -s -m 10 -o /dev/null -w '%{http_code}' $BAD/local-strict/api/tags)"
hdr "6 DEAD UPSTREAM, optimistic: cloud fallback translated to Ollama shape (non-stream)"
curl -s -m 120 -D /tmp/h -X POST $BAD/local-optimistic/api/chat -H 'Content-Type: application/json' -d "$CHAT" | python3 -c "
import sys,json; d=json.load(sys.stdin); m=d['message']
print(' content=%r done=%s done_reason=%s eval_count=%s created_at=%s' % (m.get('content'), d['done'], d.get('done_reason'), d.get('eval_count'), d['created_at'][:19]))"
echo " backend: $(grep -i x-forgeway-backend /tmp/h | tr -d '\r')"
hdr "7 DEAD UPSTREAM, optimistic: cloud fallback STREAMED as NDJSON, read with the HA-pinned client"
"$PY" - <<'PY'
import asyncio, ollama
async def main():
c = ollama.AsyncClient(host="http://127.0.0.1:18081/local-optimistic")
content = ""; done = None; n = 0
async for part in await c.chat(model="gpt-oss:120b", messages=[{"role":"user","content":"Reply with exactly: PONG"}], stream=True, think=False):
n += 1; content += part.message.content or ""
if part.done: done = part.done_reason
print(f" chunks={n} content={content!r} done_reason={done}")
asyncio.run(main())
PY
hdr "8 DEAD UPSTREAM, optimistic: tool call round-trip through the cloud (HA Assist-API shape)"
"$PY" - <<'PY'
import asyncio, ollama
async def main():
c = ollama.AsyncClient(host="http://127.0.0.1:18081/local-optimistic")
tools=[{"type":"function","function":{"name":"HassTurnOn","description":"Turn on a device","parameters":{"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}}}]
msgs=[{"role":"user","content":"Turn on the kitchen light. Use the tool."}]
calls=[]
async for part in await c.chat(model="gpt-oss:120b", messages=msgs, tools=tools, stream=True, think=False):
if part.message.tool_calls: calls += [(t.function.name, dict(t.function.arguments)) for t in part.message.tool_calls]
print(" tool_calls:", calls)
# second round: feed the tool result back (ids are synthesised by the router)
msgs += [{"role":"assistant","content":"","tool_calls":[{"function":{"name":"HassTurnOn","arguments":{"name":"kitchen light"}}}]},
{"role":"tool","content":'{"data":{"success":true},"error":null}'}]
r = await c.chat(model="gpt-oss:120b", messages=msgs, tools=tools, stream=False, think=False)
print(" after tool result:", repr((r.message.content or "")[:80]), "done_reason=", r.done_reason)
asyncio.run(main())
PY
hdr "9 DEAD UPSTREAM, optimistic: generate via cloud (stream), and format=json"
curl -s -N -m 120 -X POST $BAD/local-optimistic/api/generate -H 'Content-Type: application/json' -d '{"model":"gpt-oss:120b","prompt":"Reply with exactly: PONG","stream":true}' > /tmp/g.ndjson
echo " generate stream frames=$(wc -l < /tmp/g.ndjson) text=$(python3 -c 'import json; print(repr("".join(json.loads(l).get("response","") for l in open("/tmp/g.ndjson"))))') last=$(tail -1 /tmp/g.ndjson | cut -c1-90)"
echo " format=json: $(curl -s -m 120 -X POST $BAD/local-optimistic/api/chat -H 'Content-Type: application/json' -d '{"model":"x","messages":[{"role":"user","content":"Return JSON with key a = 1"}],"stream":false,"format":"json"}' | python3 -c 'import sys,json; print(repr(json.load(sys.stdin)["message"]["content"][:60]))')"
hdr "10 OpenAI dialect untouched (regression): /v1/models + strict chat"
echo " models: $(curl -s -m 10 -o /dev/null -w '%{http_code}' $GOOD/local-strict/v1/models) chat: $(curl -s -m 120 -o /tmp/b -w '%{http_code}' -X POST $GOOD/local-strict/v1/chat/completions -H 'Content-Type: application/json' -d '{"messages":[{"role":"user","content":"Reply with exactly: PONG"}],"max_tokens":300}') $(python3 -c 'import json; print(repr(json.load(open("/tmp/b"))["choices"][0]["message"]["content"][:20]))')"
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""Probe gpt-5.4-mini's reasoning_effort / stream_options / tool-call contract.
Needed to translate Ollama's `think` flag and streaming shape onto the cloud
fallback. Reads the key from the environment and never prints it.
"""
import json
import os
import sys
import urllib.error
import urllib.request
KEY = os.environ.get("OPENAI_API_KEY", "")
MODEL = os.environ.get("FORGEWAY_CLOUD_MODEL", "gpt-5.4-mini")
if not KEY:
sys.exit("OPENAI_API_KEY not present in the environment")
BASE = {"model": MODEL, "messages": [{"role": "user", "content": "say PONG"}], "max_completion_tokens": 64}
CASES = {
"reasoning_effort=none": {"reasoning_effort": "none"},
"reasoning_effort=low": {"reasoning_effort": "low"},
"reasoning_effort=medium": {"reasoning_effort": "medium"},
"reasoning_effort=high": {"reasoning_effort": "high"},
"stream+include_usage": {"stream": True, "stream_options": {"include_usage": True}},
"response_format=json_object": {"response_format": {"type": "json_object"},
"messages": [{"role": "user", "content": "Return JSON {\"a\":1}"}]},
"tools": {"tools": [{"type": "function", "function": {"name": "get_weather",
"description": "Weather for a city", "parameters": {"type": "object",
"properties": {"city": {"type": "string"}}, "required": ["city"]}}}],
"messages": [{"role": "user", "content": "What is the weather in Berlin? Use the tool."}]},
}
for label, extra in CASES.items():
body = {**BASE, **extra}
req = urllib.request.Request(
"https://api.openai.com/v1/chat/completions",
data=json.dumps(body).encode(),
headers={"Content-Type": "application/json", "Authorization": f"Bearer {KEY}"},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=90) as resp:
raw = resp.read().decode()
if body.get("stream"):
lines = [l for l in raw.splitlines() if l.startswith("data: ")]
last = json.loads(lines[-2][6:]) if len(lines) >= 2 and lines[-1].strip() == "data: [DONE]" else json.loads(lines[-1][6:])
print(f"{label:30s} -> {resp.status} sse_lines={len(lines)} last_has_usage={'usage' in last and last['usage'] is not None} last_choices={len(last.get('choices', []))}")
else:
d = json.loads(raw)
msg = d["choices"][0]["message"]
print(f"{label:30s} -> {resp.status} finish={d['choices'][0]['finish_reason']} content={msg.get('content')!r:.40} tool_calls={json.dumps(msg.get('tool_calls'))[:120] if msg.get('tool_calls') else None}")
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace")
try:
detail = json.loads(detail)["error"]["message"]
except Exception:
detail = detail[:160]
print(f"{label:30s} -> {exc.code} {detail}")