Skip to content

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

UN-3478 [FIX] Support OpenAI gpt-5 / o-series in openai-compatible adapter (#1983)

Praveen Kumarc2fb9318c400
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/base1.py b/unstract/sdk1/src/unstract/sdk1/adapters/base1.py
index 7bc58296c..c78fe5c43 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/base1.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/base1.py
@@ -340,10 +340,36 @@ class OpenAILLMParameters(BaseChatCompletionParameters):
def validate_model(adapter_metadata: dict[str, "Any"]) -> str:
model = adapter_metadata.get("model", "")
# Only add openai/ prefix if the model doesn't already have it
- if model.startswith("openai/"):
+ if model.startswith(_OPENAI_PROVIDER_PREFIX):
return model
else:
- return f"openai/{model}"
+ return f"{_OPENAI_PROVIDER_PREFIX}{model}"
+
+
+# LiteLLM provider prefixes hoisted to module constants so the same literal is
+# not duplicated across `OpenAILLMParameters`, `OpenAICompatibleLLMParameters`,
+# and the reasoning-model detector below.
+_OPENAI_PROVIDER_PREFIX = "openai/"
+_CUSTOM_OPENAI_PROVIDER_PREFIX = "custom_openai/"
+_OPENAI_REASONING_MODEL_PATTERN = re.compile(r"^(o1|o3|o4|gpt-5)(?:[-/]|$)")
+
+
+def _is_openai_reasoning_model(model: str) -> bool:
+ """Best-effort detection of OpenAI reasoning model names.
+
+ The check is conservative — it matches only OpenAI's known reasoning
+ families (o1, o3, o4, gpt-5) after stripping the LiteLLM `custom_openai/`
+ prefix and optional `openai/` sub-prefix. Custom gateway model aliases
+ that hide a reasoning model behind an unrelated name still need the
+ explicit `enable_reasoning` opt-in.
+ """
+ if not model:
+ return False
+ if model.startswith(_CUSTOM_OPENAI_PROVIDER_PREFIX):
+ model = model[len(_CUSTOM_OPENAI_PROVIDER_PREFIX) :]
+ if model.startswith(_OPENAI_PROVIDER_PREFIX):
+ model = model[len(_OPENAI_PROVIDER_PREFIX) :]
+ return bool(_OPENAI_REASONING_MODEL_PATTERN.match(model.lower()))
class OpenAICompatibleLLMParameters(BaseChatCompletionParameters):
@@ -351,6 +377,7 @@ class OpenAICompatibleLLMParameters(BaseChatCompletionParameters):
api_key: str | None = None
api_base: str
+ reasoning_effort: str | None = None
@staticmethod
def validate(adapter_metadata: dict[str, "Any"]) -> dict[str, "Any"]:
@@ -360,16 +387,92 @@ class OpenAICompatibleLLMParameters(BaseChatCompletionParameters):
api_key = adapter_metadata.get("api_key")
if isinstance(api_key, str) and not api_key.strip():
adapter_metadata["api_key"] = None
- return OpenAICompatibleLLMParameters(**adapter_metadata).model_dump()
+
+ # Reasoning models (OpenAI gpt-5, o1, o3, ...) routed through an
+ # OpenAI-compatible gateway reject `temperature != 1` and `max_tokens`
+ # (require `max_completion_tokens`). LiteLLM's `custom_openai` provider
+ # is generic and does not apply these transformations, so we route the
+ # reasoning-only fields via `extra_body` (which LiteLLM forwards as-is)
+ # and strip the rejected fields from the top-level kwargs.
+ # Auto-detect known OpenAI reasoning model names so users do not have
+ # to know that gpt-5 / o-series need special handling — they can still
+ # opt in explicitly for custom gateway aliases that hide the model id.
+ enable_reasoning = adapter_metadata.get("enable_reasoning", False)
+ has_reasoning_effort = (
+ "reasoning_effort" in adapter_metadata
+ and adapter_metadata.get("reasoning_effort") is not None
+ )
+ # When validate() runs again on its own previous output, the reasoning
+ # fields live ONLY inside `extra_body` (this method strips them from
+ # the top level on the reasoning path). Recover them from there so
+ # re-validation is idempotent for non-auto-detected aliases too.
+ existing_extra_body = adapter_metadata.get("extra_body")
+ has_reasoning_extra_body = (
+ isinstance(existing_extra_body, dict)
+ and existing_extra_body.get("reasoning_effort") is not None
+ )
+ # Infer reasoning only when `enable_reasoning` is ABSENT (e.g. on a
+ # re-validation pass that already stripped the field). Skip the inference
+ # if the user explicitly submitted `enable_reasoning: false` with a
+ # leftover `reasoning_effort` — that's an explicit opt-out, not an
+ # implicit opt-in.
+ if (
+ not enable_reasoning
+ and "enable_reasoning" not in adapter_metadata
+ and (has_reasoning_effort or has_reasoning_extra_body)
+ ):
+ enable_reasoning = True
+ if not enable_reasoning and _is_openai_reasoning_model(adapter_metadata["model"]):
+ enable_reasoning = True
+
+ reasoning_effort = (
+ adapter_metadata.get("reasoning_effort")
+ or (
+ existing_extra_body.get("reasoning_effort")
+ if isinstance(existing_extra_body, dict)
+ else None
+ )
+ or "medium"
+ )
+
+ exclude_fields = {"enable_reasoning"}
+ if not enable_reasoning:
+ exclude_fields.add("reasoning_effort")
+ validation_metadata = {
+ k: v for k, v in adapter_metadata.items() if k not in exclude_fields
+ }
+ validated = OpenAICompatibleLLMParameters(**validation_metadata).model_dump()
+
+ if enable_reasoning:
+ # Read max_tokens from the validated dict so Pydantic's `int | None`
+ # coercion (e.g. "4096" -> 4096) has already been applied before the
+ # value is forwarded to the upstream API via extra_body. On the
+ # re-validation path the original max_tokens is in extra_body, not
+ # at the top level — fall back to that to keep the value across
+ # passes.
+ max_tokens = validated.get("max_tokens")
+ if max_tokens is None and isinstance(existing_extra_body, dict):
+ max_tokens = existing_extra_body.get("max_completion_tokens")
+ extra_body = {"reasoning_effort": reasoning_effort}
+ if max_tokens is not None:
+ extra_body["max_completion_tokens"] = max_tokens
+ validated["extra_body"] = extra_body
+ validated.pop("temperature", None)
+ validated.pop("max_tokens", None)
+ validated.pop("reasoning_effort", None)
+ else:
+ validated.pop("reasoning_effort", None)
+
+ return validated
@staticmethod
def validate_model(adapter_metadata: dict[str, "Any"]) -> str:
model = str(adapter_metadata.get("model", "")).strip()
if not model:
raise ValueError("model is required for the OpenAI Compatible adapter.")
- if model.startswith("custom_openai/"):
+ if model.startswith(_CUSTOM_OPENAI_PROVIDER_PREFIX):
return model
- return f"custom_openai/{model}"
+ return f"{_CUSTOM_OPENAI_PROVIDER_PREFIX}{model}"
class AzureOpenAILLMParameters(BaseChatCompletionParameters):
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/llm1/static/custom_openai.json b/unstract/sdk1/src/unstract/sdk1/adapters/llm1/static/custom_openai.json
index 8767ffdcf..670616258 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/llm1/static/custom_openai.json
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/llm1/static/custom_openai.json
@@ -38,7 +38,7 @@
"multipleOf": 1,
"title": "Maximum Output Tokens",
"default": 4096,
- "description": "Maximum number of output tokens to limit LLM replies. Leave it empty to use the provider default."
+ "description": "Maximum number of output tokens to limit LLM replies. Leave it empty to use the provider default. Sent as `max_completion_tokens` when Enable Reasoning is on."
},
"max_retries": {
"type": "number",
@@ -55,6 +55,59 @@
"title": "Timeout",
"default": 900,
"description": "Timeout in seconds."
+ },
+ "enable_reasoning": {
+ "type": "boolean",
+ "title": "Enable Reasoning",
+ "default": false,
+ "description": "Auto-detected for OpenAI reasoning families (gpt-5, o1, o3, o4). Toggle on for gateway aliases that hide the underlying reasoning model behind a custom name. Drops `temperature` and sends `max_completion_tokens` and `reasoning_effort` via `extra_body` so the upstream API accepts them."
+ }
+ },
+ "allOf": [
+ {
+ "if": {
+ "properties": {
+ "enable_reasoning": {
+ "const": true
+ }
+ },
+ "required": [
+ "enable_reasoning"
+ ]
+ },
+ "then": {
+ "properties": {
+ "reasoning_effort": {
+ "type": "string",
+ "enum": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "default": "medium",
+ "title": "Reasoning Effort",
+ "description": "Sets the reasoning strength when Enable Reasoning is on."
+ }
+ },
+ "required": [
+ "reasoning_effort"
+ ]
+ }
+ },
+ {
+ "if": {
+ "properties": {
+ "enable_reasoning": {
+ "const": false
+ }
+ },
+ "required": [
+ "enable_reasoning"
+ ]
+ },
+ "then": {
+ "properties": {}
+ }
}
- }
+ ]
}
diff --git a/unstract/sdk1/tests/test_openai_compatible_adapter.py b/unstract/sdk1/tests/test_openai_compatible_adapter.py
index addbf080c..fb7da3165 100644
--- a/unstract/sdk1/tests/test_openai_compatible_adapter.py
+++ b/unstract/sdk1/tests/test_openai_compatible_adapter.py
@@ -3,11 +3,17 @@ from functools import lru_cache
from importlib import import_module
from unittest.mock import MagicMock, patch
+import pytest
from unstract.sdk1.adapters.base1 import OpenAICompatibleLLMParameters
from unstract.sdk1.adapters.constants import Common
from unstract.sdk1.adapters.llm1 import adapters
from unstract.sdk1.adapters.llm1.openai_compatible import OpenAICompatibleLLMAdapter
+# Pydantic default for `temperature` on `BaseChatCompletionParameters`. Wrapped
+# in `pytest.approx` so the non-reasoning-path assertions read the value safely
+# (float `==` triggers Sonar S1244 even when both sides are the same literal).
+_DEFAULT_TEMPERATURE = pytest.approx(0.1)
+
OPENAI_COMPATIBLE_DESCRIPTION = (
"Adapter for servers that implement the OpenAI Chat Completions API "
"(vLLM, LM Studio, self-hosted gateways, and third-party providers). "
@@ -87,6 +93,216 @@ def test_openai_compatible_schema_is_loadable() -> None:
assert "default" not in schema["properties"]["api_base"]
+def test_openai_compatible_schema_exposes_reasoning_toggle() -> None:
+ schema = json.loads(OpenAICompatibleLLMAdapter.get_json_schema())
+
+ reasoning_flag = schema["properties"]["enable_reasoning"]
+ assert reasoning_flag["type"] == "boolean"
+ assert reasoning_flag["default"] is False
+
+ reasoning_branch = next(
+ branch
+ for branch in schema["allOf"]
+ if branch["if"]["properties"]["enable_reasoning"]["const"] is True
+ )
+ effort = reasoning_branch["then"]["properties"]["reasoning_effort"]
+ assert effort["enum"] == ["low", "medium", "high"]
+ assert effort["default"] == "medium"
+ assert reasoning_branch["then"]["required"] == ["reasoning_effort"]
+ # `if` must require `enable_reasoning` so the conditional does not fire
+ # vacuously when the property is omitted from the submitted instance
+ # (JSON Schema treats a `properties`-only `if` as valid in that case).
+ for branch in schema["allOf"]:
+ assert branch["if"].get("required") == [
+ "enable_reasoning"
+ ], "if/then branches must anchor on the property being present"
+
+
+def test_openai_compatible_validate_auto_detects_reasoning_for_known_families() -> None:
+ # User-facing requirement: dropping a known OpenAI reasoning model name
+ # (gpt-5, o1, o3, o4 and their *-mini / *-nano / dated variants) into the
+ # adapter must "just work" — the upstream API rejects `temperature != 1`
+ # and `max_tokens`, and users will not know to flip a switch for that.
+ for model in [
+ "gpt-5",
+ "gpt-5-mini",
+ "gpt-5-2024-12-01",
+ "o1",
+ "o1-mini",
+ "o1-preview",
+ "o3",
+ "o3-mini",
+ "o4-mini",
+ "openai/gpt-5",
+ ]:
+ validated = OpenAICompatibleLLMParameters.validate(
+ {
+ "api_base": "https://api.openai.com/v1",
+ "api_key": "sk-test",
+ "model": model,
+ "max_tokens": 4096,
+ }
+ )
+
+ assert "temperature" not in validated, f"{model} should drop temperature"
+ assert "max_tokens" not in validated, f"{model} should drop max_tokens"
+ assert validated["extra_body"] == {
+ "reasoning_effort": "medium",
+ "max_completion_tokens": 4096,
+ }, f"{model} should route reasoning params via extra_body"
+
+
+def test_openai_compatible_validate_preserves_non_reasoning_models() -> None:
+ # Non-reasoning OpenAI models (gpt-4o, gpt-4o-mini, gpt-3.5-turbo) and
+ # arbitrary gateway aliases must keep `temperature` / `max_tokens` so the
+ # existing vLLM / LM Studio / generic gateway path is unchanged.
+ for model in ["gpt-4o", "gpt-4o-mini", "gpt-3.5-turbo", "gateway-model"]:
+ validated = OpenAICompatibleLLMParameters.validate(
+ {
+ "api_base": "https://gateway.example.com/v1",
+ "model": model,
+ "max_tokens": 1024,
+ }
+ )
+
+ assert (
+ validated["temperature"] == _DEFAULT_TEMPERATURE
+ ), f"{model} should keep temperature"
+ assert validated["max_tokens"] == 1024, f"{model} should keep max_tokens"
+ assert "extra_body" not in validated, f"{model} should not set extra_body"
+
+
+def test_openai_compatible_validate_routes_reasoning_via_extra_body() -> None:
+ # GPT-5 / o-series via custom_openai: LiteLLM does NOT auto-translate
+ # `max_tokens` to `max_completion_tokens` or drop `temperature`, so the
+ # adapter must do both — and route reasoning_effort / max_completion_tokens
+ # through `extra_body` (the only field LiteLLM's custom_openai forwards
+ # to the upstream API without rewriting).
+ validated = OpenAICompatibleLLMParameters.validate(
+ {
+ "api_base": "https://api.openai.com/v1",
+ "api_key": "sk-test",
+ "model": "gpt-5",
+ "max_tokens": 4096,
+ "enable_reasoning": True,
+ "reasoning_effort": "high",
+ }
+ )
+
+ assert validated["model"] == "custom_openai/gpt-5"
+ assert "temperature" not in validated
+ assert "max_tokens" not in validated
+ assert "reasoning_effort" not in validated
+ assert "enable_reasoning" not in validated
+ assert validated["extra_body"] == {
+ "reasoning_effort": "high",
+ "max_completion_tokens": 4096,
+ }
+
+
+def test_reasoning_omits_max_completion_tokens_when_unset() -> None:
+ validated = OpenAICompatibleLLMParameters.validate(
+ {
+ "api_base": "https://api.openai.com/v1",
+ "model": "gpt-5",
+ "enable_reasoning": True,
+ }
+ )
+
+ assert validated["extra_body"] == {"reasoning_effort": "medium"}
+ assert "max_tokens" not in validated
+ assert "temperature" not in validated
+
+
+def test_openai_compatible_validate_infers_reasoning_from_effort_field() -> None:
+ # When the adapter is re-validated (e.g. on second call), `enable_reasoning`
+ # may already have been consumed but `reasoning_effort` should still trigger
+ # the reasoning code path so the model keeps working. Use a model name that
+ # is NOT auto-detected as a reasoning family — otherwise the test passes via
+ # `_is_openai_reasoning_model` without ever exercising the inference branch.
+ validated = OpenAICompatibleLLMParameters.validate(
+ {
+ "api_base": "https://gateway.example.com/v1",
+ "model": "custom-gateway-model",
+ "max_tokens": 2048,
+ "reasoning_effort": "low",
+ }
+ )
+
+ assert "temperature" not in validated
+ assert "max_tokens" not in validated
+ assert validated["extra_body"] == {
+ "reasoning_effort": "low",
+ "max_completion_tokens": 2048,
+ }
+
+
+def test_reasoning_state_survives_revalidation_for_custom_alias() -> None:
+ # Regression: validate() strips `enable_reasoning` / `reasoning_effort`
+ # from the top level on the reasoning path and routes them into
+ # `extra_body`. Feeding that output back into validate() for a
+ # non-auto-detected alias (where `_is_openai_reasoning_model` cannot
+ # rescue) must still preserve the reasoning state — otherwise the
+ # second pass would emit `temperature` / `max_tokens` and the upstream
+ # API would reject the request.
+ first = OpenAICompatibleLLMParameters.validate(
+ {
+ "api_base": "https://gateway.example.com/v1",
+ "model": "my-gateway-alias",
+ "max_tokens": 4096,
+ "enable_reasoning": True,
+ "reasoning_effort": "high",
+ }
+ )
+ second = OpenAICompatibleLLMParameters.validate(dict(first))
+
+ assert "temperature" not in second
+ assert "max_tokens" not in second
+ assert second["extra_body"] == {
+ "reasoning_effort": "high",
+ "max_completion_tokens": 4096,
+ }
+
+
+def test_explicit_disable_overrides_leftover_reasoning_effort() -> None:
+ # Regression: when a user explicitly submits `enable_reasoning: false`
+ # while a leftover `reasoning_effort` is still in the stored metadata
+ # (e.g. the form was previously saved with reasoning on), the inference
+ # branch must NOT silently re-enable reasoning. Use a non-auto-detected
+ # model so we isolate the inference branch from the auto-detect branch.
+ validated = OpenAICompatibleLLMParameters.validate(
+ {
+ "api_base": "https://gateway.example.com/v1",
+ "model": "custom-gateway-model",
+ "max_tokens": 1024,
+ "enable_reasoning": False,
+ "reasoning_effort": "high",
+ }
+ )
+
+ assert "extra_body" not in validated
+ assert validated["max_tokens"] == 1024
+ assert "temperature" in validated
+
+
+def test_openai_compatible_validate_no_reasoning_unchanged() -> None:
+ validated = OpenAICompatibleLLMParameters.validate(
+ {
+ "api_base": "https://gateway.example.com/v1",
+ "api_key": "test-key",
+ "model": "gateway-model",
+ "max_tokens": 1024,
+ }
+ )
+
+ # Non-reasoning path must preserve temperature/max_tokens for ordinary
+ # OpenAI-compatible gateways (vLLM, LM Studio, etc.).
+ assert validated["temperature"] == _DEFAULT_TEMPERATURE
+ assert validated["max_tokens"] == 1024
+ assert "extra_body" not in validated
+ assert "reasoning_effort" not in validated
+
+
def test_openai_compatible_adapter_uses_distinct_description_and_icon() -> None:
metadata = OpenAICompatibleLLMAdapter.get_metadata()