Databricks Tutorials

Documents into Data with Genie Code and AI Functions: Parsing, Classifying and Extracting Ticket Attachments on Databricks Free Edition

From Genie Code Prototype to Production Agent on Databricks — Episode 2 of 10 ·

In Episode 1 we turned 5,327 messy support tickets into a clean medallion pipeline in workspace.support_copilot. But open a real helpdesk and half of the useful information isn't in the ticket at all. It's in the attachment: the invoice the customer says is wrong, the refund form, the blurry screenshot of an error dialog.

Our Support Copilot can't answer "how much is this customer asking us to refund?" if the answer lives in a PDF. So in this episode we turn 48 PDF attachments into a silver table joined to our tickets. Just like in E1, we let Genie Code in Agent mode build the workflow from one prompt, guided by a skill. It uses three AI Functions in SQL:

Everything runs on Databricks Free Edition. We tested ai_parse_document and ai_classify there on 23 October 2026.

What we will build

Table What it holds
bronze_attachments_index Helpdesk export: attachment_id, ticket_id, uploaded_at
bronze_attachments Raw PDF bytes from the volume
bronze_attachment_parsed ai_parse_document output + plain text, parsed once
bronze_attachment_ai Raw ai_classify and ai_extract outputs
silver_ticket_attachments One typed row per attachment, joined to silver_tickets, with review flags

Prerequisites

Step 1: Generate attachments for real tickets

The generator reads E1's raw data and only picks tickets that survive our silver layer, so every attachment joins to a real ticket_id:

pip install reportlab pillow
python generate_attachments.py --seed 42

With seed 42 we get 48 PDFs for 36 tickets: 17 invoices, 11 refund requests and 20 error reports. We made them as messy as real ones:

The file names are neutral (ATT-0001.pdf), so nothing gives the document type away. The model has to read the content.

A generated invoice An image-only error report

We unzip raw_data.zip into the E1 volume, next to the ticket folders:

/Volumes/workspace/support_copilot/raw/attachments/ATT-0001.pdf ...
/Volumes/workspace/support_copilot/raw/attachments_index/attachments_index.csv

Clip 1: the attachments in the volume, a Polish invoice, a screenshot PDF, and the index that links them to tickets.

Step 2: A skill for documents

Like in E1, we put our conventions in a skill rather than in every prompt: /Users/{username}/.assistant/skills/support-copilot-documents/SKILL.md. It holds the table names, function versions, the label set and the extraction schema. It also has one rule that saves real quota: parse once, store the result, never call an AI function twice on the same file.

## Functions and versions
- ai_parse_document(content, map('version','2.0'))
- ai_classify(parsed_text, labels_json, map('version','2.1','enableConfidenceScores','true')) -> :response[0]:value
- ai_extract(parsed_text, schema, map('version','2.1','enableConfidenceScores','true')) -> :response:<field>:value
- Confidence values may come back as strings ("1"): always try_cast(... ::string AS DOUBLE).

We pin versions on purpose. The v2 signatures of ai_classify and ai_extract went to Public Preview in March 2026, and v2.1 changed the output format: every label and field is now an object with a value key. The legacy form, ai_classify(text, ARRAY('invoice', 'refund_request', 'error_report')), still works. In our workspace it returned a plain 'refund_request' for "I was charged twice…" in about 1.7 seconds. But a plain string has no confidence score, and we want one.

We profile first, without spending any AI quota:

@support-copilot-documents Look at /Volumes/workspace/support_copilot/raw/attachments/ and raw/attachments_index/. Tell me how many files there are, how they link to silver_tickets, and how many ticket_ids are missing from silver_tickets. Don't call any AI functions yet.

Clip 2: the skill is picked up, and Genie Code reports 48 PDFs for 36 tickets with 0 missing ticket ids.

Step 3: One prompt, one document workflow

Now the main event. One prompt, four layers, with two checkpoints where Genie Code has to stop and ask us:

@support-copilot-documents Build the document workflow for ticket attachments, following the skill:
1. bronze_attachments_index and bronze_attachments (binary) from the volume,
2. bronze_attachment_parsed with ai_parse_document, parse each file once, test on 5 files first and show me the text of one invoice and one image-only error report,
3. bronze_attachment_ai with ai_classify (labels and descriptions from the skill) and ai_extract (schema from the skill), one call per document,
4. silver_ticket_attachments joined to silver_tickets with the review and mismatch flags.
Show the plan first, and ask before running steps 2-3 on all files.

Clip 3 (hero): the plan, the 5-file test, our approval, and the full run.

The heart of the parse step (the full reference is in fallback/e02_documents.sql):

CREATE OR REPLACE TABLE bronze_attachment_parsed AS
WITH p AS (
  SELECT attachment_id,
         ai_parse_document(content, map('version', '2.0', 'descriptionElementTypes', '')) AS parsed
  FROM bronze_attachments
)
SELECT attachment_id, parsed,
       concat_ws('\n\n', transform(try_cast(parsed:document:elements AS ARRAY<VARIANT>),
                                  e -> e:content::string)) AS parsed_text,
       parsed:error_status::string AS parse_error
FROM p;

On our 5-file test, each element came back with content, a bbox with page coordinates and a confidence. The first element on each page gave the document away: FAKTURA VAT for the Polish invoice, INVOICE for two English ones, Refund Request Form for the other two. descriptionElementTypes => '' turns off AI descriptions of figures. We don't need them, and they cost compute.

Two details from the live run made it into the skill:

The OCR handled the image-only screenshots too: in the 5-file test, an error report with no text layer came back as Sign-in failed / Error AUTH-1042.

Not everything went first time. While writing the first cells, Genie Code hit an error on modificationTime (a file-metadata column) and fixed it on its own before the test ran. Then, after we approved the full run (48 parse calls, 96 classify/extract calls), the panel briefly said "Failed to run 5 cells". That message was wrong: the cells were still running, and a little later the panel reported "Ran 5 cells". If you see the same thing, wait for the run to finish and check the tables before you retry. A retry would spend quota on files that are already parsed.

Then classification and extraction, one call per document, stored once:

SELECT attachment_id,
  ai_classify(parsed_text, '{
      "invoice": "A bill from the software vendor with invoice number, line items and a total due",
      "refund_request": "A form in which the customer asks for money back",
      "error_report": "A screenshot of an application error message",
      "other": "Anything else"}',
    map('version', '2.1', 'enableConfidenceScores', 'true',
        'instructions', 'Attachments sent with SaaS support tickets. Documents can be English, Polish or German.')) AS cls,
  ai_extract(parsed_text, '{
      "invoice_number": {"type": "string", "description": "Invoice number like INV-YYYYMM-NNNN; for refund forms the related invoice"},
      "document_date":  {"type": "string", "description": "Issue / request / error date, as YYYY-MM-DD"},
      "currency":       {"type": "string", "description": "ISO 4217: PLN for zł, EUR for €, GBP for £, USD for $"},
      "total_amount":   {"type": "number", "description": "Gross total due, or amount requested on a refund"},
      "ticket_ref":     {"type": "string", "description": "Ticket id printed on the document, T + 6 digits"},
      "language":       {"type": "string", "description": "ISO 639-1"},
      "refund_reason":  {"type": "string"}, "error_message": {"type": "string"}}',
    options => map('version', '2.1', 'enableConfidenceScores', 'true')) AS ext
FROM bronze_attachment_parsed;

Descriptions are prompts. Without them, "refund request" and "invoice" look alike, because both have an invoice number and an amount. With them, the model knows which one asks for money back. The currency description is what turns zł into PLN.

All five tables ended up with 48 rows each: bronze_attachments_index, bronze_attachments, bronze_attachment_parsed, bronze_attachment_ai and silver_ticket_attachments. One row per file, and no file parsed twice.

