The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(extraction): add /v1/extraction with Cloudflare Clairic support (#47473)
Mateo Wang9fbeebc98835
diff --git a/.github/workflows/test-unit.yml b/.github/workflows/test-unit.ymlindex 2b9263f0430..c593acbe8fb 100644--- a/.github/workflows/test-unit.yml+++ b/.github/workflows/test-unit.yml@@ -139,6 +139,7 @@ jobs:test-path: |-tests/unit/batch_completiontests/unit/decisions+ tests/unit/extractiontests/unit/litellm_core_utilstests/unit/systemonepython-version: "3.12"diff --git a/gateway/routes/allowlist.py b/gateway/routes/allowlist.pyindex cced49f788a..cc87a2ed16b 100644--- a/gateway/routes/allowlist.py+++ b/gateway/routes/allowlist.py@@ -1,7 +1,7 @@"""Path allowlist for the gateway component.The gateway exposes the LLM data-plane surface: chat/completions, embeddings,-audio, batches, files, fine-tuning, rerank, decisions, ocr, rag, video, search, image,+audio, batches, files, fine-tuning, rerank, decisions, extraction, ocr, rag, video, search, image,responses, vector stores, passthrough providers, realtime websockets, MCPtool-call endpoints, and operational endpoints (/health, /metrics, and the/debug/memory/summary read of the serving worker's RSS).@@ -64,6 +64,8 @@ GATEWAY_PATH_PREFIXES: tuple[str, ...] = ("/decisions","/v1/systemone","/systemone",+ "/v1/extraction",+ "/extraction","/v1/ocr","/ocr","/v1/rag/",diff --git a/litellm/__init__.py b/litellm/__init__.pyindex f6604a3b4e5..1784deeb797 100644--- a/litellm/__init__.py+++ b/litellm/__init__.py@@ -1505,6 +1505,7 @@ from .rag.main import *from .sandbox.main import *from .decisions.main import *from .systemone.main import *+from .extraction.main import *from .tool_loop import ToolLoopMaxRoundsExceeded, arun_tool_loop, run_tool_loopfrom .search.main import *from .realtime_api.main import (@@ -1711,6 +1712,9 @@ if TYPE_CHECKING:from .llms.cloudflare.decisions.transformation import (CloudflareDecisionsConfig as CloudflareDecisionsConfig,)+ from .llms.cloudflare.extraction.transformation import (+ CloudflareExtractionConfig as CloudflareExtractionConfig,+ )from .llms.strands_decider.decisions.transformation import (StrandsDeciderDecisionsConfig as StrandsDeciderDecisionsConfig,)diff --git a/litellm/_lazy_imports_registry.py b/litellm/_lazy_imports_registry.pyindex 8abc24d1417..e0cb7c680bc 100644--- a/litellm/_lazy_imports_registry.py+++ b/litellm/_lazy_imports_registry.py@@ -166,6 +166,7 @@ LLM_CONFIG_NAMES: Final = ("OpenRouterDecisionsConfig","FireworksAIDecisionsConfig","CloudflareDecisionsConfig",+ "CloudflareExtractionConfig","StrandsDeciderDecisionsConfig","DatabricksDecisionsConfig","HostedVLLMDecisionsConfig",@@ -735,6 +736,7 @@ _LLM_CONFIGS_IMPORT_MAP: Final = {"OpenRouterDecisionsConfig": (".llms.openrouter.decisions.transformation", "OpenRouterDecisionsConfig"),"FireworksAIDecisionsConfig": (".llms.fireworks_ai.decisions.transformation", "FireworksAIDecisionsConfig"),"CloudflareDecisionsConfig": (".llms.cloudflare.decisions.transformation", "CloudflareDecisionsConfig"),+ "CloudflareExtractionConfig": (".llms.cloudflare.extraction.transformation", "CloudflareExtractionConfig"),"StrandsDeciderDecisionsConfig": (".llms.strands_decider.decisions.transformation","StrandsDeciderDecisionsConfig",diff --git a/litellm/cost_calculator.py b/litellm/cost_calculator.pyindex 67178c8959c..f952883bc87 100644--- a/litellm/cost_calculator.py+++ b/litellm/cost_calculator.py@@ -112,6 +112,7 @@ from litellm.llms.xai.cost_calculator import cost_per_token as xai_cost_per_tokefrom litellm.responses.utils import ResponseAPILoggingUtilsfrom litellm.types.agents import LiteLLMSendMessageResponsefrom litellm.types.decisions import DecisionsResponse, DecisionsUsage, OpenAIDecisionResponse, OpenAIDecisionUsage+from litellm.types.extraction import ExtractionResponse, ExtractionUsagefrom litellm.types.llms.base import CachedTokensDetails, LiteLLMBaseModelfrom litellm.types.llms.openai import (HttpxBinaryResponseContent,@@ -1171,6 +1172,8 @@ def get_usage_object(if isinstance(completion_response, (DecisionsResponse, OpenAIDecisionResponse)):return None if completion_response.usage is None else _decisions_usage(completion_response.usage)+ if isinstance(completion_response, ExtractionResponse):+ return _extraction_usage(completion_response.usage)if isinstance(completion_response, HttpxBinaryResponseContent):return completion_response.usageif usage_obj is None:@@ -1227,6 +1230,14 @@ def _decisions_usage(usage: DecisionsUsage | OpenAIDecisionUsage) -> Usage:)+def _extraction_usage(usage: ExtractionUsage) -> Usage:+ return Usage(+ prompt_tokens=usage.input_tokens,+ completion_tokens=usage.output_tokens,+ total_tokens=usage.input_tokens + usage.output_tokens,+ )++def _is_known_usage_objects(usage_obj):"""Returns True if the usage obj is a known Usage type"""return (@@ -1234,6 +1245,7 @@ def _is_known_usage_objects(usage_obj):or isinstance(usage_obj, ResponseAPIUsage)or isinstance(usage_obj, DecisionsUsage)or isinstance(usage_obj, OpenAIDecisionUsage)+ or isinstance(usage_obj, ExtractionUsage)or TranscriptionUsageObjectTransformation.is_transcription_usage_object(usage_obj))@@ -1263,6 +1275,8 @@ def infer_call_type(call_type: CallTypesLiteral | None, completion_response: objreturn "send_message"elif isinstance(completion_response, (DecisionsResponse, OpenAIDecisionResponse)):return "adecisions"+ elif isinstance(completion_response, ExtractionResponse):+ return "aextraction"return call_type@@ -1674,6 +1688,8 @@ def completion_cost()if isinstance(usage_obj, (DecisionsUsage, OpenAIDecisionUsage)):_usage = _decisions_usage(usage_obj).model_dump()+ elif isinstance(usage_obj, ExtractionUsage):+ _usage = _extraction_usage(usage_obj).model_dump()elif usage_obj is None:_usage = {}elif isinstance(usage_obj, BaseModel):@@ -2199,7 +2215,8 @@ def response_cost_calculator(| Response| SearchResponse| DecisionsResponse- | OpenAIDecisionResponse,+ | OpenAIDecisionResponse+ | ExtractionResponse,model: str,custom_llm_provider: str | None,call_type: Literal[@@ -2225,6 +2242,8 @@ def response_cost_calculator("adecisions","systemone","asystemone",+ "extraction",+ "aextraction",],optional_params: dict,cache_hit: bool | None = None,diff --git a/litellm/extraction/__init__.py b/litellm/extraction/__init__.pynew file mode 100644index 00000000000..bdacdae6ea4--- /dev/null+++ b/litellm/extraction/__init__.py@@ -0,0 +1,3 @@+from litellm.extraction.main import aextraction, extraction++__all__ = ["aextraction", "extraction"]diff --git a/litellm/extraction/main.py b/litellm/extraction/main.pynew file mode 100644index 00000000000..94198e911ef--- /dev/null+++ b/litellm/extraction/main.py@@ -0,0 +1,351 @@+import asyncio+from collections.abc import Mapping, Sequence+from dataclasses import dataclass+from functools import partial+from types import MappingProxyType+from typing import Final, TypeAlias++import httpx+from pydantic import TypeAdapter, ValidationError++import litellm+from litellm.decisions.call import log_caller_request+from litellm.litellm_core_utils.core_helpers import get_metadata_variable_name_from_kwargs+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+from litellm.litellm_core_utils.tool_fields import DropPolicy, drop_policy+from litellm.llms.base_llm.chat.transformation import BaseLLMException+from litellm.llms.base_llm.extraction.transformation import BaseExtractionConfig+from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler+from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler+from litellm.types.extraction import (+ EXTRACTION_STATE_REWRITTEN_METADATA_KEY,+ ExtractionAnswer,+ ExtractionBase64Image,+ ExtractionField,+ ExtractionOptions,+ ExtractionRequestBody,+ ExtractionResponse,+)+from litellm.types.router import GenericLiteLLMParams+from litellm.types.utils import LlmProviders, is_litellm_owned_kwarg+from litellm.utils import (+ ProviderConfigManager,+ client, # pyright: ignore[reportUnknownVariableType] # client is an untyped decorator+ get_model_cost_key,+)++ExtractionFields: TypeAlias = Mapping[str, ExtractionField | Mapping[str, object]]+ExtractionImages: TypeAlias = Sequence[str | ExtractionBase64Image | Mapping[str, object]]+ExtractionOptionsParam: TypeAlias = ExtractionOptions | Mapping[str, object]++_REQUEST_ADAPTER: Final[TypeAdapter[ExtractionRequestBody]] = TypeAdapter(ExtractionRequestBody)+_METADATA_ADAPTER: Final[TypeAdapter[Mapping[str, object]]] = TypeAdapter(Mapping[str, object])+_HANDLER: Final = BaseLLMHTTPHandler()+_LOCAL_KWARGS: Final = frozenset(+ (+ *GenericLiteLLMParams.model_fields,+ "extra_headers",+ "base_url",+ "default_headers",+ "deployment_id",+ "additional_drop_params",+ )+)+++@dataclass(frozen=True, slots=True, repr=False)+class _ExtractionCall:+ model: str+ requested_model: str+ custom_llm_provider: str+ provider_config: BaseExtractionConfig+ body: Mapping[str, object]+ api_base: str+ api_key: str | None+ logging_obj: LiteLLMLoggingObj | None+ headers: Mapping[str, str]+ timeout: float | httpx.Timeout | None+ litellm_params: Mapping[str, object]+ client: HTTPHandler | AsyncHTTPHandler | None+++def supported_extraction_providers() -> tuple[str, ...]:+ return tuple(+ provider.value+ for provider in LlmProviders+ if ProviderConfigManager.get_provider_extraction_config(model="", provider=provider) is not None+ )+++def _provider_config(model: str, custom_llm_provider: str) -> BaseExtractionConfig:+ provider: Final = next((member for member in LlmProviders if member.value == custom_llm_provider), None)+ provider_config: Final = (+ None if provider is None else ProviderConfigManager.get_provider_extraction_config(model, provider)+ )+ if provider_config is None:+ raise litellm.BadRequestError(+ message=(+ f"Unknown Extraction provider '{custom_llm_provider}'. "+ f"Supported providers: {', '.join(supported_extraction_providers())}"+ ),+ model=model,+ llm_provider=custom_llm_provider,+ )+ return provider_config+++def _request_fields(+ *,+ state: str | None,+ fields: ExtractionFields | None,+ images: ExtractionImages | None,+ reference_date: str | None,+ options: ExtractionOptionsParam | None,+) -> Mapping[str, object]:+ sent: Final[Mapping[str, object | None]] = MappingProxyType(+ {"state": state, "fields": fields, "images": images, "reference_date": reference_date, "options": options}+ )+ return MappingProxyType({name: value for name, value in sent.items() if value is not None})+++def _is_unsupported(name: str, value: object, policy: DropPolicy) -> bool:+ return (+ value is not None+ and value is not False+ and name not in _LOCAL_KWARGS+ and not is_litellm_owned_kwarg(name)+ and not policy.drops(name)+ )+++def _unsupported_params(kwargs: Mapping[str, object]) -> tuple[str, ...]:+ policy: Final = drop_policy(kwargs)+ return tuple(sorted(name for name, value in kwargs.items() if _is_unsupported(name, value, policy)))+++def _prepare_call(+ *,+ model: str,+ request_fields: Mapping[str, object],+ api_key: str | None,+ api_base: str | None,+ timeout: float | httpx.Timeout | None,+ custom_llm_provider: str | None,+ extra_headers: Mapping[str, str] | None,+ kwargs: Mapping[str, object],+) -> _ExtractionCall:+ log_caller_request(kwargs, request_fields)+ upstream_model, provider, dynamic_api_key, dynamic_api_base = litellm.get_llm_provider(+ model=model,+ custom_llm_provider=custom_llm_provider,+ api_base=api_base,+ api_key=api_key,+ )+ provider_config: Final = _provider_config(model, provider)+ unsupported: Final = _unsupported_params(kwargs)+ if unsupported:+ raise litellm.UnsupportedParamsError(+ message=(+ f"{provider} does not support parameters: {list(unsupported)}, for model={model}. "+ "To drop these, set `litellm.drop_params=True` or for proxy:\n\n"+ "`litellm_settings:\n drop_params: true`\n"+ ),+ model=model,+ llm_provider=provider,+ )+ try:+ request: Final = _REQUEST_ADAPTER.validate_python(request_fields)+ except ValidationError as error:+ raise litellm.BadRequestError(+ message=f"Invalid Extraction request: {error}", model=model, llm_provider=provider+ ) from error+ canonical_model: Final = provider_config.canonical_model(upstream_model)+ resolved_api_base: Final = provider_config.resolve_api_base(dynamic_api_base or api_base)+ if resolved_api_base is None:+ raise litellm.BadRequestError(+ message=provider_config.missing_api_base_message(provider), model=model, llm_provider=provider+ )+ resolved_api_key: Final = provider_config.resolve_api_key(dynamic_api_key or api_key)+ if resolved_api_key is None:+ raise litellm.BadRequestError(+ message=f"Missing API key for Extraction provider '{provider}'", model=model, llm_provider=provider+ )+ logging_obj: Final = kwargs.get("litellm_logging_obj")+ http_client: Final = kwargs.get("client")+ if isinstance(logging_obj, LiteLLMLoggingObj):+ logging_obj.update_from_kwargs( # pyright: ignore[reportUnknownMemberType] # Logging takes untyped dicts+ kwargs=dict(kwargs),+ model=canonical_model,+ litellm_params={+ "litellm_call_id": kwargs.get("litellm_call_id"),+ "api_base": provider_config.get_complete_url(resolved_api_base, canonical_model),+ },+ custom_llm_provider=provider,+ )+ return _ExtractionCall(+ model=canonical_model,+ requested_model=model,+ custom_llm_provider=provider,+ provider_config=provider_config,+ body=provider_config.transform_extraction_request(canonical_model, request),+ api_base=resolved_api_base,+ api_key=resolved_api_key,+ logging_obj=logging_obj if isinstance(logging_obj, LiteLLMLoggingObj) else None,+ headers=MappingProxyType(dict(extra_headers or {})),+ timeout=timeout,+ litellm_params=kwargs,+ client=http_client if isinstance(http_client, HTTPHandler | AsyncHTTPHandler) else None,+ )+++def _state_rewritten_by_guardrail(litellm_params: Mapping[str, object]) -> bool:+ metadata: Final = litellm_params.get(get_metadata_variable_name_from_kwargs(litellm_params))+ return (+ isinstance(metadata, Mapping)+ and _METADATA_ADAPTER.validate_python(metadata).get(EXTRACTION_STATE_REWRITTEN_METADATA_KEY) is True+ )+++def _without_spans(answers: Mapping[str, ExtractionAnswer]) -> Mapping[str, ExtractionAnswer]:+ return {name: answer.model_copy(update={"span": None, "spans": None}) for name, answer in answers.items()}+++def _formatted_response(response: ExtractionResponse, call: _ExtractionCall) -> ExtractionResponse:+ spans_index_hidden_text: Final = response.state_text is None and _state_rewritten_by_guardrail(call.litellm_params)+ formatted: Final = response.model_copy(+ update={+ "model": call.requested_model,+ **({"answers": _without_spans(response.answers)} if spans_index_hidden_text else {}),+ }+ )+ formatted.set_hidden_params(+ {+ "model": f"{call.custom_llm_provider}/{call.model}",+ "custom_llm_provider": call.custom_llm_provider,+ "provider_response_model": (+ get_model_cost_key(f"{call.custom_llm_provider}/{response.model}")+ or f"{call.custom_llm_provider}/{call.model}"+ ),+ }+ )+ return formatted+++def _upstream_exception(error: Exception, call: _ExtractionCall) -> Exception:+ if isinstance(error, BaseLLMException) and error.status_code_is_synthesized:+ return litellm.APIConnectionError(+ message=f"{call.custom_llm_provider.capitalize()}Exception - {error.message}",+ llm_provider=call.custom_llm_provider,+ model=f"{call.custom_llm_provider}/{call.model}",+ )+ return litellm.exception_type( # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType] # untyped+ model=f"{call.custom_llm_provider}/{call.model}",+ custom_llm_provider=call.custom_llm_provider,+ original_exception=error,+ )+++async def _asend(call: _ExtractionCall) -> ExtractionResponse:+ try:+ response: Final = await _HANDLER.aextraction(+ model=call.model,+ custom_llm_provider=call.custom_llm_provider,+ logging_obj=call.logging_obj,+ provider_config=call.provider_config,+ body=call.body,+ api_base=call.api_base,+ api_key=call.api_key,+ headers=call.headers,+ timeout=call.timeout,+ litellm_params=call.litellm_params,+ client=call.client if isinstance(call.client, AsyncHTTPHandler) else None,+ )+ except Exception as error:+ raise _upstream_exception(error, call) from error+ return _formatted_response(response, call)+++def _send(call: _ExtractionCall) -> ExtractionResponse:+ try:+ response: Final = _HANDLER.extraction(+ model=call.model,+ custom_llm_provider=call.custom_llm_provider,+ logging_obj=call.logging_obj,+ provider_config=call.provider_config,+ body=call.body,+ api_base=call.api_base,+ api_key=call.api_key,+ headers=call.headers,+ timeout=call.timeout,+ litellm_params=call.litellm_params,+ client=call.client if isinstance(call.client, HTTPHandler) else None,+ )+ except Exception as error:+ raise _upstream_exception(error, call) from error+ return _formatted_response(response, call)+++@client+async def aextraction(+ model: str,+ fields: ExtractionFields,+ state: str | None = None,+ images: ExtractionImages | None = None,+ reference_date: str | None = None,+ options: ExtractionOptionsParam | None = None,+ api_key: str | None = None,+ api_base: str | None = None,+ timeout: float | httpx.Timeout | None = None,+ custom_llm_provider: str | None = None,+ extra_headers: Mapping[str, str] | None = None,+ **kwargs: object, # kwargs-ok: litellm_params forwarded by @client+) -> ExtractionResponse:+ call: Final = await asyncio.to_thread(+ partial(+ _prepare_call,+ model=model,+ request_fields=_request_fields(+ state=state, fields=fields, images=images, reference_date=reference_date, options=options+ ),+ api_key=api_key,+ api_base=api_base,+ timeout=timeout,+ custom_llm_provider=custom_llm_provider,+ extra_headers=extra_headers,+ kwargs=kwargs,+ )+ )+ return await _asend(call)+++@client+def extraction(+ model: str,+ fields: ExtractionFields,+ state: str | None = None,+ images: ExtractionImages | None = None,+ reference_date: str | None = None,+ options: ExtractionOptionsParam | None = None,+ api_key: str | None = None,+ api_base: str | None = None,+ timeout: float | httpx.Timeout | None = None,+ custom_llm_provider: str | None = None,+ extra_headers: Mapping[str, str] | None = None,+ **kwargs: object, # kwargs-ok: litellm_params forwarded by @client+) -> ExtractionResponse:+ call: Final = _prepare_call(+ model=model,+ request_fields=_request_fields(+ state=state, fields=fields, images=images, reference_date=reference_date, options=options+ ),+ api_key=api_key,+ api_base=api_base,+ timeout=timeout,+ custom_llm_provider=custom_llm_provider,+ extra_headers=extra_headers,+ kwargs=kwargs,+ )+ return _send(call)+++__all__ = ["aextraction", "extraction"]diff --git a/litellm/litellm_core_utils/health_check_helpers.py b/litellm/litellm_core_utils/health_check_helpers.pyindex 03af9076c79..b19bcd941fa 100644--- a/litellm/litellm_core_utils/health_check_helpers.py+++ b/litellm/litellm_core_utils/health_check_helpers.py@@ -4,6 +4,7 @@ Helper functions for health check calls.import base64from collections.abc import Awaitable, Callable, Mapping+from types import MappingProxyTypefrom typing import TYPE_CHECKING, Final, Literalfrom litellm.llms.base_llm.ocr.transformation import DocumentType@@ -25,6 +26,9 @@ IMAGE_EDIT_HEALTH_CHECK_PROMPT: Final = ()ANTHROPIC_MESSAGES_HEALTH_CHECK_MAX_TOKENS: Final = 16+EXTRACTION_HEALTH_CHECK_FIELDS: Final[Mapping[str, Mapping[str, str]]] = MappingProxyType(+ {"reachable": MappingProxyType({"type": "text", "instructions": "Any word from the text"})}+)def native_health_check_mode(model: str, custom_llm_provider: str | None) -> Literal["anthropic_messages"] | None:@@ -215,6 +219,7 @@ class HealthCheckHelpers:"anthropic_messages","ocr","decisions",+ "extraction",],Callable,]:@@ -237,7 +242,11 @@ class HealthCheckHelpers:from litellm.litellm_core_utils.audio_utils.utils import (get_audio_file_for_health_check,)- from litellm.litellm_core_utils.health_check_utils import DECISIONS_CALL_PARAMS, _filter_model_params+ from litellm.litellm_core_utils.health_check_utils import (+ DECISIONS_CALL_PARAMS,+ EXTRACTION_CALL_PARAMS,+ _filter_model_params,+ )from litellm.realtime_api.main import realtime_health_checkreturn {@@ -322,4 +331,13 @@ class HealthCheckHelpers:})),+ "extraction": lambda: litellm.aextraction(+ **EXTRACTION_CALL_PARAMS.validate_python(+ {+ "state": prompt or "health check",+ "fields": EXTRACTION_HEALTH_CHECK_FIELDS,+ **_filter_model_params(model_params=model_params),+ }+ )+ ),}diff --git a/litellm/litellm_core_utils/health_check_utils.py b/litellm/litellm_core_utils/health_check_utils.pyindex 9b344d08d4b..74b6f6dea5d 100644--- a/litellm/litellm_core_utils/health_check_utils.py+++ b/litellm/litellm_core_utils/health_check_utils.py@@ -8,8 +8,10 @@ from typing import Finalfrom pydantic import TypeAdapterfrom litellm.types.decisions import DecisionsCallParams+from litellm.types.extraction import ExtractionCallParamsDECISIONS_CALL_PARAMS: Final[TypeAdapter[DecisionsCallParams]] = TypeAdapter(DecisionsCallParams)+EXTRACTION_CALL_PARAMS: Final[TypeAdapter[ExtractionCallParams]] = TypeAdapter(ExtractionCallParams)OPTIONAL_STR: Final[TypeAdapter[str | None]] = TypeAdapter(str | None)diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.pyindex 004dd7b65a5..473666e5ba1 100644--- a/litellm/litellm_core_utils/litellm_logging.py+++ b/litellm/litellm_core_utils/litellm_logging.py@@ -132,6 +132,7 @@ from litellm.responses.utils import ResponseAPILoggingUtilsfrom litellm.types.agents import LiteLLMSendMessageResponsefrom litellm.types.containers.main import ContainerObjectfrom litellm.types.decisions import DecisionsResponse, OpenAIDecisionResponse+from litellm.types.extraction import ExtractionResponsefrom litellm.types.integrations.s3_v2 import S3PartitionGranularityfrom litellm.types.interactions import (InteractionsAPIResponse,@@ -2922,6 +2923,7 @@ class Logging(LiteLLMLoggingBaseClass):or isinstance(logging_result, SearchResponse) # Search APIor isinstance(logging_result, DecisionsResponse)or isinstance(logging_result, OpenAIDecisionResponse)+ or isinstance(logging_result, ExtractionResponse)or (isinstance(logging_result, InteractionsAPIResponse)and logging_result.usage is not Nonediff --git a/litellm/llms/base_llm/extraction/__init__.py b/litellm/llms/base_llm/extraction/__init__.pynew file mode 100644index 00000000000..fe48996e8b4--- /dev/null+++ b/litellm/llms/base_llm/extraction/__init__.py@@ -0,0 +1,3 @@+from .transformation import BaseExtractionConfig++__all__ = ["BaseExtractionConfig"]diff --git a/litellm/llms/base_llm/extraction/transformation.py b/litellm/llms/base_llm/extraction/transformation.pynew file mode 100644index 00000000000..8461256b883--- /dev/null+++ b/litellm/llms/base_llm/extraction/transformation.py@@ -0,0 +1,86 @@+from abc import ABC, abstractmethod+from collections.abc import Mapping+from typing import Final++import httpx+from pydantic import TypeAdapter, ValidationError++from litellm.llms.base_llm.chat.transformation import BaseLLMException+from litellm.secret_managers.main import get_secret_str+from litellm.types.extraction import ExtractionRequestBody, ExtractionResponse++_PAYLOAD_ADAPTER: Final[TypeAdapter[object]] = TypeAdapter(object)+_RESPONSE_ADAPTER: Final[TypeAdapter[ExtractionResponse]] = TypeAdapter(ExtractionResponse)+_RESERVED_HEADERS: Final[frozenset[str]] = frozenset({"authorization", "content-type"})+++class BaseExtractionConfig(ABC):+ api_key_env: tuple[str, ...] = ()+ api_base_env: tuple[str, ...] = ()++ def get_default_api_base(self) -> str | None:+ return None++ def missing_api_base_message(self, custom_llm_provider: str) -> str:+ return f"api_base is required for Extraction provider '{custom_llm_provider}'"++ def resolve_api_base(self, api_base: str | None) -> str | None:+ return api_base or self._first_secret(self.api_base_env) or self.get_default_api_base()++ def resolve_api_key(self, api_key: str | None) -> str | None:+ return api_key or self._first_secret(self.api_key_env)++ @staticmethod+ def _first_secret(names: tuple[str, ...]) -> str | None:+ return next((value for value in (get_secret_str(name) for name in names) if value), None)++ def canonical_model(self, model: str) -> str:+ return model++ def request_model(self, model: str) -> str:+ return model++ def validate_environment(+ self,+ headers: Mapping[str, str],+ model: str,+ api_key: str | None,+ litellm_params: Mapping[str, object],+ ) -> Mapping[str, str]:+ return {+ **{name: value for name, value in headers.items() if name.lower() not in _RESERVED_HEADERS},+ **({"Authorization": f"Bearer {api_key}"} if api_key is not None else {}),+ "Content-Type": "application/json",+ }++ @abstractmethod+ def get_complete_url(self, api_base: str, model: str) -> str: ...++ def transform_extraction_request(self, model: str, request: ExtractionRequestBody) -> Mapping[str, object]:+ return {**request.model_dump(mode="json", exclude_unset=True), "model": self.request_model(model)}++ def unwrap_response(self, payload: object) -> object:+ return payload++ def transform_extraction_response(+ self,+ model: str,+ custom_llm_provider: str,+ raw_response: httpx.Response,+ ) -> ExtractionResponse:+ payload: Final[object] = _PAYLOAD_ADAPTER.validate_json(raw_response.content)+ try:+ return _RESPONSE_ADAPTER.validate_python(self.unwrap_response(payload))+ except ValidationError as error:+ raise BaseLLMException(+ status_code=500,+ message=f"Extraction provider '{custom_llm_provider}' returned an unexpected response: {error}",+ ) from error++ def get_error_class(+ self,+ error_message: str,+ status_code: int,+ headers: Mapping[str, str] | httpx.Headers,+ ) -> BaseLLMException:+ return BaseLLMException(status_code=status_code, message=error_message, headers=httpx.Headers(headers))diff --git a/litellm/llms/cloudflare/common_utils.py b/litellm/llms/cloudflare/common_utils.pynew file mode 100644index 00000000000..9f1293cb9c4--- /dev/null+++ b/litellm/llms/cloudflare/common_utils.py@@ -0,0 +1,53 @@+from collections.abc import Mapping+from typing import Final++from pydantic import TypeAdapter, ValidationError++from litellm.secret_managers.main import (+ get_secret_str,+ normalize_nonempty_secret_str,+)++CLOUDFLARE_MISSING_API_BASE_MESSAGE: Final = (+ "Missing CLOUDFLARE_ACCOUNT_ID - set CLOUDFLARE_ACCOUNT_ID or pass api_base explicitly"+)+_RESPONSE_MAPPING_ADAPTER: Final[TypeAdapter[Mapping[str, object]]] = TypeAdapter(Mapping[str, object])+++def workers_ai_default_api_base() -> str | None:+ account_id: Final = normalize_nonempty_secret_str(get_secret_str("CLOUDFLARE_ACCOUNT_ID"))+ if account_id is None:+ return None+ return f"https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/run"+++def workers_ai_canonical_model(model: str) -> str:+ if model.startswith("@cf/"):+ return model+ return f"@cf/cloudflare/{model}"+++def workers_ai_request_model(model: str) -> str:+ return model.rsplit("/", maxsplit=1)[-1]+++def workers_ai_run_url(api_base: str, model: str) -> str:+ normalized_api_base: Final = api_base.rstrip("/")+ if normalized_api_base.endswith("/ai/v1"):+ return f"{normalized_api_base.removesuffix('/ai/v1')}/ai/run/{model}"+ if normalized_api_base.endswith("/ai/run"):+ return f"{normalized_api_base}/{model}"+ return f"{normalized_api_base}/ai/run/{model}"+++def unwrap_workers_ai_result(payload: object) -> object:+ try:+ response_mapping: Final = _RESPONSE_MAPPING_ADAPTER.validate_python(payload)+ except ValidationError:+ return payload+ if "answers" in response_mapping:+ return response_mapping+ try:+ return _RESPONSE_MAPPING_ADAPTER.validate_python(response_mapping.get("result"))+ except ValidationError:+ return response_mappingdiff --git a/litellm/llms/cloudflare/decisions/transformation.py b/litellm/llms/cloudflare/decisions/transformation.pyindex 967935edfb4..7c776367886 100644--- a/litellm/llms/cloudflare/decisions/transformation.py+++ b/litellm/llms/cloudflare/decisions/transformation.py@@ -1,16 +1,13 @@-from collections.abc import Mapping-from typing import Final--from pydantic import TypeAdapter, ValidationError-from litellm.llms.base_llm.decisions.transformation import BaseDecisionsConfig-from litellm.secret_managers.main import (- get_secret_str,- normalize_nonempty_secret_str,+from litellm.llms.cloudflare.common_utils import (+ CLOUDFLARE_MISSING_API_BASE_MESSAGE,+ unwrap_workers_ai_result,+ workers_ai_canonical_model,+ workers_ai_default_api_base,+ workers_ai_request_model,+ workers_ai_run_url,)-_RESPONSE_MAPPING_ADAPTER: Final[TypeAdapter[Mapping[str, object]]] = TypeAdapter(Mapping[str, object])-class CloudflareDecisionsConfig(BaseDecisionsConfig):api_key_env = ("CLOUDFLARE_API_KEY",)@@ -23,38 +20,19 @@ class CloudflareDecisionsConfig(BaseDecisionsConfig):inlines_remote_images = Truedef get_default_api_base(self) -> str | None:- account_id: Final = normalize_nonempty_secret_str(get_secret_str("CLOUDFLARE_ACCOUNT_ID"))- if account_id is None:- return None- return f"https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/run"+ return workers_ai_default_api_base()def missing_api_base_message(self, custom_llm_provider: str) -> str:- return "Missing CLOUDFLARE_ACCOUNT_ID - set CLOUDFLARE_ACCOUNT_ID or pass api_base explicitly"+ return CLOUDFLARE_MISSING_API_BASE_MESSAGEdef canonical_model(self, model: str) -> str:- if model.startswith("@cf/"):- return model- return f"@cf/cloudflare/{model}"+ return workers_ai_canonical_model(model)def request_model(self, model: str) -> str:- return model.rsplit("/", maxsplit=1)[-1]+ return workers_ai_request_model(model)def get_complete_url(self, api_base: str, model: str) -> str:- normalized_api_base: Final = api_base.rstrip("/")- if normalized_api_base.endswith("/ai/v1"):- return f"{normalized_api_base.removesuffix('/ai/v1')}/ai/run/{model}"- if normalized_api_base.endswith("/ai/run"):- return f"{normalized_api_base}/{model}"- return f"{normalized_api_base}/ai/run/{model}"+ return workers_ai_run_url(api_base, model)def unwrap_response(self, payload: object) -> object:- try:- response_mapping: Final = _RESPONSE_MAPPING_ADAPTER.validate_python(payload)- except ValidationError:- return payload- if "answers" in response_mapping:- return response_mapping- try:- return _RESPONSE_MAPPING_ADAPTER.validate_python(response_mapping.get("result"))- except ValidationError:- return response_mapping+ return unwrap_workers_ai_result(payload)diff --git a/litellm/llms/cloudflare/extraction/guardrail_translation/__init__.py b/litellm/llms/cloudflare/extraction/guardrail_translation/__init__.pynew file mode 100644index 00000000000..3fda941854a--- /dev/null+++ b/litellm/llms/cloudflare/extraction/guardrail_translation/__init__.py@@ -0,0 +1,11 @@+from typing import Final++from litellm.llms.cloudflare.extraction.guardrail_translation.handler import ExtractionHandler+from litellm.types.utils import CallTypes++guardrail_translation_mappings: Final = {+ CallTypes.extraction: ExtractionHandler,+ CallTypes.aextraction: ExtractionHandler,+}++__all__ = ["ExtractionHandler", "guardrail_translation_mappings"]diff --git a/litellm/llms/cloudflare/extraction/guardrail_translation/handler.py b/litellm/llms/cloudflare/extraction/guardrail_translation/handler.pynew file mode 100644index 00000000000..607d6fac48b--- /dev/null+++ b/litellm/llms/cloudflare/extraction/guardrail_translation/handler.py@@ -0,0 +1,276 @@+from collections.abc import Iterable, Mapping, Sequence+from dataclasses import dataclass+from itertools import chain, groupby+from types import MappingProxyType+from typing import TYPE_CHECKING, Annotated, Final, Literal, TypeAlias, TypeVar++from pydantic import Field, JsonValue, TypeAdapter++from litellm.litellm_core_utils.core_helpers import get_metadata_variable_name_from_kwargs+from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation+from litellm.types.extraction import (+ EXTRACTION_STATE_REWRITTEN_METADATA_KEY,+ ExtractionAnswer,+ ExtractionBase64Image,+ ExtractionResponse,+)+from litellm.types.utils import GenericGuardrailAPIInputs++if TYPE_CHECKING:+ from litellm.integrations.custom_guardrail import CustomGuardrail+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+ from litellm.types.proxy.auth.user_api_key_auth import UserAPIKeyAuth++_FIELDS_ADAPTER: Final[TypeAdapter[Mapping[str, Mapping[str, object]]]] = TypeAdapter(+ Mapping[str, Mapping[str, object]]+)+_METADATA_ADAPTER: Final[TypeAdapter[Mapping[str, object]]] = TypeAdapter(Mapping[str, object])+_IMAGES_ADAPTER: Final[TypeAdapter[tuple[ExtractionBase64Image | JsonValue, ...]]] = TypeAdapter(+ tuple[Annotated[ExtractionBase64Image | JsonValue, Field(union_mode="left_to_right")], ...]+)+++_AnswerKey: TypeAlias = Literal["value", "guess", "mean", "median", "p10", "p90", "quantiles"]+_ESTIMATE_KEYS: Final[tuple[_AnswerKey, ...]] = ("value", "guess", "mean", "median", "p10", "p90", "quantiles")+_STATISTIC_KEYS: Final[frozenset[_AnswerKey]] = frozenset(("mean", "median", "p10", "p90", "quantiles"))+_NULLED_ANSWER: Final[Mapping[str, None]] = MappingProxyType(+ dict.fromkeys(("value", "guess", "mean", "median", "p10", "p90", "quantiles", "steps", "span", "spans"), None)+)+++@dataclass(frozen=True, slots=True)+class _AnswerText:+ name: str+ key: _AnswerKey+ item: int | None+ text: str+++_SPEC_TEXT_KEYS: Final = ("instructions", "unit")+++@dataclass(frozen=True, slots=True)+class _SpecText:+ name: str+ key: str+ text: str+++def _spec_texts_of(name: str, spec: Mapping[str, object]) -> tuple[_SpecText, ...]:+ return tuple(+ _SpecText(name=name, key=key, text=text) for key in _SPEC_TEXT_KEYS if isinstance(text := spec.get(key), str)+ )+++def _spec_texts(fields: Mapping[str, Mapping[str, object]]) -> tuple[_SpecText, ...]:+ return tuple(chain.from_iterable(_spec_texts_of(name, spec) for name, spec in fields.items()))+++_NamedText = TypeVar("_NamedText", _AnswerText, _SpecText)+++def _scans_by_name(scanned: Iterable[tuple[_NamedText, str]]) -> Mapping[str, tuple[tuple[_NamedText, str], ...]]:+ return {name: tuple(group) for name, group in groupby(scanned, key=lambda pair: pair[0].name)}+++def _guardrailed_spec(spec: Mapping[str, object], scanned: Sequence[tuple[_SpecText, str]]) -> Mapping[str, object]:+ return {**spec, **{text.key: guardrailed for text, guardrailed in scanned}}+++def _metadata_key(data: Mapping[str, object]) -> Literal["metadata", "litellm_metadata"]:+ return get_metadata_variable_name_from_kwargs(data)+++def _metadata(data: Mapping[str, object]) -> Mapping[str, object]:+ return _METADATA_ADAPTER.validate_python(data.get(_metadata_key(data)) or {})+++def _is_text_answer(answer: ExtractionAnswer, spec: Mapping[str, object] | None) -> bool:+ return answer.type == "text" or (answer.type == "list" and (spec is None or spec.get("items") == "text"))+++def _image_urls(images: object) -> tuple[str, ...]:+ if not isinstance(images, list):+ return ()+ return tuple(+ f"data:{image.content_type};base64,{image.base64}" if isinstance(image, ExtractionBase64Image) else image+ for image in _IMAGES_ADAPTER.validate_python(images)+ if isinstance(image, (str, ExtractionBase64Image))+ )+++def _scalar_text(value: JsonValue, whole: bool) -> str | None:+ if isinstance(value, bool):+ return None+ if isinstance(value, float) and whole:+ return format(value, ".0f")+ return str(value) if isinstance(value, (str, int, float)) else None+++def _item_texts(items: Sequence[JsonValue], whole: bool) -> tuple[tuple[int, str], ...]:+ return tuple((index, text) for index, item in enumerate(items) if (text := _scalar_text(item, whole)) is not None)+++def _value_texts(name: str, key: _AnswerKey, value: JsonValue) -> tuple[_AnswerText, ...]:+ whole: Final = key in _STATISTIC_KEYS+ if isinstance(value, list):+ return tuple(+ _AnswerText(name=name, key=key, item=index, text=text) for index, text in _item_texts(value, whole)+ )+ text: Final = _scalar_text(value, whole)+ return () if text is None else (_AnswerText(name=name, key=key, item=None, text=text),)+++def _step_texts(name: str, step: JsonValue) -> tuple[_AnswerText, ...]:+ if not isinstance(step, dict):+ return ()+ return tuple(chain.from_iterable(_value_texts(name, key, step.get(key)) for key in _ESTIMATE_KEYS))+++def _answer_texts(name: str, answer: ExtractionAnswer) -> tuple[_AnswerText, ...]:+ return (+ *_value_texts(name, "value", answer.value),+ *_value_texts(name, "guess", answer.guess),+ *_value_texts(name, "mean", answer.mean),+ *_value_texts(name, "median", answer.median),+ *_value_texts(name, "p10", answer.p10),+ *_value_texts(name, "p90", answer.p90),+ *_value_texts(name, "quantiles", list(answer.quantiles or ())),+ *chain.from_iterable(_step_texts(name, step) for step in answer.steps or ()),+ )+++def _guardrailed_value(value: JsonValue, scanned: Mapping[int | None, str]) -> JsonValue:+ if isinstance(value, list):+ return [scanned.get(index, item) for index, item in enumerate(value)]+ return scanned.get(None, value)+++def _scans_of(key: _AnswerKey, scanned: Sequence[tuple[_AnswerText, str]]) -> Mapping[int | None, str]:+ return {text.item: guardrailed for text, guardrailed in scanned if text.key == key}+++def _guardrailed_answer(+ answer: ExtractionAnswer,+ scanned: Sequence[tuple[_AnswerText, str]],+ drop_spans: bool,+ is_text: bool,+) -> ExtractionAnswer:+ if not is_text and any(text.text != guardrailed for text, guardrailed in scanned):+ return answer.model_copy(update=_NULLED_ANSWER)+ value_scans: Final = _scans_of("value", scanned if is_text else ())+ guess_scans: Final = _scans_of("guess", scanned if is_text else ())+ update: Final = {+ **({"value": _guardrailed_value(answer.value, value_scans)} if value_scans else {}),+ **({"guess": _guardrailed_value(answer.guess, guess_scans)} if guess_scans else {}),+ **({"span": None, "spans": None} if drop_spans else {}),+ }+ return answer.model_copy(update=update) if update else answer+++async def _scanned_texts(+ texts: Sequence[str],+ model: object,+ guardrail_to_apply: "CustomGuardrail",+ request_data: dict[str, object], # mutable-ok: CustomGuardrail.apply_guardrail takes the request as a plain dict+ input_type: Literal["request", "response"],+ litellm_logging_obj: "LiteLLMLoggingObj | None",+ images: Sequence[str] = (),+) -> tuple[str, ...]:+ unique_texts: Final = tuple(dict.fromkeys(texts))+ inputs: Final = GenericGuardrailAPIInputs(texts=list(unique_texts), model=model if isinstance(model, str) else None)+ if images:+ inputs["images"] = list(images)+ guardrailed: Final = await guardrail_to_apply.apply_guardrail( # pyright: ignore[reportUnknownMemberType] # CustomGuardrail.apply_guardrail types request_data as a bare dict+ inputs=inputs,+ request_data=request_data,+ input_type=input_type,+ logging_obj=litellm_logging_obj,+ )+ returned: Final = guardrailed.get("texts", [])+ guardrailed_by_text: Final = MappingProxyType(+ {text: returned[index] if index < len(returned) else text for index, text in enumerate(unique_texts)}+ )+ return tuple(guardrailed_by_text[text] for text in texts)+++class ExtractionHandler(BaseTranslation):+ async def process_input_messages(+ self,+ data: dict[str, object], # mutable-ok: BaseTranslation hands over the proxy's request dict+ guardrail_to_apply: "CustomGuardrail",+ litellm_logging_obj: "LiteLLMLoggingObj | None" = None,+ ) -> Mapping[str, object]:+ state: Final = data.get("state")+ states: Final = (state,) if isinstance(state, str) and state else ()+ fields: Final = _FIELDS_ADAPTER.validate_python(data.get("fields") or {})+ spec_texts: Final = _spec_texts(fields)+ images: Final = _image_urls(data.get("images"))+ if not states and not spec_texts and not images:+ return data+ scanned: Final = await _scanned_texts(+ (*states, *(text.text for text in spec_texts)),+ data.get("model"),+ guardrail_to_apply,+ data,+ "request",+ litellm_logging_obj,+ images,+ )+ spec_scans: Final = _scans_by_name(zip(spec_texts, scanned[len(states) :]))+ state_rewritten: Final = bool(states) and scanned[0] != states[0]+ return {+ **data,+ **({"state": scanned[0]} if states else {}),+ **(+ {_metadata_key(data): {**_metadata(data), EXTRACTION_STATE_REWRITTEN_METADATA_KEY: True}}+ if state_rewritten+ else {}+ ),+ "fields": {name: _guardrailed_spec(spec, spec_scans.get(name, ())) for name, spec in fields.items()},+ }++ async def process_output_response(+ self,+ response: object,+ guardrail_to_apply: "CustomGuardrail",+ litellm_logging_obj: "LiteLLMLoggingObj | None" = None,+ user_api_key_dict: "UserAPIKeyAuth | None" = None,+ request_data: dict[str, object] | None = None, # mutable-ok: BaseTranslation hands over the request dict+ ) -> object:+ if not isinstance(response, ExtractionResponse):+ return response+ texts: Final = tuple(+ chain.from_iterable(_answer_texts(name, answer) for name, answer in response.answers.items())+ )+ state_texts: Final = (response.state_text,) if response.state_text else ()+ request: Final = request_data or {}+ scanned: Final = (+ await _scanned_texts(+ (*(text.text for text in texts), *state_texts),+ response.model,+ guardrail_to_apply,+ request,+ "response",+ litellm_logging_obj,+ )+ if texts or state_texts+ else ()+ )+ answer_scans: Final = _scans_by_name(zip(texts, scanned))+ state_text: Final = next(iter(scanned[len(texts) :]), response.state_text)+ specs: Final = _FIELDS_ADAPTER.validate_python(request.get("fields") or {})+ return response.model_copy(+ update={+ "answers": {+ name: _guardrailed_answer(+ answer,+ answer_scans.get(name, ()),+ drop_spans=state_text != response.state_text,+ is_text=_is_text_answer(answer, specs.get(name)),+ )+ for name, answer in response.answers.items()+ },+ **({"state_text": state_text} if state_texts else {}),+ }+ )diff --git a/litellm/llms/cloudflare/extraction/transformation.py b/litellm/llms/cloudflare/extraction/transformation.pynew file mode 100644index 00000000000..7aa3bf6316c--- /dev/null+++ b/litellm/llms/cloudflare/extraction/transformation.py@@ -0,0 +1,32 @@+from litellm.llms.base_llm.extraction.transformation import BaseExtractionConfig+from litellm.llms.cloudflare.common_utils import (+ CLOUDFLARE_MISSING_API_BASE_MESSAGE,+ unwrap_workers_ai_result,+ workers_ai_canonical_model,+ workers_ai_default_api_base,+ workers_ai_request_model,+ workers_ai_run_url,+)+++class CloudflareExtractionConfig(BaseExtractionConfig):+ api_key_env = ("CLOUDFLARE_API_KEY",)+ api_base_env = ("CLOUDFLARE_API_BASE",)++ def get_default_api_base(self) -> str | None:+ return workers_ai_default_api_base()++ def missing_api_base_message(self, custom_llm_provider: str) -> str:+ return CLOUDFLARE_MISSING_API_BASE_MESSAGE++ def canonical_model(self, model: str) -> str:+ return workers_ai_canonical_model(model)++ def request_model(self, model: str) -> str:+ return workers_ai_request_model(model)++ def get_complete_url(self, api_base: str, model: str) -> str:+ return workers_ai_run_url(api_base, model)++ def unwrap_response(self, payload: object) -> object:+ return unwrap_workers_ai_result(payload)diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.pyindex b1e55375f16..ac2ac1fe31b 100644--- a/litellm/llms/custom_httpx/llm_http_handler.py+++ b/litellm/llms/custom_httpx/llm_http_handler.py@@ -76,6 +76,7 @@ from litellm.llms.base_llm.containers.transformation import BaseContainerConfigfrom litellm.llms.base_llm.decisions.transformation import BaseDecisionsConfigfrom litellm.llms.base_llm.embedding.transformation import BaseEmbeddingConfigfrom litellm.llms.base_llm.evals.transformation import BaseEvalsAPIConfig+from litellm.llms.base_llm.extraction.transformation import BaseExtractionConfigfrom litellm.llms.base_llm.files.transformation import (BaseFilesConfig,BaseFileUploadStream,@@ -128,6 +129,7 @@ from litellm.types.containers.main import (DeleteContainerResult,)from litellm.types.decisions import DecisionsIRRequest, DecisionsIRResponse+from litellm.types.extraction import ExtractionResponsefrom litellm.types.files import StreamingMediaUploadConfig, TwoStepFileUploadConfigfrom litellm.types.integrations.custom_logger import (NON_CODE_INTERPRETER_INTERCEPTION_INTERNAL_PREFIXES,@@ -1700,6 +1702,115 @@ class BaseLLMHTTPHandler:model=model, custom_llm_provider=custom_llm_provider, raw_response=response, request=request)+ def _prepare_extraction_request(+ self,+ model: str,+ logging_obj: LiteLLMLoggingObj | None,+ provider_config: BaseExtractionConfig,+ body: Mapping[str, object],+ api_base: str,+ api_key: str | None,+ headers: Mapping[str, str],+ litellm_params: Mapping[str, object],+ ) -> tuple[str, Mapping[str, str]]:+ outbound_headers: Final = provider_config.validate_environment(+ headers=headers,+ model=model,+ api_key=api_key,+ litellm_params=litellm_params,+ )+ url: Final = provider_config.get_complete_url(api_base=api_base, model=model)+ if logging_obj is not None:+ logging_obj.pre_call( # pyright: ignore[reportUnknownMemberType] # Logging.pre_call is untyped+ input=dict(body),+ api_key=api_key,+ model=model,+ additional_args={"api_base": url, "complete_input_dict": dict(body), "headers": outbound_headers},+ )+ return url, outbound_headers++ def extraction(+ self,+ model: str,+ custom_llm_provider: str,+ logging_obj: LiteLLMLoggingObj | None,+ provider_config: BaseExtractionConfig,+ body: Mapping[str, object],+ api_base: str,+ api_key: str | None,+ headers: Mapping[str, str],+ timeout: float | httpx.Timeout | None,+ litellm_params: Mapping[str, object],+ client: HTTPHandler | None = None,+ ) -> ExtractionResponse:+ url, outbound_headers = self._prepare_extraction_request(+ model=model,+ logging_obj=logging_obj,+ provider_config=provider_config,+ body=body,+ api_base=api_base,+ api_key=api_key,+ headers=headers,+ litellm_params=litellm_params,+ )+ sync_httpx_client: Final = client if client is not None else get_httpx_client()+ try:+ response: Final = sync_httpx_client.post( # pyright: ignore[reportUnknownMemberType] # untyped+ url,+ json=dict(body),+ headers=dict(outbound_headers),+ timeout=timeout,+ logging_obj=logging_obj,+ )+ except httpx.HTTPError as e:+ raise self._handle_error(e=e, provider_config=provider_config)+ return provider_config.transform_extraction_response(+ model=model, custom_llm_provider=custom_llm_provider, raw_response=response+ )++ async def aextraction(+ self,+ model: str,+ custom_llm_provider: str,+ logging_obj: LiteLLMLoggingObj | None,+ provider_config: BaseExtractionConfig,+ body: Mapping[str, object],+ api_base: str,+ api_key: str | None,+ headers: Mapping[str, str],+ timeout: float | httpx.Timeout | None,+ litellm_params: Mapping[str, object],+ client: AsyncHTTPHandler | None = None,+ ) -> ExtractionResponse:+ url, outbound_headers = self._prepare_extraction_request(+ model=model,+ logging_obj=logging_obj,+ provider_config=provider_config,+ body=body,+ api_base=api_base,+ api_key=api_key,+ headers=headers,+ litellm_params=litellm_params,+ )+ async_httpx_client: Final = (+ client+ if client is not None+ else get_async_httpx_client(llm_provider=litellm.LlmProviders(custom_llm_provider))+ )+ try:+ response: Final = await async_httpx_client.post( # pyright: ignore[reportUnknownMemberType] # untyped+ url,+ json=dict(body),+ headers=dict(outbound_headers),+ timeout=timeout,+ logging_obj=logging_obj,+ )+ except httpx.HTTPError as e:+ raise self._handle_error(e=e, provider_config=provider_config)+ return provider_config.transform_extraction_response(+ model=model, custom_llm_provider=custom_llm_provider, raw_response=response+ )+def _prepare_audio_transcription_request(self,model: str,@@ -6462,6 +6573,7 @@ class BaseLLMHTTPHandler:provider_config: Union[BaseConfig,BaseDecisionsConfig,+ BaseExtractionConfig,BaseRerankConfig,BaseResponsesAPIConfig,BaseImageEditConfig,diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.jsonindex c6aea8ec98a..04a3f9225ce 100644--- a/litellm/model_prices_and_context_window_backup.json+++ b/litellm/model_prices_and_context_window_backup.json@@ -16580,6 +16580,24 @@"source": "https://developers.cloudflare.com/workers-ai/platform/pricing/","supports_vision": true},+ "cloudflare/clairic": {+ "input_cost_per_token": 1e-07,+ "litellm_provider": "cloudflare",+ "max_input_tokens": 65536,+ "mode": "extraction",+ "output_cost_per_token": 0.0,+ "source": "https://developers.cloudflare.com/workers-ai/models/clairic/",+ "supports_vision": true+ },+ "cloudflare/@cf/cloudflare/clairic": {+ "input_cost_per_token": 1e-07,+ "litellm_provider": "cloudflare",+ "max_input_tokens": 65536,+ "mode": "extraction",+ "output_cost_per_token": 0.0,+ "source": "https://developers.cloudflare.com/workers-ai/models/clairic/",+ "supports_vision": true+ },"cloudflare/@cf/meta/llama-2-7b-chat-fp16": {"input_cost_per_token": 1.923e-06,"litellm_provider": "cloudflare",diff --git a/litellm/proxy/_lazy_features.py b/litellm/proxy/_lazy_features.pyindex a7adb5c1bf5..0e2eed73364 100644--- a/litellm/proxy/_lazy_features.py+++ b/litellm/proxy/_lazy_features.py@@ -275,7 +275,7 @@ LAZY_FEATURES: Final[tuple[LazyFeature, ...]] = (LazyFeature(name="decisions",module_path="litellm.proxy.decisions_endpoints.endpoints",- path_prefixes=("/v1/decisions", "/decisions", "/v1/systemone", "/systemone"),+ path_prefixes=("/v1/decisions", "/decisions", "/v1/systemone", "/systemone", "/v1/extraction", "/extraction"),),LazyFeature(name="claude_code_marketplace",diff --git a/litellm/proxy/_lazy_openapi_snapshot.json b/litellm/proxy/_lazy_openapi_snapshot.jsonindex 7198d74909c..545b317055a 100644--- a/litellm/proxy/_lazy_openapi_snapshot.json+++ b/litellm/proxy/_lazy_openapi_snapshot.json@@ -9829,6 +9829,249 @@"title": "DecisionsUsage","type": "object"},+ "ExtractionAnswer": {+ "additionalProperties": true,+ "properties": {+ "confidence": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "title": "Confidence"+ },+ "guess": {+ "$ref": "#/components/schemas/JsonValue"+ },+ "mean": {+ "$ref": "#/components/schemas/JsonValue"+ },+ "median": {+ "$ref": "#/components/schemas/JsonValue"+ },+ "p10": {+ "$ref": "#/components/schemas/JsonValue"+ },+ "p90": {+ "$ref": "#/components/schemas/JsonValue"+ },+ "p_above": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "title": "P Above"+ },+ "p_below": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "title": "P Below"+ },+ "p_null": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "title": "P Null"+ },+ "quantiles": {+ "anyOf": [+ {+ "items": {+ "$ref": "#/components/schemas/JsonValue"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "title": "Quantiles"+ },+ "span": {+ "anyOf": [+ {+ "items": {+ "type": "integer"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "title": "Span"+ },+ "spans": {+ "anyOf": [+ {+ "items": {+ "items": {+ "type": "integer"+ },+ "type": "array"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "title": "Spans"+ },+ "steps": {+ "anyOf": [+ {+ "items": {+ "$ref": "#/components/schemas/JsonValue"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "title": "Steps"+ },+ "type": {+ "title": "Type",+ "type": "string"+ },+ "value": {+ "$ref": "#/components/schemas/JsonValue",+ "description": "The answer, null when the input does not determine it"+ }+ },+ "required": [+ "type",+ "value"+ ],+ "title": "ExtractionAnswer",+ "type": "object"+ },+ "ExtractionResponse": {+ "additionalProperties": true,+ "properties": {+ "answers": {+ "additionalProperties": {+ "$ref": "#/components/schemas/ExtractionAnswer"+ },+ "title": "Answers",+ "type": "object"+ },+ "model": {+ "title": "Model",+ "type": "string"+ },+ "state_text": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "State Text"+ },+ "truncated": {+ "title": "Truncated",+ "type": "boolean"+ },+ "usage": {+ "$ref": "#/components/schemas/ExtractionUsage"+ }+ },+ "required": [+ "model",+ "answers",+ "truncated",+ "usage"+ ],+ "title": "ExtractionResponse",+ "type": "object"+ },+ "ExtractionUsage": {+ "additionalProperties": true,+ "properties": {+ "image_tokens": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "title": "Image Tokens"+ },+ "input_tokens": {+ "title": "Input Tokens",+ "type": "integer"+ },+ "output_tokens": {+ "title": "Output Tokens",+ "type": "integer"+ },+ "passes": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "title": "Passes"+ },+ "schema_tokens": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "title": "Schema Tokens"+ },+ "state_tokens": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "title": "State Tokens"+ }+ },+ "required": [+ "input_tokens",+ "output_tokens"+ ],+ "title": "ExtractionUsage",+ "type": "object"+ },+ "JsonValue": {},"NoulAnswer": {"additionalProperties": true,"properties": {@@ -10679,7 +10922,437 @@"title": "Questions","type": "array"},- "safety_identifier": {+ "safety_identifier": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "A stable id for your end user. Sent to OpenAI and dropped for other providers",+ "title": "Safety Identifier"+ },+ "videos": {+ "default": [],+ "description": "Clef-omni only. Up to 2 embedded videos, each a base64 data URL or {content_type, base64}",+ "items": {+ "anyOf": [+ {+ "pattern": "^data:video/[^;,\\s]+;base64,.+$",+ "type": "string"+ },+ {+ "additionalProperties": false,+ "properties": {+ "base64": {+ "description": "Base64-encoded video bytes",+ "minLength": 1,+ "title": "Base64",+ "type": "string"+ },+ "content_type": {+ "description": "A video/* media type, such as video/mp4",+ "pattern": "^video/\\S+$",+ "title": "Content Type",+ "type": "string"+ }+ },+ "required": [+ "content_type",+ "base64"+ ],+ "title": "DecisionsBase64Video",+ "type": "object"+ }+ ]+ },+ "maxItems": 2,+ "title": "Videos",+ "type": "array"+ }+ },+ "required": [+ "input",+ "questions",+ "model"+ ],+ "title": "OpenAIDecisionRequest",+ "type": "object"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/OpenAIDecisionResponse"+ }+ }+ },+ "description": "Successful Response"+ }+ },+ "security": [+ {+ "APIKeyHeader": []+ }+ ],+ "summary": "Ask questions about an input (OpenAI Decisions format)",+ "tags": [+ "decisions"+ ]+ }+ },+ "/extraction": {+ "post": {+ "description": "Read a `state` text and up to 4 images and get one typed answer per named field in `fields`.\n\nField types are `text`, `number`, `date`, `time`, `datetime`, `duration`, `list` (set `items`), `estimate`\n(set `min` and `max`) and `forecast` (set `min`, `max` and `horizon`). Each answer carries its `value`, which is\nnull when the input does not determine it, plus `confidence`, `p_null`, text `span`s into the state and, for\nestimates, `mean`, `median`, `p10` and `p90`. Images are data URLs or `{content_type, base64}` objects, remote\nURLs are not accepted. An unknown field type, a field name that is not 1 to 64 letters, digits, `_`, `.` or `-`\nstarting with a letter or `_`, a remote image URL or more than 4 images is rejected with a 400 before any\nprovider is called. Any other top-level key, `stream: true` and OpenAI generation settings such as `temperature`\nincluded, is rejected with a 400 naming it unless `drop_params` or the deployment's `additional_drop_params`\ndrops it. Settings inside `fields` and `options` go to the provider as sent, so a field missing a setting its\ntype needs or an empty `state` with no images comes back with the provider's own error. `model` is any\nextraction model in the proxy model list, such as Cloudflare Clairic. The request and the answers keep the\nprovider's format.",+ "operationId": "extraction_extraction_post",+ "requestBody": {+ "content": {+ "application/json": {+ "example": {+ "fields": {+ "days_to_pay": {+ "max": 90,+ "min": 0,+ "type": "estimate"+ },+ "invoice_date": {+ "type": "date"+ },+ "items": {+ "instructions": "What was bought?",+ "items": "text",+ "type": "list"+ },+ "total": {+ "type": "number",+ "unit": "USD"+ },+ "vendor": {+ "instructions": "Who sent the invoice?",+ "type": "text"+ }+ },+ "model": "clairic",+ "state": "Invoice #4471 from Acme Tools, dated 2026-03-03. 12 hammers. Total $174. Payment due in 30 days."+ },+ "schema": {+ "additionalProperties": true,+ "properties": {+ "fields": {+ "description": "Field name to typed field spec. Each name becomes a key in the answers",+ "minProperties": 1,+ "patternProperties": {+ "^[A-Za-z_][A-Za-z0-9_.\\-]{0,63}$": {+ "additionalProperties": true,+ "properties": {+ "decimals": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Numbers, durations and number lists only, 0 to 6",+ "title": "Decimals"+ },+ "horizon": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Forecast only, number of steps",+ "title": "Horizon"+ },+ "instructions": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "What the field should contain",+ "title": "Instructions"+ },+ "integer": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "description": "Numbers and durations only",+ "title": "Integer"+ },+ "interval": {+ "anyOf": [+ {+ "enum": [+ "step",+ "minute",+ "hour",+ "day",+ "week",+ "month",+ "quarter",+ "year"+ ],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Interval"+ },+ "items": {+ "anyOf": [+ {+ "enum": [+ "text",+ "number",+ "date"+ ],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Item type, required for list fields",+ "title": "Items"+ },+ "max": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "number"+ },+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Estimate and forecast upper bound",+ "title": "Max"+ },+ "min": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "number"+ },+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Estimate and forecast lower bound",+ "title": "Min"+ },+ "null_threshold": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Probability of null above which the value is null",+ "title": "Null Threshold"+ },+ "scale": {+ "anyOf": [+ {+ "enum": [+ "linear",+ "log"+ ],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Scale"+ },+ "step": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "number"+ },+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Estimate grid step, or month or year",+ "title": "Step"+ },+ "type": {+ "description": "The answer type for this field",+ "enum": [+ "text",+ "number",+ "date",+ "time",+ "datetime",+ "duration",+ "list",+ "estimate",+ "forecast"+ ],+ "title": "Type",+ "type": "string"+ },+ "unit": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Unit label. For durations, seconds through years",+ "title": "Unit"+ }+ },+ "required": [+ "type"+ ],+ "title": "ExtractionField",+ "type": "object"+ }+ },+ "title": "Fields",+ "type": "object"+ },+ "images": {+ "anyOf": [+ {+ "items": {+ "anyOf": [+ {+ "pattern": "^[Dd][Aa][Tt][Aa]:",+ "type": "string"+ },+ {+ "additionalProperties": true,+ "properties": {+ "base64": {+ "description": "Base64-encoded image bytes",+ "title": "Base64",+ "type": "string"+ },+ "content_type": {+ "description": "The image media type, such as image/png",+ "title": "Content Type",+ "type": "string"+ }+ },+ "required": [+ "content_type",+ "base64"+ ],+ "title": "ExtractionBase64Image",+ "type": "object"+ }+ ]+ },+ "maxItems": 4,+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "description": "Up to 4 images as data URLs or content_type plus base64, no remote URLs",+ "title": "Images"+ },+ "model": {+ "description": "An extraction model from the proxy model_list",+ "title": "Model",+ "type": "string"+ },+ "options": {+ "anyOf": [+ {+ "additionalProperties": true,+ "properties": {+ "include_quantiles": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "description": "Add 99 percentiles to estimates",+ "title": "Include Quantiles"+ },+ "return_state_text": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "description": "Return the text that spans index into",+ "title": "Return State Text"+ }+ },+ "title": "ExtractionOptions",+ "type": "object"+ },+ {+ "type": "null"+ }+ ]+ },+ "reference_date": {"anyOf": [{"type": "string"@@ -10688,54 +11361,21 @@"type": "null"}],- "description": "A stable id for your end user. Sent to OpenAI and dropped for other providers",- "title": "Safety Identifier"+ "description": "ISO date that anchors dates written without a year",+ "title": "Reference Date"},- "videos": {- "default": [],- "description": "Clef-omni only. Up to 2 embedded videos, each a base64 data URL or {content_type, base64}",- "items": {- "anyOf": [- {- "pattern": "^data:video/[^;,\\s]+;base64,.+$",- "type": "string"- },- {- "additionalProperties": false,- "properties": {- "base64": {- "description": "Base64-encoded video bytes",- "minLength": 1,- "title": "Base64",- "type": "string"- },- "content_type": {- "description": "A video/* media type, such as video/mp4",- "pattern": "^video/\\S+$",- "title": "Content Type",- "type": "string"- }- },- "required": [- "content_type",- "base64"- ],- "title": "DecisionsBase64Video",- "type": "object"- }- ]- },- "maxItems": 2,- "title": "Videos",- "type": "array"+ "state": {+ "default": "",+ "description": "The text to read. Must be non-empty unless images are sent. Text answers are spans of it",+ "title": "State",+ "type": "string"}},"required": [- "input",- "questions",+ "fields","model"],- "title": "OpenAIDecisionRequest",+ "title": "ExtractionRequest","type": "object"}}@@ -10747,7 +11387,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/OpenAIDecisionResponse"+ "$ref": "#/components/schemas/ExtractionResponse"}}},@@ -10759,7 +11399,7 @@"APIKeyHeader": []}],- "summary": "Ask questions about an input (OpenAI Decisions format)",+ "summary": "Extract typed fields from a state","tags": ["decisions"]@@ -11775,6 +12415,403 @@]}},+ "/v1/extraction": {+ "post": {+ "description": "Read a `state` text and up to 4 images and get one typed answer per named field in `fields`.\n\nField types are `text`, `number`, `date`, `time`, `datetime`, `duration`, `list` (set `items`), `estimate`\n(set `min` and `max`) and `forecast` (set `min`, `max` and `horizon`). Each answer carries its `value`, which is\nnull when the input does not determine it, plus `confidence`, `p_null`, text `span`s into the state and, for\nestimates, `mean`, `median`, `p10` and `p90`. Images are data URLs or `{content_type, base64}` objects, remote\nURLs are not accepted. An unknown field type, a field name that is not 1 to 64 letters, digits, `_`, `.` or `-`\nstarting with a letter or `_`, a remote image URL or more than 4 images is rejected with a 400 before any\nprovider is called. Any other top-level key, `stream: true` and OpenAI generation settings such as `temperature`\nincluded, is rejected with a 400 naming it unless `drop_params` or the deployment's `additional_drop_params`\ndrops it. Settings inside `fields` and `options` go to the provider as sent, so a field missing a setting its\ntype needs or an empty `state` with no images comes back with the provider's own error. `model` is any\nextraction model in the proxy model list, such as Cloudflare Clairic. The request and the answers keep the\nprovider's format.",+ "operationId": "extraction_v1_extraction_post",+ "requestBody": {+ "content": {+ "application/json": {+ "example": {+ "fields": {+ "days_to_pay": {+ "max": 90,+ "min": 0,+ "type": "estimate"+ },+ "invoice_date": {+ "type": "date"+ },+ "items": {+ "instructions": "What was bought?",+ "items": "text",+ "type": "list"+ },+ "total": {+ "type": "number",+ "unit": "USD"+ },+ "vendor": {+ "instructions": "Who sent the invoice?",+ "type": "text"+ }+ },+ "model": "clairic",+ "state": "Invoice #4471 from Acme Tools, dated 2026-03-03. 12 hammers. Total $174. Payment due in 30 days."+ },+ "schema": {+ "additionalProperties": true,+ "properties": {+ "fields": {+ "description": "Field name to typed field spec. Each name becomes a key in the answers",+ "minProperties": 1,+ "patternProperties": {+ "^[A-Za-z_][A-Za-z0-9_.\\-]{0,63}$": {+ "additionalProperties": true,+ "properties": {+ "decimals": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Numbers, durations and number lists only, 0 to 6",+ "title": "Decimals"+ },+ "horizon": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Forecast only, number of steps",+ "title": "Horizon"+ },+ "instructions": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "What the field should contain",+ "title": "Instructions"+ },+ "integer": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "description": "Numbers and durations only",+ "title": "Integer"+ },+ "interval": {+ "anyOf": [+ {+ "enum": [+ "step",+ "minute",+ "hour",+ "day",+ "week",+ "month",+ "quarter",+ "year"+ ],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Interval"+ },+ "items": {+ "anyOf": [+ {+ "enum": [+ "text",+ "number",+ "date"+ ],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Item type, required for list fields",+ "title": "Items"+ },+ "max": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "number"+ },+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Estimate and forecast upper bound",+ "title": "Max"+ },+ "min": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "number"+ },+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Estimate and forecast lower bound",+ "title": "Min"+ },+ "null_threshold": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Probability of null above which the value is null",+ "title": "Null Threshold"+ },+ "scale": {+ "anyOf": [+ {+ "enum": [+ "linear",+ "log"+ ],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Scale"+ },+ "step": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "number"+ },+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Estimate grid step, or month or year",+ "title": "Step"+ },+ "type": {+ "description": "The answer type for this field",+ "enum": [+ "text",+ "number",+ "date",+ "time",+ "datetime",+ "duration",+ "list",+ "estimate",+ "forecast"+ ],+ "title": "Type",+ "type": "string"+ },+ "unit": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Unit label. For durations, seconds through years",+ "title": "Unit"+ }+ },+ "required": [+ "type"+ ],+ "title": "ExtractionField",+ "type": "object"+ }+ },+ "title": "Fields",+ "type": "object"+ },+ "images": {+ "anyOf": [+ {+ "items": {+ "anyOf": [+ {+ "pattern": "^[Dd][Aa][Tt][Aa]:",+ "type": "string"+ },+ {+ "additionalProperties": true,+ "properties": {+ "base64": {+ "description": "Base64-encoded image bytes",+ "title": "Base64",+ "type": "string"+ },+ "content_type": {+ "description": "The image media type, such as image/png",+ "title": "Content Type",+ "type": "string"+ }+ },+ "required": [+ "content_type",+ "base64"+ ],+ "title": "ExtractionBase64Image",+ "type": "object"+ }+ ]+ },+ "maxItems": 4,+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "description": "Up to 4 images as data URLs or content_type plus base64, no remote URLs",+ "title": "Images"+ },+ "model": {+ "description": "An extraction model from the proxy model_list",+ "title": "Model",+ "type": "string"+ },+ "options": {+ "anyOf": [+ {+ "additionalProperties": true,+ "properties": {+ "include_quantiles": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "description": "Add 99 percentiles to estimates",+ "title": "Include Quantiles"+ },+ "return_state_text": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "description": "Return the text that spans index into",+ "title": "Return State Text"+ }+ },+ "title": "ExtractionOptions",+ "type": "object"+ },+ {+ "type": "null"+ }+ ]+ },+ "reference_date": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "ISO date that anchors dates written without a year",+ "title": "Reference Date"+ },+ "state": {+ "default": "",+ "description": "The text to read. Must be non-empty unless images are sent. Text answers are spans of it",+ "title": "State",+ "type": "string"+ }+ },+ "required": [+ "fields",+ "model"+ ],+ "title": "ExtractionRequest",+ "type": "object"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ExtractionResponse"+ }+ }+ },+ "description": "Successful Response"+ }+ },+ "security": [+ {+ "APIKeyHeader": []+ }+ ],+ "summary": "Extract typed fields from a state",+ "tags": [+ "decisions"+ ]+ }+ },"/v1/systemone": {"post": {"description": "Judge a `state` against 1 to 128 named `questions` and get one calibrated answer per question name.\n\nQuestion types are `noul` (probability the answer is yes), `choice` (one label out of `criteria`, with\n`confidence` and `probabilities`), `score` (an index into the `criteria` levels, with `confidence`,\n`legend` and `probabilities`) and `box` (the image region the `instructions` describe, with `confidence`).\nTypeSafe models also take images in `assets`, each one referenced by its key in `state`. Requests that break\nthese rules are rejected with a 400 before any provider is called. `model` is any decision model in the proxy model list. OpenAI decision models accept this format\ntoo, LiteLLM translates it and keeps the answers keyed by question name. Streaming is not supported.\n\n[Docs](https://docs.litellm.ai/docs/decisions)",diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex 315533d6d0f..97a2fc31fb0 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -377,6 +377,8 @@ class LiteLLMRoutes(enum.Enum):"/v1/decisions","/systemone","/v1/systemone",+ "/extraction",+ "/v1/extraction",# OCR"/ocr","/v1/ocr",diff --git a/litellm/proxy/agent_endpoints/auth/managed_authorization.py b/litellm/proxy/agent_endpoints/auth/managed_authorization.pyindex cbbd1548301..cdbbd6029fa 100644--- a/litellm/proxy/agent_endpoints/auth/managed_authorization.py+++ b/litellm/proxy/agent_endpoints/auth/managed_authorization.py@@ -32,6 +32,7 @@ _MANAGED_MODEL_ROUTES: Final = frozenset("rerank","decisions","systemone",+ "extraction","ocr",),)@@ -77,6 +78,7 @@ _MODEL_ROUTE_KINDS: Final["/rerank": "body","/decisions": "body","/systemone": "body",+ "/extraction": "body","/messages/count_tokens": "body",":countTokens": "path",}diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.pyindex 2ffdd02cdf5..59db23820fc 100644--- a/litellm/proxy/common_request_processing.py+++ b/litellm/proxy/common_request_processing.py@@ -133,12 +133,14 @@ from litellm.router import Routerfrom litellm.router_utils.add_retry_fallback_headers import get_hidden_params_dictfrom litellm.router_utils.auto_router_model_naming import AUTO_ROUTER_MODEL_PREFIXfrom litellm.router_utils.common_utils import resolve_model_group_alias, resolve_served_model+from litellm.types.extraction import ExtractionResponsefrom litellm.types.guardrails import GuardrailEventHooksfrom litellm.types.router import RouterRateLimitErrorfrom litellm.types.router_weights import validate_router_weights_LateResponseT = TypeVar("_LateResponseT", bound=Response)_LlmCallT = TypeVar("_LlmCallT")+_ResponseT: Final = TypeVar("_ResponseT")_ChunkT: Final = TypeVar("_ChunkT")KNOWN_PROXY_ROUTES: Final = frozenset(@@ -190,6 +192,7 @@ ProxyRouteType: TypeAlias = Literal["asearch","adecisions","asystemone",+ "aextraction","avideo_generation","avideo_list","avideo_status",@@ -1481,11 +1484,11 @@ _is_azure_model_router_request: Final = is_azure_model_router_requestdef _override_openai_response_model(*,- response_obj: object,+ response_obj: _ResponseT,requested_model: str,log_context: str,return_raw_model_name: bool = False,-) -> None:+) -> _ResponseT:"""Force the OpenAI-compatible `model` field in the response to match what the client requested.@@ -1509,7 +1512,7 @@ def _override_openai_response_model(model group name instead of the comma-separated list the client sent."""if return_raw_model_name or not requested_model:- return+ return response_objhidden_params: Final = get_hidden_params_dict(response_obj)if isinstance(hidden_params, dict):@@ -1522,7 +1525,7 @@ def _override_openai_response_model(log_context,attempted_fallbacks,)- return+ return response_obj# For fastest_response batch completions, use the winning model's group# name rather than the comma-separated list the client sent.@@ -1541,7 +1544,7 @@ def _override_openai_response_model("%s: fastest_response detected but no model group header found, preserving actual model from response.",log_context,)- return+ return response_obj# Check if this is an Azure Model Router request - if so, preserve the actual model usedif is_azure_model_router_request(requested_model, hidden_params):@@ -1549,11 +1552,12 @@ def _override_openai_response_model("%s: Azure Model Router detected - preserving actual model used from response instead of overriding to router model.",log_context,)- return+ return response_obj+ unchanged_response: Final = response_objif isinstance(response_obj, dict):if "model" not in response_obj:- return+ return unchanged_responsedownstream_model = response_obj.get("model")if downstream_model != requested_model:verbose_proxy_logger.debug(@@ -1563,10 +1567,10 @@ def _override_openai_response_model(downstream_model,)response_obj["model"] = requested_model- return+ return unchanged_responseif not hasattr(response_obj, "model"):- return+ return response_objdownstream_model = getattr(response_obj, "model", None)if downstream_model != requested_model:@@ -1577,6 +1581,9 @@ def _override_openai_response_model(downstream_model,)+ if isinstance(response_obj, ExtractionResponse):+ return response_obj.model_copy(update={"model": requested_model})+try:setattr(response_obj, "model", requested_model)except Exception as e:@@ -1588,6 +1595,7 @@ def _override_openai_response_model(str(e),exc_info=True,)+ return response_obj_METADATA_BUCKET_KEYS: Final = ("metadata", "litellm_metadata")@@ -2200,6 +2208,7 @@ class ProxyBaseLLMRequestProcessing:"asearch","adecisions","asystemone",+ "aextraction","avideo_generation","avideo_list","avideo_status",@@ -3226,7 +3235,7 @@ class ProxyBaseLLMRequestProcessing:# Always return the client-requested model name (not provider-prefixed internal identifiers)# for OpenAI-compatible responses.if requested_model_from_client:- _override_openai_response_model(+ response = _override_openai_response_model( # rebind-ok: a frozen response comes back as a copyresponse_obj=response,requested_model=requested_model_from_client,log_context=f"litellm_call_id={logging_obj.litellm_call_id}",diff --git a/litellm/proxy/decisions_endpoints/endpoints.py b/litellm/proxy/decisions_endpoints/endpoints.pyindex 1477e9f9591..366842d23a6 100644--- a/litellm/proxy/decisions_endpoints/endpoints.py+++ b/litellm/proxy/decisions_endpoints/endpoints.py@@ -1,6 +1,6 @@from collections.abc import Mappingfrom types import MappingProxyType-from typing import Annotated, Final, Literal+from typing import Annotated, Final, Literal, TypeAliasfrom fastapi import APIRouter, Depends, Request, Responsefrom fastapi.responses import ORJSONResponse # pyright: ignore[reportDeprecated] # required endpoint contract@@ -18,6 +18,7 @@ from litellm.types.decisions import (OpenAIDecisionRequestBody,OpenAIDecisionResponse,)+from litellm.types.extraction import ExtractionRequest, ExtractionRequestBody, ExtractionResponserouter: Final = APIRouter()_REQUEST_DATA_ADAPTER: Final[TypeAdapter[dict[str, object]]] = TypeAdapter(dict[str, object])@@ -25,6 +26,7 @@ _DECISIONS_REQUEST_BODY_ADAPTER: Final[TypeAdapter[DecisionsRequestBody]] = Type_OPENAI_DECISION_REQUEST_BODY_ADAPTER: Final[TypeAdapter[OpenAIDecisionRequestBody]] = TypeAdapter(OpenAIDecisionRequestBody)+_EXTRACTION_REQUEST_BODY_ADAPTER: Final[TypeAdapter[ExtractionRequestBody]] = TypeAdapter(ExtractionRequestBody)_GENERAL_SETTINGS_ADAPTER: Final[TypeAdapter[dict[str, object]]] = TypeAdapter(dict[str, object])_OPTIONAL_STRING_ADAPTER: Final[TypeAdapter[str | None]] = TypeAdapter(str | None)_OPTIONAL_FLOAT_ADAPTER: Final[TypeAdapter[float | None]] = TypeAdapter(float | None)@@ -73,16 +75,35 @@ _DECISIONS_REQUEST_BODY: Final = inline_request_body(],},)+_EXTRACTION_REQUEST_BODY: Final = inline_request_body(+ ExtractionRequest,+ {+ "model": "clairic",+ "state": "Invoice #4471 from Acme Tools, dated 2026-03-03. 12 hammers. Total $174. Payment due in 30 days.",+ "fields": {+ "vendor": {"type": "text", "instructions": "Who sent the invoice?"},+ "invoice_date": {"type": "date"},+ "total": {"type": "number", "unit": "USD"},+ "items": {"type": "list", "items": "text", "instructions": "What was bought?"},+ "days_to_pay": {"type": "estimate", "min": 0, "max": 90},+ },+ },+)+_ApiName: TypeAlias = Literal["Decisions", "Extraction"]+_RouteType: TypeAlias = Literal["adecisions", "asystemone", "aextraction"]async def _invalid_request(- raw_data: Mapping[str, object], error: ValidationError, user_api_key_dict: UserAPIKeyAuth+ raw_data: Mapping[str, object],+ error: ValidationError,+ user_api_key_dict: UserAPIKeyAuth,+ api_name: _ApiName,) -> Exception:from litellm.proxy.proxy_server import proxy_logging_obj, versionreturn await ProxyBaseLLMRequestProcessing(data=dict(raw_data)).handle_llm_api_exception(e=BadRequestError(- message=f"Invalid Decisions request: {error}",+ message=f"Invalid {api_name} request: {error}",model=str(raw_data.get("model", "")),llm_provider="",),@@ -95,19 +116,21 @@ async def _invalid_request(_FIELDS_CHECKED_AFTER_ROUTING: Final = frozenset({"safety_identifier", "images", "assets", "audio", "videos"})-def _fields_checked_before_routing(data: Mapping[str, object]) -> Mapping[str, object]:+def _fields_checked_before_routing(data: Mapping[str, object], route_type: _RouteType) -> Mapping[str, object]:+ if route_type == "aextraction":+ return datareturn MappingProxyType({key: value for key, value in data.items() if key not in _FIELDS_CHECKED_AFTER_ROUTING})_DEPLOYMENT_ONLY_FIELDS: Final = frozenset({"model_info"})-async def _request_data(request: Request, user_api_key_dict: UserAPIKeyAuth) -> dict[str, object]:+async def _request_data(request: Request, user_api_key_dict: UserAPIKeyAuth, api_name: _ApiName) -> dict[str, object]:body: Final = await request.body()try:data: Final = _REQUEST_DATA_ADAPTER.validate_json(body)except ValidationError as error:- raise await _invalid_request(raw_data={}, error=error, user_api_key_dict=user_api_key_dict)+ raise await _invalid_request(raw_data={}, error=error, user_api_key_dict=user_api_key_dict, api_name=api_name)return {key: value for key, value in data.items() if key not in _DEPLOYMENT_ONLY_FIELDS}@@ -115,8 +138,10 @@ async def _process_decisions(request: Request,fastapi_response: Response,user_api_key_dict: UserAPIKeyAuth,- body_adapter: TypeAdapter[DecisionsRequestBody] | TypeAdapter[OpenAIDecisionRequestBody],- route_type: Literal["adecisions", "asystemone"],+ body_adapter: (+ TypeAdapter[DecisionsRequestBody] | TypeAdapter[OpenAIDecisionRequestBody] | TypeAdapter[ExtractionRequestBody]+ ),+ route_type: _RouteType,) -> object:from litellm.proxy.proxy_server import (general_settings as proxy_general_settings,@@ -139,15 +164,17 @@ async def _process_decisions(user_temperature as proxy_user_temperature,)- data: Final = await _request_data(request, user_api_key_dict)+ api_name: Final[_ApiName] = "Extraction" if route_type == "aextraction" else "Decisions"+ data: Final = await _request_data(request, user_api_key_dict, api_name)try:- body_adapter.validate_python(_fields_checked_before_routing(data))+ body_adapter.validate_python(_fields_checked_before_routing(data, route_type))except ValidationError as error:- raise await _invalid_request(raw_data=data, error=error, user_api_key_dict=user_api_key_dict)+ raise await _invalid_request(raw_data=data, error=error, user_api_key_dict=user_api_key_dict, api_name=api_name)general_settings: Final = _GENERAL_SETTINGS_ADAPTER.validate_python(proxy_general_settings)user_api_base: Final = _OPTIONAL_STRING_ADAPTER.validate_python(proxy_user_api_base)user_model: Final = _OPTIONAL_STRING_ADAPTER.validate_python(proxy_user_model)user_temperature: Final = _OPTIONAL_FLOAT_ADAPTER.validate_python(proxy_user_temperature)+ takes_generation_settings: Final = route_type != "aextraction"processor: Final = ProxyBaseLLMRequestProcessing(data=data)try:return await processor.base_process_llm_request(@@ -162,9 +189,9 @@ async def _process_decisions(select_data_generator=None,model=None,user_model=user_model,- user_temperature=user_temperature,+ user_temperature=user_temperature if takes_generation_settings else None,user_request_timeout=user_request_timeout,- user_max_tokens=user_max_tokens,+ user_max_tokens=user_max_tokens if takes_generation_settings else None,user_api_base=user_api_base,version=version,)@@ -263,3 +290,53 @@ async def decisions(body_adapter=_OPENAI_DECISION_REQUEST_BODY_ADAPTER,route_type="adecisions",)+++ "/v1/extraction",+ dependencies=[Depends(user_api_key_auth)],+ response_class=ORJSONResponse, # pyright: ignore[reportDeprecated] # required endpoint contract+ tags=["extraction"],+ summary="Extract typed fields from a state",+ responses={200: {"model": ExtractionResponse}},+ response_model=None,+ openapi_extra={"requestBody": _EXTRACTION_REQUEST_BODY},+)+ "/extraction",+ dependencies=[Depends(user_api_key_auth)],+ response_class=ORJSONResponse, # pyright: ignore[reportDeprecated] # required endpoint contract+ tags=["extraction"],+ summary="Extract typed fields from a state",+ responses={200: {"model": ExtractionResponse}},+ response_model=None,+ openapi_extra={"requestBody": _EXTRACTION_REQUEST_BODY},+)+async def extraction(+ request: Request,+ fastapi_response: Response,+ user_api_key_dict: Annotated[UserAPIKeyAuth, Depends(user_api_key_auth)],+) -> object:+ """+ Read a `state` text and up to 4 images and get one typed answer per named field in `fields`.++ Field types are `text`, `number`, `date`, `time`, `datetime`, `duration`, `list` (set `items`), `estimate`+ (set `min` and `max`) and `forecast` (set `min`, `max` and `horizon`). Each answer carries its `value`, which is+ null when the input does not determine it, plus `confidence`, `p_null`, text `span`s into the state and, for+ estimates, `mean`, `median`, `p10` and `p90`. Images are data URLs or `{content_type, base64}` objects, remote+ URLs are not accepted. An unknown field type, a field name that is not 1 to 64 letters, digits, `_`, `.` or `-`+ starting with a letter or `_`, a remote image URL or more than 4 images is rejected with a 400 before any+ provider is called. Any other top-level key, `stream: true` and OpenAI generation settings such as `temperature`+ included, is rejected with a 400 naming it unless `drop_params` or the deployment's `additional_drop_params`+ drops it. Settings inside `fields` and `options` go to the provider as sent, so a field missing a setting its+ type needs or an empty `state` with no images comes back with the provider's own error. `model` is any+ extraction model in the proxy model list, such as Cloudflare Clairic. The request and the answers keep the+ provider's format.+ """+ return await _process_decisions(+ request=request,+ fastapi_response=fastapi_response,+ user_api_key_dict=user_api_key_dict,+ body_adapter=_EXTRACTION_REQUEST_BODY_ADAPTER,+ route_type="aextraction",+ )diff --git a/litellm/proxy/health_endpoints/_health_endpoints.py b/litellm/proxy/health_endpoints/_health_endpoints.pyindex 1e7f67392e1..684f1619512 100644--- a/litellm/proxy/health_endpoints/_health_endpoints.py+++ b/litellm/proxy/health_endpoints/_health_endpoints.py@@ -2155,6 +2155,7 @@ async def test_model_connection("ocr","evaluation","decisions",+ "extraction",]| None = fastapi.Body(None,diff --git a/litellm/proxy/hooks/parallel_request_limiter_v3.py b/litellm/proxy/hooks/parallel_request_limiter_v3.pyindex d858eff3348..4f2f7f9c256 100644--- a/litellm/proxy/hooks/parallel_request_limiter_v3.py+++ b/litellm/proxy/hooks/parallel_request_limiter_v3.py@@ -7,6 +7,7 @@ This is currently in development and not yet ready for production.import asyncioimport binasciiimport itertools+import jsonimport loggingimport osimport uuid@@ -42,6 +43,7 @@ from litellm.caching.redis_batch import ()from litellm.caching.redis_cache import log_redis_failurefrom litellm.constants import DYNAMIC_RATE_LIMIT_ERROR_THRESHOLD_PER_MINUTE, INTERNAL_CALL_ORIGIN_METADATA_KEY+from litellm.cost_calculator import get_usage_objectfrom litellm.integrations.custom_logger import CustomLoggerfrom litellm.litellm_core_utils.prompt_templates.common_utils import (get_str_from_messages,@@ -78,6 +80,7 @@ from litellm.router_utils.add_retry_fallback_headers import (from litellm.router_utils.common_utils import resolve_model_group_aliasfrom litellm.router_utils.ptu_shares import PTUTeamCeilingfrom litellm.types.caching import RedisPipelineIncrementOperation+from litellm.types.extraction import ExtractionResponsefrom litellm.types.llms.openai import BaseLiteLLMOpenAIResponseObject, ResponseAPIUsagefrom litellm.types.mcp_server.mcp_server_manager import MCPServerfrom litellm.types.passthrough_endpoints.pass_through_endpoints import EndpointType@@ -490,6 +493,7 @@ RESPONSES_API_CALL_TYPES: Final = ("aresponses", "responses")EMBEDDING_API_CALL_TYPES: Final = ("aembedding", "embedding")TEXT_COMPLETION_API_CALL_TYPES: Final = ("atext_completion", "text_completion")RERANK_API_CALL_TYPES: Final = (CallTypes.rerank.value, CallTypes.arerank.value)+EXTRACTION_API_CALL_TYPES: Final = (CallTypes.extraction.value, CallTypes.aextraction.value)GOOGLE_GENAI_NATIVE_CALL_TYPES: Final = (CallTypes.generate_content.value,CallTypes.agenerate_content.value,@@ -1094,6 +1098,7 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):or PROXY_MaxParallelRequestsHandler_v3._has_explicit_output_cap(data, call_type)or is_embeddingor endpoint_type == EndpointType.DECISIONS+ or call_type in EXTRACTION_API_CALL_TYPES):returneffective_cap: Final = max(capped_floor, configured_output_tokens or 0)@@ -1218,6 +1223,8 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):if call_type in RESPONSES_API_CALL_TYPES or call_type in EMBEDDING_API_CALL_TYPESelse (None, estimable_data.get("prompt"), None)if call_type in TEXT_COMPLETION_API_CALL_TYPES+ else (None, self._extraction_input_text(_REQUEST_RATE_LIMIT_DATA.validate_python(estimable_data)), None)+ if call_type in EXTRACTION_API_CALL_TYPESelse (estimable_data.get("messages"), None, None)if call_typeelse (@@ -1245,7 +1252,9 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):estimated_input_tokens: Final = max(1, total_chars // DEFAULT_CHARS_PER_TOKEN) if total_chars > 0 else 0explicit_max_tokens: Final = self._get_explicit_output_cap(data, call_type)- is_embedding: Final = self._is_embedding_request(data, call_type)+ generates_no_output: Final = (+ self._is_embedding_request(data, call_type) or call_type in EXTRACTION_API_CALL_TYPES+ )base_output_floor: Final = self.no_max_tokens_output_floor(min_configured_tpm_limit)output_floor: Final = (@@ -1255,7 +1264,8 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):)max_tokens_estimate: Final = (0- if is_embedding or (explicit_max_tokens is None and total_chars == 0 and configured_output_tokens is None)+ if generates_no_output+ or (explicit_max_tokens is None and total_chars == 0 and configured_output_tokens is None)else explicit_max_tokensif explicit_max_tokens is not Noneelse configured_output_tokens@@ -3834,6 +3844,11 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):if isinstance(part, (str, dict)))+ @staticmethod+ def _extraction_input_text(data: Mapping[str, object]) -> str:+ state: Final = data.get("state")+ return f"{state if isinstance(state, str) else ''}\n{json.dumps(data.get('fields'), default=str)}"+def _estimate_precise_input_tokens(self, data: object, model: str | None, call_type: str | None = None) -> int:"""Model-aware input token estimate for the project ITPM reservation,@@ -3892,6 +3907,8 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):if call_type in RERANK_API_CALL_TYPESelse (None, prompt, data.get("tools"), data.get("tool_choice"))if call_type in TEXT_COMPLETION_API_CALL_TYPES+ else (None, self._extraction_input_text(_REQUEST_RATE_LIMIT_DATA.validate_python(data)), None, None)+ if call_type in EXTRACTION_API_CALL_TYPESelse (data.get("messages"), fallback_text, data.get("tools"), data.get("tool_choice")))messages, selected_text, countable_tools, countable_tool_choice = selected_inputs@@ -4512,6 +4529,8 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):) -> Usage | ResponseAPIUsage | Mapping[str, object] | None:if isinstance(response_obj, (Usage, ResponseAPIUsage)):return response_obj+ if isinstance(response_obj, ExtractionResponse):+ return get_usage_object(response_obj)if isinstance(response_obj,(ModelResponse, EmbeddingResponse, TextCompletionResponse, BaseLiteLLMOpenAIResponseObject),@@ -5143,21 +5162,24 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):# than parsed out of the body) carry their usage in# ``combined_usage_object`` instead, and would otherwise never charge# the TPM window.- _usage: Usage | dict[str, object] | None = None- if isinstance(- response_obj,- (- ModelResponse,- EmbeddingResponse,- TextCompletionResponse,- BaseLiteLLMOpenAIResponseObject,- ),- ):- _usage = getattr(response_obj, "usage", None)- else:- _combined_usage: Final = kwargs.get("combined_usage_object")- if isinstance(_combined_usage, Usage):- _usage = _combined_usage+ _combined_usage: Final = kwargs.get("combined_usage_object")+ _usage: Final[Usage | dict[str, object] | None] = (+ getattr(response_obj, "usage", None)+ if isinstance(+ response_obj,+ (+ ModelResponse,+ EmbeddingResponse,+ TextCompletionResponse,+ BaseLiteLLMOpenAIResponseObject,+ ),+ )+ else get_usage_object(response_obj)+ if isinstance(response_obj, ExtractionResponse)+ else _combined_usage+ if isinstance(_combined_usage, Usage)+ else None+ )total_tokens = self._get_total_tokens_from_usage(usage=_usage, rate_limit_type=rate_limit_type)if total_tokens == 0:total_tokens = self._aggregate_only_total_tokens(usage=_usage)diff --git a/litellm/proxy/route_llm_request.py b/litellm/proxy/route_llm_request.pyindex e16e14c8d54..25f9f1dff15 100644--- a/litellm/proxy/route_llm_request.py+++ b/litellm/proxy/route_llm_request.py@@ -111,6 +111,7 @@ ROUTE_ENDPOINT_MAPPING: Final = {"asearch": "/search","adecisions": "/decisions","asystemone": "/systemone",+ "aextraction": "/extraction","avideo_generation": "/videos","avideo_list": "/videos","avideo_status": "/videos/{video_id}",@@ -573,6 +574,7 @@ RouteType = Literal["asearch","adecisions","asystemone",+ "aextraction","avideo_generation","avideo_list","avideo_status",diff --git a/litellm/router.py b/litellm/router.pyindex 679f4eba1ea..a18ad7c3a97 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -2525,6 +2525,11 @@ class Router:self.asystemone = self.factory_function(asystemone, call_type="asystemone") # pyright: ignore[reportUnknownMemberType] # factory_function takes a bare Callableself.systemone = self.factory_function(systemone, call_type="systemone") # pyright: ignore[reportUnknownMemberType] # factory_function takes a bare Callable+ from litellm.extraction import aextraction, extraction++ self.aextraction = self.factory_function(aextraction, call_type="aextraction") # pyright: ignore[reportUnknownMemberType] # factory_function takes a bare Callable+ self.extraction = self.factory_function(extraction, call_type="extraction") # pyright: ignore[reportUnknownMemberType] # factory_function takes a bare Callable+def _initialize_video_endpoints(self):"""Initialize video endpoints."""from litellm.videos import (@@ -7705,6 +7710,8 @@ class Router:"decisions","asystemone","systemone",+ "aextraction",+ "extraction","aadapter_generate_content","avideo_generation","video_generation",@@ -7780,6 +7787,7 @@ class Router:"search","decisions","systemone",+ "extraction","video_generation","video_list","video_status",@@ -7949,6 +7957,7 @@ class Router:"ocr","adecisions","asystemone",+ "aextraction","avideo_generation","avideo_list","avideo_status",diff --git a/litellm/types/extraction.py b/litellm/types/extraction.pynew file mode 100644index 00000000000..4311e549b9a--- /dev/null+++ b/litellm/types/extraction.py@@ -0,0 +1,162 @@+from collections.abc import Mapping, Sequence+from typing import Annotated, Final, Literal, TypeAlias++from pydantic import (+ ConfigDict,+ Field,+ JsonValue,+ PrivateAttr,+ StrictBool,+ StrictFloat,+ StrictInt,+ StrictStr,+ model_validator,+ with_config,+)+from typing_extensions import ReadOnly, Required, Self, TypedDict++from litellm.types.llms.base import LiteLLMPydanticObjectBase++ExtractionFieldType: TypeAlias = Literal[+ "text", "number", "date", "time", "datetime", "duration", "list", "estimate", "forecast"+]+ExtractionFieldName: TypeAlias = Annotated[str, Field(pattern=r"^[A-Za-z_][A-Za-z0-9_.\-]{0,63}$")]+JsonNumber: TypeAlias = StrictInt | StrictFloat+ExtractionBound: TypeAlias = JsonNumber | StrictStr+EXTRACTION_STATE_REWRITTEN_METADATA_KEY: Final = "extraction_state_rewritten_by_guardrail"+++def _is_none(value: object) -> bool:+ return value is None+++_OMITTED_WHEN_NONE: Final = Field(exclude_if=_is_none)+OptionalJson: TypeAlias = Annotated[JsonValue, _OMITTED_WHEN_NONE]+OptionalFloat: TypeAlias = Annotated[float | None, _OMITTED_WHEN_NONE]+OptionalInt: TypeAlias = Annotated[int | None, _OMITTED_WHEN_NONE]+++class _ClairicObject(LiteLLMPydanticObjectBase):+ model_config = ConfigDict(extra="allow", frozen=True)+++class ExtractionField(_ClairicObject):+ type: Annotated[ExtractionFieldType, Field(description="The answer type for this field")]+ instructions: Annotated[str | None, Field(description="What the field should contain")] = None+ unit: Annotated[str | None, Field(description="Unit label. For durations, seconds through years")] = None+ integer: Annotated[StrictBool | None, Field(description="Numbers and durations only")] = None+ decimals: Annotated[JsonNumber | None, Field(description="Numbers, durations and number lists only, 0 to 6")] = None+ items: Annotated[+ Literal["text", "number", "date"] | None, Field(description="Item type, required for list fields")+ ] = None+ min: Annotated[ExtractionBound | None, Field(description="Estimate and forecast lower bound")] = None+ max: Annotated[ExtractionBound | None, Field(description="Estimate and forecast upper bound")] = None+ step: Annotated[ExtractionBound | None, Field(description="Estimate grid step, or month or year")] = None+ scale: Literal["linear", "log"] | None = None+ null_threshold: Annotated[+ JsonNumber | None, Field(description="Probability of null above which the value is null")+ ] = None+ horizon: Annotated[JsonNumber | None, Field(description="Forecast only, number of steps")] = None+ interval: Literal["step", "minute", "hour", "day", "week", "month", "quarter", "year"] | None = None++ @model_validator(mode="after")+ def _list_fields_name_their_item_type(self) -> Self:+ if self.type == "list" and self.items is None:+ raise ValueError("list fields need items set to text, number or date")+ return self+++class ExtractionBase64Image(_ClairicObject):+ content_type: Annotated[str, Field(description="The image media type, such as image/png")]+ base64: Annotated[str, Field(description="Base64-encoded image bytes")]+++ExtractionImage: TypeAlias = Annotated[str, Field(pattern=r"^[Dd][Aa][Tt][Aa]:")] | ExtractionBase64Image+++class ExtractionOptions(_ClairicObject):+ include_quantiles: Annotated[StrictBool | None, Field(description="Add 99 percentiles to estimates")] = None+ return_state_text: Annotated[StrictBool | None, Field(description="Return the text that spans index into")] = None+++class ExtractionRequestBody(_ClairicObject):+ state: Annotated[+ str,+ Field(description="The text to read. Must be non-empty unless images are sent. Text answers are spans of it"),+ ] = ""+ fields: Annotated[+ Mapping[ExtractionFieldName, ExtractionField],+ Field(min_length=1, description="Field name to typed field spec. Each name becomes a key in the answers"),+ ]+ images: Annotated[+ tuple[ExtractionImage, ...] | None,+ Field(max_length=4, description="Up to 4 images as data URLs or content_type plus base64, no remote URLs"),+ ] = None+ reference_date: Annotated[str | None, Field(description="ISO date that anchors dates written without a year")] = (+ None+ )+ options: ExtractionOptions | None = None+++class ExtractionRequest(ExtractionRequestBody):+ model: Annotated[str, Field(description="An extraction model from the proxy model_list")]+++class ExtractionAnswer(_ClairicObject):+ type: str+ value: Annotated[JsonValue, Field(description="The answer, null when the input does not determine it")]+ guess: OptionalJson = None+ p_null: OptionalFloat = None+ confidence: OptionalFloat = None+ span: Annotated[tuple[int, ...] | None, _OMITTED_WHEN_NONE] = None+ spans: Annotated[tuple[tuple[int, ...], ...] | None, _OMITTED_WHEN_NONE] = None+ mean: OptionalJson = None+ median: OptionalJson = None+ p10: OptionalJson = None+ p90: OptionalJson = None+ p_below: OptionalFloat = None+ p_above: OptionalFloat = None+ quantiles: Annotated[tuple[JsonValue, ...] | None, _OMITTED_WHEN_NONE] = None+ steps: Annotated[tuple[JsonValue, ...] | None, _OMITTED_WHEN_NONE] = None+++class ExtractionUsage(_ClairicObject):+ input_tokens: int+ output_tokens: int+ state_tokens: OptionalInt = None+ image_tokens: OptionalInt = None+ schema_tokens: OptionalInt = None+ passes: OptionalInt = None+++class ExtractionResponse(_ClairicObject):+ model: str+ answers: Mapping[str, ExtractionAnswer]+ truncated: bool+ state_text: Annotated[str | None, _OMITTED_WHEN_NONE] = None+ usage: ExtractionUsage++ _hidden_params: dict[str, object] = PrivateAttr( # mutable-ok: @client and the proxy write cost into it in place+ default_factory=dict+ )++ @property+ def hidden_params(self) -> dict[str, object]: # mutable-ok: API requires mutation+ return self._hidden_params++ def set_hidden_params(self, params: Mapping[str, object]) -> None:+ self._hidden_params.update(params)+++@with_config(ConfigDict(extra="allow"))+class ExtractionCallParams(TypedDict, total=False):+ model: Required[ReadOnly[str]]+ state: Required[ReadOnly[str]]+ fields: Required[ReadOnly[Mapping[str, Mapping[str, object]]]]+ images: ReadOnly[Sequence[str | Mapping[str, object]] | None]+ reference_date: ReadOnly[str | None]+ api_key: ReadOnly[str | None]+ api_base: ReadOnly[str | None]+ timeout: ReadOnly[float | None]+ custom_llm_provider: ReadOnly[str | None]+ extra_headers: ReadOnly[Mapping[str, str] | None]diff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex 61a179b8b65..f86c6cfd4b6 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -458,6 +458,7 @@ class ModelInfoBase(ProviderSpecificModelInfo, total=False):"responses","decisions","evaluation",+ "extraction","ocr","realtime",]@@ -518,6 +519,8 @@ class CallTypes(str, Enum):adecisions = "adecisions"systemone = "systemone"asystemone = "asystemone"+ extraction = "extraction"+ aextraction = "aextraction"arealtime = "_arealtime"aresponses_websocket = "_aresponses_websocket"create_batch = "create_batch"@@ -708,6 +711,8 @@ CallTypesLiteral = Literal["adecisions","systemone","asystemone",+ "extraction",+ "aextraction","_arealtime","_aresponses_websocket","create_batch",@@ -821,6 +826,8 @@ API_ROUTE_TO_CALL_TYPES: Final[Mapping[str, Sequence[CallTypes]]] = {"/v1/decisions": [CallTypes.adecisions, CallTypes.decisions],"/systemone": [CallTypes.asystemone, CallTypes.systemone],"/v1/systemone": [CallTypes.asystemone, CallTypes.systemone],+ "/extraction": [CallTypes.aextraction, CallTypes.extraction],+ "/v1/extraction": [CallTypes.aextraction, CallTypes.extraction],# Batches"/batches": [CallTypes.acreate_batch, CallTypes.create_batch],"/v1/batches": [CallTypes.acreate_batch, CallTypes.create_batch],diff --git a/litellm/utils.py b/litellm/utils.pyindex a9079f470c7..4687e4fa27a 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -390,6 +390,7 @@ if TYPE_CHECKING:from litellm.llms.base_llm.containers.transformation import BaseContainerConfigfrom litellm.llms.base_llm.decisions.transformation import BaseDecisionsConfigfrom litellm.llms.base_llm.embedding.transformation import BaseEmbeddingConfig+ from litellm.llms.base_llm.extraction.transformation import BaseExtractionConfigfrom litellm.llms.base_llm.files.transformation import BaseFilesConfigfrom litellm.llms.base_llm.google_genai.transformation import (BaseGoogleGenAIGenerateContentConfig,@@ -2166,7 +2167,11 @@ def client(original_function):# Sync logging_obj.stream after deployment hooks (they may convert it)._hook_stream: Final = kwargs.get("stream")- if _hook_stream is not None and logging_obj.stream != _hook_stream:+ if (+ _hook_stream is not None+ and logging_obj.stream != _hook_stream+ and call_type not in _NEVER_STREAMING_CALL_TYPES+ ):logging_obj.stream = _hook_streamkwargs["litellm_logging_obj"] = logging_obj@@ -2510,6 +2515,15 @@ _STREAMING_CALL_TYPES: Final = frozenset(})+_NEVER_STREAMING_CALL_TYPES: Final = frozenset(+ {+ CallTypes.extraction,+ CallTypes.aextraction,+ CallTypes.extraction.value,+ CallTypes.aextraction.value,+ }+)+def _is_streaming_request(kwargs: dict[str, object],@@ -2521,6 +2535,8 @@ def _is_streaming_request(- if "stream=True" in kwargs (litellm chat completion, litellm text completion, litellm messages)- if call_type is generate_content_stream or agenerate_content_stream (litellm google genai)"""+ if call_type in _NEVER_STREAMING_CALL_TYPES:+ return Falseif "stream" in kwargs and kwargs["stream"] is True:return Truereturn call_type in _STREAMING_CALL_TYPES@@ -9539,6 +9555,12 @@ class ProviderConfigManager:return litellm.AzureAIDecisionsConfig()return None+ @staticmethod+ def get_provider_extraction_config(model: str, provider: LlmProviders) -> BaseExtractionConfig | None:+ if provider == LlmProviders.CLOUDFLARE:+ return litellm.CloudflareExtractionConfig()+ return None+@staticmethoddef get_provider_anthropic_messages_config(model: str,diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.jsonindex c6aea8ec98a..04a3f9225ce 100644--- a/model_prices_and_context_window.json+++ b/model_prices_and_context_window.json@@ -16580,6 +16580,24 @@"source": "https://developers.cloudflare.com/workers-ai/platform/pricing/","supports_vision": true},+ "cloudflare/clairic": {+ "input_cost_per_token": 1e-07,+ "litellm_provider": "cloudflare",+ "max_input_tokens": 65536,+ "mode": "extraction",+ "output_cost_per_token": 0.0,+ "source": "https://developers.cloudflare.com/workers-ai/models/clairic/",+ "supports_vision": true+ },+ "cloudflare/@cf/cloudflare/clairic": {+ "input_cost_per_token": 1e-07,+ "litellm_provider": "cloudflare",+ "max_input_tokens": 65536,+ "mode": "extraction",+ "output_cost_per_token": 0.0,+ "source": "https://developers.cloudflare.com/workers-ai/models/clairic/",+ "supports_vision": true+ },"cloudflare/@cf/meta/llama-2-7b-chat-fp16": {"input_cost_per_token": 1.923e-06,"litellm_provider": "cloudflare",diff --git a/model_prices_and_context_window.schema.json b/model_prices_and_context_window.schema.jsonindex 016d40ea874..d4dfeb25429 100644--- a/model_prices_and_context_window.schema.json+++ b/model_prices_and_context_window.schema.json@@ -553,6 +553,7 @@"completion","embedding","evaluation",+ "extraction","guardrail","image_edit","image_generation",diff --git a/tests/benchmarks/test_extraction_guardrail_benchmarks.py b/tests/benchmarks/test_extraction_guardrail_benchmarks.pynew file mode 100644index 00000000000..0d8a3db42ce--- /dev/null+++ b/tests/benchmarks/test_extraction_guardrail_benchmarks.py@@ -0,0 +1,61 @@+import asyncio+from typing import Final, Literal++import pytest++from litellm.integrations.custom_guardrail import CustomGuardrail+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+from litellm.llms.cloudflare.extraction.guardrail_translation.handler import ExtractionHandler+from litellm.types.extraction import ExtractionResponse+from litellm.types.utils import GenericGuardrailAPIInputs++MANY_FIELDS: Final = 2_000+++class _MaskingGuardrail(CustomGuardrail):+ def __init__(self) -> None:+ super().__init__(guardrail_name="masking")++ async def apply_guardrail(+ self,+ inputs: GenericGuardrailAPIInputs,+ request_data: dict[str, object],+ input_type: Literal["request", "response"],+ logging_obj: LiteLLMLoggingObj | None = None,+ ) -> GenericGuardrailAPIInputs:+ return GenericGuardrailAPIInputs(texts=[text.replace("secret", "[MASKED]") for text in inputs.get("texts", [])])+++def test_extraction_request_guardrail_over_many_field_instructions() -> None:+ data: Final = {+ "model": "invoice-reader",+ "fields": {+ f"field_{index}": {"type": "text", "instructions": f"secret {index}"} for index in range(MANY_FIELDS)+ },+ }++ result: Final = asyncio.run(ExtractionHandler().process_input_messages(data, _MaskingGuardrail()))++ assert result["fields"] == {+ f"field_{index}": {"type": "text", "instructions": f"[MASKED] {index}"} for index in range(MANY_FIELDS)+ }+++def test_extraction_response_guardrail_over_many_text_answers() -> None:+ response: Final = ExtractionResponse.model_validate(+ {+ "model": "invoice-reader",+ "answers": {f"field_{index}": {"type": "text", "value": f"secret {index}"} for index in range(MANY_FIELDS)},+ "truncated": False,+ "usage": {"input_tokens": 52, "output_tokens": 0},+ }+ )++ result: Final = asyncio.run(ExtractionHandler().process_output_response(response, _MaskingGuardrail()))++ assert isinstance(result, ExtractionResponse)+ assert {name: answer.value for name, answer in result.answers.items()} == {+ f"field_{index}": f"[MASKED] {index}" for index in range(MANY_FIELDS)+ }diff --git a/tests/unit/extraction/__init__.py b/tests/unit/extraction/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/tests/unit/extraction/test_main.py b/tests/unit/extraction/test_main.pynew file mode 100644index 00000000000..584ed9cbb91--- /dev/null+++ b/tests/unit/extraction/test_main.py@@ -0,0 +1,422 @@+from __future__ import annotations++import asyncio+import json+import re+from collections.abc import Mapping+from types import MappingProxyType+from typing import Final++import httpx+import pytest+import respx++import litellm+from litellm.integrations.custom_logger import CustomLogger+from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER+from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler+from litellm.types.extraction import ExtractionResponse++_CLAIRIC_URL: Final = "https://api.cloudflare.com/client/v4/accounts/acct/ai/run/@cf/cloudflare/clairic"+_STATE: Final = "Invoice #4471 from Acme Tools, dated 2026-03-03. 12 hammers. Total $174. Payment due in 30 days."+_FIELDS: Final[Mapping[str, Mapping[str, object]]] = MappingProxyType(+ {+ "vendor": {"type": "text", "instructions": "Who sent the invoice?"},+ "invoice_date": {"type": "date"},+ "total": {"type": "number", "unit": "USD"},+ "items": {"type": "list", "items": "text"},+ "days_to_pay": {"type": "estimate", "min": 0, "max": 90, "provider_field": "kept"},+ }+)+_INPUT_TOKENS: Final = 416+_RESULT: Final[Mapping[str, object]] = {+ "model": "clairic",+ "answers": {+ "vendor": {+ "type": "text",+ "p_null": 0.0177,+ "span": [19, 29],+ "guess": "Acme Tools",+ "confidence": 0.9998,+ "value": "Acme Tools",+ },+ "invoice_date": {"type": "date", "p_null": 6.4e-07, "confidence": 0.99, "value": "2026-03-03"},+ "total": {"type": "number", "p_null": 4.2e-07, "guess": 174, "confidence": 0.99, "value": 174},+ "items": {"type": "list", "value": ["12", "hammers"], "spans": [[51, 53], [54, 61]], "confidence": 0.07},+ "days_to_pay": {+ "type": "estimate",+ "value": 31,+ "mean": 30.76,+ "median": 30,+ "p10": 29,+ "p90": 34,+ "p_below": 1.2e-06,+ "p_above": 1.2e-06,+ },+ },+ "truncated": False,+ "usage": {+ "state_tokens": 52,+ "image_tokens": 0,+ "schema_tokens": 312,+ "input_tokens": _INPUT_TOKENS,+ "output_tokens": 0,+ "passes": 2,+ },+}+_ENVELOPE: Final[Mapping[str, object]] = {"result": _RESULT, "success": True, "errors": [], "messages": []}+_PNG_DATA_URL: Final = "data:image/png;base64,AA=="++[email protected](autouse=True)+def _httpx_transport(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ litellm.in_memory_llm_clients_cache.flush_cache()+++def cloudflare_env(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("CLOUDFLARE_ACCOUNT_ID", "acct")+ monkeypatch.setenv("CLOUDFLARE_API_KEY", "cloudflare-key")+ monkeypatch.delenv("CLOUDFLARE_API_BASE", raising=False)+++def _assert_invoice_answers(response: ExtractionResponse) -> None:+ assert response.answers["vendor"].value == "Acme Tools"+ assert response.answers["vendor"].span == (19, 29)+ assert response.answers["items"].spans == ((51, 53), (54, 61))+ assert response.answers["days_to_pay"].median == 30+ assert response.usage.input_tokens == _INPUT_TOKENS+ assert response.usage.schema_tokens == 312+ assert response.truncated is False++[email protected]("model", ("cloudflare/clairic", "cloudflare/@cf/cloudflare/clairic"))[email protected]("cloudflare_env")+async def test_clairic_forwards_the_caller_body_and_unwraps_the_envelope(+ respx_mock: respx.MockRouter, model: str+) -> None:+ route: Final = respx_mock.post(_CLAIRIC_URL).respond(json=_ENVELOPE)++ response: Final = await litellm.aextraction(+ model=model,+ state=_STATE,+ fields=_FIELDS,+ images=[_PNG_DATA_URL, {"content_type": "image/jpeg", "base64": "AA=="}],+ reference_date="2026-03-04",+ options={"include_quantiles": True},+ )++ assert route.call_count == 1+ request: Final = route.calls[0].request+ assert request.headers["authorization"] == "Bearer cloudflare-key"+ assert json.loads(request.content) == {+ "model": "clairic",+ "state": _STATE,+ "fields": _FIELDS,+ "images": [_PNG_DATA_URL, {"content_type": "image/jpeg", "base64": "AA=="}],+ "reference_date": "2026-03-04",+ "options": {"include_quantiles": True},+ }+ _assert_invoice_answers(response)+ assert response.model == model+ assert response.hidden_params["model"] == "cloudflare/@cf/cloudflare/clairic"+ assert response.model_dump(mode="json", exclude={"model"}) == {+ key: value for key, value in _RESULT.items() if key != "model"+ }++[email protected]("cloudflare_env")+def test_sync_extraction_reads_an_unwrapped_result(respx_mock: respx.MockRouter) -> None:+ route: Final = respx_mock.post(_CLAIRIC_URL).respond(json=_RESULT)++ response: Final = litellm.extraction(model="cloudflare/clairic", state=_STATE, fields=_FIELDS)++ assert route.call_count == 1+ assert json.loads(route.calls[0].request.content) == {"model": "clairic", "state": _STATE, "fields": _FIELDS}+ _assert_invoice_answers(response)+++def _clairic_transport() -> httpx.MockTransport:+ def respond(request: httpx.Request) -> httpx.Response:+ assert str(request.url) == _CLAIRIC_URL+ return httpx.Response(200, json=_ENVELOPE)++ return httpx.MockTransport(respond)++[email protected]("cloudflare_env")+async def test_async_extraction_sends_through_the_callers_client(respx_mock: respx.MockRouter) -> None:+ response: Final = await litellm.aextraction(+ model="cloudflare/clairic",+ state=_STATE,+ fields=_FIELDS,+ client=AsyncHTTPHandler(transport=_clairic_transport()),+ )++ assert len(respx_mock.calls) == 0+ _assert_invoice_answers(response)++[email protected]("cloudflare_env")+def test_sync_extraction_sends_through_the_callers_client(respx_mock: respx.MockRouter) -> None:+ response: Final = litellm.extraction(+ model="cloudflare/clairic",+ state=_STATE,+ fields=_FIELDS,+ client=HTTPHandler(client=httpx.Client(transport=_clairic_transport())),+ )++ assert len(respx_mock.calls) == 0+ _assert_invoice_answers(response)++[email protected]("cloudflare_env")+async def test_a_cloudflare_bad_input_is_a_bad_request_with_the_cloudflare_message(+ respx_mock: respx.MockRouter,+) -> None:+ respx_mock.post(_CLAIRIC_URL).respond(+ status_code=400,+ json={+ "errors": [{"message": "AiError: Bad input: fields.total.decimals must be 0 to 6", "code": 5006}],+ "success": False,+ "result": {},+ "messages": [],+ },+ )++ with pytest.raises(litellm.BadRequestError, match=re.escape("fields.total.decimals must be 0 to 6")):+ await litellm.aextraction(+ model="cloudflare/clairic", state=_STATE, fields={"total": {"type": "number", "decimals": 9}}+ )+++ ("fields", "images"),+ (+ ({}, None),+ ({"total": {"type": "money"}}, None),+ ({"bad name": {"type": "text"}}, None),+ ({"total": {"type": "number"}}, ["https://example.com/invoice.png"]),+ ({"total": {"type": "number"}}, [_PNG_DATA_URL] * 5),+ ),+ ids=("no_fields", "unknown_type", "invalid_field_name", "remote_image", "too_many_images"),+)[email protected]("cloudflare_env")+async def test_an_invalid_request_is_refused_before_http(+ respx_mock: respx.MockRouter, fields: Mapping[str, object], images: list[str] | None+) -> None:+ with pytest.raises(litellm.BadRequestError, match="Invalid Extraction request"):+ await litellm.aextraction(model="cloudflare/clairic", state=_STATE, fields=fields, images=images)++ assert len(respx_mock.calls) == 0+++ ("unset", "message"),+ (+ ("CLOUDFLARE_ACCOUNT_ID", "Missing CLOUDFLARE_ACCOUNT_ID - set CLOUDFLARE_ACCOUNT_ID"),+ ("CLOUDFLARE_API_KEY", "Missing API key for Extraction provider 'cloudflare'"),+ ),+)[email protected]("cloudflare_env")+async def test_missing_cloudflare_credentials_are_refused_before_http(+ monkeypatch: pytest.MonkeyPatch, respx_mock: respx.MockRouter, unset: str, message: str+) -> None:+ monkeypatch.delenv(unset)++ with pytest.raises(litellm.BadRequestError, match=message):+ await litellm.aextraction(model="cloudflare/clairic", state=_STATE, fields=_FIELDS)++ assert len(respx_mock.calls) == 0+++async def test_a_provider_without_extraction_is_refused(respx_mock: respx.MockRouter) -> None:+ with pytest.raises(litellm.BadRequestError, match=r"Unknown Extraction provider 'openai'\. Supported.*cloudflare"):+ await litellm.aextraction(model="openai/gpt-5.5", state=_STATE, fields=_FIELDS, api_key="k")++ assert len(respx_mock.calls) == 0++[email protected]("model", ("cloudflare/clairic", "cloudflare/@cf/cloudflare/clairic"))[email protected]("cloudflare_env")+async def test_clairic_cost_bills_input_tokens_at_the_cost_map_price(respx_mock: respx.MockRouter, model: str) -> None:+ respx_mock.post(_CLAIRIC_URL).respond(json=_ENVELOPE)++ response: Final = await litellm.aextraction(model=model, state=_STATE, fields=_FIELDS)++ expected_cost: Final = _INPUT_TOKENS * float(litellm.model_cost[model]["input_cost_per_token"])+ assert expected_cost > 0+ assert litellm.completion_cost(completion_response=response) == pytest.approx(expected_cost)+ assert response.hidden_params["response_cost"] == pytest.approx(expected_cost)+++async def test_router_extraction_sends_the_deployment_model_and_credentials(respx_mock: respx.MockRouter) -> None:+ router: Final = litellm.Router(+ model_list=[+ {+ "model_name": "invoice-reader",+ "litellm_params": {+ "model": "cloudflare/clairic",+ "api_key": "deployment-key",+ "api_base": "https://api.cloudflare.com/client/v4/accounts/acct/ai/v1",+ "additional_drop_params": ["temperature"],+ },+ }+ ]+ )+ route: Final = respx_mock.post(_CLAIRIC_URL).respond(json=_ENVELOPE)++ response: Final = await router.aextraction(model="invoice-reader", state=_STATE, fields=_FIELDS)++ assert route.call_count == 1+ assert route.calls[0].request.headers["authorization"] == "Bearer deployment-key"+ assert json.loads(route.calls[0].request.content) == {"model": "clairic", "state": _STATE, "fields": _FIELDS}+ assert response.model == "cloudflare/clairic"+ _assert_invoice_answers(response)++[email protected]("cloudflare_env")+async def test_litellm_params_stay_local(respx_mock: respx.MockRouter) -> None:+ route: Final = respx_mock.post(_CLAIRIC_URL).respond(json=_ENVELOPE)++ await litellm.aextraction(+ model="cloudflare/clairic",+ state=_STATE,+ fields=_FIELDS,+ metadata={"team": "billing"},+ num_retries=0,+ stream=False,+ additional_drop_params=["language"],+ )++ assert json.loads(route.calls[0].request.content) == {"model": "clairic", "state": _STATE, "fields": _FIELDS}++[email protected]("name", ("language", "priority", "session_id", "mock_delay", "extra_body"))[email protected]("cloudflare_env")+async def test_a_key_clairic_does_not_take_is_refused_before_http_without_drop_params(+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch, name: str+) -> None:+ monkeypatch.setattr(litellm, "drop_params", False)+ with pytest.raises(litellm.UnsupportedParamsError, match=re.escape(f"does not support parameters: ['{name}']")):+ await litellm.aextraction(model="cloudflare/clairic", state=_STATE, fields=_FIELDS, **{name: "x"})++ assert len(respx_mock.calls) == 0++[email protected]("cloudflare_env")+async def test_additional_drop_params_drops_only_the_keys_it_names(+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(litellm, "drop_params", False)+ route: Final = respx_mock.post(_CLAIRIC_URL).respond(json=_ENVELOPE)++ await litellm.aextraction(+ model="cloudflare/clairic",+ state=_STATE,+ fields=_FIELDS,+ temperature=0.2,+ language="en",+ additional_drop_params=["temperature", "language"],+ )+ with pytest.raises(litellm.UnsupportedParamsError, match=re.escape("does not support parameters: ['seed']")):+ await litellm.aextraction(+ model="cloudflare/clairic", state=_STATE, fields=_FIELDS, seed=7, additional_drop_params=["temperature"]+ )++ assert route.call_count == 1+ assert json.loads(route.calls[0].request.content) == {"model": "clairic", "state": _STATE, "fields": _FIELDS}+++class _RecordingLogger(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.standard_logging_object: Mapping[str, object] | None = None+ self.stream: object = None++ async def async_log_success_event(+ self, kwargs: Mapping[str, object], response_obj: object, start_time: object, end_time: object+ ) -> None:+ self.stream = kwargs.get("stream")+ standard_logging_object: Final = kwargs.get("standard_logging_object")+ if isinstance(standard_logging_object, dict):+ self.standard_logging_object = standard_logging_object++[email protected]("cloudflare_env")+async def test_stream_is_refused_before_http_without_drop_params(respx_mock: respx.MockRouter) -> None:+ with pytest.raises(litellm.UnsupportedParamsError, match=re.escape("does not support parameters: ['stream']")):+ await litellm.aextraction(model="cloudflare/clairic", state=_STATE, fields=_FIELDS, stream=True)++ assert len(respx_mock.calls) == 0+++ ("name", "value"),+ (("temperature", 0.2), ("user", "end-user-1"), ("seed", 7), ("response_format", {"type": "json_object"})),+)[email protected]("cloudflare_env")+async def test_openai_generation_params_are_refused_before_http_without_drop_params(+ respx_mock: respx.MockRouter, name: str, value: object+) -> None:+ with pytest.raises(litellm.UnsupportedParamsError, match=re.escape(f"does not support parameters: ['{name}']")):+ await litellm.aextraction(model="cloudflare/clairic", state=_STATE, fields=_FIELDS, **{name: value})++ assert len(respx_mock.calls) == 0++[email protected]("cloudflare_env")+async def test_openai_generation_params_are_dropped_with_drop_params(respx_mock: respx.MockRouter) -> None:+ route: Final = respx_mock.post(_CLAIRIC_URL).respond(json=_ENVELOPE)++ await litellm.aextraction(+ model="cloudflare/clairic",+ state=_STATE,+ fields=_FIELDS,+ temperature=0.2,+ user="end-user-1",+ seed=7,+ drop_params=True,+ )++ assert json.loads(route.calls[0].request.content) == {"model": "clairic", "state": _STATE, "fields": _FIELDS}++[email protected]("cloudflare_env")+async def test_a_dropped_stream_is_sent_and_logged_as_a_billed_non_stream_call(+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch+) -> None:+ route: Final = respx_mock.post(_CLAIRIC_URL).respond(json=_ENVELOPE)+ recording_logger: Final = _RecordingLogger()+ monkeypatch.setattr(litellm, "callbacks", [recording_logger])++ response: Final = await litellm.aextraction(+ model="cloudflare/clairic", state=_STATE, fields=_FIELDS, stream=True, drop_params=True+ )+ await asyncio.sleep(0)+ GLOBAL_LOGGING_WORKER.start()+ await asyncio.wait_for(GLOBAL_LOGGING_WORKER.flush(), timeout=10.0)++ assert "stream" not in json.loads(route.calls[0].request.content)+ _assert_invoice_answers(response)+ logged: Final = recording_logger.standard_logging_object+ assert logged is not None+ assert recording_logger.stream is False+ assert response.hidden_params["response_cost"] > 0+ assert logged["response_cost"] == pytest.approx(response.hidden_params["response_cost"])diff --git a/tests/unit/litellm_core_utils/test_health_check_helpers.py b/tests/unit/litellm_core_utils/test_health_check_helpers.pyindex c23749f7a20..b584a72855a 100644--- a/tests/unit/litellm_core_utils/test_health_check_helpers.py+++ b/tests/unit/litellm_core_utils/test_health_check_helpers.py@@ -195,9 +195,7 @@ def test_update_model_params_with_health_check_tracking_information():},}- result = HealthCheckHelpers.update_model_params_with_health_check_tracking_information(- initial_model_params- )+ result = HealthCheckHelpers.update_model_params_with_health_check_tracking_information(initial_model_params)# Verify that litellm_metadata was addedassert "litellm_metadata" in result@@ -753,9 +751,7 @@ async def test_ahealth_check_keeps_the_noul_probe_for_other_decisions_providers(assert "error" not in result, resultassert upstream.calledsent: Final = json.loads(upstream.calls[0].request.content)- assert sent["questions"] == {- "reachable": {"type": "noul", "instructions": "Is the service reachable?"}- }+ assert sent["questions"] == {"reachable": {"type": "noul", "instructions": "Is the service reachable?"}}@pytest.mark.parametrize(@@ -916,6 +912,7 @@ async def test_ahealth_check_without_mode_reports_the_real_failure(assert "Missing `mode`" not in result["error"]assert "raw_request_typed_dict" in result+def test_update_litellm_params_for_health_check():"""Test if update_litellm_params_for_health_check correctly:@@ -1010,12 +1007,10 @@ def test_update_litellm_params_for_health_check():"model": f"bedrock/{prefix}anthropic.claude-3-haiku-20240307-v1:0","api_key": "fake_key",}- updated_params = update_litellm_params_for_health_check(- model_info, litellm_params+ updated_params = update_litellm_params_for_health_check(model_info, litellm_params)+ assert updated_params["model"] == f"{prefix}anthropic.claude-3-haiku-20240307-v1:0", (+ f"Failed to preserve CRIS prefix: {prefix}")- assert (- updated_params["model"] == f"{prefix}anthropic.claude-3-haiku-20240307-v1:0"- ), f"Failed to preserve CRIS prefix: {prefix}"litellm_params = {"model": "bedrock/us-east-2/us.anthropic.claude-3-haiku-20240307-v1:0",@@ -1036,30 +1031,21 @@ def test_update_litellm_params_for_health_check():"api_key": "fake_key",}updated_params = update_litellm_params_for_health_check(model_info, litellm_params)- assert (- updated_params["model"]- == "llama/arn:aws:bedrock:us-east-1:123:imported-model/abc"- )+ assert updated_params["model"] == "llama/arn:aws:bedrock:us-east-1:123:imported-model/abc"litellm_params = {"model": "bedrock/deepseek_r1/arn:aws:bedrock:us-west-2:456:imported-model/xyz","api_key": "fake_key",}updated_params = update_litellm_params_for_health_check(model_info, litellm_params)- assert (- updated_params["model"]- == "deepseek_r1/arn:aws:bedrock:us-west-2:456:imported-model/xyz"- )+ assert updated_params["model"] == "deepseek_r1/arn:aws:bedrock:us-west-2:456:imported-model/xyz"litellm_params = {"model": "bedrock/converse/us.anthropic.claude-haiku-4-5-20251001-v1:0","api_key": "fake_key",}updated_params = update_litellm_params_for_health_check(model_info, litellm_params)- assert (- updated_params["model"]- == "converse/us.anthropic.claude-haiku-4-5-20251001-v1:0"- )+ assert updated_params["model"] == "converse/us.anthropic.claude-haiku-4-5-20251001-v1:0"litellm_params = {"model": "bedrock/invoke/us-west-2/anthropic.claude-instant-v1",@@ -1073,29 +1059,22 @@ def test_update_litellm_params_for_health_check():"api_key": "fake_key",}updated_params = update_litellm_params_for_health_check(model_info, litellm_params)- assert (- updated_params["model"]- == "arn:aws:bedrock:eu-central-1:000:application-inference-profile/abc"- )+ assert updated_params["model"] == "arn:aws:bedrock:eu-central-1:000:application-inference-profile/abc"litellm_params = {"model": "bedrock/us-west-2/llama/arn:aws:bedrock:us-east-1:123:imported-model/abc","api_key": "fake_key",}updated_params = update_litellm_params_for_health_check(model_info, litellm_params)- assert (- updated_params["model"]- == "llama/arn:aws:bedrock:us-east-1:123:imported-model/abc"- )+ assert updated_params["model"] == "llama/arn:aws:bedrock:us-east-1:123:imported-model/abc"litellm_params = {"model": "bedrock/converse/us-west-2/eu.anthropic.claude-3-sonnet-20240229-v1:0","api_key": "fake_key",}updated_params = update_litellm_params_for_health_check(model_info, litellm_params)- assert (- updated_params["model"] == "converse/eu.anthropic.claude-3-sonnet-20240229-v1:0"- )+ assert updated_params["model"] == "converse/eu.anthropic.claude-3-sonnet-20240229-v1:0"+@pytest.mark.asyncioasync def test_perform_health_check_filters_by_model_id():@@ -1142,6 +1121,7 @@ async def test_perform_health_check_filters_by_model_id():assert len(healthy_endpoints) == 1assert healthy_endpoints[0]["api_key"] == "fake-key-2"+@pytest.mark.asyncioasync def test_perform_health_check_skip_disabled_background_models():from litellm.proxy.health_check import perform_health_check@@ -1180,6 +1160,7 @@ async def test_perform_health_check_skip_disabled_background_models():assert len(captured[0]) == 1assert captured[0][0]["model_name"] == "a"+@pytest.mark.asyncioasync def test_perform_health_check_with_health_check_model():"""@@ -1206,9 +1187,7 @@ async def test_perform_health_check_with_health_check_model():return {"status": "healthy"}with patch("litellm.ahealth_check", side_effect=mock_health_check):- healthy_endpoints, unhealthy_endpoints, _ = await _perform_health_check(- model_list- )+ healthy_endpoints, unhealthy_endpoints, _ = await _perform_health_check(model_list)print("health check calls: ", health_check_calls)assert health_check_calls[0] == "openai/gpt-5-mini"@@ -1217,6 +1196,7 @@ async def test_perform_health_check_with_health_check_model():assert len(healthy_endpoints) == 1assert len(unhealthy_endpoints) == 0+@pytest.mark.asyncioasync def test_image_generation_health_check_prompt(monkeypatch):"""Health checks should respect default and environment-configured prompts."""@@ -1267,9 +1247,7 @@ async def test_image_generation_health_check_prompt(monkeypatch):health_check_calls = await run_health_check(reloaded_health_check)assert len(health_check_calls) == 1- assert (- health_check_calls[0]["prompt"] == reloaded_constants.DEFAULT_HEALTH_CHECK_PROMPT- )+ assert health_check_calls[0]["prompt"] == reloaded_constants.DEFAULT_HEALTH_CHECK_PROMPT# Environment override should change the prompt without code changesoverride_prompt = "environment override prompt"@@ -1293,9 +1271,7 @@ async def test_health_check_with_custom_llm_provider("object": "chat.completion","created": 0,"model": "deepseek-r1-distill-qwen-1.5B-q4",- "choices": [- {"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}- ],+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},})@@ -1503,3 +1479,37 @@ async def test_audio_transcription_health_check_returns_transcribed_text(assert "error" not in responseassert upstream.calledassert b'name="file"' in upstream.calls.last.request.content++[email protected]("model", ("cloudflare/clairic", "cloudflare/@cf/cloudflare/clairic"))+async def test_ahealth_check_probes_extraction_models_through_the_extraction_api(+ model: str,+ monkeypatch: pytest.MonkeyPatch,+ respx_mock: respx.MockRouter,+) -> None:+ monkeypatch.setenv("CLOUDFLARE_ACCOUNT_ID", "acct-1")+ monkeypatch.delenv("CLOUDFLARE_API_BASE", raising=False)+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)+ litellm.in_memory_llm_clients_cache.flush_cache()+ upstream: Final = respx_mock.post(+ "https://api.cloudflare.com/client/v4/accounts/acct-1/ai/run/@cf/cloudflare/clairic"+ ).respond(+ json={+ "result": {+ "model": "clairic",+ "answers": {"reachable": {"type": "text", "value": "health"}},+ "truncated": False,+ "usage": {"input_tokens": 20, "output_tokens": 0},+ },+ "success": True,+ "errors": [],+ "messages": [],+ }+ )++ result: Final = await ahealth_check({"model": model, "api_key": "sk-test"}, mode=None)++ assert "error" not in result, result+ sent: Final = json.loads(upstream.calls[0].request.content)+ assert sent["state"] == "health check"+ assert sent["fields"]["reachable"]["type"] == "text"diff --git a/tests/unit/llms/azure/test_azure_common_utils.py b/tests/unit/llms/azure/test_azure_common_utils.pyindex 41ad27d6f40..b3bd1b8743a 100644--- a/tests/unit/llms/azure/test_azure_common_utils.py+++ b/tests/unit/llms/azure/test_azure_common_utils.py@@ -477,6 +477,7 @@ def test_default_max_retries_env_var_reaches_azure_sdk_client():"asearch","adecisions","asystemone",+ "aextraction","avector_store_create","avector_store_search","acreate_skill",diff --git a/tests/unit/llms/cloudflare/test_cloudflare_extraction_guardrail_handler.py b/tests/unit/llms/cloudflare/test_cloudflare_extraction_guardrail_handler.pynew file mode 100644index 00000000000..1db105f4495--- /dev/null+++ b/tests/unit/llms/cloudflare/test_cloudflare_extraction_guardrail_handler.py@@ -0,0 +1,335 @@+from typing import Final, Literal++import pytest++from litellm.integrations.custom_guardrail import CustomGuardrail+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+from litellm.llms import get_guardrail_translation_mapping+from litellm.llms.cloudflare.extraction.guardrail_translation.handler import ExtractionHandler+from litellm.types.extraction import ExtractionResponse+from litellm.types.utils import CallTypes, GenericGuardrailAPIInputs+++class _TaggingGuardrail(CustomGuardrail):+ def __init__(self) -> None:+ super().__init__(guardrail_name="tagging")+ self.seen: tuple[str, tuple[str, ...]] | None = None+ self.seen_images: tuple[str, ...] = ()++ async def apply_guardrail(+ self,+ inputs: GenericGuardrailAPIInputs,+ request_data: dict[str, object],+ input_type: Literal["request", "response"],+ logging_obj: LiteLLMLoggingObj | None = None,+ ) -> GenericGuardrailAPIInputs:+ texts: Final = tuple(inputs.get("texts", []))+ self.seen = (input_type, texts)+ self.seen_images = tuple(inputs.get("images", []))+ return GenericGuardrailAPIInputs(texts=[f"{text} [GUARDRAILED]" for text in texts])+++class _MaskingGuardrail(CustomGuardrail):+ def __init__(self, secret: str, mask: str) -> None:+ super().__init__(guardrail_name="masking")+ self.secret = secret+ self.mask = mask++ async def apply_guardrail(+ self,+ inputs: GenericGuardrailAPIInputs,+ request_data: dict[str, object],+ input_type: Literal["request", "response"],+ logging_obj: LiteLLMLoggingObj | None = None,+ ) -> GenericGuardrailAPIInputs:+ return GenericGuardrailAPIInputs(+ texts=[text.replace(self.secret, self.mask) for text in inputs.get("texts", [])]+ )++[email protected]("call_type", (CallTypes.extraction, CallTypes.aextraction))+def test_extraction_call_types_resolve_to_the_extraction_handler(call_type: CallTypes) -> None:+ assert get_guardrail_translation_mapping(call_type) is ExtractionHandler+++async def test_request_state_and_field_instructions_are_guardrailed_on_a_copy() -> None:+ guardrail: Final = _TaggingGuardrail()+ data: Final = {+ "model": "invoice-reader",+ "state": "Invoice from Acme Tools, contact [email protected]",+ "fields": {+ "vendor": {"type": "text", "instructions": "Who sent the invoice?"},+ "total": {"type": "number", "unit": "USD"},+ },+ "images": ["data:image/png;base64,AA=="],+ }++ result: Final = await ExtractionHandler().process_input_messages(data, guardrail)++ assert guardrail.seen == (+ "request",+ ("Invoice from Acme Tools, contact [email protected]", "Who sent the invoice?", "USD"),+ )+ assert {key: value for key, value in result.items() if key != "metadata"} == {+ **{key: value for key, value in data.items() if key != "metadata"},+ "state": "Invoice from Acme Tools, contact [email protected] [GUARDRAILED]",+ "fields": {+ "vendor": {"type": "text", "instructions": "Who sent the invoice? [GUARDRAILED]"},+ "total": {"type": "number", "unit": "USD [GUARDRAILED]"},+ },+ }+ assert data["state"] == "Invoice from Acme Tools, contact [email protected]"+++async def test_a_request_with_no_text_or_images_skips_the_guardrail() -> None:+ guardrail: Final = _TaggingGuardrail()+ data: Final = {"model": "invoice-reader", "fields": {"total": {"type": "number"}}}++ assert await ExtractionHandler().process_input_messages(data, guardrail) is data+ assert guardrail.seen is None+++async def test_request_images_reach_the_guardrail_as_data_urls() -> None:+ guardrail: Final = _TaggingGuardrail()+ data: Final = {+ "model": "invoice-reader",+ "fields": {"total": {"type": "number"}},+ "images": [{"content_type": "image/png", "base64": "iVBORw0KGgo="}, "data:image/jpeg;base64,/9j/"],+ }++ result: Final = await ExtractionHandler().process_input_messages(data, guardrail)++ assert guardrail.seen == ("request", ())+ assert guardrail.seen_images == ("data:image/png;base64,iVBORw0KGgo=", "data:image/jpeg;base64,/9j/")+ assert result["images"] == data["images"]+++async def test_response_answers_and_state_text_are_guardrailed_on_a_copy_without_stale_spans() -> None:+ guardrail: Final = _TaggingGuardrail()+ response: Final = ExtractionResponse.model_validate(+ {+ "model": "invoice-reader",+ "answers": {+ "vendor": {"type": "text", "value": "Acme Tools", "guess": "Acme Tools", "span": [19, 29]},+ "items": {"type": "list", "value": ["12", "hammers"], "spans": [[51, 53], [54, 61]]},+ "total": {"type": "number", "value": 174, "guess": 174},+ "contact": {"type": "text", "value": None, "p_null": 0.98},+ },+ "truncated": False,+ "state_text": "Invoice from Acme Tools",+ "usage": {"input_tokens": 52, "output_tokens": 0},+ }+ )+ response.set_hidden_params({"response_cost": 0.0000052})++ result: Final = await ExtractionHandler().process_output_response(response, guardrail)++ assert guardrail.seen == (+ "response",+ ("Acme Tools", "12", "hammers", "174", "Invoice from Acme Tools"),+ )+ assert isinstance(result, ExtractionResponse)+ assert result.model_dump(mode="json") == {+ **response.model_dump(mode="json"),+ "answers": {+ "vendor": {"type": "text", "value": "Acme Tools [GUARDRAILED]", "guess": "Acme Tools [GUARDRAILED]"},+ "items": {"type": "list", "value": ["12 [GUARDRAILED]", "hammers [GUARDRAILED]"]},+ "total": {"type": "number", "value": None},+ "contact": {"type": "text", "value": None, "p_null": 0.98},+ },+ "state_text": "Invoice from Acme Tools [GUARDRAILED]",+ }+ assert response.answers["vendor"].value == "Acme Tools"+ assert result.hidden_params["response_cost"] == 0.0000052+++async def test_spans_into_the_callers_own_state_survive_a_response_guardrail() -> None:+ response: Final = ExtractionResponse.model_validate(+ {+ "model": "invoice-reader",+ "answers": {"vendor": {"type": "text", "value": "Acme Tools", "span": [19, 29]}},+ "truncated": False,+ "usage": {"input_tokens": 52, "output_tokens": 0},+ }+ )++ result: Final = await ExtractionHandler().process_output_response(response, _TaggingGuardrail())++ assert isinstance(result, ExtractionResponse)+ assert result.answers["vendor"].model_dump(mode="json") == {+ "type": "text",+ "value": "Acme Tools [GUARDRAILED]",+ "span": [19, 29],+ }+++async def test_a_response_guardrail_change_to_a_typed_answer_nulls_it_instead_of_breaking_its_type() -> None:+ guardrail: Final = _MaskingGuardrail("2026-03-03", "[DATE]")+ request_data: Final = {+ "fields": {+ "invoice_date": {"type": "date"},+ "due_dates": {"type": "list", "items": "date"},+ "notes": {"type": "list", "items": "text"},+ }+ }+ response: Final = ExtractionResponse.model_validate(+ {+ "model": "invoice-reader",+ "answers": {+ "invoice_date": {"type": "date", "value": "2026-03-03", "guess": "2026-03-03", "span": [30, 40]},+ "due_dates": {"type": "list", "value": ["2026-03-03", "2026-04-02"], "spans": [[30, 40], [50, 60]]},+ "notes": {"type": "list", "value": ["paid 2026-03-03"], "spans": [[70, 85]]},+ "received": {"type": "date", "value": "2026-02-27", "span": [90, 100]},+ },+ "truncated": False,+ "usage": {"input_tokens": 52, "output_tokens": 0},+ }+ )++ result: Final = await ExtractionHandler().process_output_response(response, guardrail, request_data=request_data)++ assert isinstance(result, ExtractionResponse)+ assert {name: answer.model_dump(mode="json") for name, answer in result.answers.items()} == {+ "invoice_date": {"type": "date", "value": None},+ "due_dates": {"type": "list", "value": None},+ "notes": {"type": "list", "value": ["paid [DATE]"], "spans": [[70, 85]]},+ "received": {"type": "date", "value": "2026-02-27", "span": [90, 100]},+ }+++async def test_a_response_guardrail_that_masks_a_number_nulls_every_answer_carrying_it() -> None:+ request_data: Final = {+ "fields": {+ "phone_text": {"type": "text"},+ "phone_number": {"type": "number"},+ "phone_list": {"type": "list", "items": "number"},+ "phone_mean": {"type": "estimate"},+ "phone_median": {"type": "estimate"},+ "phone_p10": {"type": "estimate"},+ "phone_p90": {"type": "estimate"},+ "phone_quantile": {"type": "estimate"},+ "phone_forecast": {"type": "forecast"},+ "total": {"type": "number"},+ }+ }+ response: Final = ExtractionResponse.model_validate(+ {+ "model": "invoice-reader",+ "answers": {+ "phone_text": {"type": "text", "value": "4155550123", "span": [10, 20]},+ "phone_number": {"type": "number", "value": 4155550123, "guess": 4155550123, "span": [10, 20]},+ "phone_list": {"type": "list", "value": [4155550123], "spans": [[10, 20]]},+ "phone_mean": {+ "type": "estimate",+ "value": None,+ "mean": 4155550123.4,+ "p10": 4155550000,+ "p_null": 0.6,+ },+ "phone_median": {+ "type": "estimate",+ "value": None,+ "median": 4155550123,+ "p90": 4155550200,+ "p_null": 0.6,+ },+ "phone_p10": {"type": "estimate", "value": None, "p10": 4155550123, "p_null": 0.6},+ "phone_p90": {"type": "estimate", "value": None, "p90": 4155550123.2, "p_null": 0.6},+ "phone_quantile": {+ "type": "estimate",+ "value": None,+ "quantiles": [4155550000, 4155550123, 4155550200],+ "p_null": 0.6,+ },+ "phone_forecast": {+ "type": "forecast",+ "value": None,+ "steps": [{"value": 12, "p10": 10}, {"value": 13, "p90": 4155550123}],+ "p_null": 0.6,+ },+ "total": {"type": "number", "value": 174, "guess": 174},+ },+ "truncated": False,+ "usage": {"input_tokens": 52, "output_tokens": 0},+ }+ )++ result: Final = await ExtractionHandler().process_output_response(+ response, _MaskingGuardrail("4155550123", "[PHONE]"), request_data=request_data+ )++ assert isinstance(result, ExtractionResponse)+ assert {name: answer.model_dump(mode="json") for name, answer in result.answers.items()} == {+ "phone_text": {"type": "text", "value": "[PHONE]", "span": [10, 20]},+ "phone_number": {"type": "number", "value": None},+ "phone_list": {"type": "list", "value": None},+ "phone_mean": {"type": "estimate", "value": None, "p_null": 0.6},+ "phone_median": {"type": "estimate", "value": None, "p_null": 0.6},+ "phone_p10": {"type": "estimate", "value": None, "p_null": 0.6},+ "phone_p90": {"type": "estimate", "value": None, "p_null": 0.6},+ "phone_quantile": {"type": "estimate", "value": None, "p_null": 0.6},+ "phone_forecast": {"type": "forecast", "value": None, "p_null": 0.6},+ "total": {"type": "number", "value": 174, "guess": 174},+ }+++async def test_a_response_guardrail_does_not_scan_the_fraction_digits_of_an_estimate() -> None:+ days_late: Final = {+ "type": "estimate",+ "value": None,+ "mean": 3.4525830151341586,+ "median": 2.4525830151341586,+ "p_null": 0.2,+ }+ response: Final = ExtractionResponse.model_validate(+ {+ "model": "invoice-reader",+ "answers": {"days_late": days_late},+ "truncated": False,+ "usage": {"input_tokens": 52, "output_tokens": 0},+ }+ )++ result: Final = await ExtractionHandler().process_output_response(+ response,+ _MaskingGuardrail("4525830151341586", "[CARD]"),+ request_data={"fields": {"days_late": {"type": "estimate"}}},+ )++ assert isinstance(result, ExtractionResponse)+ assert result.answers["days_late"].model_dump(mode="json") == days_late+++async def test_a_response_guardrail_sees_the_decimal_text_of_a_fractional_number_answer() -> None:+ response: Final = ExtractionResponse.model_validate(+ {+ "model": "invoice-reader",+ "answers": {+ "unit_price": {"type": "number", "value": 14.5, "guess": 14.5, "span": [30, 36]},+ "prices": {"type": "list", "value": [14.5, 2.25], "spans": [[30, 36], [40, 45]]},+ },+ "truncated": False,+ "usage": {"input_tokens": 52, "output_tokens": 0},+ }+ )++ result: Final = await ExtractionHandler().process_output_response(+ response,+ _MaskingGuardrail("14.5", "[PRICE]"),+ request_data={"fields": {"unit_price": {"type": "number"}, "prices": {"type": "list", "items": "number"}}},+ )++ assert isinstance(result, ExtractionResponse)+ assert {name: answer.model_dump(mode="json") for name, answer in result.answers.items()} == {+ "unit_price": {"type": "number", "value": None},+ "prices": {"type": "list", "value": None},+ }diff --git a/tests/unit/llms/cloudflare/test_cloudflare_extraction_transformation.py b/tests/unit/llms/cloudflare/test_cloudflare_extraction_transformation.pynew file mode 100644index 00000000000..214fec07284--- /dev/null+++ b/tests/unit/llms/cloudflare/test_cloudflare_extraction_transformation.py@@ -0,0 +1,221 @@+import json+from typing import Final++import httpx+import pytest+from pydantic import ValidationError++import litellm+from litellm.llms.base_llm.chat.transformation import BaseLLMException+from litellm.llms.base_llm.extraction.transformation import BaseExtractionConfig+from litellm.types.extraction import ExtractionRequestBody+from litellm.types.utils import LlmProviders+from litellm.utils import ProviderConfigManager++INVOICE_STATE: Final = "Invoice #4471 from Acme Tools, dated March 3 2026. Total $174.00. Payment due in 30 days."+INVOICE_FIELDS: Final = {+ "vendor": {"type": "text", "instructions": "Who sent the invoice"},+ "invoice_date": {"type": "date"},+ "total": {"type": "number", "decimals": 2, "unit": "USD"},+ "items": {"type": "list", "items": "text"},+ "days_to_pay": {"type": "estimate", "min": 0, "max": 90, "step": 1},+}+CLAIRIC_RESULT: Final = {+ "model": "clairic",+ "answers": {+ "vendor": {+ "type": "text",+ "p_null": 0.01,+ "span": [19, 29],+ "guess": "Acme Tools",+ "confidence": 0.99,+ "value": "Acme Tools",+ },+ "total": {"type": "number", "p_null": 0.0, "guess": 174, "confidence": 0.99, "value": 174},+ "items": {"type": "list", "value": ["hammers"], "spans": [[54, 61]], "confidence": 0.4},+ "days_to_pay": {+ "type": "estimate",+ "value": 31,+ "mean": 30.7,+ "median": 30,+ "p10": 29,+ "p90": 34,+ "p_below": 0.0,+ "p_above": 0.0,+ },+ },+ "truncated": False,+ "usage": {+ "state_tokens": 52,+ "image_tokens": 0,+ "schema_tokens": 312,+ "input_tokens": 416,+ "output_tokens": 0,+ "passes": 2,+ },+}+++def _cloudflare_config() -> BaseExtractionConfig:+ config: Final = ProviderConfigManager.get_provider_extraction_config("clairic", LlmProviders.CLOUDFLARE)+ assert config is not None+ return config+++def _response(payload: object) -> httpx.Response:+ return httpx.Response(status_code=200, content=json.dumps(payload).encode())+++def test_only_cloudflare_serves_extraction() -> None:+ assert ProviderConfigManager.get_provider_extraction_config("gpt-5", LlmProviders.OPENAI) is None+ assert isinstance(_cloudflare_config(), litellm.CloudflareExtractionConfig)++[email protected]("model", ("clairic", "@cf/cloudflare/clairic"))+def test_clairic_resolves_to_its_workers_ai_run_url(monkeypatch: pytest.MonkeyPatch, model: str) -> None:+ monkeypatch.setenv("CLOUDFLARE_ACCOUNT_ID", "acct")+ config: Final = _cloudflare_config()+ canonical: Final = config.canonical_model(model)+ api_base: Final = config.resolve_api_base(None)++ assert canonical == "@cf/cloudflare/clairic"+ assert api_base is not None+ assert (+ config.get_complete_url(api_base, canonical)+ == "https://api.cloudflare.com/client/v4/accounts/acct/ai/run/@cf/cloudflare/clairic"+ )+++ "api_base",+ (+ "https://gateway.example/client/v4/accounts/acct/ai/v1",+ "https://gateway.example/client/v4/accounts/acct/ai/run/",+ "https://gateway.example/client/v4/accounts/acct",+ ),+)+def test_custom_api_base_keeps_the_run_path(api_base: str) -> None:+ assert (+ _cloudflare_config().get_complete_url(api_base, "@cf/cloudflare/clairic")+ == "https://gateway.example/client/v4/accounts/acct/ai/run/@cf/cloudflare/clairic"+ )+++def test_missing_account_id_leaves_no_default_api_base(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("CLOUDFLARE_ACCOUNT_ID", raising=False)+ monkeypatch.delenv("CLOUDFLARE_API_BASE", raising=False)++ assert _cloudflare_config().resolve_api_base(None) is None+++def test_request_forwards_the_callers_fields_unchanged() -> None:+ request: Final = ExtractionRequestBody.model_validate(+ {+ "state": INVOICE_STATE,+ "fields": INVOICE_FIELDS,+ "reference_date": "2026-03-01",+ "options": {"return_state_text": True},+ "images": [{"content_type": "image/png", "base64": "iVBORw0KGgo="}],+ }+ )++ assert _cloudflare_config().transform_extraction_request("@cf/cloudflare/clairic", request) == {+ "model": "clairic",+ "state": INVOICE_STATE,+ "fields": INVOICE_FIELDS,+ "reference_date": "2026-03-01",+ "options": {"return_state_text": True},+ "images": [{"content_type": "image/png", "base64": "iVBORw0KGgo="}],+ }++[email protected]("wrapped", (True, False))+def test_response_parses_typed_answers_and_usage(wrapped: bool) -> None:+ payload: Final = (+ {"result": CLAIRIC_RESULT, "success": True, "errors": [], "messages": []} if wrapped else CLAIRIC_RESULT+ )++ response: Final = _cloudflare_config().transform_extraction_response(+ "@cf/cloudflare/clairic", "cloudflare", _response(payload)+ )++ assert response.model_dump(mode="json") == CLAIRIC_RESULT+ assert response.answers["vendor"].span == (19, 29)+ assert response.usage.input_tokens == 416+++def test_unexpected_response_raises_a_provider_error() -> None:+ with pytest.raises(BaseLLMException) as error:+ _cloudflare_config().transform_extraction_response(+ "@cf/cloudflare/clairic", "cloudflare", _response({"result": {"answers": {}}})+ )++ assert error.value.status_code == 500+++def test_unknown_field_type_is_rejected() -> None:+ with pytest.raises(ValidationError, match=r"fields\.vendor\.type"):+ ExtractionRequestBody.model_validate({"state": INVOICE_STATE, "fields": {"vendor": {"type": "color"}}})+++def test_a_list_field_without_an_item_type_is_rejected_locally() -> None:+ # Cloudflare answered a list field without items with 422 code 3030 on @cf/cloudflare/clairic, probed 2026-10-20+ with pytest.raises(ValidationError, match=r"fields\.line_items\n.*list fields need items"):+ ExtractionRequestBody.model_validate({"state": INVOICE_STATE, "fields": {"line_items": {"type": "list"}}})+++ "spec",+ (+ {"type": "number", "decimals": "2"},+ {"type": "number", "integer": "yes"},+ {"type": "number", "integer": 1},+ {"type": "estimate", "min": True, "max": 90},+ ),+ ids=("string_decimals", "string_integer", "number_integer", "bool_min"),+)+def test_a_field_value_of_the_wrong_json_type_is_rejected_instead_of_coerced(spec: dict[str, object]) -> None:+ # Cloudflare answered each of these specs with a 400 or 422 on @cf/cloudflare/clairic, probed 2026-10-20+ with pytest.raises(ValidationError, match=r"fields\.total\."):+ ExtractionRequestBody.model_validate({"state": INVOICE_STATE, "fields": {"total": spec}})+++def test_numbers_in_a_field_spec_go_to_cloudflare_exactly_as_sent() -> None:+ # Cloudflare answered "decimals": 2.0 and "step": 1.0 with a 200 on @cf/cloudflare/clairic, probed 2026-10-20+ fields: Final = {+ "total": {"type": "number", "decimals": 2.0, "null_threshold": 1},+ "days_to_pay": {"type": "estimate", "min": 0, "max": 90, "step": 1.0},+ }+ request: Final = ExtractionRequestBody.model_validate({"state": INVOICE_STATE, "fields": fields})++ body: Final = _cloudflare_config().transform_extraction_request("@cf/cloudflare/clairic", request)++ assert json.dumps(body["fields"]) == json.dumps(fields)++[email protected]("name", ("due date", "1st_item", "x" * 80), ids=("space", "digit_first", "80_chars"))+def test_a_field_name_clairic_refuses_is_rejected_locally(name: str) -> None:+ # Cloudflare answered each of these names with 422 code 3030 on @cf/cloudflare/clairic, probed 2026-10-19+ with pytest.raises(ValidationError, match=r"fields\."):+ ExtractionRequestBody.model_validate({"state": INVOICE_STATE, "fields": {name: {"type": "text"}}})++[email protected]("name", ("_vendor", "line.items", "days-to-pay", "x" * 64))+def test_field_names_with_dots_dashes_and_underscores_up_to_64_chars_are_accepted(name: str) -> None:+ # Cloudflare answered each of these names with a 200 on @cf/cloudflare/clairic, probed 2026-10-19+ request: Final = ExtractionRequestBody.model_validate({"state": INVOICE_STATE, "fields": {name: {"type": "text"}}})++ assert tuple(request.fields) == (name,)+++def test_decisions_config_still_resolves_clef_after_the_shared_helpers_moved(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("CLOUDFLARE_ACCOUNT_ID", "acct")+ config: Final = litellm.CloudflareDecisionsConfig()+ api_base: Final = config.get_default_api_base()++ assert api_base is not None+ assert (+ config.get_complete_url(api_base, config.canonical_model("clef"))+ == "https://api.cloudflare.com/client/v4/accounts/acct/ai/run/@cf/cloudflare/clef"+ )+ assert config.unwrap_response({"result": {"answers": {}}}) == {"answers": {}}diff --git a/tests/unit/proxy/decisions_endpoints/test_endpoints.py b/tests/unit/proxy/decisions_endpoints/test_endpoints.pyindex fcf56eaea9a..021eb289ad7 100644--- a/tests/unit/proxy/decisions_endpoints/test_endpoints.py+++ b/tests/unit/proxy/decisions_endpoints/test_endpoints.py@@ -8,7 +8,7 @@ import sysfrom collections.abc import AsyncGenerator, Callable, Iterator, Mappingfrom contextlib import asynccontextmanagerfrom pathlib import Path-from typing import Final+from typing import Final, Literalimport pytestimport respx@@ -19,6 +19,8 @@ from pydantic import TypeAdapterfrom starlette.routing import Matchimport litellm+from litellm.integrations.custom_guardrail import CustomGuardrail+from litellm.integrations.custom_logger import CustomLoggerfrom litellm.litellm_core_utils.decisions_pricing import apply_decisions_pricingfrom litellm.proxy._lazy_features import LAZY_FEATURES, LazyFeature, attach_lazy_featuresfrom litellm.proxy._types import UserAPIKeyAuth@@ -32,6 +34,9 @@ from litellm.proxy.proxy_server import (initialize,)from litellm.types.decisions import DecisionsRequestBody, OpenAIDecisionRequestBody+from litellm.types.extraction import ExtractionRequestBody+from litellm.types.guardrails import GuardrailEventHooks+from litellm.types.utils import GenericGuardrailAPIInputsfrom tests._master_key import MASTER_KEYif sys.version_info >= (3, 14):@@ -1296,6 +1301,328 @@ def test_the_two_decisions_routes_document_different_request_formats(decisions_oassert "input" in properties("/v1/decisions") and "input" not in properties("/v1/systemone")+_CLAIRIC_UPSTREAM: Final = "https://api.cloudflare.com/client/v4/accounts/acct/ai/run/@cf/cloudflare/clairic"+_CLAIRIC_INPUT_TOKENS: Final = 416+_CLAIRIC_RESULT: Final[Mapping[str, object]] = {+ "model": "clairic",+ "answers": {+ "vendor": {"type": "text", "p_null": 0.0177, "span": [19, 29], "confidence": 0.9998, "value": "Acme Tools"},+ "days_to_pay": {"type": "estimate", "value": 31, "mean": 30.76, "median": 30, "p10": 29, "p90": 34},+ },+ "truncated": False,+ "usage": {"input_tokens": _CLAIRIC_INPUT_TOKENS, "output_tokens": 0, "schema_tokens": 312, "passes": 2},+}+_EXTRACTION_REQUEST: Final[Mapping[str, object]] = {+ "model": "invoice-reader",+ "state": "Invoice #4471 from Acme Tools. Payment due in 30 days.",+ "fields": {+ "vendor": {"type": "text", "instructions": "Who sent the invoice?"},+ "days_to_pay": {"type": "estimate", "min": 0, "max": 90},+ },+ "images": ["data:image/png;base64,AA=="],+}+++def _route_invoice_reader_to_clairic(+ monkeypatch: pytest.MonkeyPatch, drop_params: bool = False, additional_drop_params: tuple[str, ...] = ()+) -> None:+ monkeypatch.setattr(+ litellm.proxy.proxy_server,+ "llm_router",+ litellm.Router(+ model_list=[+ {+ "model_name": "invoice-reader",+ "litellm_params": {+ "model": "cloudflare/clairic",+ "api_key": "cloudflare-key",+ "api_base": "https://api.cloudflare.com/client/v4/accounts/acct/ai/run",+ "drop_params": drop_params,+ **({"additional_drop_params": list(additional_drop_params)} if additional_drop_params else {}),+ },+ }+ ]+ ),+ )++[email protected]("endpoint", ("/v1/extraction", "/extraction"))+def test_proxy_extraction_forwards_the_body_to_clairic_and_returns_its_answers_and_cost(+ client: TestClient,+ monkeypatch: pytest.MonkeyPatch,+ respx_mock: respx.MockRouter,+ endpoint: str,+) -> None:+ _route_invoice_reader_to_clairic(monkeypatch)+ upstream: Final = respx_mock.post(_CLAIRIC_UPSTREAM).respond(+ json={"result": _CLAIRIC_RESULT, "success": True, "errors": [], "messages": []}+ )++ response: Final = client.post(endpoint, json=_EXTRACTION_REQUEST)++ assert response.status_code == 200, response.text+ assert response.json() == {**_CLAIRIC_RESULT, "model": "invoice-reader"}+ expected_cost: Final = _CLAIRIC_INPUT_TOKENS * float(+ litellm.model_cost["cloudflare/clairic"]["input_cost_per_token"]+ )+ assert expected_cost > 0+ assert float(response.headers["x-litellm-response-cost"]) == pytest.approx(expected_cost)+ assert json.loads(upstream.calls[0].request.content) == {**_EXTRACTION_REQUEST, "model": "clairic"}+ assert upstream.calls[0].request.headers["authorization"] == "Bearer cloudflare-key"+++ "request_body",+ (+ {"model": "invoice-reader", "state": "Invoice #4471"},+ {"model": "invoice-reader", "state": "Invoice #4471", "fields": {"total": {"type": "money"}}},+ {**_EXTRACTION_REQUEST, "images": ["https://example.com/invoice.png"]},+ ),+ ids=("missing_fields", "unknown_field_type", "remote_image"),+)+def test_proxy_extraction_refuses_a_malformed_body_before_calling_clairic(+ client: TestClient,+ monkeypatch: pytest.MonkeyPatch,+ respx_mock: respx.MockRouter,+ request_body: Mapping[str, object],+) -> None:+ _route_invoice_reader_to_clairic(monkeypatch)+ upstream: Final = respx_mock.post(_CLAIRIC_UPSTREAM).respond(json=_CLAIRIC_RESULT)++ response: Final = client.post("/v1/extraction", json=request_body)++ assert response.status_code == 400, response.text+ assert "Invalid Extraction request" in response.text+ assert not upstream.called+++ ("key", "value"),+ (+ ("language", "en"),+ ("priority", 1),+ ("extra_body", {"language": "en"}),+ ("temperature", 0.5),+ ("user", "end-user-1"),+ ),+)+def test_proxy_extraction_refuses_a_key_clairic_does_not_take_before_calling_clairic(+ client: TestClient, monkeypatch: pytest.MonkeyPatch, respx_mock: respx.MockRouter, key: str, value: object+) -> None:+ monkeypatch.setattr(litellm, "drop_params", False)+ _route_invoice_reader_to_clairic(monkeypatch)+ upstream: Final = respx_mock.post(_CLAIRIC_UPSTREAM).respond(json={"result": _CLAIRIC_RESULT, "success": True})++ response: Final = client.post("/v1/extraction", json={**_EXTRACTION_REQUEST, key: value})++ assert response.status_code == 400, response.text+ assert f"does not support parameters: ['{key}']" in response.text+ assert not upstream.called+++ ("drop_params", "additional_drop_params"),+ ((True, ()), (False, ("language", "temperature", "user"))),+ ids=("drop_params", "additional_drop_params"),+)+def test_proxy_extraction_sends_only_the_clairic_request_when_the_deployment_drops_other_keys(+ client: TestClient,+ monkeypatch: pytest.MonkeyPatch,+ respx_mock: respx.MockRouter,+ drop_params: bool,+ additional_drop_params: tuple[str, ...],+) -> None:+ monkeypatch.setattr(litellm, "drop_params", False)+ _route_invoice_reader_to_clairic(monkeypatch, drop_params, additional_drop_params)+ upstream: Final = respx_mock.post(_CLAIRIC_UPSTREAM).respond(json={"result": _CLAIRIC_RESULT, "success": True})++ response: Final = client.post(+ "/v1/extraction", json={**_EXTRACTION_REQUEST, "language": "en", "temperature": 0.2, "user": "end-user-1"}+ )++ assert response.status_code == 200, response.text+ assert json.loads(upstream.calls[0].request.content) == {**_EXTRACTION_REQUEST, "model": "clairic"}+++def test_proxy_extraction_leaves_out_the_cli_generation_defaults(+ client: TestClient, monkeypatch: pytest.MonkeyPatch, respx_mock: respx.MockRouter+) -> None:+ monkeypatch.setattr(litellm, "drop_params", False)+ monkeypatch.setattr(litellm.proxy.proxy_server, "user_max_tokens", 256)+ monkeypatch.setattr(litellm.proxy.proxy_server, "user_temperature", 0.2)+ _route_invoice_reader_to_clairic(monkeypatch)+ upstream: Final = respx_mock.post(_CLAIRIC_UPSTREAM).respond(json={"result": _CLAIRIC_RESULT, "success": True})++ response: Final = client.post("/v1/extraction", json=_EXTRACTION_REQUEST)++ assert response.status_code == 200, response.text+ assert json.loads(upstream.calls[0].request.content) == {**_EXTRACTION_REQUEST, "model": "clairic"}+++class _PreCallRecorder(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.calls = 0++ async def async_pre_call_hook(+ self, user_api_key_dict: UserAPIKeyAuth, cache: object, data: dict, call_type: str+ ) -> dict:+ self.calls += 1+ return data+++def test_proxy_extraction_refuses_a_remote_image_before_any_pre_call_hook_runs(+ client: TestClient, monkeypatch: pytest.MonkeyPatch, respx_mock: respx.MockRouter+) -> None:+ recorder: Final = _PreCallRecorder()+ monkeypatch.setattr(litellm, "callbacks", [recorder])+ _route_invoice_reader_to_clairic(monkeypatch)+ upstream: Final = respx_mock.post(_CLAIRIC_UPSTREAM).respond(json={"result": _CLAIRIC_RESULT, "success": True})++ response: Final = client.post(+ "/v1/extraction", json={**_EXTRACTION_REQUEST, "images": ["https://example.com/invoice.png"]}+ )++ assert response.status_code == 400, response.text+ assert recorder.calls == 0+ assert not upstream.called+++def test_proxy_extraction_refuses_stream_before_calling_clairic_unless_the_deployment_drops_params(+ client: TestClient, monkeypatch: pytest.MonkeyPatch, respx_mock: respx.MockRouter+) -> None:+ monkeypatch.setattr(litellm, "drop_params", False)+ _route_invoice_reader_to_clairic(monkeypatch)+ upstream: Final = respx_mock.post(_CLAIRIC_UPSTREAM).respond(json={"result": _CLAIRIC_RESULT, "success": True})++ response: Final = client.post("/v1/extraction", json={**_EXTRACTION_REQUEST, "stream": True})++ assert response.status_code == 400, response.text+ assert "does not support parameters: ['stream']" in response.text+ assert not upstream.called+++def test_proxy_extraction_answers_a_dropped_stream_with_one_json_body(+ client: TestClient, monkeypatch: pytest.MonkeyPatch, respx_mock: respx.MockRouter+) -> None:+ _route_invoice_reader_to_clairic(monkeypatch, drop_params=True)+ upstream: Final = respx_mock.post(_CLAIRIC_UPSTREAM).respond(json={"result": _CLAIRIC_RESULT, "success": True})++ response: Final = client.post("/v1/extraction", json={**_EXTRACTION_REQUEST, "stream": True})++ assert response.status_code == 200, response.text+ assert response.headers["content-type"].startswith("application/json")+ assert response.json() == {**_CLAIRIC_RESULT, "model": "invoice-reader"}+ assert json.loads(upstream.calls[0].request.content) == {**_EXTRACTION_REQUEST, "model": "clairic"}+++class _RequestEmailMasker(CustomGuardrail):+ def __init__(self, email: str) -> None:+ super().__init__(guardrail_name="mask-email", event_hook=GuardrailEventHooks.pre_call, default_on=True)+ self.email = email++ async def apply_guardrail(+ self,+ inputs: GenericGuardrailAPIInputs,+ request_data: dict,+ input_type: Literal["request", "response"],+ logging_obj: object = None,+ ) -> GenericGuardrailAPIInputs:+ return GenericGuardrailAPIInputs(+ texts=[text.replace(self.email, "[EMAIL]") for text in inputs.get("texts", [])]+ )+++_EMAIL_STATE: Final = "Questions go to [email protected] today. The vendor is Acme Tools."+_MASKED_EMAIL_STATE: Final = "Questions go to [EMAIL] today. The vendor is Acme Tools."+_VENDOR_IN_MASKED_STATE: Final = {+ "type": "text",+ "value": "Acme Tools",+ "span": [_MASKED_EMAIL_STATE.index("Acme Tools"), _MASKED_EMAIL_STATE.index("Acme Tools") + len("Acme Tools")],+}+++def _clairic_vendor_result(state_text: str | None = None) -> Mapping[str, object]:+ return {+ "model": "clairic",+ "answers": {"vendor": _VENDOR_IN_MASKED_STATE},+ "truncated": False,+ "usage": {"input_tokens": 52, "output_tokens": 0},+ **({"state_text": state_text} if state_text is not None else {}),+ }+++ ("guardrail_email", "sent_state", "returned_vendor"),+ (+ ("[email protected]", _MASKED_EMAIL_STATE, {"type": "text", "value": "Acme Tools"}),+ ("[email protected]", _EMAIL_STATE, _VENDOR_IN_MASKED_STATE),+ ),+ ids=("state_masked", "state_untouched"),+)+def test_proxy_extraction_drops_spans_into_a_state_only_its_request_guardrail_saw(+ client: TestClient,+ monkeypatch: pytest.MonkeyPatch,+ respx_mock: respx.MockRouter,+ guardrail_email: str,+ sent_state: str,+ returned_vendor: Mapping[str, object],+) -> None:+ monkeypatch.setattr(litellm, "callbacks", [_RequestEmailMasker(guardrail_email)])+ _route_invoice_reader_to_clairic(monkeypatch)+ upstream: Final = respx_mock.post(_CLAIRIC_UPSTREAM).respond(+ json={"result": _clairic_vendor_result(), "success": True}+ )++ response: Final = client.post(+ "/v1/extraction",+ json={"model": "invoice-reader", "state": _EMAIL_STATE, "fields": {"vendor": {"type": "text"}}},+ )++ assert response.status_code == 200, response.text+ assert json.loads(upstream.calls[0].request.content)["state"] == sent_state+ assert response.json()["answers"] == {"vendor": returned_vendor}+++def test_proxy_extraction_keeps_spans_into_the_masked_state_it_returns(+ client: TestClient, monkeypatch: pytest.MonkeyPatch, respx_mock: respx.MockRouter+) -> None:+ monkeypatch.setattr(litellm, "callbacks", [_RequestEmailMasker("[email protected]")])+ _route_invoice_reader_to_clairic(monkeypatch)+ respx_mock.post(_CLAIRIC_UPSTREAM).respond(+ json={"result": _clairic_vendor_result(state_text=_MASKED_EMAIL_STATE), "success": True}+ )++ response: Final = client.post(+ "/v1/extraction",+ json={+ "model": "invoice-reader",+ "state": _EMAIL_STATE,+ "fields": {"vendor": {"type": "text"}},+ "options": {"return_state_text": True},+ },+ )++ assert response.status_code == 200, response.text+ body: Final = response.json()+ assert body["answers"] == {"vendor": _VENDOR_IN_MASKED_STATE}+ assert body["state_text"][slice(*body["answers"]["vendor"]["span"])] == "Acme Tools"++[email protected]("path", ("/v1/extraction", "/extraction"))+def test_swagger_documents_the_extraction_request_and_response(decisions_openapi: dict[str, object], path: str) -> None:+ operation = decisions_openapi["paths"][path]["post"]+ media = operation["requestBody"]["content"]["application/json"]++ assert {"model", "fields"} <= set(media["schema"]["required"])+ assert "$ref" not in json.dumps(media["schema"])+ example = {key: value for key, value in media["example"].items() if key != "model"}+ assert len(TypeAdapter(ExtractionRequestBody).validate_python(example).fields) == 5+ response_ref = operation["responses"]["200"]["content"]["application/json"]["schema"]["$ref"]+ assert response_ref == "#/components/schemas/ExtractionResponse"+ assert {"answers", "usage"} <= set(decisions_openapi["components"]["schemas"]["ExtractionResponse"]["properties"])++def test_proxy_systemone_reads_a_zstd_compressed_request_body(client: TestClient,respx_mock: respx.MockRouter,diff --git a/tests/unit/proxy/health_endpoints/test_health_endpoints.py b/tests/unit/proxy/health_endpoints/test_health_endpoints.pyindex d5288a7fc12..950d1742d49 100644--- a/tests/unit/proxy/health_endpoints/test_health_endpoints.py+++ b/tests/unit/proxy/health_endpoints/test_health_endpoints.py@@ -5297,9 +5297,49 @@ def test_test_model_connection_accepts_image_edit_mode(monkeypatch):assert response.json()["status"] == "success"[email protected]("mode", ("decisions", "evaluation"), ids=("decisions", "legacy-evaluation"))-def test_test_model_connection_accepts_decision_modes(- monkeypatch, mode: Literal["evaluation", "decisions"]+_TYPESAFE_TEST_CONNECTION: Final = (+ {"model": "typesafe/jev-latest", "api_key": "sk-test"},+ "https://api.typesafe.ai/v1/systemone",+ {+ "model": "jev-latest",+ "answers": {"reachable": {"type": "noul", "noul": 1.0}},+ "usage": {"input_tokens": 12, "output_tokens": 1},+ },+)+_CLAIRIC_TEST_CONNECTION: Final = (+ {+ "model": "cloudflare/clairic",+ "api_key": "sk-test",+ "api_base": "https://api.cloudflare.com/client/v4/accounts/acct/ai/run",+ },+ "https://api.cloudflare.com/client/v4/accounts/acct/ai/run/@cf/cloudflare/clairic",+ {+ "result": {+ "model": "clairic",+ "answers": {"status": {"type": "text", "value": "ok"}},+ "truncated": False,+ "usage": {"input_tokens": 9, "output_tokens": 0},+ },+ "success": True,+ },+)+++ ("mode", "litellm_params", "upstream_url", "upstream_json"),+ (+ ("decisions", *_TYPESAFE_TEST_CONNECTION),+ ("evaluation", *_TYPESAFE_TEST_CONNECTION),+ ("extraction", *_CLAIRIC_TEST_CONNECTION),+ ),+ ids=("decisions", "legacy-evaluation", "extraction"),+)+def test_test_model_connection_accepts_decision_and_extraction_modes(+ monkeypatch,+ mode: Literal["evaluation", "decisions", "extraction"],+ litellm_params: Mapping[str, str],+ upstream_url: str,+ upstream_json: Mapping[str, object],):monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)litellm.in_memory_llm_clients_cache.flush_cache()@@ -5315,20 +5355,8 @@ def test_test_model_connection_accepts_decision_modes(),respx.mock(assert_all_called=True) as respx_mock,):- upstream = respx_mock.post("https://api.typesafe.ai/v1/systemone").respond(- json={- "model": "jev-latest",- "answers": {"reachable": {"type": "noul", "noul": 1.0}},- "usage": {"input_tokens": 12, "output_tokens": 1},- }- )- response = client.post(- "/health/test_connection",- json={- "mode": mode,- "litellm_params": {"model": "typesafe/jev-latest", "api_key": "sk-test"},- },- )+ upstream = respx_mock.post(upstream_url).respond(json=upstream_json)+ response = client.post("/health/test_connection", json={"mode": mode, "litellm_params": litellm_params})assert response.status_code == 200, response.textassert response.json()["status"] == "success"diff --git a/tests/unit/proxy/hooks/test_parallel_request_limiter_v3.py b/tests/unit/proxy/hooks/test_parallel_request_limiter_v3.pyindex 7af747fc26d..8a74f2d50b4 100644--- a/tests/unit/proxy/hooks/test_parallel_request_limiter_v3.py+++ b/tests/unit/proxy/hooks/test_parallel_request_limiter_v3.py@@ -48,6 +48,7 @@ from litellm.proxy.spend_tracking.ptu_feature_flag import PTU_COST_ATTRIBUTION_Efrom litellm.proxy.utils import InternalUsageCache, ProxyLogging, hash_tokenfrom litellm.router_utils.ptu_shares import PTUTeamCeilingfrom litellm.types.caching import RedisPipelineIncrementOperation+from litellm.types.extraction import ExtractionResponsefrom litellm.types.llms.openai import ResponsesAPIResponsefrom litellm.types.mcp import MCPPreCallRequestObject, MCPTransportfrom litellm.types.mcp_server.mcp_server_manager import MCPServer@@ -8686,3 +8687,78 @@ async def test_a2a_url_target_owns_invocation_fee_and_request_limit(await _rpm_request(limiter, cache, auth, "a2a/cheap")assert denied.value.status_code == 429assert "expensive" in str(denied.value.detail)+++def _extraction_request(state: str, call_id: str) -> dict[str, object]:+ return {+ "model": "invoice-reader",+ "state": state,+ "fields": {"vendor": {"type": "text", "instructions": "Who sent the invoice"}},+ "litellm_call_id": call_id,+ }+++async def test_an_extraction_request_passes_a_tpm_limited_key_without_an_injected_output_cap():+ cache: Final = DualCache()+ handler: Final = _PROXY_MaxParallelRequestsHandler(internal_usage_cache=InternalUsageCache(cache))+ key: Final = UserAPIKeyAuth(api_key=hash_token("sk-extraction-cap"), tpm_limit=2000)+ data: Final = _extraction_request("Invoice from Acme Tools", "extraction-cap")+ sent: Final = dict(data)++ await handler.async_pre_call_hook(user_api_key_dict=key, cache=cache, data=data, call_type="aextraction")++ assert data == sent+++async def test_an_extraction_request_reserves_its_state_and_no_output_budget(monkeypatch):+ monkeypatch.delenv("LITELLM_TPM_TOKEN_RESERVATION_ENABLED", raising=False)+ cache: Final = DualCache()+ handler: Final = _PROXY_MaxParallelRequestsHandler(internal_usage_cache=InternalUsageCache(cache))+ key: Final = UserAPIKeyAuth(api_key=hash_token("sk-extraction-estimate"), tpm_limit=1_000_000)+ state_tokens: Final = 500++ reserved: Final = await _reserved_tokens_for(+ handler, cache, key, _extraction_request("word" * state_tokens, "extraction-estimate"), call_type="aextraction"+ )++ assert state_tokens <= reserved < 2 * state_tokens+++async def test_a_successful_extraction_counts_its_input_tokens_toward_the_key_tpm_limit(monkeypatch):+ monkeypatch.setattr(_PROXY_MaxParallelRequestsHandler, "get_rate_limit_type", lambda self: "total")+ cache: Final = DualCache()+ handler: Final = _PROXY_MaxParallelRequestsHandler(internal_usage_cache=InternalUsageCache(cache))+ api_key: Final = hash_token("sk-extraction-usage")+ key: Final = UserAPIKeyAuth(api_key=api_key, tpm_limit=500)+ await handler.async_pre_call_hook(+ user_api_key_dict=key, cache=cache, data=_extraction_request("Invoice", "extraction-1"), call_type="aextraction"+ )++ await handler.async_log_success_event(+ kwargs={+ "litellm_call_id": "extraction-1",+ "standard_logging_object": {"metadata": {"user_api_key_hash": api_key}},+ },+ response_obj=ExtractionResponse.model_validate(+ {+ "model": "invoice-reader",+ "answers": {"vendor": {"type": "text", "value": "Acme Tools"}},+ "truncated": False,+ "usage": {"input_tokens": 480, "output_tokens": 0},+ }+ ),+ start_time=datetime.now(),+ end_time=datetime.now(),+ )++ with pytest.raises(HTTPException) as refused:+ await handler.async_pre_call_hook(+ user_api_key_dict=key,+ cache=cache,+ data=_extraction_request("Invoice " * 40, "extraction-2"),+ call_type="aextraction",+ )+ assert refused.value.status_code == 429diff --git a/tests/unit/proxy/test_common_request_processing.py b/tests/unit/proxy/test_common_request_processing.pyindex 39423939b68..d742956bb59 100644--- a/tests/unit/proxy/test_common_request_processing.py+++ b/tests/unit/proxy/test_common_request_processing.py@@ -3551,6 +3551,30 @@ class TestOverrideOpenAIResponseModel:assert response_obj.model == "downstream-model"+ def test_frozen_response_comes_back_as_a_copy_carrying_the_requested_model(self):+ from litellm.types.extraction import ExtractionResponse++ response_obj = ExtractionResponse.model_validate(+ {+ "model": "cloudflare/@cf/cloudflare/clairic",+ "answers": {"vendor": {"type": "text", "value": "Acme Tools"}},+ "truncated": False,+ "usage": {"input_tokens": 52, "output_tokens": 0},+ }+ )+ response_obj.set_hidden_params({"response_cost": 0.0000052})++ stamped = _override_openai_response_model(+ response_obj=response_obj,+ requested_model="invoice-reader",+ log_context="test_context",+ )++ assert isinstance(stamped, ExtractionResponse)+ assert stamped.model == "invoice-reader"+ assert stamped.answers == response_obj.answers+ assert stamped.hidden_params["response_cost"] == 0.0000052+class TestIsAzureModelRouterRequest:"""Tests for _is_azure_model_router_request helper"""diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.pyindex 24d3ed678c9..9b6700e9d39 100644--- a/tests/unit/test_utils.py+++ b/tests/unit/test_utils.py@@ -1073,6 +1073,7 @@ def test_aaamodel_prices_and_context_window_json_is_valid():"image_edit","embedding","evaluation",+ "extraction","guardrail","image_generation","video_generation",@@ -9378,7 +9379,7 @@ def test_models_by_provider():continueelif v["litellm_provider"] == "sagemaker" or v["litellm_provider"] == "bedrock_converse":continue- elif v.get("mode") in ("search", "decisions", "evaluation"):+ elif v.get("mode") in ("search", "decisions", "evaluation", "extraction"):continueelse:providers.add(v["litellm_provider"])diff --git a/ui/litellm-dashboard/src/components/AIHub/modelUsageExample.test.ts b/ui/litellm-dashboard/src/components/AIHub/modelUsageExample.test.tsindex 25d1b83ebe9..8591e6f82f8 100644--- a/ui/litellm-dashboard/src/components/AIHub/modelUsageExample.test.ts+++ b/ui/litellm-dashboard/src/components/AIHub/modelUsageExample.test.ts@@ -21,6 +21,16 @@ describe("modelUsageExample", () => {);});+ it("posts an extraction model to /v1/extraction with typed fields", () => {+ const example = modelUsageExample("extraction", BASE_URL, "clairic", "X-Litellm-Key");+ expect(example).toContain('"https://proxy.example.com/v1/extraction"');+ expect(example).toContain('headers={"X-Litellm-Key": "Bearer your_api_key"}');+ expect(example).toContain('"model": "clairic"');+ expect(example).toContain('"fields": {');+ expect(example).not.toContain("chat.completions");+ expect(example).not.toContain("/v1/systemone");+ });+it("keeps the chat completions example for every other mode", () => {for (const mode of ["chat", null, undefined]) {const example = modelUsageExample(mode, BASE_URL, "gpt-5.5", "Authorization");@@ -28,6 +38,7 @@ describe("modelUsageExample", () => {expect(example).toContain('base_url="https://proxy.example.com"');expect(example).toContain('model="gpt-5.5"');expect(example).not.toContain("/v1/systemone");+ expect(example).not.toContain("/v1/extraction");}});diff --git a/ui/litellm-dashboard/src/components/AIHub/modelUsageExample.ts b/ui/litellm-dashboard/src/components/AIHub/modelUsageExample.tsindex 2426ec09942..83f2af1e8c6 100644--- a/ui/litellm-dashboard/src/components/AIHub/modelUsageExample.ts+++ b/ui/litellm-dashboard/src/components/AIHub/modelUsageExample.ts@@ -38,10 +38,33 @@ response = requests.post(print(response.json()["answers"])`;+const extractionExample = (baseUrl: string, model: string, keyHeaderName: string): string => `import requests++response = requests.post(+ ${JSON.stringify(`${baseUrl}/v1/extraction`)}, # Your LiteLLM Proxy URL+ headers={${JSON.stringify(keyHeaderName)}: "Bearer your_api_key"},+ json={+ "model": ${JSON.stringify(model)},+ "state": "Invoice #4471 from Acme Tools. Total $174.00, due in 30 days.",+ "fields": {+ "vendor": {"type": "text", "instructions": "Who sent the invoice?"},+ "total": {"type": "number", "unit": "USD"}+ }+ }+)++print(response.json()["answers"])`;+export const modelUsageExample = (mode: string | null | undefined,baseUrl: string,model: string,keyHeaderName: string,-): string =>- isDecisionMode(mode) ? systemOneExample(baseUrl, model, keyHeaderName) : chatCompletionsExample(baseUrl, model);+): string => {+ if (mode === "extraction") {+ return extractionExample(baseUrl, model, keyHeaderName);+ }+ return isDecisionMode(mode)+ ? systemOneExample(baseUrl, model, keyHeaderName)+ : chatCompletionsExample(baseUrl, model);+};diff --git a/ui/litellm-dashboard/src/components/add_model/AddModelForm.integration.test.tsx b/ui/litellm-dashboard/src/components/add_model/AddModelForm.integration.test.tsxindex cdc681a1c91..a95d9ffbfb8 100644--- a/ui/litellm-dashboard/src/components/add_model/AddModelForm.integration.test.tsx+++ b/ui/litellm-dashboard/src/components/add_model/AddModelForm.integration.test.tsx@@ -465,7 +465,7 @@ describe("AddModelForm", () => {expect(await screen.findByRole("button", { name: "Add Model" })).toBeInTheDocument();});- it("offers the Decisions mode", async () => {+ it.each(["Decisions - /v1/decisions", "Extraction - /v1/extraction"])("offers the %s mode", async (option) => {const mockUseAuthorized = vi.mocked(await import("@/app/(dashboard)/hooks/useAuthorized"));mockUseAuthorized.default.mockReturnValue(mockAuthorizedUser("proxy_admin", "user-1", true));@@ -474,7 +474,7 @@ describe("AddModelForm", () => {await screen.findByText("Provider");await userEvent.click(screen.getByRole("combobox", { name: "Mode" }));- expect(await screen.findByRole("option", { name: "Decisions - /v1/decisions", exact: true })).toBeInTheDocument();+ expect(await screen.findByRole("option", { name: option, exact: true })).toBeInTheDocument();});it("shows only the Close button in the connection test dialog footer", async () => {diff --git a/ui/litellm-dashboard/src/components/add_model/add_model_modes.tsx b/ui/litellm-dashboard/src/components/add_model/add_model_modes.tsxindex 45ffe969a21..63def76db8f 100644--- a/ui/litellm-dashboard/src/components/add_model/add_model_modes.tsx+++ b/ui/litellm-dashboard/src/components/add_model/add_model_modes.tsx@@ -14,6 +14,7 @@ export const TEST_MODES = [{ value: "anthropic_messages", label: "Anthropic Messages - /v1/messages" },{ value: "ocr", label: "OCR - /ocr" },{ value: "decisions", label: "Decisions - /v1/decisions" },+ { value: "extraction", label: "Extraction - /v1/extraction" },];// Define the available auto router routing strategiesdiff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.tsindex 4bd945b13ca..244141ec076 100644--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@ -5333,6 +5333,39 @@ export interface paths {patch: operations["assemblyai_proxy_route_eu_assemblyai__endpoint__patch"];trace?: never;};+ "/extraction": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ /**+ * Extract typed fields from a state+ * @description Read a `state` text and up to 4 images and get one typed answer per named field in `fields`.+ *+ * Field types are `text`, `number`, `date`, `time`, `datetime`, `duration`, `list` (set `items`), `estimate`+ * (set `min` and `max`) and `forecast` (set `min`, `max` and `horizon`). Each answer carries its `value`, which is+ * null when the input does not determine it, plus `confidence`, `p_null`, text `span`s into the state and, for+ * estimates, `mean`, `median`, `p10` and `p90`. Images are data URLs or `{content_type, base64}` objects, remote+ * URLs are not accepted. An unknown field type, a field name that is not 1 to 64 letters, digits, `_`, `.` or `-`+ * starting with a letter or `_`, a remote image URL or more than 4 images is rejected with a 400 before any+ * provider is called. Any other top-level key, `stream: true` and OpenAI generation settings such as `temperature`+ * included, is rejected with a 400 naming it unless `drop_params` or the deployment's `additional_drop_params`+ * drops it. Settings inside `fields` and `options` go to the provider as sent, so a field missing a setting its+ * type needs or an empty `state` with no images comes back with the provider's own error. `model` is any+ * extraction model in the proxy model list, such as Cloudflare Clairic. The request and the answers keep the+ * provider's format.+ */+ post: operations["extraction_extraction_post"];+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/fal_ai/{endpoint}": {parameters: {query?: never;@@ -20204,6 +20237,39 @@ export interface paths {patch?: never;trace?: never;};+ "/v1/extraction": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ /**+ * Extract typed fields from a state+ * @description Read a `state` text and up to 4 images and get one typed answer per named field in `fields`.+ *+ * Field types are `text`, `number`, `date`, `time`, `datetime`, `duration`, `list` (set `items`), `estimate`+ * (set `min` and `max`) and `forecast` (set `min`, `max` and `horizon`). Each answer carries its `value`, which is+ * null when the input does not determine it, plus `confidence`, `p_null`, text `span`s into the state and, for+ * estimates, `mean`, `median`, `p10` and `p90`. Images are data URLs or `{content_type, base64}` objects, remote+ * URLs are not accepted. An unknown field type, a field name that is not 1 to 64 letters, digits, `_`, `.` or `-`+ * starting with a letter or `_`, a remote image URL or more than 4 images is rejected with a 400 before any+ * provider is called. Any other top-level key, `stream: true` and OpenAI generation settings such as `temperature`+ * included, is rejected with a 400 naming it unless `drop_params` or the deployment's `additional_drop_params`+ * drops it. Settings inside `fields` and `options` go to the provider as sent, so a field missing a setting its+ * type needs or an empty `state` with no images comes back with the provider's own error. `model` is any+ * extraction model in the proxy model list, such as Cloudflare Clairic. The request and the answers keep the+ * provider's format.+ */+ post: operations["extraction_v1_extraction_post"];+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/v1/files": {parameters: {query?: never;@@ -27515,7 +27581,7 @@ export interface components {* Mode* @description The mode to test the model with. If not provided, resolved the way /health does: the deployment's model_info.mode (only while the request tests the deployment's own model), then the mode the provider requires for that model, then the model cost map.*/- mode?: ("chat" | "completion" | "embedding" | "audio_speech" | "audio_transcription" | "image_generation" | "image_edit" | "video_generation" | "batch" | "rerank" | "realtime" | "responses" | "anthropic_messages" | "ocr" | "evaluation" | "decisions") | null;+ mode?: ("chat" | "completion" | "embedding" | "audio_speech" | "audio_transcription" | "image_generation" | "image_edit" | "video_generation" | "batch" | "rerank" | "realtime" | "responses" | "anthropic_messages" | "ocr" | "evaluation" | "decisions" | "extraction") | null;/*** Model Info* @description Model info for the health check@@ -28399,7 +28465,7 @@ export interface components {* CallTypes* @enum {string}*/- CallTypes: "embedding" | "aembedding" | "completion" | "acompletion" | "atext_completion" | "text_completion" | "image_generation" | "aimage_generation" | "image_edit" | "aimage_edit" | "moderation" | "amoderation" | "atranscription" | "transcription" | "aspeech" | "speech" | "rerank" | "arerank" | "search" | "asearch" | "decisions" | "adecisions" | "systemone" | "asystemone" | "_arealtime" | "_aresponses_websocket" | "create_batch" | "acreate_batch" | "aretrieve_batch" | "retrieve_batch" | "acancel_batch" | "cancel_batch" | "pass_through_endpoint" | "anthropic_messages" | "aanthropic_messages" | "get_assistants" | "aget_assistants" | "create_assistants" | "acreate_assistants" | "delete_assistant" | "adelete_assistant" | "acreate_thread" | "create_thread" | "aget_thread" | "get_thread" | "a_add_message" | "add_message" | "aget_messages" | "get_messages" | "arun_thread" | "run_thread" | "arun_thread_stream" | "run_thread_stream" | "afile_retrieve" | "file_retrieve" | "afile_delete" | "file_delete" | "afile_list" | "file_list" | "acreate_file" | "create_file" | "afile_content" | "file_content" | "create_fine_tuning_job" | "acreate_fine_tuning_job" | "create_video" | "acreate_video" | "video_generation" | "avideo_generation" | "avideo_retrieve" | "video_retrieve" | "avideo_content" | "video_content" | "video_remix" | "avideo_remix" | "video_list" | "avideo_list" | "video_retrieve_job" | "avideo_retrieve_job" | "video_delete" | "avideo_delete" | "video_create_character" | "avideo_create_character" | "video_get_character" | "avideo_get_character" | "video_edit" | "avideo_edit" | "video_extension" | "avideo_extension" | "vector_store_file_create" | "avector_store_file_create" | "vector_store_file_list" | "avector_store_file_list" | "vector_store_file_retrieve" | "avector_store_file_retrieve" | "vector_store_file_content" | "avector_store_file_content" | "vector_store_file_update" | "avector_store_file_update" | "vector_store_file_delete" | "avector_store_file_delete" | "vector_store_create" | "avector_store_create" | "vector_store_search" | "avector_store_search" | "ingest" | "aingest" | "query" | "aquery" | "create_interaction" | "acreate_interaction" | "create_container" | "acreate_container" | "list_containers" | "alist_containers" | "retrieve_container" | "aretrieve_container" | "delete_container" | "adelete_container" | "list_container_files" | "alist_container_files" | "upload_container_file" | "aupload_container_file" | "create_sandbox" | "acreate_sandbox" | "delete_sandbox" | "adelete_sandbox" | "run_code" | "arun_code" | "code_interpreter_tool" | "acode_interpreter_tool" | "acancel_fine_tuning_job" | "cancel_fine_tuning_job" | "alist_fine_tuning_jobs" | "list_fine_tuning_jobs" | "aretrieve_fine_tuning_job" | "retrieve_fine_tuning_job" | "responses" | "aresponses" | "alist_input_items" | "llm_passthrough_route" | "allm_passthrough_route" | "generate_content" | "agenerate_content" | "generate_content_stream" | "agenerate_content_stream" | "ocr" | "aocr" | "call_mcp_tool" | "list_mcp_tools" | "asend_message" | "send_message" | "acreate_skill";+ CallTypes: "embedding" | "aembedding" | "completion" | "acompletion" | "atext_completion" | "text_completion" | "image_generation" | "aimage_generation" | "image_edit" | "aimage_edit" | "moderation" | "amoderation" | "atranscription" | "transcription" | "aspeech" | "speech" | "rerank" | "arerank" | "search" | "asearch" | "decisions" | "adecisions" | "systemone" | "asystemone" | "extraction" | "aextraction" | "_arealtime" | "_aresponses_websocket" | "create_batch" | "acreate_batch" | "aretrieve_batch" | "retrieve_batch" | "acancel_batch" | "cancel_batch" | "pass_through_endpoint" | "anthropic_messages" | "aanthropic_messages" | "get_assistants" | "aget_assistants" | "create_assistants" | "acreate_assistants" | "delete_assistant" | "adelete_assistant" | "acreate_thread" | "create_thread" | "aget_thread" | "get_thread" | "a_add_message" | "add_message" | "aget_messages" | "get_messages" | "arun_thread" | "run_thread" | "arun_thread_stream" | "run_thread_stream" | "afile_retrieve" | "file_retrieve" | "afile_delete" | "file_delete" | "afile_list" | "file_list" | "acreate_file" | "create_file" | "afile_content" | "file_content" | "create_fine_tuning_job" | "acreate_fine_tuning_job" | "create_video" | "acreate_video" | "video_generation" | "avideo_generation" | "avideo_retrieve" | "video_retrieve" | "avideo_content" | "video_content" | "video_remix" | "avideo_remix" | "video_list" | "avideo_list" | "video_retrieve_job" | "avideo_retrieve_job" | "video_delete" | "avideo_delete" | "video_create_character" | "avideo_create_character" | "video_get_character" | "avideo_get_character" | "video_edit" | "avideo_edit" | "video_extension" | "avideo_extension" | "vector_store_file_create" | "avector_store_file_create" | "vector_store_file_list" | "avector_store_file_list" | "vector_store_file_retrieve" | "avector_store_file_retrieve" | "vector_store_file_content" | "avector_store_file_content" | "vector_store_file_update" | "avector_store_file_update" | "vector_store_file_delete" | "avector_store_file_delete" | "vector_store_create" | "avector_store_create" | "vector_store_search" | "avector_store_search" | "ingest" | "aingest" | "query" | "aquery" | "create_interaction" | "acreate_interaction" | "create_container" | "acreate_container" | "list_containers" | "alist_containers" | "retrieve_container" | "aretrieve_container" | "delete_container" | "adelete_container" | "list_container_files" | "alist_container_files" | "upload_container_file" | "aupload_container_file" | "create_sandbox" | "acreate_sandbox" | "delete_sandbox" | "adelete_sandbox" | "run_code" | "arun_code" | "code_interpreter_tool" | "acode_interpreter_tool" | "acancel_fine_tuning_job" | "cancel_fine_tuning_job" | "alist_fine_tuning_jobs" | "list_fine_tuning_jobs" | "aretrieve_fine_tuning_job" | "retrieve_fine_tuning_job" | "responses" | "aresponses" | "alist_input_items" | "llm_passthrough_route" | "allm_passthrough_route" | "generate_content" | "agenerate_content" | "generate_content_stream" | "agenerate_content_stream" | "ocr" | "aocr" | "call_mcp_tool" | "list_mcp_tools" | "asend_message" | "send_message" | "acreate_skill";/** CallbackDelete */CallbackDelete: {/** Callback Name */@@ -32203,6 +32269,69 @@ export interface components {* @enum {string}*/ExportType: "daily" | "daily_with_keys" | "daily_with_models" | "daily_with_users";+ /** ExtractionAnswer */+ ExtractionAnswer: {+ /** Confidence */+ confidence?: number | null;+ guess?: components["schemas"]["JsonValue"];+ mean?: components["schemas"]["JsonValue"];+ median?: components["schemas"]["JsonValue"];+ p10?: components["schemas"]["JsonValue"];+ p90?: components["schemas"]["JsonValue"];+ /** P Above */+ p_above?: number | null;+ /** P Below */+ p_below?: number | null;+ /** P Null */+ p_null?: number | null;+ /** Quantiles */+ quantiles?: components["schemas"]["JsonValue"][] | null;+ /** Span */+ span?: number[] | null;+ /** Spans */+ spans?: number[][] | null;+ /** Steps */+ steps?: components["schemas"]["JsonValue"][] | null;+ /** Type */+ type: string;+ /** @description The answer, null when the input does not determine it */+ value: components["schemas"]["JsonValue"];+ } & {+ [key: string]: unknown;+ };+ /** ExtractionResponse */+ ExtractionResponse: {+ /** Answers */+ answers: {+ [key: string]: components["schemas"]["ExtractionAnswer"];+ };+ /** Model */+ model: string;+ /** State Text */+ state_text?: string | null;+ /** Truncated */+ truncated: boolean;+ usage: components["schemas"]["ExtractionUsage"];+ } & {+ [key: string]: unknown;+ };+ /** ExtractionUsage */+ ExtractionUsage: {+ /** Image Tokens */+ image_tokens?: number | null;+ /** Input Tokens */+ input_tokens: number;+ /** Output Tokens */+ output_tokens: number;+ /** Passes */+ passes?: number | null;+ /** Schema Tokens */+ schema_tokens?: number | null;+ /** State Tokens */+ state_tokens?: number | null;+ } & {+ [key: string]: unknown;+ };/*** FacetListResponse* @description The distinct values one column takes over a filtered query. `data` holds bare values, not entity rows.@@ -59011,6 +59140,180 @@ export interface operations {};};};+ extraction_extraction_post: {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody: {+ content: {+ /**+ * @example {+ * "fields": {+ * "days_to_pay": {+ * "max": 90,+ * "min": 0,+ * "type": "estimate"+ * },+ * "invoice_date": {+ * "type": "date"+ * },+ * "items": {+ * "instructions": "What was bought?",+ * "items": "text",+ * "type": "list"+ * },+ * "total": {+ * "type": "number",+ * "unit": "USD"+ * },+ * "vendor": {+ * "instructions": "Who sent the invoice?",+ * "type": "text"+ * }+ * },+ * "model": "clairic",+ * "state": "Invoice #4471 from Acme Tools, dated 2026-03-03. 12 hammers. Total $174. Payment due in 30 days."+ * }+ */+ "application/json": {+ /**+ * Fields+ * @description Field name to typed field spec. Each name becomes a key in the answers+ */+ fields: {+ [key: string]: {+ /**+ * Decimals+ * @description Numbers, durations and number lists only, 0 to 6+ */+ decimals?: number | null;+ /**+ * Horizon+ * @description Forecast only, number of steps+ */+ horizon?: number | null;+ /**+ * Instructions+ * @description What the field should contain+ */+ instructions?: string | null;+ /**+ * Integer+ * @description Numbers and durations only+ */+ integer?: boolean | null;+ /** Interval */+ interval?: ("step" | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year") | null;+ /**+ * Items+ * @description Item type, required for list fields+ */+ items?: ("text" | "number" | "date") | null;+ /**+ * Max+ * @description Estimate and forecast upper bound+ */+ max?: number | string | null;+ /**+ * Min+ * @description Estimate and forecast lower bound+ */+ min?: number | string | null;+ /**+ * Null Threshold+ * @description Probability of null above which the value is null+ */+ null_threshold?: number | null;+ /** Scale */+ scale?: ("linear" | "log") | null;+ /**+ * Step+ * @description Estimate grid step, or month or year+ */+ step?: number | string | null;+ /**+ * Type+ * @description The answer type for this field+ * @enum {string}+ */+ type: "text" | "number" | "date" | "time" | "datetime" | "duration" | "list" | "estimate" | "forecast";+ /**+ * Unit+ * @description Unit label. For durations, seconds through years+ */+ unit?: string | null;+ } & {+ [key: string]: unknown;+ };+ };+ /**+ * Images+ * @description Up to 4 images as data URLs or content_type plus base64, no remote URLs+ */+ images?: (string | ({+ /**+ * Base64+ * @description Base64-encoded image bytes+ */+ base64: string;+ /**+ * Content Type+ * @description The image media type, such as image/png+ */+ content_type: string;+ } & {+ [key: string]: unknown;+ }))[] | null;+ /**+ * Model+ * @description An extraction model from the proxy model_list+ */+ model: string;+ options?: ({+ /**+ * Include Quantiles+ * @description Add 99 percentiles to estimates+ */+ include_quantiles?: boolean | null;+ /**+ * Return State Text+ * @description Return the text that spans index into+ */+ return_state_text?: boolean | null;+ } & {+ [key: string]: unknown;+ }) | null;+ /**+ * Reference Date+ * @description ISO date that anchors dates written without a year+ */+ reference_date?: string | null;+ /**+ * State+ * @description The text to read. Must be non-empty unless images are sent. Text answers are spans of it+ * @default+ */+ state?: string;+ } & {+ [key: string]: unknown;+ };+ };+ };+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["ExtractionResponse"];+ };+ };+ };+ };fal_ai_proxy_route_fal_ai__endpoint__get: {parameters: {query?: never;@@ -78336,6 +78639,180 @@ export interface operations {};};};+ extraction_v1_extraction_post: {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody: {+ content: {+ /**+ * @example {+ * "fields": {+ * "days_to_pay": {+ * "max": 90,+ * "min": 0,+ * "type": "estimate"+ * },+ * "invoice_date": {+ * "type": "date"+ * },+ * "items": {+ * "instructions": "What was bought?",+ * "items": "text",+ * "type": "list"+ * },+ * "total": {+ * "type": "number",+ * "unit": "USD"+ * },+ * "vendor": {+ * "instructions": "Who sent the invoice?",+ * "type": "text"+ * }+ * },+ * "model": "clairic",+ * "state": "Invoice #4471 from Acme Tools, dated 2026-03-03. 12 hammers. Total $174. Payment due in 30 days."+ * }+ */+ "application/json": {+ /**+ * Fields+ * @description Field name to typed field spec. Each name becomes a key in the answers+ */+ fields: {+ [key: string]: {+ /**+ * Decimals+ * @description Numbers, durations and number lists only, 0 to 6+ */+ decimals?: number | null;+ /**+ * Horizon+ * @description Forecast only, number of steps+ */+ horizon?: number | null;+ /**+ * Instructions+ * @description What the field should contain+ */+ instructions?: string | null;+ /**+ * Integer+ * @description Numbers and durations only+ */+ integer?: boolean | null;+ /** Interval */+ interval?: ("step" | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year") | null;+ /**+ * Items+ * @description Item type, required for list fields+ */+ items?: ("text" | "number" | "date") | null;+ /**+ * Max+ * @description Estimate and forecast upper bound+ */+ max?: number | string | null;+ /**+ * Min+ * @description Estimate and forecast lower bound+ */+ min?: number | string | null;+ /**+ * Null Threshold+ * @description Probability of null above which the value is null+ */+ null_threshold?: number | null;+ /** Scale */+ scale?: ("linear" | "log") | null;+ /**+ * Step+ * @description Estimate grid step, or month or year+ */+ step?: number | string | null;+ /**+ * Type+ * @description The answer type for this field+ * @enum {string}+ */+ type: "text" | "number" | "date" | "time" | "datetime" | "duration" | "list" | "estimate" | "forecast";+ /**+ * Unit+ * @description Unit label. For durations, seconds through years+ */+ unit?: string | null;+ } & {+ [key: string]: unknown;+ };+ };+ /**+ * Images+ * @description Up to 4 images as data URLs or content_type plus base64, no remote URLs+ */+ images?: (string | ({+ /**+ * Base64+ * @description Base64-encoded image bytes+ */+ base64: string;+ /**+ * Content Type+ * @description The image media type, such as image/png+ */+ content_type: string;+ } & {+ [key: string]: unknown;+ }))[] | null;+ /**+ * Model+ * @description An extraction model from the proxy model_list+ */+ model: string;+ options?: ({+ /**+ * Include Quantiles+ * @description Add 99 percentiles to estimates+ */+ include_quantiles?: boolean | null;+ /**+ * Return State Text+ * @description Return the text that spans index into+ */+ return_state_text?: boolean | null;+ } & {+ [key: string]: unknown;+ }) | null;+ /**+ * Reference Date+ * @description ISO date that anchors dates written without a year+ */+ reference_date?: string | null;+ /**+ * State+ * @description The text to read. Must be non-empty unless images are sent. Text answers are spans of it+ * @default+ */+ state?: string;+ } & {+ [key: string]: unknown;+ };+ };+ };+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["ExtractionResponse"];+ };+ };+ };+ };list_files_v1_files_get: {parameters: {query?: {