authoring: dedicated llm provider for skill title/description

Move new category/skill draft authoring off SemIfEngine.generate onto a
separate small OpenAI-compatible provider, deliberately distinct from
codegen. Extract the shared transport (SSE/budget/idle/degeneration) into
provider.OpenAICompatClient; LLMClient and CodegenClient subclass it with
their own endpoints, sampler defaults, and error types.

Draft authoring now runs on its own async single-slot worker: a create
request queues, the gate stays free, a category job chains into its skill
job, and the original request re-runs when the body lands. An unreachable
llm endpoint is graceful (draft_failed trace, user notified, no
re-dispatch); only SemIf availability is fatal. Elicitation is deferred on
every front end (REPL included) now that authoring is async.
This commit is contained in:
Denton Social committed 2026-09-29 22:18:01 -05:00
1 parent ea3d79be99
commit fb5303928b
14 files changed
+1140 -957

No files matched your search

+19 -19
View File
@@ -2,8 +2,9 @@
python -m pytest tests/integration -q
The decision engine is real (llamacpp GGUF) and self-assessment is a real
local LLM endpoint. If either is unavailable this fails loudly — no mocking.
The decision engine is real (llamacpp GGUF), and the `llm` and `codegen`
providers are real OpenAI-compatible endpoints. If any is unavailable this
fails loudly — no mocking.
"""
import json
@@ -78,7 +79,7 @@ def _install_tracking_fixture(scheduler):
The pipeline tests need a target whose flow is stable; the hardcoded
email/tracking examples were removed because they faked their integrations.
This injects a runnable tracking leaf instead — the decision engine, the
self-assessment LLM, and the decision log all remain real.
`llm`/`codegen` providers, and the decision log all remain real.
"""
def predict(ctx, request):
@@ -240,29 +241,22 @@ def test_busy_choice_path(tmp_path):
scheduler.idle()
def test_engine_generation_normal_mode(tmp_path):
"""The pinned decision model must also generate text in the normal way."""
def test_engine_scoring_only(tmp_path):
"""The pinned decision model scores (makes decisions); it no longer writes
free text. Text authoring is the `llm` provider's job."""
config = load_config()
require_real(config)
scheduler, config = build_scheduler(config)
out = scheduler.engine.generate(
[
{"role": "system", "content": "Reply with the single word ok."},
{"role": "user", "content": "say ok"},
],
max_tokens=16,
)
print(f"generation: {out!r}")
assert isinstance(out, str) and out.strip()
assert not hasattr(scheduler.engine, "generate")
def test_generate_category(tmp_path):
"""Authoring a category stub through the real decision model."""
"""Authoring a category stub through the real `llm` provider."""
config = load_config()
require_real(config)
scheduler, config = build_scheduler(config)
draft = generate_category(
scheduler.engine,
scheduler.llm,
Request("tell me if my package was delivered"),
scheduler.tree,
)
@@ -272,12 +266,12 @@ def test_generate_category(tmp_path):
def test_generate_skill(tmp_path):
"""Authoring a skill leaf stub through the real decision model."""
"""Authoring a skill leaf stub through the real `llm` provider."""
config = load_config()
require_real(config)
scheduler, config = build_scheduler(config)
draft = generate_skill(
scheduler.engine,
scheduler.llm,
Request("tell me if my package was delivered"),
"tracking",
scheduler.tree,
@@ -481,8 +475,14 @@ def test_create_category_chain_runs_new_skill(tmp_path):
status, detail = scheduler.submit("track my drone delivery in real time")
print(f"[{status}] {detail}")
assert status in ("running", "preempted", "queued", "rejected")
assert scheduler.current is None, "gate must be free again right after the stub is created"
assert scheduler.current is None, "gate must be free again right after the draft is queued"
draft_deadline = time.monotonic() + 10 * 60
while time.monotonic() < draft_deadline:
kinds = [e["kind"] for e in scheduler.trace.read()]
if "category_created" in kinds and "skill_writing" in kinds:
break
time.sleep(5)
kinds = [e["kind"] for e in scheduler.trace.read()]
assert "category_created" in kinds, "category stub must be authored first"
assert "skill_writing" in kinds, "the async body write must be launched"
+117 -5
View File
@@ -1,11 +1,69 @@
"""Pure-stdlib tests for the retained JSON helper on the dormant LLM client.
"""Pure-stdlib tests for the `llm` authoring provider.
The LLM no longer participates in any decision path (assessment and fidelity
are SemIf decisions), so only `_parse_json` — which the authoring parsers
borrow — is exercised here.
A throwaway stdlib HTTP server stands in for the OpenAI-compatible endpoint —
the LLMClient itself is real, not mocked.
"""
from semif_agent.llm import LLMClient
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
from semif_agent.decisions import Request
from semif_agent.llm import LLMClient, LLMError
from semif_agent.skills import (
CategoryDraft,
SkillDraft,
build_skills,
build_tree,
generate_category,
generate_skill,
)
def _sse_frame(payload: dict) -> str:
return f"data: {json.dumps(payload)}\n\n"
class _FakeOpenAI(BaseHTTPRequestHandler):
"""Single-shot SSE server: the reply arrives as one content delta. The
`/api/show` window query is answered too but never recorded."""
reply: str = ""
received: list = []
def do_POST(self) -> None:
length = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(length).decode("utf-8")
if self.path.rstrip("/").endswith("/api/show"):
body = json.dumps({"parameters": {"num_ctx": 32768}}).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
return
type(self).received.append(json.loads(raw))
body = (
_sse_frame({"choices": [{"delta": {"content": self.reply}}]})
+ "data: [DONE]\n\n"
).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, format, *args) -> None:
pass
def _fake_server(reply: str) -> tuple[ThreadingHTTPServer, str]:
handler = type("Handler", (_FakeOpenAI,), {"reply": reply, "received": []})
httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=httpd.serve_forever, daemon=True).start()
return httpd, f"http://127.0.0.1:{httpd.server_address[1]}/v1"
def test_parse_json_extracts_object_from_prose():
@@ -15,3 +73,57 @@ def test_parse_json_extracts_object_from_prose():
def test_parse_json_handles_bare_object():
assert LLMClient._parse_json('{"ok": true}') == {"ok": True}
def test_chat_returns_streamed_content():
httpd, base = _fake_server('{"title": "track_live", "description": "Follow it."}')
try:
client = LLMClient(base_url=base, model="test", timeout=10)
out = client.chat([{"role": "user", "content": "name this"}])
assert out == '{"title": "track_live", "description": "Follow it."}'
assert httpd.RequestHandlerClass.received[0]["model"] == "test"
finally:
httpd.shutdown()
httpd.server_close()
def test_generate_category_via_provider():
httpd, base = _fake_server(
'{"title": "Track Delivery", "description": "Track parcels end to end."}'
)
try:
client = LLMClient(base_url=base, model="test", timeout=10)
draft = generate_category(
client, Request("where is my parcel?"), build_tree(build_skills({"skills": {}}))
)
assert isinstance(draft, CategoryDraft)
assert draft.name == "track_delivery"
assert draft.description == "Track parcels end to end."
finally:
httpd.shutdown()
httpd.server_close()
def test_generate_skill_via_provider():
httpd, base = _fake_server(
'{"title": "track.live", "description": "Follow a package in real time."}'
)
try:
client = LLMClient(base_url=base, model="test", timeout=10)
draft = generate_skill(
client,
Request("track my drone delivery"),
"tracking",
build_tree(build_skills({"skills": {}})),
)
assert isinstance(draft, SkillDraft)
assert draft.name == "track.live"
finally:
httpd.shutdown()
httpd.server_close()
def test_unreachable_endpoint_raises_llm_error():
client = LLMClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=2)
with pytest.raises(LLMError):
client.chat([{"role": "user", "content": "hi"}])
+50 -68
View File
@@ -19,12 +19,11 @@ import pytest
from semif_agent.cli import REPO_ROOT, load_config
from semif_agent.codegen import CodegenClient
from semif_agent.decisions import Request
from semif_agent.engine import EngineConfig, EngineUnavailable, SemIfEngine
from semif_agent.llm import LLMClient
from semif_agent.engine import EngineConfig, SemIfEngine
from semif_agent.llm import LLMClient, LLMError
from semif_agent.log import DecisionLog
from semif_agent.skill import RunResult
from semif_agent.scheduler import (
DispatchResult,
PendingQuestion,
RepairOffer,
Scheduler,
@@ -280,16 +279,10 @@ def test_category_registry_roundtrip(tmp_path):
assert loaded["delivery"]["skills"] == []
def test_generate_category_without_engine_raises():
engine = SemIfEngine(EngineConfig())
with pytest.raises(EngineUnavailable):
generate_category(engine, Request("anything"), {})
def test_generate_without_engine_raises():
engine = SemIfEngine(EngineConfig())
with pytest.raises(EngineUnavailable):
engine.generate([{"role": "user", "content": "hi"}])
def test_generate_category_without_endpoint_raises():
client = LLMClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=2)
with pytest.raises(LLMError):
generate_category(client, Request("anything"), {})
def test_build_tree_includes_registry_stubs(tmp_path):
@@ -359,10 +352,10 @@ def test_parse_skill_draft_rejects_unclean_title():
parse_skill_draft('{"title": "ca$h!", "description": "nope"}')
def test_generate_skill_without_engine_raises():
engine = SemIfEngine(EngineConfig())
with pytest.raises(EngineUnavailable):
generate_skill(engine, Request("anything"), "tracking", {})
def test_generate_skill_without_endpoint_raises():
client = LLMClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=2)
with pytest.raises(LLMError):
generate_skill(client, Request("anything"), "tracking", {})
def test_category_registry_register_skill(tmp_path):
@@ -796,12 +789,14 @@ def test_dispatch_intent_mismatch_authorizes_new_skill(tmp_path):
scheduler.tree["simplex"] = [
Skill(name="next_message", category="simplex", description="Read the next SimpleX message."),
]
scheduler._create_skill = lambda request, category: DispatchResult(
kind="create_skill", summary="authoring requested", skill="send_message"
queued: list = []
scheduler._queue_draft = lambda request, category, kind, weight: queued.append(
(category, kind)
)
request = Request("send a simplex message to pepper")
result = scheduler._dispatch(request)
assert result.kind == "create_skill"
assert queued == [("simplex", "skill")]
phases = [r["extra"].get("phase") for r in scheduler.log.read()]
assert "navigate:intent" in phases
@@ -832,14 +827,15 @@ def test_dispatch_intent_match_runs_skill(tmp_path):
def test_dispatch_create_category_without_engine_is_fatal(tmp_path):
"""An empty tree short-circuits to CreateCategory; without an engine the
category authoring is fatal — the app is marked and the caller stops."""
def test_dispatch_create_category_queues_draft_and_is_not_fatal(tmp_path):
"""An empty tree short-circuits to CreateCategory; the `llm` draft is
queued asynchronously. An unreachable llm endpoint is graceful — traced and
the request is not re-dispatched — never fatal (only SemIf is fatal)."""
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
trace = TraceLog(str(tmp_path / "runs.jsonl"))
scheduler = Scheduler(
engine=SemIfEngine(EngineConfig()),
llm=LLMClient(base_url="http://localhost:1/v1", model="test"),
llm=LLMClient(base_url="http://127.0.0.1:1/v1", model="test", timeout=2),
log=log,
config={
"skills": {},
@@ -850,10 +846,16 @@ def test_dispatch_create_category_without_engine_is_fatal(tmp_path):
trace=trace,
)
scheduler.tree = {}
with pytest.raises(EngineUnavailable):
scheduler._dispatch(Request("anything"))
assert scheduler.fatal is not None
assert "not available" in scheduler.fatal
result = scheduler._dispatch(Request("anything"))
assert result.kind == "create_category"
assert scheduler.fatal is None
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
if any(e["kind"] == "draft_failed" for e in trace.read()):
break
time.sleep(0.02)
assert any(e["kind"] == "draft_failed" for e in trace.read())
assert scheduler.fatal is None
def test_skill_status_reflects_writing_and_noop():
@@ -1077,20 +1079,34 @@ def test_unresolved_variables_respects_tiered_config(tmp_path):
assert unresolved_variables(store, skill2, {}) == ["sender_address", "tag"]
assert unresolved_variables(store, skill2, {}, answered={"tag": "per-fire"}) == ["sender_address"]
def test_elicit_requirements_asks_and_records(tmp_path):
"""Opt-in elicitation asks the product owner refinement questions before
the body is written and rides the answers on the draft into the body prompt."""
def test_deferred_elicitation_asks_and_records(tmp_path):
"""Opt-in elicitation runs on the codegen worker (deferred): questions are
posted to the question queue, the worker waits, and the answers ride the
draft into the body prompt."""
httpd, base = _pipeline_codegen_server(
['{"questions": ["Draft or send?"]}', GOOD_BODY, "{}", GOOD_TEST]
)
try:
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10))
scheduler.defer_questions = True
scheduler.elicitation_enabled = True
answers = []
scheduler.asker = lambda q: (answers.append(q), "draft first")[1]
request = Request("track my package")
draft = SkillDraft(name="track_live", description="Follow a package.")
scheduler._elicit_requirements(Request("track my package"), "tracking", draft)
assert answers == ["Draft or send?"]
job = SkillWrite(request=request, category="tracking", draft=draft, weight=0.5)
def answerer() -> None:
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
pending = scheduler.pending_questions()
if pending:
scheduler.answer_question(pending[0]["id"], "draft first")
return
time.sleep(0.02)
thread = threading.Thread(target=answerer)
thread.start()
scheduler._deferred_elicit(job, scheduler.tree)
thread.join()
assert draft.requirements == {"Draft or send?": "draft first"}
assert any(e["kind"] == "requirements" for e in scheduler.trace.read())
finally:
@@ -1098,40 +1114,6 @@ def test_elicit_requirements_asks_and_records(tmp_path):
httpd.server_close()
def test_elicit_requirements_disabled_skips(tmp_path):
httpd, base = _pipeline_codegen_server([GOOD_BODY, "{}", GOOD_TEST])
try:
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10))
scheduler.elicitation_enabled = False
scheduler.asker = lambda q: "answer"
draft = SkillDraft(name="track_live", description="Follow a package.")
scheduler._elicit_requirements(Request("track my package"), "tracking", draft)
assert draft.requirements == {}
assert httpd.RequestHandlerClass.chat_calls == 0
finally:
httpd.shutdown()
httpd.server_close()
def test_elicit_requirements_asker_none_stops(tmp_path):
"""An asker that stops answering (None) halts collection without error."""
httpd, base = _pipeline_codegen_server(
['{"questions": ["A?", "B?"]}', GOOD_BODY, "{}", GOOD_TEST]
)
try:
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10))
scheduler.elicitation_enabled = True
asked = []
scheduler.asker = lambda q: (asked.append(q), None)[1]
draft = SkillDraft(name="track_live", description="Follow a package.")
scheduler._elicit_requirements(Request("track my package"), "tracking", draft)
assert asked == ["A?"]
assert draft.requirements == {}
finally:
httpd.shutdown()
httpd.server_close()
def test_async_skill_write_regen_ladder_on_failing_test(tmp_path):
"""A failing auto-run test triggers the regen decision (regen_test by
default when no factory), regenerating the test until it passes."""