📦 google-gemini / cookbook

📄 Pdf_structured_outputs_on_invoices_and_forms.ipynb · 498 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Tce3stUlHN0L"
      },
      "source": [
        "##### Copyright 2025 Google LLC."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 17,
      "metadata": {
        "cellView": "form",
        "id": "tuOe1ymfHZPu"
      },
      "outputs": [],
      "source": [
        "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dfsDR_omdNea"
      },
      "source": [
        "# Gemini API: Automated Invoice and Form Data Extraction with Gemini API & Pydantic\n",
        "\n",
        "This notebook demonstrates how you can convert a PDF file so that it can be read by the Gemini API.\n",
        "\n",
        "<a target=\"_blank\" href=\"https://colab.research.google.com/github/google-gemini/cookbook/blob/main/examples/Pdf_structured_outputs_on_invoices_and_forms.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" height=30/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cdfdb44021cd"
      },
      "source": [
        "## 1. Set up Environment and create inference Client\n",
        "\n",
        "The first task is to install the `google-genai` [Python SDK](https://googleapis.github.io/python-genai/) and obtain an API key. If you don”t have a can get one from Google AI Studio: [Get a Gemini API key](https://aistudio.google.com/app/apikey). If you are new to Google Colab checkout the [quickstart](../quickstarts/Authentication.ipynb)).\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "7bb370b2609a"
      },
      "outputs": [],
      "source": [
        "%pip install \"google-genai>=1\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "d23fd7166d83"
      },
      "source": [
        "Once you have the SDK and API key, you can create a client and define the model you are going to use the new Gemini Flash model, which is available via [free tier](https://ai.google.dev/pricing#2_0flash) with 1,500 request per day (at 2025-02-06). "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 24,
      "metadata": {
        "id": "4cf581eca5ef"
      },
      "outputs": [],
      "source": [
        "from google import genai\n",
        "from google.colab import userdata\n",
        "api_key = userdata.get(\"GOOGLE_API_KEY\") # If you are not using Colab you can set the API key directly\n",
        "\n",
        "# Create a client\n",
        "client = genai.Client(api_key=api_key)\n",
        "\n",
        "# Define the model you are going to use\n",
        "model_id =  \"gemini-2.5-flash\" # or \"gemini-2.5-flash-lite\", \"gemini-2.5-flash\", \"gemini-2.5-pro\",\"gemini-3-pro-preview\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7403eae04304"
      },
      "source": [
        "*Note: If you want to use Vertex AI see [here](https://googleapis.github.io/python-genai/#create-a-client) how to create your client*"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "e68aefb88671"
      },
      "source": [
        "## 2. Work with PDFs and other files\n",
        "\n",
        "Gemini models are able to process [images and videos](https://ai.google.dev/gemini-api/docs/vision?lang=python#image-input), which can used with base64 strings or using the `files`api. After uploading the file you can include the file uri in the call directly. The Python API includes a [upload](https://googleapis.github.io/python-genai/#upload) and [delete](https://googleapis.github.io/python-genai/#delete) method. \n",
        "\n",
        "For this example you have 2 PDFs samples, one basic invoice and on form with and written values. \n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "37e99d94e05b"
      },
      "outputs": [],
      "source": [
        "!wget -q -O handwriting_form.pdf https://storage.googleapis.com/generativeai-downloads/data/pdf_structured_outputs/handwriting_form.pdf\n",
        "!wget -q -O invoice.pdf https://storage.googleapis.com/generativeai-downloads/data/pdf_structured_outputs/invoice.pdf"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9e451e09e1e1"
      },
      "source": [
        "You can now upload the files using our client with the `upload` method. Let's try this for one of the files.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {
        "id": "a26a622caec8"
      },
      "outputs": [],
      "source": [
        "invoice_pdf = client.files.upload(file=\"invoice.pdf\", config={'display_name': 'invoice'})"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "c02e316f6b80"
      },
      "source": [
        "_Note: The File API lets you store up to 20 GB of files per project, with a per-file maximum size of 2 GB. Files are stored for 48 hours. They can be accessed in that period with your API key, but they cannot be downloaded. File uploads are available at no cost._\n",
        "\n",
        "After a file is uploaded you can check to how many tokens it got converted. This not only help us understand the context you are working with it also helps to keep track of the cost. "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {
        "id": "268cecdab1b4"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "File: invoice equals to 821 tokens\n"
          ]
        }
      ],
      "source": [
        "file_size = client.models.count_tokens(model=model_id,contents=invoice_pdf)\n",
        "print(f'File: {invoice_pdf.display_name} equals to {file_size.total_tokens} tokens')\n",
        "# File: invoice equals to 821 tokens"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "13215cead66e"
      },
      "source": [
        "## 3. Structured outputs with Gemini 2.0 and Pydantic\n",
        "\n",
        "Structured Outputs is a feature that ensures Gemini always generate responses that adhere to a predefined format, such as JSON Schema. This means you have more control over the output and how to integrate it into our application as it is guaranteed to return a valid JSON object with the schema you define. \n",
        "\n",
        "Gemini 2.0 currenlty supports 3 dfferent types of how to define a JSON schemas:\n",
        "- A single python type, as you would use in a [typing annotation](https://docs.python.org/3/library/typing.html).\n",
        "- A Pydantic [BaseModel](https://docs.pydantic.dev/latest/concepts/models/)\n",
        "- A dict equivalent of [genai.types.Schema](https://googleapis.github.io/python-genai/genai.html#genai.types.Schema) / [Pydantic BaseModel](https://docs.pydantic.dev/latest/concepts/models/)\n",
        "\n",
        "Lets look at quick text-based example."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {
        "id": "fcb7f5a10c3e"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "{\n",
            "  \"age\": 0,\n",
            "  \"first_name\": \"Philipp\",\n",
            "  \"last_name\": \"Schmid\",\n",
            "  \"work_topics\": [\n",
            "    {\n",
            "      \"name\": \"AI\"\n",
            "    },\n",
            "    {\n",
            "      \"name\": \"Gemini\"\n",
            "    },\n",
            "    {\n",
            "      \"name\": \"Gemma\"\n",
            "    }\n",
            "  ]\n",
            "}\n",
            "First name is Philipp\n"
          ]
        }
      ],
      "source": [
        "from pydantic import BaseModel, Field\n",
        "\n",
        "# Define a Pydantic model\n",
        "# Use the Field class to add a description and default value to provide more context to the model\n",
        "class Topic(BaseModel):\n",
        "    name: str = Field(description=\"The name of the topic\")\n",
        "\n",
        "class Person(BaseModel):\n",
        "    first_name: str = Field(description=\"The first name of the person\")\n",
        "    last_name: str = Field(description=\"The last name of the person\")\n",
        "    age: int = Field(description=\"The age of the person, if not provided please return 0\")\n",
        "    work_topics: list[Topic] = Field(description=\"The fields of interest of the person, if not provided please return an empty list\")\n",
        "\n",
        "\n",
        "# Define the prompt\n",
        "prompt = \"Philipp Schmid is a Senior AI Developer Relations Engineer at Google DeepMind working on Gemini, Gemma with the mission to help every developer to build and benefit from AI in a responsible way.  \"\n",
        "\n",
        "# Generate a response using the Person model\n",
        "response = client.models.generate_content(model=model_id, contents=prompt, config={'response_mime_type': 'application/json', 'response_schema': Person})\n",
        "\n",
        "# print the response as a json string\n",
        "print(response.text)\n",
        "\n",
        "# sdk automatically converts the response to the pydantic model\n",
        "philipp: Person = response.parsed\n",
        "\n",
        "# access an attribute of the json response\n",
        "print(f\"First name is {philipp.first_name}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "98ba7c85f7a4"
      },
      "source": [
        "## 4. Extract Structured data from PDFs using Gemini 2.0\n",
        "\n",
        "Now, let's combine the File API and structured output to extract information from our PDFs. You can create a simple method that accepts a local file path and a pydantic model and return the structured data for us. The method will:\n",
        "\n",
        "1. Upload the file to the File API\n",
        "2. Generate a structured response using the Gemini API\n",
        "3. Convert the response to the pydantic model and return it\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "metadata": {
        "id": "4bae48dddcf3"
      },
      "outputs": [],
      "source": [
        "def extract_structured_data(file_path: str, model: BaseModel):\n",
        "    # Upload the file to the File API\n",
        "    file = client.files.upload(file=file_path, config={'display_name': file_path.split('/')[-1].split('.')[0]})\n",
        "    # Generate a structured response using the Gemini API\n",
        "    prompt = f\"Extract the structured data from the following PDF file\"\n",
        "    response = client.models.generate_content(model=model_id, contents=[prompt, file], config={'response_mime_type': 'application/json', 'response_schema': model})\n",
        "    # Convert the response to the pydantic model and return it\n",
        "    return response.parsed"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8657cdd843fa"
      },
      "source": [
        "In our Example every PDF is a different to each other. So you want to define unique Pydantic models for each PDF to show the performance of the Gemini 2.0. If you have very similar PDFs and want to extract the same information you can use the same model for all of them. \n",
        "\n",
        "- `Invoice.pdf` : Extract the invoice number, date and all list items with description, quantity and gross worth and the total gross worth\n",
        "- `handwriting_form.pdf` : Extract the form number, plan start date and the plan liabilities beginning of the year and end of the year\n",
        "\n",
        "_Note: Using Pydantic features you can add more context to the model to make it more accurate as well as some validation to the data. Adding a comprehensive description can significantly improve the performance of the model. Libraries like [instructor](https://python.useinstructor.com/) added automatic retries based on validation errors, which can be a great help, but come at the cost of additional requests._\n",
        "\n",
        "\n",
        "### Invoice.pdf\n",
        "\n",
        "![Invoice.pdf](https://storage.googleapis.com/generativeai-downloads/data/pdf_structured_outputs/invoice.png)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "metadata": {
        "id": "e3c8f5b59da8"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "<class '__main__.Invoice'>\n",
            "Extracted Invoice: 27301261 on 10/09/2012 with total gross worth 544.46\n",
            "Item: Lilly Pulitzer dress Size 2 with quantity 5.0 and gross worth 247.5\n",
            "Item: New ERIN Erin Fertherston Straight Dress White Sequence Lining Sleeveless SZ 10 with quantity 1.0 and gross worth 65.99\n",
            "Item: Sequence dress Size Small with quantity 3.0 and gross worth 115.5\n",
            "Item: fire los angeles dress Medium with quantity 3.0 and gross worth 21.45\n",
            "Item: Eileen Fisher Women's Long Sleeve Fleece Lined Front Pockets Dress XS Gray with quantity 3.0 and gross worth 52.77\n",
            "Item: Lularoe Nicole Dress Size Small Light Solid Grey/ White Ringer Tee Trim with quantity 2.0 and gross worth 8.25\n",
            "Item: J.Crew Collection Black & White sweater Dress sz S with quantity 1.0 and gross worth 33.0\n"
          ]
        }
      ],
      "source": [
        "from pydantic import BaseModel, Field\n",
        "\n",
        "class Item(BaseModel):\n",
        "    description: str = Field(description=\"The description of the item\")\n",
        "    quantity: float = Field(description=\"The Qty of the item\")\n",
        "    gross_worth: float = Field(description=\"The gross worth of the item\")\n",
        "\n",
        "class Invoice(BaseModel):\n",
        "    \"\"\"Extract the invoice number, date and all list items with description, quantity and gross worth and the total gross worth.\"\"\"\n",
        "    invoice_number: str = Field(description=\"The invoice number e.g. 1234567890\")\n",
        "    date: str = Field(description=\"The date of the invoice e.g. 2024-01-01\")\n",
        "    items: list[Item] = Field(description=\"The list of items with description, quantity and gross worth\")\n",
        "    total_gross_worth: float = Field(description=\"The total gross worth of the invoice\")\n",
        "\n",
        "\n",
        "result = extract_structured_data(\"invoice.pdf\", Invoice)\n",
        "print(type(result))\n",
        "print(f\"Extracted Invoice: {result.invoice_number} on {result.date} with total gross worth {result.total_gross_worth}\")\n",
        "for item in result.items:\n",
        "    print(f\"Item: {item.description} with quantity {item.quantity} and gross worth {item.gross_worth}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1f34f1b9f793"
      },
      "source": [
        "Fantastic! The model did a great job extracting the information from the invoice. \n",
        "\n",
        "### handwriting_form.pdf\n",
        "\n",
        "![handwriting_form.pdf](https://storage.googleapis.com/generativeai-downloads/data/pdf_structured_outputs/handwriting_form.jpg)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 29,
      "metadata": {
        "id": "d24349d82683"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Extracted Form Number: CA530082 with start date 02/05/2022. \n",
            "Plan liabilities beginning of the year 40000.0 and end of the year 55000.0\n"
          ]
        }
      ],
      "source": [
        "class Form(BaseModel):\n",
        "    \"\"\"Extract the form number, fiscal start date, fiscal end date, and the plan liabilities beginning of the year and end of the year.\"\"\"\n",
        "    form_number: str = Field(description=\"The Form Number\")\n",
        "    start_date: str = Field(description=\"Effective Date\")\n",
        "    beginning_of_year: float = Field(description=\"The plan liabilities beginning of the year\")\n",
        "    end_of_year: float = Field(description=\"The plan liabilities end of the year\")\n",
        "\n",
        "result = extract_structured_data(\"handwriting_form.pdf\", Form)\n",
        "\n",
        "print(f'Extracted Form Number: {result.form_number} with start date {result.start_date}. \\nPlan liabilities beginning of the year {result.beginning_of_year} and end of the year {result.end_of_year}')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "db5dd4819309"
      },
      "source": [
        "## Learning more\n",
        "\n",
        "If you want to learn more about the File API, Structured Outputs and how to use it to process images, audio, and video files, check out the following resources:\n",
        "\n",
        "* Learn more about the [File API](../quickstarts/File_API.ipynb) with the quickstart.\n",
        "* Learn more about prompting with [media files](https://ai.google.dev/gemini-api/docs/file-prompting-strategies) in the docs, including the supported formats and maximum length.\n",
        "* Learn more about [Structured Outputs](https://ai.google.dev/gemini-api/docs/structured-output?lang=python) in the docs.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "55c03b7e87ba"
      },
      "source": [
        "## Property ordering with Gemini 2.0\n",
        "\n",
        "**Important:** Gemini 2.0 models require explicit ordering of keys in structured output schemas. When working with Gemini 2.0, you must define the desired property ordering as a list within the `propertyOrdering` field as part of your schema configuration.\n",
        "\n",
        "This ensures consistent and predictable ordering of properties in the JSON response, which is particularly important when the output property order matters for downstream processing."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "82bf6f49188e"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "{\n",
            "  \"invoice_number\": \"12345\",\n",
            "  \"date\": \"2024-01-15\",\n",
            "  \"vendor\": \"Acme Corp\",\n",
            "  \"total_amount\": 1250.00\n",
            "}\n"
          ]
        }
      ],
      "source": [
        "# Example: Specifying property ordering for Gemini 2.0\n",
        "from google import genai\n",
        "from google.genai import types\n",
        "\n",
        "# Define a schema with explicit property ordering\n",
        "invoice_schema = types.Schema(\n",
        "    type=types.Type.OBJECT,\n",
        "    properties={\n",
        "        \"invoice_number\": types.Schema(type=types.Type.STRING),\n",
        "        \"date\": types.Schema(type=types.Type.STRING),\n",
        "        \"vendor\": types.Schema(type=types.Type.STRING),\n",
        "        \"total_amount\": types.Schema(type=types.Type.NUMBER),\n",
        "    },\n",
        "    # REQUIRED for Gemini 2.0: Specify the exact order of properties, not Gemini 2.5 or newer\n",
        "    property_ordering=[\"invoice_number\", \"date\", \"vendor\", \"total_amount\"],\n",
        ")\n",
        "\n",
        "# Use the schema with generateContent\n",
        "client = genai.Client()\n",
        "\n",
        "response = client.models.generate_content(\n",
        "    model=\"gemini-2.0-flash\",\n",
        "    contents=\"Extract invoice details: Invoice #12345 dated 2024-01-15 from Acme Corp for $1,250.00\",\n",
        "    config=types.GenerateContentConfig(\n",
        "        response_mime_type=\"application/json\",\n",
        "        response_schema=invoice_schema,\n",
        "    ),\n",
        ")\n",
        "\n",
        "print(response.text)"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "name": "Pdf_structured_outputs_on_invoices_and_forms.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}