436226370a
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>
76 lines
2.7 KiB
Python
76 lines
2.7 KiB
Python
"""Firecrawl's hosted search API.
|
|
|
|
The paid option, and the only one of the three that needs a key. Included
|
|
because it answers with cleaned page content rather than a search engine's
|
|
snippet, which is materially better material for a model to read.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
import httpx
|
|
|
|
from lembas.services.crypto import decrypt
|
|
from lembas.services.search.base import SearchError, SearchResult, clean
|
|
|
|
DEFAULT_BASE_URL = "https://api.firecrawl.dev"
|
|
|
|
|
|
async def search(config: dict[str, Any], query: str, count: int) -> list[SearchResult]:
|
|
api_key = decrypt(str(config.get("firecrawl_api_key_encrypted") or ""))
|
|
if not api_key:
|
|
raise SearchError("No Firecrawl API key has been configured.")
|
|
|
|
base_url = str(config.get("firecrawl_base_url") or DEFAULT_BASE_URL).strip().rstrip("/")
|
|
|
|
try:
|
|
async with httpx.AsyncClient(timeout=float(config.get("timeout") or 20.0)) as client:
|
|
response = await client.post(
|
|
f"{base_url}/v1/search",
|
|
headers={
|
|
"Authorization": f"Bearer {api_key}",
|
|
"Content-Type": "application/json",
|
|
},
|
|
json={"query": query, "limit": count},
|
|
)
|
|
except httpx.RequestError as exc:
|
|
raise SearchError(f"Could not reach {base_url}: {exc}") from exc
|
|
|
|
if response.status_code == 401:
|
|
raise SearchError("Firecrawl rejected the API key.")
|
|
if response.status_code == 402:
|
|
raise SearchError("The Firecrawl account is out of credit.")
|
|
|
|
try:
|
|
payload = response.json()
|
|
except ValueError as exc:
|
|
raise SearchError(f"Firecrawl returned HTTP {response.status_code}.") from exc
|
|
|
|
if response.status_code >= 400 or (
|
|
isinstance(payload, dict) and payload.get("success") is False
|
|
):
|
|
detail = payload.get("error") if isinstance(payload, dict) else ""
|
|
raise SearchError(str(detail) or f"Firecrawl returned HTTP {response.status_code}.")
|
|
|
|
rows = payload.get("data") if isinstance(payload, dict) else None
|
|
# Newer responses nest the list under data.web; older ones put it directly
|
|
# in data. Both are read so an API revision does not empty the results.
|
|
if isinstance(rows, dict):
|
|
rows = rows.get("web")
|
|
if not isinstance(rows, list):
|
|
raise SearchError("Firecrawl returned a response in an unexpected shape.")
|
|
|
|
results = []
|
|
for row in rows[:count]:
|
|
if not isinstance(row, dict):
|
|
continue
|
|
result = clean(
|
|
row.get("title"),
|
|
row.get("url"),
|
|
row.get("description") or row.get("markdown") or row.get("content"),
|
|
)
|
|
if result is not None:
|
|
results.append(result)
|
|
return results
|