Why LLM-Generated Formulas Turn into Garbled Text: Causes and a Document Parsing Workflow

    This article explains why formulas generated by large language models often display as garbled text, question marks, or broken symbols when copied into documents. It breaks down five root causes—inconsistent markup syntax, Unicode variants, rich-text clipboard behavior, font issues, and OCR errors—and presents a practical five-stage pipeline: constraining model output, building an intermediate representation, cleaning and normalization (with sample Python code), converting to target formats, and regression testing. It also covers path selection for different formula sources, tool selection and data security, and how to integrate formula handling with RAG and AI agents.

    1. Problem Background

    Many developers and researchers have run into this: you ask a large language model to derive a formula, copy the answer into a document, and end up with question-mark boxes, leftover backslashes, misplaced subscripts and superscripts, or an entire formula reduced to an unreadable string of symbols.

    It may look like a minor copy-paste annoyance, but in knowledge base and AI agent applications the impact is significant. Once a formula is corrupted, downstream retrieval, question answering, and citation all drift away from the original meaning. Formula corruption should therefore be treated as a first-class document parsing problem, not something to patch by hand one occurrence at a time.

    2. Five Causes of Garbled Formulas

    2.1 Inconsistent Markup Syntax

    LLMs use several formula delimiters, including \(...\), \[...\], and $...$. Different renderers support these delimiters to different degrees. Some editors recognize only one or two of them and display the rest as literal backslashes and brackets.

    Another common issue is escaping. Backslashes in model output may be double-escaped during transmission or storage, turning into double backslashes and breaking command names.

    2.2 Character Encoding and Unicode Variants

    The same mathematical symbol can have multiple code points in Unicode. For example, a visually identical minus sign might be a hyphen, an en dash, or a true minus sign. Mathematical letters also come in many variants—bold, script, double-struck, and so on. These characters look similar on screen but are treated as different characters in font mapping and search matching, which leads to display anomalies or failed retrieval.

    In addition, zero-width characters such as the zero-width space and the byte order mark can silently survive copy-paste and interfere with later parsing and comparison.

    2.3 Implicit Formatting from the Rich-Text Clipboard

    When you copy content from web pages and chat interfaces, the clipboard usually contains both plain text and rich text. If the target application preferentially reads the rich text, it pulls in the original page’s fonts, styles, and hidden nodes. The formula may be converted into another internal representation and then reinterpreted by the target application; a failure at any step produces garbled output.

    2.4 Missing Glyphs and Rendering Differences

    Mathematical symbols depend on specific fonts. If the current font does not contain a glyph, the system renders it with a fallback font or simply shows a box. The same document opened on different devices may look different because of missing fonts.

    2.5 OCR Errors in Image-Based Formulas

    When formulas exist as images or scanned documents, they must first go through optical character recognition. Recognition models easily confuse similar glyphs—for example, reading 1 as l or α as a—or lose the hierarchical relationship of superscripts and subscripts. Once a recognition error enters the pipeline, it is stored as if it were correct content.

    3. Understanding the Problem from a Document Parsing Perspective

    In early document processing, the problem was often framed as “converting a file into text.” But in retrieval-augmented generation (RAG) and agent scenarios, text is only part of the result. What the system really needs is structural information:

    • Reading order: if paragraph order in a multi-column layout is scrambled, the context loses logical coherence.
    • Table structure: once row-column relationships are lost, answers to numeric questions drift.
    • Formula objects: formulas should be preserved as recognizable standalone blocks, not scattered symbols inside sentences.
    • Headers, footers, and footnotes: if these bleed into the body text, retrieval results fill up with noise.
    • Source location: citations need to point back to a page, paragraph, or block so users can verify the original text.

    Therefore, when dealing with garbled formulas, the goal should not be just “it displays correctly,” but “semantics, structure, and provenance are preserved.”

    A robust formula processing pipeline can be divided into five stages.

    4.1 Constrain the Model’s Output Format

    In the prompt, explicitly require the model to use a consistent formula delimiter and avoid full-width punctuation inside formulas. This reduces format inconsistency at the source. For example, you can specify that inline formulas are wrapped in single dollar signs and display formulas in double dollar signs.

    4.2 Build an Intermediate Representation

    Do not write model output directly into the final document. First save it as a structured intermediate representation—for example, recording each formula block’s raw source text, its paragraph, page number, and type. An intermediate representation makes cleaning, validation, and traceability easier, and makes it possible to reprocess content when a format conversion fails.

    4.3 Cleaning and Normalization

    The cleaning step includes unifying delimiters, removing zero-width characters, normalizing Unicode forms, and checking bracket pairing. Here is an example:

    1. import re
    2. import unicodedata
    3. def normalize_formula_text(text: str) -> str:
    4. # Use NFC, which preserves the semantic differences of math letters.
    5. # Note: NFKC folds script, bold, and other math letters into plain
    6. # letters, which can change a formula's meaning, so avoid it here.
    7. text = unicodedata.normalize("NFC", text)
    8. # Unify inline delimiters \( ... \) to $...$
    9. text = re.sub(r"\\\((.+?)\\\)", r"$\1$", text)
    10. # Unify display delimiters \[ ... \] to $...$
    11. text = re.sub(r"\\\[(.+?)\\\]", r"$\1$", text, flags=re.S)
    12. # Remove zero-width characters
    13. text = re.sub(r"[\u200b\u200c\u200d\ufeff]", "", text)
    14. return text
    15. def check_formula_balance(formula: str) -> list[str]:
    16. errors = []
    17. depth = 0
    18. for ch in formula:
    19. if ch == "{":
    20. depth += 1
    21. elif ch == "}":
    22. depth -= 1
    23. if depth < 0:
    24. errors.append("more closing braces than opening braces")
    25. break
    26. if depth > 0:
    27. errors.append("more opening braces than closing braces")
    28. if formula.count("$") % 2 != 0:
    29. errors.append("unpaired dollar-sign delimiters")
    30. return errors

    Cleaning functions only address format-level issues; they cannot judge whether a formula itself is correct. Mathematical correctness still requires manual spot checks or comparison against the original material.

    4.4 Convert to the Target Format

    During conversion, prefer formula objects natively supported by the target document format rather than inserting images. Formula objects remain editable, searchable, and copyable, while images lose all of these properties. If the target format does not support formula objects, fall back to high-resolution images and keep the source text alongside them.

    4.5 Validation and Regression

    After every change to prompts, cleaning rules, or conversion tools, run regression against a fixed test set. The test set can contain fifty to one hundred formulas covering different types, such as fractions, matrices, summations, integrals, labeled equation systems, and formulas with natural-language annotations.

    5. Choosing a Conversion Path

    Formulas from different sources should take different paths. The table below compares common approaches across several dimensions:

    Dimension Pasting rich text directly Conversion from source text Conversion after OCR
    Fidelity Low; depends on clipboard format High; source text is controllable Medium; depends on recognition quality
    Traceability Poor Good; source text is preserved Medium; requires keeping the original image
    Batch processing Difficult Easy Requires an extra validation step
    Data privacy Completed locally Depends on where it is deployed Depends on where it is deployed
    Best suited for Small amounts of ad-hoc content LLM output, knowledge base construction Scans, screenshots, legacy documents

    Most knowledge base projects should prioritize the source-text conversion path and introduce OCR only when no source text is available.

    6. Tool Selection and Data Security

    Free options generally fall into three categories:

    1. Locally run open-source parsing components. Documents never leave your machine, which suits internal or sensitive data, but they require some deployment and maintenance effort.
    2. Free tiers of online services. Quick to get started, but usually limited by page count, rate, or features—confirm the quota rules before adopting one.
    3. Built-in formula features in office suites. Suitable for individuals doing occasional editing, but with limited batch processing capability.

    Whichever category you choose, first check the terms of service regarding data retention and usage. This is especially important when uploading unpublished paper drafts, contracts, or internal reports—you need to confirm whether your data will be stored or used for training.

    Evaluate tools with your own test set rather than relying on advertised metrics. Evaluation dimensions include formula rendering success rate, structural preservation, processing speed, and the types of failure cases.

    7. Integration with RAG and AI Agents

    The ultimate purpose of formula processing is to let retrieval and reasoning work with correct content. The following points are worth considering in your design:

    • Chunking strategy: treat formula blocks and table blocks as the smallest units when splitting documents, so a single formula is never torn across two chunks.
    • Metadata preservation: record page number, section title, block type, and source file location for each chunk to support later citation.
    • Dual representation: for key formulas, store both the source text and a natural-language description. The description helps the model understand the formula’s purpose, while the source text supports precise computation and display.
    • Citation traceability: when an agent produces an answer, it should be able to point to a specific location in the original file so users can quickly verify it.

    When an agent needs to compute based on a formula, it should call a dedicated computation module rather than letting the model do mental arithmetic. The model is responsible for understanding the problem and organizing the steps; deterministic programs produce the numerical results.

    8. Practical Checklist

    • Unify formula delimiters and output conventions in the prompt.
    • Preserve the source text of formulas along with their location and type.
    • During cleaning, unify delimiters, remove zero-width characters, and normalize Unicode forms.
    • Automatically check brackets and delimiters, routing failures to a manual review queue.
    • Prefer formula objects natively supported by the target format over images.
    • Maintain a fixed test set of at least fifty items and run regression after every change.
    • Before adopting an online service, confirm its data retention and training-usage terms.
    • Preserve structure and provenance in chunking and citation.