FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Streaming Math and LaTeX Markup

Buffer incomplete TeX across stream chunks, recognize escaped inline and display delimiters, and render only closed, bounded formulas with KaTeX.

Freshness: current•14 min read•AI User Experience and Human-AI Interaction
Full Technical Reference Document

Mental model

Streaming math rendering should keep the original character stream and parser state separate from rendered output. Treat dollar delimiters as state transitions that can cross transport chunks, hold an unfinished formula as plain text, and send only a complete, bounded TeX expression to KaTeX. This prevents flicker, malformed markup, and repeated full-prefix parsing.

Theory

An SSE event boundary is a transport boundary, not a mathematical boundary. A provider can split a display delimiter, a TeX command, or a closing brace between text deltas. The UI therefore needs a small lexical state machine: outside math, inside inline math, or inside display math. It also carries whether the previous character was a backslash, because an escaped dollar is content rather than a closing delimiter. The remark-math extension defines math syntax in Markdown; KaTeX turns a completed TeX expression into HTML and MathML. Neither step makes each partial delta a valid formula.

Keep two representations: the received text and the segments that are safe to display as formatted math. Text before an opening delimiter can be emitted immediately. Once an inline or display delimiter opens a formula, accumulate its TeX characters without calling KaTeX for every token. Emit a math segment only after the matching unescaped close arrives. If the stream ends first, return the opening delimiter and buffered text as literal text so users can still inspect the unfinished answer. When displaying ordinary text, let React escape it as text; do not inject an untrusted stream as HTML.

The scanner below processes characters as chunks arrive and retains only delimiter state plus the current formula. It holds an ambiguous trailing dollar until the next chunk clarifies whether it begins or ends a delimiter. A closed segment can be passed once to KaTeX with trust disabled; untrusted macro definitions, HTML, or URL commands should not be enabled merely to make streamed output richer.

Receive a typed text delta
Carry split delimiter and escape state
Buffer the open TeX expression
Emit only a matching closed segment
Render once with KaTeX or preserve literal tail
Conceptual teaching model synthesized from:vercel-ai-sdk-ui-stream-protocol,remark-math-docs,katex-docs

For example, the deltas “Area: open-inline x-sub-i”, “plus-one squared, close-inline; sum: open-display sum-sub”, and “j equals one through n, j, close-display” produce two stable math segments: x with subscript i plus one, squared, in inline mode and the sum from j equals one through n in display mode. The first half of each delimiter can arrive in a different network event from its second half. Appending rendered HTML after each event instead would briefly show broken braces or lose the intended display mode.

Quantitative model

Suppose a formula contains NN TeX characters and a renderer reparses the entire growing prefix after every one-character delta. Its delimiter-scan work is:

Cprefix(N)=∑j=1Nj=N(N+1)2C_{\text{prefix}}(N) = \sum_{j=1}^{N} j = \frac{N(N+1)}{2}

Here NN is the number of TeX characters, BB is the number of chunk boundaries, and CC counts character inspections. At N=300N=300, repeated prefix scans inspect 45,150 characters. The stateful scanner checks each arriving character once and may recheck at most one held dollar per boundary, so Cstate(N,B)≤N+BC_{\text{state}}(N,B) \leq N+B, before KaTeX parses each completed formula once. This is scan work, not a browser-time guarantee: KaTeX parse and layout cost still depends on expression structure, DOM size, and device speed.

Trade-offs

Buffering until a close delimiter avoids displaying malformed math and prevents repeated KaTeX work, but a long formula has no formatted preview while it is being generated. A product can show the raw TeX in a visibly pending state, or reveal a plain-text fallback if generation stops. Reparsing the whole Markdown document can simplify code but redoes work for stable paragraphs and makes layout jump as partial tokens change meaning. A stateful math splitter is cheaper, yet it is not a Markdown parser: fenced code, inline code, links, and math delimiters each have different syntax rules. Keep the full Markdown parser responsible for document structure and use this scanner only at a clearly defined math-rendering boundary.

KaTeX error handling is another deliberate choice. With throw-on-error disabled, an unsupported command can be represented as source text instead of crashing the message renderer, but it should be reported to telemetry and never mistaken for a validated equation. A strict command and macro policy limits surprising layout and prevents content from invoking trusted HTML features. Bound the number of pending characters and the time a formula may remain open; after that, preserve the source literally and mark the segment incomplete.

Failure modes and misconceptions

