PWA, one send/stop button, audio in and out, web search as a tool

Four pieces of work.

**Installable.** A manifest carrying the instance name, PWA icons rasterised
from the existing mark at design time, a service worker and a themed offline
page. The worker caches the shell only and bails out on /api/, /auth/, /admin/
and anything accepting text/event-stream -- passing a reply stream through a
worker turns it into one delivery at the end, or nothing. It is served from
GET /sw.js rather than the static mount because a worker's scope is the path it
came from.

**Send and Stop are one button.** They were two, and the hidden one was never
hidden: `.btn` is display: inline-flex, which outranks the browser's own
`[hidden] { display: none }`, so Stop sat permanently beside Send. app.css now
forces the attribute to win -- every control toggled with `hidden` depended on
that -- and the composer renders one button carrying both icons, with ui.js
flipping data-composer-action and the type with it.

**Audio.** Speech to text and text to speech against any OpenAI-shaped
/v1/audio/* endpoint: dictate into the composer, have a reply read out.
Instance settings in Admin, per-reader overrides in Settings, with the voice
list discovered from the server where it offers one. Recorded audio is capped
and never written to disk -- it is not an attachment, it has no owner, and
nothing would ever sweep it.

**Web search, as a tool.** This is the tool loop PLAN.md described as the real
work: one reply is now a bounded sequence of requests rather than one. The model
asks, the tool runs, the result goes back and it is asked again, up to three
rounds. Providers are DuckDuckGo (no setup), SearXNG and Firecrawl.

Two decisions worth stating. Tools are only offered to models flagged `tools`,
because an endpoint without support rejects the whole request rather than
ignoring the array -- the same reason images only reach models flagged
`vision`. And tool results are not replayed as context on the next turn, for the
same reasons reasoning is not: the answer already contains what the model made
of them, and replaying stale results into every later request wastes the window
and reliably sends a small model into a search loop. The sources stay visible in
the transcript instead.

Search results are untrusted third-party text and are treated as such: escaped,
and only http/https URLs rendered as links.

338 tests, ruff clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jaroslav Beneš
2026-07-21 17:56:50 +02:00
parent ca3e4fd04f
commit 436226370a
61 changed files with 4481 additions and 116 deletions
+88
View File
@@ -0,0 +1,88 @@
"""DuckDuckGo, via the ddgs package.
The default provider because it is the only one that works with no account, no
key and no server to run: enabling web search should not also be a
configuration exercise.
Optional at install time -- see the `search` extra in pyproject.toml -- so the
import is guarded and its absence is reported as something to install rather
than as a crash.
"""
from __future__ import annotations
import asyncio
from typing import Any
from lembas.services.search.base import SearchError, SearchResult, clean
try: # pragma: no cover - exercised by whether the extra is installed
from ddgs import DDGS
_IMPORT_ERROR = ""
except ImportError as exc: # pragma: no cover
DDGS = None
_IMPORT_ERROR = str(exc)
def is_available() -> bool:
return DDGS is not None
def _blocking_search(query: str, count: int, region: str, safesearch: str) -> list[dict[str, Any]]:
with DDGS() as client:
return list(
client.text(
query,
region=region or "wt-wt",
safesearch=safesearch or "moderate",
max_results=count,
)
)
async def search(config: dict[str, Any], query: str, count: int) -> list[SearchResult]:
if not is_available():
raise SearchError(
'The ddgs package is not installed. Install it with: pip install "lembas[search]"'
)
try:
# ddgs is synchronous. Run it on a thread: blocking the event loop here
# would stall every other chat in the process, including the one that
# asked for the search.
rows = await asyncio.wait_for(
asyncio.to_thread(
_blocking_search,
query,
count,
str(config.get("region") or "wt-wt"),
str(config.get("safesearch") or "moderate"),
),
timeout=float(config.get("timeout") or 20.0),
)
except TimeoutError as exc:
raise SearchError("DuckDuckGo did not answer in time.") from exc
except Exception as exc: # noqa: BLE001 - the library raises its own types
# Rate limiting is the common failure and worth naming, because the fix
# is to wait rather than to change anything.
detail = str(exc)
if "ratelimit" in detail.lower() or "202" in detail:
raise SearchError(
"DuckDuckGo is rate limiting this instance. Try again shortly, "
"or configure SearXNG instead."
) from exc
raise SearchError(f"DuckDuckGo search failed: {detail[:200]}") from exc
results = []
for row in rows:
# ddgs renamed its fields across versions; both spellings are read so
# an upgrade does not silently return empty snippets.
result = clean(
row.get("title"),
row.get("href") or row.get("url") or row.get("link"),
row.get("body") or row.get("description") or row.get("snippet"),
)
if result is not None:
results.append(result)
return results