llm: add the loaded semif engine as a text-generation provider
Restore SemIfEngine.generate (autoregressive sampling from the loaded llama.cpp context) and wrap it in provider.SemIfEngineClient, a non-HTTP sibling of OpenAICompatClient with the same chat() surface. llm.SemIfLLMClient keeps the LLMError contract so the scheduler's graceful draft_failed path and the LLM bridge's 502 path are unchanged. llm.provider now selects "semif" (the in-process decision model, no endpoint or model needed), "opencode", or the default "ollama"; build_llm_client owns the choice (build_scheduler delegates). Knobs live under llm.semif (temperature 0 = greedy, max_tokens). bootstrap skips the ollama llm warn/pull/probe when provider is semif. Only the llm task supports it; codegen still needs a real code model.
This commit is contained in:
1 parent
1dc0550659
commit
e426998cf7
9 files changed
+305
-26
No files matched your search
@@ -143,7 +143,10 @@ timers.py in-process timer/alarm service (TimerService) owned by the
|
|||||||
the gateway routes it to the originating chat, the dashboard
|
the gateway routes it to the originating chat, the dashboard
|
||||||
shows pending/fired). Real local compute (`compute` transport),
|
shows pending/fired). Real local compute (`compute` transport),
|
||||||
per-process, and deliberately NOT persisted across restarts.
|
per-process, and deliberately NOT persisted across restarts.
|
||||||
engine.py SemIfEngine -> semif_phase1.llamacpp_backend (lazy import)
|
engine.py SemIfEngine -> semif_phase1.llamacpp_backend (lazy import);
|
||||||
|
call() scores a decision, generate() autoregressively samples
|
||||||
|
text from the same loaded model (shares the engine lock, clears
|
||||||
|
the KV cache) — backs the `semif` llm provider
|
||||||
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
|
||||||
@@ -169,12 +172,16 @@ llm.py small OpenAI-compatible provider (LLMClient) that authors a
|
|||||||
new category/skill title + description — its own endpoint/model,
|
new category/skill title + description — its own endpoint/model,
|
||||||
deliberate separate from codegen; provider logic (SSE/budget/idle)
|
deliberate separate from codegen; provider logic (SSE/budget/idle)
|
||||||
is shared from provider.py; `_parse_json` is also borrowed by the
|
is shared from provider.py; `_parse_json` is also borrowed by the
|
||||||
authoring parsers
|
authoring parsers; SemIfLLMClient serves the same `llm` task from
|
||||||
|
the loaded SemIf engine model (llm.provider == "semif")
|
||||||
provider.py shared OpenAI-compatible chat transport (OpenAICompatClient:
|
provider.py shared OpenAI-compatible chat transport (OpenAICompatClient:
|
||||||
SSE stream, token budget, idle watchdog, degeneration hook,
|
SSE stream, token budget, idle watchdog, degeneration hook,
|
||||||
optional `api_key` bearer auth + `extra_headers`/`user_agent`,
|
optional `api_key` bearer auth + `extra_headers`/`user_agent`,
|
||||||
and `query_context` to skip the ollama /api/show probe)
|
and `query_context` to skip the ollama /api/show probe)
|
||||||
subclassed by llm.LLMClient and codegen.CodegenClient
|
subclassed by llm.LLMClient and codegen.CodegenClient;
|
||||||
|
SemIfEngineClient is the non-HTTP sibling that generates text
|
||||||
|
from the in-process SemIf engine behind the same `chat(...)`
|
||||||
|
surface (llm.provider == "semif")
|
||||||
console.py OpenCode Console provider: OpenCodeConsoleClient + the
|
console.py OpenCode Console provider: OpenCodeConsoleClient + the
|
||||||
ConsoleLLMClient / ConsoleCodegenClient endpoint subclasses.
|
ConsoleLLMClient / ConsoleCodegenClient endpoint subclasses.
|
||||||
Hosted, authenticated OpenAI-compatible Chat Completions API
|
Hosted, authenticated OpenAI-compatible Chat Completions API
|
||||||
@@ -183,7 +190,8 @@ console.py OpenCode Console provider: OpenCodeConsoleClient + the
|
|||||||
urllib's default Python-urllib/<ver>), and forces
|
urllib's default Python-urllib/<ver>), and forces
|
||||||
disable_thinking off (the gateway 400s reasoning_effort).
|
disable_thinking off (the gateway 400s reasoning_effort).
|
||||||
Selected via the llm/codegen `provider` key
|
Selected via the llm/codegen `provider` key
|
||||||
("opencode" vs "ollama").
|
("opencode" vs "ollama"; `llm` also accepts "semif", the
|
||||||
|
in-process engine model).
|
||||||
log.py decisions.jsonl rows {state, question, options, predicted_probs,
|
log.py decisions.jsonl rows {state, question, options, predicted_probs,
|
||||||
selected, observed_outcome, label_source}
|
selected, observed_outcome, label_source}
|
||||||
trace.py runs.jsonl lifecycle events keyed by run_id (submit/queued/
|
trace.py runs.jsonl lifecycle events keyed by run_id (submit/queued/
|
||||||
@@ -675,6 +683,21 @@ CLI, unit tests (24) + integration tests (2).
|
|||||||
larger/slower than `llm`). Title + description for new skills come from the
|
larger/slower than `llm`). Title + description for new skills come from the
|
||||||
separate small `llm` provider (its own endpoint/model, shared transport in
|
separate small `llm` provider (its own endpoint/model, shared transport in
|
||||||
`provider.py`); only the runnable code body uses codegen.
|
`provider.py`); only the runnable code body uses codegen.
|
||||||
|
- **Local engine as the `llm` provider: `"semif"`** (`provider.SemIfEngineClient`
|
||||||
|
+ `llm.SemIfLLMClient`). Set `llm.provider = "semif"` to generate the
|
||||||
|
title/description (and any other `llm` text: gateway result cleanup, the LLM
|
||||||
|
bridge) from the **already-loaded SemIf decision model** in-process, with no
|
||||||
|
ollama endpoint and no `llm.model` — the pinned GGUF is the model. `engine.
|
||||||
|
SemIfEngine.generate` autoregressively samples through the backend's low-level
|
||||||
|
llama.cpp context (chat template with `enable_thinking=False`, KV cache
|
||||||
|
cleared), holding the same lock as `call`, so a reply briefly serializes
|
||||||
|
against routing/assessment on the one loaded model. The adapter is a drop-in
|
||||||
|
sibling of `OpenAICompatClient` (same `chat(messages, max_tokens=...,
|
||||||
|
temperature=..., ...)` surface; HTTP-only args accepted and ignored) and
|
||||||
|
raises `LLMError` on any engine failure, so the scheduler's graceful
|
||||||
|
`draft_failed` path and the LLM bridge's 502 path are unchanged. Knobs:
|
||||||
|
`llm.semif.temperature` (0 = greedy) and `llm.semif.max_tokens`. Only the
|
||||||
|
`llm` task supports it (codegen still needs a real code model).
|
||||||
- **Alternate hosted provider: OpenCode Console** (`console.py`). Either
|
- **Alternate hosted provider: OpenCode Console** (`console.py`). Either
|
||||||
endpoint can run against the hosted, authenticated OpenAI-compatible Console
|
endpoint can run against the hosted, authenticated OpenAI-compatible Console
|
||||||
inference API instead of local ollama: set `llm.provider` / `codegen.provider`
|
inference API instead of local ollama: set `llm.provider` / `codegen.provider`
|
||||||
|
|||||||
@@ -367,9 +367,12 @@ semif_agent/
|
|||||||
create gates, intent guard, tiered config resolution
|
create gates, intent guard, tiered config resolution
|
||||||
codegen.py OpenAI-compatible client; body/elicitation/test generation;
|
codegen.py OpenAI-compatible client; body/elicitation/test generation;
|
||||||
parse/validate; CONTRACT + INTEGRATION extraction; test runner
|
parse/validate; CONTRACT + INTEGRATION extraction; test runner
|
||||||
provider.py shared OpenAI-compatible transport (SSE/budget/idle/watchdog)
|
provider.py shared OpenAI-compatible transport (SSE/budget/idle/watchdog);
|
||||||
engine.py SemIfEngine -> semif_phase1.llamacpp_backend (lazy import)
|
SemIfEngineClient generates text from the in-process engine
|
||||||
llm.py small OpenAI-compatible provider; authors new title + description
|
engine.py SemIfEngine -> semif_phase1.llamacpp_backend (lazy import);
|
||||||
|
call() scores, generate() samples text
|
||||||
|
llm.py small provider; authors new title + description
|
||||||
|
(ollama / opencode / the loaded engine via `semif`)
|
||||||
log.py decisions.jsonl rows {state, question, options, probs, ...}
|
log.py decisions.jsonl rows {state, question, options, probs, ...}
|
||||||
trace.py runs.jsonl lifecycle events keyed by run_id
|
trace.py runs.jsonl lifecycle events keyed by run_id
|
||||||
dream.py NLL / weighted CE / accuracy / ECE cost report
|
dream.py NLL / weighted CE / accuracy / ECE cost report
|
||||||
@@ -414,7 +417,10 @@ machines:
|
|||||||
newly created category/skill. Deliberately its own endpoint/model, so it can
|
newly created category/skill. Deliberately its own endpoint/model, so it can
|
||||||
stay local even when `codegen` is remote; it uses the same provider transport
|
stay local even when `codegen` is remote; it uses the same provider transport
|
||||||
(`provider.py`) and an unreachable endpoint is graceful (the request is not
|
(`provider.py`) and an unreachable endpoint is graceful (the request is not
|
||||||
re-dispatched), never fatal.
|
re-dispatched), never fatal. Its `provider` can be `"ollama"` (default),
|
||||||
|
`"opencode"` (the hosted Console API), or `"semif"` — the already-loaded
|
||||||
|
decision engine model generates in-process, with no endpoint and no
|
||||||
|
`llm.model` at all (see the `llm.semif` block in `config.json`).
|
||||||
|
|
||||||
The **decision engine is separate** and runs via llama.cpp CPU (or Vulkan if your
|
The **decision engine is separate** and runs via llama.cpp CPU (or Vulkan if your
|
||||||
build enables it), not ollama.
|
build enables it), not ollama.
|
||||||
|
|||||||
+7
-2
@@ -18,7 +18,7 @@
|
|||||||
"threads": 8
|
"threads": 8
|
||||||
},
|
},
|
||||||
"llm": {
|
"llm": {
|
||||||
"_comment": "Small OpenAI-compatible model that authors a new category/skill title + description (never the runnable body — that is `codegen` below). Deliberately its own endpoint/model, so it can be local and fast even when codegen is remote. Runs on THIS machine's local ollama; bootstrap reads base_url/model from here (a --llm-url/--llm-model flag overrides for that run only) and pulls `model` if it is missing. `model` is required (no default): set it to a model the endpoint serves. Uses the same provider machinery as codegen (real SSE stream, token budget, idle watchdog); short JSON replies. Sampler params (temperature/top_p/presence_penalty/frequency_penalty) are opt-in: an unset value is omitted from the request so the server's model default applies — set them here only when you know the right values for the model. The draft is authored asynchronously by a single-slot worker and the request re-runs when it lands; an unreachable endpoint is graceful (traced, user notified), not fatal. disable_thinking sends reasoning_effort:none so a reasoning model answers the short JSON directly instead of spending the reply budget on hidden chain-of-thought (set false only for an endpoint that rejects the parameter). provider selects the transport: \"ollama\" (default; a local OpenAI-compatible server, context auto-detected via /api/show) or \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code or glm-5.3, and provide api_key or api_key_env; the ollama probe is skipped).",
|
"_comment": "Small OpenAI-compatible model that authors a new category/skill title + description (never the runnable body — that is `codegen` below). Deliberately its own endpoint/model, so it can be local and fast even when codegen is remote. Runs on THIS machine's local ollama; bootstrap reads base_url/model from here (a --llm-url/--llm-model flag overrides for that run only) and pulls `model` if it is missing. `model` is required (no default): set it to a model the endpoint serves. Uses the same provider machinery as codegen (real SSE stream, token budget, idle watchdog); short JSON replies. Sampler params (temperature/top_p/presence_penalty/frequency_penalty) are opt-in: an unset value is omitted from the request so the server's model default applies — set them here only when you know the right values for the model. The draft is authored asynchronously by a single-slot worker and the request re-runs when it lands; an unreachable endpoint is graceful (traced, user notified), not fatal. disable_thinking sends reasoning_effort:none so a reasoning model answers the short JSON directly instead of spending the reply budget on hidden chain-of-thought (set false only for an endpoint that rejects the parameter). provider selects the transport: \"ollama\" (default; a local OpenAI-compatible server, context auto-detected via /api/show), \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code or glm-5.3, and provide api_key or api_key_env; the ollama probe is skipped), or \"semif\" (the loaded SemIf decision GGUF generates in-process via SemIfEngine.generate — no endpoint/model/api_key is used; see the `semif` block below).",
|
||||||
"provider": "ollama",
|
"provider": "ollama",
|
||||||
"base_url": "http://localhost:11434/v1",
|
"base_url": "http://localhost:11434/v1",
|
||||||
"model": "",
|
"model": "",
|
||||||
@@ -34,7 +34,12 @@
|
|||||||
"top_p": 0.9,
|
"top_p": 0.9,
|
||||||
"presence_penalty": 0.0,
|
"presence_penalty": 0.0,
|
||||||
"frequency_penalty": 0.0,
|
"frequency_penalty": 0.0,
|
||||||
"disable_thinking": true
|
"disable_thinking": true,
|
||||||
|
"semif": {
|
||||||
|
"_comment": "Settings for provider == \"semif\": the already-loaded SemIf engine model generates the text in-process (the same GGUF the decision engine scored with), so no base_url/model/api_key is used and `model` above is not required. temperature 0 = greedy decoding; max_tokens bounds the reply length (callers may override per call). Generation shares the engine's lock with decision scoring, so a reply briefly serializes against routing/assessment.",
|
||||||
|
"temperature": 0.0,
|
||||||
|
"max_tokens": 256
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"codegen": {
|
"codegen": {
|
||||||
"_comment": "OpenAI-compatible model that writes runnable skill bodies. Runs on a REMOTE ollama host (bootstrap reads base_url/model from here; a --codegen-url/--codegen-model flag overrides for that run only); the local small model is `llm` above. `model` is required (no default): set it to a code-capable model the endpoint serves. Bodies perform real actions against the user's configured services via stdlib transports, read every operational value from ctx.config, and declare their integration (INTEGRATION: service/transport/config_vars). Larger/slower than the decision or title/description model. The transport always streams so the client-side token budget (output cap / peak total fill) can abort a runaway in real time; stream only toggles console echo of tokens. timeout is total seconds; idle_warn/idle_timeout surface a silent (wedged) stream. The context window is auto-detected via ollama /api/show; context_window is the manual fallback (0 = auto/default 100000). smart_limit/warn_limit and max_fill_ratio/warn_fill_ratio bound total fill; max_output caps streamed output (>=1 absolute tokens, 0<x<1 fraction of window); chars_per_token converts chars to the token estimate. temperature/top_p/presence_penalty/frequency_penalty are opt-in: an unset value is omitted from the request so the server's model/Modelfile default applies; set them here only when you know the right values for the model. A rejected body retries with a fresh short prompt (max_attempts attempts), reusing the same sampler params. elicitation asks the product owner implementation questions before the body is written (posted to the question queue; every front end defers). After the body lands it is reviewed for real-action fidelity, then the data contract (contract.json) is derived in a separate call, then skill.test.py (hermetic mechanics test: loopback http.server for HTTP bodies, fixtures inline, no external network) in a shared-context call, and the test is auto-run as a subprocess (test_timeout seconds); on failure a 3-option SemIf decision (code/contract/test) regenerates the failing piece, bounded by test_max_attempts. contract_search.enabled auto-populates the skill config.json via SemIf against the global + category config. provider selects the transport: \"ollama\" (default; local OpenAI-compatible server, context auto-detected via /api/show) or \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code, glm-5.3, or deepseek-v4.1-flash, and provide api_key or api_key_env; the ollama probe is skipped).",
|
"_comment": "OpenAI-compatible model that writes runnable skill bodies. Runs on a REMOTE ollama host (bootstrap reads base_url/model from here; a --codegen-url/--codegen-model flag overrides for that run only); the local small model is `llm` above. `model` is required (no default): set it to a code-capable model the endpoint serves. Bodies perform real actions against the user's configured services via stdlib transports, read every operational value from ctx.config, and declare their integration (INTEGRATION: service/transport/config_vars). Larger/slower than the decision or title/description model. The transport always streams so the client-side token budget (output cap / peak total fill) can abort a runaway in real time; stream only toggles console echo of tokens. timeout is total seconds; idle_warn/idle_timeout surface a silent (wedged) stream. The context window is auto-detected via ollama /api/show; context_window is the manual fallback (0 = auto/default 100000). smart_limit/warn_limit and max_fill_ratio/warn_fill_ratio bound total fill; max_output caps streamed output (>=1 absolute tokens, 0<x<1 fraction of window); chars_per_token converts chars to the token estimate. temperature/top_p/presence_penalty/frequency_penalty are opt-in: an unset value is omitted from the request so the server's model/Modelfile default applies; set them here only when you know the right values for the model. A rejected body retries with a fresh short prompt (max_attempts attempts), reusing the same sampler params. elicitation asks the product owner implementation questions before the body is written (posted to the question queue; every front end defers). After the body lands it is reviewed for real-action fidelity, then the data contract (contract.json) is derived in a separate call, then skill.test.py (hermetic mechanics test: loopback http.server for HTTP bodies, fixtures inline, no external network) in a shared-context call, and the test is auto-run as a subprocess (test_timeout seconds); on failure a 3-option SemIf decision (code/contract/test) regenerates the failing piece, bounded by test_max_attempts. contract_search.enabled auto-populates the skill config.json via SemIf against the global + category config. provider selects the transport: \"ollama\" (default; local OpenAI-compatible server, context auto-detected via /api/show) or \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code, glm-5.3, or deepseek-v4.1-flash, and provide api_key or api_key_env; the ollama probe is skipped).",
|
||||||
|
|||||||
+13
-3
@@ -136,7 +136,7 @@ if [[ -z "$SIMPLEX_BIN_URL" || -z "$SIMPLEX_SHA256" ]]; then
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
# --- read per-machine values from config.json (flags override for this run) --
|
# --- read per-machine values from config.json (flags override for this run) --
|
||||||
IFS=$'\x1f' read -r CFG_LLM_URL CFG_LLM_MODEL CFG_CODEGEN_URL CFG_CODEGEN_MODEL \
|
IFS=$'\x1f' read -r CFG_LLM_URL CFG_LLM_MODEL CFG_LLM_PROVIDER CFG_CODEGEN_URL CFG_CODEGEN_MODEL \
|
||||||
SIMPLEX_PORT SIMPLEX_DISPLAY SIMPLEX_FORWARD_PORT SIMPLEX_FORWARD_DISPLAY < <(
|
SIMPLEX_PORT SIMPLEX_DISPLAY SIMPLEX_FORWARD_PORT SIMPLEX_FORWARD_DISPLAY < <(
|
||||||
python3 - "$CONFIG" <<'PY'
|
python3 - "$CONFIG" <<'PY'
|
||||||
import json, sys
|
import json, sys
|
||||||
@@ -148,6 +148,7 @@ def strip_v1(u):
|
|||||||
print("\x1f".join([
|
print("\x1f".join([
|
||||||
strip_v1(cfg.get("llm", {}).get("base_url")),
|
strip_v1(cfg.get("llm", {}).get("base_url")),
|
||||||
str(cfg.get("llm", {}).get("model", "") or ""),
|
str(cfg.get("llm", {}).get("model", "") or ""),
|
||||||
|
str(cfg.get("llm", {}).get("provider", "ollama") or "ollama").lower(),
|
||||||
strip_v1(cfg.get("codegen", {}).get("base_url")),
|
strip_v1(cfg.get("codegen", {}).get("base_url")),
|
||||||
str(cfg.get("codegen", {}).get("model", "") or ""),
|
str(cfg.get("codegen", {}).get("model", "") or ""),
|
||||||
str(s.get("port", "")),
|
str(s.get("port", "")),
|
||||||
@@ -163,6 +164,7 @@ LLM_URL="${LLM_URL:-${CFG_LLM_URL:-http://127.0.0.1:11434}}"
|
|||||||
CODEGEN_URL="${CODEGEN_URL:-$CFG_CODEGEN_URL}"
|
CODEGEN_URL="${CODEGEN_URL:-$CFG_CODEGEN_URL}"
|
||||||
LLM_MODEL="${LLM_MODEL:-$CFG_LLM_MODEL}"
|
LLM_MODEL="${LLM_MODEL:-$CFG_LLM_MODEL}"
|
||||||
CODEGEN_MODEL="${CODEGEN_MODEL:-$CFG_CODEGEN_MODEL}"
|
CODEGEN_MODEL="${CODEGEN_MODEL:-$CFG_CODEGEN_MODEL}"
|
||||||
|
LLM_PROVIDER="${LLM_PROVIDER:-${CFG_LLM_PROVIDER:-ollama}}"
|
||||||
|
|
||||||
if [[ -z "$SIMPLEX_PORT" || -z "$SIMPLEX_FORWARD_PORT" ]]; then
|
if [[ -z "$SIMPLEX_PORT" || -z "$SIMPLEX_FORWARD_PORT" ]]; then
|
||||||
echo "config.json: simplex_chat.port and simplex_chat.forward_port are required" >&2
|
echo "config.json: simplex_chat.port and simplex_chat.forward_port are required" >&2
|
||||||
@@ -178,7 +180,11 @@ with_v1() { local u="${1%/}"; [[ "$u" == */v1 ]] && printf '%s' "$u" || printf '
|
|||||||
LLM_V1="$(with_v1 "$LLM_URL")"
|
LLM_V1="$(with_v1 "$LLM_URL")"
|
||||||
|
|
||||||
echo "== pins: semif @ $SEMIF_REF | gguf sha256 ${GGUF_SHA256:0:12}… | simplex-chat sha256 ${SIMPLEX_SHA256:0:12}…"
|
echo "== pins: semif @ $SEMIF_REF | gguf sha256 ${GGUF_SHA256:0:12}… | simplex-chat sha256 ${SIMPLEX_SHA256:0:12}…"
|
||||||
echo "== llm $LLM_URL (local, model $LLM_MODEL) | codegen $CODEGEN_URL"
|
if [[ "$LLM_PROVIDER" == "semif" ]]; then
|
||||||
|
echo "== llm semif (in-process engine model) | codegen $CODEGEN_URL"
|
||||||
|
else
|
||||||
|
echo "== llm $LLM_URL (local, model $LLM_MODEL) | codegen $CODEGEN_URL"
|
||||||
|
fi
|
||||||
echo "== runtime tree: $RUNTIME"
|
echo "== runtime tree: $RUNTIME"
|
||||||
|
|
||||||
mkdir -p "$RUNTIME" "$MODELS" "$HF_CACHE" "$TOOLDIR" "$SIMPLEX_DB" "$RUNTIME/simplex-forward" "$RUNTIME/lxmf" "$RUNTIME/voice" "$UNITS" "$USER_UNITS"
|
mkdir -p "$RUNTIME" "$MODELS" "$HF_CACHE" "$TOOLDIR" "$SIMPLEX_DB" "$RUNTIME/simplex-forward" "$RUNTIME/lxmf" "$RUNTIME/voice" "$UNITS" "$USER_UNITS"
|
||||||
@@ -430,7 +436,11 @@ echo "== verifying imports"
|
|||||||
|
|
||||||
# The small self-assessment model runs on this machine's local ollama; ensure it
|
# The small self-assessment model runs on this machine's local ollama; ensure it
|
||||||
# is pulled so assess/elicitation/fidelity work without a remote dependency.
|
# is pulled so assess/elicitation/fidelity work without a remote dependency.
|
||||||
if [[ -z "$LLM_MODEL" ]]; then
|
# With llm.provider == "semif" the loaded decision engine generates the text
|
||||||
|
# in-process, so no ollama model/endpoint is involved.
|
||||||
|
if [[ "$LLM_PROVIDER" == "semif" ]]; then
|
||||||
|
echo "== llm provider semif: the loaded engine model generates text in-process (no ollama pull/probe)"
|
||||||
|
elif [[ -z "$LLM_MODEL" ]]; then
|
||||||
echo "WARN: llm.model is not set in config.json — set it (and codegen.model) before starting the agent" >&2
|
echo "WARN: llm.model is not set in config.json — set it (and codegen.model) before starting the agent" >&2
|
||||||
else
|
else
|
||||||
echo "== llm ollama ($LLM_API), model $LLM_MODEL"
|
echo "== llm ollama ($LLM_API), model $LLM_MODEL"
|
||||||
|
|||||||
+30
-11
@@ -29,7 +29,7 @@ from .console import (
|
|||||||
)
|
)
|
||||||
from .decisions import DecisionRequest, Option
|
from .decisions import DecisionRequest, Option
|
||||||
from .engine import EngineConfig, EngineUnavailable, SemIfEngine
|
from .engine import EngineConfig, EngineUnavailable, SemIfEngine
|
||||||
from .llm import LLMClient
|
from .llm import LLMClient, SemIfLLMClient
|
||||||
from .log import DecisionLog
|
from .log import DecisionLog
|
||||||
from .scheduler import Scheduler
|
from .scheduler import Scheduler
|
||||||
from .skills import tree_summary
|
from .skills import tree_summary
|
||||||
@@ -231,14 +231,28 @@ def build_codegen_client(config: dict) -> CodegenClient:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
|
def build_llm_client(config: dict, engine):
|
||||||
engine = SemIfEngine(build_engine_config(config))
|
"""Build the `llm` title/description client from the `llm` config block.
|
||||||
|
|
||||||
|
`provider` selects the backend: `"semif"` drives the already-loaded SemIf
|
||||||
|
engine model in-process (the GGUF is the model — no endpoint or `model` is
|
||||||
|
needed), `"opencode"` the hosted Console client, and anything else the
|
||||||
|
default ollama-compatible `LLMClient`. Shared by `build_scheduler` and tests
|
||||||
|
so both exercise the configured provider rather than assuming ollama.
|
||||||
|
"""
|
||||||
llm_cfg = config.get("llm", {}) or {}
|
llm_cfg = config.get("llm", {}) or {}
|
||||||
llm_provider = str(llm_cfg.get("provider", "ollama") or "ollama").lower()
|
provider = str(llm_cfg.get("provider", "ollama") or "ollama").lower()
|
||||||
llm_cls = ConsoleLLMClient if llm_provider == "opencode" else LLMClient
|
if provider == "semif":
|
||||||
llm_endpoint = _provider_endpoint(llm_cfg, "http://localhost:11434/v1")
|
semif_cfg = llm_cfg.get("semif", {}) or {}
|
||||||
llm = llm_cls(
|
return SemIfLLMClient(
|
||||||
base_url=llm_endpoint["base_url"],
|
engine,
|
||||||
|
temperature=float(semif_cfg.get("temperature", 0.0)),
|
||||||
|
max_tokens=int(semif_cfg.get("max_tokens", 256)),
|
||||||
|
)
|
||||||
|
llm_cls = ConsoleLLMClient if provider == "opencode" else LLMClient
|
||||||
|
endpoint = _provider_endpoint(llm_cfg, "http://localhost:11434/v1")
|
||||||
|
return llm_cls(
|
||||||
|
base_url=endpoint["base_url"],
|
||||||
model=_required_model(llm_cfg, "llm"),
|
model=_required_model(llm_cfg, "llm"),
|
||||||
timeout=float(llm_cfg.get("timeout", 600.0)),
|
timeout=float(llm_cfg.get("timeout", 600.0)),
|
||||||
stream=bool(llm_cfg.get("stream", False)),
|
stream=bool(llm_cfg.get("stream", False)),
|
||||||
@@ -250,10 +264,15 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
|
|||||||
presence_penalty=_opt_float(llm_cfg.get("presence_penalty")),
|
presence_penalty=_opt_float(llm_cfg.get("presence_penalty")),
|
||||||
frequency_penalty=_opt_float(llm_cfg.get("frequency_penalty")),
|
frequency_penalty=_opt_float(llm_cfg.get("frequency_penalty")),
|
||||||
disable_thinking=bool(llm_cfg.get("disable_thinking", True)),
|
disable_thinking=bool(llm_cfg.get("disable_thinking", True)),
|
||||||
api_key=llm_endpoint["api_key"],
|
api_key=endpoint["api_key"],
|
||||||
extra_headers=llm_endpoint["extra_headers"],
|
extra_headers=endpoint["extra_headers"],
|
||||||
user_agent=llm_endpoint["user_agent"],
|
user_agent=endpoint["user_agent"],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
|
||||||
|
engine = SemIfEngine(build_engine_config(config))
|
||||||
|
llm = build_llm_client(config, engine)
|
||||||
log = DecisionLog(config.get("log", "data/decisions.jsonl"))
|
log = DecisionLog(config.get("log", "data/decisions.jsonl"))
|
||||||
trace = TraceLog(config.get("trace", "data/runs.jsonl"))
|
trace = TraceLog(config.get("trace", "data/runs.jsonl"))
|
||||||
codegen_cfg = config.get("codegen", {})
|
codegen_cfg = config.get("codegen", {})
|
||||||
|
|||||||
@@ -95,3 +95,64 @@ class SemIfEngine:
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def generate(
|
||||||
|
self,
|
||||||
|
messages: list[dict],
|
||||||
|
temperature: float = 0.0,
|
||||||
|
max_tokens: int = 256,
|
||||||
|
) -> str:
|
||||||
|
"""Drive the pinned decision model in the normal way: text generation.
|
||||||
|
|
||||||
|
SemIf scoring reads option logits directly; this instead autoregressively
|
||||||
|
samples from the same llama.cpp context, e.g. for skill-tree authoring.
|
||||||
|
Generation decodes the chat template through the backend's low-level
|
||||||
|
context (there is no high-level chat-completion object on the CPU
|
||||||
|
backend), stopping at the tokenizer's eos token. The KV cache is cleared
|
||||||
|
at the start, so interleaving scoring and generation on one model is safe.
|
||||||
|
|
||||||
|
It shares `self._lock` with `call`, so a generation serializes against
|
||||||
|
decisions on the one loaded model — short JSON replies are seconds of
|
||||||
|
contention, and there is only ever one copy of the GGUF.
|
||||||
|
"""
|
||||||
|
with self._lock:
|
||||||
|
model, tokenizer, metadata = self._ensure_loaded()
|
||||||
|
try:
|
||||||
|
import numpy
|
||||||
|
|
||||||
|
engine = model.engine
|
||||||
|
prompt_text = tokenizer.apply_chat_template(
|
||||||
|
messages,
|
||||||
|
tokenize=False,
|
||||||
|
add_generation_prompt=True,
|
||||||
|
enable_thinking=False,
|
||||||
|
)
|
||||||
|
prompt_ids = tokenizer.encode(prompt_text, add_special_tokens=False)
|
||||||
|
engine.clear()
|
||||||
|
logits = engine._decode(prompt_ids, 0, 0, True)
|
||||||
|
generated: list[int] = []
|
||||||
|
rng = numpy.random.default_rng()
|
||||||
|
for position in range(max_tokens):
|
||||||
|
token = _sample_token(logits, temperature, rng)
|
||||||
|
if token == tokenizer.eos_token_id:
|
||||||
|
break
|
||||||
|
generated.append(token)
|
||||||
|
logits = engine._decode([token], len(prompt_ids) + position, 0, True)
|
||||||
|
return tokenizer.decode(generated).strip()
|
||||||
|
except EngineUnavailable:
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
raise EngineUnavailable(f"generation failed: {exc}") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def _sample_token(logits, temperature: float, rng) -> int:
|
||||||
|
"""Pick the next token from next-position logits: greedy or temperature."""
|
||||||
|
import numpy
|
||||||
|
|
||||||
|
if temperature <= 0.0:
|
||||||
|
return int(numpy.argmax(logits))
|
||||||
|
scaled = numpy.asarray(logits, dtype=numpy.float64) / max(temperature, 1e-6)
|
||||||
|
scaled = scaled - scaled.max()
|
||||||
|
probabilities = numpy.exp(scaled)
|
||||||
|
probabilities /= probabilities.sum()
|
||||||
|
return int(rng.choice(probabilities.size, p=probabilities))
|
||||||
|
|
||||||
+15
-1
@@ -13,7 +13,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import json
|
import json
|
||||||
|
|
||||||
from .provider import OpenAICompatClient, ProviderError
|
from .provider import OpenAICompatClient, ProviderError, SemIfEngineClient
|
||||||
|
|
||||||
|
|
||||||
class LLMError(ProviderError):
|
class LLMError(ProviderError):
|
||||||
@@ -102,3 +102,17 @@ class LLMClient(OpenAICompatClient):
|
|||||||
if start != -1 and end != -1:
|
if start != -1 and end != -1:
|
||||||
text = text[start : end + 1]
|
text = text[start : end + 1]
|
||||||
return json.loads(text)
|
return json.loads(text)
|
||||||
|
|
||||||
|
|
||||||
|
class SemIfLLMClient(SemIfEngineClient):
|
||||||
|
"""`llm` authoring backed by the loaded SemIf engine model.
|
||||||
|
|
||||||
|
The `llm.provider = "semif"` option: the same in-process GGUF the decision
|
||||||
|
engine already loaded generates the title/description (and any other `llm`
|
||||||
|
text) instead of calling an HTTP endpoint. Same `chat(...)` surface, same
|
||||||
|
graceful error contract — raises `LLMError` so the scheduler traces a
|
||||||
|
`draft_failed` and the LLM bridge reports 502 rather than crashing.
|
||||||
|
"""
|
||||||
|
|
||||||
|
error_class = LLMError
|
||||||
|
label = "semif:llm"
|
||||||
@@ -8,6 +8,11 @@ provider logic once; subclasses set `base_url`/`model`, their sampler
|
|||||||
parameters, and the error classes they raise so existing callers keep catching
|
parameters, and the error classes they raise so existing callers keep catching
|
||||||
their own types.
|
their own types.
|
||||||
|
|
||||||
|
It also holds `SemIfEngineClient`, the non-HTTP sibling that generates text
|
||||||
|
from the in-process SemIf engine model (`engine.SemIfEngine.generate`) behind
|
||||||
|
the same ``chat(...)`` surface, so the `llm` task can be served by the loaded
|
||||||
|
decision model instead of an HTTP endpoint.
|
||||||
|
|
||||||
Stdlib-only and imports nothing from the agent's own modules, so `codegen.py`
|
Stdlib-only and imports nothing from the agent's own modules, so `codegen.py`
|
||||||
(which imports `skills.py`, which imports `llm.py`) can depend on it without a
|
(which imports `skills.py`, which imports `llm.py`) can depend on it without a
|
||||||
cycle.
|
cycle.
|
||||||
@@ -633,3 +638,66 @@ class OpenAICompatClient:
|
|||||||
if sock is None:
|
if sock is None:
|
||||||
sock = getattr(response, "sock", None)
|
sock = getattr(response, "sock", None)
|
||||||
return sock
|
return sock
|
||||||
|
|
||||||
|
|
||||||
|
class SemIfEngineClient:
|
||||||
|
"""Text generation backed by the in-process SemIf engine model.
|
||||||
|
|
||||||
|
A drop-in sibling of `OpenAICompatClient` for the small `llm` task: instead
|
||||||
|
of speaking HTTP to an ollama/Console endpoint it drives the already-loaded
|
||||||
|
decision GGUF through `engine.generate(...)`. It exposes the same
|
||||||
|
``chat(messages, max_tokens=..., temperature=..., ...)`` surface every `llm`
|
||||||
|
caller uses, so the provider choice is invisible to callers — title/
|
||||||
|
description authoring, gateway result cleanup, and the LLM bridge all reuse
|
||||||
|
it unchanged.
|
||||||
|
|
||||||
|
The engine is duck-typed (any object with ``generate(messages, temperature,
|
||||||
|
max_tokens)``); this module stays free of imports from the agent's own
|
||||||
|
modules, so subclasses in `llm.py` set the `LLMError` contract without a
|
||||||
|
cycle. Sampler/`timeout`/`degeneration_check` arguments are accepted for
|
||||||
|
signature compatibility and ignored: the engine generation is bounded by
|
||||||
|
`max_tokens` and serializes on the engine's own lock.
|
||||||
|
|
||||||
|
Any engine failure (`EngineUnavailable`, a missing GGUF, a sampling error)
|
||||||
|
is re-raised as `error_class` so the scheduler's graceful `draft_failed`
|
||||||
|
path and the LLM bridge's 502 path keep their existing contracts.
|
||||||
|
"""
|
||||||
|
|
||||||
|
error_class = ProviderError
|
||||||
|
label = "semif"
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
engine,
|
||||||
|
temperature: float = 0.0,
|
||||||
|
max_tokens: int = 256,
|
||||||
|
disable_thinking: bool = True,
|
||||||
|
):
|
||||||
|
self.engine = engine
|
||||||
|
self.temperature = temperature
|
||||||
|
self.max_tokens = max_tokens
|
||||||
|
# The engine's `generate` always decodes with thinking disabled; the knob
|
||||||
|
# is accepted so the class mirrors the other providers' constructors.
|
||||||
|
self.disable_thinking = disable_thinking
|
||||||
|
|
||||||
|
def chat(
|
||||||
|
self,
|
||||||
|
messages: list[dict],
|
||||||
|
max_tokens: int | None = None,
|
||||||
|
temperature: float | None = None,
|
||||||
|
top_p: float | None = None,
|
||||||
|
presence_penalty: float | None = None,
|
||||||
|
frequency_penalty: float | None = None,
|
||||||
|
timeout: float | None = None,
|
||||||
|
degeneration_check: Callable[[str], str | None] | None = None,
|
||||||
|
) -> str:
|
||||||
|
resolved_max = self.max_tokens if max_tokens is None else max_tokens
|
||||||
|
resolved_temp = self.temperature if temperature is None else temperature
|
||||||
|
try:
|
||||||
|
return self.engine.generate(
|
||||||
|
messages, temperature=resolved_temp, max_tokens=resolved_max
|
||||||
|
)
|
||||||
|
except Exception as exc: # EngineUnavailable and anything the engine raises
|
||||||
|
raise self.error_class(
|
||||||
|
f"{self.label} generation failed: {exc}"
|
||||||
|
) from exc
|
||||||
+74
-1
@@ -11,7 +11,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from semif_agent.decisions import Request
|
from semif_agent.decisions import Request
|
||||||
from semif_agent.llm import LLMClient, LLMError
|
from semif_agent.llm import LLMClient, LLMError, SemIfLLMClient
|
||||||
from semif_agent.skills import (
|
from semif_agent.skills import (
|
||||||
CategoryDraft,
|
CategoryDraft,
|
||||||
SkillDraft,
|
SkillDraft,
|
||||||
@@ -207,3 +207,76 @@ def test_unreachable_endpoint_raises_llm_error():
|
|||||||
client = LLMClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=2)
|
client = LLMClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=2)
|
||||||
with pytest.raises(LLMError):
|
with pytest.raises(LLMError):
|
||||||
client.chat([{"role": "user", "content": "hi"}])
|
client.chat([{"role": "user", "content": "hi"}])
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeEngine:
|
||||||
|
"""Duck-typed stand-in for SemIfEngine: records generate() calls."""
|
||||||
|
|
||||||
|
def __init__(self, reply: str = "", error: Exception | None = None):
|
||||||
|
self.reply = reply
|
||||||
|
self.error = error
|
||||||
|
self.calls: list[dict] = []
|
||||||
|
|
||||||
|
def generate(self, messages, temperature: float = 0.0, max_tokens: int = 256) -> str:
|
||||||
|
self.calls.append(
|
||||||
|
{"messages": messages, "temperature": temperature, "max_tokens": max_tokens}
|
||||||
|
)
|
||||||
|
if self.error is not None:
|
||||||
|
raise self.error
|
||||||
|
return self.reply
|
||||||
|
|
||||||
|
|
||||||
|
def test_semif_llm_client_generates_via_engine():
|
||||||
|
"""provider == "semif": the loaded engine model answers; a per-call
|
||||||
|
max_tokens override wins over the client default."""
|
||||||
|
engine = _FakeEngine('{"title": "track_live", "description": "Follow it."}')
|
||||||
|
client = SemIfLLMClient(engine, temperature=0.0, max_tokens=256)
|
||||||
|
out = client.chat([{"role": "user", "content": "name this"}], max_tokens=128)
|
||||||
|
assert out == '{"title": "track_live", "description": "Follow it."}'
|
||||||
|
call = engine.calls[0]
|
||||||
|
assert call["max_tokens"] == 128
|
||||||
|
assert call["temperature"] == 0.0
|
||||||
|
assert call["messages"] == [{"role": "user", "content": "name this"}]
|
||||||
|
|
||||||
|
|
||||||
|
def test_semif_llm_client_accepts_http_provider_kwargs():
|
||||||
|
"""It is a drop-in for the HTTP clients: sampler/timeout/degeneration
|
||||||
|
arguments are accepted and ignored, defaults apply."""
|
||||||
|
engine = _FakeEngine("hello")
|
||||||
|
out = SemIfLLMClient(engine).chat(
|
||||||
|
[{"role": "user", "content": "hi"}],
|
||||||
|
top_p=0.9,
|
||||||
|
presence_penalty=0.1,
|
||||||
|
frequency_penalty=0.0,
|
||||||
|
timeout=5.0,
|
||||||
|
degeneration_check=lambda _text: None,
|
||||||
|
)
|
||||||
|
assert out == "hello"
|
||||||
|
assert engine.calls[0]["max_tokens"] == 256
|
||||||
|
assert engine.calls[0]["temperature"] == 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_semif_llm_client_wraps_engine_failure_as_llm_error():
|
||||||
|
client = SemIfLLMClient(_FakeEngine(error=RuntimeError("boom")))
|
||||||
|
with pytest.raises(LLMError):
|
||||||
|
client.chat([{"role": "user", "content": "hi"}])
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_llm_client_selects_provider():
|
||||||
|
"""build_llm_client maps llm.provider to the right client class; the semif
|
||||||
|
branch needs no model and wraps the supplied engine."""
|
||||||
|
from semif_agent import cli
|
||||||
|
from semif_agent.console import ConsoleLLMClient
|
||||||
|
|
||||||
|
engine = _FakeEngine("x")
|
||||||
|
assert isinstance(
|
||||||
|
cli.build_llm_client({"llm": {"provider": "semif"}}, engine), SemIfLLMClient
|
||||||
|
)
|
||||||
|
assert isinstance(
|
||||||
|
cli.build_llm_client({"llm": {"provider": "ollama", "model": "m"}}, engine),
|
||||||
|
LLMClient,
|
||||||
|
)
|
||||||
|
assert isinstance(
|
||||||
|
cli.build_llm_client({"llm": {"provider": "opencode", "model": "m"}}, engine),
|
||||||
|
ConsoleLLMClient,
|
||||||
|
)
|
||||||
Reference in new issue
Block a user