ai-patterns-for-glam / patterns /structured-generation /vlm-structured-generation.html
davanstrien's picture
davanstrien HF Staff
Upload folder using huggingface_hub
b292d4f verified
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head>
<meta charset="utf-8">
<meta name="generator" content="quarto-1.8.27">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<title>3&nbsp; Structured Information Extraction with Vision Language Models – AI Design Patterns for GLAM</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
div.columns{display: flex; gap: min(4vw, 1.5em);}
div.column{flex: auto; overflow-x: auto;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
ul.task-list li input[type="checkbox"] {
width: 0.8em;
margin: 0 0.8em 0.2em -1em; /* quarto-specific, see https://github.com/quarto-dev/quarto-cli/issues/4556 */
vertical-align: middle;
}
/* CSS for syntax highlighting */
html { -webkit-text-size-adjust: 100%; }
pre > code.sourceCode { white-space: pre; position: relative; }
pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
pre > code.sourceCode > span:empty { height: 1.2em; }
.sourceCode { overflow: visible; }
code.sourceCode > span { color: inherit; text-decoration: inherit; }
div.sourceCode { margin: 1em 0; }
pre.sourceCode { margin: 0; }
@media screen {
div.sourceCode { overflow: auto; }
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; }
}
pre.numberSource code
{ counter-reset: source-line 0; }
pre.numberSource code > span
{ position: relative; left: -4em; counter-increment: source-line; }
pre.numberSource code > span > a:first-child::before
{ content: counter(source-line);
position: relative; left: -1em; text-align: right; vertical-align: baseline;
border: none; display: inline-block;
-webkit-touch-callout: none; -webkit-user-select: none;
-khtml-user-select: none; -moz-user-select: none;
-ms-user-select: none; user-select: none;
padding: 0 4px; width: 4em;
}
pre.numberSource { margin-left: 3em; padding-left: 4px; }
div.sourceCode
{ }
@media screen {
pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; }
}
</style>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js" integrity="sha384-ZvpUoO/+PpLXR1lu4jmpXWu80pZlYUAfxl5NsBMWOEPSjUn/6Z/hRTt8+pR6L4N2" crossorigin="anonymous"></script><script src="../../site_libs/quarto-nav/quarto-nav.js"></script>
<script src="../../site_libs/quarto-nav/headroom.min.js"></script>
<script src="../../site_libs/clipboard/clipboard.min.js"></script>
<script src="../../site_libs/quarto-search/autocomplete.umd.js"></script>
<script src="../../site_libs/quarto-search/fuse.min.js"></script>
<script src="../../site_libs/quarto-search/quarto-search.js"></script>
<meta name="quarto:offset" content="../../">
<link href="../../patterns/structured-generation/intro.html" rel="prev">
<script src="../../site_libs/quarto-html/quarto.js" type="module"></script>
<script src="../../site_libs/quarto-html/tabsets/tabsets.js" type="module"></script>
<script src="../../site_libs/quarto-html/axe/axe-check.js" type="module"></script>
<script src="../../site_libs/quarto-html/popper.min.js"></script>
<script src="../../site_libs/quarto-html/tippy.umd.min.js"></script>
<script src="../../site_libs/quarto-html/anchor.min.js"></script>
<link href="../../site_libs/quarto-html/tippy.css" rel="stylesheet">
<link href="../../site_libs/quarto-html/quarto-syntax-highlighting-ed96de9b727972fe78a7b5d16c58bf87.css" rel="stylesheet" id="quarto-text-highlighting-styles">
<script src="../../site_libs/bootstrap/bootstrap.min.js"></script>
<link href="../../site_libs/bootstrap/bootstrap-icons.css" rel="stylesheet">
<link href="../../site_libs/bootstrap/bootstrap-27c261d06b905028a18691de25d09dde.min.css" rel="stylesheet" append-hash="true" id="quarto-bootstrap" data-mode="light">
<script id="quarto-search-options" type="application/json">{
"location": "sidebar",
"copy-button": false,
"collapse-after": 3,
"panel-placement": "start",
"type": "textbox",
"limit": 50,
"keyboard-shortcut": [
"f",
"/",
"s"
],
"show-item-context": false,
"language": {
"search-no-results-text": "No results",
"search-matching-documents-text": "matching documents",
"search-copy-link-title": "Copy link to search",
"search-hide-matches-text": "Hide additional matches",
"search-more-match-text": "more match in this document",
"search-more-matches-text": "more matches in this document",
"search-clear-button-title": "Clear",
"search-text-placeholder": "",
"search-detached-cancel-button-title": "Cancel",
"search-submit-button-title": "Submit",
"search-label": "Search"
}
}</script>
<script src="https://cdn.jsdelivr.net/npm/requirejs@2.3.6/require.min.js" integrity="sha384-c9c+LnTbwQ3aujuU7ULEPVvgLs+Fn6fJUvIGTsuu1ZcCf11fiEubah0ttpca4ntM sha384-6V1/AdqZRWk1KAlWbKBlGhN7VG4iE/yAZcO6NZPMF8od0vukrvr0tg4qY6NSrItx" crossorigin="anonymous"></script>
<script type="application/javascript">define('jquery', [],function() {return window.jQuery;})</script>
<script src="https://cdn.jsdelivr.net/npm/@jupyter-widgets/html-manager@*/dist/embed-amd.js" crossorigin="anonymous"></script>
</head>
<body class="nav-sidebar floating quarto-light">
<div id="quarto-search-results"></div>
<header id="quarto-header" class="headroom fixed-top">
<nav class="quarto-secondary-nav">
<div class="container-fluid d-flex">
<button type="button" class="quarto-btn-toggle btn" data-bs-toggle="collapse" role="button" data-bs-target=".quarto-sidebar-collapse-item" aria-controls="quarto-sidebar" aria-expanded="false" aria-label="Toggle sidebar navigation" onclick="if (window.quartoToggleHeadroom) { window.quartoToggleHeadroom(); }">
<i class="bi bi-layout-text-sidebar-reverse"></i>
</button>
<nav class="quarto-page-breadcrumbs" aria-label="breadcrumb"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="../../patterns/structured-generation/intro.html">Structured Information Extraction</a></li><li class="breadcrumb-item"><a href="../../patterns/structured-generation/vlm-structured-generation.html"><span class="chapter-number">3</span>&nbsp; <span class="chapter-title">Structured Information Extraction with Vision Language Models</span></a></li></ol></nav>
<a class="flex-grow-1" role="navigation" data-bs-toggle="collapse" data-bs-target=".quarto-sidebar-collapse-item" aria-controls="quarto-sidebar" aria-expanded="false" aria-label="Toggle sidebar navigation" onclick="if (window.quartoToggleHeadroom) { window.quartoToggleHeadroom(); }">
</a>
<button type="button" class="btn quarto-search-button" aria-label="Search" onclick="window.quartoOpenSearch();">
<i class="bi bi-search"></i>
</button>
</div>
</nav>
</header>
<!-- content -->
<div id="quarto-content" class="quarto-container page-columns page-rows-contents page-layout-article">
<!-- sidebar -->
<nav id="quarto-sidebar" class="sidebar collapse collapse-horizontal quarto-sidebar-collapse-item sidebar-navigation floating overflow-auto">
<div class="pt-lg-2 mt-2 text-left sidebar-header">
<div class="sidebar-title mb-0 py-0">
<a href="../../">AI Design Patterns for GLAM</a>
</div>
</div>
<div class="mt-2 flex-shrink-0 align-items-center">
<div class="sidebar-search">
<div id="quarto-search" class="" title="Search"></div>
</div>
</div>
<div class="sidebar-menu-container">
<ul class="list-unstyled mt-1">
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="../../index.html" class="sidebar-item-text sidebar-link">
<span class="menu-text">Welcome</span></a>
</div>
</li>
<li class="sidebar-item sidebar-item-section">
<span class="sidebar-item-text sidebar-link text-start">
<span class="menu-text">Beyond Chat Interfaces to Collections?</span></span>
</li>
<li class="sidebar-item sidebar-item-section">
<div class="sidebar-item-container">
<a class="sidebar-item-text sidebar-link text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-2" role="navigation" aria-expanded="true">
<span class="menu-text">Design Patterns</span></a>
<a class="sidebar-item-toggle text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-2" role="navigation" aria-expanded="true" aria-label="Toggle section">
<i class="bi bi-chevron-right ms-2"></i>
</a>
</div>
<ul id="quarto-sidebar-section-2" class="collapse list-unstyled sidebar-section depth1 show">
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="../../patterns/what-is-an-ai-pattern.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">1</span>&nbsp; <span class="chapter-title">What is an AI Pattern?</span></span></a>
</div>
</li>
</ul>
</li>
<li class="sidebar-item sidebar-item-section">
<div class="sidebar-item-container">
<a class="sidebar-item-text sidebar-link text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-3" role="navigation" aria-expanded="true">
<span class="menu-text">Structured Information Extraction</span></a>
<a class="sidebar-item-toggle text-start" data-bs-toggle="collapse" data-bs-target="#quarto-sidebar-section-3" role="navigation" aria-expanded="true" aria-label="Toggle section">
<i class="bi bi-chevron-right ms-2"></i>
</a>
</div>
<ul id="quarto-sidebar-section-3" class="collapse list-unstyled sidebar-section depth1 show">
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="../../patterns/structured-generation/intro.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">2</span>&nbsp; <span class="chapter-title">Structured Document Processing</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="../../patterns/structured-generation/vlm-structured-generation.html" class="sidebar-item-text sidebar-link active">
<span class="menu-text"><span class="chapter-number">3</span>&nbsp; <span class="chapter-title">Structured Information Extraction with Vision Language Models</span></span></a>
</div>
</li>
</ul>
</li>
</ul>
</div>
</nav>
<div id="quarto-sidebar-glass" class="quarto-sidebar-collapse-item" data-bs-toggle="collapse" data-bs-target=".quarto-sidebar-collapse-item"></div>
<!-- margin-sidebar -->
<div id="quarto-margin-sidebar" class="sidebar margin-sidebar">
<nav id="TOC" role="doc-toc" class="toc-active">
<h2 id="toc-title">Table of contents</h2>
<ul>
<li><a href="#introduction" id="toc-introduction" class="nav-link active" data-scroll-target="#introduction"><span class="header-section-number">3.1</span> Introduction</a></li>
<li><a href="#the-sloane-index-cards-dataset" id="toc-the-sloane-index-cards-dataset" class="nav-link" data-scroll-target="#the-sloane-index-cards-dataset"><span class="header-section-number">3.2</span> The Sloane Index Cards Dataset</a></li>
<li><a href="#setup" id="toc-setup" class="nav-link" data-scroll-target="#setup"><span class="header-section-number">3.3</span> Setup</a>
<ul class="collapse">
<li><a href="#connecting-to-a-vision-language-model" id="toc-connecting-to-a-vision-language-model" class="nav-link" data-scroll-target="#connecting-to-a-vision-language-model"><span class="header-section-number">3.3.1</span> Connecting to a Vision Language Model</a></li>
</ul></li>
<li><a href="#basic-vlm-query" id="toc-basic-vlm-query" class="nav-link" data-scroll-target="#basic-vlm-query"><span class="header-section-number">3.4</span> Basic VLM Query</a></li>
<li><a href="#simple-vlm-query-example" id="toc-simple-vlm-query-example" class="nav-link" data-scroll-target="#simple-vlm-query-example"><span class="header-section-number">3.5</span> 102: Simple VLM Query Example</a></li>
<li><a href="#classification" id="toc-classification" class="nav-link" data-scroll-target="#classification"><span class="header-section-number">3.6</span> Classification</a>
<ul class="collapse">
<li><a href="#classifying-with-structured-labels" id="toc-classifying-with-structured-labels" class="nav-link" data-scroll-target="#classifying-with-structured-labels"><span class="header-section-number">3.6.1</span> Classifying with structured labels</a></li>
</ul></li>
<li><a href="#beyond-classifying---extracting-structured-information" id="toc-beyond-classifying---extracting-structured-information" class="nav-link" data-scroll-target="#beyond-classifying---extracting-structured-information"><span class="header-section-number">3.7</span> Beyond classifying - Extracting structured information</a></li>
<li><a href="#appendix-using-a-local-model" id="toc-appendix-using-a-local-model" class="nav-link" data-scroll-target="#appendix-using-a-local-model"><span class="header-section-number">3.8</span> Appendix: Using a Local Model</a></li>
</ul>
</nav>
</div>
<!-- main -->
<main class="content" id="quarto-document-content">
<header id="title-block-header" class="quarto-title-block default"><nav class="quarto-page-breadcrumbs quarto-title-breadcrumbs d-none d-lg-block" aria-label="breadcrumb"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="../../patterns/structured-generation/intro.html">Structured Information Extraction</a></li><li class="breadcrumb-item"><a href="../../patterns/structured-generation/vlm-structured-generation.html"><span class="chapter-number">3</span>&nbsp; <span class="chapter-title">Structured Information Extraction with Vision Language Models</span></a></li></ol></nav>
<div class="quarto-title">
<h1 class="title"><span class="chapter-number">3</span>&nbsp; <span class="chapter-title">Structured Information Extraction with Vision Language Models</span></h1>
</div>
<div class="quarto-title-meta">
</div>
</header>
<section id="introduction" class="level2" data-number="3.1">
<h2 data-number="3.1" class="anchored" data-anchor-id="introduction"><span class="header-section-number">3.1</span> Introduction</h2>
<p>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.</p>
<p>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 <a href="#appendix-using-a-local-model">appendix</a>).</p>
</section>
<section id="the-sloane-index-cards-dataset" class="level2" data-number="3.2">
<h2 data-number="3.2" class="anchored" data-anchor-id="the-sloane-index-cards-dataset"><span class="header-section-number">3.2</span> The Sloane Index Cards Dataset</h2>
<p>We’ll use the <a href="https://huggingface.co/datasets/biglam/sloane-index-cards">Sloane Index Cards Dataset</a> from Hugging Face for our examples. This is a publicly available dataset that is well suited to demonstrating structured information extraction with VLMs.</p>
<blockquote class="blockquote">
<p>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.</p>
</blockquote>
<p>The dataset is available in Parquet format on <a href="https://huggingface.co/datasets/biglam/biglam/sloane-catalogues">Hugging Face</a> so it can be easily loaded using the <code>datasets</code> library.</p>
<p>Let’s load the dataset and take a look at one row.</p>
<div id="7d5760cc" class="cell" data-cache="true" data-execution_count="1">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> datasets <span class="im">import</span> load_dataset</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a>ds <span class="op">=</span> load_dataset(<span class="st">"biglam/sloane-catalogues"</span>, split<span class="op">=</span><span class="st">"train"</span>)</span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a>ds[<span class="dv">0</span>]</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display" data-execution_count="1">
<pre><code>{'image': &lt;PIL.JpegImagePlugin.JpegImageFile image mode=L size=3144x2267&gt;,
'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'}</code></pre>
</div>
</div>
<p>We can see that we have a dictionary that contains an <code>image</code> as well as some additional metadata fields.</p>
<p>Let’s take a look at an actual example image from the dataset.</p>
<div id="902a544b" class="cell" data-cache="true" data-execution_count="2">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a>ds[<span class="dv">0</span>][<span class="st">"image"</span>]</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display" data-execution_count="2">
<div>
<figure class="figure">
<p><img src="vlm-structured-generation_files/figure-html/cell-3-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>Let’s look at a couple more examples to get a sense of the variety in the dataset.</p>
<div id="b1e3fc05" class="cell" data-execution_count="3">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a>ds[<span class="dv">2</span>][<span class="st">"image"</span>]</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display" data-execution_count="3">
<div>
<figure class="figure">
<p><img src="vlm-structured-generation_files/figure-html/cell-4-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>one more from later in the dataset</p>
<div id="b23fa754" class="cell" data-execution_count="4">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a>ds[<span class="dv">50</span>][<span class="st">"image"</span>]</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display" data-execution_count="4">
<div>
<figure class="figure">
<p><img src="vlm-structured-generation_files/figure-html/cell-5-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>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.</p>
<p>We’ll look at how we can use VLMs to work with kind of collection.</p>
</section>
<section id="setup" class="level2" data-number="3.3">
<h2 data-number="3.3" class="anchored" data-anchor-id="setup"><span class="header-section-number">3.3</span> Setup</h2>
<section id="connecting-to-a-vision-language-model" class="level3" data-number="3.3.1">
<h3 data-number="3.3.1" class="anchored" data-anchor-id="connecting-to-a-vision-language-model"><span class="header-section-number">3.3.1</span> Connecting to a Vision Language Model</h3>
<p>We’ll use <a href="https://huggingface.co/docs/api-inference/">Hugging Face Inference Providers</a> 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.</p>
<p>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 <a href="#appendix-using-a-local-model">appendix</a> at the end of this chapter for details.</p>
<div class="callout callout-style-default callout-tip callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
<span class="screen-reader-only">Tip</span>Getting a Hugging Face Token
</div>
</div>
<div class="callout-body-container callout-body">
<ol type="1">
<li>Create a free account at <a href="https://huggingface.co/join">huggingface.co</a></li>
<li>Go to <a href="https://huggingface.co/settings/tokens">Settings → Access Tokens</a></li>
<li>Create a new token with <strong>Read</strong> access</li>
<li>Set it as an environment variable: <code>export HF_TOKEN=hf_...</code> or add it to a <code>.env</code> file</li>
</ol>
</div>
</div>
<div id="4fc5f6da" class="cell" data-cache="true" data-execution_count="5">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><a href="#cb6-1" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> os</span>
<span id="cb6-2"><a href="#cb6-2" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> openai <span class="im">import</span> OpenAI</span>
<span id="cb6-3"><a href="#cb6-3" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> rich <span class="im">import</span> <span class="bu">print</span> <span class="im">as</span> rprint</span>
<span id="cb6-4"><a href="#cb6-4" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> dotenv <span class="im">import</span> load_dotenv</span>
<span id="cb6-5"><a href="#cb6-5" aria-hidden="true" tabindex="-1"></a>load_dotenv()</span>
<span id="cb6-6"><a href="#cb6-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb6-7"><a href="#cb6-7" aria-hidden="true" tabindex="-1"></a>client <span class="op">=</span> OpenAI(</span>
<span id="cb6-8"><a href="#cb6-8" aria-hidden="true" tabindex="-1"></a> base_url<span class="op">=</span><span class="st">"https://router.huggingface.co/v1"</span>,</span>
<span id="cb6-9"><a href="#cb6-9" aria-hidden="true" tabindex="-1"></a> api_key<span class="op">=</span>os.environ.get(<span class="st">"HF_TOKEN"</span>),</span>
<span id="cb6-10"><a href="#cb6-10" aria-hidden="true" tabindex="-1"></a>)</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
</div>
<p>We’ll use <code>Qwen/Qwen3-VL-8B-Instruct</code> throughout this chapter — an 8 billion parameter vision-language model that offers a good balance of quality and speed for document understanding tasks.</p>
</section>
</section>
<section id="basic-vlm-query" class="level2" data-number="3.4">
<h2 data-number="3.4" class="anchored" data-anchor-id="basic-vlm-query"><span class="header-section-number">3.4</span> Basic VLM Query</h2>
<p>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.</p>
<p>We’ll default to using the <code>Qwen/Qwen3-VL-8B-Instruct</code> model via HF Inference Providers. You could experiment with different models later on — the code works with any OpenAI-compatible VLM endpoint.</p>
<div id="36489552" class="cell" data-cache="true" data-execution_count="6">
<details class="code-fold">
<summary>Code</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><a href="#cb7-1" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> base64</span>
<span id="cb7-2"><a href="#cb7-2" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> PIL.Image <span class="im">import</span> Image <span class="im">as</span> PILImage</span>
<span id="cb7-3"><a href="#cb7-3" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> io <span class="im">import</span> BytesIO</span>
<span id="cb7-4"><a href="#cb7-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb7-5"><a href="#cb7-5" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> query_image(image: <span class="bu">str</span> <span class="op">|</span> PILImage, prompt: <span class="bu">str</span>, model: <span class="bu">str</span><span class="op">=</span><span class="st">'Qwen/Qwen3-VL-8B-Instruct'</span>, max_image_size: <span class="bu">int</span><span class="op">=</span><span class="dv">1024</span>, client<span class="op">=</span>client) <span class="op">-&gt;</span> <span class="bu">str</span>:</span>
<span id="cb7-6"><a href="#cb7-6" aria-hidden="true" tabindex="-1"></a> <span class="co">"""Query VLM with an image."""</span></span>
<span id="cb7-7"><a href="#cb7-7" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> <span class="bu">isinstance</span>(image, PILImage):</span>
<span id="cb7-8"><a href="#cb7-8" aria-hidden="true" tabindex="-1"></a> <span class="co"># Convert PIL Image to bytes and encode to base64</span></span>
<span id="cb7-9"><a href="#cb7-9" aria-hidden="true" tabindex="-1"></a> buffered <span class="op">=</span> BytesIO()</span>
<span id="cb7-10"><a href="#cb7-10" aria-hidden="true" tabindex="-1"></a> <span class="co"># ensure image is not too big</span></span>
<span id="cb7-11"><a href="#cb7-11" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> image.size <span class="op">&gt;</span> (max_image_size, max_image_size):</span>
<span id="cb7-12"><a href="#cb7-12" aria-hidden="true" tabindex="-1"></a> image.thumbnail((max_image_size, max_image_size)) </span>
<span id="cb7-13"><a href="#cb7-13" aria-hidden="true" tabindex="-1"></a> image.save(buffered, <span class="bu">format</span><span class="op">=</span><span class="st">"JPEG"</span>)</span>
<span id="cb7-14"><a href="#cb7-14" aria-hidden="true" tabindex="-1"></a> image_base64 <span class="op">=</span> base64.b64encode(buffered.getvalue()).decode(<span class="st">'utf-8'</span>)</span>
<span id="cb7-15"><a href="#cb7-15" aria-hidden="true" tabindex="-1"></a> <span class="cf">else</span>:</span>
<span id="cb7-16"><a href="#cb7-16" aria-hidden="true" tabindex="-1"></a> <span class="co"># Assume image is a file path</span></span>
<span id="cb7-17"><a href="#cb7-17" aria-hidden="true" tabindex="-1"></a> <span class="cf">with</span> <span class="bu">open</span>(image, <span class="st">"rb"</span>) <span class="im">as</span> f:</span>
<span id="cb7-18"><a href="#cb7-18" aria-hidden="true" tabindex="-1"></a> image_base64 <span class="op">=</span> base64.b64encode(f.read()).decode(<span class="st">'utf-8'</span>)</span>
<span id="cb7-19"><a href="#cb7-19" aria-hidden="true" tabindex="-1"></a> <span class="co">#</span></span>
<span id="cb7-20"><a href="#cb7-20" aria-hidden="true" tabindex="-1"></a> <span class="co"># Query</span></span>
<span id="cb7-21"><a href="#cb7-21" aria-hidden="true" tabindex="-1"></a> response <span class="op">=</span> client.chat.completions.create(</span>
<span id="cb7-22"><a href="#cb7-22" aria-hidden="true" tabindex="-1"></a> model<span class="op">=</span>model,</span>
<span id="cb7-23"><a href="#cb7-23" aria-hidden="true" tabindex="-1"></a> messages<span class="op">=</span>[{</span>
<span id="cb7-24"><a href="#cb7-24" aria-hidden="true" tabindex="-1"></a> <span class="st">"role"</span>: <span class="st">"user"</span>,</span>
<span id="cb7-25"><a href="#cb7-25" aria-hidden="true" tabindex="-1"></a> <span class="st">"content"</span>: [</span>
<span id="cb7-26"><a href="#cb7-26" aria-hidden="true" tabindex="-1"></a> {<span class="st">"type"</span>: <span class="st">"text"</span>, <span class="st">"text"</span>: prompt},</span>
<span id="cb7-27"><a href="#cb7-27" aria-hidden="true" tabindex="-1"></a> {<span class="st">"type"</span>: <span class="st">"image_url"</span>, <span class="st">"image_url"</span>: {<span class="st">"url"</span>: <span class="ss">f"data:image/jpeg;base64,</span><span class="sc">{</span>image_base64<span class="sc">}</span><span class="ss">"</span>}}</span>
<span id="cb7-28"><a href="#cb7-28" aria-hidden="true" tabindex="-1"></a> ]</span>
<span id="cb7-29"><a href="#cb7-29" aria-hidden="true" tabindex="-1"></a> }]</span>
<span id="cb7-30"><a href="#cb7-30" aria-hidden="true" tabindex="-1"></a> )</span>
<span id="cb7-31"><a href="#cb7-31" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> response.choices[<span class="dv">0</span>].message.content</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
</details>
</div>
</section>
<section id="simple-vlm-query-example" class="level2" data-number="3.5">
<h2 data-number="3.5" class="anchored" data-anchor-id="simple-vlm-query-example"><span class="header-section-number">3.5</span> 102: Simple VLM Query Example</h2>
<p>To get started let’s do a simple query to describe an image from the dataset.</p>
<div id="9b70b918" class="cell" data-cache="true" data-execution_count="7">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a>image <span class="op">=</span> ds[<span class="dv">0</span>][<span class="st">"image"</span>]</span>
<span id="cb8-2"><a href="#cb8-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb8-3"><a href="#cb8-3" aria-hidden="true" tabindex="-1"></a><span class="co"># Query the VLM to describe the image</span></span>
<span id="cb8-4"><a href="#cb8-4" aria-hidden="true" tabindex="-1"></a>description <span class="op">=</span> query_image(image, <span class="st">"Describe this image."</span>, model<span class="op">=</span><span class="st">'Qwen/Qwen3-VL-8B-Instruct'</span>)</span>
<span id="cb8-5"><a href="#cb8-5" aria-hidden="true" tabindex="-1"></a>rprint(description)</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display">
<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace">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 <span style="color: #008080; text-decoration-color: #008080; font-weight: bold">3972.</span>C. <span style="font-weight: bold">(</span>Vol. <span style="color: #008080; text-decoration-color: #008080; font-weight: bold">1</span><span style="font-weight: bold">)</span>
* **Order Number:** SCH NO <span style="color: #008080; text-decoration-color: #008080; font-weight: bold">98876</span>
* **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 <span style="color: #008080; text-decoration-color: #008080; font-weight: bold">12</span>, meaning the reproduction will be scaled down to
<span style="color: #008080; text-decoration-color: #008080; font-weight: bold">1</span>/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 <span style="color: #008080; text-decoration-color: #008080; font-weight: bold">1</span> of the <span style="color: #008000; text-decoration-color: #008000">"Catalogue of Sir Hans Sloane's </span>
<span style="color: #008000; text-decoration-color: #008000">Library,"</span> which is held in the Manuscripts department under the shelfmark SLOANE <span style="color: #008080; text-decoration-color: #008080; font-weight: bold">3972.</span>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.
</pre>
</div>
</div>
<p>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.</p>
<div id="47752997" class="cell" data-execution_count="8">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a>image</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display" data-execution_count="8">
<div>
<figure class="figure">
<p><img src="vlm-structured-generation_files/figure-html/cell-9-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>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.</p>
</section>
<section id="classification" class="level2" data-number="3.6">
<h2 data-number="3.6" class="anchored" data-anchor-id="classification"><span class="header-section-number">3.6</span> Classification</h2>
<!-- TODO maybe we have a "chapter" or "section" with tasks which we can then embedded across other parts of the book? -->
<p>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.</p>
<div id="588f0dd9" class="cell" data-cache="true" data-execution_count="9">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a><span class="im">import</span> time</span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> tqdm.auto <span class="im">import</span> tqdm</span>
<span id="cb10-3"><a href="#cb10-3" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> rich <span class="im">import</span> <span class="bu">print</span> <span class="im">as</span> rprint</span>
<span id="cb10-4"><a href="#cb10-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-5"><a href="#cb10-5" aria-hidden="true" tabindex="-1"></a>sample_size <span class="op">=</span> <span class="dv">10</span></span>
<span id="cb10-6"><a href="#cb10-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-7"><a href="#cb10-7" aria-hidden="true" tabindex="-1"></a>sample <span class="op">=</span> ds.take(sample_size)</span>
<span id="cb10-8"><a href="#cb10-8" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-9"><a href="#cb10-9" aria-hidden="true" tabindex="-1"></a>prompt <span class="op">=</span> <span class="st">"""Classify this image into one of the following categories:</span></span>
<span id="cb10-10"><a href="#cb10-10" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-11"><a href="#cb10-11" aria-hidden="true" tabindex="-1"></a><span class="st">1. **Index/Reference Card**: A library catalog or reference card</span></span>
<span id="cb10-12"><a href="#cb10-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-13"><a href="#cb10-13" aria-hidden="true" tabindex="-1"></a><span class="st">2. **Manuscript Page**: A handwritten or historical document page</span></span>
<span id="cb10-14"><a href="#cb10-14" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-15"><a href="#cb10-15" aria-hidden="true" tabindex="-1"></a><span class="st">3. **Other**: Any document that doesn't fit the above categories</span></span>
<span id="cb10-16"><a href="#cb10-16" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-17"><a href="#cb10-17" aria-hidden="true" tabindex="-1"></a><span class="st">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).</span></span>
<span id="cb10-18"><a href="#cb10-18" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-19"><a href="#cb10-19" aria-hidden="true" tabindex="-1"></a><span class="st">Return only the category name: "Index/Reference Card", "Manuscript Page", or "Other"</span></span>
<span id="cb10-20"><a href="#cb10-20" aria-hidden="true" tabindex="-1"></a><span class="st">"""</span></span>
<span id="cb10-21"><a href="#cb10-21" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb10-22"><a href="#cb10-22" aria-hidden="true" tabindex="-1"></a>results <span class="op">=</span> []</span>
<span id="cb10-23"><a href="#cb10-23" aria-hidden="true" tabindex="-1"></a><span class="co"># Time the execution using standard Python</span></span>
<span id="cb10-24"><a href="#cb10-24" aria-hidden="true" tabindex="-1"></a>start_time <span class="op">=</span> time.time()</span>
<span id="cb10-25"><a href="#cb10-25" aria-hidden="true" tabindex="-1"></a><span class="cf">for</span> row <span class="kw">in</span> tqdm(sample):</span>
<span id="cb10-26"><a href="#cb10-26" aria-hidden="true" tabindex="-1"></a> image <span class="op">=</span> row[<span class="st">'image'</span>]</span>
<span id="cb10-27"><a href="#cb10-27" aria-hidden="true" tabindex="-1"></a> results.append(query_image(image, prompt, model<span class="op">=</span><span class="st">'Qwen/Qwen3-VL-8B-Instruct'</span>))</span>
<span id="cb10-28"><a href="#cb10-28" aria-hidden="true" tabindex="-1"></a>elapsed_time <span class="op">=</span> time.time() <span class="op">-</span> start_time</span>
<span id="cb10-29"><a href="#cb10-29" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="ss">f"Execution time: </span><span class="sc">{</span>elapsed_time<span class="sc">:.2f}</span><span class="ss"> seconds"</span>)</span>
<span id="cb10-30"><a href="#cb10-30" aria-hidden="true" tabindex="-1"></a>rprint(results)</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display">
<script type="application/vnd.jupyter.widget-view+json">
{"model_id":"7c6477b5384d4da3837c3ae504d452ba","version_major":2,"version_minor":0,"quarto_mimetype":"application/vnd.jupyter.widget-view+json"}
</script>
</div>
<div class="cell-output cell-output-stdout">
<pre><code>Execution time: 18.31 seconds</code></pre>
</div>
<div class="cell-output cell-output-display">
<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="font-weight: bold">[</span>
<span style="color: #008000; text-decoration-color: #008000">'Index/Reference Card'</span>,
<span style="color: #008000; text-decoration-color: #008000">'Other'</span>,
<span style="color: #008000; text-decoration-color: #008000">'Manuscript Page'</span>,
<span style="color: #008000; text-decoration-color: #008000">'Manuscript Page'</span>,
<span style="color: #008000; text-decoration-color: #008000">'Manuscript Page'</span>,
<span style="color: #008000; text-decoration-color: #008000">'Manuscript Page'</span>,
<span style="color: #008000; text-decoration-color: #008000">'Manuscript Page'</span>,
<span style="color: #008000; text-decoration-color: #008000">'Manuscript Page'</span>,
<span style="color: #008000; text-decoration-color: #008000">'Manuscript Page'</span>,
<span style="color: #008000; text-decoration-color: #008000">'Manuscript Page'</span>
<span style="font-weight: bold">]</span>
</pre>
</div>
</div>
<p>Let’s check the result that was predicted as “index/reference card”</p>
<div id="25e8df82" class="cell" data-execution_count="10">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a>sample[<span class="dv">0</span>][<span class="st">'image'</span>]</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display" data-execution_count="10">
<div>
<figure class="figure">
<p><img src="vlm-structured-generation_files/figure-html/cell-11-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>We can extrapolate how long this would take for the full dataset</p>
<div id="c4891945" class="cell" data-cache="true" data-execution_count="11">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a><span class="co"># Calculate average time per image</span></span>
<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a>avg_time_per_image <span class="op">=</span> elapsed_time <span class="op">/</span> sample_size</span>
<span id="cb13-3"><a href="#cb13-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb13-4"><a href="#cb13-4" aria-hidden="true" tabindex="-1"></a><span class="co"># Project time for full dataset</span></span>
<span id="cb13-5"><a href="#cb13-5" aria-hidden="true" tabindex="-1"></a>total_images <span class="op">=</span> <span class="bu">len</span>(ds)</span>
<span id="cb13-6"><a href="#cb13-6" aria-hidden="true" tabindex="-1"></a>projected_time <span class="op">=</span> avg_time_per_image <span class="op">*</span> total_images</span>
<span id="cb13-7"><a href="#cb13-7" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb13-8"><a href="#cb13-8" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="ss">f"Sample processing time: </span><span class="sc">{</span>elapsed_time<span class="sc">:.2f}</span><span class="ss"> seconds (</span><span class="sc">{</span>elapsed_time<span class="op">/</span><span class="dv">60</span><span class="sc">:.2f}</span><span class="ss"> minutes)"</span>)</span>
<span id="cb13-9"><a href="#cb13-9" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="ss">f"Average time per image: </span><span class="sc">{</span>avg_time_per_image<span class="sc">:.2f}</span><span class="ss"> seconds"</span>)</span>
<span id="cb13-10"><a href="#cb13-10" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="ss">f"Total images in dataset: </span><span class="sc">{</span>total_images<span class="sc">}</span><span class="ss">"</span>)</span>
<span id="cb13-11"><a href="#cb13-11" aria-hidden="true" tabindex="-1"></a><span class="bu">print</span>(<span class="ss">f"Projected time for full dataset: </span><span class="sc">{</span>projected_time<span class="op">/</span><span class="dv">60</span><span class="sc">:.2f}</span><span class="ss"> minutes (</span><span class="sc">{</span>projected_time<span class="op">/</span><span class="dv">3600</span><span class="sc">:.2f}</span><span class="ss"> hours)"</span>)</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-stdout">
<pre><code>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)</code></pre>
</div>
</div>
<section id="classifying-with-structured-labels" class="level3" data-number="3.6.1">
<h3 data-number="3.6.1" class="anchored" data-anchor-id="classifying-with-structured-labels"><span class="header-section-number">3.6.1</span> Classifying with structured labels</h3>
<p>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.</p>
<p>In this example, we’ll define a Pydantic model for our classification task. The model will have a single field <code>category</code> which can take one of three literal values <code>"Index/Reference Card"</code>, <code>"Manuscript Page"</code>, or <code>"other"</code>.</p>
<p>What this means in practice is that the model will only be able to return one of these three values for the <code>category</code> field.</p>
<div id="907e5dd9" class="cell" data-execution_count="12">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> pydantic <span class="im">import</span> BaseModel, Field</span>
<span id="cb15-2"><a href="#cb15-2" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> typing <span class="im">import</span> Literal</span>
<span id="cb15-3"><a href="#cb15-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb15-4"><a href="#cb15-4" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> PageCategory(BaseModel):</span>
<span id="cb15-5"><a href="#cb15-5" aria-hidden="true" tabindex="-1"></a> category: Literal[<span class="st">"Index/Reference Card"</span>, <span class="st">"Manuscript Page"</span>, <span class="st">"other"</span>] <span class="op">=</span> Field(</span>
<span id="cb15-6"><a href="#cb15-6" aria-hidden="true" tabindex="-1"></a> ..., description<span class="op">=</span><span class="st">"The category of the image"</span></span>
<span id="cb15-7"><a href="#cb15-7" aria-hidden="true" tabindex="-1"></a> )</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
</div>
<p>When using the OpenAI client we can specify this Pydantic model as the <code>response_format</code> 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).</p>
<div id="166e0d6b" class="cell" data-execution_count="13">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb16-1"><a href="#cb16-1" aria-hidden="true" tabindex="-1"></a>buffered <span class="op">=</span> BytesIO()</span>
<span id="cb16-2"><a href="#cb16-2" aria-hidden="true" tabindex="-1"></a>image.save(buffered, <span class="bu">format</span><span class="op">=</span><span class="st">"JPEG"</span>)</span>
<span id="cb16-3"><a href="#cb16-3" aria-hidden="true" tabindex="-1"></a>image_base64 <span class="op">=</span> base64.b64encode(buffered.getvalue()).decode(<span class="st">'utf-8'</span>)</span>
<span id="cb16-4"><a href="#cb16-4" aria-hidden="true" tabindex="-1"></a>completion <span class="op">=</span> client.beta.chat.completions.parse(</span>
<span id="cb16-5"><a href="#cb16-5" aria-hidden="true" tabindex="-1"></a> model<span class="op">=</span><span class="st">"Qwen/Qwen3-VL-8B-Instruct"</span>,</span>
<span id="cb16-6"><a href="#cb16-6" aria-hidden="true" tabindex="-1"></a> messages<span class="op">=</span>[</span>
<span id="cb16-7"><a href="#cb16-7" aria-hidden="true" tabindex="-1"></a> {</span>
<span id="cb16-8"><a href="#cb16-8" aria-hidden="true" tabindex="-1"></a> <span class="st">"role"</span>: <span class="st">"user"</span>,</span>
<span id="cb16-9"><a href="#cb16-9" aria-hidden="true" tabindex="-1"></a> <span class="st">"content"</span>: [</span>
<span id="cb16-10"><a href="#cb16-10" aria-hidden="true" tabindex="-1"></a> {</span>
<span id="cb16-11"><a href="#cb16-11" aria-hidden="true" tabindex="-1"></a> <span class="st">"type"</span>: <span class="st">"text"</span>,</span>
<span id="cb16-12"><a href="#cb16-12" aria-hidden="true" tabindex="-1"></a> <span class="st">"text"</span>: prompt,</span>
<span id="cb16-13"><a href="#cb16-13" aria-hidden="true" tabindex="-1"></a> },</span>
<span id="cb16-14"><a href="#cb16-14" aria-hidden="true" tabindex="-1"></a> {</span>
<span id="cb16-15"><a href="#cb16-15" aria-hidden="true" tabindex="-1"></a> <span class="st">"type"</span>: <span class="st">"image_url"</span>,</span>
<span id="cb16-16"><a href="#cb16-16" aria-hidden="true" tabindex="-1"></a> <span class="st">"image_url"</span>: {<span class="st">"url"</span>: <span class="ss">f"data:image/jpeg;base64,</span><span class="sc">{</span>image_base64<span class="sc">}</span><span class="ss">"</span>},</span>
<span id="cb16-17"><a href="#cb16-17" aria-hidden="true" tabindex="-1"></a> },</span>
<span id="cb16-18"><a href="#cb16-18" aria-hidden="true" tabindex="-1"></a> ],</span>
<span id="cb16-19"><a href="#cb16-19" aria-hidden="true" tabindex="-1"></a> },</span>
<span id="cb16-20"><a href="#cb16-20" aria-hidden="true" tabindex="-1"></a> ],</span>
<span id="cb16-21"><a href="#cb16-21" aria-hidden="true" tabindex="-1"></a> max_tokens<span class="op">=</span><span class="dv">200</span>,</span>
<span id="cb16-22"><a href="#cb16-22" aria-hidden="true" tabindex="-1"></a> temperature<span class="op">=</span><span class="fl">0.7</span>,</span>
<span id="cb16-23"><a href="#cb16-23" aria-hidden="true" tabindex="-1"></a> response_format<span class="op">=</span>PageCategory,</span>
<span id="cb16-24"><a href="#cb16-24" aria-hidden="true" tabindex="-1"></a>)</span>
<span id="cb16-25"><a href="#cb16-25" aria-hidden="true" tabindex="-1"></a>rprint(completion)</span>
<span id="cb16-26"><a href="#cb16-26" aria-hidden="true" tabindex="-1"></a>rprint(completion.choices[<span class="dv">0</span>].message.parsed)</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display">
<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace">ParsedChatCompletion<span style="font-weight: bold">[</span>PageCategory<span style="font-weight: bold">](</span>
<span style="color: #808000; text-decoration-color: #808000">id</span>=<span style="color: #008000; text-decoration-color: #008000">'47c1a911111046291f6bbec65ebb1ead'</span>,
<span style="color: #808000; text-decoration-color: #808000">choices</span>=<span style="font-weight: bold">[</span>
ParsedChoice<span style="font-weight: bold">[</span>PageCategory<span style="font-weight: bold">](</span>
<span style="color: #808000; text-decoration-color: #808000">finish_reason</span>=<span style="color: #008000; text-decoration-color: #008000">'stop'</span>,
<span style="color: #808000; text-decoration-color: #808000">index</span>=<span style="color: #008080; text-decoration-color: #008080; font-weight: bold">0</span>,
<span style="color: #808000; text-decoration-color: #808000">logprobs</span>=<span style="color: #800080; text-decoration-color: #800080; font-style: italic">None</span>,
<span style="color: #808000; text-decoration-color: #808000">message</span>=<span style="color: #800080; text-decoration-color: #800080">ParsedChatCompletionMessage</span><span style="font-weight: bold">[</span>PageCategory<span style="font-weight: bold">](</span>
<span style="color: #808000; text-decoration-color: #808000">content</span>=<span style="color: #008000; text-decoration-color: #008000">'{\n "category": "Manuscript Page"\n}'</span>,
<span style="color: #808000; text-decoration-color: #808000">refusal</span>=<span style="color: #800080; text-decoration-color: #800080; font-style: italic">None</span>,
<span style="color: #808000; text-decoration-color: #808000">role</span>=<span style="color: #008000; text-decoration-color: #008000">'assistant'</span>,
<span style="color: #808000; text-decoration-color: #808000">annotations</span>=<span style="color: #800080; text-decoration-color: #800080; font-style: italic">None</span>,
<span style="color: #808000; text-decoration-color: #808000">audio</span>=<span style="color: #800080; text-decoration-color: #800080; font-style: italic">None</span>,
<span style="color: #808000; text-decoration-color: #808000">function_call</span>=<span style="color: #800080; text-decoration-color: #800080; font-style: italic">None</span>,
<span style="color: #808000; text-decoration-color: #808000">tool_calls</span>=<span style="color: #800080; text-decoration-color: #800080; font-style: italic">None</span>,
<span style="color: #808000; text-decoration-color: #808000">parsed</span>=<span style="color: #800080; text-decoration-color: #800080; font-weight: bold">PageCategory</span><span style="font-weight: bold">(</span><span style="color: #808000; text-decoration-color: #808000">category</span>=<span style="color: #008000; text-decoration-color: #008000">'Manuscript Page'</span><span style="font-weight: bold">)</span>
<span style="font-weight: bold">)</span>
<span style="font-weight: bold">)</span>
<span style="font-weight: bold">]</span>,
<span style="color: #808000; text-decoration-color: #808000">created</span>=<span style="color: #008080; text-decoration-color: #008080; font-weight: bold">1771255803</span>,
<span style="color: #808000; text-decoration-color: #808000">model</span>=<span style="color: #008000; text-decoration-color: #008000">'qwen/qwen3-vl-8b-instruct'</span>,
<span style="color: #808000; text-decoration-color: #808000">object</span>=<span style="color: #008000; text-decoration-color: #008000">'chat.completion'</span>,
<span style="color: #808000; text-decoration-color: #808000">service_tier</span>=<span style="color: #800080; text-decoration-color: #800080; font-style: italic">None</span>,
<span style="color: #808000; text-decoration-color: #808000">system_fingerprint</span>=<span style="color: #008000; text-decoration-color: #008000">''</span>,
<span style="color: #808000; text-decoration-color: #808000">usage</span>=<span style="color: #800080; text-decoration-color: #800080; font-weight: bold">CompletionUsage</span><span style="font-weight: bold">(</span>
<span style="color: #808000; text-decoration-color: #808000">completion_tokens</span>=<span style="color: #008080; text-decoration-color: #008080; font-weight: bold">13</span>,
<span style="color: #808000; text-decoration-color: #808000">prompt_tokens</span>=<span style="color: #008080; text-decoration-color: #008080; font-weight: bold">966</span>,
<span style="color: #808000; text-decoration-color: #808000">total_tokens</span>=<span style="color: #008080; text-decoration-color: #008080; font-weight: bold">979</span>,
<span style="color: #808000; text-decoration-color: #808000">completion_tokens_details</span>=<span style="color: #800080; text-decoration-color: #800080; font-weight: bold">CompletionTokensDetails</span><span style="font-weight: bold">(</span>
<span style="color: #808000; text-decoration-color: #808000">accepted_prediction_tokens</span>=<span style="color: #008080; text-decoration-color: #008080; font-weight: bold">0</span>,
<span style="color: #808000; text-decoration-color: #808000">audio_tokens</span>=<span style="color: #008080; text-decoration-color: #008080; font-weight: bold">0</span>,
<span style="color: #808000; text-decoration-color: #808000">reasoning_tokens</span>=<span style="color: #008080; text-decoration-color: #008080; font-weight: bold">0</span>,
<span style="color: #808000; text-decoration-color: #808000">rejected_prediction_tokens</span>=<span style="color: #008080; text-decoration-color: #008080; font-weight: bold">0</span>,
<span style="color: #808000; text-decoration-color: #808000">text_tokens</span>=<span style="color: #008080; text-decoration-color: #008080; font-weight: bold">13</span>,
<span style="color: #808000; text-decoration-color: #808000">image_tokens</span>=<span style="color: #008080; text-decoration-color: #008080; font-weight: bold">0</span>,
<span style="color: #808000; text-decoration-color: #808000">video_tokens</span>=<span style="color: #008080; text-decoration-color: #008080; font-weight: bold">0</span>
<span style="font-weight: bold">)</span>,
<span style="color: #808000; text-decoration-color: #808000">prompt_tokens_details</span>=<span style="color: #800080; text-decoration-color: #800080; font-weight: bold">PromptTokensDetails</span><span style="font-weight: bold">(</span>
<span style="color: #808000; text-decoration-color: #808000">audio_tokens</span>=<span style="color: #008080; text-decoration-color: #008080; font-weight: bold">0</span>,
<span style="color: #808000; text-decoration-color: #808000">cached_tokens</span>=<span style="color: #008080; text-decoration-color: #008080; font-weight: bold">0</span>,
<span style="color: #808000; text-decoration-color: #808000">cache_creation_input_tokens</span>=<span style="color: #008080; text-decoration-color: #008080; font-weight: bold">0</span>,
<span style="color: #808000; text-decoration-color: #808000">cache_read_input_tokens</span>=<span style="color: #008080; text-decoration-color: #008080; font-weight: bold">0</span>,
<span style="color: #808000; text-decoration-color: #808000">text_tokens</span>=<span style="color: #008080; text-decoration-color: #008080; font-weight: bold">228</span>,
<span style="color: #808000; text-decoration-color: #808000">image_tokens</span>=<span style="color: #008080; text-decoration-color: #008080; font-weight: bold">738</span>,
<span style="color: #808000; text-decoration-color: #808000">video_tokens</span>=<span style="color: #008080; text-decoration-color: #008080; font-weight: bold">0</span>
<span style="font-weight: bold">)</span>
<span style="font-weight: bold">)</span>
<span style="font-weight: bold">)</span>
</pre>
</div>
<div class="cell-output cell-output-display">
<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #800080; text-decoration-color: #800080; font-weight: bold">PageCategory</span><span style="font-weight: bold">(</span><span style="color: #808000; text-decoration-color: #808000">category</span>=<span style="color: #008000; text-decoration-color: #008000">'Manuscript Page'</span><span style="font-weight: bold">)</span>
</pre>
</div>
</div>
<div id="16d63ec2" class="cell" data-execution_count="14">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb17"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb17-1"><a href="#cb17-1" aria-hidden="true" tabindex="-1"></a>image</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display" data-execution_count="14">
<div>
<figure class="figure">
<p><img src="vlm-structured-generation_files/figure-html/cell-15-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
</section>
</section>
<section id="beyond-classifying---extracting-structured-information" class="level2" data-number="3.7">
<h2 data-number="3.7" class="anchored" data-anchor-id="beyond-classifying---extracting-structured-information"><span class="header-section-number">3.7</span> Beyond classifying - Extracting structured information</h2>
<p>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.</p>
<div id="bba089db" class="cell" data-cache="true" data-execution_count="15">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb18"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a>index_image <span class="op">=</span> ds[<span class="dv">0</span>][<span class="st">'image'</span>]</span>
<span id="cb18-2"><a href="#cb18-2" aria-hidden="true" tabindex="-1"></a>index_image</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display" data-execution_count="15">
<div>
<figure class="figure">
<p><img src="vlm-structured-generation_files/figure-html/cell-16-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
<p>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.</p>
<div id="93efb7a1" class="cell" data-execution_count="16">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb19"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> pydantic <span class="im">import</span> BaseModel, Field</span>
<span id="cb19-2"><a href="#cb19-2" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> typing <span class="im">import</span> Optional</span>
<span id="cb19-3"><a href="#cb19-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb19-4"><a href="#cb19-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb19-5"><a href="#cb19-5" aria-hidden="true" tabindex="-1"></a><span class="kw">class</span> BritishLibraryReprographicCard(BaseModel):</span>
<span id="cb19-6"><a href="#cb19-6" aria-hidden="true" tabindex="-1"></a> <span class="co">"""</span></span>
<span id="cb19-7"><a href="#cb19-7" aria-hidden="true" tabindex="-1"></a><span class="co"> Pydantic model for extracting information from British Library Reference Division </span></span>
<span id="cb19-8"><a href="#cb19-8" aria-hidden="true" tabindex="-1"></a><span class="co"> reprographic cards used to document manuscripts and other materials.</span></span>
<span id="cb19-9"><a href="#cb19-9" aria-hidden="true" tabindex="-1"></a><span class="co"> """</span></span>
<span id="cb19-10"><a href="#cb19-10" aria-hidden="true" tabindex="-1"></a> </span>
<span id="cb19-11"><a href="#cb19-11" aria-hidden="true" tabindex="-1"></a> department: <span class="bu">str</span> <span class="op">=</span> Field(</span>
<span id="cb19-12"><a href="#cb19-12" aria-hidden="true" tabindex="-1"></a> ..., </span>
<span id="cb19-13"><a href="#cb19-13" aria-hidden="true" tabindex="-1"></a> description<span class="op">=</span><span class="st">"The division that holds the material (e.g., 'MANUSCRIPTS')"</span></span>
<span id="cb19-14"><a href="#cb19-14" aria-hidden="true" tabindex="-1"></a> )</span>
<span id="cb19-15"><a href="#cb19-15" aria-hidden="true" tabindex="-1"></a> </span>
<span id="cb19-16"><a href="#cb19-16" aria-hidden="true" tabindex="-1"></a> shelfmark: <span class="bu">str</span> <span class="op">=</span> Field(</span>
<span id="cb19-17"><a href="#cb19-17" aria-hidden="true" tabindex="-1"></a> ..., </span>
<span id="cb19-18"><a href="#cb19-18" aria-hidden="true" tabindex="-1"></a> description<span class="op">=</span><span class="st">"The library's classification/location code (e.g., 'SLOANE 3972.C. (VOL 1)')"</span></span>
<span id="cb19-19"><a href="#cb19-19" aria-hidden="true" tabindex="-1"></a> )</span>
<span id="cb19-20"><a href="#cb19-20" aria-hidden="true" tabindex="-1"></a> </span>
<span id="cb19-21"><a href="#cb19-21" aria-hidden="true" tabindex="-1"></a> order: <span class="bu">str</span> <span class="op">=</span> Field(</span>
<span id="cb19-22"><a href="#cb19-22" aria-hidden="true" tabindex="-1"></a> ..., </span>
<span id="cb19-23"><a href="#cb19-23" aria-hidden="true" tabindex="-1"></a> description<span class="op">=</span><span class="st">"Order reference, typically starting with 'SCH NO' followed by numbers"</span></span>
<span id="cb19-24"><a href="#cb19-24" aria-hidden="true" tabindex="-1"></a> )</span>
<span id="cb19-25"><a href="#cb19-25" aria-hidden="true" tabindex="-1"></a> </span>
<span id="cb19-26"><a href="#cb19-26" aria-hidden="true" tabindex="-1"></a> author: Optional[<span class="bu">str</span>] <span class="op">=</span> Field(</span>
<span id="cb19-27"><a href="#cb19-27" aria-hidden="true" tabindex="-1"></a> <span class="va">None</span>, </span>
<span id="cb19-28"><a href="#cb19-28" aria-hidden="true" tabindex="-1"></a> description<span class="op">=</span><span class="st">"Author name if present, null if blank or marked with diagonal line"</span></span>
<span id="cb19-29"><a href="#cb19-29" aria-hidden="true" tabindex="-1"></a> )</span>
<span id="cb19-30"><a href="#cb19-30" aria-hidden="true" tabindex="-1"></a> </span>
<span id="cb19-31"><a href="#cb19-31" aria-hidden="true" tabindex="-1"></a> title: <span class="bu">str</span> <span class="op">=</span> Field(</span>
<span id="cb19-32"><a href="#cb19-32" aria-hidden="true" tabindex="-1"></a> ..., </span>
<span id="cb19-33"><a href="#cb19-33" aria-hidden="true" tabindex="-1"></a> description<span class="op">=</span><span class="st">"The name of the work or manuscript"</span></span>
<span id="cb19-34"><a href="#cb19-34" aria-hidden="true" tabindex="-1"></a> )</span>
<span id="cb19-35"><a href="#cb19-35" aria-hidden="true" tabindex="-1"></a> </span>
<span id="cb19-36"><a href="#cb19-36" aria-hidden="true" tabindex="-1"></a> place_and_date_of_publication: Optional[<span class="bu">str</span>] <span class="op">=</span> Field(</span>
<span id="cb19-37"><a href="#cb19-37" aria-hidden="true" tabindex="-1"></a> <span class="va">None</span>, </span>
<span id="cb19-38"><a href="#cb19-38" aria-hidden="true" tabindex="-1"></a> description<span class="op">=</span><span class="st">"Place and date of publication if present, null if blank"</span></span>
<span id="cb19-39"><a href="#cb19-39" aria-hidden="true" tabindex="-1"></a> )</span>
<span id="cb19-40"><a href="#cb19-40" aria-hidden="true" tabindex="-1"></a> </span>
<span id="cb19-41"><a href="#cb19-41" aria-hidden="true" tabindex="-1"></a> reduction: <span class="bu">int</span> <span class="op">=</span> Field(</span>
<span id="cb19-42"><a href="#cb19-42" aria-hidden="true" tabindex="-1"></a> ..., </span>
<span id="cb19-43"><a href="#cb19-43" aria-hidden="true" tabindex="-1"></a> description<span class="op">=</span><span class="st">"The reduction number shown at the bottom of the card"</span></span>
<span id="cb19-44"><a href="#cb19-44" aria-hidden="true" tabindex="-1"></a> )</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
</div>
<p>We’ll now create a function to handle the querying process using this structured schema.</p>
<div id="617aedff" class="cell" data-execution_count="17">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb20"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> query_image_structured(image, prompt, schema, model<span class="op">=</span><span class="st">'Qwen/Qwen3-VL-8B-Instruct'</span>):</span>
<span id="cb20-2"><a href="#cb20-2" aria-hidden="true" tabindex="-1"></a> <span class="co">"""</span></span>
<span id="cb20-3"><a href="#cb20-3" aria-hidden="true" tabindex="-1"></a><span class="co"> Query VLM with an image and get structured output based on a Pydantic schema.</span></span>
<span id="cb20-4"><a href="#cb20-4" aria-hidden="true" tabindex="-1"></a><span class="co"> </span></span>
<span id="cb20-5"><a href="#cb20-5" aria-hidden="true" tabindex="-1"></a><span class="co"> Args:</span></span>
<span id="cb20-6"><a href="#cb20-6" aria-hidden="true" tabindex="-1"></a><span class="co"> image: PIL Image or file path to the image</span></span>
<span id="cb20-7"><a href="#cb20-7" aria-hidden="true" tabindex="-1"></a><span class="co"> prompt: Text prompt describing what to extract</span></span>
<span id="cb20-8"><a href="#cb20-8" aria-hidden="true" tabindex="-1"></a><span class="co"> schema: Pydantic model class defining the expected output structure</span></span>
<span id="cb20-9"><a href="#cb20-9" aria-hidden="true" tabindex="-1"></a><span class="co"> model: Model ID to use for the query</span></span>
<span id="cb20-10"><a href="#cb20-10" aria-hidden="true" tabindex="-1"></a><span class="co"> </span></span>
<span id="cb20-11"><a href="#cb20-11" aria-hidden="true" tabindex="-1"></a><span class="co"> Returns:</span></span>
<span id="cb20-12"><a href="#cb20-12" aria-hidden="true" tabindex="-1"></a><span class="co"> Parsed Pydantic model instance with the extracted data</span></span>
<span id="cb20-13"><a href="#cb20-13" aria-hidden="true" tabindex="-1"></a><span class="co"> """</span></span>
<span id="cb20-14"><a href="#cb20-14" aria-hidden="true" tabindex="-1"></a> <span class="co"># Convert image to base64</span></span>
<span id="cb20-15"><a href="#cb20-15" aria-hidden="true" tabindex="-1"></a> <span class="cf">if</span> <span class="bu">isinstance</span>(image, PILImage):</span>
<span id="cb20-16"><a href="#cb20-16" aria-hidden="true" tabindex="-1"></a> buffered <span class="op">=</span> BytesIO()</span>
<span id="cb20-17"><a href="#cb20-17" aria-hidden="true" tabindex="-1"></a> image.save(buffered, <span class="bu">format</span><span class="op">=</span><span class="st">"JPEG"</span>)</span>
<span id="cb20-18"><a href="#cb20-18" aria-hidden="true" tabindex="-1"></a> image_base64 <span class="op">=</span> base64.b64encode(buffered.getvalue()).decode(<span class="st">'utf-8'</span>)</span>
<span id="cb20-19"><a href="#cb20-19" aria-hidden="true" tabindex="-1"></a> <span class="cf">else</span>:</span>
<span id="cb20-20"><a href="#cb20-20" aria-hidden="true" tabindex="-1"></a> <span class="cf">with</span> <span class="bu">open</span>(image, <span class="st">"rb"</span>) <span class="im">as</span> f:</span>
<span id="cb20-21"><a href="#cb20-21" aria-hidden="true" tabindex="-1"></a> image_base64 <span class="op">=</span> base64.b64encode(f.read()).decode(<span class="st">'utf-8'</span>)</span>
<span id="cb20-22"><a href="#cb20-22" aria-hidden="true" tabindex="-1"></a> </span>
<span id="cb20-23"><a href="#cb20-23" aria-hidden="true" tabindex="-1"></a> <span class="co"># Query with structured output</span></span>
<span id="cb20-24"><a href="#cb20-24" aria-hidden="true" tabindex="-1"></a> completion <span class="op">=</span> client.beta.chat.completions.parse(</span>
<span id="cb20-25"><a href="#cb20-25" aria-hidden="true" tabindex="-1"></a> model<span class="op">=</span>model,</span>
<span id="cb20-26"><a href="#cb20-26" aria-hidden="true" tabindex="-1"></a> messages<span class="op">=</span>[{</span>
<span id="cb20-27"><a href="#cb20-27" aria-hidden="true" tabindex="-1"></a> <span class="st">"role"</span>: <span class="st">"user"</span>,</span>
<span id="cb20-28"><a href="#cb20-28" aria-hidden="true" tabindex="-1"></a> <span class="st">"content"</span>: [</span>
<span id="cb20-29"><a href="#cb20-29" aria-hidden="true" tabindex="-1"></a> {<span class="st">"type"</span>: <span class="st">"text"</span>, <span class="st">"text"</span>: prompt},</span>
<span id="cb20-30"><a href="#cb20-30" aria-hidden="true" tabindex="-1"></a> {<span class="st">"type"</span>: <span class="st">"image_url"</span>, <span class="st">"image_url"</span>: {<span class="st">"url"</span>: <span class="ss">f"data:image/jpeg;base64,</span><span class="sc">{</span>image_base64<span class="sc">}</span><span class="ss">"</span>}}</span>
<span id="cb20-31"><a href="#cb20-31" aria-hidden="true" tabindex="-1"></a> ]</span>
<span id="cb20-32"><a href="#cb20-32" aria-hidden="true" tabindex="-1"></a> }],</span>
<span id="cb20-33"><a href="#cb20-33" aria-hidden="true" tabindex="-1"></a> response_format<span class="op">=</span>schema,</span>
<span id="cb20-34"><a href="#cb20-34" aria-hidden="true" tabindex="-1"></a> temperature<span class="op">=</span><span class="fl">0.3</span> <span class="co"># Lower temperature for more consistent extraction</span></span>
<span id="cb20-35"><a href="#cb20-35" aria-hidden="true" tabindex="-1"></a> )</span>
<span id="cb20-36"><a href="#cb20-36" aria-hidden="true" tabindex="-1"></a> </span>
<span id="cb20-37"><a href="#cb20-37" aria-hidden="true" tabindex="-1"></a> <span class="co"># Return the parsed structured data</span></span>
<span id="cb20-38"><a href="#cb20-38" aria-hidden="true" tabindex="-1"></a> <span class="cf">return</span> completion.choices[<span class="dv">0</span>].message.parsed</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
</div>
<p>We also need to define a prompt that describes what information we want to extract from the card.</p>
<div id="6cb8e664" class="cell" data-execution_count="18">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb21"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true" tabindex="-1"></a><span class="co"># Example usage</span></span>
<span id="cb21-2"><a href="#cb21-2" aria-hidden="true" tabindex="-1"></a>extraction_prompt <span class="op">=</span> <span class="st">"""</span></span>
<span id="cb21-3"><a href="#cb21-3" aria-hidden="true" tabindex="-1"></a><span class="st">Extract the information from this British Library card into structured data (JSON format).</span></span>
<span id="cb21-4"><a href="#cb21-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-5"><a href="#cb21-5" aria-hidden="true" tabindex="-1"></a><span class="st">Read each field on the card and extract the following information:</span></span>
<span id="cb21-6"><a href="#cb21-6" aria-hidden="true" tabindex="-1"></a><span class="st">- department: The division name (e.g., "MANUSCRIPTS")</span></span>
<span id="cb21-7"><a href="#cb21-7" aria-hidden="true" tabindex="-1"></a><span class="st">- shelfmark: The catalog number (e.g., "SLOANE 3972.C. (VOL 1)")</span></span>
<span id="cb21-8"><a href="#cb21-8" aria-hidden="true" tabindex="-1"></a><span class="st">- order: The SCH NO reference number</span></span>
<span id="cb21-9"><a href="#cb21-9" aria-hidden="true" tabindex="-1"></a><span class="st">- author: The author name, or null if blank</span></span>
<span id="cb21-10"><a href="#cb21-10" aria-hidden="true" tabindex="-1"></a><span class="st">- title: The full title of the work</span></span>
<span id="cb21-11"><a href="#cb21-11" aria-hidden="true" tabindex="-1"></a><span class="st">- place_and_date_of_publication: Publication info, or null if blank</span></span>
<span id="cb21-12"><a href="#cb21-12" aria-hidden="true" tabindex="-1"></a><span class="st">- reduction: The reduction number (as integer) at bottom of card</span></span>
<span id="cb21-13"><a href="#cb21-13" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-14"><a href="#cb21-14" aria-hidden="true" tabindex="-1"></a><span class="st">Return the exact text as shown on the card. For empty fields with diagonal lines or no text, use null.</span></span>
<span id="cb21-15"><a href="#cb21-15" aria-hidden="true" tabindex="-1"></a><span class="st">"""</span></span>
<span id="cb21-16"><a href="#cb21-16" aria-hidden="true" tabindex="-1"></a>result <span class="op">=</span> query_image_structured(index_image, extraction_prompt, BritishLibraryReprographicCard)</span>
<span id="cb21-17"><a href="#cb21-17" aria-hidden="true" tabindex="-1"></a>rprint(result)</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display">
<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #800080; text-decoration-color: #800080; font-weight: bold">BritishLibraryReprographicCard</span><span style="font-weight: bold">(</span>
<span style="color: #808000; text-decoration-color: #808000">department</span>=<span style="color: #008000; text-decoration-color: #008000">'MANUSCRIPTS'</span>,
<span style="color: #808000; text-decoration-color: #808000">shelfmark</span>=<span style="color: #008000; text-decoration-color: #008000">'SLOANE 3972.C. (VOL 1)'</span>,
<span style="color: #808000; text-decoration-color: #808000">order</span>=<span style="color: #008000; text-decoration-color: #008000">'SCH NO 98876'</span>,
<span style="color: #808000; text-decoration-color: #808000">author</span>=<span style="color: #800080; text-decoration-color: #800080; font-style: italic">None</span>,
<span style="color: #808000; text-decoration-color: #808000">title</span>=<span style="color: #008000; text-decoration-color: #008000">'CATALOGUE OF SIR HANS SLOANES LIBRARY'</span>,
<span style="color: #808000; text-decoration-color: #808000">place_and_date_of_publication</span>=<span style="color: #800080; text-decoration-color: #800080; font-style: italic">None</span>,
<span style="color: #808000; text-decoration-color: #808000">reduction</span>=<span style="color: #008080; text-decoration-color: #008080; font-weight: bold">12</span>
<span style="font-weight: bold">)</span>
</pre>
</div>
</div>
<div id="b8ef1639" class="cell" data-execution_count="19">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb22"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb22-1"><a href="#cb22-1" aria-hidden="true" tabindex="-1"></a>rprint(result)</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display">
<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #800080; text-decoration-color: #800080; font-weight: bold">BritishLibraryReprographicCard</span><span style="font-weight: bold">(</span>
<span style="color: #808000; text-decoration-color: #808000">department</span>=<span style="color: #008000; text-decoration-color: #008000">'MANUSCRIPTS'</span>,
<span style="color: #808000; text-decoration-color: #808000">shelfmark</span>=<span style="color: #008000; text-decoration-color: #008000">'SLOANE 3972.C. (VOL 1)'</span>,
<span style="color: #808000; text-decoration-color: #808000">order</span>=<span style="color: #008000; text-decoration-color: #008000">'SCH NO 98876'</span>,
<span style="color: #808000; text-decoration-color: #808000">author</span>=<span style="color: #800080; text-decoration-color: #800080; font-style: italic">None</span>,
<span style="color: #808000; text-decoration-color: #808000">title</span>=<span style="color: #008000; text-decoration-color: #008000">'CATALOGUE OF SIR HANS SLOANES LIBRARY'</span>,
<span style="color: #808000; text-decoration-color: #808000">place_and_date_of_publication</span>=<span style="color: #800080; text-decoration-color: #800080; font-style: italic">None</span>,
<span style="color: #808000; text-decoration-color: #808000">reduction</span>=<span style="color: #008080; text-decoration-color: #008080; font-weight: bold">12</span>
<span style="font-weight: bold">)</span>
</pre>
</div>
</div>
<div id="6008255a" class="cell" data-execution_count="20">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb23"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb23-1"><a href="#cb23-1" aria-hidden="true" tabindex="-1"></a>index_image</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
<div class="cell-output cell-output-display" data-execution_count="20">
<div>
<figure class="figure">
<p><img src="vlm-structured-generation_files/figure-html/cell-21-output-1.png" class="img-fluid figure-img"></p>
</figure>
</div>
</div>
</div>
</section>
<section id="appendix-using-a-local-model" class="level2" data-number="3.8">
<h2 data-number="3.8" class="anchored" data-anchor-id="appendix-using-a-local-model"><span class="header-section-number">3.8</span> Appendix: Using a Local Model</h2>
<p>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, <code>.parse()</code> calls — works identically.</p>
<div id="91cc2f2d" class="cell" data-execution_count="21">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb24"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb24-1"><a href="#cb24-1" aria-hidden="true" tabindex="-1"></a><span class="co"># Replace the HF Inference client with a local server</span></span>
<span id="cb24-2"><a href="#cb24-2" aria-hidden="true" tabindex="-1"></a><span class="im">from</span> openai <span class="im">import</span> OpenAI</span>
<span id="cb24-3"><a href="#cb24-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb24-4"><a href="#cb24-4" aria-hidden="true" tabindex="-1"></a>client <span class="op">=</span> OpenAI(</span>
<span id="cb24-5"><a href="#cb24-5" aria-hidden="true" tabindex="-1"></a> base_url<span class="op">=</span><span class="st">"http://localhost:1234/v1"</span>, <span class="co"># LM Studio default port</span></span>
<span id="cb24-6"><a href="#cb24-6" aria-hidden="true" tabindex="-1"></a> api_key<span class="op">=</span><span class="st">"lm-studio"</span> <span class="co"># Default API key</span></span>
<span id="cb24-7"><a href="#cb24-7" aria-hidden="true" tabindex="-1"></a>)</span></code></pre></div><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></div>
</div>
<p><strong>Popular local options:</strong></p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Tool</th>
<th>Best for</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><a href="https://lmstudio.ai/">LM Studio</a></td>
<td>Getting started quickly</td>
<td>GUI-based, MLX acceleration on Mac, built-in model browser</td>
</tr>
<tr class="even">
<td><a href="https://ollama.com/">Ollama</a></td>
<td>CLI workflows</td>
<td>Simple <code>ollama run</code> commands, runs on port 11434</td>
</tr>
<tr class="odd">
<td><a href="https://docs.vllm.ai/">vLLM</a></td>
<td>Production &amp; batch processing</td>
<td>GPU-optimized, highest throughput, best for large-scale extraction</td>
</tr>
</tbody>
</table>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Note
</div>
</div>
<div class="callout-body-container callout-body">
<p>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).</p>
</div>
</div>
</section>
</main> <!-- /main -->
<script type="application/vnd.jupyter.widget-state+json">
{"state":{"075d2973f7704bbea4fb038e6bbc38e7":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"StyleView","background":null,"description_width":"","font_size":null,"text_color":null}},"17e3be666ff34554be6e0467208b49bb":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"28a32a0d0ce74f03b03c78d258e833c7":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"ProgressStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"ProgressStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"StyleView","bar_color":null,"description_width":""}},"296e56f128d74b4a9a3220376ae8e408":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"HTMLView","description":"","description_allow_html":false,"layout":"IPY_MODEL_17e3be666ff34554be6e0467208b49bb","placeholder":"​","style":"IPY_MODEL_9b22327111634402993093389cb6ffd9","tabbable":null,"tooltip":null,"value":" 10/10 [00:18&lt;00:00,  2.15s/it]"}},"7c6477b5384d4da3837c3ae504d452ba":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HBoxModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HBoxModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"HBoxView","box_style":"","children":["IPY_MODEL_88cf551dd9ee4bfca638f5f035536e70","IPY_MODEL_af3005f932a343828a0633f15f02fb38","IPY_MODEL_296e56f128d74b4a9a3220376ae8e408"],"layout":"IPY_MODEL_a9b589f05da7421ea81affbdf6dbe09b","tabbable":null,"tooltip":null}},"81bcff1e98ad4aa580f8f28285245d97":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"88cf551dd9ee4bfca638f5f035536e70":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"HTMLView","description":"","description_allow_html":false,"layout":"IPY_MODEL_9871cddb874d4820803d85d7df53e33c","placeholder":"​","style":"IPY_MODEL_075d2973f7704bbea4fb038e6bbc38e7","tabbable":null,"tooltip":null,"value":"100%"}},"9871cddb874d4820803d85d7df53e33c":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"9b22327111634402993093389cb6ffd9":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"HTMLStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"HTMLStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"StyleView","background":null,"description_width":"","font_size":null,"text_color":null}},"a9b589f05da7421ea81affbdf6dbe09b":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"af3005f932a343828a0633f15f02fb38":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"FloatProgressModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"FloatProgressModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"ProgressView","bar_style":"success","description":"","description_allow_html":false,"layout":"IPY_MODEL_81bcff1e98ad4aa580f8f28285245d97","max":10,"min":0,"orientation":"horizontal","style":"IPY_MODEL_28a32a0d0ce74f03b03c78d258e833c7","tabbable":null,"tooltip":null,"value":10}}},"version_major":2,"version_minor":0}
</script>
<script id="quarto-html-after-body" type="application/javascript">
window.document.addEventListener("DOMContentLoaded", function (event) {
const icon = "";
const anchorJS = new window.AnchorJS();
anchorJS.options = {
placement: 'right',
icon: icon
};
anchorJS.add('.anchored');
const isCodeAnnotation = (el) => {
for (const clz of el.classList) {
if (clz.startsWith('code-annotation-')) {
return true;
}
}
return false;
}
const onCopySuccess = function(e) {
// button target
const button = e.trigger;
// don't keep focus
button.blur();
// flash "checked"
button.classList.add('code-copy-button-checked');
var currentTitle = button.getAttribute("title");
button.setAttribute("title", "Copied!");
let tooltip;
if (window.bootstrap) {
button.setAttribute("data-bs-toggle", "tooltip");
button.setAttribute("data-bs-placement", "left");
button.setAttribute("data-bs-title", "Copied!");
tooltip = new bootstrap.Tooltip(button,
{ trigger: "manual",
customClass: "code-copy-button-tooltip",
offset: [0, -8]});
tooltip.show();
}
setTimeout(function() {
if (tooltip) {
tooltip.hide();
button.removeAttribute("data-bs-title");
button.removeAttribute("data-bs-toggle");
button.removeAttribute("data-bs-placement");
}
button.setAttribute("title", currentTitle);
button.classList.remove('code-copy-button-checked');
}, 1000);
// clear code selection
e.clearSelection();
}
const getTextToCopy = function(trigger) {
const outerScaffold = trigger.parentElement.cloneNode(true);
const codeEl = outerScaffold.querySelector('code');
for (const childEl of codeEl.children) {
if (isCodeAnnotation(childEl)) {
childEl.remove();
}
}
return codeEl.innerText;
}
const clipboard = new window.ClipboardJS('.code-copy-button:not([data-in-quarto-modal])', {
text: getTextToCopy
});
clipboard.on('success', onCopySuccess);
if (window.document.getElementById('quarto-embedded-source-code-modal')) {
const clipboardModal = new window.ClipboardJS('.code-copy-button[data-in-quarto-modal]', {
text: getTextToCopy,
container: window.document.getElementById('quarto-embedded-source-code-modal')
});
clipboardModal.on('success', onCopySuccess);
}
var localhostRegex = new RegExp(/^(?:http|https):\/\/localhost\:?[0-9]*\//);
var mailtoRegex = new RegExp(/^mailto:/);
var filterRegex = new RegExp('/' + window.location.host + '/');
var isInternal = (href) => {
return filterRegex.test(href) || localhostRegex.test(href) || mailtoRegex.test(href);
}
// Inspect non-navigation links and adorn them if external
var links = window.document.querySelectorAll('a[href]:not(.nav-link):not(.navbar-brand):not(.toc-action):not(.sidebar-link):not(.sidebar-item-toggle):not(.pagination-link):not(.no-external):not([aria-hidden]):not(.dropdown-item):not(.quarto-navigation-tool):not(.about-link)');
for (var i=0; i<links.length; i++) {
const link = links[i];
if (!isInternal(link.href)) {
// undo the damage that might have been done by quarto-nav.js in the case of
// links that we want to consider external
if (link.dataset.originalHref !== undefined) {
link.href = link.dataset.originalHref;
}
}
}
function tippyHover(el, contentFn, onTriggerFn, onUntriggerFn) {
const config = {
allowHTML: true,
maxWidth: 500,
delay: 100,
arrow: false,
appendTo: function(el) {
return el.parentElement;
},
interactive: true,
interactiveBorder: 10,
theme: 'quarto',
placement: 'bottom-start',
};
if (contentFn) {
config.content = contentFn;
}
if (onTriggerFn) {
config.onTrigger = onTriggerFn;
}
if (onUntriggerFn) {
config.onUntrigger = onUntriggerFn;
}
window.tippy(el, config);
}
const noterefs = window.document.querySelectorAll('a[role="doc-noteref"]');
for (var i=0; i<noterefs.length; i++) {
const ref = noterefs[i];
tippyHover(ref, function() {
// use id or data attribute instead here
let href = ref.getAttribute('data-footnote-href') || ref.getAttribute('href');
try { href = new URL(href).hash; } catch {}
const id = href.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
if (note) {
return note.innerHTML;
} else {
return "";
}
});
}
const xrefs = window.document.querySelectorAll('a.quarto-xref');
const processXRef = (id, note) => {
// Strip column container classes
const stripColumnClz = (el) => {
el.classList.remove("page-full", "page-columns");
if (el.children) {
for (const child of el.children) {
stripColumnClz(child);
}
}
}
stripColumnClz(note)
if (id === null || id.startsWith('sec-')) {
// Special case sections, only their first couple elements
const container = document.createElement("div");
if (note.children && note.children.length > 2) {
container.appendChild(note.children[0].cloneNode(true));
for (let i = 1; i < note.children.length; i++) {
const child = note.children[i];
if (child.tagName === "P" && child.innerText === "") {
continue;
} else {
container.appendChild(child.cloneNode(true));
break;
}
}
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(container);
}
return container.innerHTML
} else {
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(note);
}
return note.innerHTML;
}
} else {
// Remove any anchor links if they are present
const anchorLink = note.querySelector('a.anchorjs-link');
if (anchorLink) {
anchorLink.remove();
}
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(note);
}
if (note.classList.contains("callout")) {
return note.outerHTML;
} else {
return note.innerHTML;
}
}
}
for (var i=0; i<xrefs.length; i++) {
const xref = xrefs[i];
tippyHover(xref, undefined, function(instance) {
instance.disable();
let url = xref.getAttribute('href');
let hash = undefined;
if (url.startsWith('#')) {
hash = url;
} else {
try { hash = new URL(url).hash; } catch {}
}
if (hash) {
const id = hash.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
if (note !== null) {
try {
const html = processXRef(id, note.cloneNode(true));
instance.setContent(html);
} finally {
instance.enable();
instance.show();
}
} else {
// See if we can fetch this
fetch(url.split('#')[0])
.then(res => res.text())
.then(html => {
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(html, "text/html");
const note = htmlDoc.getElementById(id);
if (note !== null) {
const html = processXRef(id, note);
instance.setContent(html);
}
}).finally(() => {
instance.enable();
instance.show();
});
}
} else {
// See if we can fetch a full url (with no hash to target)
// This is a special case and we should probably do some content thinning / targeting
fetch(url)
.then(res => res.text())
.then(html => {
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(html, "text/html");
const note = htmlDoc.querySelector('main.content');
if (note !== null) {
// This should only happen for chapter cross references
// (since there is no id in the URL)
// remove the first header
if (note.children.length > 0 && note.children[0].tagName === "HEADER") {
note.children[0].remove();
}
const html = processXRef(null, note);
instance.setContent(html);
}
}).finally(() => {
instance.enable();
instance.show();
});
}
}, function(instance) {
});
}
let selectedAnnoteEl;
const selectorForAnnotation = ( cell, annotation) => {
let cellAttr = 'data-code-cell="' + cell + '"';
let lineAttr = 'data-code-annotation="' + annotation + '"';
const selector = 'span[' + cellAttr + '][' + lineAttr + ']';
return selector;
}
const selectCodeLines = (annoteEl) => {
const doc = window.document;
const targetCell = annoteEl.getAttribute("data-target-cell");
const targetAnnotation = annoteEl.getAttribute("data-target-annotation");
const annoteSpan = window.document.querySelector(selectorForAnnotation(targetCell, targetAnnotation));
const lines = annoteSpan.getAttribute("data-code-lines").split(",");
const lineIds = lines.map((line) => {
return targetCell + "-" + line;
})
let top = null;
let height = null;
let parent = null;
if (lineIds.length > 0) {
//compute the position of the single el (top and bottom and make a div)
const el = window.document.getElementById(lineIds[0]);
top = el.offsetTop;
height = el.offsetHeight;
parent = el.parentElement.parentElement;
if (lineIds.length > 1) {
const lastEl = window.document.getElementById(lineIds[lineIds.length - 1]);
const bottom = lastEl.offsetTop + lastEl.offsetHeight;
height = bottom - top;
}
if (top !== null && height !== null && parent !== null) {
// cook up a div (if necessary) and position it
let div = window.document.getElementById("code-annotation-line-highlight");
if (div === null) {
div = window.document.createElement("div");
div.setAttribute("id", "code-annotation-line-highlight");
div.style.position = 'absolute';
parent.appendChild(div);
}
div.style.top = top - 2 + "px";
div.style.height = height + 4 + "px";
div.style.left = 0;
let gutterDiv = window.document.getElementById("code-annotation-line-highlight-gutter");
if (gutterDiv === null) {
gutterDiv = window.document.createElement("div");
gutterDiv.setAttribute("id", "code-annotation-line-highlight-gutter");
gutterDiv.style.position = 'absolute';
const codeCell = window.document.getElementById(targetCell);
const gutter = codeCell.querySelector('.code-annotation-gutter');
gutter.appendChild(gutterDiv);
}
gutterDiv.style.top = top - 2 + "px";
gutterDiv.style.height = height + 4 + "px";
}
selectedAnnoteEl = annoteEl;
}
};
const unselectCodeLines = () => {
const elementsIds = ["code-annotation-line-highlight", "code-annotation-line-highlight-gutter"];
elementsIds.forEach((elId) => {
const div = window.document.getElementById(elId);
if (div) {
div.remove();
}
});
selectedAnnoteEl = undefined;
};
// Handle positioning of the toggle
window.addEventListener(
"resize",
throttle(() => {
elRect = undefined;
if (selectedAnnoteEl) {
selectCodeLines(selectedAnnoteEl);
}
}, 10)
);
function throttle(fn, ms) {
let throttle = false;
let timer;
return (...args) => {
if(!throttle) { // first call gets through
fn.apply(this, args);
throttle = true;
} else { // all the others get throttled
if(timer) clearTimeout(timer); // cancel #2
timer = setTimeout(() => {
fn.apply(this, args);
timer = throttle = false;
}, ms);
}
};
}
// Attach click handler to the DT
const annoteDls = window.document.querySelectorAll('dt[data-target-cell]');
for (const annoteDlNode of annoteDls) {
annoteDlNode.addEventListener('click', (event) => {
const clickedEl = event.target;
if (clickedEl !== selectedAnnoteEl) {
unselectCodeLines();
const activeEl = window.document.querySelector('dt[data-target-cell].code-annotation-active');
if (activeEl) {
activeEl.classList.remove('code-annotation-active');
}
selectCodeLines(clickedEl);
clickedEl.classList.add('code-annotation-active');
} else {
// Unselect the line
unselectCodeLines();
clickedEl.classList.remove('code-annotation-active');
}
});
}
const findCites = (el) => {
const parentEl = el.parentElement;
if (parentEl) {
const cites = parentEl.dataset.cites;
if (cites) {
return {
el,
cites: cites.split(' ')
};
} else {
return findCites(el.parentElement)
}
} else {
return undefined;
}
};
var bibliorefs = window.document.querySelectorAll('a[role="doc-biblioref"]');
for (var i=0; i<bibliorefs.length; i++) {
const ref = bibliorefs[i];
const citeInfo = findCites(ref);
if (citeInfo) {
tippyHover(citeInfo.el, function() {
var popup = window.document.createElement('div');
citeInfo.cites.forEach(function(cite) {
var citeDiv = window.document.createElement('div');
citeDiv.classList.add('hanging-indent');
citeDiv.classList.add('csl-entry');
var biblioDiv = window.document.getElementById('ref-' + cite);
if (biblioDiv) {
citeDiv.innerHTML = biblioDiv.innerHTML;
}
popup.appendChild(citeDiv);
});
return popup.innerHTML;
});
}
}
});
</script>
<nav class="page-navigation">
<div class="nav-page nav-page-previous">
<a href="../../patterns/structured-generation/intro.html" class="pagination-link" aria-label="Structured Document Processing">
<i class="bi bi-arrow-left-short"></i> <span class="nav-page-text"><span class="chapter-number">2</span>&nbsp; <span class="chapter-title">Structured Document Processing</span></span>
</a>
</div>
<div class="nav-page nav-page-next">
</div>
</nav>
</div> <!-- /content -->
</body></html>