Skip to content

fix(azure_ai): preserve content, tables, and keyValuePairs in doc-intelligence /v1/ocr - #32018

Merged
mateo-berri merged 2 commits into
litellm_internal_stagingfrom
litellm_lit4151_azure_di_ocr_native_fields
Jul 3, 2026
Merged

mateo-berri merged 2 commits into
litellm_internal_stagingfrom
litellm_lit4151_azure_di_ocr_native_fields

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Relevant issues

Reported by a customer (Pylon #5296)

Linear ticket

Resolves LIT-4151

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have requested a Greptile review by commenting @greptileai and received a Confidence Score of at least 4/5 before requesting a maintainer review

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

End-to-end against a live local proxy hitting the real Azure Document Intelligence API (resource litellm-di-test-17f97.cognitiveservices.azure.com, real requests, no mocks). The before run is base litellm_internal_staging at 2633e8f; the after run is this PR's head d925bf9. Same venv, same port, same config both times. The test document is Azure's public layout sample PDF, which contains 2 tables and key-value pairs

Config (qa_config.yaml):

model_list:
  - model_name: azure-prebuilt-layout
    litellm_params:
      model: azure_ai/doc-intelligence/prebuilt-layout
      api_base: os.environ/AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT
      api_key: os.environ/AZURE_DOCUMENT_INTELLIGENCE_API_KEY
    model_info:
      mode: ocr
general_settings:
  master_key: sk-1234

Proxy start (identical for both runs, after checking out the respective commit; editable install picks up whatever is checked out):

set -a; source .env; set +a
python litellm/proxy/proxy_cli.py --config qa_config.yaml --port 24453

Before (base litellm_internal_staging, 2633e8f)

curl -s -X POST http://localhost:24453/v1/ocr \
  -H "Authorization: Bearer sk-1234" -H "Content-Type: application/json" \
  -d '{"model":"azure-prebuilt-layout","document":{"type":"document_url","document_url":"https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf"}}' \
  | jq '{has_content: has("content"), has_tables: has("tables"), has_keyValuePairs: has("keyValuePairs"), content_populated: (.content != null), tables_populated: (.tables != null), keyValuePairs_populated: (.keyValuePairs != null), page0_keys: (.pages[0]|keys)}'
{
  "has_content": false,
  "has_tables": false,
  "has_keyValuePairs": false,
  "content_populated": false,
  "tables_populated": false,
  "keyValuePairs_populated": false,
  "page0_keys": [
    "dimensions",
    "images",
    "index",
    "markdown"
  ]
}

Azure's native content, tables, and keyValuePairs are dropped entirely; only the Mistral-schema pages[].markdown survives

After (this PR, d925bf9)

Same curl as above:

{
  "has_content": true,
  "has_tables": true,
  "has_keyValuePairs": true,
  "content_populated": true,
  "tables_populated": true,
  "keyValuePairs_populated": false,
  "page0_keys": [
    "dimensions",
    "images",
    "index",
    "markdown"
  ]
}

content and tables are now populated (2813 chars and 2 tables for this document) and pages[].markdown is unchanged. keyValuePairs serializes as null here because Azure only computes key-value pairs when the features=keyValuePairs add-on is requested; requesting it through the new features param:

curl -s -X POST http://localhost:24453/v1/ocr \
  -H "Authorization: Bearer sk-1234" -H "Content-Type: application/json" \
  -d '{"model":"azure-prebuilt-layout","document":{"type":"document_url","document_url":"https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf"},"features":["keyValuePairs"]}' \
  | jq '{content_chars: (.content|length), tables: (.tables|length), keyValuePairs: (.keyValuePairs|length), page0_has_markdown: (.pages[0].markdown|length > 0)}'
{
  "content_chars": 2813,
  "tables": 2,
  "keyValuePairs": 22,
  "page0_has_markdown": true
}

Type

🐛 Bug Fix

Changes

The /v1/ocr endpoint normalizes Azure Document Intelligence (azure_ai/doc-intelligence/<model>) responses into the Mistral OCR schema and silently dropped Azure's native analyzeResult.content (full-document text), analyzeResult.tables, and analyzeResult.keyValuePairs. These are now passed through verbatim as top-level content, tables, and keyValuePairs fields on the OCR response, alongside the unchanged Mistral-schema fields. For other OCR providers the new fields simply serialize as null

Azure's analyze endpoint also takes a features query param, and features=keyValuePairs is required for Azure to return key-value pairs at all. features is now a supported OCR param for Azure DI: it accepts a list of feature names (e.g. ["keyValuePairs"]) or a comma-separated string, is validated against garbage input the same way pages is, and is emitted comma-joined on the analyze URL (e.g. &features=keyValuePairs,languages), combining correctly with pages

While fixing both transform paths, the near-duplicate sync and async response parsing bodies were consolidated into a single helper that validates the Azure operation payload with pydantic models, so the fix lands once instead of twice

Regression tests in tests/test_litellm/llms/azure_ai/test_azure_document_intelligence_ocr_transformation.py feed a realistic Azure analyzeResult payload through both transform paths and assert the native fields survive in the serialized response (via model_dump()), tolerate payloads without tables/keyValuePairs, and cover the features param mapping, URL building, and invalid-input rejection


Note

Medium Risk
Adds optional fields to the shared OCR response contract and changes Azure analyze URL/query handling; behavior is additive and covered by tests, but proxy clients may depend on the slimmer response shape.

Overview
Fixes Azure Document Intelligence OCR responses dropping analyzeResult.content, tables, and keyValuePairs when /v1/ocr normalizes to the Mistral OCR shape. Those values are now copied to top-level content, tables, and keyValuePairs on OCRResponse (other providers leave them null).

Adds Azure’s features analyze query param (e.g. keyValuePairs) with the same style of validation as pages, URL emission in get_complete_url, and map_ocr_params updates so callers can request key-value extraction.

Refactors sync/async Azure response handling into shared _get_polling_target / _transform_completed_response with Pydantic models for the operation payload, so polling and parsing live in one place.

Reviewed by Cursor Bugbot for commit 8735f49. Bugbot is set up for automated code reviews on this repo. Configure here.

…elligence /v1/ocr

Azure Document Intelligence analyzeResult.content, .tables, and
.keyValuePairs were dropped when normalizing to the Mistral OCR schema.
They are now passed through verbatim as top-level response fields, and
the duplicated sync/async response parsing is consolidated into one
pydantic-validated helper.

Also adds the Azure DI features query param (list[str] or
comma-separated string, e.g. features=keyValuePairs) which Azure
requires for keyValuePairs extraction.
@greptile-apps

greptile-apps Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes the /v1/ocr Azure Document Intelligence path, which was silently dropping analyzeResult.content, analyzeResult.tables, and analyzeResult.keyValuePairs from every response, and adds a new features query-parameter pass-through so callers can enable Azure add-ons like keyValuePairs at request time.

  • Response passthrough: Adds Pydantic models (AzureDocumentIntelligenceOperation, AzureDocumentIntelligenceAnalyzeResult, AzureDocumentIntelligencePage, AzureDocumentIntelligenceLine) to parse the completed operation payload with type safety, then surfaces content, tables, and keyValuePairs as top-level fields on OCRResponse; non-Azure providers are unaffected since the fields default to None.
  • Features param: _normalize_features_param validates and normalizes a list-or-string input against a strict ^[A-Za-z][A-Za-z0-9]*$ regex, and get_complete_url appends it as &features=... alongside the existing pages param.
  • Deduplication: Near-identical sync and async response-parsing bodies are consolidated into a single _transform_completed_response helper, with _get_polling_target extracting the shared 202 branch logic.

Confidence Score: 5/5

Safe to merge — the change is narrowly scoped to the Azure DI OCR transformation path, all logic is covered by new mock-based unit tests, and existing provider behavior is unchanged.

The fix correctly preserves Azure-native fields that were always present in the API response but never forwarded. The refactor consolidates two near-identical code paths into a single well-tested helper without changing external behavior. Input validation for the new features param is strict and fully tested, including injection-style inputs and type mismatches. No auth, routing, or cross-provider logic is touched.

No files require special attention.

Important Files Changed

Filename Overview
litellm/llms/azure_ai/ocr/document_intelligence/transformation.py Major refactor: adds Pydantic models for Azure DI response, consolidates sync/async response parsing into _transform_completed_response, adds features param support, and preserves content/tables/keyValuePairs in the OCR response.
litellm/llms/base_llm/ocr/transformation.py Adds three new optional fields (content, tables, keyValuePairs) to the shared OCRResponse base class; for non-Azure providers they serialize as null with no effect.
tests/test_litellm/llms/azure_ai/test_azure_document_intelligence_ocr_transformation.py New comprehensive unit tests covering native field passthrough, async path, missing-fields tolerance, error status handling, features param mapping, URL building, and invalid-input rejection — all using in-memory httpx.Response mocks, no network calls.
tests/ocr_tests/test_ocr_azure_document_intelligence.py Existing test renamed and assertion updated from ["pages"] to ["pages", "features"] to reflect the newly advertised features param — correctly tracks the extended interface.

Reviews (2): Last reviewed commit: "test(azure_ai): replace fastapi jsonable..." | Re-trigger Greptile

@codecov

codecov Bot commented Jul 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.02439% with 9 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...ure_ai/ocr/document_intelligence/transformation.py 88.60% 9 Missing ⚠️

📢 Thoughts on this report? Let us know!

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 8735f49. Configure here.

@mateo-berri mateo-berri left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM; thanks!

@mateo-berri
mateo-berri enabled auto-merge (squash) July 3, 2026 03:50
@mateo-berri
mateo-berri merged commit ae356cf into litellm_internal_staging Jul 3, 2026
79 checks passed
@mateo-berri
mateo-berri deleted the litellm_lit4151_azure_di_ocr_native_fields branch July 3, 2026 05:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants