This prompt is for document pipeline engineers who need to extract a structured, hierarchical table of contents (TOC) from long documents—PDFs, reports, legal filings, technical manuals, or regulatory submissions—where the TOC carries the document's logical skeleton. The job-to-be-done is producing a navigable JSON tree of section titles, heading levels, page numbers, and parent-child relationships that can drive navigation UIs, search indexes, or downstream chunking strategies. The ideal user is an integration engineer or document intelligence developer building a production ingestion pipeline where TOC accuracy directly affects downstream retrieval and user experience.
Prompt
Table-of-Contents Extraction Prompt for Long Documents

When to Use This Prompt
Define the job, reader, and constraints for extracting structured table-of-contents entries from long documents.
Use this prompt when the source document has an explicit table of contents section or when section headings are consistently styled and numbered. It works best with documents that follow predictable heading conventions (e.g., '1.', '1.1', 'Chapter 3', 'Appendix A'). Do not use this prompt for documents without any heading structure, for image-only PDFs where OCR hasn't been applied, or for extracting body content itself—this prompt targets the TOC as a structural map, not the full text. The prompt assumes you've already extracted the TOC pages or the full document text and can provide it as [DOCUMENT_TEXT]. For multi-column layouts or documents where the TOC spans non-contiguous pages, pair this with the Reading Order Recovery Prompt first.
The prompt produces a JSON array of TOC entries, each with a title string, a hierarchical level integer, a page number, and an optional parent reference. The harness should validate that page numbers are monotonically increasing within each section, that heading levels don't skip (e.g., jumping from level 1 to level 3 without a level 2), and that the total entry count is plausible for the document length. For high-stakes documents like legal filings or regulatory submissions, add a human review step that compares the extracted TOC against the original document's stated TOC. The next section provides the copy-ready template with placeholders you can adapt to your document format and output schema.
Use Case Fit
Where this prompt works, where it fails, and the operational conditions required before putting it into a document pipeline.
Good Fit: Structured Long Documents
Use when: documents have explicit heading hierarchies, numbered sections, or a dedicated TOC page. Guardrail: works best on born-digital PDFs, well-formed markdown, or clean OCR output. Avoid handwritten or heavily scanned documents without layout preprocessing.
Bad Fit: Unstructured or Narrative Text
Avoid when: the document lacks clear section breaks, uses only visual formatting (bold, font size) without heading tags, or is a continuous narrative. Guardrail: preprocess with a layout analysis model to detect implicit structure before sending to this prompt.
Required Inputs
Must provide: full document text with preserved page markers, heading indicators, or TOC page content. Guardrail: if page numbers are missing or unreliable, use a page-offset validation step to reconcile extracted TOC entries against body text locations.
Operational Risk: TOC-to-Body Drift
What to watch: extracted TOC entries may reference sections that don't exist, have mismatched titles, or point to wrong pages. Guardrail: always run a post-extraction consistency check comparing TOC entries against actual section headers found in the document body.
Operational Risk: Hierarchical Collapse
What to watch: deeply nested sections (H1-H6) may flatten into a single level if the prompt doesn't enforce hierarchy preservation. Guardrail: require explicit parent-child relationships in the output schema and validate tree depth against the source document's heading levels.
Operational Risk: Page Number Noise
What to watch: roman numerals, offset page numbering, or missing page references can corrupt navigation trees. Guardrail: normalize all page references to a consistent zero-based or one-based offset and flag entries where page numbers cannot be reconciled with the document's physical page count.
Copy-Ready Prompt Template
A reusable prompt template with square-bracket placeholders for extracting a structured table of contents from a long document.
The following prompt template is designed to be dropped into your document processing pipeline. It instructs the model to extract a hierarchical table of contents (TOC) from the provided document text, returning a navigable JSON tree. The template uses square-bracket placeholders for all dynamic inputs, allowing you to swap in the document content, specify the desired output schema, and add any domain-specific constraints without rewriting the core instruction.
textYou are a precise document structure extraction engine. Your task is to extract the table of contents from the provided document. INPUT DOCUMENT: --- [DOCUMENT_TEXT] --- INSTRUCTIONS: 1. Identify all entries that constitute the document's table of contents, including section headings, subheadings, and any listed front-matter or back-matter items (e.g., Preface, Appendix, Index). 2. For each entry, determine its hierarchical level. The top-level sections are level 1, their direct subsections are level 2, and so on. 3. Extract the exact title text for each entry. 4. If a page number is provided for an entry, capture it as an integer. If no page number is present, use `null`. 5. Reconstruct the full hierarchy as a nested JSON tree structure. OUTPUT_SCHEMA: ```json [OUTPUT_SCHEMA]
CONSTRAINTS:
- Do not infer or hallucinate entries that are not explicitly present in the text.
- Preserve the original casing and punctuation of titles.
- If the document contains multiple conflicting TOCs (e.g., a brief overview and a detailed one), prioritize the most detailed one and note the conflict in a
[WARNING]comment within the output. - If no TOC is found, return an empty list
[]. - [CONSTRAINTS]
EXAMPLES OF GOOD OUTPUT: [EXAMPLES]
Now, extract the table of contents.
To adapt this template, start by replacing [DOCUMENT_TEXT] with the full text of your document. The [OUTPUT_SCHEMA] placeholder is critical for downstream integration; replace it with the exact JSON schema you expect, for example, a recursive structure with title, page, level, and children fields. Use the [CONSTRAINTS] placeholder to inject domain-specific rules, such as ignoring page numbers in a legal document's table of authorities or handling documents where sections are numbered with Roman numerals. The [EXAMPLES] placeholder should be used to provide one or two few-shot examples of a correctly parsed TOC from a similar document, which dramatically improves accuracy on complex layouts. After generating the output, always validate it against your schema and run a consistency check to ensure the extracted page numbers are monotonically increasing and that no section titles are duplicated at the same level without a clear distinguishing context.
Prompt Variables
Required inputs for the Table-of-Contents extraction prompt. Each placeholder must be populated before the prompt is sent. Validation notes describe how to check the input before execution.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[DOCUMENT_TEXT] | Full text of the document from which the TOC will be extracted | Chapter 1. Introduction\n1.1 Background\n...\nAppendix A. Glossary | Must be non-empty string. Check character length against model context window. Strip non-printable control characters before insertion. |
[PAGE_OFFSET] | Starting page number for the document, used to calculate absolute page references | 1 | Must be a non-negative integer. If null or 0, page numbers in output are relative to document start. Validate that [PAGE_OFFSET] + max extracted page number does not exceed known document length. |
[MAX_DEPTH] | Maximum heading nesting level to extract | 4 | Must be an integer between 1 and 6. Depths above 6 increase hallucination risk for flat documents. Default to 4 if unspecified. |
[OUTPUT_SCHEMA] | JSON schema or format description the model must conform to | {"entries": [{"title": string, "level": int, "page": int|null}]} | Must be a valid JSON Schema object or a strict natural-language format spec. Validate schema parseability before prompt assembly. Reject schemas that allow ambiguous field types. |
[INCLUDE_UNNUMBERED] | Boolean flag indicating whether to extract unnumbered headings such as Preface or Foreword | Must be 'true' or 'false'. When false, the model may skip front-matter sections. Log this flag in trace for downstream TOC-to-body consistency checks. | |
[TITLE_PATTERN_HINT] | Optional regex or description of the document's heading pattern to improve extraction accuracy | Chapter \d+. .* | If provided, must be a valid regex string or null. Test regex against sample headings before use. Null is allowed and triggers default heading detection. |
[LANGUAGE_HINT] | ISO 639-1 language code of the document to guide tokenization and title boundary detection | en | Must be a valid two-letter ISO 639-1 code or null. Use 'null' for auto-detection. Mismatched language hints degrade title-boundary accuracy in multi-script documents. |
Implementation Harness Notes
How to wire the TOC extraction prompt into a production document pipeline with validation, retries, and consistency checks.
The TOC extraction prompt is rarely a standalone call. In production, it sits inside a document processing pipeline that first extracts the raw text (and optionally layout metadata) from a PDF or other format, then passes a windowed segment containing the table of contents to the LLM. The prompt expects a chunk of text that includes the TOC, but it does not need the entire document body. A common pattern is to extract the first 5–15 pages of a long document, or to use a layout-aware parser to isolate the TOC section before sending it to the model. This reduces token cost and prevents the model from confusing body-text headings with TOC entries.
Validation and repair loop. The prompt output is a JSON array of TOC entries with level, title, and page fields. Before accepting the result, run a structural validator that checks: (1) the root entry has level: 1, (2) levels increment by at most 1 between consecutive entries (no skipped levels), (3) page numbers are non-decreasing, and (4) every entry has a non-empty title. If validation fails, feed the malformed output and the specific validator error back to the model in a repair prompt: 'The previous output failed validation with error: [ERROR]. The TOC must have a single level-1 root, no skipped nesting levels, and non-decreasing page numbers. Return the corrected JSON.' Allow up to 2 repair retries before flagging for human review. Log every repair attempt with the validator error and the model's correction for observability.
TOC-to-body consistency check. The most dangerous failure mode is a TOC that looks structurally valid but does not match the actual document body. After extraction, run a consistency harness that samples 5–10 TOC entries, searches for the corresponding section titles in the document body text, and verifies that the section appears near the claimed page number. Use fuzzy string matching (e.g., Levenshtein distance with a threshold of 0.85) to handle minor OCR or formatting differences. Flag any entry where the title cannot be found within ±1 page of the claimed location. If more than 10% of sampled entries fail, reject the entire TOC and escalate for manual review. This check catches hallucinated entries, page-offset errors from Roman-numeral front matter, and misaligned PDF text extraction.
Model choice and latency budget. For most TOC extraction tasks, a mid-tier model (e.g., GPT-4o-mini, Claude 3.5 Haiku, or a fine-tuned open-weight model) provides sufficient accuracy at low latency and cost. Reserve larger models for documents with complex multi-level numbering schemes, legal clause references, or non-English TOCs. Set a latency budget of 3–5 seconds for the initial extraction call, and 2 seconds per repair retry. If the document pipeline processes hundreds of documents per hour, batch TOC extraction calls asynchronously and use a model router that falls back to a faster model when the primary model exceeds the latency budget.
Integration with downstream systems. The validated TOC JSON should be stored alongside the document record in your search index or document store. Use the page field to build navigation links in a document viewer, and the level and title fields to render an expandable sidebar tree. If your system supports section-level retrieval for RAG, use the TOC entries as chunk boundary hints: each TOC entry defines a logical section start, and you can chunk the document body from one TOC entry's page to the next. This produces semantically coherent chunks that align with the document's own structure. Avoid using the TOC as the sole source of truth for document structure without the consistency check described above—always verify against the body.
Common Failure Modes
TOC extraction fails silently in ways that corrupt downstream navigation and chunking. These are the most common failure modes and how to prevent them before they reach production.
Flat List Instead of Nested Hierarchy
What to watch: The model outputs a flat array of entries instead of a proper parent-child tree. All sections appear at the same level, losing the document's logical structure. This happens when the prompt doesn't explicitly require nested output or when the document uses inconsistent heading styles. Guardrail: Require a strict recursive JSON schema with children arrays. Add a post-extraction validator that rejects any output where all entries share the same level value and the document exceeds a minimum depth threshold.
Page Number Hallucination
What to watch: The model fabricates page numbers that don't match the source document, especially for sections near page boundaries or when page markers are ambiguous in the extracted text. This breaks every downstream navigation feature. Guardrail: Cross-validate extracted page numbers against the document's actual page count. Flag any entry where the page number exceeds the total page count or where sequential entries have non-monotonic page numbers. For high-stakes pipelines, require page-offset validation against the original PDF page index.
Missing Mid-Level Sections
What to watch: The model skips intermediate heading levels, producing a hierarchy that jumps from H1 directly to H3. This creates orphaned sub-sections and broken navigation paths. Common in documents with subtle visual hierarchy cues rather than explicit numbering. Guardrail: Implement a heading-level continuity check that detects gaps in the numbering sequence. Require the prompt to explicitly enumerate all heading levels present and instruct the model to mark missing levels with a gap_detected flag rather than silently collapsing the hierarchy.
TOC-to-Body Mismatch
What to watch: The extracted TOC entries don't match the actual section headings found in the document body. The model may extract from a document's own TOC page but fail to verify against body content, or it may generate a TOC from body headings but miss entries listed only in the TOC page. Guardrail: Run a consistency check that samples body-text headings at random positions and verifies they appear in the extracted TOC. For documents with an explicit TOC page, cross-reference extracted entries against both the TOC page and body headings, flagging discrepancies for human review.
Title Text Truncation or Concatenation
What to watch: Long section titles get truncated mid-phrase, or adjacent short titles get concatenated into a single nonsensical entry. This is especially common with OCR-processed documents where line breaks are ambiguous or with decorative title formatting that confuses boundary detection. Guardrail: Set explicit maximum and minimum title length bounds based on the document type. Add a post-extraction filter that flags titles below a minimum word count or above a maximum character threshold. For concatenation, check for entries that contain multiple numbering patterns or punctuation anomalies.
Introductory Front Matter Misclassified as Sections
What to watch: The model extracts preface, abstract, disclaimer, and table-of-contents entries as if they were numbered body sections. This pollutes the navigation tree with non-content entries and breaks section-count expectations. Guardrail: Add explicit exclusion rules in the prompt for front-matter patterns such as roman-numeral pages, unnumbered prefaces, and TOC self-references. Implement a post-extraction classifier that identifies and optionally relegates front-matter entries to a separate front_matter array rather than the main hierarchy.
Evaluation Rubric
Criteria for testing TOC extraction quality before integrating into a production document pipeline. Each row defines a pass standard, a failure signal, and a concrete test method.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Entry Count Match | Extracted entry count equals the number of entries in the ground-truth TOC within a tolerance of 1 | Entry count differs by more than 2 entries from ground truth | Parse output JSON, count entries in the [entries] array, and compare to the labeled count in the golden dataset |
Title Text Exact Match | At least 95% of extracted [title] fields match ground-truth titles after whitespace normalization | More than 5% of titles contain character-level errors, truncation, or hallucinated words | Normalize whitespace, lowercase both extracted and expected titles, compute Levenshtein distance, and flag any distance greater than 2 |
Hierarchy Depth Correctness | Every entry's [level] integer matches the ground-truth nesting depth | Any entry has a [level] value that is off by more than 1 from ground truth | Walk the output tree, compare each node's [level] to the expected depth in the golden hierarchy, and count mismatches |
Page Number Accuracy | At least 98% of extracted [page] values match ground-truth page numbers exactly | Any page number is off by more than 1 or is null when ground truth has a valid integer | Extract all [page] fields, compare to golden page numbers, and flag any difference greater than 0 |
Parent-Child Link Integrity | Every non-root entry has a valid [parent_id] that references an existing entry with a lower [level] | Any [parent_id] points to a non-existent entry or an entry with an equal or higher [level] | Build a set of all entry IDs, verify every [parent_id] exists in the set, and assert that the parent's [level] is strictly less than the child's [level] |
No Hallucinated Entries | Zero entries exist in the output that cannot be matched to a ground-truth TOC line | Output contains a title or page reference not present in the source document's actual TOC | Perform fuzzy string matching between every output [title] and the set of ground-truth titles; flag any entry with no match above a 0.8 similarity threshold |
Page Offset Consistency | All extracted [page] values fall within the document's known page range and are monotonically non-decreasing when sorted by TOC order | A page number is negative, zero, exceeds the document page count, or decreases relative to the previous entry | Validate that min([page]) >= 1, max([page]) <= [DOCUMENT_PAGE_COUNT], and the sequence of page numbers is sorted in ascending order |
Schema Compliance | Output is valid JSON that parses without errors and contains all required fields: [id], [title], [level], [page], [parent_id] | JSON parse failure, missing required fields, or fields with incorrect types (e.g., string instead of integer for [level]) | Run the output through a JSON schema validator configured with the expected output contract; reject on any validation error |
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
Use the base prompt with a frontier model (GPT-4o, Claude 3.5 Sonnet). Accept raw JSON output without strict schema enforcement. Focus on getting the hierarchy and page numbers correct for a single document type.
codeExtract the table of contents from [DOCUMENT_TEXT] as a JSON array of entries. Each entry: {"level": <int>, "title": <string>, "page": <int or null>}.
Watch for
- Page numbers parsed as strings instead of integers
- Roman numeral front matter pages causing type errors
- Flat lists instead of nested hierarchies when the source uses indentation alone

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