llm bridge service

This commit is contained in:
gabby committed 2026-10-03 09:05:28 +00:00
1 parent f21baa7ebd
commit 63c5fc9903
20 files changed
+725 -172

No files matched your search

+6 -5
View File
@@ -1,11 +1,12 @@
"""Third-party API bridges: a secure local layer between skills and services.
A **bridge service** is a standalone process that exposes one third-party system
(SimpleX first, more later) to codegen-authored skill bodies over a local,
token-guarded HTTP API. It exists so a generated body never speaks a system's
native protocol (WebSocket, SMTP, CalDAV, a CLI's private flags) directly: it
calls a small, documented, uniform HTTP surface instead, and the bridge owns the
messy integration details and credentials.
(SimpleX, the local language model) to codegen-authored skill bodies over a
local, token-guarded HTTP API. It exists so a generated body never speaks a
system's native protocol (WebSocket, SMTP, CalDAV, an OpenAI-compatible chat
API, a CLI's private flags) directly: it calls a small, documented, uniform HTTP
surface instead, and the bridge owns the messy integration details and
credentials.
Two boundaries matter:
+99
View File
@@ -0,0 +1,99 @@
"""LLM bridge: the agent's language model behind the standard bridge surface.
Skill bodies are stdlib-only and must not speak a model's native
OpenAI-compatible protocol directly. This bridge exposes one generic chat call
over the same local, token-guarded JSON surface every other bridge uses, so a
body can ask for short generated text (e.g. extract an event title and
description from a request) without importing a client or knowing the endpoint.
It does **not** own the model connection: it reuses the scheduler's already
configured `llm` client, passed in at construction, so the endpoint/model/
sampler live in one place (the top-level `llm` block). Constructed without a
client (tests, standalone) it has no model and every call reports 502 rather
than fabricating an answer.
"""
from __future__ import annotations
from .base import BridgeInfo, BridgeService
class LLMBridge(BridgeService):
name = "llm"
INFO = BridgeInfo(
name="llm",
service="llm",
description=(
"Generate short text with the agent's configured language model, "
"e.g. extract a title and a description from a user's request."
),
url_config_var="llm_bridge_url",
endpoints=(
'GET /health -> 200 {"ok": true, "platform": "llm"} — the bridge is up',
'POST /chat {"messages": [{"role", "content"}, ...], "max_tokens"?: int} '
'-> 200 {"text": "<model reply>"}; 400 {"error": "..."} on a '
'missing/invalid messages list; 502 {"error": "..."} when the model '
"call fails or no model is configured",
'any request -> 401 {"error": "unauthorized"} when the token is '
"configured and the auth header is missing or wrong",
),
config_vars=("llm_bridge_url", "llm_bridge_token"),
config_var_docs=(
(
"llm_bridge_url",
"Base URL of the local LLM bridge (e.g. http://127.0.0.1:5229); "
"never hardcode it in the body.",
),
(
"llm_bridge_token",
"Shared secret for the bridge, if one is configured; sent as the "
"X-Semif-Token header. Leave blank when the bridge requires no auth.",
),
),
auth_header="X-Semif-Token",
auth_config_var="llm_bridge_token",
)
def __init__(self, config: dict | None = None, trace=None, client=None):
super().__init__(config, trace)
#: The scheduler's configured `llm` client (or a test double). None when
#: the bridge is built without one; calls then report 502, never a guess.
self.client = client
# ---- lifecycle ----
def check_requirements(self) -> tuple[bool, str | None]:
# Stdlib only: no missing dependency can make the bridge unstartable. A
# missing model surfaces as a 502 on the call, not as a startup failure.
return True, None
# ---- routes ----
def handle_get(self, path: str, query: dict) -> tuple[int, dict]:
if path == "/health":
return 200, {"ok": True, "platform": self.name}
return 404, {"error": "not found"}
def handle_post(self, path: str, payload: dict) -> tuple[int, dict]:
if path != "/chat":
return 404, {"error": "not found"}
messages = payload.get("messages")
if not isinstance(messages, list) or not messages:
return 400, {"error": "messages is required"}
if not all(
isinstance(message, dict)
and isinstance(message.get("role"), str)
and isinstance(message.get("content"), str)
for message in messages
):
return 400, {"error": "each message needs a string role and content"}
max_tokens = payload.get("max_tokens")
if max_tokens is not None and not isinstance(max_tokens, int):
return 400, {"error": "max_tokens must be an integer"}
if self.client is None:
return 502, {"error": "no language model is configured"}
try:
text = self.client.chat(messages, max_tokens=max_tokens)
except Exception as exc: # the model client's error type + anything it raises
return 502, {"error": f"llm call failed: {exc}"[:300]}
return 200, {"text": text}
+17 -5
View File
@@ -13,10 +13,11 @@ from __future__ import annotations
import threading
from .base import BridgeInfo, BridgeService
from .llm import LLMBridge
from .simplex import SimplexBridge
#: Known bridge services. Order is presentation order.
CATALOG: tuple[type[BridgeService], ...] = (SimplexBridge,)
CATALOG: tuple[type[BridgeService], ...] = (SimplexBridge, LLMBridge)
def _class_for(name: str) -> type[BridgeService] | None:
@@ -67,12 +68,21 @@ def describe_bridges() -> str:
return "\n".join(lines) + "\n"
def build_bridge(config: dict, name: str, trace=None) -> BridgeService:
"""Instantiate one bridge from the top-level `bridges.<name>` config block."""
def build_bridge(
config: dict, name: str, trace=None, llm=None
) -> BridgeService:
"""Instantiate one bridge from the top-level `bridges.<name>` config block.
`llm` is the scheduler's configured language-model client, handed to the LLM
bridge so it reuses the top-level `llm` endpoint/model instead of duplicating
that config. Other bridges ignore it.
"""
bridge_class = _class_for(name)
if bridge_class is None:
raise KeyError(f"unknown bridge: {name!r}")
block = (config.get("bridges", {}) or {}).get(name, {}) or {}
if bridge_class is LLMBridge:
return LLMBridge(block, trace=trace, client=llm)
return bridge_class(block, trace=trace)
@@ -80,11 +90,13 @@ def run_bridges(
config: dict,
names: list[str] | None = None,
trace=None,
llm=None,
) -> int:
"""Run the selected (+ enabled) bridges until interrupted.
With explicit `names`, a bridge runs even if disabled is not set; with no
names, only `enabled` bridges run. Returns a process exit code.
names, only `enabled` bridges run. Returns a process exit code. `llm` is the
scheduler's configured language-model client (see `build_bridge`).
"""
blocks = config.get("bridges", {}) or {}
selected: list[BridgeService] = []
@@ -95,7 +107,7 @@ def run_bridges(
block = blocks.get(name, {}) or {}
if not names and not block.get("enabled", False):
continue
bridge = bridge_class(block, trace=trace)
bridge = build_bridge(config, name, trace=trace, llm=llm)
ok, hint = bridge.check_requirements()
if not ok:
print(f"bridge {name} unavailable: {hint}")
+5 -2
View File
@@ -486,7 +486,8 @@ def repl(scheduler: Scheduler, config: dict) -> int:
if _fatal_exit(scheduler) is not None:
return 1
while scheduler.pending is not None:
answer = input(f"{scheduler.pending.question} ")
hint = "" if scheduler.pending.pre_act else " [leave empty to skip]"
answer = input(f"{scheduler.pending.question}{hint} ")
status, detail = scheduler.answer(answer)
print(f"[{status}] {detail}")
if _fatal_exit(scheduler) is not None:
@@ -629,7 +630,9 @@ def run_bridge(scheduler: Scheduler, config: dict, name: str | None = None) -> i
from .bridges.registry import run_bridges
names = [name] if name else None
return run_bridges(config, names=names, trace=scheduler.trace)
return run_bridges(
config, names=names, trace=scheduler.trace, llm=scheduler.llm
)
def main(argv: list[str] | None = None) -> int:
+10 -2
View File
@@ -572,7 +572,10 @@ class Scheduler:
"""Feed the human's answer to a run paused for input.
Routed directly to the pending run — no gate, score, or navigation —
and the run resumes by re-invoking `act`.
and the run resumes by re-invoking `act`. An empty answer is accepted:
a pre-act contract variable is left unset and marked skipped, and an
act-driven pause receives the empty string (the body may then fail,
which is assessed normally).
"""
with self._lock:
if self.pending is None:
@@ -580,7 +583,12 @@ class Scheduler:
pending = self.pending
self.pending = None
pending.request.user_input = text
self.trace.append("answered", pending.request.id, text=text)
self.trace.append(
"answered",
pending.request.id,
text=text,
skipped=not (text or "").strip(),
)
outcome = self.runner.resume(
pending.skill, pending.request, pre_act=pending.pre_act
)
+14 -6
View File
@@ -125,17 +125,22 @@ class SkillRunner:
return []
answered = request.meta.get("config_answers", {})
if self.store is not None:
return unresolved_variables(self.store, skill, self.ctx.config, answered)
merged = {**self.ctx.config}
merged.update(skill.config or {})
merged.update(answered)
return [name for name in skill.contract if name not in merged]
missing = unresolved_variables(self.store, skill, self.ctx.config, answered)
else:
merged = {**self.ctx.config}
merged.update(skill.config or {})
merged.update(answered)
missing = [name for name in skill.contract if name not in merged]
# A variable the human chose to skip (empty answer) stays unresolved but
# must never be re-asked: the run proceeds with it left unset.
skipped = request.meta.get("config_skipped", ())
return [name for name in missing if name not in skipped]
def _variable_question(self, skill: Skill, variable: str) -> str:
desc = (skill.contract or {}).get(variable, "")
return (
f"To run {skill.category}.{skill.name} I need `{variable}`. {desc}\n"
"Reply with the value, or 'skip' to leave it empty."
"Reply with the value, or leave it empty to skip."
)
def _decide_record(self, skill: Skill, request: Request, variable: str, value: str) -> bool:
@@ -172,6 +177,8 @@ class SkillRunner:
def _record_answer(self, skill: Skill, request: Request) -> None:
"""Persist (or stash per-fire) the human's answer to the last question.
An empty answer (or the literal "skip") leaves the variable unset and
marks it skipped for this run, so the run continues instead of re-asking.
`request.user_input` is cleared after consumption so a contract answer
does not leak into a later act-driven pause or the skill's own
user_input checks.
@@ -183,6 +190,7 @@ class SkillRunner:
return
value = answer.strip()
if not value or value.lower() == "skip":
request.meta.setdefault("config_skipped", set()).add(variable)
return
if self._decide_record(skill, request, variable, value):
skill.config = {**(skill.config or {}), variable: value}
+1 -1
View File
@@ -699,7 +699,7 @@ function renderStatus() {
const pending = state.status.pending;
$("#answer-form").classList.toggle("hidden", !pending);
if (pending) {
$("#answer-input").placeholder = `${pending.skill}: ${pending.question}`;
$("#answer-input").placeholder = `${pending.skill}: ${pending.question} (empty to skip)`;
const p = document.createElement("div");
p.className = "pending-line";
p.textContent = `awaiting input (${pending.run_id || pending.skill}): ${pending.question}`;
+1 -1
View File
@@ -20,7 +20,7 @@
</form>
<form id="answer-form" class="hidden">
<input id="answer-input" type="text" autocomplete="off" spellcheck="false"
placeholder="answer the pending question">
placeholder="answer the pending question (empty to skip)">
<button type="submit" id="answer-btn">answer</button>
</form>
<div id="answer-feedback" class="hidden"></div>