The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bedrock): size inference-profile ARNs from the wrapped foundation model
liuhao10244c28be68c240
diff --git a/agent/bedrock_adapter.py b/agent/bedrock_adapter.pyindex a23b3ec164c..ae76640bd82 100644--- a/agent/bedrock_adapter.py+++ b/agent/bedrock_adapter.py@@ -1123,11 +1123,60 @@ 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")."""+ 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:+ model_id = _resolve_inference_profile_model_id(profile_arn, region)if probe and region and (probed := probe_bedrock_context_length(model_id, region)):return probedmatches = [key for key in BEDROCK_CONTEXT_LENGTHS if key in model_id.lower()]- return BEDROCK_CONTEXT_LENGTHS[max(matches, key=len)] if matches else BEDROCK_DEFAULT_CONTEXT_LENGTH+ if matches:+ return BEDROCK_CONTEXT_LENGTHS[max(matches, key=len)]+ if profile_arn:+ logger.warning(+ "Bedrock inference profile %s resolved no known model window; using the %s default. "+ "Grant bedrock:GetInferenceProfile or set model.context_length explicitly if the "+ "wrapped model has a larger window.",+ profile_arn,+ f"{BEDROCK_DEFAULT_CONTEXT_LENGTH:,}",+ )+ 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/(.+)$")+_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]+ 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+ 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+ return resolved# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----diff --git a/tests/agent/test_bedrock_adapter.py b/tests/agent/test_bedrock_adapter.pyindex 636f75a6128..c1e83fbc9e3 100644--- a/tests/agent/test_bedrock_adapter.py+++ b/tests/agent/test_bedrock_adapter.py@@ -1067,7 +1067,71 @@ class TestBedrockContextLength:mock_probe.assert_not_called()-class TestBedrockContextProbe:+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."""++ ARN = "arn:aws:bedrock:us-west-2:123456789012:application-inference-profile/abcdef123456"++ def setup_method(self):+ 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.+ 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.+ 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++ 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()"""Test the live context-window probe that reads the real window fromBedrock's 'prompt is too long' validation error."""