3  Structured Information Extraction with Vision Language Models

3.1 Introduction

In this chapter we’ll start to look at how we can use Visual Language Models (VLMs) to extract structured information from images of documents.

We already saw what this looked like at a conceptual level in the previous chapter. In this chapter we’ll get hands on with some code examples to illustrate how this can be done in practice. To start we’ll focus on some relatively simple documents and tasks. This allows us to focus on the core concepts without getting bogged down in too many complexities. We’ll use open source models accessed via the Hugging Face Inference API (you can also run them locally — see the appendix).

3.2 The Sloane Index Cards Dataset

We’ll use the Sloane Index Cards Dataset from Hugging Face for our examples. This is a publicly available dataset that is well suited to demonstrating structured information extraction with VLMs.

The files in this dataset are derived from microfilm copies of the original library catalogue of Sir Hans Sloane, now presented across 9 volumes, Sloane MS 3972 C 1-8, and the name index to the Sloane library catalogue, Sloane MS 3972 D. The catalogues are crucial for understanding the development of Sloane’s collections, the present-day collections of the British Library, British Museum and Natural History Museum, and to identifying collection items which are now dispersed across a number of institutions.

The dataset is available in Parquet format on Hugging Face so it can be easily loaded using the datasets library.

Let’s load the dataset and take a look at one row.

from datasets import load_dataset

ds = load_dataset("biglam/sloane-catalogues", split="train")
ds[0]
{'image': <PIL.JpegImagePlugin.JpegImageFile image mode=L size=3144x2267>,
 'filename': 'sloane_ms_3972_c!1_001.jpg',
 'collection': 'sloane_ms_3972_c!1_jpegs',
 'page_number': 1,
 'page_index_in_directory': 0,
 'source': 'British Library Sloane Manuscripts'}

We can see that we have a dictionary that contains an image as well as some additional metadata fields.

Let’s take a look at an actual example image from the dataset.

ds[0]["image"]

Let’s look at a couple more examples to get a sense of the variety in the dataset.

ds[2]["image"]

one more from later in the dataset

ds[50]["image"]

We can see we have a mixture of different types of digitised content here including index cards from the original microfilm as well as the actual handwritten manuscript pages from Sloane’s collection.

We’ll look at how we can use VLMs to work with kind of collection.

3.3 Setup

3.3.1 Connecting to a Vision Language Model

We’ll use Hugging Face Inference Providers to access VLMs via an API. This means we don’t need to install or run any models locally — we just need a free Hugging Face account and an API token.

Since the Hugging Face Inference API is compatible with the OpenAI Python client, all the code in this chapter will also work with local model servers (like LM Studio, Ollama, or vLLM) with just a one-line change to the client setup. See the appendix at the end of this chapter for details.

TipGetting a Hugging Face Token
  1. Create a free account at huggingface.co
  2. Go to Settings → Access Tokens
  3. Create a new token with Read access
  4. Set it as an environment variable: export HF_TOKEN=hf_... or add it to a .env file
import os
from openai import OpenAI
from rich import print as rprint
from dotenv import load_dotenv
load_dotenv()

client = OpenAI(
    base_url="https://router.huggingface.co/v1",
    api_key=os.environ.get("HF_TOKEN"),
)

We’ll use Qwen/Qwen3-VL-8B-Instruct throughout this chapter — an 8 billion parameter vision-language model that offers a good balance of quality and speed for document understanding tasks.

3.4 Basic VLM Query

Let’s start by defining a simple function that we can use to query a VLM with an image and a prompt. This function will handle converting the image to base64 and sending the request to the model.

We’ll default to using the Qwen/Qwen3-VL-8B-Instruct model via HF Inference Providers. You could experiment with different models later on — the code works with any OpenAI-compatible VLM endpoint.

Code
import base64
from PIL.Image import Image as PILImage
from io import BytesIO

