andrewyng/context-hub/document-workflows

Claude Code and agent skill by andrewyng/context-hub

Trust tier 2
  • community
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

Use this skill for building end-to-end document processing workflows and pipelines using LandingAI ADE. Trigger when users need to: (1) Process batches of documents in parallel or async, (2) Build classify-then-extract pipelines for mixed document types, (3) Prepare parsed documents for RAG systems with chunking and vector DB ingestion, (4) Load extraction results into databases like Snowflake or export to CSV/DataFrames, (5) Visualize extraction results: draw bounding box overlays on pages, cr…

Install

npx vskill@latest install andrewyng/context-hub/document-workflows

SKILL.md

The same SKILL.md was published earlier as andrewyng/context-hub/document-workflows.

Document Workflows — ADE Pipeline Patterns

Overview

This skill provides reusable building blocks for composing LandingAI ADE primitives (parse, extract, split) into production-ready document processing pipelines. It complements the document-extraction skill:

Concerndocument-extractiondocument-workflows
ScopeADE SDK API: parse, extract, split, groundingEnd-to-end pipelines: batch, RAG, DB, classify-route
WhenNeed to call a single ADE operationNeed to compose operations into a workflow
CodeSDK method calls with parametersComplete functions with error handling, parallelism
Depslandingai-ade only+ workflow-specific libs (pandas, chromadb, etc.)

Philosophy: Organize by workflow pattern (batch, RAG, DB insertion), not by document type. The same pattern applies whether documents are invoices, utility bills, or medical forms.


