This prompt is designed for document ingestion engineers who need to reconstruct continuous elements—paragraphs, tables, lists, and callout boxes—that have been split across page boundaries during PDF text extraction. The core job-to-be-done is transforming a stream of layout-aware text fragments with page metadata into a single, logically coherent document where split elements are merged and page-break locations are explicitly annotated. The ideal user is a backend engineer or pipeline architect building a production document processing system, not an end-user manually cleaning up a single PDF. You should use this prompt when your extraction pipeline produces per-page or per-region text blocks and you need to reassemble them before chunking, indexing, or structured extraction downstream.
Prompt
Multi-Page Element Stitching Prompt Template

When to Use This Prompt
Define the job, the ideal user, required inputs, and the boundaries where this prompt should not be deployed.
The prompt requires structured input containing text fragments with their page numbers, bounding box coordinates, font metadata, and element-type classifications (e.g., 'paragraph', 'table-row', 'list-item', 'callout'). Without this layout-aware metadata, the model cannot reliably distinguish a genuine continuation from a coincidental text similarity. The output contract is strict: a JSON array of stitched elements, each with a merged_from array of source fragments, a page_break_positions list indicating where breaks occurred, and a continuation_confidence score. This structured output is designed to be machine-readable so your pipeline can log merge decisions, flag low-confidence stitches for human review, and preserve provenance for audit trails. You should wire a JSON schema validator directly after the model response to catch malformed output before it corrupts downstream chunking or retrieval.
Do not use this prompt when you lack reliable page-boundary metadata, when the document is a single-page flyer, or when your extraction pipeline already produces correctly ordered continuous text. This prompt is also inappropriate for real-time chat interfaces where a user is asking questions about a document—it is a batch ingestion component, not a conversational tool. If your document contains complex mixed-orientation pages, right-to-left scripts, or heavily degraded OCR output, you should run those through specialized layout correction prompts first and feed the cleaned output into this stitching step. Finally, if the cost of a false merge is extremely high—such as in legal contract clause assembly or financial statement reconstruction—you must route low-confidence stitches to a human review queue rather than relying solely on the model's confidence score.
Use Case Fit
Where this prompt works and where it does not. Use these cards to decide if multi-page element stitching is the right tool for your ingestion pipeline.
Good Fit: Structured Documents with Predictable Breaks
Use when: Your pipeline ingests contracts, reports, manuals, or filings where paragraphs, tables, and lists predictably span page breaks. The prompt excels at merging continuation text when the document uses consistent numbering, indentation, or header/footer patterns. Guardrail: Pre-process with layout-aware extraction to provide bounding box and page boundary metadata before stitching.
Bad Fit: Highly Decorative or Image-Heavy Layouts
Avoid when: Documents rely on visual proximity rather than structural cues to connect elements across pages—magazine spreads, brochures, infographics, or heavily designed annual reports. The prompt's text-continuity heuristics fail when layout intent is visual rather than semantic. Guardrail: Route visually complex documents to a multimodal model that can reason about spatial relationships before attempting text stitching.
Required Inputs: Layout Metadata and Page Boundaries
What you must provide: Each text element needs page number, bounding box coordinates, font metadata, and element type classification (paragraph, table row, list item, callout). Without layout metadata, the prompt cannot distinguish a page-break continuation from a new element. Guardrail: Validate that your upstream extraction pipeline preserves page-boundary markers and element-type tags before invoking stitching.
Operational Risk: False Merges Across Unrelated Elements
What to watch: The prompt may incorrectly merge elements that happen to share similar text patterns across page boundaries—such as identically numbered list items in different sections or table rows from separate tables. Guardrail: Add a post-stitching validation step that checks merged elements against section hierarchy and heading context. Flag merges that cross section boundaries for human review.
Operational Risk: Orphaned Continuations Without Starts
What to watch: A table row or paragraph fragment appears mid-page with no preceding element to stitch to—often caused by upstream extraction dropping the first part of a split element. Guardrail: Implement orphan detection that flags continuation elements missing a start element on the prior page. Route orphans to a repair queue rather than silently passing incomplete data downstream.
Scale Consideration: Token Costs for Long Documents
What to watch: Stitching a 200-page document in a single prompt window consumes significant tokens and increases latency. Long contexts also increase the risk of mid-context attention drift where the model loses track of early-page element relationships. Guardrail: Chunk the document into page batches of 10-20 pages with overlap windows. Stitch within each batch, then reconcile batch boundaries with a lightweight merge pass.
Copy-Ready Prompt Template
A reusable prompt for identifying and merging document elements that span page breaks, producing continuous elements with page-break annotations.
This prompt template is designed for ingestion pipelines that process multi-page documents where paragraphs, tables, lists, and callout boxes frequently break across page boundaries. The template accepts layout-aware extraction output—typically text blocks with bounding box coordinates, page numbers, and element-type labels—and stitches split elements back together into continuous logical units. The output preserves the original page-break locations as annotations, enabling downstream consumers to trace content back to source pages while working with complete semantic units.
textYou are a document structure reconstruction engine. Your task is to identify and merge document elements that span page breaks. ## INPUT You will receive layout-aware extraction output containing text blocks with the following fields per block: - page_number: integer - element_type: one of [paragraph, table_row, list_item, callout_box, heading, caption, footnote] - text: string content of the block - bbox: [x0, y0, x1, y1] coordinates in page space - font_metadata: {family, size, style} - block_sequence: integer position on the page Input data: [LAYOUT_BLOCKS] ## TASK 1. Identify elements that are continuations from the previous page or continue onto the next page. 2. Merge split elements into single continuous elements. 3. Annotate each merge point with the page boundary location. 4. Preserve the original element type and reading order. ## STITCHING RULES - **Paragraph continuation**: Merge when the last block on page N and first block on page N+1 share font metadata, element_type is paragraph, and the page N block ends mid-sentence (no terminal punctuation) OR the page N+1 block starts with a lowercase letter. - **Table continuation**: Merge when consecutive pages contain table_row blocks with matching column counts and consistent column alignment (x-coordinate overlap within [TOLERANCE] pixels). Include a header-row repeat check. - **List continuation**: Merge when list_item blocks continue numbering or bullet pattern across page boundary, with matching indentation levels. - **Callout box continuation**: Merge when callout_box blocks on consecutive pages share background shading, border style, or explicit "continued" markers. - **Do NOT merge**: Headings, captions, or footnotes across pages unless explicit continuation markers exist. ## OUTPUT SCHEMA Return a JSON object with this structure: { "stitched_elements": [ { "element_id": "string", "element_type": "string", "merged_from_blocks": [block_indices], "continuous_text": "string", "page_break_annotations": [ {"after_page": integer, "before_page": integer, "break_position": integer} ], "confidence": 0.0-1.0, "stitching_evidence": ["reason strings"] } ], "unmerged_blocks": [block_indices], "warnings": ["string descriptions of ambiguous cases"] } ## CONSTRAINTS - Never merge across more than [MAX_CONSECUTIVE_PAGES] pages without flagging a warning. - If confidence is below [CONFIDENCE_THRESHOLD], include the element in both stitched_elements AND warnings with a flag for human review. - Preserve original block indices for traceability. - Handle empty pages and page-number gaps gracefully. ## EXAMPLES [FEW_SHOT_EXAMPLES] ## RISK LEVEL [HUMAN_REVIEW_TRIGGER]: Require human review when confidence < 0.7, when table column counts change mid-merge, or when more than 3 consecutive pages are stitched.
To adapt this template for your pipeline, replace the bracketed placeholders with your specific values. Set [TOLERANCE] based on your PDF extraction tool's coordinate precision—typically 5-15 pixels for scanned documents and 2-5 pixels for digital PDFs. [MAX_CONSECUTIVE_PAGES] should reflect your document types; legal contracts rarely span more than 2 pages for a single element, while technical manuals may have tables spanning 5+ pages. [CONFIDENCE_THRESHOLD] of 0.7 is a reasonable default, but lower it to 0.5 for noisy OCR output or raise it to 0.85 for clean digital documents. The [FEW_SHOT_EXAMPLES] placeholder should contain 2-3 annotated examples showing correct merges and deliberate non-merges. The [HUMAN_REVIEW_TRIGGER] section should be customized to your operational tolerance for errors—false merges are typically more damaging than orphaned continuations, so bias toward conservative merging if your downstream consumers cannot tolerate merged-paragraph errors.
Before deploying this prompt, build a validation harness that checks: (1) no block appears in both stitched_elements and unmerged_blocks, (2) all original block indices are accounted for, (3) page_break_annotations reference consecutive page numbers, and (4) confidence scores are present for every stitched element. Run this prompt against a golden dataset of 20-50 documents with known page-break locations to establish baseline precision and recall. Common failure modes include false merges of similar-looking but distinct paragraphs, missed continuations when the first word on a new page is capitalized, and table-header confusion when headers repeat mid-page. Plan to iterate on the stitching rules after reviewing production traces.
Prompt Variables
Required inputs for the Multi-Page Element Stitching prompt. Each placeholder must be populated before the prompt is sent. Missing or malformed inputs are the most common cause of false merges and orphaned continuations.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[PAGE_SEQUENCE] | Ordered list of page objects with page number and extracted text blocks | {"pages": [{"page_num": 1, "text_blocks": [...]}, {"page_num": 2, "text_blocks": [...]}]} | Validate array length matches document page count. Reject if pages are out of order or missing page_num. Each text_blocks array must be non-empty unless page is intentionally blank. |
[ELEMENT_TYPES] | Whitelist of element types to stitch across page breaks | ["paragraph", "table", "ordered_list", "unordered_list", "callout_box"] | Must be a JSON array of strings. Reject if empty. Unknown types should trigger a warning but not block execution. Common types: paragraph, table, ordered_list, unordered_list, callout_box, code_block, footnote_continuation. |
[STITCHING_RULES] | Rules dictating when adjacent page elements should be merged | {"paragraph": {"min_text_overlap_chars": 0, "max_vertical_gap_mm": 5}, "table": {"match_header_columns": true}} | Must be valid JSON object with at least one rule per element type in [ELEMENT_TYPES]. Rules without corresponding element types are ignored. Schema check: each rule object must have defined merge conditions. |
[PAGE_BREAK_MARKER] | Token or string inserted at stitch points to mark original page boundaries | "<|PAGE_BREAK|>" | Must be a non-empty string. Avoid using characters that appear in document content. Common choices: <|PAGE_BREAK|>, ---PAGE BREAK---, or a Unicode non-printing character. Validate that marker does not appear in source text. |
[OUTPUT_SCHEMA] | JSON schema defining the structure of stitched output elements | {"type": "object", "properties": {"elements": {"type": "array", "items": {"type": "object", "properties": {"element_id": {"type": "string"}, "element_type": {"type": "string"}, "content": {"type": "string"}, "source_pages": {"type": "array", "items": {"type": "integer"}}, "stitch_confidence": {"type": "number"}}}}}} | Must be valid JSON Schema draft-07 or later. Required fields: element_id, element_type, content, source_pages, stitch_confidence. Reject if schema is malformed. Validate output against this schema post-generation. |
[CONFIDENCE_THRESHOLD] | Minimum confidence score for accepting a stitch as valid | 0.7 | Must be a float between 0.0 and 1.0. Stitches below this threshold should be flagged for human review. Recommended range: 0.6-0.8 for production. Lower values increase false merges; higher values increase orphaned continuations. |
[MAX_STITCH_SPAN] | Maximum number of pages a single element can span before forced termination | 3 | Must be a positive integer. Prevents runaway stitching of repetitive content like headers or footers. Set to null to disable. Typical values: 2-4 for paragraphs, 5-10 for tables. Validate that value is reasonable for document type. |
[ABORT_ON_ORPHAN] | Whether to abort processing when unstitched continuations are detected | Must be boolean. When true, orphaned continuations (elements that appear to be mid-element but cannot be stitched) cause the pipeline to halt and escalate. When false, orphans are flagged in output with stitch_confidence=0.0 and source_pages containing only the continuation page. |
Implementation Harness Notes
How to wire the multi-page element stitching prompt into a production document ingestion pipeline with validation, retries, and failure handling.
The multi-page element stitching prompt operates as a post-extraction correction step in a document ingestion pipeline. After a layout-aware extraction engine produces per-page text blocks with bounding box coordinates, font metadata, and element type classifications, the stitching prompt receives a sequence of elements spanning a page break boundary. The harness should batch elements in sliding windows of two to three pages, passing the last few elements of page N alongside the first few elements of page N+1. This windowed approach prevents token waste from processing entire documents at once while ensuring the model has sufficient context to determine whether a paragraph, table row, list item, or callout box continues across the break.
Validation layer. The harness must validate the model's output against a strict schema before accepting any merge decision. Each stitched element should include a merge_decision enum (merge, no_merge, uncertain), a merged_text field when applicable, a confidence score between 0.0 and 1.0, and a page_break_annotation marking where the break occurred. Reject outputs that claim a merge but produce identical text to the input, that merge elements of different types (e.g., stitching a paragraph to a table row), or that produce confidence scores below a configurable threshold. For uncertain decisions, route the element pair to a human review queue with the source page images rendered side by side. Log every merge decision with the input element IDs, output decision, confidence, and the model version used for traceability.
Retry and escalation logic. When the model returns malformed JSON, missing required fields, or schema-invalid output, retry once with the same input and an explicit instruction to correct the format error. If the retry also fails, fall back to a conservative no-merge default and flag the element pair for downstream review. Do not retry more than twice on the same window—cost and latency accumulate quickly in high-volume ingestion pipelines. For uncertain decisions that exceed a volume threshold (e.g., more than 5% of page breaks in a document), pause the pipeline and alert an operator rather than silently producing low-confidence merges that corrupt downstream retrieval or structured extraction.
Model choice and performance. This task benefits from models with strong instruction-following and structured output capabilities. Use a model that supports JSON mode or structured output constraints natively to reduce parsing failures. For high-volume pipelines, consider a smaller fine-tuned model if the layout extraction engine provides consistent element formatting. Cache the prompt prefix containing the schema and instructions across calls to reduce per-request token costs. Measure pipeline performance on three metrics: merge precision (did we merge only when correct?), merge recall (did we catch all true continuations?), and orphan rate (elements left unmerged that should have been stitched). Run these evals against a golden dataset of documents with known page-break continuations before deploying any prompt or model change.
Integration points. Wire the stitching step after layout extraction and before chunking or structured extraction. If your pipeline already produces markdown or JSON from each page, the stitcher should operate on the structured representation rather than raw text to preserve element type metadata. Downstream, the page-break annotations enable chunking strategies that respect element boundaries and retrieval systems that can cite continuous passages across page breaks without fabricating content. Avoid running stitching on documents where the layout extractor already handles page breaks correctly—add a pre-check that counts elements ending mid-sentence at page bottoms and only invoke the stitching prompt when the count exceeds a threshold.
Expected Output Contract
Defines the structure, types, and validation rules for the stitched output. Use this contract to build post-processing validators and integration tests before deploying the prompt.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
stitched_elements | Array of objects | Array must not be empty. Each object must have a unique element_id. | |
element_id | String | Must match pattern | |
element_type | Enum: paragraph, table, list, callout_box, code_block, other | Must be one of the allowed enum values. Reject unknown types. | |
content | String | Must be a non-empty string. For tables, content must be a valid Markdown table string. For lists, content must preserve bullet or numbered list markers. | |
page_break_annotations | Array of objects | If present, each object must contain | |
confidence_score | Number (0.0 to 1.0) | Must be a float between 0.0 and 1.0 inclusive. Score below [CONFIDENCE_THRESHOLD] should trigger a human review flag in the application layer. | |
source_pages | Array of integers | Must contain at least one positive integer. If the element spans multiple pages, the array must list all pages in ascending order. | |
continuity_marker | Enum: start, continuation, termination, standalone | Must be one of the allowed values. 'continuation' requires a preceding element with a matching element_type. 'termination' requires no subsequent continuation. |
Common Failure Modes
Multi-page element stitching fails silently in production when pipelines assume page boundaries are content boundaries. These are the most common breakages and how to catch them before they corrupt downstream retrieval, chunking, and structured extraction.
False Merges Across Unrelated Elements
What to watch: The stitcher joins a paragraph ending on one page with a sidebar or callout box starting on the next page because they share vertical proximity. The merged output reads as a single incoherent block. Guardrail: Require semantic continuity checks before merging. Compare font metadata, bounding box alignment, and content-type labels. Flag merges where the combined text has low coherence or where element types differ.
Orphaned Table Continuations
What to watch: A table header row appears on page N, but the continuation rows on page N+1 are treated as a new independent table instead of being stitched. Downstream extraction sees two partial tables with missing columns. Guardrail: Detect table fragments by checking for repeated header patterns, column count mismatches, and missing opening or closing borders. Require explicit table-continuation markers in the output schema and validate that every table fragment has a resolved parent.
Paragraph Split at Page Break Without Annotation
What to watch: A paragraph that spans a page break is split into two separate text blocks with no indication they belong together. Chunking and embedding treat them as independent units, breaking semantic coherence. Guardrail: Insert explicit page-break annotations in the stitched output. Validate that every paragraph ending mid-sentence at a page bottom has a corresponding continuation on the next page. Run sentence-boundary checks across page transitions.
List Item Numbering Reset on Continuation
What to watch: An ordered list continues across a page break, but the continuation items restart numbering at 1 instead of continuing the sequence. Downstream consumers see duplicate item numbers and broken list semantics. Guardrail: Detect list continuations by matching indentation, bullet style, and font properties. Preserve the original numbering sequence across page boundaries. Validate that no ordered list contains duplicate item numbers unless intentionally restarted.
Header and Footer Text Contamination
What to watch: Page headers, footers, or page numbers get stitched into body text when they appear between split elements. The merged output contains stray text like 'Chapter 3' or 'Page 12' mid-paragraph. Guardrail: Run header/footer suppression before stitching, not after. Validate stitched output against a known header/footer pattern list. Flag any merged block that contains text matching repeating page furniture patterns.
Silent Drop of Single-Line Page Orphans
What to watch: A single line of text at the top or bottom of a page—such as a widow line, footnote reference, or isolated heading—is dropped entirely during stitching because it doesn't match any continuation pattern. Guardrail: Audit for unassigned elements after stitching completes. Every extracted element must either be merged into a parent or explicitly flagged as a standalone element. Log orphaned elements with page coordinates for manual review or retry.
Evaluation Rubric
Use this rubric to test the quality of the multi-page element stitching output before integrating it into a production ingestion pipeline. Each criterion targets a known failure mode for this prompt template.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Continuation Detection | All split paragraphs, tables, and lists are correctly identified and merged into a single continuous element. | A split element appears as two separate, orphaned elements in the output. | Provide a 3-page document with a paragraph split across pages 1-2 and a table split across pages 2-3. Assert that exactly 2 stitched elements exist with correct page-break annotations. |
False Merge Prevention | No distinct elements from different pages are incorrectly merged together. | Two separate paragraphs or a list and a following paragraph are merged into one element. | Provide a document where a paragraph ends at the bottom of page 1 and a new, unrelated heading starts at the top of page 2. Assert that the output contains two distinct elements, not one merged block. |
Page-Break Annotation Accuracy | Every stitched element includes a | The | Parse the output JSON. For each stitched element, verify that |
Table Row Continuity | A table split across pages is stitched into a single table with all rows present and in the correct order, with no duplicated header rows. | The stitched table is missing rows, has rows in the wrong order, or includes a repeated header row in the middle of the table body. | Provide a 4-column table split after row 15 on page 1 and continuing on page 2 with a repeated header. Assert the output table has exactly the correct number of rows and the repeated header is removed. |
List Nesting Preservation | A nested list split across pages retains its correct indentation levels and bullet/number types after stitching. | The stitched list has flattened nesting or incorrect bullet types at the continuation point. | Provide a 3-level nested list split mid-item across pages. Assert the output list tree has the correct depth and marker types for all items, including the split item. |
Orphaned Continuation Flagging | Any element that appears to be a continuation but has no matching start element is flagged with | A continuation element is stitched without a start, or the | Provide a document where page 2 starts with the end of a sentence but page 1 is not supplied. Assert the output element has |
Callout Box Stitching | A callout box or sidebar split across pages is stitched into a single typed region object with correct boundaries. | The callout box is either not stitched or is merged into the surrounding body text. | Provide a document with a shaded callout box starting on page 1 and finishing on page 2. Assert the output contains a single element with |
Confidence Score Consistency | The stitched element's confidence score reflects the minimum confidence of its constituent parts and is not artificially inflated. | The stitched element has a confidence score of 1.0 when one of its parts had a score of 0.6. | Provide a split paragraph where one part has a confidence of 0.95 and the other 0.60. Assert the stitched element's confidence is <= 0.60. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Add strict schema validation, per-element confidence scoring, page-break annotations with exact coordinates, and a retry loop for low-confidence merges. Wire the output into your ingestion pipeline's chunking step so merged elements become coherent chunks.
Include [CONFIDENCE_SCORING_RULES] that require the model to score each merge decision (0.0-1.0) based on: semantic continuity, numbering sequence, font/size consistency, and layout proximity. Add [FALSE_MERGE_PREVENTION] rules: never merge elements with different heading levels, never merge across section boundaries, never merge when an intervening element exists on either page.
Prompt modification
Add to [CONSTRAINTS]: "For each merged element, output a merge_confidence float and a merge_evidence array of the signals you used. When confidence is below 0.7, set requires_review: true and include the conflicting evidence."
Add to [OUTPUT_SCHEMA]: page_break_positions array with {"after_character_index": number, "page_number": number, "layout_context": string} for each break within a merged element.
Watch for
- Silent format drift where the model stops including
merge_evidenceafter many elements - False merges across section boundaries when a section ends at the bottom of a page and a new section starts at the top of the next
- Orphaned continuations where the start of an element was on a page that wasn't included in the extraction window
- Performance degradation on documents with 50+ page breaks; consider batching by chapter or section

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us