def query_image(image: str | PILImage, prompt: str, model: str='Qwen/Qwen3-VL-8B-Instruct', max_image_size: int=1024, client=client) -> str:
    """Query VLM with an image."""
    if isinstance(image, PILImage):
        # Convert PIL Image to bytes and encode to base64
        buffered = BytesIO()
        # ensure image is not too big
        if image.size > (max_image_size, max_image_size):
            image.thumbnail((max_image_size, max_image_size))   
        image.save(buffered, format="JPEG")
        image_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
    else:
        # Assume image is a file path
        with open(image, "rb") as f:
            image_base64 = base64.b64encode(f.read()).decode('utf-8')
    #
    # Query
    response = client.chat.completions.create(
        model=model,
        messages=[{
            "role": "user",
            "content": [
                {"type": "text", "text": prompt},
                {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_base64}"}}
            ]
        }]
    )
    return response.choices[0].message.content

3.5 102: Simple VLM Query Example

To get started let’s do a simple query to describe an image from the dataset.

image = ds[0]["image"]

# Query the VLM to describe the image
description = query_image(image, "Describe this image.", model='Qwen/Qwen3-VL-8B-Instruct')
rprint(description)
This is a black-and-white image of a form from The British Library's Reprographic Section, used to request a copy 
of a manuscript or archival material.

Here is a breakdown of the information on the form:

*   **Institution:** The British Library, Reference Division, Reprographic Section.
*   **Address:** Great Russell Street, London WC1B 3DG.
*   **Department:** Manuscripts.
*   **Shelfmark:** SLOANE 3972.C. (Vol. 1)
*   **Order Number:** SCH NO 98876
*   **Author:** This field is blank.
*   **Title:** CATALOGUE OF SIR HANS SLOANES LIBRARY
*   **Place and date of publication:** This field is blank.
*   **Scale/Reduction:** The form indicates a reduction of 12, meaning the reproduction will be scaled down to 
1/12th of the original size. A ruler scale is provided for reference in centimetres and inches.

The form appears to be filled out by hand for a specific item: Volume 1 of the "Catalogue of Sir Hans Sloane's 
Library," which is held in the Manuscripts department under the shelfmark SLOANE 3972.C. This catalogue was 
compiled by Sir Hans Sloane himself and is a significant historical document detailing his extensive collection, 
which later formed part of the foundation of the British Museum and now resides at the British Library.

We can see we get a fairly useful description of the card. If we compare against the image we can see most of the details it mentions appear to be largely correct.

image

There are workflows where open ended description like this could be useful but this isn’t usually the kind of format we want if we want to take some action or do something based on the predictions of the model. In these cases it’s usually nice to have some more controlled output, for example, a label.

3.6 Classification

We’ll define a fairly simple prompt that asks the VLM to decide if a page is one of three categories. We describe each of these categopries and then ask the model to only return one of these as the output. We’ll do this for ten examples and we’ll also log how long it’s taking.

import time
from tqdm.auto import tqdm
from rich import print as rprint

sample_size = 10

sample = ds.take(sample_size)

prompt = """Classify this image into one of the following categories:

1. **Index/Reference Card**: A library catalog or reference card

2. **Manuscript Page**: A handwritten or historical document page

3. **Other**: Any document that doesn't fit the above categories

Examine the overall structure, layout, and content type to determine the classification. Focus on whether the document is a structured catalog/reference tool (Index Card) or a historical manuscript with continuous text (Manuscript Page).

Return only the category name: "Index/Reference Card", "Manuscript Page", or "Other"
"""

results = []
# Time the execution using standard Python
start_time = time.time()
for row in tqdm(sample):
    image = row['image']
    results.append(query_image(image, prompt, model='Qwen/Qwen3-VL-8B-Instruct'))
elapsed_time = time.time() - start_time
print(f"Execution time: {elapsed_time:.2f} seconds")
rprint(results)
Execution time: 18.31 seconds
[
    'Index/Reference Card',
    'Other',
    'Manuscript Page',
    'Manuscript Page',
    'Manuscript Page',
    'Manuscript Page',
    'Manuscript Page',
    'Manuscript Page',
    'Manuscript Page',
    'Manuscript Page'
]

Let’s check the result that was predicted as “index/reference card”

sample[0]['image']

We can extrapolate how long this would take for the full dataset

# Calculate average time per image
avg_time_per_image = elapsed_time / sample_size

# Project time for full dataset
total_images = len(ds)
projected_time = avg_time_per_image * total_images