Step 0 (mandatory) — Pre-Flight Document Exploration {#pre-flight}

Run this before writing any pipeline code whenever working with documents whose internal structure has not already been inspected in this session.

**Rule: never write section-detection, heading-matching, or text-search code
without first running Tool 2 (diagnostic parse) on the sample document.
Heading format is document-specific and cannot be inferred from the task
description or document type alone — the only reliable way to know it is to
look at the actual ADE output.**
Common surprises: a paper's "Introduction" heading may appear as
1. Introduction (plain text, no #), ## Introduction, INTRODUCTION
(all-caps), or embedded inside a text chunk with body copy. Getting this
wrong means a silent failure (zero chunks matched) that requires a full
re-parse to debug.

Run Tool 1 (visual render) and Tool 2 (diagnostic parse) on 1–3 representative sample documents before writing any code. This takes under a minute and prevents debugging iterations that a pre-flight would have avoided.

Tool 1 — Visual page render

Render 1–2 pages as PNG and read them as visual context. No ADE credits used, but each PNG consumes context tokens. Use when layout is ambiguous or document origin is unknown (handwriting? scan? form?).

bash
.venv/bin/python - << 'EOF'
import pymupdf
from pathlib import Path
from PIL import Image
pdf = Path('path/to/sample.pdf')
out_dir = Path('/tmp/ade_preflight'); out_dir.mkdir(exist_ok=True)
doc = pymupdf.open(pdf)
for pg in range(min(2, len(doc))): # first 2 pages only
pix = doc[pg].get_pixmap(matrix=pymupdf.Matrix(1.5, 1.5)) # 108 DPI
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
out = out_dir / f"{pdf.stem}_page{pg + 1}.png"
img.save(out)
print(out)
doc.close()
EOF

Then read the saved PNGs. Immediately answers:

  • Are headings bold text (→ ADE may output plain-text heading, not # Heading)
  • Is the document handwritten or scanned? → Tesseract OCR needed, not PyMuPDF
  • Single-column or two-column layout?
  • Any noise: running headers, page numbers, watermarks, stamps?
Tool 2 — ADE diagnostic parse

Parses 1 sample and prints markdown structure + chunk inventory. Uses ADE credits — keep to 1–3 samples only, never the full corpus.

bash
.venv/bin/python - << 'EOF'
import os
from pathlib import Path
from collections import Counter
from dotenv import load_dotenv
# Load API key: prefer existing env var, then .env file lookup
load_dotenv() # Load API key from .env. Add a path to the .env if needed.
from landingai_ade import LandingAIADE
client = LandingAIADE()
pr = client.parse(document=Path('path/to/sample.pdf'))
print("=== MARKDOWN (first 80 lines) ===")
for i, ln in enumerate(pr.markdown.splitlines()[:80], 1):
print(f"{i:3}: {ln}")
print("\n=== CHUNKS ===")
for ch in pr.chunks:
txt = (ch.markdown or '').replace('\n', ' ')[:70]
b = ch.grounding.box
print(f"p{ch.grounding.page} {ch.type:12} "
f"l={b.left:.2f} t={b.top:.2f} r={b.right:.2f} b={b.bottom:.2f} | {txt}")
print(f"\nPages: {pr.metadata.page_count} "
f"Chunks: {len(pr.chunks)} "
f"Types: {dict(Counter(ch.type for ch in pr.chunks))}")
EOF
Cost note: Save the parse result with pr.model_dump() to a JSON file
after the first run. Load it for later development instead of calling
client.parse() again. Only re-parse when the document set changes.
What to look for
ObservationImplication
Heading is 1. Introduction (plain text, no #)ADE markdown won't use ATX header → use ADE extract, not regex
Heading format varies across docs (# INTRO in one, 1. Intro in another)Regex will break on some docs → use ADE extract for robustness
Every ch.markdown starts with <a id='...'></a>Strip anchor before string matching or display
Two-column: chunks on same page with l=0.07 vs l=0.50Text order is left column then right; sections may span both
Chunk text cut mid-word at page breakSection spans pages; collect chunks from multiple pages
marginalia chunks at t<0.08 or t>0.90Running headers / page numbers → exclude from content extraction
Scanned / handwritten content visible in page imagePyMuPDF text extraction won't work → use Tesseract OCR
Tool 3 — Post-Crop Visual Verification (mandatory for bounding-box workflows) {#post-crop-verification}

After producing any bounding-box crop or overlay (figure extraction, chunk cropping, table cell extraction, word-level grounding), read back at least one output PNG as an image and describe what you see. Compare your description against the user's request. This catches:

  • Wrong-page bugs — ADE page numbers are 0-indexed; an off-by-one error

lands the crop on an adjacent page with completely different content

  • Wrong-region bugs — coordinate system mismatches that crop blank space

or an unrelated section

**Rule: never declare a crop workflow complete without visually reading at
least one output PNG and confirming its content matches the user's request.**
Verification steps
  1. Save the first crop as PNG (the workflow already does this)
  2. Read the PNG file as an image (use the read_file tool on the PNG path)
  3. Describe what you see: what content, table, figure, or text appears?
  4. Compare against the user's request:
  • User asked for "the Events table" → does the crop show an Events table?
  • User asked for "Figure 3" → does the crop show a chart/diagram?
  • User asked for "Introduction section" → does the crop show intro text?
  1. If the description doesn't match → investigate page indexing and

bounding-box coordinates before continuing

  1. Only proceed with remaining crops after the first one is verified
Why LLM vision, not heuristics

A blank-check heuristic (e.g. "mean brightness > 250 → blank") catches only the most obvious failures. The agent's own vision capability can semantically verify: "this crop shows a bar chart" vs "the user asked for a data table." This catches wrong-page errors even when the crop contains valid content from the wrong section.


Quick Reference — Building Blocks

#BlockPatternReference
0Pre-flight (mandatory)Render pages + diagnostic parse before buildingAbove
1Parse + SaveSingle doc → JSON + markdownBelow
2Parse + Extract + SaveSingle doc → structured dataBelow
3Batch (sync)ThreadPoolExecutor + tqdmbatch-processing.md
4Batch (async)AsyncLandingAIADE + aiolimiterbatch-processing.md
5Large filesParse Jobs API (async polling)batch-processing.md
6Classify → ExtractEnum classification + schema routingBelow
7Results → DataFrameFlatten nested extraction to tablesdatabase-integration.md
8Results → CSVSummary + per-document exportdatabase-integration.md
9Results → Snowflake4 normalized tables + COPY uploaddatabase-integration.md
10Chunks → RAG CSV19-column chunk datasetrag-pipelines.md
11Chunks → ChromaDBOpenAI embeddings + persistent storerag-pipelines.md
12Chunks → FAISSLangChain Documents + FAISS indexrag-pipelines.md
13RAG queryRetrievalQA chain with sourcesrag-pipelines.md
14Chunk imagesCrop chunks from pages as PNGsvisualization.md
15Grounding overlayColor-coded bounding boxes on pagesvisualization.md
16Word-level groundingOCR + fuzzy match highlightingvisualization.md
17Section extractionNamed section from markdown (regex or ADE extract)Below
18Embedding computationLocal (FastEmbed) or API (OpenAI) with best practicesrag-pipelines.md
19Hierarchical chunkingGroup ADE chunks into semantic units for embeddingrag-pipelines.md
20Multi-granularity RAGChunk vs hierarchical vs document-level strategyrag-pipelines.md
21Table stitchingParse-only or parse+extract merge of multi-page tablestable-stitching.md
—Schema catalogReady-to-use Pydantic modelsschema-catalog.md

Core Workflow: Parse + Extract + Save

The fundamental two-step ADE pattern. Every other workflow builds on this.

python
import io
from pathlib import Path
from typing import Any, Tuple, Type
from landingai_ade import LandingAIADE
from landingai_ade.lib import pydantic_to_json_schema
def parse_extract_save(
doc_path: Path,
client: LandingAIADE,
schema_cls: Type[Any],
output_dir: str = "./ade_results",
) -> Tuple[Any, Any]:
"""Parse a document, extract structured data, save both
as JSON via save_to. Returns (parse_result, extract_result)."""
# Step 1 — Parse (auto-saves {stem}_parse_output.json)
parse_result = client.parse(
document=doc_path, save_to=output_dir,
)
# Step 2 — Extract (auto-saves {stem}_extract_output.json)
extract_result = client.extract(
schema=pydantic_to_json_schema(schema_cls),
markdown=io.BytesIO(
parse_result.markdown.encode("utf-8")
),
save_to=output_dir,
)
return parse_result, extract_result
`save_to` parameter: Available on parse(), extract(), and split().
Creates the folder if needed and writes {input_filename}_{method}_output.json.
This is a client-side convenience — the full response is saved locally after the API call.
Parse-Only (no extraction)
python
def parse_and_save(
doc_path: Path,
client: LandingAIADE,
output_dir: str = "./ade_results",
) -> Any:
return client.parse(
document=doc_path, save_to=output_dir,
)
Schemas: See schema-catalog.md for
ready-to-use Pydantic models (invoice, utility bill, bank statement,
pay stub, food label, CME certificate, document classifier).
See the document-extraction skill for schema design rules.

Classify-then-Extract

Process mixed document types by first classifying, then applying the appropriate schema. Two approaches:

Approach 1: Classification Extraction (any document mix)

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
0

Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/andrewyng/context-hub/document-workflows/badge)](https://verified-skill.com/skills/andrewyng/context-hub/document-workflows)

Something wrong with this skill or its page? Tell us.