humanize ouputs at gateway

This commit is contained in:
gabby committed 2026-10-06 10:29:57 +00:00
1 parent ddbe5f167d
commit 85cdb94dc9
7 files changed
+375 -17

No files matched your search

+3 -1
View File
@@ -718,7 +718,8 @@ def _resolve_platforms(requested: str, gateway_cfg: dict) -> list[str]:
`all`/`*` means every **enabled** gateway block in config; a
comma-separated list is taken as-is (unknown names are kept so the caller
can report them).
can report them). Non-platform keys (`_comment`, the global `humanize`
defaults block) are skipped.
"""
requested = (requested or "simplex").strip()
if requested in ("all", "*"):
@@ -727,6 +728,7 @@ def _resolve_platforms(requested: str, gateway_cfg: dict) -> list[str]:
for name, block in (gateway_cfg or {}).items()
if isinstance(block, dict)
and not name.startswith("_")
and name != "humanize"
and block.get("enabled", False)
]
return [name.strip() for name in requested.split(",") if name.strip()]
+107
View File
@@ -0,0 +1,107 @@
"""Optional LLM cleanup of a skill's result line for the messenger gateway.
The scheduler's run summary is deterministic and technical — ``<skill>:
<ok|failed> — <action_log>``, where the action log is whatever the skill body
wrote (often mechanical: ``PUT 201 …``, ``sent via /_send to contact 12``).
This layer rewrites only that result detail into one grounded, friendly
sentence for a chat front end.
It is generation, never a decision: the success/failure verdict and the routing
are already settled by SemIf and the runner, and the rewrite is never fed back
into assessment, tracing, or the decision log. The prompt forbids adding,
inferring, or dropping facts, and `humanize` falls back to the original text on
any error, timeout, empty reply, refusal, or runaway length — a cleanup failure
must never swallow or corrupt a real result.
It reuses the scheduler's configured ``llm`` client (its endpoint/model/sampler)
and passes a short per-call ``timeout`` so a slow cleanup cannot hold the
gateway's poll loop for the client's full authoring budget. It is deliberately
gateway-only: the runner and the REPL keep the raw, deterministic summary.
"""
from __future__ import annotations
#: The strict rephrasing instruction. Grounding is enforced by the prompt and
#: by the caller's fallback, not by a second model call.
SYSTEM_PROMPT = (
"You rewrite an assistant's raw action result into one short, friendly "
"sentence for a chat reply.\n"
"Rules:\n"
"- Use ONLY the facts in the result. Do not add, guess, or infer anything.\n"
"- Preserve whether the action succeeded or failed exactly as stated.\n"
"- Do not mention servers, HTTP status codes, command names, file paths, "
"or internal bookkeeping unless that is the only content.\n"
"- One sentence. No preamble, no explanation, no quotes, no markdown.\n"
"- If the result is already a plain sentence, return it unchanged."
)
#: Leading phrases that mark a meta/refusal reply rather than a rewrite.
_REFUSAL_PREFIXES = (
"i cannot",
"i can't",
"i'm sorry",
"i am sorry",
"i'm unable",
"i am unable",
"as an ai",
"sorry,",
)
def _clean_reply(raw: str) -> str:
"""Normalize a model reply into one bare sentence, or "" if unusable."""
text = (raw or "").strip()
if not text:
return ""
# Drop a wrapping pair of quotes the model may add.
if len(text) >= 2 and text[0] == text[-1] and text[0] in "\"'“”‘’":
text = text[1:-1].strip()
# Collapse newlines / runs of whitespace to a single line.
return " ".join(text.split())
class Humanizer:
"""Rewrite a result line with an LLM, falling back to the source verbatim."""
def __init__(
self,
client,
*,
enabled: bool = True,
timeout: float = 20.0,
max_tokens: int = 200,
max_chars: int = 600,
):
self.client = client
self.enabled = bool(enabled) and client is not None
self.timeout = float(timeout)
self.max_tokens = int(max_tokens)
self.max_chars = int(max_chars)
def humanize(self, text: str) -> str:
"""Return a grounded rewrite of `text`, or `text` unchanged.
Never raises: any failure (unreachable client, timeout, empty or
unusable reply, refusal, runaway length) returns the original text.
"""
source = (text or "").strip()
if not self.enabled or not source:
return text
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": source},
]
try:
raw = self.client.chat(
messages, max_tokens=self.max_tokens, timeout=self.timeout
)
except Exception:
return text
cleaned = _clean_reply(raw)
if not cleaned:
return text
if cleaned.lower().startswith(_REFUSAL_PREFIXES):
return text
if len(cleaned) > self.max_chars:
return text
return cleaned
+61 -4
View File
@@ -26,6 +26,7 @@ import re
import threading
from .base import InboundMessage, OutboundMessage
from .humanize import Humanizer
_LEADING_RUN_ID = re.compile(r"^\[[0-9a-f]{6,}\]\s*")
@@ -112,6 +113,7 @@ class GatewayService:
adapters,
config: dict | None = None,
poll_interval: float = 1.0,
humanizer: Humanizer | None = None,
):
self.scheduler = scheduler
self.adapters = _normalize_adapters(adapters)
@@ -125,6 +127,17 @@ class GatewayService:
self._platform_cfg: dict[str, dict] = {
platform: self._config_for(platform) for platform in self.platforms
}
#: Optional LLM result cleanup (gateway-only presentation). Built from
#: the scheduler's `llm` client unless one is injected; a no-op unless
#: `gateway.humanize.enabled` (or a per-platform override) turns it on.
if humanizer is not None:
self.humanizer = humanizer
self._humanize_default = bool(humanizer.enabled)
else:
humanize_cfg = self.config.get("humanize")
humanize_cfg = humanize_cfg if isinstance(humanize_cfg, dict) else {}
self._humanize_default = bool(humanize_cfg.get("enabled", False))
self.humanizer = self._build_humanizer(humanize_cfg)
self._owners: dict[str, Target] = {}
self._parents: dict[str, str] = {}
self._pending_owner: Target | None = None
@@ -165,6 +178,44 @@ class GatewayService:
return bool(cfg["result_only"])
return bool(getattr(self.adapters.get(platform), "result_only", False))
# ---- optional LLM result cleanup ----
def _build_humanizer(self, cfg: dict) -> Humanizer | None:
"""Build the result humanizer from config + the scheduler's `llm`.
Global defaults live in `gateway.humanize`; a per-platform
`gateway.<platform>.humanize` (bool or `{enabled, timeout, max_tokens,
max_chars}`) overrides the enable flag. Returns None when no `llm`
client is available, so a client-less scheduler degrades to no cleanup.
The instance is always built `enabled`; the global default is kept
separately so a per-platform override can turn it on or off.
"""
client = getattr(self.scheduler, "llm", None)
if client is None:
return None
return Humanizer(
client,
enabled=True,
timeout=float(cfg.get("timeout", 20.0)),
max_tokens=int(cfg.get("max_tokens", 200)),
max_chars=int(cfg.get("max_chars", 600)),
)
def _humanize_enabled(self, platform: str) -> bool:
"""Whether this platform cleans up its result line.
A per-platform `humanize` bool (or `{enabled: bool}`) overrides the
global `gateway.humanize.enabled`. Default is off.
"""
if self.humanizer is None:
return False
override = self._platform_cfg.get(platform, {}).get("humanize")
if isinstance(override, bool):
return override
if isinstance(override, dict) and "enabled" in override:
return bool(override["enabled"])
return self._humanize_default
def _fallback_target(self) -> Target | None:
for platform in self.platforms:
home = self._home_channel(platform)
@@ -379,13 +430,19 @@ class GatewayService:
self, platform: str, chat_id: str, text: str, kind: str = "reply"
) -> None:
text = _strip_run_id(text)
if self._result_only(platform):
result_only = self._result_only(platform)
humanize = kind == "result" and self._humanize_enabled(platform)
if result_only:
# A spoken front end says the skill's result, not the scheduler's
# bookkeeping: drop queue/urgency chatter and unwrap the result line.
# bookkeeping: drop queue/urgency chatter.
if kind == "status":
return
if kind == "result":
text = _result_detail(text)
if kind == "result" and (result_only or humanize):
# Unwrap `<skill>: <ok|failed> — <detail>` to the skill's own
# result before optionally cleaning it up.
text = _result_detail(text)
if humanize:
text = self.humanizer.humanize(text)
prefix = str(self._platform_cfg.get(platform, {}).get("reply_prefix", "") or "")
if prefix:
text = f"{prefix}{text}"
+24 -11
View File
@@ -192,8 +192,13 @@ class OpenAICompatClient:
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:
# A per-call `timeout` overrides the constructor value for this request
# only (used by short auxiliary calls such as the gateway's result
# cleanup, which must not inherit the authoring client's long budget).
deadline = self.timeout if timeout is None else timeout
budget = self._compute_budget(messages)
if self.stream:
self._print_budget(budget)
@@ -227,15 +232,17 @@ class OpenAICompatClient:
url, data=body, headers=self._headers()
)
try:
with urllib.request.urlopen(request, timeout=self.timeout) as response:
return self._read_stream(response, budget, degeneration_check)
with urllib.request.urlopen(request, timeout=deadline) as response:
return self._read_stream(
response, budget, degeneration_check, timeout=deadline
)
except urllib.error.URLError as exc:
raise self.error_class(
f"{self.label} endpoint unreachable at {url}: {exc}. Is your local server running?"
) from exc
except TimeoutError as exc:
raise self.error_class(
f"{self.label} request timed out after {self.timeout}s at {url}"
f"{self.label} request timed out after {deadline:.0f}s at {url}"
) from exc
def _native_base_url(self) -> str:
@@ -399,6 +406,7 @@ class OpenAICompatClient:
response,
budget: TokenBudget,
degeneration_check: Callable[[str], str | None] | None = None,
timeout: float | None = None,
) -> str:
"""Read an OpenAI-compatible SSE stream; echo tokens if `stream`.
@@ -426,7 +434,10 @@ class OpenAICompatClient:
parts: list[str] = []
sock = self._stream_socket(response)
if sock is None:
return self._read_stream_blocking(response, budget, degeneration_check)
return self._read_stream_blocking(
response, budget, degeneration_check, timeout=timeout
)
deadline = self.timeout if timeout is None else timeout
start = time.monotonic()
last_activity = start
warned = False
@@ -437,9 +448,9 @@ class OpenAICompatClient:
recent_len = 0
last_check: int | None = None
while True:
if time.monotonic() - start >= self.timeout:
if time.monotonic() - start >= deadline:
raise self.error_class(
f"{self.label} request exceeded {self.timeout:.0f}s total budget"
f"{self.label} request exceeded {deadline:.0f}s total budget"
)
ready, _, _ = select.select([sock], [], [], 1.0)
now = time.monotonic()
@@ -499,16 +510,18 @@ class OpenAICompatClient:
response,
budget: TokenBudget,
degeneration_check: Callable[[str], str | None] | None = None,
timeout: float | None = None,
) -> str:
"""Fallback reader when the response socket can't be located.
A plain blocking read relies on the per-read socket timeout for
silence, but that bounds individual reads, not the whole stream — so
enforce the same total wall-clock budget `self.timeout` and the token
budget in the loop, or a continuously-streaming runaway would never be
cut short.
enforce the same total wall-clock budget (the per-call `timeout`, else
`self.timeout`) and the token budget in the loop, or a
continuously-streaming runaway would never be cut short.
"""
parts: list[str] = []
deadline = self.timeout if timeout is None else timeout
start = time.monotonic()
warned_fill = False
out_chars = 0
@@ -517,9 +530,9 @@ class OpenAICompatClient:
recent_len = 0
last_check: int | None = None
for raw in response:
if time.monotonic() - start >= self.timeout:
if time.monotonic() - start >= deadline:
raise self.error_class(
f"{self.label} request exceeded {self.timeout:.0f}s total budget"
f"{self.label} request exceeded {deadline:.0f}s total budget"
)
continues, text, reasoning, frame_usage = self._consume_frame(
raw.decode("utf-8").strip()