print(f"Sample processing time: {elapsed_time:.2f} seconds ({elapsed_time/60:.2f} minutes)")
print(f"Average time per image: {avg_time_per_image:.2f} seconds")
print(f"Total images in dataset: {total_images}")
print(f"Projected time for full dataset: {projected_time/60:.2f} minutes ({projected_time/3600:.2f} hours)")
Sample processing time: 18.31 seconds (0.31 minutes)
Average time per image: 1.83 seconds
Total images in dataset: 2734
Projected time for full dataset: 83.45 minutes (1.39 hours)

3.6.1 Classifying with structured labels

In the previous example, we relied on the model to return the label in the correct format. While this often works, it can sometimes lead to inconsistencies in the output. To address this, we can use Pydantic models to define a structured output format. This way, we can ensure that the output adheres to a specific schema.

In this example, we’ll define a Pydantic model for our classification task. The model will have a single field category which can take one of three literal values "Index/Reference Card", "Manuscript Page", or "other".

What this means in practice is that the model will only be able to return one of these three values for the category field.

from pydantic import BaseModel, Field
from typing import Literal

class PageCategory(BaseModel):
    category: Literal["Index/Reference Card", "Manuscript Page", "other"] = Field(
        ..., description="The category of the image"
    )

When using the OpenAI client we can specify this Pydantic model as the response_format when making the request. This tells the model to return the output in a format that can be parsed into the Pydantic model (the APIs for this are still evolving so may change slightly over time).

buffered = BytesIO()
image.save(buffered, format="JPEG")
image_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
completion = client.beta.chat.completions.parse(
    model="Qwen/Qwen3-VL-8B-Instruct",
    messages=[
         {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": prompt,
                },
                {
                    "type": "image_url",
                    "image_url": {"url": f"data:image/jpeg;base64,{image_base64}"},
                },
            ],
        },
    ],
    max_tokens=200,
    temperature=0.7,
    response_format=PageCategory,
)
rprint(completion)
rprint(completion.choices[0].message.parsed)
ParsedChatCompletion[PageCategory](
    id='47c1a911111046291f6bbec65ebb1ead',
    choices=[
        ParsedChoice[PageCategory](
            finish_reason='stop',
            index=0,
            logprobs=None,
            message=ParsedChatCompletionMessage[PageCategory](
                content='{\n  "category": "Manuscript Page"\n}',
                refusal=None,
                role='assistant',
                annotations=None,
                audio=None,
                function_call=None,
                tool_calls=None,
                parsed=PageCategory(category='Manuscript Page')
            )
        )
    ],
    created=1771255803,
    model='qwen/qwen3-vl-8b-instruct',
    object='chat.completion',
    service_tier=None,
    system_fingerprint='',
    usage=CompletionUsage(
        completion_tokens=13,
        prompt_tokens=966,
        total_tokens=979,
        completion_tokens_details=CompletionTokensDetails(
            accepted_prediction_tokens=0,
            audio_tokens=0,
            reasoning_tokens=0,
            rejected_prediction_tokens=0,
            text_tokens=13,
            image_tokens=0,
            video_tokens=0
        ),
        prompt_tokens_details=PromptTokensDetails(
            audio_tokens=0,
            cached_tokens=0,
            cache_creation_input_tokens=0,
            cache_read_input_tokens=0,
            text_tokens=228,
            image_tokens=738,
            video_tokens=0
        )
    )
)
PageCategory(category='Manuscript Page')
image

3.7 Beyond classifying - Extracting structured information

So far we’ve focused on classifying images but what if we want to extract information from the images? Let’s take the first example from the dataset again.

index_image = ds[0]['image']
index_image

If we have an image like this we don’t just want to assign a label from it (we may do this as a first step) we actually want to extract the various fields from the card in a structured way. We can again use a Pydantic model to define the structure of the data we want to extract.

from pydantic import BaseModel, Field
from typing import Optional


