|
58 | 58 |
|
59 | 59 | from mercury_composable import ( |
60 | 60 | AppException, |
| 61 | + AsyncHttpRequest, |
61 | 62 | Body, |
62 | 63 | EventEnvelope, |
63 | 64 | EventStreamWriter, |
64 | 65 | PostOffice, |
| 66 | + UploadedFile, |
65 | 67 | annotate_trace, |
66 | 68 | app_config, |
67 | 69 | default_registry, |
@@ -797,6 +799,14 @@ def _plan(request: LlmRequest, backend: Backend) -> tuple[Any, dict[str, Any]]: |
797 | 799 | # that can reach this app can have a file under the root sent to the provider and read back in |
798 | 800 | # the reply: the root is deployment configuration, certified with the deployment. |
799 | 801 |
|
| 802 | +# --- the document intake: llm.upload behind a REST automation entry with upload: true ----- |
| 803 | +# the files of a multipart upload saved under this folder of the root, each under a new name |
| 804 | +UPLOAD_FOLDER = "uploads" |
| 805 | +UPLOAD_NO_FILES = ( |
| 806 | + "upload: no file in the request - send multipart/form-data to an entry with upload: true" |
| 807 | +) |
| 808 | +_SAFE_NAME = re.compile(r"[^A-Za-z0-9._-]") |
| 809 | + |
800 | 810 | _attachments_root: Path | None = None # resolved on first use - module-level so tests can inject |
801 | 811 |
|
802 | 812 |
|
@@ -2482,6 +2492,60 @@ def forward(text: str) -> None: |
2482 | 2492 | out.close(trailing) |
2483 | 2493 |
|
2484 | 2494 |
|
| 2495 | +def _safe_name(filename: str) -> str: |
| 2496 | + """The uploaded name as a safe suffix of the saved name: the base name only, hidden-entry |
| 2497 | + dots stripped (the attachments rules would refuse them), every other character an |
| 2498 | + underscore, at most 80 characters.""" |
| 2499 | + base = Path(filename).name if filename else "" |
| 2500 | + return _SAFE_NAME.sub("_", base).lstrip(".")[:80] |
| 2501 | + |
| 2502 | + |
| 2503 | +def _save_uploads(root: Path, files: list[UploadedFile]) -> list[dict[str, Any]]: |
| 2504 | + """Write each file under a new name in the uploads folder of the root (in a worker thread) |
| 2505 | + and return the references a later call names: the path inside the root, the original name, |
| 2506 | + the kind by the first bytes (else the declared type), the size, the SHA-256 the audit keeps, |
| 2507 | + and whether llm.chat can attach the file as it is.""" |
| 2508 | + folder = root / UPLOAD_FOLDER |
| 2509 | + folder.mkdir(parents=True, exist_ok=True) |
| 2510 | + saved: list[dict[str, Any]] = [] |
| 2511 | + for uploaded in files: |
| 2512 | + suffix = _safe_name(uploaded.name) |
| 2513 | + name = f"{uuid.uuid4().hex}-{suffix}" if suffix else uuid.uuid4().hex |
| 2514 | + with open(folder / name, "xb") as handle: # a new name - never an overwrite |
| 2515 | + handle.write(uploaded.content) |
| 2516 | + detected = _media_type(uploaded.content[:16]) |
| 2517 | + saved.append({ |
| 2518 | + "path": f"{UPLOAD_FOLDER}/{name}", |
| 2519 | + "filename": uploaded.name, |
| 2520 | + "media_type": detected or uploaded.content_type, |
| 2521 | + "bytes": len(uploaded.content), |
| 2522 | + "sha256": hashlib.sha256(uploaded.content).hexdigest(), |
| 2523 | + "attachable": detected is not None, |
| 2524 | + }) |
| 2525 | + return saved |
| 2526 | + |
| 2527 | + |
| 2528 | +@preload(route="llm.upload", instances=10) |
| 2529 | +async def llm_upload(_headers: dict[str, str], body: Body) -> Any: |
| 2530 | + """The document intake for the attachments folder (RFC-0016): behind a REST automation entry |
| 2531 | + with ``upload: true`` (``POST /api/llm/upload`` in resources/rest.yaml), the files of a |
| 2532 | + multipart upload are saved under ``uploads/`` inside ``llm.attachments.root``, each under a |
| 2533 | + new name, and their references returned - the ``path`` a later ``llm.chat`` call names in |
| 2534 | + ``attachments``, the kind by the first bytes, the size and the SHA-256 the audit keeps, and |
| 2535 | + ``attachable``: whether the model takes the file as it is (a PDF or an image) or a conversion |
| 2536 | + comes first (a word-processor file, a spreadsheet). The folder is readable through the model: |
| 2537 | + put an authentication function or the gateway in front of the entry.""" |
| 2538 | + request = AsyncHttpRequest(body) |
| 2539 | + files = request.files() |
| 2540 | + if not files: |
| 2541 | + raise AppException(400, UPLOAD_NO_FILES) |
| 2542 | + root = attachments_root() |
| 2543 | + saved = await asyncio.get_running_loop().run_in_executor(None, _save_uploads, root, files) |
| 2544 | + annotate_trace("llm_uploads", len(saved)) |
| 2545 | + log.info("Uploaded %d file(s), %d bytes", len(saved), sum(item["bytes"] for item in saved)) |
| 2546 | + return {"files": saved} |
| 2547 | + |
| 2548 | + |
2485 | 2549 | @preload(route="llm.health", instances=5, private=True) |
2486 | 2550 | async def llm_health(headers: dict[str, str], _body: Body) -> Any: |
2487 | 2551 | """Health check speaking the engines' interface contract (type=info / type=health). |
|
0 commit comments