File attachments: images for vision, PDFs and text into the prompt
Drag, paste or pick a file in the composer. Images go to vision models as multimodal content parts; PDFs and text files have their content extracted and placed in the prompt. Verified end to end against gemma4-e4b-q8 on llama-swap: given a drawing and a text file, it named the red square and blue circle and read the number out of the document. Type is decided by inspecting the bytes, never the filename or the browser's Content-Type -- a .png full of text is stored as text. Images are downscaled to 1400px and re-encoded: a phone photo is several megabytes of base64, which is slow and a large slice of the context window. PDF text is extracted once, at upload, and stored; re-extracting per request would let a reply change because a parser was upgraded. Design points worth keeping: - Images are only sent to models an administrator has marked `vision`. This is not graceful degradation -- most endpoints reject the entire request rather than ignoring an image part. A plain text turn stays a plain string for the same reason: the list form 400s on endpoints that do not implement it. - Images reach the model as base64 data URIs, not links. A local endpoint has no route back to LLeMbas, and a hosted one has no credentials for it. - Non-images are served Content-Disposition: attachment with nosniff, so an uploaded .html can never execute in this origin. Stored names are random; the uploader's name is a label and never a path. - Uploads are unbound until the message is sent, which is what lets a file be removed beforehand. claim() only takes unclaimed rows owned by the sender, so a forged id cannot pull in someone else's file. Abandoned uploads are swept at startup. - A scanned PDF says so rather than silently contributing nothing, and truncation is declared to the model in the document tag so it can admit it did not see page 400. - "Here, look at this" with no words is a legitimate turn, so a message is only empty when it carries neither text nor files. Also fixes auto-titling, which read message["content"] as a string and would have broken on the first multimodal turn. 186 tests, ruff clean. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
+29
-3
@@ -16,6 +16,7 @@ from lembas.db.models import ROLE_ASSISTANT, ROLE_USER, Chat, Message, User
|
||||
from lembas.db.session import session_scope
|
||||
from lembas.security import permissions
|
||||
from lembas.services import chat as chat_service
|
||||
from lembas.services import files as files_service
|
||||
from lembas.services import sse
|
||||
from lembas.services.llm.openai_client import (
|
||||
LLMError,
|
||||
@@ -66,7 +67,8 @@ async def post_message(
|
||||
db: Db,
|
||||
user: RequiredUser,
|
||||
chat_id: str,
|
||||
content: str = Form(...),
|
||||
content: str = Form(""),
|
||||
file_ids: list[str] = Form(default=[]),
|
||||
) -> Response:
|
||||
"""Persist the user's turn and hand back the pair of bubbles.
|
||||
|
||||
@@ -77,10 +79,15 @@ async def post_message(
|
||||
chat = _owned_chat(db, chat_id, user.id)
|
||||
|
||||
content = content.strip()
|
||||
if not content:
|
||||
# "Here, look at this" with no words is a legitimate turn, so an empty
|
||||
# message is only empty when it carries nothing at all.
|
||||
if not content and not file_ids:
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
|
||||
user_message = chat_service.create_message(db, chat, ROLE_USER, content)
|
||||
if file_ids:
|
||||
files_service.claim(db, ids=file_ids, user_id=user.id, message_id=user_message.id)
|
||||
db.refresh(user_message)
|
||||
assistant_message = chat_service.create_message(
|
||||
db, chat, ROLE_ASSISTANT, "", complete_=False, model_id=chat.model_id
|
||||
)
|
||||
@@ -130,6 +137,19 @@ async def stream_message(
|
||||
)
|
||||
|
||||
|
||||
def _plain_text(content: str | list) -> str:
|
||||
"""The text of a message payload, whether it is a string or content parts."""
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
if isinstance(content, list):
|
||||
return " ".join(
|
||||
part.get("text", "")
|
||||
for part in content
|
||||
if isinstance(part, dict) and part.get("type") == "text"
|
||||
).strip()
|
||||
return ""
|
||||
|
||||
|
||||
async def _generate(chat_id: str, message_id: str) -> AsyncIterator[str]:
|
||||
"""Drive one completion and frame it as SSE.
|
||||
|
||||
@@ -159,8 +179,14 @@ async def _generate(chat_id: str, message_id: str) -> AsyncIterator[str]:
|
||||
try:
|
||||
endpoint, model_id = chat_service.resolve_endpoint(db, chat)
|
||||
payload = chat_service.build_request(db, chat, upto=message)
|
||||
# A multimodal turn's content is a list of parts, not a string, so
|
||||
# the text has to be picked out before it can title a chat.
|
||||
first_user_text = next(
|
||||
(m["content"] for m in reversed(payload["messages"]) if m["role"] == ROLE_USER),
|
||||
(
|
||||
_plain_text(m["content"])
|
||||
for m in reversed(payload["messages"])
|
||||
if m["role"] == ROLE_USER
|
||||
),
|
||||
"",
|
||||
)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user