Agentic Document Extraction: A Software Engineer's Guide to LandingAI's Python Library


Agentic Document Extraction: A Software Engineer's Guide to LandingAI's Python Library

landing-ai/agentic-doc

2025-07-19

Agentic Document Extraction by LandingAI is a powerful technology designed to extract structured data from visually complex documents. Unlike traditional OCR (Optical Character Recognition) that primarily focuses on recognizing text, this system goes a step further. It understands the visual layout and relationships between different elements within a document, such as text, tables, charts, and images. It then returns this extracted data in a hierarchical JSON format, complete with the exact locations of each element.

From a software engineer's perspective, this capability is incredibly valuable because it

Handles Complex Documents with Ease
It can process documents with intricate layouts, including checkboxes, charts, and nested tables, which are often challenging for simpler extraction methods.

"Reasons" About Document Content
It doesn't just read; it analyzes and connects component pieces, understanding their context and how they relate to each other visually and semantically.

Automates Data Preparation
The output is a structured JSON, making it "LLM-ready" (ready for Large Language Models) and suitable for direct use in various downstream applications like

Retrieval-Augmented Generation (RAG)
Powering chatbots or knowledge retrieval systems with accurate document content.

Business Process Automation
Streamlining tasks like financial statement analysis, contract review, claims processing, and supply chain document handling.

Compliance and Risk Management
Precisely extracting regulatory information or identifying risk factors from application forms.

Offers Robustness for Large-Scale Processing
The Python library specifically enhances the API by providing

Long-document support
Process PDFs with hundreds or even thousands of pages in a single call.

Automatic retry and paging
Handles concurrency, timeouts, and rate limits, ensuring reliable extraction even with large volumes.

Parallel processing
Efficiently parse multiple documents at once.

Visual Grounding
The extracted data includes references to the original document, page, and coordinates, which is great for traceability, debugging, and validation.

This means you can build more intelligent, automated systems that can "understand" and act upon information locked away in various document types, saving significant development time and improving accuracy compared to manual or less sophisticated methods.

The LandingAI Agentic Document Extraction functionality is accessible via a Python library. Here’s how you can typically set it up

Install the Library
You can install the Python library directly from its GitHub repository

pip install git+https://github.com/landing-ai/agentic-doc.git

Alternatively, you might find it on PyPI

pip install agentic-doc

Requirements

Python version 3.9, 3.10, 3.11, or 3.12.

A LandingAI Agentic AI API key. You will need to obtain this key from LandingAI.

Set Your API Key
After acquiring your API key, it's recommended to set it as an environment variable to keep it secure

export VISION_AGENT_API_KEY="<your-api-key>"

(Replace <your-api-key> with your actual key.)

Supported File Types
The library can extract data from

PDFs of any length.

Images supported by OpenCV-Python (e.g., JPEG, PNG).

URLs pointing to PDF or image files.

While I don't have a live environment to run and generate a full, runnable code snippet directly, based on the library's structure and common practices for such tools, a typical usage pattern would look something like this

import os
# Assuming the main class for document extraction is DocumentExtractor
# The actual import path might be slightly different, e.g., from agentic_doc import DocumentExtractor
from landingai.document import DocumentExtractor # This is a placeholder import based on typical library structures

# Ensure your API key is set as an environment variable:
# VISION_AGENT_API_KEY="your_actual_api_key_here"

def extract_data_from_document(file_path: str):
    """
    Extracts structured data from a given document using LandingAI's Agentic Document Extraction.
    """
    try:
        # Initialize the document extractor
        # In a real scenario, you might pass your API key here if not using env vars,
        # or it might pick it up automatically from the environment.
        extractor = DocumentExtractor()

        print(f"Loading document: {file_path}")
        document = extractor.load_document(file_path) # Load the document

        print("Extracting structured data...")
        # The 'extract' method is designed to get all structured data (text, tables, images, relationships)
        extracted_data = extractor.extract(document)

        print("\nExtracted Data (JSON Format - simplified example):")
        # In reality, 'extracted_data' would be a complex JSON object.
        # Here we're just printing a conceptual representation.
        if extracted_data:
            # For demonstration, let's assume extracted_data has a 'content' or similar attribute
            # that represents the structured output.
            # print(json.dumps(extracted_data, indent=2)) # You would typically pretty-print the JSON
            print("Successfully extracted data. Example of content structure might include sections, paragraphs, tables, etc.")
            print("You can access specific parts like:")
            print("- document.text (for full text)")
            # Example if a table was extracted:
            # for table in extracted_data.tables:
            #     print(f"Table found: {table.to_dataframe()}")
        else:
            print("No data extracted or document was empty.")

        # You might also want to extract specific types of data:
        # plain_text = extractor.extract_text(document)
        # tables = extractor.extract_tables(document) # Returns tables in a structured format

    except Exception as e:
        print(f"An error occurred during extraction: {e}")

if __name__ == "__main__":
    # Example usage: Replace 'your_document.pdf' with the path to your actual document
    # You can also use image files or URLs.
    # Make sure 'your_document.pdf' exists in the same directory or provide its full path.
    sample_document_path = "path/to/your/document.pdf" # e.g., "my_invoice.pdf" or "report.jpg"

    # For a real example, you would create a dummy PDF or use one you have.
    # For now, this is illustrative.
    if os.path.exists(sample_document_path):
        extract_data_from_document(sample_document_path)
    else:
        print(f"Please replace '{sample_document_path}' with a valid path to your document (PDF or image).")
        print("Example: If you have 'invoice.pdf' in the same directory, change the path to 'invoice.pdf'.")
        print("\nRemember to set your VISION_AGENT_API_KEY environment variable before running!")

Explanation of the Sample Code

DocumentExtractor
This is the core class you'd interact with. You'd instantiate it to begin the extraction process.

load_document(file_path)
This method is used to load your PDF or image file into the extractor.

extract(document)
This is the main method for comprehensive extraction. It intelligently processes the document and returns a rich, structured representation of its content, including text, tables, figures, and their relationships, often in a JSON format.

Error Handling
A try-except block is crucial for robust applications to catch any issues during the extraction process, such as invalid file paths or API errors.

By leveraging this library, software engineers can significantly reduce the complexity of working with unstructured documents, unlocking valuable data and enabling a new generation of intelligent applications!

Feel free to ask if you have more questions!

LandingAI Agentic Document Extraction Python library (GitHub)
Python library for Agentic Document Extraction from LandingAI

Agentic Document Extraction (LandingAI Overview)
Agentic Document Extraction | AI Document Intelligence by LandingAI

agentic-doc (PyPI)
agentic-doc - PyPI


landing-ai/agentic-doc