Skip to content

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

[FIX] Strip deprecated sampling params for Claude Opus 4.7 (#1934)

Praveen Kumar2224a3dd3bce
diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/base1.py b/unstract/sdk1/src/unstract/sdk1/adapters/base1.py
index 1ec66f6b8..22a1e2522 100644
--- a/unstract/sdk1/src/unstract/sdk1/adapters/base1.py
+++ b/unstract/sdk1/src/unstract/sdk1/adapters/base1.py
@@ -2,6 +2,7 @@ import glob
import inspect
import logging
import os
+import re
from abc import ABC, abstractmethod
from importlib import import_module
from typing import TYPE_CHECKING
@@ -15,6 +16,126 @@ from unstract.sdk1.adapters.enums import AdapterTypes
logger = logging.getLogger(__name__)
+# Anthropic models that have deprecated sampling parameters (`temperature`,
+# `top_p`, `top_k`). The patterns are regex-searched against the model id
+# after lowercasing and normalizing `.` / `_` to `-`. The match is anchored at
+# the trailing edge so that unrelated future ids (`claude-opus-4-70`,
+# `claude-opus-4-75`, `claude-opus-4-7verbose`) do not match. A single entry
+# covers every encoding of the id we have observed:
+# - Native Anthropic `claude-opus-4-7`, `anthropic/claude-opus-4-7`
+# - Bedrock foundation model `anthropic.claude-opus-4-7-<date>-v1:0`
+# - Bedrock cross-region profile `us.anthropic.claude-opus-4-7-...`,
+# `eu.`, `apac.`, `global.` variants
+# - Bedrock foundation-model ARN `arn:aws:bedrock:<region>::foundation-model/
+# anthropic.claude-opus-4-7-...`
+# - Bedrock inference-profile ARN `arn:aws:bedrock:<region>:<account>:
+# inference-profile/us.anthropic.claude-opus-4-7-...`
+# - Vertex AI `vertex_ai/claude-opus-4-7@<date>`
+# - Azure AI Foundry deployments whose name embeds `claude-opus-4-7`
+# Leading text (route prefixes like `converse/`, `invoke/`, `bedrock/`) passes
+# through because the regex is anchored only at the trailing edge.
+# Add new entries here when Anthropic deprecates sampling on more models.
+# Trailing anchor allows: end-of-string, or one of `-`/`:`/`@`/`/` (the
+# delimiters used in date suffixes, ARN paths, Vertex `@<date>`, and the
+# `v1:0` tag), or `v` followed by a digit (the version-tag start). A bare
+# `v` is intentionally rejected so alpha continuations like `4-7verbose` do
+# not silently match.
+# See https://docs.claude.com/en/about-claude/models/whats-new-claude-4-7
+_SAMPLING_DEPRECATED_MODEL_PATTERNS: tuple[re.Pattern[str], ...] = (
+ re.compile(r"claude-opus-4-7(?=$|[-:@/]|v\d)"),
+)
+_DEPRECATED_SAMPLING_PARAMS: tuple[str, ...] = ("temperature", "top_p", "top_k")
+# Fields whose value can carry a model id. `model` is universal; `model_id` is
+# Bedrock's separate ARN field used for Application Inference Profile cost
+# tracking — when callers route through an AIP, the standard model id often
+# only appears here, not in `model`.
+_MODEL_ID_FIELDS: tuple[str, ...] = ("model", "model_id")
+# Substring of a Bedrock Application Inference Profile ARN; the rest of the
+# ARN is an opaque profile id so the underlying foundation model id is not
+# recoverable from the string. Used only to narrow the debug-breadcrumb path
+# on the strip's no-match branch.
+_OPAQUE_AIP_ARN_MARKER: str = "application-inference-profile"
+
+
+def _looks_like_opaque_aip_arn(value: str | None) -> bool:
+ """Return True when the value looks like a Bedrock AIP ARN.
+
+ Bedrock AIP ARNs do not carry the underlying foundation-model id in the
+ string, so the sampling-strip detector cannot decide whether the call is
+ bound for Claude Opus 4.7.
+ """
+ return bool(value) and _OPAQUE_AIP_ARN_MARKER in value
+
+
+def _has_deprecated_sampling_params(model: str | None) -> bool:
+ """Return True when the model rejects sampling parameters.
+
+ Anthropic deprecated `temperature`, `top_p`, and `top_k` starting with
+ Claude Opus 4.7; sending any of them yields a 400 from Anthropic and from
+ the providers that proxy it (Bedrock, Azure AI Foundry, Vertex AI).
+
+ The check normalizes case and `.`/`_` separators to `-`, then regex-
+ searches against the patterns with a trailing-edge boundary, so
+ `claude-opus-4-70` and `claude-opus-4-7verbose` do not match. This
+ catches every format that embeds the model id (foundation model ids,
+ cross-region profiles, foundation-model ARNs, inference-profile ARNs,
+ Vertex `@`-suffixed ids).
+
+ It does NOT catch:
+ - Bedrock Application Inference Profile ARNs (e.g.
+ `arn:aws:bedrock:...:application-inference-profile/abcd1234`), whose
+ tail is an opaque profile id — the underlying model is not recoverable
+ from the string. Pass the AIP ARN in `model_id` and keep the standard
+ model id in `model`, or the strip won't fire.
+ - Azure AI Foundry deployment names that omit the model id; rename the
+ deployment to include `claude-opus-4-7` so detection works.
+ """
+ if not model:
+ return False
+ normalized = model.lower().replace(".", "-").replace("_", "-")
+ return any(rx.search(normalized) for rx in _SAMPLING_DEPRECATED_MODEL_PATTERNS)
+
+
+def _strip_deprecated_sampling_params(validated: dict[str, "Any"]) -> dict[str, "Any"]:
+ """Return a copy of `validated` with deprecated sampling params removed.
+
+ The input dict is not mutated. Returns a shallow copy so callers can rely
+ on `before is not after` and follow the file's copy-then-mutate style.
+
+ `temperature` is the load-bearing case: `BaseChatCompletionParameters`
+ declares `temperature: float | None = Field(default=0.1)`, so Pydantic's
+ `model_dump()` re-emits the default even when the caller never set one.
+ `top_p` and `top_k` are not declared fields and are normally dropped by
+ Pydantic, but the strip defends against caller-supplied values flowing
+ through `**adapter_metadata`.
+
+ Checks both `model` and `model_id` so Bedrock callers routing through an
+ Application Inference Profile are covered when the standard model id only
+ appears in `model_id`.
+
+ Contract change: the returned dict may not contain a `temperature` key.
+ Consumers must read via `.get("temperature")`, not `dict["temperature"]`.
+ """
+ result = dict(validated)
+ if any(_has_deprecated_sampling_params(result.get(f)) for f in _MODEL_ID_FIELDS):
+ for param in _DEPRECATED_SAMPLING_PARAMS:
+ result.pop(param, None)
+ elif any(_looks_like_opaque_aip_arn(result.get(f)) for f in _MODEL_ID_FIELDS):
+ # An opaque Bedrock AIP ARN reached us with no Anthropic model id in
+ # any field. If the underlying foundation model is Opus 4.7+, the
+ # upstream call will 400 on `temperature is deprecated`; this debug
+ # log makes the strip-skipped state distinguishable from a
+ # never-attempted strip when debugging the resulting 400. The guard
+ # is intentionally narrow — the broader "any sampling param present"
+ # form fires for every routine call because Pydantic's `model_dump`
+ # always re-emits the default `temperature=0.1`.
+ logger.debug(
+ "Sampling-param strip skipped for opaque Bedrock AIP ARN; no "
+ "model id field matched a deprecation pattern. Model ids: %s",
+ {f: result.get(f) for f in _MODEL_ID_FIELDS if result.get(f)},
+ )
+ return result
+
def register_adapters(adapters: dict[str, dict[str, "Any"]], adapter_type: str) -> None:
"""Register all SDK v1 adapters of given type.
@@ -462,7 +583,7 @@ class VertexAILLMParameters(BaseChatCompletionParameters):
if "thinking" in result_metadata:
validated_data["thinking"] = result_metadata["thinking"]
- return validated_data
+ return _strip_deprecated_sampling_params(validated_data)
@staticmethod
def validate_model(adapter_metadata: dict[str, "Any"]) -> str:
@@ -646,7 +767,8 @@ class AWSBedrockLLMParameters(BaseChatCompletionParameters):
# Keys mode requires non-blank values, legacy (no auth_type) is
# lenient. Reads auth_type from result_metadata since validation_
# metadata strips it before Pydantic.
- return _resolve_bedrock_aws_credentials(result_metadata, validated)
+ validated = _resolve_bedrock_aws_credentials(result_metadata, validated)
+ return _strip_deprecated_sampling_params(validated)
@staticmethod
def validate_model(adapter_metadata: dict[str, "Any"]) -> str:
@@ -735,7 +857,7 @@ class AnthropicLLMParameters(BaseChatCompletionParameters):
if enable_extended_context:
validated["extra_headers"] = {"anthropic-beta": "context-1m-2025-08-07"}
- return validated
+ return _strip_deprecated_sampling_params(validated)
@staticmethod
def validate_model(adapter_metadata: dict[str, "Any"]) -> str:
@@ -945,7 +1067,8 @@ class AzureAIFoundryLLMParameters(BaseChatCompletionParameters):
adapter_metadata
)
- return AzureAIFoundryLLMParameters(**adapter_metadata).model_dump()
+ validated = AzureAIFoundryLLMParameters(**adapter_metadata).model_dump()
+ return _strip_deprecated_sampling_params(validated)
@staticmethod
def validate_model(adapter_metadata: dict[str, "Any"]) -> str:
diff --git a/unstract/sdk1/tests/test_sampling_strip.py b/unstract/sdk1/tests/test_sampling_strip.py
new file mode 100644
index 000000000..3e3ce8b40
--- /dev/null
+++ b/unstract/sdk1/tests/test_sampling_strip.py
@@ -0,0 +1,300 @@
+"""Tests for Claude Opus 4.7 sampling-parameter strip.
+
+Pins the detection regex and the four-adapter wiring against the failure
+modes that surfaced in PR #1934 review:
+- prefix collisions (`claude-opus-4-70`, `-75`, `4-7verbose`)
+- Bedrock Application Inference Profile ARN fallback via `model_id`
+- mutate-and-return regression (input dict must be preserved)
+- silent skip with sampling params present must emit a debug breadcrumb
+- every adapter calls the strip on its return path
+"""
+
+import logging
+from typing import Any
+
+import pytest
+from unstract.sdk1.adapters.base1 import (
+ _DEPRECATED_SAMPLING_PARAMS,
+ AnthropicLLMParameters,
+ AWSBedrockLLMParameters,
+ AzureAIFoundryLLMParameters,
+ VertexAILLMParameters,
+ _has_deprecated_sampling_params,
+ _strip_deprecated_sampling_params,
+)
+
+# ── detection: positives ────────────────────────────────────────────────────
+
+OPUS_47_POSITIVES: list[str] = [
+ # Native Anthropic
+ "claude-opus-4-7",
+ "anthropic/claude-opus-4-7",
+ "Claude-Opus-4-7", # case
+ # Bedrock foundation model id with date stamp
+ "anthropic.claude-opus-4-7-20260101-v1:0",
+ "bedrock/anthropic.claude-opus-4-7-20260101-v1:0",
+ # Bedrock route prefixes pass through the trailing-edge anchor
+ "bedrock/converse/anthropic.claude-opus-4-7-20260101-v1:0",
+ "bedrock/invoke/anthropic.claude-opus-4-7-20260101-v1:0",
+ # Bedrock cross-region inference profiles
+ "us.anthropic.claude-opus-4-7-20260101-v1:0",
+ "bedrock/us.anthropic.claude-opus-4-7-20260101-v1:0",
+ "bedrock/eu.anthropic.claude-opus-4-7-20260101-v1:0",
+ "bedrock/apac.anthropic.claude-opus-4-7-20260101-v1:0",
+ "bedrock/global.anthropic.claude-opus-4-7-20260101-v1:0",
+ # Bedrock foundation-model ARN
+ "arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-opus-4-7-20260101-v1:0",
+ # Bedrock inference-profile ARN (cross-region)
+ "arn:aws:bedrock:us-east-1:000000000000:inference-profile/us.anthropic.claude-opus-4-7-20260101-v1:0",
+ # Vertex AI
+ "vertex_ai/claude-opus-4-7@20260101",
+ "vertex_ai/claude-opus-4-7",
+ # Azure AI Foundry deployments embedding the model id
+ "azure_ai/claude-opus-4-7",
+ "azure_ai/claude-opus-4-7-prod",
+ "azure_ai/my-claude-opus-4-7-deployment",
+ # Separator variants — Anthropic uses dashes, but the normalize step
+ # collapses `.` and `_` so dot/underscore forms still match
+ "claude.opus.4.7",
+ "claude_opus_4_7",
+ # Version tag accepted only as `v\d` after the trailing edge
+ "claude-opus-4-7v1",
+ "claude-opus-4-7v9",
+]
+
+
[email protected]("model", OPUS_47_POSITIVES)
+def test_has_deprecated_sampling_params_positive(model: str) -> None:
+ assert _has_deprecated_sampling_params(model)
+
+
+# ── detection: negatives ────────────────────────────────────────────────────
+
+NEGATIVES: list[str | None] = [
+ # Adjacent Claude model families that retain temperature
+ "claude-opus-4-6",
+ "claude-opus-4-5",
+ "claude-sonnet-4-7",
+ "claude-haiku-4-5",
+ "anthropic.claude-3-5-sonnet-20241022-v2:0",
+ # Non-Anthropic providers
+ "gpt-4o",
+ "gemini-2.0-flash",
+ "mistral-large-latest",
+ # Prefix collisions — lock the trailing-edge anchor against future
+ # versions whose id starts with `claude-opus-4-7` but is unrelated.
+ "claude-opus-4-70",
+ "claude-opus-4-75",
+ "claude-opus-4-79",
+ "anthropic/claude-opus-4-70",
+ "bedrock/anthropic.claude-opus-4-71-20260101-v1:0",
+ # Bare-`v` alpha continuations must NOT match (HIGH line 41 fix).
+ "claude-opus-4-7verbose",
+ "claude-opus-4-7vnext",
+ "claude-opus-4-7variant",
+ # Opaque Bedrock Application Inference Profile ARN — model id is not
+ # recoverable from the string. Strip-detection is expected to skip;
+ # callers must keep the standard id in `model` or `model_id`.
+ "arn:aws:bedrock:us-east-1:000000000000:application-inference-profile/abcd1234efgh",
+ # Empty / missing
+ None,
+ "",
+]
+
+
[email protected]("model", NEGATIVES)
+def test_has_deprecated_sampling_params_negative(model: str | None) -> None:
+ assert not _has_deprecated_sampling_params(model)
+
+
+# ── strip contract ──────────────────────────────────────────────────────────
+
+
+def test_strip_returns_copy_without_mutating_input() -> None:
+ inp: dict[str, Any] = {"model": "claude-opus-4-7", "temperature": 0.5}
+ out = _strip_deprecated_sampling_params(inp)
+ assert out is not inp
+ assert inp == {"model": "claude-opus-4-7", "temperature": 0.5}
+ assert "temperature" not in out
+
+
+def test_strip_removes_all_three_sampling_params() -> None:
+ inp = {
+ "model": "claude-opus-4-7",
+ "temperature": 0.5,
+ "top_p": 0.9,
+ "top_k": 40,
+ }
+ out = _strip_deprecated_sampling_params(inp)
+ for param in _DEPRECATED_SAMPLING_PARAMS:
+ assert param not in out, f"{param} should be stripped"
+
+
+def test_strip_via_model_id_field_when_model_is_opaque_aip_arn() -> None:
+ """Bedrock AIP fallback: opaque ARN in `model`, real id in `model_id`."""
+ inp = {
+ "model": "bedrock/arn:aws:bedrock:us-east-1:0:application-inference-profile/abcd",
+ "model_id": "anthropic.claude-opus-4-7-20260101-v1:0",
+ "temperature": 0.5,
+ }
+ out = _strip_deprecated_sampling_params(inp)
+ assert "temperature" not in out
+
+
+def test_strip_via_model_field_when_model_id_is_opaque_aip_arn() -> None:
+ """Bedrock AIP fallback: standard id in `model`, opaque ARN in `model_id`."""
+ inp = {
+ "model": "bedrock/anthropic.claude-opus-4-7-20260101-v1:0",
+ "model_id": "arn:aws:bedrock:us-east-1:0:application-inference-profile/abcd",
+ "temperature": 0.5,
+ }
+ out = _strip_deprecated_sampling_params(inp)
+ assert "temperature" not in out
+
+
+def test_strip_skipped_when_both_fields_opaque_and_logs_debug(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """Documented limitation: opaque-only state must emit a breadcrumb.
+
+ With no model id in any field, the strip is a no-op; the debug log makes
+ the upstream 400 traceable.
+ """
+ inp = {
+ "model": "bedrock/arn:aws:bedrock:us-east-1:0:application-inference-profile/abcd",
+ "model_id": "arn:aws:bedrock:us-east-1:0:application-inference-profile/efgh",
+ "temperature": 0.5,
+ }
+ with caplog.at_level(logging.DEBUG, logger="unstract.sdk1.adapters.base1"):
+ out = _strip_deprecated_sampling_params(inp)
+ # Documented limitation: not stripped when no field carries the model id.
+ assert out["temperature"] == pytest.approx(0.5)
+ assert any(
+ "Sampling-param strip skipped" in rec.message for rec in caplog.records
+ ), "expected debug breadcrumb when strip is a no-op"
+
+
+def test_strip_does_not_log_when_no_sampling_params_present(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """The breadcrumb stays quiet on the common no-op path.
+
+ No model id field looks opaque, so the strip-skipped state is not worth
+ a debug breadcrumb.
+ """
+ inp = {"model": "gpt-4o"}
+ with caplog.at_level(logging.DEBUG, logger="unstract.sdk1.adapters.base1"):
+ _strip_deprecated_sampling_params(inp)
+ assert not any(
+ "Sampling-param strip skipped" in rec.message for rec in caplog.records
+ )
+
+
+def test_strip_does_not_log_when_sampling_params_present_but_model_not_opaque(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """Non-deprecated models with default `temperature` must not emit noise.
+
+ `BaseChatCompletionParameters` declares `temperature: float | None =
+ Field(default=0.1)`, so every adapter's `validate()` returns a dict that
+ carries `temperature`. If the breadcrumb keyed off "any sampling param
+ present" it would fire for every routine call to `claude-3-5-sonnet`,
+ `claude-opus-4-6`, `gpt-4o`, etc. — pure log noise. The guard must
+ instead key off an opaque-looking model id field.
+ """
+ inp = {"model": "claude-3-5-sonnet-20241022", "temperature": 0.1}
+ with caplog.at_level(logging.DEBUG, logger="unstract.sdk1.adapters.base1"):
+ _strip_deprecated_sampling_params(inp)
+ assert not any(
+ "Sampling-param strip skipped" in rec.message for rec in caplog.records
+ )
+
+
+def test_strip_retains_temperature_for_non_deprecated_models() -> None:
+ inp = {"model": "claude-3-5-sonnet-20241022", "temperature": 0.5}
+ out = _strip_deprecated_sampling_params(inp)
+ assert out["temperature"] == pytest.approx(0.5)
+
+
+# ── adapter wiring (regression guard for the Vertex AI gap) ─────────────────
+
+
+def _vertex_metadata(model: str, temperature: float = 0.5) -> dict[str, Any]:
+ return {
+ "model": model,
+ "vertex_credentials": "{}",
+ "vertex_project": "p",
+ "safety_settings": {},
+ "temperature": temperature,
+ }
+
+
+ADAPTER_CASES: list[tuple[str, type, dict[str, Any]]] = [
+ (
+ "anthropic",
+ AnthropicLLMParameters,
+ {"api_key": "k"},
+ ),
+ (
+ "bedrock",
+ AWSBedrockLLMParameters,
+ {"aws_region_name": "us-east-1"},
+ ),
+ (
+ "azure_ai_foundry",
+ AzureAIFoundryLLMParameters,
+ {"api_key": "k", "api_base": "https://x.inference.ai.azure.com"},
+ ),
+]
+
+
+ "name,cls,extra",
+ ADAPTER_CASES,
+ ids=lambda v: v if isinstance(v, str) else "",
+)
+def test_validate_strips_temperature_for_opus_4_7(
+ name: str, cls: type, extra: dict[str, Any]
+) -> None:
+ """Every adapter that proxies Anthropic must drop temperature on return.
+
+ The Vertex AI gap (commit 5a4ea27f shipped without it, fixed in 7fb66f15)
+ is exactly the regression this locks in.
+ """
+ model = {
+ "anthropic": "claude-opus-4-7",
+ "bedrock": "anthropic.claude-opus-4-7-20260101-v1:0",
+ "azure_ai_foundry": "claude-opus-4-7",
+ }[name]
+ result = cls.validate({"model": model, "temperature": 0.5, **extra})
+ for param in _DEPRECATED_SAMPLING_PARAMS:
+ assert param not in result, f"{name}: {param} should be stripped"
+
+
+def test_vertex_validate_strips_temperature_for_opus_4_7() -> None:
+ result = VertexAILLMParameters.validate(_vertex_metadata("claude-opus-4-7@20260101"))
+ for param in _DEPRECATED_SAMPLING_PARAMS:
+ assert param not in result, f"vertex: {param} should be stripped"
+
+
+ "name,cls,extra",
+ ADAPTER_CASES,
+ ids=lambda v: v if isinstance(v, str) else "",
+)
+def test_validate_retains_temperature_for_opus_4_6(
+ name: str, cls: type, extra: dict[str, Any]
+) -> None:
+ """Non-deprecated Claude models must keep temperature intact."""
+ model = {
+ "anthropic": "claude-opus-4-6",
+ "bedrock": "anthropic.claude-opus-4-6-20251022-v1:0",
+ "azure_ai_foundry": "claude-opus-4-6",
+ }[name]
+ result = cls.validate({"model": model, "temperature": 0.5, **extra})
+ assert result["temperature"] == pytest.approx(0.5)
+
+
+def test_vertex_validate_retains_temperature_for_gemini() -> None:
+ result = VertexAILLMParameters.validate(_vertex_metadata("gemini-2.0-flash"))
+ assert result["temperature"] == pytest.approx(0.5)