class BritishLibraryReprographicCard(BaseModel):
    """
    Pydantic model for extracting information from British Library Reference Division 
    reprographic cards used to document manuscripts and other materials.
    """
    
    department: str = Field(
        ..., 
        description="The division that holds the material (e.g., 'MANUSCRIPTS')"
    )
    
    shelfmark: str = Field(
        ..., 
        description="The library's classification/location code (e.g., 'SLOANE 3972.C. (VOL 1)')"
    )
    
    order: str = Field(
        ..., 
        description="Order reference, typically starting with 'SCH NO' followed by numbers"
    )
    
    author: Optional[str] = Field(
        None, 
        description="Author name if present, null if blank or marked with diagonal line"
    )
    
    title: str = Field(
        ..., 
        description="The name of the work or manuscript"
    )
    
    place_and_date_of_publication: Optional[str] = Field(
        None, 
        description="Place and date of publication if present, null if blank"
    )
    
    reduction: int = Field(
        ..., 
        description="The reduction number shown at the bottom of the card"
    )

We’ll now create a function to handle the querying process using this structured schema.

def query_image_structured(image, prompt, schema, model='Qwen/Qwen3-VL-8B-Instruct'):
    """
    Query VLM with an image and get structured output based on a Pydantic schema.
    
    Args:
        image: PIL Image or file path to the image
        prompt: Text prompt describing what to extract
        schema: Pydantic model class defining the expected output structure
        model: Model ID to use for the query
    
    Returns:
        Parsed Pydantic model instance with the extracted data
    """
    # Convert image to base64
    if isinstance(image, PILImage):
        buffered = BytesIO()
        image.save(buffered, format="JPEG")
        image_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
    else:
        with open(image, "rb") as f:
            image_base64 = base64.b64encode(f.read()).decode('utf-8')
    
    # Query with structured output
    completion = client.beta.chat.completions.parse(
        model=model,
        messages=[{
            "role": "user",
            "content": [
                {"type": "text", "text": prompt},
                {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_base64}"}}
            ]
        }],
        response_format=schema,
        temperature=0.3  # Lower temperature for more consistent extraction
    )
    
    # Return the parsed structured data
    return completion.choices[0].message.parsed

We also need to define a prompt that describes what information we want to extract from the card.

# Example usage
extraction_prompt = """
Extract the information from this British Library card into structured data (JSON format).

Read each field on the card and extract the following information:
- department: The division name (e.g., "MANUSCRIPTS")
- shelfmark: The catalog number (e.g., "SLOANE 3972.C. (VOL 1)")
- order: The SCH NO reference number
- author: The author name, or null if blank
- title: The full title of the work
- place_and_date_of_publication: Publication info, or null if blank
- reduction: The reduction number (as integer) at bottom of card

Return the exact text as shown on the card. For empty fields with diagonal lines or no text, use null.
"""
result = query_image_structured(index_image, extraction_prompt, BritishLibraryReprographicCard)
rprint(result)
BritishLibraryReprographicCard(
    department='MANUSCRIPTS',
    shelfmark='SLOANE 3972.C. (VOL 1)',
    order='SCH NO 98876',
    author=None,
    title='CATALOGUE OF SIR HANS SLOANES LIBRARY',
    place_and_date_of_publication=None,
    reduction=12
)
rprint(result)
BritishLibraryReprographicCard(
    department='MANUSCRIPTS',
    shelfmark='SLOANE 3972.C. (VOL 1)',
    order='SCH NO 98876',
    author=None,
    title='CATALOGUE OF SIR HANS SLOANES LIBRARY',
    place_and_date_of_publication=None,
    reduction=12
)
index_image

3.8 Appendix: Using a Local Model

All the code in this chapter uses the OpenAI-compatible API, which means you can swap in a local model server with a single change to the client setup. Everything else — schemas, prompts, .parse() calls — works identically.

# Replace the HF Inference client with a local server
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:1234/v1",  # LM Studio default port
    api_key="lm-studio"                   # Default API key
)

Popular local options:

Tool Best for Notes
LM Studio Getting started quickly GUI-based, MLX acceleration on Mac, built-in model browser
Ollama CLI workflows Simple ollama run commands, runs on port 11434
vLLM Production & batch processing GPU-optimized, highest throughput, best for large-scale extraction
Note

Smaller local models (2B-4B parameters) work well for simpler tasks like classification, but for accurate structured extraction you’ll generally want 8B+ parameter models. The trade-off is between running costs/speed (local, smaller models) and extraction quality (API or larger models).