Skip to content

The agent that grows with you

fix(bedrock): application inference profile ARNs size from the wrapped model on the real path

teknium111445cc54e9b
diff --git a/agent/bedrock_adapter.py b/agent/bedrock_adapter.py
index ae76640bd82..279e74dac9d 100644
--- a/agent/bedrock_adapter.py
+++ b/agent/bedrock_adapter.py
@@ -127,6 +127,7 @@ def reset_client_cache():
_bedrock_runtime_client_cache.clear()
_bedrock_control_client_cache.clear()
_bedrock_clients_by_home.clear()
+ _inference_profile_model_cache.clear()
def invalidate_runtime_client(region: str) -> bool:
@@ -1124,9 +1125,9 @@ def probe_bedrock_context_length(model_id: str, region: str) -> Optional[int]:
def get_bedrock_context_length(model_id: str, region: str = "", probe: bool = True) -> int:
"""Context window: live probe (if ``probe`` and ``region``) → static table → default. The table is fallback
only: a stale substring match silently caps the window (a 1M Opus pinned to 200K via "opus-4").
- An inference-profile ARN is first resolved to the wrapped foundation model (#114476)."""
- profile_arn = model_id if _INFERENCE_PROFILE_ARN_RE.search(model_id) else ""
- if profile_arn and region:
+ An application-inference-profile ARN is first resolved to the model it wraps (#114476)."""
+ profile_arn = model_id if _APPLICATION_PROFILE_ARN_RE.search(model_id) else ""
+ if profile_arn:
model_id = _resolve_inference_profile_model_id(profile_arn, region)
if probe and region and (probed := probe_bedrock_context_length(model_id, region)):
return probed
@@ -1144,38 +1145,34 @@ def get_bedrock_context_length(model_id: str, region: str = "", probe: bool = Tr
return BEDROCK_DEFAULT_CONTEXT_LENGTH
-# An application-inference-profile ARN names no model, so the probe error text and the static
-# substring table both miss and the 128k default silently applies (#114476). An application
-# profile's id IS its ARN, so GetInferenceProfile(inferenceProfileId=<ARN>) works on both the
-# original API shape and the later arn-parameterised one.
-_INFERENCE_PROFILE_ARN_RE = re.compile(r":(?:application-)?inference-profile/")
-_FOUNDATION_MODEL_ARN_RE = re.compile(r"foundation-model/(.+)$")
+# An application-inference-profile ARN (cost-allocation wrapper) carries an opaque id, so the probe
+# error text and the static substring table both miss and the 128k default silently applies
+# (#114476). System-defined `inference-profile/us.anthropic...` ARNs embed the model id and need no
+# lookup. The ARN's own region (field 4) is authoritative for the control-plane call: the runtime
+# region / base_url may differ, and an empty region must not skip the lookup because the
+# production caller (agent/model_metadata.py::_resolve_bedrock_context_length) passes none.
+_APPLICATION_PROFILE_ARN_RE = re.compile(r":application-inference-profile/")
+_ARN_REGION_RE = re.compile(r"^arn:[^:]+:bedrock:([a-z0-9-]+):", re.IGNORECASE)
_inference_profile_model_cache: Dict[str, str] = {}
-def _resolve_inference_profile_model_id(profile_arn: str, region: str, _depth: int = 0) -> str:
- """Inference-profile ARN → the wrapped foundation-model id (a profile may wrap another profile);
- the ARN itself when resolution is unavailable or ``bedrock:GetInferenceProfile`` is not granted,
- so callers fall back to the existing default-window behaviour."""
- cache_key = f"{profile_arn}@{region}"
- if cache_key in _inference_profile_model_cache:
- return _inference_profile_model_cache[cache_key]
+def _resolve_inference_profile_model_id(profile_arn: str, region: str = "") -> str:
+ """Application-profile ARN → the wrapped model's ARN (its ``foundation-model/<id>`` tail satisfies the
+ static-table substring match); the profile ARN itself when ``bedrock:GetInferenceProfile`` is not
+ granted or unavailable, so callers keep the default-window behaviour. Both outcomes are cached per
+ process: this runs on every context-length resolution, not once per model."""
+ if profile_arn in _inference_profile_model_cache:
+ return _inference_profile_model_cache[profile_arn]
+ arn_region = _ARN_REGION_RE.match(profile_arn)
+ region = (arn_region.group(1) if arn_region else "") or region or resolve_bedrock_region()
resolved = profile_arn
try:
client = _get_bedrock_control_client(region)
- profile = client.get_inference_profile(inferenceProfileId=profile_arn)
- for wrapped in profile.get("models", []):
- model_arn = (wrapped.get("modelArn") or "").strip()
- if match := _FOUNDATION_MODEL_ARN_RE.search(model_arn):
- resolved = match.group(1)
- break
- if _INFERENCE_PROFILE_ARN_RE.search(model_arn) and _depth < 2:
- resolved = _resolve_inference_profile_model_id(model_arn, region, _depth + 1)
- break
+ models = client.get_inference_profile(inferenceProfileIdentifier=profile_arn).get("models") or []
+ resolved = next((m["modelArn"] for m in models if m.get("modelArn")), profile_arn)
except Exception as exc: # no boto3 / credentials / GetInferenceProfile not granted
logger.debug("Inference profile resolution skipped for %s: %s", profile_arn, exc)
- return profile_arn
- _inference_profile_model_cache[cache_key] = resolved
+ _inference_profile_model_cache[profile_arn] = resolved
return resolved
diff --git a/tests/agent/test_bedrock_adapter.py b/tests/agent/test_bedrock_adapter.py
index c1e83fbc9e3..51c817d48f5 100644
--- a/tests/agent/test_bedrock_adapter.py
+++ b/tests/agent/test_bedrock_adapter.py
@@ -1068,8 +1068,8 @@ class TestBedrockContextLength:
class TestInferenceProfileContextLength:
- """Test context-window sizing for application-inference-profile ARNs (#114476): the ARN itself
- names no model, so the window must come from the wrapped foundation model."""
+ """Application-inference-profile ARNs name no model, so the window must come from the model the
+ profile wraps via GetInferenceProfile — on the production call shape (no region, probe=False)."""
ARN = "arn:aws:bedrock:us-west-2:123456789012:application-inference-profile/abcdef123456"
@@ -1077,61 +1077,36 @@ class TestInferenceProfileContextLength:
from agent import bedrock_adapter
bedrock_adapter._inference_profile_model_cache.clear()
- def _control_client(self, profile_response):
- client = MagicMock()
- client.get_inference_profile.return_value = profile_response
- return client
-
- def test_arn_resolves_wrapped_model_window(self):
- # Sonnet 4.6 (1M) wrapped by the profile: the static table must match on the
- # foundation-model id recovered from GetInferenceProfile, not on the ARN.
+ def test_arn_resolves_wrapped_model_window_in_the_arn_region(self):
+ # No region passed (agent/model_metadata.py::_resolve_bedrock_context_length passes none) and
+ # AWS_REGION elsewhere: the lookup must still run, in the ARN's own region, with the
+ # parameter name botocore actually validates (inferenceProfileIdentifier).
from agent.bedrock_adapter import get_bedrock_context_length
- response = {"models": [
- {"modelArn": "arn:aws:bedrock:::foundation-model/anthropic.claude-sonnet-4-6-v1:0"}]}
- with patch("agent.bedrock_adapter._get_bedrock_control_client",
- return_value=self._control_client(response)):
- assert get_bedrock_context_length(self.ARN, region="us-west-2", probe=False) == 1_000_000
-
- def test_nested_profile_resolves_to_foundation_model(self):
- # A profile wrapping another profile ARN must recurse to the foundation model.
- from agent.bedrock_adapter import get_bedrock_context_length
- inner_arn = "arn:aws:bedrock:us-west-2:123456789012:inference-profile/us.anthropic.claude-sonnet-4-6-v1:0"
- responses = [
- {"models": [{"modelArn": inner_arn}]},
- {"models": [{"modelArn": "arn:aws:bedrock:::foundation-model/anthropic.claude-sonnet-4-6-v1:0"}]},
- ]
- with patch("agent.bedrock_adapter._get_bedrock_control_client",
- side_effect=[self._control_client(r) for r in responses]):
- assert get_bedrock_context_length(self.ARN, region="us-west-2", probe=False) == 1_000_000
-
- def test_resolution_denied_falls_back_to_default_with_warning(self):
- # Without bedrock:GetInferenceProfile the call raises; the default window applies and the
- # silence is broken with a WARNING naming the profile and the explicit-config escape hatch.
+ client = MagicMock()
+ client.get_inference_profile.return_value = {"models": [
+ {"modelArn": "arn:aws:bedrock:us-west-2::foundation-model/anthropic.claude-sonnet-4-6"}]}
+ with patch("agent.bedrock_adapter._get_bedrock_control_client", return_value=client) as factory, \
+ patch.dict("os.environ", {"AWS_REGION": "us-east-1"}):
+ assert get_bedrock_context_length(self.ARN, probe=False) == 1_000_000
+ assert get_bedrock_context_length(self.ARN, probe=False) == 1_000_000 # cached per process
+ factory.assert_called_once_with("us-west-2")
+ client.get_inference_profile.assert_called_once_with(inferenceProfileIdentifier=self.ARN)
+
+ def test_resolution_denied_falls_back_to_default_with_warning(self, caplog):
+ # Without bedrock:GetInferenceProfile the default window applies and the silence is broken
+ # with a WARNING naming the profile and the explicit-config escape hatch.
from agent.bedrock_adapter import get_bedrock_context_length, BEDROCK_DEFAULT_CONTEXT_LENGTH
client = MagicMock()
client.get_inference_profile.side_effect = Exception("AccessDeniedException")
with patch("agent.bedrock_adapter._get_bedrock_control_client", return_value=client), \
- patch("agent.bedrock_adapter.logger") as mock_logger:
- assert get_bedrock_context_length(
- self.ARN, region="us-west-2", probe=False) == BEDROCK_DEFAULT_CONTEXT_LENGTH
- assert mock_logger.warning.called
+ caplog.at_level("WARNING", logger="agent.bedrock_adapter"):
+ assert get_bedrock_context_length(self.ARN, probe=False) == BEDROCK_DEFAULT_CONTEXT_LENGTH
+ warnings = [r for r in caplog.records if r.levelname == "WARNING"]
+ assert len(warnings) == 1 and self.ARN in warnings[0].getMessage()
+ assert "GetInferenceProfile" in warnings[0].getMessage()
- def test_resolved_arn_is_cached_per_process(self):
- from agent.bedrock_adapter import get_bedrock_context_length
- response = {"models": [
- {"modelArn": "arn:aws:bedrock:::foundation-model/anthropic.claude-sonnet-4-6-v1:0"}]}
- with patch("agent.bedrock_adapter._get_bedrock_control_client",
- return_value=self._control_client(response)) as mock_client_factory:
- assert get_bedrock_context_length(self.ARN, region="us-west-2", probe=False) == 1_000_000
- assert get_bedrock_context_length(self.ARN, region="us-west-2", probe=False) == 1_000_000
- assert mock_client_factory.call_count == 1
-
- def test_no_region_skips_profile_resolution(self):
- # The no-region path must stay offline like the probe does (display/offline callers).
- from agent.bedrock_adapter import get_bedrock_context_length, BEDROCK_DEFAULT_CONTEXT_LENGTH
- with patch("agent.bedrock_adapter._resolve_inference_profile_model_id") as mock_resolve:
- assert get_bedrock_context_length(self.ARN) == BEDROCK_DEFAULT_CONTEXT_LENGTH
- mock_resolve.assert_not_called()
+
+class TestBedrockContextProbe:
"""Test the live context-window probe that reads the real window from
Bedrock's 'prompt is too long' validation error."""
diff --git a/website/docs/guides/aws-bedrock.md b/website/docs/guides/aws-bedrock.md
index 348dd17306b..2c83542215d 100644
--- a/website/docs/guides/aws-bedrock.md
+++ b/website/docs/guides/aws-bedrock.md
@@ -29,6 +29,7 @@ All three routes share the same AWS credential chain and region resolution — n
- **IAM permissions** — at minimum:
- `bedrock:InvokeModel` and `bedrock:InvokeModelWithResponseStream` (for inference)
- `bedrock:ListFoundationModels` and `bedrock:ListInferenceProfiles` (for model discovery)
+ - `bedrock:GetInferenceProfile` (only if `model.default` is an application inference profile ARN — used to size the context window from the wrapped model)
:::tip EC2 / ECS / Lambda
On AWS compute, attach an IAM role with `AmazonBedrockFullAccess` and you're done. No API keys, no `.env` configuration — Hermes detects the instance role automatically.
@@ -110,6 +111,8 @@ Hermes automatically applies prompt caching on the Bedrock **Converse API** path
For models whose context window isn't in Hermes' static table, Hermes can probe the real limit by sending oversized requests at fixed tiers (~1.3M and ~2.2M tokens) and parsing the `maximum` reported in Bedrock's length-validation error. Probed values feed the same metadata cache as the static table; stale cached entries that under-report a model's window (e.g. entries seeded before a model's 1M window went GA) are dropped automatically in favor of the larger known value.
+**Application inference profiles.** An ARN such as `arn:aws:bedrock:us-west-2:123456789012:application-inference-profile/abcdef123456` names no model, so neither the probe nor the static table can size it. Hermes calls `bedrock:GetInferenceProfile` in the ARN's region and sizes the window from the model the profile wraps (1M for a profile wrapping Claude Sonnet 4.6). Without that permission the 128,000-token default applies and a WARNING names the profile; set `model.context_length` explicitly to override either way.
+
## Available Models
Bedrock models use **inference profile IDs** for on-demand invocation. The `hermes model` picker shows these automatically, with recommended models at the top: