One reader for every event stream, one error shape, the unused lint waivers gone

services/llm/sse.py reads every server-sent stream the server consumes — a
model's reply, an Anthropic reply, the /v1 relay, a remote MCP server — with
the rules the CLI's reader has: an unterminated last line is a frame, a bare
{"error":…} line inside a 200 is the error it is, comments pass through for
a relay's keep-alives. A server error before any output is retried once. A
tool-call fragment without an index continues the last call, in chats and
through /v1 alike, from one accumulator. The three /v1 error helpers and the
four admin redirect helpers are one each. RUF100 is on and the waivers it
found unused are gone. The pinned-open route nothing posted to is removed;
the stored value is still read and carried over.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.1 committed 2026-10-18 04:41:30 +02:00
1 parent 14c228d634
commit bedc8d51db
57 files changed
+893 -329

No files matched your search

+44
View File
@@ -39,6 +39,30 @@ Every chat can keep a plan, and any chat can be put into Plan mode.
you does not count. They are instance settings (`loop_wall_seconds`,
`loop_output_bytes`, `loop_completion_tokens` under General; 0 turns one
off), without a field on the settings page yet.
- **An agent chat knows what the instance knows.** A chat on a linked device
now gets the instructions it would get here -- the chat's own, its folder's,
its model's or the instance's -- your personalization, which knowledge
bases it may search, and whether it may write a prototype, sent with the
session and again on every message, so a change made here reaches the
device's next turn (harness spec 1.1.0, `_meta.lembas` on `session/new`
and `session/prompt`; a LLeMbas CLI 1.3.0, each piece on its capability).
- **The plan card for a device chat is the structured one.** A device sends
its plan as the same structure a chat here keeps, so the panel above the
message box, the card in the reply and the plan it asks you to approve
are drawn as for any other chat -- and a chat taken up again after a
restart draws the plan the device has, without waiting for the next
change. A device without it still sends its todo list, shown as before.
- **Edit and Regenerate on agent chats**, with a LLeMbas CLI 1.3.0: the
device drops the turn and every later one from the conversation its model
reads, and the edited or repeated message goes as a new turn. The files
the device changed are not undone, and the controls say so. With an older
CLI, or while the device is not linked, the controls stay hidden as before.
- **The library scoped to the chat for a device.** A library call the CLI
makes for an agent chat names the chat's session (`_meta.lembas.scope` on
`/mcp`), and is answered within that chat's scope -- its knowledge bases
and its data group, exactly as the chat loop's own tools are; a session
that is not that device's is refused. Without a scope, the account's
default group, as before.
### Changed
@@ -79,6 +103,15 @@ Every chat can keep a plan, and any chat can be put into Plan mode.
- Dead stylesheet rules for the background-jobs panel, the talk-rules matrix
and form, the old model picker, the admin page header, the connection card's
header and footer, the directory row and the history sentinel are gone.
- Every event stream LLeMbas reads -- a model's reply, an Anthropic reply, a
reply relayed through the `/v1` API, an MCP server's answer -- is read by one
parser, which knows what servers really send: a last line with no newline
after it, Windows line endings, a frame split over several `data:` lines,
keep-alive comments, and frames with no blank line between them.
- A model's server failing before it had sent any of the reply -- llama-swap
saying the model was unloaded because another client loaded a different
one, or any other server error -- is asked once more before the failure is
shown, since a second request usually succeeds.
### Fixed
@@ -97,6 +130,14 @@ Every chat can keep a plan, and any chat can be put into Plan mode.
- Opening a thinking or tool block while a reply streams no longer stops the
page following the reply after the next tool call, and the open thinking
box stays open as the block it becomes.
- A streaming error a server sends as a bare line inside a 200 reply --
llama.cpp's way, often as the very last line -- is shown as the error it is,
not as an empty reply; through the `/v1` API it is passed on as a proper
error frame. An error a server frames as data is read the same way.
- A tool call whose fragments arrive without an index is assembled onto the
right call: the one started last, not the first. A reply through an
Anthropic connection to the non-streaming `/v1` API reassembles its tool
calls by the same rule.
### Removed
@@ -106,6 +147,9 @@ Every chat can keep a plan, and any chat can be put into Plan mode.
CLI has assembled itself since agent chats moved there. They were on the
prompts page and reached no model.
- The todo list above the composer, replaced by the plan.
- The old `POST /api/preferences/pinned-open` route, which nothing has posted
to since 1.2.0 moved every sidebar section's state into one map. A choice
stored under the old key is still read until the next change retires it.
## 1.2.0 — 2026-10-14
+1 -1
View File
@@ -77,7 +77,7 @@ target-version = "py311"
src = ["src", "tests"]
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B", "SIM", "C4"]
select = ["E", "F", "I", "UP", "B", "SIM", "C4", "RUF100"]
ignore = ["B008"] # FastAPI Depends() in defaults is idiomatic
[tool.ruff.lint.per-file-ignores]
+1 -1
View File
@@ -43,7 +43,7 @@ RELEASE_TAG = re.compile(r"^v\d+\.\d+\.\d+$")
def _get(url: str) -> bytes:
request = urllib.request.Request(url, headers={"User-Agent": "lembas-fetch-harness"})
with urllib.request.urlopen(request, timeout=60) as response: # noqa: S310 - a fixed https forge
with urllib.request.urlopen(request, timeout=60) as response: # a fixed https forge
return response.read()
+1 -1
View File
@@ -87,7 +87,7 @@ def sha256(data: bytes) -> str:
def fetch(url: str) -> bytes:
request = urllib.request.Request(url, headers={"User-Agent": "lembas-vendor-fetch"})
with urllib.request.urlopen(request, timeout=60) as response: # noqa: S310
with urllib.request.urlopen(request, timeout=60) as response:
return response.read()
+20
View File
@@ -0,0 +1,20 @@
"""The redirect a form handler answers with: back to its page, with a word."""
from __future__ import annotations
from urllib.parse import quote
from fastapi import status
from fastapi.responses import RedirectResponse, Response
def back(path: str, message: str = "", *, ok: bool = True) -> Response:
"""See Other to `path`, carrying `message` as `?saved=` -- or `?error=`
when it is not good news -- for the page to show; nothing when there is
nothing to say."""
if not message:
return RedirectResponse(path, status_code=status.HTTP_303_SEE_OTHER)
field = "saved" if ok else "error"
return RedirectResponse(
f"{path}?{field}={quote(message)}", status_code=status.HTTP_303_SEE_OTHER
)
+3 -5
View File
@@ -3,11 +3,11 @@
from __future__ import annotations
import logging
from urllib.parse import quote
from functools import partial
from fastapi import APIRouter, Form, HTTPException, Request, Response, status
from fastapi.responses import RedirectResponse
from lembas.api._redirect import back
from lembas.api.deps import AdminUser, Db
from lembas.db.models import Suggestion
from lembas.services import suggestions as suggestions_service
@@ -26,9 +26,7 @@ def _suggestion(db: Db, suggestion_id: str) -> Suggestion:
return suggestion
def _back(message: str = "") -> Response:
target = f"/admin/suggestions?saved={quote(message)}" if message else "/admin/suggestions"
return RedirectResponse(target, status_code=status.HTTP_303_SEE_OTHER)
_back = partial(back, "/admin/suggestions")
@router.get("")
+5 -9
View File
@@ -16,12 +16,12 @@ import json
import logging
import re
from datetime import UTC, datetime
from urllib.parse import quote
from functools import partial
from fastapi import APIRouter, HTTPException, Request, Response, status
from fastapi.responses import RedirectResponse
from sqlalchemy import func, select
from lembas.api._redirect import back
from lembas.api.deps import AdminUser, Db
from lembas.db.models import (
RESPONSE_JSON,
@@ -102,9 +102,7 @@ def _ordered(db: Db) -> list[CustomTool]:
return list(db.scalars(select(CustomTool).order_by(CustomTool.position, CustomTool.slug)))
def _back(message: str = "") -> Response:
target = f"/admin/tools?saved={quote(message)}" if message else "/admin/tools"
return RedirectResponse(target, status_code=status.HTTP_303_SEE_OTHER)
_back = partial(back, "/admin/tools")
# --- Form <-> row ------------------------------------------------------------
@@ -205,7 +203,7 @@ def _problem(db: Db, tool: CustomTool, form, *, existing_id: str = "") -> str:
# is refused here rather than at the first call.
try:
custom_tools.fill_url(custom_tools.spec_from(tool), {})
except Exception as exc: # noqa: BLE001 - any refusal is a message for the form
except Exception as exc: # any refusal is a message for the form
return str(getattr(exc, "message", exc))
return ""
@@ -450,9 +448,7 @@ def _server(db: Db, server_id: str) -> McpServer:
return server
def _mcp_back(message: str = "") -> Response:
target = f"/admin/mcp?saved={quote(message)}" if message else "/admin/mcp"
return RedirectResponse(target, status_code=status.HTTP_303_SEE_OTHER)
_mcp_back = partial(back, "/admin/mcp")
def _populate_server(server: McpServer, form) -> None:
+4 -7
View File
@@ -23,13 +23,14 @@ Every change is an audit event.
from __future__ import annotations
from datetime import UTC, date, datetime
from functools import partial
from typing import Any
from urllib.parse import quote
from fastapi import APIRouter, Body, Form, Header, HTTPException, Request, status
from fastapi.responses import RedirectResponse, Response
from fastapi.responses import Response
from sqlalchemy import select
from lembas.api._redirect import back
from lembas.api.deps import Db, RequiredUser
from lembas.db.models import (
ENTRY_ADJUST,
@@ -59,11 +60,7 @@ def _guard(db, user: User) -> None:
raise HTTPException(status.HTTP_403_FORBIDDEN, i18n.t("You may not manage credits."))
def _back(message: str, ok: bool = True) -> Response:
field = "saved" if ok else "error"
return RedirectResponse(
f"/admin/credits?{field}={quote(message)}", status_code=status.HTTP_303_SEE_OTHER
)
_back = partial(back, "/admin/credits")
@router.get("/admin/credits")
+1 -1
View File
@@ -739,7 +739,7 @@ async def healthz() -> Response:
try:
with session_scope() as db:
db.execute(text("SELECT 1"))
except Exception: # noqa: BLE001 - the answer is the status code
except Exception: # the answer is the status code
return JSONResponse({"status": "error"}, status_code=503)
return JSONResponse({"status": "ok"})
-19
View File
@@ -170,25 +170,6 @@ async def set_sidebar_kind(
)
@router.post("/pinned-open")
async def set_pinned_open(db: Db, user: RequiredUser, state: str = Form("1")) -> Response:
"""Remember whether `[ PINNED MODELS ]` is open or closed.
On the account, not in `localStorage`, because the sidebar renders it: the
server writes `open` into the `<details>`, so the group is drawn the way it
was left with no flash -- and the same way after the Chats/Agents switch
swaps it out of band, which re-renders it from this. Posted by app.js on the
element's `toggle` event; nothing comes back to swap, the browser already
shows the new state.
Anything other than "0" is open, so a malformed request can only leave the
shortcuts showing.
"""
# Kept for a page loaded before an update, whose app.js still
# posts here; it lands in the one map every section now uses.
return _store_section(db, user, "pinned", state != "0")
def _store_section(db, user, key: str, is_open: bool) -> Response:
from lembas.api.pages import SECTION_DEFAULTS, SECTIONS_KEY
+1 -1
View File
@@ -160,7 +160,7 @@ async def terminal_socket(
except ExecError as exc:
await _refuse(websocket, str(exc))
return
except Exception: # noqa: BLE001 - a failure here is one socket, not the app
except Exception: # a failure here is one socket, not the app
log.exception("could not open a terminal for %s", owner_email)
await _refuse(websocket, t("The shell could not be started."))
return
+3 -5
View File
@@ -9,11 +9,13 @@ audit log.
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from functools import partial
from urllib.parse import quote
from fastapi import APIRouter, HTTPException, Request, status
from fastapi.responses import RedirectResponse, Response
from lembas.api._redirect import back
from lembas.api.deps import AdminUser, Db, RequiredUser
from lembas.db.models import ApiToken, User
from lembas.security import api_tokens, permissions
@@ -26,11 +28,7 @@ router = APIRouter(tags=["tokens"])
EXPIRY_CHOICES = (0, 30, 90, 365)
def _back(message: str, *, ok: bool = True) -> Response:
field = "saved" if ok else "error"
return RedirectResponse(
f"/settings?{field}={quote(message)}", status_code=status.HTTP_303_SEE_OTHER
)
_back = partial(back, "/settings")
@router.post("/api/tokens")
+15
View File
@@ -0,0 +1,15 @@
"""What the `/v1` modules share."""
from __future__ import annotations
from fastapi.responses import JSONResponse
def error_response(
status_code: int, message: str, kind: str = "invalid_request_error"
) -> JSONResponse:
"""OpenAI's error shape, which every client already knows how to print."""
return JSONResponse(
{"error": {"message": message, "type": kind, "code": status_code}},
status_code=status_code,
)
+19 -23
View File
@@ -34,6 +34,7 @@ from fastapi import APIRouter, Request
from fastapi.responses import FileResponse, JSONResponse, Response
from lembas.api.deps import Db
from lembas.api.v1._common import error_response
from lembas.security import permissions
from lembas.security.api_tokens import ModelsCaller
from lembas.services import settings_store
@@ -48,13 +49,6 @@ FORMATS = ("url", "b64_json")
_SIZE = re.compile(r"^\s*(\d{1,5})\s*[xX×]\s*(\d{1,5})\s*$")
def _error(status_code: int, message: str, kind: str = "invalid_request_error") -> JSONResponse:
return JSONResponse(
{"error": {"message": message, "type": kind, "code": status_code}},
status_code=status_code,
)
def available(db, user) -> bool:
"""Whether this person may draw through the API: the instance can draw, and
they hold the permission a chat's tool asks for."""
@@ -111,45 +105,45 @@ async def generations(request: Request, db: Db, caller: ModelsCaller):
user = caller.user
if not available(db, user):
return _error(404, "Image generation is not on for this account on this instance.")
return error_response(404, "Image generation is not on for this account on this instance.")
try:
body = await request.json()
except (ValueError, UnicodeDecodeError):
body = None
if not isinstance(body, dict):
return _error(400, "The body must be a JSON object.")
return error_response(400, "The body must be a JSON object.")
prompt = str(body.get("prompt") or "").strip()
if not prompt:
return _error(400, "`prompt` is required: what to draw.")
return error_response(400, "`prompt` is required: what to draw.")
values = settings_store.images(db)
try:
count = int(body.get("n") or 1)
except (TypeError, ValueError):
return _error(400, "`n` must be a whole number.")
return error_response(400, "`n` must be a whole number.")
cap = int(values["api_max_images"])
if not 1 <= count <= cap:
return _error(400, f"`n` is 1 to {cap} on this instance.")
return error_response(400, f"`n` is 1 to {cap} on this instance.")
response_format = str(body.get("response_format") or "url")
if response_format not in FORMATS:
return _error(400, "`response_format` is url or b64_json.")
return error_response(400, "`response_format` is url or b64_json.")
checkpoint, unknown = _checkpoint(str(body.get("model") or ""), values)
if unknown:
return _error(
return error_response(
404, f"There is no model {body.get('model')!r} here. GET /v1/models lists them.",
"not_found_error",
)
if checkpoint is None:
return _error(404, "No checkpoint is listed on this instance.")
return error_response(404, "No checkpoint is listed on this instance.")
# The two budgets, before a minute of somebody's GPU is spent.
if over := usage_service.over_image_budget(db, user):
return _error(429, over, "rate_limit_error")
return error_response(429, over, "rate_limit_error")
price = float(values["per_image"])
if short := credits_service.service_refusal(db, user, price):
return _error(429, short, "rate_limit_error")
return error_response(429, short, "rate_limit_error")
ceiling = permissions.limit(db, user, "images_per_day")
if ceiling and usage_service.images_today(db, user.id) + count > ceiling:
return _error(
return error_response(
429, f"That would be more than this account's {ceiling} image(s) for today.",
"rate_limit_error",
)
@@ -157,7 +151,7 @@ async def generations(request: Request, db: Db, caller: ModelsCaller):
rows, _ = _choices(db, values)
chosen = _pick(rows, "", "", values)
if chosen is None:
return _error(404, "No image workflow has been set up on this instance.")
return error_response(404, "No image workflow has been set up on this instance.")
template = json.loads(json.dumps(chosen.workflow_json or {}))
slug = chosen.slug
given: dict[str, Any] = {"prompt": prompt, "model": checkpoint}
@@ -187,7 +181,7 @@ async def generations(request: Request, db: Db, caller: ModelsCaller):
except comfy.ComfyError as exc:
log.info("an image through the API failed: %s", exc.message)
if not pictures:
return _error(502, f"The image could not be generated: {exc.message}",
return error_response(502, f"The image could not be generated: {exc.message}",
"upstream_error")
base = str(request.base_url).rstrip("/")
@@ -228,7 +222,9 @@ async def generations(request: Request, db: Db, caller: ModelsCaller):
)
session.commit()
if not data:
return _error(502, "The images were generated but could not be saved.", "upstream_error")
return error_response(
502, "The images were generated but could not be saved.", "upstream_error"
)
return JSONResponse({"created": int(time.time()), "data": data})
@@ -248,10 +244,10 @@ async def file_content(db: Db, caller: ModelsCaller, attachment_id: str) -> Resp
attachment = db.get(Attachment, attachment_id)
if attachment is None or attachment.user_id != caller.user.id:
return _error(404, "There is no such file.", "not_found_error")
return error_response(404, "There is no such file.", "not_found_error")
path = files_service.stored_path(attachment.stored_name)
if path is None:
return _error(404, "That file is no longer on disk.", "not_found_error")
return error_response(404, "That file is no longer on disk.", "not_found_error")
return FileResponse(
path,
media_type=attachment.media_type if attachment.is_image else "application/octet-stream",
+60 -44
View File
@@ -49,9 +49,11 @@ from fastapi.responses import JSONResponse, StreamingResponse
from sqlalchemy.orm import Session as DBSession
from lembas.api.deps import Db
from lembas.api.v1._common import error_response
from lembas.config import settings
from lembas.db.models import MODEL_CHAT, MODEL_EMBEDDING, MODEL_KINDS, Connection, Model, User
from lembas.security.api_tokens import ModelsCaller
from lembas.services.llm import sse
from lembas.services.llm.openai_client import (
Endpoint,
LLMError,
@@ -267,14 +269,6 @@ async def list_models(db: Db, caller: ModelsCaller) -> dict[str, Any]:
return {"object": "list", "data": data}
def _error(status_code: int, message: str, kind: str = "invalid_request_error") -> JSONResponse:
"""OpenAI's error shape, which every client already knows how to print."""
return JSONResponse(
{"error": {"message": message, "type": kind, "code": status_code}},
status_code=status_code,
)
def _refusal(db: DBSession, user: User, model: Model | None = None) -> str:
from lembas.security import permissions
from lembas.services import credits as credits_service
@@ -375,17 +369,17 @@ async def chat_completions(request: Request, db: Db, caller: ModelsCaller):
body = await _read_json(request)
wanted = str(body.get("model") or "")
if not wanted:
return _error(400, "`model` is required.")
return error_response(400, "`model` is required.")
try:
served = resolve(db, caller.user, wanted)
except HTTPException as exc:
return _error(exc.status_code, str(exc.detail), "not_found_error")
return error_response(exc.status_code, str(exc.detail), "not_found_error")
if kind_of(served.model) == MODEL_EMBEDDING:
return _error(
return error_response(
400, f"{served.id} is an embedding model: send it to /v1/embeddings."
)
if reason := _refusal(db, caller.user, served.model):
return _error(429, reason, "rate_limit_error")
return error_response(429, reason, "rate_limit_error")
model_row_id, token_id = served.model.id, caller.token.id
endpoint = Endpoint.from_connection(served.connection)
@@ -407,12 +401,18 @@ async def chat_completions(request: Request, db: Db, caller: ModelsCaller):
try:
response.raise_for_status()
except httpx.HTTPStatusError as exc:
return _error(response.status_code, describe_http_error(exc), "upstream_error")
return error_response(
response.status_code, describe_http_error(exc), "upstream_error"
)
data = response.json()
except httpx.RequestError as exc:
return _error(502, f"The model's server could not be reached: {exc}", "upstream_error")
return error_response(
502, f"The model's server could not be reached: {exc}", "upstream_error"
)
except ValueError:
return _error(502, "The model's server answered with something that is not JSON.")
return error_response(
502, "The model's server answered with something that is not JSON."
)
finally:
_IN_FLIGHT[user_id] = max(0, _IN_FLIGHT.get(user_id, 1) - 1)
if isinstance(data, dict):
@@ -441,7 +441,9 @@ async def chat_completions(request: Request, db: Db, caller: ModelsCaller):
except httpx.RequestError as exc:
await client.aclose()
_IN_FLIGHT[user_id] = max(0, _IN_FLIGHT.get(user_id, 1) - 1)
return _error(502, f"The model's server could not be reached: {exc}", "upstream_error")
return error_response(
502, f"The model's server could not be reached: {exc}", "upstream_error"
)
if upstream_response.status_code >= 400:
await upstream_response.aread()
await client.aclose()
@@ -449,29 +451,39 @@ async def chat_completions(request: Request, db: Db, caller: ModelsCaller):
try:
upstream_response.raise_for_status()
except httpx.HTTPStatusError as exc:
return _error(upstream_response.status_code, describe_http_error(exc), "upstream_error")
return error_response(
upstream_response.status_code, describe_http_error(exc), "upstream_error"
)
async def relay() -> AsyncIterator[bytes]:
usage: dict[str, Any] | None = None
try:
async for line in upstream_response.aiter_lines():
stripped = line.strip()
if stripped.startswith("data:"):
data = stripped[5:].strip()
if data and data != "[DONE]":
try:
frame = json.loads(data)
except json.JSONDecodeError:
frame = None
if isinstance(frame, dict):
if frame.get("usage"):
usage = frame["usage"]
frame["model"] = served.id
yield f"data: {json.dumps(frame, ensure_ascii=False)}\n\n".encode()
continue
yield (stripped + "\n\n").encode()
elif stripped.startswith(":"):
yield (stripped + "\n\n").encode()
async for event, data in sse.iter_sse(upstream_response.aiter_lines()):
if event == sse.COMMENT:
yield f":{data}\n\n".encode() # a keep-alive, passed on as one
continue
if event == sse.ERROR:
# Written outside the frame format upstream (quirks.json
# `error-in-200-stream`); framed properly here, so the
# client reads the error it is rather than an empty reply.
frame = sse.error_object(data)
yield f"data: {json.dumps(frame, ensure_ascii=False)}\n\n".encode()
continue
data = data.strip()
if not data:
continue
if data != sse.DONE:
try:
frame = json.loads(data)
except json.JSONDecodeError:
frame = None
if isinstance(frame, dict):
if frame.get("usage"):
usage = frame["usage"]
frame["model"] = served.id
yield f"data: {json.dumps(frame, ensure_ascii=False)}\n\n".encode()
continue
yield f"data: {data}\n\n".encode()
finally:
await upstream_response.aclose()
await client.aclose()
@@ -513,7 +525,7 @@ async def _anthropic(
try:
data = await anthropic_client.complete_response(endpoint, upstream)
except LLMError as exc:
return _error(exc.status_code or 502, exc.message, "upstream_error")
return error_response(exc.status_code or 502, exc.message, "upstream_error")
finally:
_release(user_id)
await asyncio.to_thread(_record, user_id, data.get("usage"), 1, model_row_id, token_id)
@@ -527,7 +539,7 @@ async def _anthropic(
first = None
except LLMError as exc:
_release(user_id)
return _error(exc.status_code or 502, exc.message, "upstream_error")
return error_response(exc.status_code or 502, exc.message, "upstream_error")
async def relay() -> AsyncIterator[bytes]:
usage: dict[str, Any] | None = None
@@ -570,20 +582,20 @@ async def embeddings(request: Request, db: Db, caller: ModelsCaller):
try:
served = resolve(db, caller.user, str(body.get("model") or ""))
except HTTPException as exc:
return _error(exc.status_code, str(exc.detail), "not_found_error")
return error_response(exc.status_code, str(exc.detail), "not_found_error")
endpoint = Endpoint.from_connection(served.connection)
try:
require_openai(endpoint, "embeddings")
except LLMError as exc:
return _error(400, exc.message)
return error_response(400, exc.message)
if not takes_embeddings(served.model):
return _error(
return error_response(
400,
f"{served.id} is a chat model: send it to /v1/chat/completions, or an "
"embedding model here.",
)
if reason := _refusal(db, caller.user, served.model):
return _error(429, reason, "rate_limit_error")
return error_response(429, reason, "rate_limit_error")
upstream = {**body, "model": served.model.model_id}
started = time.monotonic()
try:
@@ -595,12 +607,16 @@ async def embeddings(request: Request, db: Db, caller: ModelsCaller):
try:
response.raise_for_status()
except httpx.HTTPStatusError as exc:
return _error(response.status_code, describe_http_error(exc), "upstream_error")
return error_response(
response.status_code, describe_http_error(exc), "upstream_error"
)
data = response.json()
except httpx.RequestError as exc:
return _error(502, f"The model's server could not be reached: {exc}", "upstream_error")
return error_response(
502, f"The model's server could not be reached: {exc}", "upstream_error"
)
except ValueError:
return _error(502, "The model's server answered with something that is not JSON.")
return error_response(502, "The model's server answered with something that is not JSON.")
if isinstance(data, dict):
# Counted and charged like a reply, on the model's input price: the
# caller asked for these vectors. The library's own index is the one
+20 -26
View File
@@ -37,6 +37,7 @@ from starlette.datastructures import UploadFile
from lembas import __version__
from lembas.api.deps import Db
from lembas.api.v1._common import error_response
from lembas.security import permissions
from lembas.security.api_tokens import ModelsCaller
from lembas.services import audio as audio_service
@@ -65,13 +66,6 @@ def connection_name(name: str) -> str:
return slug[:40].strip("-") or "lembas"
def _error(status_code: int, message: str, kind: str = "invalid_request_error") -> JSONResponse:
return JSONResponse(
{"error": {"message": message, "type": kind, "code": status_code}},
status_code=status_code,
)
def _audio_user(user) -> dict[str, Any]:
return dict((user.settings_json or {}).get("audio") or {})
@@ -133,19 +127,19 @@ async def transcriptions(request: Request, db: Db, caller: ModelsCaller):
"""OpenAI's transcription call: a multipart `file`, and optionally
`language` and `prompt`. `model` is ignored -- the instance's is used."""
if not available(db, caller.user)["stt"]:
return _error(404, "Speech to text is not on for this account on this instance.")
return error_response(404, "Speech to text is not on for this account on this instance.")
form = await request.form()
upload = form.get("file")
if not isinstance(upload, UploadFile):
return _error(400, "`file` is required: the recording.")
return error_response(400, "`file` is required: the recording.")
data = await upload.read(MAX_AUDIO_BYTES + 1)
if len(data) > MAX_AUDIO_BYTES:
return _error(413, "That recording is too long.")
return error_response(413, "That recording is too long.")
if not data:
return _error(400, "The recording was empty.")
return error_response(400, "The recording was empty.")
# Credits, as a reply's: a priced transcription is gated first.
if short := audio_service.refusal(db, caller.user, "stt"):
return _error(429, short, "rate_limit_error")
return error_response(429, short, "rate_limit_error")
config = settings_store.audio(db)
asked = form.get("language")
language = (
@@ -165,7 +159,7 @@ async def transcriptions(request: Request, db: Db, caller: ModelsCaller):
)
except LLMError as exc:
log.info("transcription through the API failed: %s", exc.message)
return _error(502, exc.message, "upstream_error")
return error_response(502, exc.message, "upstream_error")
audio_service.record_transcription(db, caller.user.id, seconds, token_id=caller.token.id)
return JSONResponse({"text": text})
@@ -178,20 +172,20 @@ async def speech(request: Request, db: Db, caller: ModelsCaller):
from lembas.api.audio import resolve_speed, resolve_voice
if not available(db, caller.user)["tts"]:
return _error(404, "Text to speech is not on for this account on this instance.")
return error_response(404, "Text to speech is not on for this account on this instance.")
try:
body = await request.json()
except (ValueError, UnicodeDecodeError):
body = None
if not isinstance(body, dict):
return _error(400, "The body must be a JSON object.")
return error_response(400, "The body must be a JSON object.")
text = str(body.get("input") or "").strip()
if not text:
return _error(400, "`input` is required: the text to speak.")
return error_response(400, "`input` is required: the text to speak.")
if len(text) > MAX_SPEECH_CHARS:
return _error(413, f"That is more than {MAX_SPEECH_CHARS} characters.")
return error_response(413, f"That is more than {MAX_SPEECH_CHARS} characters.")
if short := audio_service.refusal(db, caller.user, "tts"):
return _error(429, short, "rate_limit_error")
return error_response(429, short, "rate_limit_error")
config = settings_store.audio(db)
voice = str(body.get("voice") or "").strip() or resolve_voice(config, caller.user)
try:
@@ -210,7 +204,7 @@ async def speech(request: Request, db: Db, caller: ModelsCaller):
)
except LLMError as exc:
log.info("speech through the API failed: %s", exc.message)
return _error(502, exc.message, "upstream_error")
return error_response(502, exc.message, "upstream_error")
audio_service.record_speech(db, caller.user.id, len(text), token_id=caller.token.id)
return StreamingResponse(
stream, media_type=media_type, headers={"Cache-Control": "no-store"}
@@ -233,10 +227,10 @@ async def web_search(request: Request, db: Db, caller: ModelsCaller):
from lembas.services.search import SearchError
if not available(db, caller.user)["search"]:
return _error(404, "Web search is not on for this account on this instance.")
return error_response(404, "Web search is not on for this account on this instance.")
body = await _json(request)
if body is None:
return _error(400, "The body must be a JSON object.")
return error_response(400, "The body must be a JSON object.")
config = settings_store.search(db)
try:
limit = int(body["max_results"]) if body.get("max_results") is not None else None
@@ -245,7 +239,7 @@ async def web_search(request: Request, db: Db, caller: ModelsCaller):
try:
results = await search_service.run(config, str(body.get("query") or ""), limit=limit)
except SearchError as exc:
return _error(502, exc.message, "upstream_error")
return error_response(502, exc.message, "upstream_error")
return JSONResponse(
{
"provider": str(config.get("provider") or "ddgs"),
@@ -262,20 +256,20 @@ async def web_fetch(request: Request, db: Db, caller: ModelsCaller):
from lembas.services import fetch as fetch_service
if not available(db, caller.user)["fetch"]:
return _error(404, "Fetching pages is not on for this account on this instance.")
return error_response(404, "Fetching pages is not on for this account on this instance.")
body = await _json(request)
if body is None:
return _error(400, "The body must be a JSON object.")
return error_response(400, "The body must be a JSON object.")
url = str(body.get("url") or "").strip()
if not url:
return _error(400, "`url` is required.")
return error_response(400, "`url` is required.")
config = settings_store.search(db)
try:
page = await fetch_service.fetch(
url, allow_private=bool(config.get("allow_private_fetch"))
)
except fetch_service.FetchError as exc:
return _error(502, exc.message, "upstream_error")
return error_response(502, exc.message, "upstream_error")
return JSONResponse(
{"url": page.url, "title": page.title, "text": page.text, "truncated": page.truncated}
)
+4 -4
View File
@@ -55,7 +55,7 @@ def _default_shape(column: Column) -> type | None:
try:
# SQLAlchemy wraps a zero-argument callable to take a context.
produced = default.arg(None)
except Exception: # noqa: BLE001 - a default we cannot call tells us nothing
except Exception: # a default we cannot call tells us nothing
return None
if isinstance(produced, list):
return list
@@ -473,7 +473,7 @@ def sync_schema(engine: Engine) -> list[str]:
for step in (prices_to_money, backfill_entry_costs, infer_model_kinds):
try:
changes.extend(step(engine))
except Exception: # noqa: BLE001 - a conversion that fails must not stop a start
except Exception: # a conversion that fails must not stop a start
log.exception("could not run %s", step.__name__)
# Before the search indexes, and before anything can try to load a row:
@@ -481,13 +481,13 @@ def sync_schema(engine: Engine) -> list[str]:
try:
for repair in repair_json_shapes(engine):
changes.append(f"repair {repair}")
except Exception: # noqa: BLE001 - a repair that fails must not stop a start
except Exception: # a repair that fails must not stop a start
log.exception("could not repair JSON column shapes")
try:
for index in ensure_fts(engine):
changes.append(f"create search index {index}")
except Exception: # noqa: BLE001 - search is not worth refusing to start over
except Exception: # search is not worth refusing to start over
log.exception("could not create the full-text search indexes")
if changes:
+1 -1
View File
@@ -18,7 +18,7 @@ _SessionFactory: sessionmaker[Session] | None = None
@event.listens_for(Engine, "connect")
def _configure_sqlite(dbapi_connection, connection_record) -> None: # noqa: ANN001
def _configure_sqlite(dbapi_connection, connection_record) -> None:
"""Apply the pragmas SQLite needs to behave under a concurrent web server.
- WAL lets readers proceed while a write is in flight, which matters because
+3 -3
View File
@@ -116,7 +116,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
sweep_chunks(db)
# Three starting points on the empty screen, written once ever.
seed_suggestions(db)
except Exception: # noqa: BLE001 - housekeeping must never block startup
except Exception: # housekeeping must never block startup
log.exception("orphaned upload sweep failed")
# Schedules. `release_claims` first, because a firing interrupted by the
@@ -138,7 +138,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
if released:
log.info("released %s interrupted schedule claim(s)", released)
start_ticker()
except Exception: # noqa: BLE001 - scheduling failing must not block startup
except Exception: # scheduling failing must not block startup
log.exception("could not start the schedule ticker")
# Replies the last shutdown cut off are taken up again, after the
@@ -152,7 +152,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
try:
with session_scope() as db:
api_only = settings_store.api_only(db)
except Exception: # noqa: BLE001 - the mode unreadable is the mode it was before
except Exception: # the mode unreadable is the mode it was before
api_only = False
resuming = asyncio.get_running_loop().create_task(
+1 -1
View File
@@ -520,7 +520,7 @@ async def _reaper_loop() -> None:
_reap()
except asyncio.CancelledError:
raise
except Exception: # noqa: BLE001 - the reaper must outlive one bad sweep
except Exception: # the reaper must outlive one bad sweep
log.exception("the terminal reaper raised")
+2 -2
View File
@@ -120,7 +120,7 @@ def measure_seconds(data: bytes, reported: Any = None) -> float:
rate = recording.getframerate()
if rate:
return recording.getnframes() / rate
except Exception: # noqa: BLE001 - a header that lies is measured by its size
except Exception: # a header that lies is measured by its size
pass
return len(data) / ASSUMED_BYTES_PER_SECOND
@@ -388,7 +388,7 @@ def record_speech(db, user_id: str, characters: int, *, token_id: str | None = N
def _commit(db) -> None:
try:
db.commit()
except Exception: # noqa: BLE001 - bookkeeping must never break the request
except Exception: # bookkeeping must never break the request
db.rollback()
log.warning("could not record speech usage", exc_info=True)
+2 -2
View File
@@ -101,7 +101,7 @@ def record(
)
)
db.commit()
except Exception: # noqa: BLE001 - the log must never break what it records
except Exception: # the log must never break what it records
log.warning("could not write audit event %s", action, exc_info=True)
@@ -281,7 +281,7 @@ class AdminAuditMiddleware:
target_id=path[:64],
summary=f"{request.method} {path}",
)
except Exception: # noqa: BLE001 - the log must never break what it records
except Exception: # the log must never break what it records
log.warning("could not audit an admin change", exc_info=True)
+1 -1
View File
@@ -170,7 +170,7 @@ def snapshot() -> Branding:
with session_scope() as db:
_CACHE = _read(db)
except Exception: # noqa: BLE001 - defaults are a usable answer, an exception is not
except Exception: # defaults are a usable answer, an exception is not
log.debug("could not read the instance name; using the default", exc_info=True)
return build()
return _CACHE
+2 -2
View File
@@ -504,7 +504,7 @@ def charge(
usage=usage,
commit=commit,
)
except Exception: # noqa: BLE001 - bookkeeping must never break a reply
except Exception: # bookkeeping must never break a reply
log.warning("could not charge credits to %s", user_id, exc_info=True)
return 0
@@ -542,7 +542,7 @@ def charge_service(
token_id=token_id,
commit=commit,
)
except Exception: # noqa: BLE001 - bookkeeping must never break a request
except Exception: # bookkeeping must never break a request
log.warning("could not charge %s to %s", service, user_id, exc_info=True)
return 0
+4 -4
View File
@@ -147,7 +147,7 @@ def limits() -> Limits:
),
reject_unreadable_pdf=bool(values.get("reject_unreadable_pdf")),
)
except Exception: # noqa: BLE001 - the shipped defaults are a usable answer
except Exception: # the shipped defaults are a usable answer
log.debug("could not read extraction settings; using defaults", exc_info=True)
return Limits()
return _LIMITS
@@ -279,7 +279,7 @@ def _process_pdf(payload: bytes) -> Prepared:
# An empty password unlocks a surprising number of "encrypted" PDFs.
try:
reader.decrypt("")
except Exception: # noqa: BLE001 - any failure means the same thing
except Exception: # any failure means the same thing
prepared.extraction_error = (
"This PDF is password-protected, so its text could not be read."
)
@@ -292,7 +292,7 @@ def _process_pdf(payload: bytes) -> Prepared:
for index, page in enumerate(reader.pages[:bounds.max_pdf_pages]):
try:
text = page.extract_text() or ""
except Exception as exc: # noqa: BLE001 - one bad page is not fatal
except Exception as exc: # one bad page is not fatal
log.debug("page %d of a PDF failed to extract: %s", index, exc)
continue
if not text.strip():
@@ -319,7 +319,7 @@ def _process_pdf(payload: bytes) -> Prepared:
except PdfReadError as exc:
prepared.extraction_error = "This file is not a readable PDF."
log.info("unreadable PDF: %s", exc)
except Exception as exc: # noqa: BLE001 - never let a bad file 500 the upload
except Exception as exc: # never let a bad file 500 the upload
prepared.extraction_error = "This PDF could not be read."
log.warning("unexpected PDF failure: %s", exc)
+8 -8
View File
@@ -534,7 +534,7 @@ async def resume_interrupted(delay: float = 20.0) -> int:
row.origin = ORIGIN_ATTACH
row.interrupted = True
db.commit()
except Exception: # noqa: BLE001 - never stops the instance from starting
except Exception: # never stops the instance from starting
log.exception("could not mark unfinished device replies")
await asyncio.sleep(delay)
started: list[tuple[str, str]] = []
@@ -573,7 +573,7 @@ async def resume_interrupted(delay: float = 20.0) -> int:
)
started.append((chat.id, reply.id))
db.commit()
except Exception: # noqa: BLE001 - never stops the instance from starting
except Exception: # never stops the instance from starting
log.exception("could not take up interrupted replies")
return 0
for chat_id, message_id in started:
@@ -669,7 +669,7 @@ def _learn_refused_effort(model_id: str, refused: str, message: str) -> None:
"model %s refused reasoning effort %r; efforts narrowed to %s",
model_id, refused, wanted,
)
except Exception: # noqa: BLE001 - never let bookkeeping fail a reply
except Exception: # never let bookkeeping fail a reply
log.exception("could not record the refused effort for model %s", model_id)
@@ -1257,7 +1257,7 @@ async def _run(generation: Generation) -> None:
generation.stopped = True
generation.interrupted = True
raise
except Exception: # noqa: BLE001 - a task that dies silently is worse
except Exception: # a task that dies silently is worse
generation.error = i18n.t("Something went wrong while generating this reply.")
log.exception("unexpected generation failure for chat %s", generation.chat_id)
finally:
@@ -1444,7 +1444,7 @@ async def _maybe_compact(generation: Generation) -> None:
compaction_service.apply(chat, summary=summary, upto=upto)
db.commit()
log.info("chat %s compacted automatically through %s", chat.id, upto_id)
except Exception: # noqa: BLE001 - the reply matters more than the tidy-up
except Exception: # the reply matters more than the tidy-up
log.exception("automatic compaction failed for chat %s", generation.chat_id)
finally:
generation.status = ""
@@ -2163,7 +2163,7 @@ def _drain(generation: Generation) -> None:
db, chat, ROLE_ASSISTANT, "", complete_=False, model_id=chat.model_id
)
chat_id, assistant_id = chat.id, assistant.id
except Exception: # noqa: BLE001 - the reply is over either way
except Exception: # the reply is over either way
log.exception("could not drain the queue for chat %s", generation.chat_id)
return
@@ -2225,7 +2225,7 @@ def _inject(
placeholder.created_at = datetime.now(UTC)
generation.injected_ids.append(waiting.id)
waiting_id = waiting.id
except Exception: # noqa: BLE001 - a lost interjection is not a failed reply
except Exception: # a lost interjection is not a failed reply
log.exception("could not take a queued prompt into chat %s", chat_id)
return None
@@ -2409,7 +2409,7 @@ def _persist(generation: Generation, title: str, elapsed: float) -> None:
len(message.reasoning),
elapsed,
)
except Exception: # noqa: BLE001 - the task is ending either way
except Exception: # the task is ending either way
log.exception("could not persist generation for chat %s", generation.chat_id)
+1 -1
View File
@@ -338,7 +338,7 @@ async def free(config: Config) -> None:
headers=config.headers(),
json={"unload_models": True, "free_memory": True},
)
except Exception: # noqa: BLE001 - a hint that failed is not a failed generation
except Exception: # a hint that failed is not a failed generation
log.debug("could not free ComfyUI at %s", config.base_url, exc_info=True)
+5 -5
View File
@@ -294,7 +294,7 @@ async def _unload_llm(context: ToolContext) -> bool:
if connection is not None:
url = (connection.unload_url or "").strip()
method = (connection.unload_method or "POST").upper()
except Exception: # noqa: BLE001 - a hint that could not be looked up is not a failure
except Exception: # a hint that could not be looked up is not a failure
log.debug("could not read the unload hook", exc_info=True)
return False
@@ -304,7 +304,7 @@ async def _unload_llm(context: ToolContext) -> bool:
async with httpx.AsyncClient(timeout=UNLOAD_TIMEOUT) as client:
await client.request(method, url)
return True
except Exception: # noqa: BLE001 - see the module docstring: a hint, not a step
except Exception: # see the module docstring: a hint, not a step
log.info("could not unload the model at %s", url, exc_info=True)
return False
@@ -375,7 +375,7 @@ def _reviewer(context: ToolContext) -> tuple[Endpoint, str] | None:
if connection is None or not connection.enabled:
return None
return Endpoint.from_connection(connection), model.model_id
except Exception: # noqa: BLE001 - no reviewer is a degraded mode, not an error
except Exception: # no reviewer is a degraded mode, not an error
log.warning("could not resolve an image reviewer", exc_info=True)
return None
@@ -514,7 +514,7 @@ async def run(context: ToolContext, args: dict[str, Any]) -> ToolOutcome:
template_slug, template_name = chosen.slug, chosen.name
except ToolOutcome: # pragma: no cover - defensive
raise
except Exception as exc: # noqa: BLE001
except Exception as exc:
log.exception("could not resolve an image workflow")
return ToolOutcome(
f"The image workflow could not be read: {exc}",
@@ -627,7 +627,7 @@ async def run(context: ToolContext, args: dict[str, Any]) -> ToolOutcome:
quantity=1,
note="image: 1 picture(s)",
)
except Exception as exc: # noqa: BLE001
except Exception as exc:
log.exception("could not store a generated image")
return ToolOutcome(
f"The image was generated but could not be saved: {exc}",
+1 -1
View File
@@ -114,7 +114,7 @@ def _api_only() -> bool:
with session_scope() as db:
return settings_store.api_only(db)
except Exception: # noqa: BLE001
except Exception:
log.debug("could not read the instance mode; treating it as full", exc_info=True)
return False
+2 -2
View File
@@ -76,12 +76,12 @@ def search_ids(
try:
rows = db.execute(
text(
f"SELECT id, bm25({index}) AS rank FROM {index} " # noqa: S608 - see above
f"SELECT id, bm25({index}) AS rank FROM {index} " # see above
f"WHERE {index} MATCH :q ORDER BY rank LIMIT :limit"
),
{"q": query, "limit": max(1, min(limit, 100))},
).fetchall()
except Exception: # noqa: BLE001 - a broken index must not break the page
except Exception: # a broken index must not break the page
log.exception("full-text search failed on %s", index)
# Rolled back because a failed statement leaves the session
# unusable: without this, one broken search turns into every later
+2 -2
View File
@@ -315,7 +315,7 @@ async def index_resource(kind: str, resource_id: str, *, force: bool = False) ->
return 0
except asyncio.CancelledError:
raise
except Exception: # noqa: BLE001 - one bad record must not stop a rebuild
except Exception: # one bad record must not stop a rebuild
log.exception("indexing %s %s failed", kind, resource_id)
return 0
@@ -515,7 +515,7 @@ async def rebuild_all(*, force: bool = True) -> None:
except asyncio.CancelledError:
_PROGRESS.error = "Stopped."
raise
except Exception as exc: # noqa: BLE001 - a rebuild failing must be reportable
except Exception as exc: # a rebuild failing must be reportable
log.exception("rebuilding the index failed")
_PROGRESS.error = str(exc)
finally:
+27 -22
View File
@@ -57,6 +57,7 @@ from typing import Any
import httpx
from lembas.config import settings
from lembas.services.llm import sse
from lembas.services.llm.openai_client import Endpoint, LLMError, wrap_transport_error
log = logging.getLogger(__name__)
@@ -771,11 +772,19 @@ async def stream_chat(
if not 200 <= response.status_code < 300:
await response.aread()
raise _error_from(response)
async for line in response.aiter_lines():
line = line.strip()
if not line.startswith("data:"):
continue # `event:` lines repeat the type the data carries
data = line[5:].strip()
# The `event:` name is not read: it repeats the `type` the data carries.
async for name, data in sse.iter_sse(response.aiter_lines()):
if name == sse.COMMENT:
continue
if name == sse.ERROR:
# Written outside the frame format, as a proxy in front of
# the API might (quirks.json `error-in-200-stream`).
error = sse.error_object(data)["error"]
raise LLMError(
f"Anthropic stopped the reply: {sse.error_message(error)}",
status_code=sse.error_status(error),
)
data = data.strip()
if not data:
continue
try:
@@ -800,6 +809,7 @@ async def complete_response(endpoint: Endpoint, payload: dict[str, Any]) -> dict
at the mercy of one HTTP request's timeout, and there is one parser, not two.
"""
from lembas.services.llm.openai_client import (
ToolCallAccumulator,
delta_reasoning,
delta_text,
delta_tool_calls,
@@ -808,7 +818,7 @@ async def complete_response(endpoint: Endpoint, payload: dict[str, Any]) -> dict
text: list[str] = []
reasoning: list[str] = []
calls: dict[int, dict[str, Any]] = {}
calls = ToolCallAccumulator()
finish = "stop"
usage: dict[str, Any] | None = None
blocks: list[dict[str, Any]] = []
@@ -817,17 +827,7 @@ async def complete_response(endpoint: Endpoint, payload: dict[str, Any]) -> dict
response_id = chunk.get("id") or response_id
text.append(delta_text(chunk))
reasoning.append(delta_reasoning(chunk))
for fragment in delta_tool_calls(chunk):
slot = calls.setdefault(
int(fragment.get("index") or 0),
{"id": "", "type": "function", "function": {"name": "", "arguments": ""}},
)
if fragment.get("id"):
slot["id"] = fragment["id"]
function = fragment.get("function") or {}
if function.get("name"):
slot["function"]["name"] = function["name"]
slot["function"]["arguments"] += function.get("arguments") or ""
calls.feed(delta_tool_calls(chunk))
finish = finish_reason(chunk) or finish
if chunk.get("usage"):
usage = chunk["usage"]
@@ -837,11 +837,16 @@ async def complete_response(endpoint: Endpoint, payload: dict[str, Any]) -> dict
if any(reasoning):
message["reasoning_content"] = "".join(reasoning)
if calls:
for call in calls.values():
# A tool called with no input streams no JSON at all; an OpenAI
# client parses `arguments`, and "" is not JSON.
call["function"]["arguments"] = call["function"]["arguments"] or "{}"
message["tool_calls"] = [calls[i] for i in sorted(calls)]
message["tool_calls"] = [
{
"id": call["id"],
"type": "function",
# A tool called with no input streams no JSON at all; an OpenAI
# client parses `arguments`, and "" is not JSON.
"function": {"name": call["name"], "arguments": call["arguments"] or "{}"},
}
for call in calls.calls
]
if blocks:
message["assistant_blocks"] = blocks
out: dict[str, Any] = {
+133 -21
View File
@@ -26,6 +26,7 @@ import httpx
from lembas.config import settings
from lembas.db.models import Connection
from lembas.services.crypto import decrypt
from lembas.services.llm import sse
log = logging.getLogger(__name__)
@@ -44,6 +45,26 @@ class LLMError(Exception):
self.status_code = status_code
class StreamError(LLMError):
"""An error the server wrote inside a 200 event stream (quirks.json
`error-in-200-stream`, `model-unloaded`).
Its own class because the HTTP status was fine: the retry that drops
`stream_options` after a 400 is about the request, and must not fire for a
400 the model's server reported while already answering.
"""
def _stream_error(error_object: dict[str, Any]) -> StreamError:
"""The LLMError for an error object found inside a stream."""
error = error_object.get("error")
message = sse.error_message(error)
return StreamError(
message or "The endpoint reported an error inside the reply.",
status_code=sse.error_status(error),
)
@dataclass(frozen=True)
class Endpoint:
"""Everything needed to call a connection, with the key already decrypted.
@@ -324,20 +345,39 @@ async def stream_chat(
return
wants_usage = endpoint.base_url not in _NO_STREAM_OPTIONS
retried_server_error = False
try:
async for chunk in _stream_once(endpoint, payload, usage=wants_usage):
yield chunk
except LLMError as exc:
if not wants_usage or exc.status_code not in (400, 422):
while True:
sent = False
try:
async for chunk in _stream_once(endpoint, payload, usage=wants_usage):
sent = True
yield chunk
return
except LLMError as exc:
# Once a chunk has reached the caller the reply is under way, and a
# second request would duplicate what was already shown.
if sent:
raise
if wants_usage and exc.status_code in (400, 422) and not isinstance(exc, StreamError):
_NO_STREAM_OPTIONS.add(endpoint.base_url)
log.info(
"%s rejected stream_options; token counts will be estimated there",
endpoint.base_url,
)
wants_usage = False
continue
# A server error before anything was streamed is retried once: often
# the model's own output failing the server's parser, or the model
# swapped out from under the request by another client (llama-swap's
# "model unloaded" frame, quirks.json `model-unloaded`). Sampling
# differs on a second go.
if (exc.status_code or 0) >= 500 and not retried_server_error:
retried_server_error = True
log.info("%s: server error before any output, retrying once: %s",
endpoint.base_url, exc.message)
continue
raise
_NO_STREAM_OPTIONS.add(endpoint.base_url)
log.info(
"%s rejected stream_options; token counts will be estimated there",
endpoint.base_url,
)
async for chunk in _stream_once(endpoint, payload, usage=False):
yield chunk
async def _stream_once(
@@ -366,21 +406,29 @@ async def _stream_once(
await response.aread()
response.raise_for_status()
async for line in response.aiter_lines():
line = line.strip()
if not line or line.startswith(":"):
continue # keep-alive comment
if not line.startswith("data:"):
async for event, data in sse.iter_sse(response.aiter_lines()):
if event == sse.COMMENT:
continue # keep-alive
if event == sse.ERROR:
# llama.cpp's mid-stream failure: a bare error line inside a
# 200, often the stream's unterminated last line.
raise _stream_error(sse.error_object(data))
data = data.strip()
if not data:
continue
data = line[5:].strip()
if data == "[DONE]":
if data == sse.DONE:
return
try:
yield json.loads(data)
chunk = json.loads(data)
except json.JSONDecodeError:
# A malformed frame is not worth killing a reply over.
log.warning("skipping unparseable SSE frame: %.120s", data)
continue
if isinstance(chunk, dict) and chunk.get("error"):
# An error framed as data (quirks.json `error-in-200-stream`):
# the error it is, not a chunk with nothing in it.
raise _stream_error(chunk)
yield chunk
except httpx.HTTPStatusError as exc:
raise LLMError(describe_http_error(exc), status_code=exc.response.status_code) from exc
@@ -442,7 +490,7 @@ def delta_tool_calls(chunk: dict[str, Any]) -> list[dict[str, Any]]:
Each entry carries an ``index`` and, across chunks, a name that arrives
once and an ``arguments`` string that arrives in pieces. Reassembling them
is lembas.services.tools.ToolCallAccumulator's job; this only extracts.
is `ToolCallAccumulator`'s job; this only extracts.
"""
try:
choices = chunk.get("choices") or []
@@ -454,6 +502,70 @@ def delta_tool_calls(chunk: dict[str, Any]) -> list[dict[str, Any]]:
return []
class ToolCallAccumulator:
"""Reassembles tool calls arriving as streamed fragments.
An endpoint sends ``delta.tool_calls`` as a list of partial objects: the id
and the function name arrive once, and ``arguments`` arrives as a string
split across however many chunks the tokeniser produced. Entries are keyed
by ``index`` because that is the only field guaranteed on every fragment --
the id is absent from continuations, and matching on name breaks the moment
a model calls the same tool twice in one turn.
Some llama.cpp builds omit the index (quirks.json `tool-call-without-index`,
conformance `toolcall_index.json`): such a fragment continues the call
started last, and the first fragment of a stream without one starts call 0.
Arguments are concatenated as text, never parsed on the way.
"""
def __init__(self) -> None:
self._calls: dict[int, dict[str, Any]] = {}
self._last = 0
def feed(self, fragments: list[dict[str, Any]]) -> None:
if not isinstance(fragments, list):
return
for fragment in fragments:
if not isinstance(fragment, dict):
continue
index = fragment.get("index")
if not isinstance(index, int) or isinstance(index, bool):
index = self._last
self._last = index
call = self._calls.setdefault(index, {"id": "", "name": "", "arguments": ""})
if fragment.get("id"):
call["id"] = str(fragment["id"])
function = fragment.get("function") or {}
if isinstance(function, dict):
if function.get("name"):
call["name"] = str(function["name"])
arguments = function.get("arguments")
if isinstance(arguments, str):
call["arguments"] += arguments
elif isinstance(arguments, dict):
# A server that sends the arguments already parsed.
call["arguments"] += json.dumps(arguments, ensure_ascii=False)
@property
def calls(self) -> list[dict[str, Any]]:
"""Completed calls, in the order the endpoint indexed them."""
return [
{
# An id is required when the results are sent back, and not
# every server supplies one.
"id": call["id"] or f"call_{index}",
"name": call["name"],
"arguments": call["arguments"],
}
for index, call in sorted(self._calls.items())
if call["name"]
]
def __bool__(self) -> bool:
return bool(self.calls)
def assistant_blocks(chunk: dict[str, Any]) -> list[dict[str, Any]]:
"""The assistant turn in its endpoint's own words, when a chunk carries it.
+174
View File
@@ -0,0 +1,174 @@
"""Reading server-sent events -- the one parser every stream in LLeMbas reads with.
`services/sse.py` is the writer; this is the reader, and it exists because four
hand-written ones had each learned a different lesson about what servers
really send. Everything they learned is here:
- `data:` lines are gathered until a blank line and joined with newlines, as
the SSE specification says; an `event:` line names the frame; a line
starting with `:` is a comment (a keep-alive, usually) and is passed on as
one so a relay can forward it.
- **The last line may have no newline after it** -- llama.cpp behind llama-swap
ends a failed stream exactly that way -- so whatever is pending when the
lines run out is dispatched like any other frame.
- **An error may be a bare `{"error": ...}` line inside a 200**, with no
`data:` in front of it (quirks.json `error-in-200-stream`). By the letter of
the specification that is a field called `{"error"` and would be ignored,
silently ending the reply as an empty one. It is dispatched as an `error`
event instead, and so is a line whose field is literally `error:`.
- Some servers omit the blank line between frames. A pending frame that is
already complete JSON is dispatched when the next `data:` line arrives,
rather than being joined to it into something that parses as nothing.
`[DONE]` is dispatched as ordinary data: what it means is the caller's
business, and a relay wants to pass it on.
The LLeMbas CLI's `provider/sse.ts` is the same parser in TypeScript; a case
one of them learns goes into the other.
"""
from __future__ import annotations
import json
from collections.abc import AsyncIterable, AsyncIterator, Iterable, Iterator
from typing import Any
# The reader's own event names begin with ":", which an `event:` line never
# yields (see `SseParser.feed`), so a server's `event: error` -- Anthropic names
# its error frames that -- reaches the caller as the named data frame it is.
# A comment line.
COMMENT = ":"
# An error a server wrote outside the frame format.
ERROR = ":error"
# What an OpenAI-compatible server sends to say the reply is over.
DONE = "[DONE]"
class SseParser:
"""Incremental: feed it lines, collect frames. `flush()` when the lines end."""
def __init__(self) -> None:
self._event = ""
self._data: list[str] = []
def feed(self, line: str) -> list[tuple[str, str]]:
"""The frames this line completes: (event name or "", data)."""
if line.endswith("\r"):
line = line[:-1]
if not line:
return self._dispatch()
if line.startswith(":"):
return [(COMMENT, line[1:])]
if line.startswith("{") and _is_error_object(line):
return [*self._dispatch(), (ERROR, line)]
field, colon, value = line.partition(":")
if colon and value.startswith(" "):
value = value[1:]
if field == "data":
out = self._dispatch() if self._data and _is_json("\n".join(self._data)) else []
self._data.append(value)
return out
if field == "event":
# A name beginning with ":" is reserved for this reader's own frames.
self._event = "" if value.startswith(":") else value
return []
if field == "error":
return [*self._dispatch(), (ERROR, value)]
return [] # `id`, `retry`, and anything this reader has no use for
def flush(self) -> list[tuple[str, str]]:
"""Whatever is pending: the frame an unterminated last line belongs to."""
return self._dispatch()
def _dispatch(self) -> list[tuple[str, str]]:
if not self._data:
self._event = ""
return []
frame = (self._event, "\n".join(self._data))
self._event = ""
self._data = []
return [frame]
def parse_sse(lines: Iterable[str]) -> Iterator[tuple[str, str]]:
"""Every frame in `lines`, which carry no line endings (`str.splitlines()`)."""
parser = SseParser()
for line in lines:
yield from parser.feed(line)
yield from parser.flush()
async def iter_sse(lines: AsyncIterable[str]) -> AsyncIterator[tuple[str, str]]:
"""`parse_sse` over a response's `aiter_lines()`."""
parser = SseParser()
async for line in lines:
for frame in parser.feed(line):
yield frame
for frame in parser.flush():
yield frame
def error_object(data: str) -> dict[str, Any]:
"""The error an `error` frame carries, in OpenAI's shape: `{"error": {...}}`.
A bare JSON line already has that shape. An `error:` field may carry JSON
or a sentence; either way the result has an `error` member to read.
"""
try:
parsed = json.loads(data)
except json.JSONDecodeError:
parsed = None
if isinstance(parsed, dict) and "error" in parsed:
return parsed
return {"error": parsed if parsed is not None else data}
def error_status(error: Any) -> int | None:
"""The HTTP status an error object inside a stream stands for.
A numeric `code` or `status` is one. llama-swap's "model unloaded" frame
(quirks.json `model-unloaded`) carries `type: "server_error"` and a string
code; that, `overloaded_error`, `api_error` and any code naming something
internal are a 500, so the server-error rule (retried once, before anything
was streamed) applies to them.
"""
if not isinstance(error, dict):
return None
code = error.get("code")
if isinstance(code, int) and not isinstance(code, bool):
return code
status = error.get("status")
if isinstance(status, int) and not isinstance(status, bool):
return status
if error.get("type") in ("server_error", "overloaded_error", "api_error"):
return 500
if "internal" in str(code or "").lower():
return 500
return None
def error_message(error: Any) -> str:
"""The words of an error object, whatever shape it came in."""
if isinstance(error, dict):
message = error.get("message")
if isinstance(message, str) and message.strip():
return message.strip()
return json.dumps(error, ensure_ascii=False)
return str(error).strip()
def _is_json(text: str) -> bool:
try:
json.loads(text)
except json.JSONDecodeError:
return False
return True
def _is_error_object(line: str) -> bool:
try:
parsed = json.loads(line)
except json.JSONDecodeError:
return False
return isinstance(parsed, dict) and "error" in parsed
+11 -13
View File
@@ -18,6 +18,7 @@ from contextlib import suppress
from typing import Any
from lembas import __version__
from lembas.services.llm import sse
# What we tell a server we speak. A server answering an older version is not
# refused: several in the wild still answer 2024-11-05 and work perfectly.
@@ -77,20 +78,17 @@ def _messages(body: bytes, content_type: str) -> list[dict[str, Any]]:
raise McpError(f"That server did not answer with JSON: {exc}") from exc
return document if isinstance(document, list) else [document]
# Frames are `data:` lines gathered until a blank line -- the same framing
# services/sse.py writes. Read here rather than shared, because that module
# is a writer and this is a reader with a size cap.
# Frames are `data:` lines gathered until a blank line, read by the one
# SSE reader (services/llm/sse.py); the size cap is the caller's.
out: list[dict[str, Any]] = []
data: list[str] = []
for line in text.splitlines() + [""]:
if line.startswith("data:"):
data.append(line[5:].lstrip())
elif not line.strip() and data:
# A frame that is not JSON is a comment or a keep-alive, not a
# message; the stream carries both.
with suppress(json.JSONDecodeError):
out.append(json.loads("\n".join(data)))
data = []
for event, data in sse.parse_sse(text.splitlines()):
if event == sse.COMMENT:
continue # a keep-alive, not a message
# A frame that is not JSON is not a message either; the stream carries
# both. An error a server wrote outside the frame format is read as a
# message, which `result_of` then answers for.
with suppress(json.JSONDecodeError):
out.append(json.loads(data))
return out
+1 -1
View File
@@ -76,7 +76,7 @@ async def _read(connection) -> dict[str, str]:
entries = await asyncio.wait_for(
list_models(Endpoint.from_connection(connection)), TIMEOUT
)
except Exception: # noqa: BLE001 - an unreachable endpoint has no state, not an error page
except Exception: # an unreachable endpoint has no state, not an error page
log.debug("model state unavailable for %s", connection.name, exc_info=True)
# Not cached: the next open asks again, which is right for an endpoint
# that is merely starting up.
+2 -2
View File
@@ -263,7 +263,7 @@ async def send_one(db: DBSession, subscription: PushSubscription, payload: dict[
body, p256dh=subscription.p256dh, auth=subscription.auth_secret
)
token = _jwt(keys(db).private, _audience(subscription.endpoint), subject_for(db))
except Exception: # noqa: BLE001 - a malformed stored key must not kill a reply
except Exception: # a malformed stored key must not kill a reply
log.exception("could not build a push for %s", subscription.id)
return False
@@ -396,7 +396,7 @@ def announce_later(user_id: str, *, title: str, body: str, url: str = "", kind:
if user is None:
return
await announce(db, user, title=title, body=body, url=url, kind=kind)
except Exception: # noqa: BLE001 - nothing upstream can act on this
except Exception: # nothing upstream can act on this
log.exception("could not announce to %s", user_id)
task = asyncio.create_task(run())
+1 -1
View File
@@ -255,7 +255,7 @@ async def fire(schedule_id: str, *, due_at: datetime | None = None) -> None:
await deliver(schedule_id, message_id, since=began)
except asyncio.CancelledError:
raise
except Exception: # noqa: BLE001 - one bad schedule must not stop the rest
except Exception: # one bad schedule must not stop the rest
log.exception("schedule %s failed to fire", schedule_id)
with contextlib.suppress(Exception), session_scope() as db:
schedule = db.get(Schedule, schedule_id)
+3 -3
View File
@@ -135,7 +135,7 @@ async def sweep(*, now: datetime | None = None) -> int:
fire_now, _ = claim(schedule, now=now, zone=clock.zone_for(owner))
if fire_now:
to_fire.append((schedule.id, due_at))
except Exception: # noqa: BLE001 - one bad row must not stop the sweep
except Exception: # one bad row must not stop the sweep
log.exception("could not claim schedule %s", schedule.id)
with contextlib.suppress(Exception):
schedule.enabled = False
@@ -199,7 +199,7 @@ def tidy(*, force: bool = False) -> None:
from lembas.services import credits
credits.renew_due(db)
except Exception: # noqa: BLE001 - housekeeping must never stop the ticker
except Exception: # housekeeping must never stop the ticker
log.exception("the ticker's housekeeping raised")
@@ -228,7 +228,7 @@ async def _loop() -> None:
await sweep()
except asyncio.CancelledError:
raise
except Exception: # noqa: BLE001 - the ticker must outlive one bad sweep
except Exception: # the ticker must outlive one bad sweep
log.exception("the schedule ticker raised")
+1 -1
View File
@@ -63,7 +63,7 @@ async def search(config: dict[str, Any], query: str, count: int) -> list[SearchR
)
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
except Exception as exc: # 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)
+1 -1
View File
@@ -346,7 +346,7 @@ def _cleanup(chat_id: str, *, keep: bool) -> None:
# `db.delete` would leave both on disk with the row that named
# them gone.
chat_service.delete_chats(db, [chat])
except Exception: # noqa: BLE001 - tidying up is not the result
except Exception: # tidying up is not the result
log.debug("could not remove subagent chat %s", chat_id, exc_info=True)
+2 -53
View File
@@ -43,6 +43,7 @@ from lembas.services.library import documents as documents_service
from lembas.services.library import memories as memories_service
from lembas.services.library import notes as notes_service
from lembas.services.library import skills as skills_service
from lembas.services.llm.openai_client import ToolCallAccumulator
from lembas.services.search.base import SearchError
from lembas.web.i18n import N_
@@ -2119,7 +2120,7 @@ async def run_tool(
parsed = parse_arguments(tool, arguments)
try:
return await tool.run(context, parsed)
except Exception as exc: # noqa: BLE001 - a tool must never kill the reply
except Exception as exc: # a tool must never kill the reply
log.exception("tool %s failed", name)
return ToolOutcome(
f"The {name} tool failed: {exc}",
@@ -2127,58 +2128,6 @@ async def run_tool(
)
class ToolCallAccumulator:
"""Reassembles tool calls arriving as streamed fragments.
An endpoint sends ``delta.tool_calls`` as a list of partial objects: the id
and the function name arrive once, and ``arguments`` arrives as a string
split across however many chunks the tokeniser produced. Entries are keyed
by ``index`` because that is the only field guaranteed on every fragment --
the id is absent from continuations, and matching on name breaks the moment
a model calls the same tool twice in one turn.
"""
def __init__(self) -> None:
self._calls: dict[int, dict[str, Any]] = {}
def feed(self, fragments: list[dict[str, Any]]) -> None:
for fragment in fragments:
if not isinstance(fragment, dict):
continue
index = fragment.get("index")
if not isinstance(index, int):
# Some servers omit index entirely when there is only one call.
index = 0
call = self._calls.setdefault(index, {"id": "", "name": "", "arguments": ""})
if fragment.get("id"):
call["id"] = str(fragment["id"])
function = fragment.get("function") or {}
if isinstance(function, dict):
if function.get("name"):
call["name"] = str(function["name"])
arguments = function.get("arguments")
if isinstance(arguments, str):
call["arguments"] += arguments
@property
def calls(self) -> list[dict[str, Any]]:
"""Completed calls, in the order the endpoint indexed them."""
return [
{
# An id is required when the results are sent back, and not
# every server supplies one.
"id": call["id"] or f"call_{index}",
"name": call["name"],
"arguments": call["arguments"],
}
for index, call in sorted(self._calls.items())
if call["name"]
]
def __bool__(self) -> bool:
return bool(self.calls)
def assistant_turn(
calls: list[dict[str, Any]],
+2 -2
View File
@@ -242,7 +242,7 @@ def _git(args: list[str], *, cwd: Path, timeout: float = GIT_TIMEOUT) -> tuple[i
a thing to report on the page, not a 500.
"""
try:
done = subprocess.run( # noqa: S603 - fixed argv, no shell, admin-only
done = subprocess.run( # fixed argv, no shell, admin-only
["git", *args],
cwd=str(cwd),
capture_output=True,
@@ -254,7 +254,7 @@ def _git(args: list[str], *, cwd: Path, timeout: float = GIT_TIMEOUT) -> tuple[i
return 127, "git is not installed on this machine."
except subprocess.TimeoutExpired:
return 124, f"git took longer than {int(timeout)}s."
except Exception as exc: # noqa: BLE001 - a broken git is a message, not a crash
except Exception as exc: # a broken git is a message, not a crash
log.debug("git %s failed", args, exc_info=True)
return 1, str(exc)
return done.returncode, (done.stdout or done.stderr or "").strip()
+3 -3
View File
@@ -169,7 +169,7 @@ async def apply(who: str) -> str:
return t("The update helper is not installed on this host.")
try:
taken = await asyncio.to_thread(backup.take, f"before-{STATE.wanted or 'update'}")
except Exception as exc: # noqa: BLE001 - no update without a backup
except Exception as exc: # no update without a backup
log.exception("pre-update backup failed")
return t(
"The backup before the update failed, so nothing was requested: %(error)s", error=exc
@@ -202,7 +202,7 @@ def _tell_admins(title: str, body: str) -> None:
push.announce_later(
admin.id, title=title, body=body, url="/admin/updates", kind="update"
)
except Exception: # noqa: BLE001 - a notification is never worth failing over
except Exception: # a notification is never worth failing over
log.debug("could not tell the administrators", exc_info=True)
@@ -264,7 +264,7 @@ async def tick(*, now: float | None = None, moment: datetime | None = None) -> N
return
problem = await apply("an administrator" if STATE.manual else "automatic")
STATE.error = problem
except Exception: # noqa: BLE001 - the ticker must outlive one bad pass
except Exception: # the ticker must outlive one bad pass
log.exception("the automatic update check raised")
+3 -3
View File
@@ -71,7 +71,7 @@ def record(
row.replies += max(0, int(replies))
row.audio_seconds = (row.audio_seconds or 0) + max(0, math.ceil(audio_seconds))
row.speech_chars = (row.speech_chars or 0) + max(0, int(speech_chars))
except Exception: # noqa: BLE001 - bookkeeping must never break a reply
except Exception: # bookkeeping must never break a reply
log.debug("could not record usage for %s", user_id, exc_info=True)
@@ -93,7 +93,7 @@ def record_token(
token.usage_completion_tokens = 0
token.usage_prompt_tokens += max(0, int(prompt_tokens))
token.usage_completion_tokens += max(0, int(completion_tokens))
except Exception: # noqa: BLE001 - bookkeeping must never break a reply
except Exception: # bookkeeping must never break a reply
log.debug("could not record usage for token %s", token_id, exc_info=True)
@@ -110,7 +110,7 @@ def images_today(db: DBSession, user_id: str) -> int:
and a second reset. The month's total on `Usage.images` is for the admin
screen, where a number that is a day stale costs nothing.
"""
start = datetime.combine(date.today(), datetime.min.time(), tzinfo=UTC) # noqa: DTZ011
start = datetime.combine(date.today(), datetime.min.time(), tzinfo=UTC)
return int(
db.scalar(
select(func.count())
+2 -2
View File
@@ -67,7 +67,7 @@ async def wake_chat(chat_id: str, content: str, *, model_id: str = "") -> str:
if settings_store.api_only(db):
log.info("not waking chat %s: this instance serves the API only", chat_id)
return ""
except Exception: # noqa: BLE001 - unreadable is "full", what it was before
except Exception: # unreadable is "full", what it was before
log.debug("could not read the instance mode for chat %s", chat_id, exc_info=True)
assistant_id = ""
@@ -96,7 +96,7 @@ async def wake_chat(chat_id: str, content: str, *, model_id: str = "") -> str:
model_id=model_id or chat.model_id,
)
assistant_id = assistant.id
except Exception: # noqa: BLE001 - a failed wake must not kill its caller
except Exception: # a failed wake must not kill its caller
log.exception("could not wake chat %s", chat_id)
return ""
+2 -2
View File
@@ -117,7 +117,7 @@ def instance_default() -> str:
with session_scope() as db:
_DEFAULT = known(settings_store.get(db, "language"))
except Exception: # noqa: BLE001 - defaults are a usable answer
except Exception: # defaults are a usable answer
log.debug("could not read the instance language; using %s", SOURCE, exc_info=True)
return SOURCE
return _DEFAULT
@@ -161,7 +161,7 @@ def catalogue(code: str) -> Mapping[str, str]:
try:
module = __import__(f"lembas.web.i18n.{code}", fromlist=["MESSAGES"])
_catalogues[code] = dict(getattr(module, "MESSAGES", {}))
except Exception: # noqa: BLE001 - a broken catalogue must not break the page
except Exception: # a broken catalogue must not break the page
log.exception("could not load the %s catalogue", code)
_catalogues[code] = {}
return _catalogues[code]
+29
View File
@@ -344,3 +344,32 @@ def test_revoking_ones_own_token(client, db, registered):
client.post(f"/api/tokens/{token.id}/revoke")
db.expire_all()
assert api_tokens.resolve(db, raw) is None
def test_a_bare_error_line_in_the_upstream_stream_is_relayed_as_a_framed_error(
client, db, registered, mock_http
):
"""llama.cpp writes a mid-stream failure as a bare JSON line, often the
stream's unterminated last line. The relay frames it as `data:` so the
client reads the error it is rather than an empty reply."""
_models(db)
body = (
'data: {"choices":[{"delta":{"content":"Lem"}}]}\n\n'
': keepalive\n\n'
'{"error":{"code":500,"message":"model unloaded"}}'
)
mock_http(
lambda r: httpx.Response(200, text=body, headers={"content-type": "text/event-stream"})
)
response = client.post(
"/v1/chat/completions",
headers=_bearer(_token(db)),
json={"model": "qwen", "stream": True, "messages": [{"role": "user", "content": "x"}]},
)
assert response.status_code == 200
events = [e for e in response.text.split("\n\n") if e]
assert events[0].startswith('data: {"choices"') and '"model": "local/qwen"' in events[0]
assert events[1] == ": keepalive"
assert json.loads(events[2].removeprefix("data: ")) == {
"error": {"code": 500, "message": "model unloaded"}
}
+1 -1
View File
@@ -98,7 +98,7 @@ def test_create_admin_promotes_an_account_that_already_exists(db):
User(
email="sam@shire.test",
name="Sam",
password_hash="not-a-real-hash", # noqa: S106
password_hash="not-a-real-hash",
role=ROLE_USER,
active=False,
)
+14 -1
View File
@@ -23,6 +23,7 @@ from lembas.services import generation, harness_spec, plans, prompts, prototypes
from lembas.services import tools as tools_service
from lembas.services.agent import policy, shell
from lembas.services.library import chunks, documents
from lembas.services.llm import openai_client
ROOT = Path(__file__).resolve().parent.parent
@@ -43,9 +44,22 @@ AREAS = {
"plan": lambda c: _plan(c),
"prototype": lambda c: prototypes.info(c["info"], c["code"]),
"library_scope": lambda c: documents.resolve_base(c["bases"], c["base"]),
"toolcall_index": lambda c: _toolcalls(c),
}
def _toolcalls(c):
"""The spec writes a delta flat; the wire puts name and arguments under `function`."""
acc = openai_client.ToolCallAccumulator()
for delta in c["deltas"]:
fragment = {k: delta[k] for k in ("index", "id") if k in delta}
function = {k: delta[k] for k in ("name", "arguments") if k in delta}
if function:
fragment["function"] = function
acc.feed([fragment])
return acc.calls
def _plan(c):
if c["op"] == "normalise":
return plans.normalise(c["plan"])
@@ -76,7 +90,6 @@ PENDING = {
"edit": _ON_THE_DEVICE,
"unidiff": _ON_THE_DEVICE,
"envelope": _ON_THE_DEVICE,
"toolcall_index": "openai_client, next agent",
}
+1 -1
View File
@@ -241,7 +241,7 @@ def test_an_administrator_cannot_read_somebody_elses_note(db, client, registered
"""`permissions.resolve` gives an admin everything and `services/sharing.py`
deliberately has no admin branch. Reading somebody's private notes is not
configuration, and being able to reach the database is not being invited."""
other = User(email="merry@shire.test", name="Merry", password_hash="x") # noqa: S106
other = User(email="merry@shire.test", name="Merry", password_hash="x")
db.add(other)
db.commit()
note = _note(db, other, title="Theirs", body="not for you")
+228
View File
@@ -0,0 +1,228 @@
"""The one SSE reader (services/llm/sse.py), and what its callers make of errors
inside a 200 stream (quirks.json `error-in-200-stream`, `model-unloaded`) and of
tool-call fragments without an index (`tool-call-without-index`)."""
from __future__ import annotations
import json
import httpx
import pytest
from lembas.services.llm import sse
from lembas.services.llm.openai_client import (
Endpoint,
LLMError,
StreamError,
ToolCallAccumulator,
stream_chat,
)
def frames(text: str) -> list[tuple[str, str]]:
return list(sse.parse_sse(text.splitlines()))
# --- The parser ---------------------------------------------------------------
def test_data_lines_are_joined_with_newlines_until_a_blank_line():
text = 'data: {"a":\ndata: 1}\n\ndata: x\n\n'
assert frames(text) == [("", '{"a":\n 1}'), ("", "x")]
def test_the_event_name_rides_with_its_data_and_resets():
text = 'event: ping\ndata: {}\n\ndata: {"b":2}\n\n'
assert frames(text) == [("ping", "{}"), ("", '{"b":2}')]
def test_an_unterminated_last_line_is_a_frame_like_any_other():
assert frames('data: {"a":1}\n\ndata: {"b":2}') == [("", '{"a":1}'), ("", '{"b":2}')]
def test_crlf_line_endings_are_read():
lines = ['data: {"a":1}\r', "\r", "data: [DONE]\r"]
assert list(sse.parse_sse(lines)) == [("", '{"a":1}'), ("", "[DONE]")]
def test_comments_are_passed_on_as_comments():
assert frames(": keepalive\n\ndata: x\n\n") == [(sse.COMMENT, " keepalive"), ("", "x")]
def test_a_bare_error_line_inside_the_stream_is_an_error_frame():
"""llama.cpp behind llama-swap: no `data:`, and the stream's last line, with
no newline after it. By the letter of the spec it is a field called
`{"error"`, and ignoring it ends the reply as an empty one."""
text = 'data: {"choices":[]}\n\n{"error":{"code":500,"message":"boom"}}'
assert frames(text) == [
("", '{"choices":[]}'),
(sse.ERROR, '{"error":{"code":500,"message":"boom"}}'),
]
def test_a_bare_error_line_flushes_the_frame_before_it():
text = 'data: {"a":1}\n{"error":"x"}\n'
assert frames(text) == [("", '{"a":1}'), (sse.ERROR, '{"error":"x"}')]
def test_a_bare_json_line_without_an_error_member_is_not_a_frame():
assert frames('{"choices":[]}\n\ndata: x\n\n') == [("", "x")]
def test_an_error_field_is_an_error_frame_too():
assert frames("error: model unloaded\n\n") == [(sse.ERROR, "model unloaded")]
def test_a_servers_event_named_error_is_an_ordinary_named_frame():
"""Anthropic names its error frames `error`; the reader's own names begin
with a colon, and an `event:` line can never produce one."""
text = 'event: error\ndata: {"type":"error"}\n\nevent: :error\ndata: x\n\n'
assert frames(text) == [("error", '{"type":"error"}'), ("", "x")]
def test_frames_without_a_blank_line_between_them_are_not_joined():
assert frames('data: {"a":1}\ndata: {"b":2}\n\n') == [("", '{"a":1}'), ("", '{"b":2}')]
def test_other_fields_and_empty_frames_are_dropped():
assert frames("id: 7\nretry: 100\n\nevent: x\n\n") == []
async def test_iter_sse_reads_a_response_to_its_unterminated_end():
async def body():
yield b'data: {"a":1}\n\n'
yield b'{"error":{"message":"late"}}'
response = httpx.Response(200, content=body())
out = [frame async for frame in sse.iter_sse(response.aiter_lines())]
assert out == [("", '{"a":1}'), (sse.ERROR, '{"error":{"message":"late"}}')]
def test_error_status_reads_every_shape_seen():
assert sse.error_status({"code": 503}) == 503
assert sse.error_status({"status": 429}) == 429
assert sse.error_status({"type": "server_error", "code": "internal_error"}) == 500
assert sse.error_status({"code": "INTERNAL"}) == 500
assert sse.error_status({"type": "overloaded_error"}) == 500
assert sse.error_status({"message": "x"}) is None
assert sse.error_status("x") is None
def test_error_object_and_message():
assert sse.error_object('{"error":{"message":"m"}}') == {"error": {"message": "m"}}
assert sse.error_object("plain words") == {"error": "plain words"}
assert sse.error_message({"message": " m "}) == "m"
assert sse.error_message({"type": "t"}) == '{"type": "t"}'
assert sse.error_message("s") == "s"
# --- The OpenAI client -------------------------------------------------------
ENDPOINT = Endpoint("http://h", "", {})
PAYLOAD = {"model": "m", "messages": [{"role": "user", "content": "hi"}]}
def _chunk(text: str) -> str:
return f"data: {json.dumps({'choices': [{'delta': {'content': text}}]})}\n\n"
async def _collect(payload=PAYLOAD) -> list[dict]:
return [chunk async for chunk in stream_chat(ENDPOINT, payload)]
def _server(bodies: list[str]):
"""Answers each request with the next body; records how many were made."""
calls: list[dict] = []
def handler(request: httpx.Request) -> httpx.Response:
calls.append(json.loads(request.content))
body = bodies[min(len(calls), len(bodies)) - 1]
return httpx.Response(
200, content=body.encode(), headers={"content-type": "text/event-stream"}
)
return handler, calls
async def test_an_error_framed_as_data_is_the_error_it_is(mock_http):
body = 'data: {"error":{"code":400,"message":"context too long"}}\n\ndata: [DONE]\n\n'
handler, calls = _server([body])
mock_http(handler)
with pytest.raises(StreamError) as caught:
await _collect()
assert caught.value.status_code == 400
assert "context too long" in caught.value.message
# A 400 inside the stream is about the reply, not the request: the
# stream_options retry does not fire for it.
assert len(calls) == 1
async def test_a_bare_error_as_the_unterminated_last_line_is_raised_after_the_text(mock_http):
body = _chunk("Hel") + '{"error":{"code":500,"message":"boom"}}'
handler, calls = _server([body])
mock_http(handler)
got: list[dict] = []
with pytest.raises(LLMError) as caught:
async for chunk in stream_chat(ENDPOINT, PAYLOAD):
got.append(chunk)
assert got and got[0]["choices"][0]["delta"]["content"] == "Hel"
assert caught.value.status_code == 500
assert "boom" in caught.value.message
assert len(calls) == 1 # output had been streamed: no retry
async def test_a_model_unloaded_frame_before_any_output_is_retried_once(mock_http):
"""llama-swap, when another client swapped the model out: `type:
server_error` with a string code is read as the 500 it is."""
unloaded = (
'data: {"error":{"message":"group: model unloaded","type":"server_error",'
'"code":"internal_error"}}\n\n'
)
handler, calls = _server([unloaded, _chunk("ok") + "data: [DONE]\n\n"])
mock_http(handler)
chunks = await _collect()
assert [c["choices"][0]["delta"]["content"] for c in chunks] == ["ok"]
assert len(calls) == 2
async def test_a_server_error_is_retried_once_and_then_raised(mock_http):
unloaded = 'data: {"error":{"message":"model unloaded","type":"server_error"}}\n\n'
handler, calls = _server([unloaded, unloaded])
mock_http(handler)
with pytest.raises(LLMError) as caught:
await _collect()
assert caught.value.status_code == 500
assert len(calls) == 2
async def test_a_plain_stream_still_reads_as_before(mock_http):
body = ": keepalive\n\n" + _chunk("a") + _chunk("b") + "data: [DONE]\n\n" + _chunk("never")
handler, _calls = _server([body])
mock_http(handler)
chunks = await _collect()
assert [c["choices"][0]["delta"]["content"] for c in chunks] == ["a", "b"]
# --- Tool-call reassembly ------------------------------------------------------
def test_a_fragment_without_an_index_continues_the_last_call():
acc = ToolCallAccumulator()
acc.feed([{"index": 0, "id": "a", "function": {"name": "read", "arguments": "{}"}}])
acc.feed([{"index": 1, "id": "b", "function": {"name": "grep", "arguments": '{"q":'}}])
acc.feed([{"function": {"arguments": '"x"}'}}])
assert acc.calls == [
{"id": "a", "name": "read", "arguments": "{}"},
{"id": "b", "name": "grep", "arguments": '{"q":"x"}'},
]
def test_the_first_fragment_without_an_index_starts_call_zero():
acc = ToolCallAccumulator()
acc.feed([{"id": "a", "function": {"name": "read", "arguments": "{"}}])
acc.feed([{"function": {"arguments": "}"}}])
assert acc.calls == [{"id": "a", "name": "read", "arguments": "{}"}]
def test_calls_are_ordered_by_index_and_given_an_id_when_the_server_sent_none():
acc = ToolCallAccumulator()
acc.feed([{"index": 1, "function": {"name": "b"}}, {"index": 0, "function": {"name": "a"}}])
acc.feed([{"index": 2, "function": {"name": "", "arguments": "x"}}]) # nameless: not a call
assert [c["id"] for c in acc.calls] == ["call_0", "call_1"]
assert bool(acc)
assert not ToolCallAccumulator()
+3 -3
View File
@@ -105,7 +105,7 @@ def test_an_old_database_with_data_upgrades(db):
# Data first, while the schema still has the columns the ORM expects.
from lembas.db.models import Chat, Group, User
owner = User(name="Frodo", email="f@shire.test", password_hash="x") # noqa: S106
owner = User(name="Frodo", email="f@shire.test", password_hash="x")
db.add(owner)
db.commit()
group = Group(name="Fellowship")
@@ -162,7 +162,7 @@ def test_a_nullable_column_arrives_empty_rather_than_defaulted(db):
from lembas.db.models import Chat, User
owner = User(name="Sam", email="s@shire.test", password_hash="x") # noqa: S106
owner = User(name="Sam", email="s@shire.test", password_hash="x")
db.add(owner)
db.commit()
chat = Chat(user_id=owner.id, model_id="m")
@@ -191,7 +191,7 @@ def test_a_not_null_column_backfills_every_existing_row(db):
from lembas.db.models import Chat, User
owner = User(name="Merry", email="m@shire.test", password_hash="x") # noqa: S106
owner = User(name="Merry", email="m@shire.test", password_hash="x")
db.add(owner)
db.commit()
db.add(Chat(user_id=owner.id, model_id="m"))
+2 -2
View File
@@ -19,7 +19,7 @@ from lembas.services import usage as usage_service
@pytest.fixture
def reader(db, registered) -> User:
person = User(
email="sam@shire.test", name="Sam", password_hash="x", role=ROLE_USER # noqa: S106
email="sam@shire.test", name="Sam", password_hash="x", role=ROLE_USER
)
db.add(person)
db.commit()
@@ -217,7 +217,7 @@ def test_the_user_list_is_paginated_and_searchable(db, client, registered):
User(
email=f"p{n}@shire.test",
name=f"Person {n}",
password_hash="x", # noqa: S106
password_hash="x",
)
)
db.commit()
+3 -3
View File
@@ -35,7 +35,7 @@ def owner(db, registered) -> User:
@pytest.fixture
def reader(db) -> User:
person = User(
email="sam@shire.test", name="Sam", password_hash="x", role=ROLE_USER # noqa: S106
email="sam@shire.test", name="Sam", password_hash="x", role=ROLE_USER
)
db.add(person)
db.commit()
@@ -123,7 +123,7 @@ def test_reading_somebody_elses_report_does_not_clear_their_dot(db, client, regi
"""`unread` is the owner's notification. Somebody it was shared with opening
it would silence a dot meant for a person who has not seen it."""
other = User(
email="sam@shire.test", name="Sam", password_hash="x", role=ROLE_USER # noqa: S106
email="sam@shire.test", name="Sam", password_hash="x", role=ROLE_USER
)
db.add(other)
db.commit()
@@ -195,7 +195,7 @@ def test_the_panel_searches_rather_than_listing_everybody(db, client, registered
User(
email=f"p{n}@shire.test",
name=f"Person {n}",
password_hash="x", # noqa: S106
password_hash="x",
)
)
db.commit()
+6 -5
View File
@@ -387,20 +387,21 @@ def test_pinned_models_fold_and_remember_it(client: TestClient, db, registered):
assert user.settings_json["sections"] == {}
def test_the_old_pinned_key_is_still_read_and_its_route_still_answers(
def test_the_old_pinned_key_is_still_read_and_retired_on_the_next_write(
client: TestClient, db, registered
):
"""The pinned group's state lives in `sections`, not the older `pinned_open`
key. A choice stored under the old key is honoured, and a page loaded before
the update still posts to the old route -- which writes the new map and
retires the old key."""
key. A choice stored under the old key is honoured until the first write
to the map, which retires it. (The old key's own route is gone: nothing
has posted to it since 1.2.0.)"""
_pin_a_model(db)
user = _owner(db)
user.settings_json = {**(user.settings_json or {}), "pinned_open": False}
db.commit()
assert 'aria-expanded="false"' in _pinned_head(client.get("/chat").text)
assert client.post("/api/preferences/pinned-open", data={"state": "1"}).status_code == 204
posted = client.post("/api/preferences/section", data={"key": "pinned", "state": "1"})
assert posted.status_code == 204
db.refresh(user)
assert "pinned_open" not in user.settings_json
assert 'aria-expanded="true"' in _pinned_head(client.get("/chat").text)
+1 -1
View File
@@ -556,7 +556,7 @@ def test_the_permission_withdraws_it(db):
settings_store.update(db, {"default_permissions": {"tools.subagent": False}})
reader = User(
email="sam@example.test", name="Sam", password_hash="x", role=ROLE_USER # noqa: S106
email="sam@example.test", name="Sam", password_hash="x", role=ROLE_USER
)
db.add(reader)
db.commit()