mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-28 00:00:38 +00:00
* feat(nace): add NDI document parse as an OCR provider Add a Rust OCR adapter for Nace Document Intelligence (NDI) Parse with the models nace/parse-low, nace/parse-medium and nace/parse-high. A public https link goes to Nace as a link. Any other document is uploaded with a one-time grant, parsed, and deleted after the call. The cost map bills each processed page at the price of the effort. * fix(nace): clean the job error before the OCR response hooks see it The copy of a Nace job that goes to the response hooks now has its error code and message cleaned and the deployment API key masked. The copy keeps the key order of the job. The password texts now say that the logging callbacks mask it. * fix(nace): accept include_image_base64 and never send it to Nace Clients that use the Mistral OCR request shape send the top-level include_image_base64 option. A host that passes every body field on sent it to Nace, which refuses an unknown field with a 422. The option is now accepted with any value and left out of the parse request, since Nace returns images as links (output.include_images), not base64. * fix(nace): map the pages option to Nace page_ranges Clients that use the Mistral OCR request shape select pages with the top-level pages option (0-based page indexes). The Python host dropped it, so Nace parsed and billed the whole document, and a host that passes every body field on sent it to Nace, which refuses it with a 422. The option is now sorted, deduplicated, shifted to 1-based pages and merged into page_ranges runs. An empty list parses the whole document. Values that are not non-negative integers, or pages together with page_ranges, are refused with a 400 before the upload. * test(nace): assert request headers without loops and drop a redundant doc line * fix(nace): refuse include_image_base64 true unless drop_params is on Nace returns images as links, never as base64, so a request asking for base64 images now gets the unsupported-param 400 that other OCR providers give for output they cannot return. drop_params drops it instead, and false or null are still accepted and never sent, which keeps Open WebUI's Mistral loader working * fix(nace): refuse output.include_images unless drop_params is on Nace returns image crops only as links that need the operator's Nace key and stop working once cleanup deletes the job, so image requests now get the same unsupported-param 400 as include_image_base64 and every job is deleted * fix(nace): bill only the requested pages when Nace omits billed units With page_ranges, the page count Nace reports covers the whole document, so a job without units now bills the requested pages that exist in the document instead of every page --------- Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
189 lines
7.2 KiB
Python
189 lines
7.2 KiB
Python
from io import BytesIO
|
|
from typing import Final
|
|
|
|
import pytest
|
|
|
|
import litellm
|
|
from litellm.types.utils import admin_api_key_secret_reference
|
|
from tests.test_litellm_rust.ocr.data import (
|
|
OCR_DOCUMENT,
|
|
OCR_RESPONSE,
|
|
call,
|
|
call_aocr,
|
|
call_ocr,
|
|
)
|
|
from tests.test_litellm_rust.support.recording_server import RecordingServer, ResponseSpec
|
|
from tests.test_litellm_rust.support.routing import assert_served_natively
|
|
|
|
pytestmark = pytest.mark.requires_rust_extension
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
|
|
@pytest.mark.parametrize("model", ["mistral/mistral-ocr-latest", "azure_ai/mistral-ocr-latest", "reducto/parse-v3"])
|
|
async def test_ocr_contract_native_format_supported(
|
|
server: RecordingServer,
|
|
asynchronous: bool,
|
|
model: str,
|
|
) -> None:
|
|
server.expected_requests = None
|
|
payload: Final = (
|
|
{"result": {"chunks": [{"content": "native OCR response"}]}, "usage": {"num_pages": 1}}
|
|
if model.startswith("reducto/")
|
|
else OCR_RESPONSE
|
|
)
|
|
server.default_response = ResponseSpec(body=payload)
|
|
arguments: Final = {
|
|
"model": model,
|
|
"req_format": "native",
|
|
"num_retries": 0,
|
|
"document": {"type": "document_url", "document_url": "reducto://ready.pdf"}
|
|
if model.startswith("reducto/")
|
|
else OCR_DOCUMENT,
|
|
}
|
|
response: Final = await call_aocr(server, **arguments) if asynchronous else call_ocr(server, **arguments)
|
|
assert response.pages[0].markdown == "native OCR response"
|
|
assert response.get_provider_native_response() == payload
|
|
assert len(server.requests) == 1
|
|
assert_served_natively(server, response)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
|
|
async def test_ocr_contract_nace_parses_a_public_link_into_pages(
|
|
server: RecordingServer,
|
|
asynchronous: bool,
|
|
) -> None:
|
|
source: Final = {"type": "url", "url": "https://docs.example/report.pdf", "file_name": "report.pdf"}
|
|
server.expected_requests = 2
|
|
server.default_response = ResponseSpec(
|
|
body={
|
|
"job_id": "job-1",
|
|
"status": "succeeded",
|
|
"source": source,
|
|
"units": 2,
|
|
"result": {
|
|
"document": {"markdown": "--- Page 1 ---\none\n\n--- Page 2 ---\ntwo", "page_count": 2, "blocks": []},
|
|
"disclosures": [],
|
|
},
|
|
}
|
|
)
|
|
response: Final = await call(
|
|
server,
|
|
asynchronous,
|
|
model="nace/parse-medium",
|
|
document={"type": "document_url", "document_url": source["url"]},
|
|
num_retries=0,
|
|
)
|
|
assert [page.markdown for page in response.pages] == ["one", "two"]
|
|
assert response.usage_info is not None and response.usage_info.pages_processed == 2
|
|
sent: Final = server.requests[0]
|
|
assert sent.path.startswith("/v1/documents/parse?wait_seconds=")
|
|
assert sent.headers["authorization"] == "Bearer test-key"
|
|
assert sent.body == {"source": source, "parse_mode": "medium", "output": {"include_page_markers": True}}
|
|
assert (server.requests[1].method, server.requests[1].path) == ("DELETE", "/v1/documents/jobs/job-1")
|
|
assert_served_natively(server, count=2)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
|
|
async def test_ocr_contract_unknown_reducto_model_reaches_provider(
|
|
server: RecordingServer,
|
|
asynchronous: bool,
|
|
) -> None:
|
|
server.default_response = ResponseSpec(body={"result": {"chunks": [{"content": "future model response"}]}})
|
|
arguments: Final = {
|
|
"model": "reducto/future-parse-model",
|
|
"document": {"type": "document_url", "document_url": "reducto://ready.pdf"},
|
|
"num_retries": 0,
|
|
}
|
|
response: Final = await call_aocr(server, **arguments) if asynchronous else call_ocr(server, **arguments)
|
|
assert response.model == "future-parse-model"
|
|
assert response.pages[0].markdown == "future model response"
|
|
assert len(server.requests) == 1
|
|
assert server.requests[0].path == "/parse"
|
|
assert server.requests[0].body == {"input": "reducto://ready.pdf"}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
|
|
async def test_native_azure_ocr_uses_token_provider_result_as_bearer_token(
|
|
server: RecordingServer, isolated_azure_auth: None, asynchronous: bool
|
|
) -> None:
|
|
calls: Final = []
|
|
|
|
def token_provider() -> str:
|
|
calls.append("token")
|
|
return "callback-token"
|
|
|
|
arguments: Final = {
|
|
"model": "azure_ai/mistral-ocr-latest",
|
|
"api_key": None,
|
|
"azure_ad_token_provider": token_provider,
|
|
}
|
|
response: Final = await call_aocr(server, **arguments) if asynchronous else call_ocr(server, **arguments)
|
|
|
|
assert calls == ["token"]
|
|
assert response.pages[0].markdown == "native OCR response"
|
|
assert_served_natively(server, response)
|
|
assert server.requests[0].headers["authorization"] == "Bearer callback-token"
|
|
|
|
|
|
def test_native_ocr_encodes_python_file_input_and_drops_unknown_arguments(server: RecordingServer) -> None:
|
|
response: Final = call_ocr(
|
|
server,
|
|
document={"type": "file", "file": BytesIO(b"abc"), "mime_type": "image/png"},
|
|
opaque_extension=object(),
|
|
)
|
|
|
|
assert response.pages[0].markdown == "native OCR response"
|
|
assert_served_natively(server, response)
|
|
assert server.requests[0].body == {
|
|
"model": "mistral-ocr-latest",
|
|
"document": {"type": "image_url", "image_url": "data:image/png;base64,YWJj"},
|
|
}
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"drop_params,global_drop_params",
|
|
[(True, False), (" TRUE ", False), (None, True), (False, True)],
|
|
ids=["per_call", "per_call_spelled", "global", "global_wins"],
|
|
)
|
|
def test_azure_document_intelligence_drop_params_drops_an_unsupported_output_content_format(
|
|
server: RecordingServer,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
drop_params: object,
|
|
global_drop_params: bool,
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "drop_params", global_drop_params)
|
|
server.default_response = ResponseSpec(
|
|
body={"status": "succeeded", "analyzeResult": {"pages": [{"pageNumber": 1, "lines": [{"content": "hello"}]}]}}
|
|
)
|
|
|
|
response: Final = call_ocr(
|
|
server,
|
|
model="azure_ai/doc-intelligence/prebuilt-layout",
|
|
outputContentFormat="html",
|
|
drop_params=drop_params,
|
|
)
|
|
|
|
assert_served_natively(server, response)
|
|
assert response.pages[0].markdown == "hello"
|
|
assert "outputContentFormat" not in server.requests[0].path
|
|
assert "drop_params" not in server.requests[0].path
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
|
|
async def test_ocr_sends_the_token_behind_an_admin_oidc_env_api_key(
|
|
server: RecordingServer, asynchronous: bool, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
monkeypatch.setenv("MISTRAL_SA_TOKEN", "env-token")
|
|
reference: Final = admin_api_key_secret_reference(
|
|
{"api_key": "oidc/env/MISTRAL_SA_TOKEN", "api_base": server.base_url}
|
|
)["api_key"]
|
|
|
|
response: Final = await call(server, asynchronous, api_key=reference)
|
|
|
|
assert server.requests[0].headers["authorization"] == "Bearer env-token"
|
|
assert_served_natively(server, response)
|