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

+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}"