engine: add the ollama System One provider

A third decision-engine provider alongside the local SemIf GGUF and the
remote Winnow server: `engine.provider == "ollama"` talks to ollama's
native `/v1/systemone` route via `semif_agent/ollama_systemone.py`.

It reuses the Winnow DecisionRequest -> choice mapping and the same strict
distribution validation over exactly the requested option ids, and adds
the edges only ollama has:

- no `/health`: `warm()` probes `GET /api/version` + `POST /api/show`,
  which also proves the model is pulled and advertises the `decision`
  capability;
- `engine.ollama.context_tokens: 0` follows the model's real `num_ctx`
  from `/api/show`;
- `keep_alive` rides on the request, criteria descriptions use the ollama
  subset `string | null`, and a choice question needs >= 2 options;
- decision models do not generate text, so `generate()` raises
  `EngineUnavailable` (use `llm.provider == "ollama"` for chat).

Every failure is an `EngineUnavailable` (fatal, like the local engine) and
the engine lock still serializes on the single-slot server.

`cli.build_engine` selects it, the setup interview and `--answers` accept
it, and the install plan skips the engine clone/GGUF/tokenizer for it.
Docs, config.example.json, and tests updated.
This commit is contained in:
gabby committed 2026-11-11 02:57:53 +00:00
1 parent 894a85ec2d
commit addbe53392
12 files changed
+903 -41

No files matched your search

