A vectorizer can return a complete SVG at the end of a request. That is enough for a download button, but it gives the UI no way to distinguish “still working” from “waiting on a connection that already closed.” For a preview, it helps to make completion an event in the protocol.
This example builds the streaming part in FastAPI. It uses a tiny fixture in place of GPU inference so you can test the viewer on any laptop. The fixture is deliberately not presented as model output.
What an editable result looks like
The example assets from Baidu’s Unlimited-SVG Space make a useful comparison. The sample PNG is 600 × 600 pixels. Its paired SVG has a 0 0 1024 1024 viewBox, seven path elements and three circles. Those elements can be selected and recoloured individually. The viewBox describes the coordinate space of the drawing, so it does not have to match the source image’s pixel dimensions.
These are measurements of one supplied pair, not a benchmark or a promise about file size. Check recognisable geometry and text on your own inputs. A valid SVG can still be a poor redraw.
Make each event a line
Use newline-delimited JSON (NDJSON). Put one event on each line. Send delta events for text the user can inspect, and one complete event containing the final document. A production service can add a separate error event for a failure that occurs after headers have already been sent.
Save this as preview.py.
import asyncio import json from fastapi import FastAPI from fastapi.responses import StreamingResponse app = FastAPI() OPEN = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">' SHAPE = '<circle cx="12" cy="12" r="8" fill="royalblue"/>' CLOSE = '</svg>' def line(event: dict[str, str]) -> bytes: return (json.dumps(event) + "\n").encode("utf-8") async def preview_events(): for piece in (OPEN, SHAPE, CLOSE): yield line({"type": "delta", "text": piece}) await asyncio.sleep(0.15) yield line({"type": "complete", "svg": OPEN + SHAPE + CLOSE}) @app.get("/preview") def preview(): return StreamingResponse( preview_events(), media_type="application/x-ndjson", headers={"Cache-Control": "no-store"}, ) Install fastapi and uvicorn in a virtual environment. Then start the server and request the stream without curl's output buffering.
python -m uvicorn preview:app --host 127.0.0.1 --port 8786 # In another terminal curl --no-buffer http://127.0.0.1:8786/preview The first three lines carry pieces of the drawing. The fourth carries the completed SVG. If you later put a reverse proxy in front of the service, check response buffering there too. Turning off curl buffering does not turn it off elsewhere.
Parse records rather than chunks
A network chunk is not an NDJSON record. It can end halfway through a JSON string or contain multiple lines. Decode incrementally and keep the unfinished tail. Treat the missing complete event as a failed preview, even if the connection closed cleanly.
async function readPreview(url, { onDelta = () => {}, signal } = {}) { const response = await fetch(url, { signal }); if (!response.ok || !response.body) throw new Error("Preview unavailable"); const reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); let tail = ""; try { while (true) { const { value, done } = await reader.read(); if (done) throw new Error("Stream ended before the completed SVG arrived"); tail += value; let newline; while ((newline = tail.indexOf("\n")) >= 0) { const record = tail.slice(0, newline); tail = tail.slice(newline + 1); if (!record.trim()) continue; const event = JSON.parse(record); if (event.type === "delta") onDelta(event.text); if (event.type === "error") throw new Error(event.message); if (event.type === "complete") return event.svg; } } } finally { try { await reader.cancel(); } catch { // A caller may already have aborted fetch. } reader.releaseLock(); } } Call it from the same origin as the endpoint. Update a text panel through textContent, rather than inserting model output as page HTML. A valid XML document is not necessarily a safe preview. Validate and sanitize a real model result separately before rendering or exporting it, and put a practical limit on buffered messages and output size.
Replace the fixture after the UI works
Keep the adapter narrow. Feed a validated image into your model runner, forward text fragments through the same event contract, and emit complete only after the final result passes validation. Run blocking model work outside the async event loop. An aborted browser request stops reading responses, but it does not automatically stop the model, so the server-side runner needs its own cancellation support.
The Unlimited-SVG model card documents the upstream model. FastAPI's streaming response reference covers the transport used here. Test the stream with a deliberately fragmented response, an abrupt end, and a complete fixture before adding GPU inference.
AI disclosure: This article was generated with AI. The bundled sample measurements and the runnable streaming example were checked separately.