FailureUser-visible effectControl
The two display delimiter characters arrive in separate deltasThe first dollar is mistaken for an inline delimiterRetain one ambiguous delimiter character between chunks
A backslash is the final character of one deltaAn escaped dollar in the next delta closes mathCarry escape state across the transport boundary
A closing delimiter never arrivesThe UI keeps growing an unbounded pending formulaSet a size and time bound, then display the literal unfinished source
KaTeX renders every prefixCPU and layout work grow while braces and subscripts flickerScan deltas once and render only closed segments
Trust is enabled for model outputUntrusted TeX can request unsafe HTML or linksDisable trust, restrict macros, and escape text segments

An escaped delimiter does not mean every dollar belongs to math; prose may contain currency and code samples may contain literal dollar signs. Apply the product's Markdown and currency rules before math scanning, and test both odd and even runs of backslashes. Also keep accessibility in mind: a screen reader should receive the final mathematical expression in a useful textual form, not a sequence of re-announced partial HTML trees.

Decision scenario

A response streams for several seconds and ends with an opening display delimiter and the unfinished expression integral from zero to one of x squared dx because the server closed unexpectedly. The inline preview currently flashes KaTeX errors as each token arrives. Do not publish each prefix as formatted math. Keep the partial expression pending during the stream; on the terminal error, return the raw expression as escaped text with an incomplete indicator, record the stream failure, and let the user retry. A later successful response can replace that pending segment by its stable ID without duplicating the surrounding prose.

typescript
import katex from "katex";
​
type Mode = "text" | "inline" | "display";
type Segment = { kind: "text"; value: string } | { kind: "inline" | "display"; value: string };
​
export class MathStream {
private mode: Mode = "text";
private text = "";
private tex = "";
private escaped = false;
private pendingDollar = false;
​
push(chunk: string): Segment[] {
const input = (this.pendingDollar ? "$" : "") + chunk;
this.pendingDollar = false;
const out: Segment[] = [];
for (let i = 0; i < input.length; i++) {
const ch = input[i]!;
if (this.escaped) { this.append(ch); this.escaped = false; continue; }
if (ch === "\\") { this.append(ch); this.escaped = true; continue; }
if (ch !== "$") { this.append(ch); continue; }
const next = input[i + 1];
if (next === undefined) { this.pendingDollar = true; break; }
if (this.mode === "text") {
this.flushText(out); this.mode = next === "$" ? "display" : "inline";
if (next === "$") i++;
} else if (this.mode === "inline") {
out.push({ kind: "inline", value: this.tex }); this.tex = ""; this.mode = "text";
} else if (next === "$") {
out.push({ kind: "display", value: this.tex }); this.tex = ""; this.mode = "text"; i++;
} else this.tex += "$";
}
return out;
}
​
finish(): Segment[] {
const out: Segment[] = [];
if (this.pendingDollar) {
if (this.mode === "inline") { out.push({ kind: "inline", value: this.tex }); this.tex = ""; this.mode = "text"; }
else if (this.mode === "display") this.tex += "$";
else this.text += "$";
this.pendingDollar = false;
}
if (this.mode !== "text") {
this.text += (this.mode === "display" ? "$$" : "$") + this.tex;
this.tex = ""; this.mode = "text";
}
this.flushText(out);
return out;
}
​
private append(ch: string) { if (this.mode === "text") this.text += ch; else this.tex += ch; }
private flushText(out: Segment[]) { if (this.text) out.push({ kind: "text", value: this.text }); this.text = ""; }
}
​
export function renderFormula(segment: Segment): string | null {
if (segment.kind === "text") return null;
return katex.renderToString(segment.value, {
displayMode: segment.kind === "display", throwOnError: false, trust: false,
});
}

The caller should render text segments as ordinary framework text nodes and send only inline or display segments to KaTeX. The code is intentionally a delimiter scanner, not a full Markdown parser; code fences and inline-code regions must be resolved by the Markdown layer before math segments are interpreted. Apply a maximum formula length before storing more source.

Learning outcomes

  • Track inline and display delimiter state across arbitrary text-delta boundaries.
  • Explain why rendering only closed expressions avoids both malformed previews and repeated prefix work.
  • Configure KaTeX and text rendering so model-provided TeX remains bounded and untrusted HTML stays disabled.
Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-501AI Evaluation and Reliability

Turn product intent and risk into representative evaluations release gates traces service targets and continuously improving regression evidence.

17 concepts~22h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next