# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """``Translator`` with a chat model on Amazon Bedrock, through the Converse API.""" import warnings from collections.abc import Mapping, Sequence from typing import Any from .translation import TranslationError, Translator __all__ = ["BedrockTranslator"] # the boto3 client a BedrockTranslator makes when it is given none CLIENT_CONFIG = {"read_timeout": 240, "connect_timeout": 10, "retries": {"max_attempts": 25, "mode": "standard"}} # additionalModelRequestFields by provider; Anthropic models were evaluated with adaptive thinking REQUEST_FIELDS: dict[str, dict[str, Any]] = {"anthropic": {"thinking": {"type": "adaptive", "display": "omitted"}}} # errors of one call (the model's own output, or a transient service error), after which the item is asked again MODEL_ERRORS = ("ModelErrorException", "InternalServerException", "ServiceUnavailableException") class BedrockTranslator(Translator): """ ``Translator`` with a chat model on Amazon Bedrock that supports tool use, through the Converse API. Requires ``boto3`` (``pip install 'chronos-forecasting[text]'``). Tested so far with Claude 5.5 (Opus, Haiku), OpenAI (GPT-6.1-sol, gpt-oss-120b) and Z.ai (GLM 5) models; other providers may not work out of the box. Parameters ---------- model_id Bedrock model id or inference profile. Translations were evaluated with "us.anthropic.claude-opus-5-5" and "us.anthropic.claude-haiku-5-5". client A boto3 "bedrock-runtime" client, by default one with ``CLIENT_CONFIG`` in ``region_name``. region_name Bedrock region of the default client, by default the one boto3 is configured with. max_tokens Most output tokens of a call, reasoning included. request_fields Model-specific request fields (Converse's ``additionalModelRequestFields``), merged over the provider's ``REQUEST_FIELDS``; a field set to None removes it. cache_prompt Whether to cache the system prompt. A model that rejects the cache point is called without it from then on. **kwargs Passed to ``Translator``. """ def __init__( self, model_id: str, *, client: Any = None, region_name: str | None = None, max_tokens: int = 64_000, request_fields: Mapping[str, Any] | None = None, cache_prompt: bool = True, **kwargs, ): super().__init__(**kwargs) if client is None: try: import boto3 from botocore.config import Config except ImportError as e: raise ImportError("BedrockTranslator needs boto3: pip install 'chronos-forecasting[text]'") from e client = boto3.client("bedrock-runtime", region_name=region_name, config=Config(**CLIENT_CONFIG)) provider = next((p for p in REQUEST_FIELDS if f"{p}." in model_id), "") fields = {**REQUEST_FIELDS.get(provider, {}), **(request_fields or {})} self.model_id = model_id self.client = client self.max_tokens = max_tokens self.request_fields = {k: v for k, v in fields.items() if v is not None} self.cache_prompt = cache_prompt def _complete(self, system: Sequence[str], user: str, tool: Mapping[str, Any]) -> dict[str, Any]: from botocore.exceptions import ClientError, HTTPClientError from botocore.exceptions import ConnectionError as BotoConnectionError spec = { "name": tool["name"], "description": tool["description"], "inputSchema": {"json": tool["input_schema"]}, } request: dict[str, Any] = { "modelId": self.model_id, "messages": [{"role": "user", "content": [{"text": user}]}], "toolConfig": { "tools": [{"toolSpec": spec}], # not forced, so that the model can think before it calls the tool "toolChoice": {"auto": {}}, }, "inferenceConfig": {"maxTokens": self.max_tokens}, } if self.request_fields: request["additionalModelRequestFields"] = self.request_fields cached = self.cache_prompt cache = [{"cachePoint": {"type": "default"}}] if cached else [] request["system"] = [block for part in system for block in ({"text": part}, *cache)] try: response = self.client.converse(**request) except (ClientError, HTTPClientError, BotoConnectionError) as e: # HTTP and connection errors: transient # only a request with a cache point falls back: other threads may have turned caching off meanwhile if isinstance(e, ClientError) and cached and _rejects_cache(e): self.cache_prompt = False # not an attempt: asked again at once without the cache point warnings.warn(f"{self.model_id} does not accept a prompt cache point; translating without one") return self._complete(system, user, tool) if isinstance(e, ClientError) and not _is_model_error(e): raise raise TranslationError(str(e)) from e calls = [ block["toolUse"]["input"] for block in response["output"]["message"]["content"] if "toolUse" in block and block["toolUse"]["name"] == tool["name"] ] if response["stopReason"] in ("tool_use", "end_turn") and calls: return calls[0] raise TranslationError(f"no complete tool call, stop reason {response['stopReason']!r}") def _is_model_error(e: Exception) -> bool: code = getattr(e, "response", {}).get("Error", {}).get("Code") # Bedrock reports an invalid reply of the model as a ValidationException, told apart by its message return code in MODEL_ERRORS or ( code == "ValidationException" and "The model returned the following errors" in str(e) ) def _rejects_cache(e: Exception) -> bool: # How Bedrock rejected a cache point (us-east-1, 2026-11): AccessDeniedException "You invoked an unsupported model # or your request did not allow prompt caching" (gpt-oss-120b, GLM 5, Kimi K2.5, DeepSeek V3.2, Mistral Large 3), # ValidationException "This model doesn't support the cachePoint field" (Kimi K3.1). An access denial for another # reason also turns caching off; the call without the cache point then raises it. code = getattr(e, "response", {}).get("Error", {}).get("Code") return code in ("AccessDeniedException", "ValidationException") and ( "prompt caching" in str(e) or "cachePoint" in str(e) )