"""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" )