+28 -5
View File
@@ -41,6 +41,7 @@ from .console import (
)
from .decisions import DecisionRequest, Option
from .engine import DecisionEngine, EngineConfig, EngineUnavailable, SemIfEngine
from .ollama_systemone import OllamaSystemOneConfig, OllamaSystemOneEngine
from .winnow import WinnowConfig, WinnowEngine
from .llm import LLMClient, SemIfLLMClient
from .log import DecisionLog
@@ -54,6 +55,7 @@ from .trace import TraceLog
REPO_ROOT = Path(__file__).resolve().parent.parent
DEFAULT_WINNOW_URL = "http://127.0.0.1:8091"
DEFAULT_OLLAMA_SYSTEMONE_URL = "http://127.0.0.1:11434"
_PATH_KEYS = (
"skill_packs",
@@ -221,14 +223,19 @@ def build_engine(config: dict, pins: dict | None = None) -> DecisionEngine:
* ``"semif"`` (default) — the local llama.cpp GGUF (`SemIfEngine`), built
from the per-machine `engine` knobs + the pinned refs in pins.json.
* ``"winnow"`` — a remote `/v1/systemone` typed-decision API
* ``"winnow"`` — a remote Winnow `/v1/systemone` typed-decision API
(`WinnowEngine`), configured by the nested `engine.winnow` block
(`base_url`/`model`/`api_key`/`timeout`/`retries`).
* ``"ollama"`` — ollama's native System One `/v1/systemone` route
(`OllamaSystemOneEngine`), configured by the nested `engine.ollama` block
(`base_url`/`model`/`keep_alive`/`api_key`/`timeout`/`retries`), probed
through ollama's own `/api/version` + `/api/show` endpoints.
The engine is always real: a provider that cannot be reached raises
`EngineUnavailable` at call time, which the scheduler treats as fatal. The
`winnow` model is required (no default) exactly as `llm.model`/`codegen.model`
are, so a misconfigured endpoint fails as an actionable config error.
`winnow` and `ollama` models are required (no default) exactly as
`llm.model`/`codegen.model` are, so a misconfigured endpoint fails as an
actionable config error.
"""
eng = config.get("engine", {}) or {}
provider = str(eng.get("provider", "semif") or "semif").lower()
@@ -247,6 +254,22 @@ def build_engine(config: dict, pins: dict | None = None) -> DecisionEngine:
user_agent=str(win.get("user_agent") or "semif-agent"),
)
)
if provider == "ollama":
block = eng.get("ollama", {}) or {}
endpoint = _provider_endpoint(block, DEFAULT_OLLAMA_SYSTEMONE_URL)
return OllamaSystemOneEngine(
OllamaSystemOneConfig(
base_url=endpoint["base_url"],
model=_required_model(block, "engine.ollama"),
context_tokens=int(block.get("context_tokens", 16384)),
timeout=float(block.get("timeout", 120.0)),
retries=int(block.get("retries", 0)),
api_key=endpoint["api_key"],
extra_headers=endpoint["extra_headers"],
user_agent=str(block.get("user_agent") or "semif-agent"),
keep_alive=str(block.get("keep_alive") or ""),
)
)
return SemIfEngine(build_engine_config(config, pins))
@@ -1164,8 +1187,8 @@ def main(argv: list[str] | None = None) -> int:
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=(
"answers JSON fields (all optional; --answers FILE):\n"
" engine_provider (semif|winnow), winnow_base_url, winnow_model,\n"
" winnow_api_key\n"
" engine_provider (semif|winnow|ollama), winnow_base_url, winnow_model,\n"
" winnow_api_key, ollama_base_url, ollama_model, ollama_api_key\n"
" new_skill_creation (deny|ask|allow)\n"
" llm_provider (semif|ollama|opencode|openai), llm_base_url,\n"
" llm_model, llm_api_key\n"
+9
View File
@@ -75,6 +75,15 @@ CORE_SCHEMA: dict[str, Any] = {'tau': {'default': 0.6, 'type': 'float', 'doc': '
'retries': {'default': 0, 'type': 'int'},
'user_agent': {'default': 'semif-agent', 'type': 'str'},
'extra_headers': {'default': {}, 'type': 'dict'}},
'ollama': {'base_url': {'default': 'http://127.0.0.1:11434', 'type': 'str'},
'model': {'default': '', 'type': 'str'},
'context_tokens': {'default': 16384, 'type': 'int'},
'api_key': {'default': '', 'type': 'str', 'secret': True},
'timeout': {'default': 120, 'type': 'int'},
'retries': {'default': 0, 'type': 'int'},
'keep_alive': {'default': '', 'type': 'str'},
'user_agent': {'default': 'semif-agent', 'type': 'str'},
'extra_headers': {'default': {}, 'type': 'dict'}},
'gguf': {'default': '', 'type': 'str'}},
'llm': {'provider': {'default': 'ollama', 'type': 'str'},
'base_url': {'default': 'http://localhost:11434/v1', 'type': 'str'},
+7 -2
View File
@@ -9,7 +9,9 @@ installed. The shipped llama.cpp backend scores a local GGUF; it runs on CPU by
default, and `EngineConfig.gpu_layers` offloads to a GPU when llama-cpp-python
was built with a GPU backend (Vulkan/ROCm/CUDA). This engine is only usable on a
machine with SemIf and the pinned GGUF available; elsewhere calls raise
EngineUnavailable. The remote alternative lives in `semif_agent.winnow`.
EngineUnavailable. The remote alternatives live in `semif_agent.winnow` (the
Winnow reference server) and `semif_agent.ollama_systemone` (ollama's native
System One route).
"""
from __future__ import annotations
@@ -40,8 +42,11 @@ class DecisionEngine(ABC):
`llm.provider` / `codegen.provider`:
* ``"semif"`` (default) — the local llama.cpp GGUF (`SemIfEngine`).
* ``"winnow"`` — a remote ``/v1/systemone`` typed-decision API
* ``"winnow"`` — a remote Winnow ``/v1/systemone`` typed-decision API
(`semif_agent.winnow.WinnowEngine`).
* ``"ollama"`` — ollama's native System One ``/v1/systemone`` route
(`semif_agent.ollama_systemone.OllamaSystemOneEngine`), probed through
ollama's own ``/api/version`` + ``/api/show`` endpoints.
The engine is always real: any failure to produce a decision raises
`EngineUnavailable`, which the scheduler treats as fatal. `generate` is the
+348
View File
@@ -0,0 +1,348 @@
"""Ollama System One decision engine: ollama's native ``/v1/systemone`` API.
An alternative to the local SemIf llama.cpp engine (`engine.SemIfEngine`) and
to the Winnow server (`semif_agent.winnow.WinnowEngine`), selected per machine
with ``engine.provider == "ollama"`` in config.json — the same provider pattern
as ``llm`` / ``codegen``.
The agent's flat decision contract (state + question + typed options) maps onto
Ollama's System One ``choice`` question: the options become the question's
``criteria`` (id -> description, or ``null`` for a bare label) and the question
becomes its ``instructions``; the server returns a probability over exactly
those keys. This provider implements the **Ollama** shape of that API (the one
documented at docs.ollama.com/api/systemone), which differs from the Winnow
reference server in ways that matter at the edges:
* no ``/health`` route — reachability/warmth is probed through Ollama's native
``GET /api/version`` and ``POST /api/show`` (which also verifies the model
exists and advertises the ``decision`` capability);
* the decision context window is read from the model's ``num_ctx`` parameter
(``/api/show``) when ``engine.ollama.context_tokens`` is 0, so generated
skill bodies are sized to what the server really loaded;
* ``keep_alive`` is an Ollama request knob, not part of the System One contract;
* choice criteria descriptions are the Ollama subset ``string | null`` (never
an object) and at least two options are required;
* decision models do not generate text, so ``generate`` is unavailable here
(use ``llm.provider == "ollama"`` for the chat path).
The engine is real: any network, HTTP, or distribution failure raises
`EngineUnavailable`, which the scheduler treats as fatal — there is no fallback
model and no fabricated reply.
"""
from __future__ import annotations
import json
import math
import re
import threading
import time
import urllib.error
import urllib.request
from dataclasses import dataclass
from .decisions import DecisionRequest, DecisionResult
from .engine import DecisionEngine, EngineUnavailable
@dataclass
class OllamaSystemOneConfig:
"""Per-machine settings for the Ollama System One engine (`engine.ollama`)."""
#: The Ollama server root — **no** ``/v1`` suffix (System One lives at
#: ``/v1/systemone`` on the root server, unlike the OpenAI-compatible API).
base_url: str = "http://127.0.0.1:11434"
model: str = ""
#: The model's decision context window, in tokens. 0 asks the server (the
#: model's `num_ctx` parameter, then its architecture context length), so
#: the fidelity-state budget mirrors the window the server really loaded.
context_tokens: int = 16384
timeout: float = 120.0
#: Transient-failure retries before declaring the engine unavailable. 0
#: means a single attempt: an unreachable remote engine is fatal by
#: contract.
retries: int = 0
#: Bearer key for Ollama's cloud models (``https://ollama.com``); empty for
#: a local server.
api_key: str = ""
extra_headers: dict | None = None
user_agent: str = "semif-agent"
#: Ollama's model-unload policy for the request (a duration such as "5m",
#: or seconds). Empty keeps the server's own keep-alive setting.
keep_alive: str = ""
def _context_from_show(show: dict) -> int | None:
"""The model's context window from an Ollama ``/api/show`` payload.
Ollama reports ``parameters`` either as modelfile text
(``"num_ctx 16384\\n..."``) or as a mapping, depending on version; the
architecture context length in ``model_info`` is the fallback. Returns
``None`` when neither shape carries a usable number.
"""
params = show.get("parameters")
if isinstance(params, str):
match = re.search(r"(?m)^\s*num_ctx\s+(\d+)\s*$", params)
if match:
return int(match.group(1))
elif isinstance(params, dict):
value = params.get("num_ctx")
if value is not None:
try:
return int(value)
except (TypeError, ValueError):
pass
info = show.get("model_info")
if isinstance(info, dict):
# Prefer the text model's context length over a vision tower's.
candidates = [
value
for key, value in info.items()
if str(key).endswith(".context_length") and "vision" not in str(key)
]
for value in candidates:
try:
return int(value)
except (TypeError, ValueError):
continue
return None
class OllamaSystemOneEngine(DecisionEngine):
"""One Ollama System One endpoint, used for every decision.
Scoring maps a `DecisionRequest` -> a single ``choice`` question and reads
the returned distribution back over the requested option ids. The endpoint
is a single-slot server, so calls serialize on an internal lock exactly as
`SemIfEngine` serializes on its llama.cpp context.
"""
label = "ollama"
def __init__(self, config: OllamaSystemOneConfig):
self.config = config
self._lock = threading.Lock()
self._loaded = False
self._discovered_context: int | None = None
@property
def context_tokens(self) -> int:
configured = int(self.config.context_tokens or 0)
if configured > 0:
return configured
return int(self._discovered_context or 16384)
@property
def loaded(self) -> bool:
return self._loaded
# ---- transport ----
def _headers(self) -> dict:
headers = {
"content-type": "application/json",
"accept": "application/json",
}
if self.config.user_agent:
headers["user-agent"] = self.config.user_agent
if self.config.api_key:
headers["authorization"] = f"Bearer {self.config.api_key}"
for key, value in (self.config.extra_headers or {}).items():
headers[str(key)] = str(value)
return headers
def _request(self, path: str, payload: dict | None = None) -> dict:
"""GET (no payload) or POST JSON, or raise `EngineUnavailable`."""
url = self.config.base_url.rstrip("/") + path
data = None
if payload is not None:
data = json.dumps(payload).encode("utf-8")
attempts = max(0, int(self.config.retries)) + 1
last: Exception | None = None
for attempt in range(attempts):
request = urllib.request.Request(
url,
data=data,
method="POST" if data is not None else "GET",
headers=self._headers(),
)
try:
with urllib.request.urlopen(
request, timeout=self.config.timeout
) as response:
body = response.read().decode("utf-8", errors="replace")
parsed = json.loads(body)
if not isinstance(parsed, dict):
raise EngineUnavailable(
f"Ollama response from {url} is not a JSON object"
)
return parsed
except urllib.error.HTTPError as exc:
detail = ""
try:
# Ollama reports failures as {"error": "..."}.
detail = exc.read().decode("utf-8", errors="replace")[:300]
except Exception:
pass
last = EngineUnavailable(
f"HTTP {exc.code} from {url}: {detail}".strip()
)
# A 4xx (except 429) will not succeed on retry.
if 400 <= exc.code < 500 and exc.code != 429:
break
except EngineUnavailable:
raise
except Exception as exc: # URLError, timeout, socket, JSONDecodeError
last = exc
if attempt + 1 < attempts:
time.sleep(min(2.0**attempt, 5.0))
if isinstance(last, EngineUnavailable):
raise last
raise EngineUnavailable(
f"Ollama request to {url} failed: {type(last).__name__}: {last}"
)
def _post(self, path: str, payload: dict) -> dict:
return self._request(path, payload)
# ---- DecisionEngine ----
def warm(self) -> None:
"""Verify the server and the configured model, then mark loaded.
Ollama has no ``/health`` route: ``GET /api/version`` proves the server
answers and ``POST /api/show`` proves the model is pulled (404 when it
is not) and lets a 0 ``context_tokens`` follow the model's real
``num_ctx``. A model that advertises capabilities without ``decision``
is rejected with an actionable error instead of failing on first use.
"""
self._request("/api/version")
show = self._post("/api/show", {"model": self.config.model})
if int(self.config.context_tokens or 0) <= 0:
discovered = _context_from_show(show)
if discovered:
self._discovered_context = discovered
capabilities = show.get("capabilities")
if isinstance(capabilities, list) and capabilities:
if "decision" not in capabilities:
raise EngineUnavailable(
f"Ollama model {self.config.model!r} does not advertise the "
"'decision' capability (capabilities: "
f"{', '.join(str(c) for c in capabilities)}); point "
"engine.ollama.model at a System One model"
)
self._loaded = True
def call(self, request: DecisionRequest) -> DecisionResult:
option_ids = [option.id for option in request.options]
if len(option_ids) < 2:
raise EngineUnavailable(
"Ollama System One choice questions need at least two options"
)
state = request.state if isinstance(request.state, str) else json.dumps(
request.state
)
if not state.strip():
raise EngineUnavailable("Ollama System One requires a non-empty state")
# Ollama's choice criteria descriptions are `string | null`; a bare
# label is the explicit `null` form.
criteria = {
option.id: (option.description.strip() or None)
for option in request.options
}
payload = {
"model": self.config.model,
"state": state,
"questions": {
"decision": {
"type": "choice",
"instructions": request.question,
"criteria": criteria,
}
},
}
keep_alive = str(self.config.keep_alive or "").strip()
if keep_alive:
payload["keep_alive"] = keep_alive
with self._lock:
started = time.perf_counter()
body = self._post("/v1/systemone", payload)
elapsed = time.perf_counter() - started
answers = body.get("answers")
answer = answers.get("decision") if isinstance(answers, dict) else None
if not isinstance(answer, dict):
raise EngineUnavailable(
"Ollama response is missing answers.decision"
)
if answer.get("type") not in (None, "choice"):
raise EngineUnavailable(
f"Ollama answer type {answer.get('type')!r} is not 'choice'"
)
raw = answer.get("probabilities")
if not isinstance(raw, dict):
raise EngineUnavailable("Ollama answer is missing probabilities")
if set(raw) != set(option_ids):
raise EngineUnavailable(
"Ollama probabilities do not match the requested options: "
f"{sorted(raw)} != {sorted(option_ids)}"
)
choice = answer.get("choice")
if choice is not None and choice not in option_ids:
raise EngineUnavailable(
f"Ollama choice {choice!r} is not one of the requested options"
)
try:
values = [float(raw[option_id]) for option_id in option_ids]
except (TypeError, ValueError) as exc:
raise EngineUnavailable(
f"Ollama probabilities are not numeric: {exc}"
) from exc
if any(
(not math.isfinite(value)) or value < 0.0 or value > 1.0
for value in values
):
raise EngineUnavailable(
"Ollama returned a non-finite or out-of-range probability"
)
total = sum(values)
if total <= 0.0:
raise EngineUnavailable("Ollama returned an all-zero distribution")
probabilities = [value / total for value in values]
usage = body.get("usage") if isinstance(body.get("usage"), dict) else {}
self._loaded = True
return DecisionResult(
request=request,
option_ids=option_ids,
probabilities=probabilities,
extra={
"input_tokens": usage.get("input_tokens"),
"output_tokens": usage.get("output_tokens"),
"forward_seconds": elapsed,
"total_seconds": elapsed,
"raw_probability_sum": total,
"served_model": body.get("model"),
"choice": choice,
"confidence": answer.get("confidence"),
},
)
def generate(
self,
messages: list[dict],
temperature: float = 0.0,
max_tokens: int = 256,
) -> str:
"""Unavailable: System One decision models do not generate text.
Use ``llm.provider == "ollama"`` (an OpenAI-compatible chat endpoint) for
text; pointing ``llm.provider`` at this decision engine would ask a
classifier to write prose, so it is refused rather than faked.
"""
raise EngineUnavailable(
"the ollama System One decision engine does not generate text; "
"configure llm.provider = \"ollama\" for the chat path"
)
+51 -5
View File
@@ -46,7 +46,7 @@ from .packs import SkillPack, pack_enabled
#: ``llm``/``codegen`` providers the wizard can emit.
PROVIDERS = ("semif", "ollama", "opencode", "openai")
#: ``engine`` providers.
ENGINE_PROVIDERS = ("semif", "winnow")
ENGINE_PROVIDERS = ("semif", "winnow", "ollama")
#: New-skill creation modes.
AUTHORING_MODES = ("deny", "ask", "allow")
@@ -71,10 +71,14 @@ class Answers:
"""The wizard's answers, and the source of truth for the generated config."""
# Decision engine.
engine_provider: str = "semif" # semif | winnow
engine_provider: str = "semif" # semif | winnow | ollama
winnow_base_url: str = ""
winnow_model: str = ""
winnow_api_key: str = ""
#: Ollama's native System One route (`engine.ollama`).
ollama_base_url: str = ""
ollama_model: str = ""
ollama_api_key: str = ""
# New-skill authoring: deny | ask | allow.
new_skill_creation: str = "deny"
@@ -351,7 +355,7 @@ def run_interview(
output(
" The decision engine routes every request. It runs locally on the\n"
" pinned SemIf 4B GGUF by default (no network), or against a remote\n"
" Winnow /v1/systemone server."
" Winnow /v1/systemone server or an Ollama System One decision model."
)
answers.engine_provider = _ask_choice(
input_fn,
@@ -360,6 +364,7 @@ def run_interview(
[
("semif", "local SemIf 4B (llama.cpp, pinned GGUF)"),
("winnow", "remote Winnow decision server"),
("ollama", "remote Ollama System One model (/v1/systemone)"),
],
1,
)
@@ -376,6 +381,25 @@ def run_interview(
answers.winnow_api_key = _ask_text(
input_fn, output, " winnow API key (blank for none)", "", secret=True
)
elif answers.engine_provider == "ollama":
answers.ollama_base_url = _ask_text(
input_fn, output, " ollama base URL", "http://127.0.0.1:11434"
)
model = ""
while not model:
model = _ask_text(
input_fn, output, " ollama System One model (required)"
)
if not model:
output(" engine.ollama.model is required.")
answers.ollama_model = model
answers.ollama_api_key = _ask_text(
input_fn,
output,
" ollama API key (blank for a local server)",
"",
secret=True,
)
# 2. Skill authoring.
output("")
@@ -399,7 +423,15 @@ def run_interview(
answers.new_skill_creation = mode
if mode != "deny":
output("")
_collect_llm(input_fn, output, answers, label="llm", allow_semif=True)
# The Ollama System One decision model does not generate text, so it
# cannot back the small `llm` task; only a real endpoint can.
_collect_llm(
input_fn,
output,
answers,
label="llm",
allow_semif=answers.engine_provider != "ollama",
)
output("")
_collect_llm(input_fn, output, answers, label="codegen", allow_semif=False)
@@ -529,6 +561,14 @@ def build_config(answers: Answers, packs: Sequence[SkillPack]) -> dict:
_set_secret_or_literal(
winnow, "api_key", answers.winnow_api_key, "engine_winnow_api_key"
)
elif answers.engine_provider == "ollama":
ollama = engine.setdefault("ollama", {})
if answers.ollama_base_url:
ollama["base_url"] = answers.ollama_base_url
ollama["model"] = answers.ollama_model
_set_secret_or_literal(
ollama, "api_key", answers.ollama_api_key, "engine_ollama_api_key"
)
# Authoring mode.
config["new_skill_creation"] = answers.new_skill_creation
@@ -613,6 +653,8 @@ def build_secrets(answers: Answers) -> dict:
secrets: dict[str, str] = {}
if answers.engine_provider == "winnow" and answers.winnow_api_key:
secrets["engine_winnow_api_key"] = answers.winnow_api_key
if answers.engine_provider == "ollama" and answers.ollama_api_key:
secrets["engine_ollama_api_key"] = answers.ollama_api_key
if answers.llm_provider != "semif" and answers.llm_api_key:
secrets["llm_api_key"] = answers.llm_api_key
if answers.codegen_api_key:
@@ -834,7 +876,11 @@ def _print_summary(answers: Answers, output: Callable[[str], None]) -> None:
+ (
"local SemIf 4B"
if answers.engine_provider == "semif"
else f"remote Winnow ({answers.winnow_model or '?'})"
else (
f"remote Winnow ({answers.winnow_model or '?'})"
if answers.engine_provider == "winnow"
else f"remote Ollama System One ({answers.ollama_model or '?'})"
)
)
)
output(f" authoring: {answers.new_skill_creation}")
+7 -5
View File
@@ -8,10 +8,12 @@ question type: the options become the question's ``criteria`` (id -> description
and the question becomes its ``instructions``; the server returns a probability
over exactly those keys.
Winnow runs as its own process (``winnow-server``); see ``local/ENVIRONMENT.md``
for this deployment. The engine is real: any network, HTTP, or distribution
failure raises `EngineUnavailable`, which the scheduler treats as fatal — there
is no fallback model and no fabricated reply.
It works against any server implementing that route: the reference
``winnow-server``, or an OpenAI-compatible host (ollama 0.40+) serving a
``decision`` model such as ``clef-flash``. See ``local/ENVIRONMENT.md`` for this
deployment. The engine is real: any network, HTTP, or distribution failure
raises `EngineUnavailable`, which the scheduler treats as fatal — there is no
fallback model and no fabricated reply.
"""
from __future__ import annotations
@@ -24,7 +26,7 @@ import urllib.error
import urllib.request
from dataclasses import dataclass
from .decisions import DecisionRequest, DecisionResult
from .decisions import DecisionRequest, DecisionResult, Option
from .engine import DecisionEngine, EngineUnavailable