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

+46 -18
View File
@@ -227,6 +227,16 @@ winnow.py WinnowEngine -> a remote Winnow `/v1/systemone` typed-decision
ids, and generate() via /v1/chat/completions. stdlib urllib; an ids, and generate() via /v1/chat/completions. stdlib urllib; an
internal lock serializes on the single-slot server; every internal lock serializes on the single-slot server; every
failure raises EngineUnavailable (fatal, like the local engine) failure raises EngineUnavailable (fatal, like the local engine)
ollama_systemone.py
OllamaSystemOneEngine -> ollama's native System One
`/v1/systemone` route (`engine.provider == "ollama"`): same
DecisionRequest -> choice mapping and strict distribution
validation, plus ollama's own edges — reachability/warmth via
/api/version + /api/show (model exists, `decision` capability,
real `num_ctx`), request `keep_alive`, `string | null` criteria
descriptions, and no text generation (decision models don't
generate). stdlib urllib; internal lock; every failure raises
EngineUnavailable.
codegen.py CodegenClient (OpenAI-compatible) writes real-integration skill codegen.py CodegenClient (OpenAI-compatible) writes real-integration skill
bodies against CODEGEN.md (real actions via stdlib transports, bodies against CODEGEN.md (real actions via stdlib transports,
data from the runner via ctx.config, never embedded; bodies data from the runner via ctx.config, never embedded; bodies
@@ -823,28 +833,45 @@ CLI, unit tests (24) + integration tests (2).
in config.json — the same provider pattern as `llm`/`codegen`. `"semif"` in config.json — the same provider pattern as `llm`/`codegen`. `"semif"`
(default) is the local llama.cpp GGUF (`SemIfEngine`); `"winnow"` is a remote (default) is the local llama.cpp GGUF (`SemIfEngine`); `"winnow"` is a remote
Winnow `/v1/systemone` typed-decision API (`semif_agent.winnow.WinnowEngine`, Winnow `/v1/systemone` typed-decision API (`semif_agent.winnow.WinnowEngine`,
configured by the nested `engine.winnow` block). `cli.build_engine` picks the configured by the nested `engine.winnow` block); `"ollama"` is ollama's native
class; `SemIfEngine`/`WinnowEngine` both satisfy `engine.DecisionEngine` System One `/v1/systemone` route
(`call`/`warm`/`loaded`/`generate`). (`semif_agent.ollama_systemone.OllamaSystemOneEngine`, configured by the
nested `engine.ollama` block). `cli.build_engine` picks the class;
`SemIfEngine`/`WinnowEngine`/`OllamaSystemOneEngine` all satisfy
`engine.DecisionEngine` (`call`/`warm`/`loaded`/`generate`).
- **`winnow` and `ollama` are different edges of the same System One contract.**
Both map the flat decision onto a `choice` question and validate/normalize the
returned distribution over exactly the requested option ids, but the
`ollama` provider implements the deployment details only ollama has: there is
no `/health`, so `warm()` probes `GET /api/version` and `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, choice criteria
descriptions use the ollama subset `string | null`, and a choice question
needs at least two options. Decision models do not generate text, so
`OllamaSystemOneEngine.generate` raises `EngineUnavailable` — use
`llm.provider == "ollama"` for the chat path.
- **The engine is always real and every `EngineUnavailable` is fatal**, - **The engine is always real and every `EngineUnavailable` is fatal**,
whichever provider is selected: `WinnowEngine` converts every network, HTTP, whichever provider is selected: `WinnowEngine`/`OllamaSystemOneEngine` convert
and malformed/unnormalized-distribution failure into `EngineUnavailable` so every network, HTTP, and malformed/unnormalized-distribution failure into
the scheduler's fatal path (and the codegen watchdog / LLM bridge's graceful `EngineUnavailable` so the scheduler's fatal path (and the codegen watchdog /
paths) behave identically to the local engine. There is no fallback model. LLM bridge's graceful paths) behave identically to the local engine. There is
no fallback model.
- The agent's flat decision (`state` + `question` + typed `options`) maps onto - The agent's flat decision (`state` + `question` + typed `options`) maps onto
Winnow's `choice` question type (`options` -> `criteria` id->description, the System One `choice` question type (`options` -> `criteria`
`question` -> `instructions`); the returned distribution is validated against id->description, `question` -> `instructions`); the returned distribution is
exactly the requested option ids and normalized. `generate` goes through the validated against exactly the requested option ids and normalized. For
same server's `/v1/chat/completions`, so `llm.provider == "semif"` keeps `winnow`, `generate` goes through the same server's `/v1/chat/completions`, so
working when the decision engine is Winnow. `llm.provider == "semif"` keeps working when the decision engine is Winnow.
- Swapping the decision model changes routing/assessment behaviour and the - Swapping the decision model changes routing/assessment behaviour and the
decision-log distribution; that is the intended per-machine choice. The decision-log distribution; that is the intended per-machine choice. The
decision log and `dream` cost are unchanged because `DecisionResult` is the decision log and `dream` cost are unchanged because `DecisionResult` is the
same contract. same contract.
- Context differs by provider (the local engine's `engine.context_tokens` vs the - Context differs by provider (the local engine's `engine.context_tokens` vs the
remote server's own `--ctx-size`, mirrored in `engine.winnow.context_tokens`); remote server's own decision window, mirrored in `engine.winnow.context_tokens`
a state that overflows is a fatal `EngineUnavailable`, the same class as the or discovered from `engine.ollama`'s `/api/show` `num_ctx`); a state that
local token limit. Every engine exposes its window as `context_tokens` (a overflows is a fatal `EngineUnavailable`, the same class as the local token
limit. Every engine exposes its window as `context_tokens` (a
`DecisionEngine` property), which the scheduler uses to size generated `DecisionEngine` property), which the scheduler uses to size generated
artifacts — see "Artifact size budget". artifacts — see "Artifact size budget".
@@ -890,8 +917,8 @@ CLI, unit tests (24) + integration tests (2).
which installs the Vulkan build prereqs which installs the Vulkan build prereqs
(`libvulkan-dev glslc spirv-headers glslang-tools`) when needed. A CPU-only (`libvulkan-dev glslc spirv-headers glslang-tools`) when needed. A CPU-only
host keeps the default CPU wheel — a GPU build is slower on CPU. A host whose host keeps the default CPU wheel — a GPU build is slower on CPU. A host whose
`engine.provider` is `"winnow"` installs none of this (no clone, no GGUF, no `engine.provider` is `"winnow"` or `"ollama"` installs none of this (no clone,
tokenizer, no engine deps). no GGUF, no tokenizer, no engine deps).
- **Expected pip warnings:** pip reports "dependency conflicts" against - **Expected pip warnings:** pip reports "dependency conflicts" against
semif-phase1's declared requirements (torch/accelerate/protobuf/sentencepiece semif-phase1's declared requirements (torch/accelerate/protobuf/sentencepiece
not installed, numpy 2.2.6 vs 2.3.5). These are informational — the staging not installed, numpy 2.2.6 vs 2.3.5). These are informational — the staging
@@ -971,7 +998,8 @@ CLI, unit tests (24) + integration tests (2).
a checkout (register its SSH key on your git host first), then run a checkout (register its SSH key on your git host first), then run
`scripts/bootstrap.sh`. On a fresh machine it runs the **setup interview** `scripts/bootstrap.sh`. On a fresh machine it runs the **setup interview**
(`semif_agent/setup.py`, the `cli setup` subcommand) and writes the split (`semif_agent/setup.py`, the `cli setup` subcommand) and writes the split
config from the answers — decision engine (local SemIf 4B or remote Winnow), config from the answers — decision engine (local SemIf 4B, remote Winnow, or
an Ollama System One decision model),
new-skill authoring mode (+ `llm`/`codegen` endpoints when enabled), capability new-skill authoring mode (+ `llm`/`codegen` endpoints when enabled), capability
packs, gateways, and timezone — then installs only what those answers require packs, gateways, and timezone — then installs only what those answers require
(the install *plan* drives every conditional stage). Which packs exist is owned (the install *plan* drives every conditional stage). Which packs exist is owned
+13 -6
View File
@@ -445,13 +445,18 @@ what it needs, based on the answers to a short first-run interview.
### Prerequisites: the decision engine, and optional models ### Prerequisites: the decision engine, and optional models
The **decision engine** routes every request. It runs one of two ways, chosen in The **decision engine** routes every request. It runs one of three ways,
the interview: chosen in the interview:
- **local** — the pinned SemIf 4B GGUF via llama.cpp (no network). This is the - **local** — the pinned SemIf 4B GGUF via llama.cpp (no network). This is the
default and the whole minimum path. default and the whole minimum path.
- **remote** — a Winnow `/v1/systemone` decision server (`engine.provider == - **remote** — a Winnow `/v1/systemone` decision server (`engine.provider ==
"winnow"`). The local engine clone, GGUF, and tokenizer are then skipped. "winnow"`). The local engine clone, GGUF, and tokenizer are then skipped.
- **remote Ollama** — ollama's native System One `/v1/systemone` route
(`engine.provider == "ollama"`) against a pulled decision model. It probes
ollama's `/api/version` + `/api/show`, follows the model's real `num_ctx`, and
skips the local engine clone/GGUF/tokenizer too. System One models do not
generate text, so this provider cannot back `llm.provider == "semif"`.
The local engine is CPU by default; to offload it to a GPU, set The local engine is CPU by default; to offload it to a GPU, set
`engine.gpu_layers` in `config.json` and run `engine.gpu_layers` in `config.json` and run
@@ -467,7 +472,8 @@ shipped packs. When it is on, two OpenAI-compatible endpoints are required
newly created category/skill. Its `provider` can be `"ollama"` (default), newly created category/skill. Its `provider` can be `"ollama"` (default),
`"opencode"` (the hosted Console API), or `"semif"` — the already-loaded `"opencode"` (the hosted Console API), or `"semif"` — the already-loaded
decision engine model generates in-process, with no endpoint and no decision engine model generates in-process, with no endpoint and no
`llm.model` at all. `llm.model` at all (the local SemIf or Winnow engine only; an Ollama
System One decision model does not generate text).
- **`codegen`** — a large, code-capable model that writes skill bodies. This is - **`codegen`** — a large, code-capable model that writes skill bodies. This is
slow and ideally on a beefier host. slow and ideally on a beefier host.
@@ -482,7 +488,8 @@ scripts/bootstrap.sh
On a fresh machine the script **asks a few questions** and writes this machine's On a fresh machine the script **asks a few questions** and writes this machine's
config from the answers: config from the answers:
1. **Decision engine** — local SemIf 4B, or a remote Winnow server (URL/model/key). 1. **Decision engine** — local SemIf 4B, a remote Winnow server, or a remote
Ollama System One decision model (URL/model/key).
2. **Skill authoring** — `deny` (default), `ask`, or `allow`; if enabled, the 2. **Skill authoring** — `deny` (default), `ask`, or `allow`; if enabled, the
`llm` + `codegen` endpoints and credentials. `llm` + `codegen` endpoints and credentials.
3. **Capabilities** — the skill packs to enable, offered from the pack index 3. **Capabilities** — the skill packs to enable, offered from the pack index
@@ -498,8 +505,8 @@ are reachable by the end of a run:
- **minimum** — local SemIf 4B + `essentials` (canned replies, time/timers, - **minimum** — local SemIf 4B + `essentials` (canned replies, time/timers,
calculator, skill listing). No account, no network, no gateway, no heavy calculator, skill listing). No account, no network, no gateway, no heavy
downloads. downloads.
- **maximum** — every pack, a remote Winnow engine, remote `llm`/`codegen` - **maximum** — every pack, a remote Winnow or Ollama System One decision
endpoints, and all gateways. engine, remote `llm`/`codegen` endpoints, and all gateways.
Non-interactive runs: `--yes` takes the minimum defaults; `--answers FILE` Non-interactive runs: `--yes` takes the minimum defaults; `--answers FILE`
replays a saved answer set (JSON matching the `setup` fields). The script is replays a saved answer set (JSON matching the `setup` fields). The script is
+11
View File
@@ -39,6 +39,17 @@
"user_agent": "semif-agent", "user_agent": "semif-agent",
"extra_headers": {} "extra_headers": {}
}, },
"ollama": {
"base_url": "http://127.0.0.1:11434",
"model": "",
"context_tokens": 16384,
"api_key": "!secret engine_ollama_api_key",
"timeout": 120,
"retries": 0,
"keep_alive": "",
"user_agent": "semif-agent",
"extra_headers": {}
},
"gguf": "" "gguf": ""
}, },
"llm": { "llm": {
+28 -5
View File
@@ -41,6 +41,7 @@ from .console import (
) )
from .decisions import DecisionRequest, Option from .decisions import DecisionRequest, Option
from .engine import DecisionEngine, EngineConfig, EngineUnavailable, SemIfEngine from .engine import DecisionEngine, EngineConfig, EngineUnavailable, SemIfEngine
from .ollama_systemone import OllamaSystemOneConfig, OllamaSystemOneEngine
from .winnow import WinnowConfig, WinnowEngine from .winnow import WinnowConfig, WinnowEngine
from .llm import LLMClient, SemIfLLMClient from .llm import LLMClient, SemIfLLMClient
from .log import DecisionLog from .log import DecisionLog
@@ -54,6 +55,7 @@ from .trace import TraceLog
REPO_ROOT = Path(__file__).resolve().parent.parent REPO_ROOT = Path(__file__).resolve().parent.parent
DEFAULT_WINNOW_URL = "http://127.0.0.1:8091" DEFAULT_WINNOW_URL = "http://127.0.0.1:8091"
DEFAULT_OLLAMA_SYSTEMONE_URL = "http://127.0.0.1:11434"
_PATH_KEYS = ( _PATH_KEYS = (
"skill_packs", "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 * ``"semif"`` (default) — the local llama.cpp GGUF (`SemIfEngine`), built
from the per-machine `engine` knobs + the pinned refs in pins.json. 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 (`WinnowEngine`), configured by the nested `engine.winnow` block
(`base_url`/`model`/`api_key`/`timeout`/`retries`). (`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 The engine is always real: a provider that cannot be reached raises
`EngineUnavailable` at call time, which the scheduler treats as fatal. The `EngineUnavailable` at call time, which the scheduler treats as fatal. The
`winnow` model is required (no default) exactly as `llm.model`/`codegen.model` `winnow` and `ollama` models are required (no default) exactly as
are, so a misconfigured endpoint fails as an actionable config error. `llm.model`/`codegen.model` are, so a misconfigured endpoint fails as an
actionable config error.
""" """
eng = config.get("engine", {}) or {} eng = config.get("engine", {}) or {}
provider = str(eng.get("provider", "semif") or "semif").lower() 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"), 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)) return SemIfEngine(build_engine_config(config, pins))
@@ -1164,8 +1187,8 @@ def main(argv: list[str] | None = None) -> int:
formatter_class=argparse.RawDescriptionHelpFormatter, formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=( epilog=(
"answers JSON fields (all optional; --answers FILE):\n" "answers JSON fields (all optional; --answers FILE):\n"
" engine_provider (semif|winnow), winnow_base_url, winnow_model,\n" " engine_provider (semif|winnow|ollama), winnow_base_url, winnow_model,\n"
" winnow_api_key\n" " winnow_api_key, ollama_base_url, ollama_model, ollama_api_key\n"
" new_skill_creation (deny|ask|allow)\n" " new_skill_creation (deny|ask|allow)\n"
" llm_provider (semif|ollama|opencode|openai), llm_base_url,\n" " llm_provider (semif|ollama|opencode|openai), llm_base_url,\n"
" llm_model, llm_api_key\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'}, 'retries': {'default': 0, 'type': 'int'},
'user_agent': {'default': 'semif-agent', 'type': 'str'}, 'user_agent': {'default': 'semif-agent', 'type': 'str'},
'extra_headers': {'default': {}, 'type': 'dict'}}, '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'}}, 'gguf': {'default': '', 'type': 'str'}},
'llm': {'provider': {'default': 'ollama', 'type': 'str'}, 'llm': {'provider': {'default': 'ollama', 'type': 'str'},
'base_url': {'default': 'http://localhost:11434/v1', '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 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 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 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 from __future__ import annotations
@@ -40,8 +42,11 @@ class DecisionEngine(ABC):
`llm.provider` / `codegen.provider`: `llm.provider` / `codegen.provider`:
* ``"semif"`` (default) — the local llama.cpp GGUF (`SemIfEngine`). * ``"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`). (`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 The engine is always real: any failure to produce a decision raises
`EngineUnavailable`, which the scheduler treats as fatal. `generate` is the `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. #: ``llm``/``codegen`` providers the wizard can emit.
PROVIDERS = ("semif", "ollama", "opencode", "openai") PROVIDERS = ("semif", "ollama", "opencode", "openai")
#: ``engine`` providers. #: ``engine`` providers.
ENGINE_PROVIDERS = ("semif", "winnow") ENGINE_PROVIDERS = ("semif", "winnow", "ollama")
#: New-skill creation modes. #: New-skill creation modes.
AUTHORING_MODES = ("deny", "ask", "allow") AUTHORING_MODES = ("deny", "ask", "allow")
@@ -71,10 +71,14 @@ class Answers:
"""The wizard's answers, and the source of truth for the generated config.""" """The wizard's answers, and the source of truth for the generated config."""
# Decision engine. # Decision engine.
engine_provider: str = "semif" # semif | winnow engine_provider: str = "semif" # semif | winnow | ollama
winnow_base_url: str = "" winnow_base_url: str = ""
winnow_model: str = "" winnow_model: str = ""
winnow_api_key: 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 authoring: deny | ask | allow.
new_skill_creation: str = "deny" new_skill_creation: str = "deny"
@@ -351,7 +355,7 @@ def run_interview(
output( output(
" The decision engine routes every request. It runs locally on the\n" " 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" " 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( answers.engine_provider = _ask_choice(
input_fn, input_fn,
@@ -360,6 +364,7 @@ def run_interview(
[ [
("semif", "local SemIf 4B (llama.cpp, pinned GGUF)"), ("semif", "local SemIf 4B (llama.cpp, pinned GGUF)"),
("winnow", "remote Winnow decision server"), ("winnow", "remote Winnow decision server"),
("ollama", "remote Ollama System One model (/v1/systemone)"),
], ],
1, 1,
) )
@@ -376,6 +381,25 @@ def run_interview(
answers.winnow_api_key = _ask_text( answers.winnow_api_key = _ask_text(
input_fn, output, " winnow API key (blank for none)", "", secret=True 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. # 2. Skill authoring.
output("") output("")
@@ -399,7 +423,15 @@ def run_interview(
answers.new_skill_creation = mode answers.new_skill_creation = mode
if mode != "deny": if mode != "deny":
output("") 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("") output("")
_collect_llm(input_fn, output, answers, label="codegen", allow_semif=False) _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( _set_secret_or_literal(
winnow, "api_key", answers.winnow_api_key, "engine_winnow_api_key" 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. # Authoring mode.
config["new_skill_creation"] = answers.new_skill_creation config["new_skill_creation"] = answers.new_skill_creation
@@ -613,6 +653,8 @@ def build_secrets(answers: Answers) -> dict:
secrets: dict[str, str] = {} secrets: dict[str, str] = {}
if answers.engine_provider == "winnow" and answers.winnow_api_key: if answers.engine_provider == "winnow" and answers.winnow_api_key:
secrets["engine_winnow_api_key"] = 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: if answers.llm_provider != "semif" and answers.llm_api_key:
secrets["llm_api_key"] = answers.llm_api_key secrets["llm_api_key"] = answers.llm_api_key
if answers.codegen_api_key: if answers.codegen_api_key:
@@ -834,7 +876,11 @@ def _print_summary(answers: Answers, output: Callable[[str], None]) -> None:
+ ( + (
"local SemIf 4B" "local SemIf 4B"
if answers.engine_provider == "semif" 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}") 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 and the question becomes its ``instructions``; the server returns a probability
over exactly those keys. over exactly those keys.
Winnow runs as its own process (``winnow-server``); see ``local/ENVIRONMENT.md`` It works against any server implementing that route: the reference
for this deployment. The engine is real: any network, HTTP, or distribution ``winnow-server``, or an OpenAI-compatible host (ollama 0.40+) serving a
failure raises `EngineUnavailable`, which the scheduler treats as fatal — there ``decision`` model such as ``clef-flash``. See ``local/ENVIRONMENT.md`` for this
is no fallback model and no fabricated reply. 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 from __future__ import annotations
@@ -24,7 +26,7 @@ import urllib.error
import urllib.request import urllib.request
from dataclasses import dataclass from dataclasses import dataclass
from .decisions import DecisionRequest, DecisionResult from .decisions import DecisionRequest, DecisionResult, Option
from .engine import DecisionEngine, EngineUnavailable from .engine import DecisionEngine, EngineUnavailable
+30
View File
@@ -19,6 +19,7 @@ from semif_agent.engine import (
_install_gpu_state_reset, _install_gpu_state_reset,
_offloading_params, _offloading_params,
) )
from semif_agent.ollama_systemone import OllamaSystemOneEngine
from semif_agent.winnow import WinnowEngine from semif_agent.winnow import WinnowEngine
PINS = { PINS = {
@@ -111,3 +112,32 @@ def test_build_engine_selects_the_winnow_provider():
def test_build_engine_winnow_requires_a_model(): def test_build_engine_winnow_requires_a_model():
with pytest.raises(SystemExit): with pytest.raises(SystemExit):
build_engine({"engine": {"provider": "winnow", "winnow": {}}}, PINS) build_engine({"engine": {"provider": "winnow", "winnow": {}}}, PINS)
def test_build_engine_selects_the_ollama_systemone_provider():
engine = build_engine(
{
"engine": {
"provider": "ollama",
"ollama": {
"base_url": "http://example:11434",
"model": "clef-flash",
"context_tokens": 8192,
"keep_alive": "5m",
},
}
},
PINS,
)
assert isinstance(engine, OllamaSystemOneEngine)
assert isinstance(engine, DecisionEngine)
assert engine.label == "ollama"
assert engine.config.base_url == "http://example:11434"
assert engine.config.model == "clef-flash"
assert engine.context_tokens == 8192
assert engine.config.keep_alive == "5m"
def test_build_engine_ollama_requires_a_model():
with pytest.raises(SystemExit):
build_engine({"engine": {"provider": "ollama", "ollama": {}}}, PINS)
+336
View File
@@ -0,0 +1,336 @@
"""Pure-stdlib tests for the Ollama System One decision engine provider.
The engine is exercised over a real loopback HTTP server (the transport is not
mocked): the handler records requests and returns canned ollama
``/api/version``, ``/api/show``, and ``/v1/systemone`` responses, so the tests
prove the decision-contract mapping, the ollama-specific probing, and the strict
distribution validation. No model, no GGUF, no external network.
"""
from __future__ import annotations
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
from semif_agent.decisions import DecisionRequest, Option
from semif_agent.engine import EngineUnavailable
from semif_agent.ollama_systemone import OllamaSystemOneConfig, OllamaSystemOneEngine
class _Handler(BaseHTTPRequestHandler):
def log_message(self, *args): # keep the test output quiet
pass
def _read(self) -> dict:
length = int(self.headers.get("content-length", 0) or 0)
raw = self.rfile.read(length) if length else b"{}"
return json.loads(raw or b"{}")
def _send(self, status: int, payload: dict) -> None:
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("content-type", "application/json")
self.send_header("content-length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
self.server.state.setdefault("gets", []).append(self.path)
if self.path == "/api/version":
self._send(
self.server.state.get("version_status", 200),
{"version": "0.40.13"},
)
else:
self._send(404, {"error": "not found"})
def do_POST(self):
body = self._read()
self.server.state.setdefault("requests", []).append(
(self.path, body, {k.lower(): v for k, v in self.headers.items()})
)
if self.path == "/api/show":
status = self.server.state.get("show_status", 200)
response = self.server.state.get("show_response")
if response is None:
response = _default_show()
self._send(status, response)
elif self.path == "/v1/systemone":
status = self.server.state.get("systemone_status", 200)
response = self.server.state.get("systemone_response")
if response is None:
response = _default_systemone(body)
self._send(status, response)
else:
self._send(404, {"error": "not found"})
def _default_show() -> dict:
return {
"model": "clef-flash",
"parameters": "num_ctx 16384",
"capabilities": ["decision"],
"model_info": {"clef.context_length": 262144},
}
def _default_systemone(body: dict) -> dict:
criteria = body["questions"]["decision"]["criteria"]
keys = list(criteria)
probs = {
key: (0.9 if index == 0 else 0.1 / max(len(keys) - 1, 1))
for index, key in enumerate(keys)
}
# Return the keys in REVERSE order to prove the engine aligns by id, not by
# position in the returned object.
return {
"model": "clef-flash",
"answers": {
"decision": {
"type": "choice",
"choice": keys[0],
"probabilities": dict(reversed(list(probs.items()))),
"confidence": 0.8,
}
},
"usage": {"input_tokens": 42, "output_tokens": 1},
}
@pytest.fixture()
def ollama():
server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
server.state = {}
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
base = f"http://127.0.0.1:{server.server_address[1]}"
yield server, base
server.shutdown()
server.server_close()
def _engine(base: str, **cfg) -> OllamaSystemOneEngine:
return OllamaSystemOneEngine(
OllamaSystemOneConfig(base_url=base, model="clef-flash", timeout=5.0, **cfg)
)
def _decision(*option_ids: str) -> DecisionRequest:
return DecisionRequest(
state="the user said hello",
question="Which category handles this request?",
options=[Option(oid, f"description for {oid}") for oid in option_ids],
)
def test_call_maps_decision_to_a_choice_question(ollama):
server, base = ollama
result = _engine(base).call(_decision("response", "calendar"))
assert result.option_ids == ["response", "calendar"]
assert result.prob("response") == pytest.approx(0.9)
assert result.prob("calendar") == pytest.approx(0.1)
assert result.selected == "response"
assert result.extra["input_tokens"] == 42
assert result.extra["choice"] == "response"
assert result.extra["confidence"] == 0.8
assert result.extra["served_model"] == "clef-flash"
path, body, _ = server.state["requests"][-1]
assert path == "/v1/systemone"
assert body["model"] == "clef-flash"
assert body["state"] == "the user said hello"
question = body["questions"]["decision"]
assert question["type"] == "choice"
assert question["instructions"] == "Which category handles this request?"
assert question["criteria"] == {
"response": "description for response",
"calendar": "description for calendar",
}
# keep_alive is omitted unless configured.
assert "keep_alive" not in body
def test_call_sends_a_configured_keep_alive(ollama):
server, base = ollama
_engine(base, keep_alive="5m").call(_decision("a", "b"))
_, body, _ = server.state["requests"][-1]
assert body["keep_alive"] == "5m"
def test_call_sends_null_for_a_bare_label(ollama):
server, base = ollama
request = DecisionRequest(
state="state",
question="question",
options=[Option("a", ""), Option("b", " ")],
)
_engine(base).call(request)
_, body, _ = server.state["requests"][-1]
assert body["questions"]["decision"]["criteria"] == {"a": None, "b": None}
def test_call_normalizes_an_unnormalized_distribution(ollama):
server, base = ollama
server.state["systemone_response"] = {
"answers": {"decision": {"type": "choice", "probabilities": {"a": 0.4, "b": 0.4}}}
}
result = _engine(base).call(_decision("a", "b"))
assert result.probs == pytest.approx({"a": 0.5, "b": 0.5})
def test_call_rejects_mismatched_probability_keys(ollama):
server, base = ollama
server.state["systemone_response"] = {
"answers": {"decision": {"type": "choice", "probabilities": {"a": 1.0}}}
}
with pytest.raises(EngineUnavailable):
_engine(base).call(_decision("a", "b"))
def test_call_rejects_a_choice_outside_the_requested_options(ollama):
server, base = ollama
server.state["systemone_response"] = {
"answers": {
"decision": {
"type": "choice",
"choice": "other",
"probabilities": {"a": 0.8, "b": 0.2},
}
}
}
with pytest.raises(EngineUnavailable):
_engine(base).call(_decision("a", "b"))
def test_call_rejects_all_zero_distribution(ollama):
server, base = ollama
server.state["systemone_response"] = {
"answers": {"decision": {"type": "choice", "probabilities": {"a": 0.0, "b": 0.0}}}
}
with pytest.raises(EngineUnavailable):
_engine(base).call(_decision("a", "b"))
def test_call_rejects_out_of_range_probability(ollama):
server, base = ollama
server.state["systemone_response"] = {
"answers": {"decision": {"type": "choice", "probabilities": {"a": 1.5, "b": 0.5}}}
}
with pytest.raises(EngineUnavailable):
_engine(base).call(_decision("a", "b"))
def test_call_rejects_http_error_with_the_ollama_error_body(ollama):
server, base = ollama
server.state["systemone_status"] = 400
with pytest.raises(EngineUnavailable, match="400"):
_engine(base).call(_decision("a", "b"))
def test_call_rejects_missing_answer(ollama):
server, base = ollama
server.state["systemone_response"] = {"answers": {}}
with pytest.raises(EngineUnavailable):
_engine(base).call(_decision("a", "b"))
def test_call_requires_at_least_two_options(ollama):
_, base = ollama
with pytest.raises(EngineUnavailable):
_engine(base).call(_decision("a"))
def test_call_requires_a_non_empty_state(ollama):
_, base = ollama
request = DecisionRequest(
state=" ",
question="q",
options=[Option("a", "a"), Option("b", "b")],
)
with pytest.raises(EngineUnavailable):
_engine(base).call(request)
def test_call_sends_bearer_token(ollama):
server, base = ollama
_engine(base, api_key="secret").call(_decision("a", "b"))
_, _, headers = server.state["requests"][-1]
assert headers.get("authorization") == "Bearer secret"
def test_generate_is_unavailable(ollama):
_, base = ollama
with pytest.raises(EngineUnavailable):
_engine(base).generate([{"role": "user", "content": "hi"}])
def test_warm_probes_ollama_native_endpoints_and_marks_loaded(ollama):
server, base = ollama
engine = _engine(base, context_tokens=0)
assert engine.loaded is False
engine.warm()
assert engine.loaded is True
assert "/api/version" in server.state["gets"]
assert [path for path, _, _ in server.state["requests"]] == ["/api/show"]
# context_tokens=0 follows the model's real num_ctx from /api/show.
assert engine.context_tokens == 16384
def test_warm_falls_back_to_the_architecture_context_length(ollama):
server, base = ollama
server.state["show_response"] = {
"capabilities": ["decision"],
"parameters": "",
"model_info": {"clef.context_length": 8192},
}
engine = _engine(base, context_tokens=0)
engine.warm()
assert engine.context_tokens == 8192
def test_warm_keeps_an_explicit_context_window(ollama):
server, base = ollama
engine = _engine(base, context_tokens=4096)
engine.warm()
assert engine.context_tokens == 4096
def test_warm_rejects_a_model_without_the_decision_capability(ollama):
server, base = ollama
server.state["show_response"] = {
"capabilities": ["completion", "thinking"],
"parameters": "num_ctx 4096",
}
with pytest.raises(EngineUnavailable, match="decision"):
_engine(base).warm()
def test_warm_rejects_a_missing_model(ollama):
server, base = ollama
server.state["show_status"] = 404
with pytest.raises(EngineUnavailable):
_engine(base).warm()
def test_warm_rejects_an_unreachable_server():
engine = OllamaSystemOneEngine(
OllamaSystemOneConfig(
base_url="http://127.0.0.1:1", model="clef-flash", timeout=1.0
)
)
with pytest.raises(EngineUnavailable):
engine.warm()
def test_unreachable_endpoint_raises_engine_unavailable():
engine = OllamaSystemOneEngine(
OllamaSystemOneConfig(
base_url="http://127.0.0.1:1", model="clef-flash", timeout=1.0
)
)
with pytest.raises(EngineUnavailable):
engine.call(_decision("a", "b"))
+17
View File
@@ -152,6 +152,23 @@ def test_maximum_config_enables_everything():
assert "llm_api_key" not in secrets assert "llm_api_key" not in secrets
def test_ollama_engine_answers_emit_the_ollama_block():
answers = Answers(
engine_provider="ollama",
ollama_base_url="http://10.0.0.9:11434",
ollama_model="clef-flash",
ollama_api_key="ok",
)
config = build_config(answers, _packs())
assert config["engine"]["provider"] == "ollama"
assert config["engine"]["ollama"]["base_url"] == "http://10.0.0.9:11434"
assert config["engine"]["ollama"]["model"] == "clef-flash"
assert config["engine"]["ollama"]["api_key"] == "!secret engine_ollama_api_key"
assert validate_config(config, _packs()) == []
assert build_plan(answers, _packs())["install_engine"] is False
assert build_secrets(answers)["engine_ollama_api_key"] == "ok"
def test_simplex_gateway_without_pack_still_needs_the_binary(): def test_simplex_gateway_without_pack_still_needs_the_binary():
answers = Answers(gateways=["simplex"]) answers = Answers(gateways=["simplex"])
plan = build_plan(answers, _packs()) plan = build_plan(answers, _packs())