Step 4: Read the results

Clip 4: the raw extraction for ATT-0001, the Polish invoice, stored as a VARIANT with a confidence score per field: INV-202610-4582, 2026-10-15, 7606.32 PLN, confidence 1.

The summary of the whole run matched the generator exactly, and 7 of the 48 attachments were flagged needs_review:

doc_type Expected (ground truth) Got
invoice 17 17
refund_request 11 11
error_report 20 20

Step 5: Land it in silver, joined to tickets

The silver table turns VARIANTs into typed columns, joins to silver_tickets through the index, and adds the flags a support lead actually cares about:

x.cls:response[0]:value::string                                          AS doc_type,
try_cast(x.cls:response[0]:confidence_score::string AS DOUBLE)           AS doc_type_confidence,
try_cast(x.ext:response:total_amount:value::string AS DECIMAL(12,2))     AS doc_total_amount,
...
a.doc_type = 'refund_request' AND a.doc_total_amount <> inv.invoice_amount AS is_refund_amount_mismatch,
(coalesce(a.doc_type_confidence, 0) < 0.8 OR a.doc_type = 'other')        AS needs_review

needs_review is our human in the loop: anything the model isn't sure about goes to a person, not into a refund.

Note the coalesce. Our first version compared the confidence directly, and in SQL NULL < 0.8 is NULL, not true, so a row with no confidence score would silently skip the review queue. We asked Genie Code to harden the flag and rebuild. Rows with no confidence now get flagged too. In our run the count didn't change (still 7), but the rule no longer depends on luck.

SELECT ticket_id, doc_invoice_number, doc_total_amount, doc_currency, refund_reason, priority, status
FROM workspace.support_copilot.silver_ticket_attachments
WHERE is_refund_amount_mismatch;

The generator planted 3 mismatched refunds, and the query found exactly 3: T000575 (asks for double the invoice), T004280 (asks for half) and T004295.

Clip 5: the summary and review queue, the mismatch check, the NULL-confidence hardening, and silver_ticket_attachments with its column comments in Catalog Explorer.

Step 6: Ask a business question

With attachments in silver, joined to tickets, we can ask questions that cross both:

Which Enterprise or Business customers asked for refunds?

Genie Code looks up tier and priority from the tickets and answers: T000739, T000161 and T004280. T004280 is also on the mismatch list, so that's the one a support lead should look at first.

Clip 6: Enterprise and Business refund requests: T000739, T000161 and T004280.

What about Agent Bricks Information Extraction? The docs describe a UI for it, but the Agents page in our Free Edition workspace doesn't offer it. Instead, a banner there points document workflows to Genie Code, which is exactly the path we took.

Coming later: real charity reports

Synthetic data proves the workflow works. Real documents show whether it holds up. In the series finale, Charity Lens (a public Databricks App comparing charities across the UK, Canada, Australia, the US and Poland), we'll run the same parse-and-extract pattern on real annual reports, extracting organisation-level fields only (name, year end, currency, income, expenditure) and using enableCitations so every number points back to its place on the page.

What we learned

Free Edition notes

Next up: real data is coming

48 synthetic PDFs were a rehearsal. The workflow Genie Code built today (parse, classify, extract with citations, land in silver, flag for review) works on any document. Over the next episodes our Support Copilot gets its retrieval, tools, evaluation and monitoring. Then, in the finale, we point everything at real public charity data from the UK, Canada, Australia, the US and Poland, and ship Charity Lens as a public Databricks App.


Sources: ai_parse_document (docs.databricks.com/aws/en/sql/language-manual/functions/ai_parse_document), ai_extract (…/functions/ai_extract), ai_classify (…/functions/ai_classify), Genie Code skills (docs.databricks.com/aws/en/genie-code/skills), March 2026 release notes (docs.databricks.com/aws/en/release-notes/product/2026/march), Free Edition limitations (docs.databricks.com/aws/en/getting-started/free-edition-limitations).