Skip to content

API Reference parrot.clients.amazon.bedrock

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.clients.amazon.bedrock

View source

Native AWS Bedrock Converse API client for AI-Parrot (FEAT-302, FEAT-315).

Implements :class:BedrockConverseBase, the model-family-agnostic Converse API engine (session/client management, message/tool conversion, the tool-use loop, streaming, guardrails, structured output, and credential resolution), and :class:BedrockConverseClient, a thin :class:BedrockConverseBase subclass that keeps the historical Claude/ Llama/Mistral-oriented public surface byte-compatible.

BedrockConverseBase talks to the AWS Bedrock Runtime Converse API directly via aioboto3 — as opposed to :class:~parrot.clients.anthropic.AnthropicClient's backend="bedrock", which routes through the Anthropic SDK's AsyncAnthropicBedrock transport (FEAT-232) and is therefore limited to Claude models.

This module implements Spec Module 4 ("BedrockConverseClient — Core"): session/client management, the Converse API tool-use loop, streaming, resume(), and a lightweight invoke(). Module 5 ("Advanced Features", TASK-1746) adds extended thinking, prompt caching, schema-based structured output, guardrails (apply_guardrail_text()), and the _invoke_native() fallback for models without ARN-versioned IDs. Factory registration is Module 6 (TASK-1747).

FEAT-315 (TASK-1806) extracted the engine into BedrockConverseBase so that :class:~parrot.clients.amazon.nova.NovaClient can inherit it directly instead of delegating to a second internal client object, and fixed the aws_id credential-resolution bug described below.

See sdd/specs/bedrock-client-llm.spec.md and sdd/specs/novaclient-amazon-aws.spec.md for the full design.

Alias AIMessage

Re-exported from parrot.models.responses.AIMessage.

Alias AIMessageFactory

Re-exported from parrot.models.responses.AIMessageFactory.

Alias AWS_CREDENTIALS

Re-exported from parrot.conf.AWS_CREDENTIALS.

Alias AWS_NOVA_API_KEY

Re-exported from parrot.conf.AWS_NOVA_API_KEY.

Alias AWS_REGION_NAME

Re-exported from parrot.conf.AWS_REGION_NAME.

Alias AbstractClient

Re-exported from parrot.clients.base.AbstractClient.

Alias AmazonModel

Re-exported from parrot.clients.amazon.models.AmazonModel.

Alias BEDROCK_AWS_REGION

Re-exported from parrot.conf.BEDROCK_AWS_REGION.

Alias BedrockBudgetAdapter

Re-exported from parrot.clients.amazon.budget.BedrockBudgetAdapter.

Class BedrockConverseBase

Model-family-agnostic engine for AWS Bedrock's native Converse API.

Carries everything that does NOT vary by model family: credential/ region resolution, aioboto3 session/client management, message and tool-schema conversion, the Converse tool-use loop, streaming, resume(), invoke(), guardrails, and structured output.

Concrete subclasses (e.g. :class:BedrockConverseClient, :class:~parrot.clients.amazon.nova.NovaClient) set the family-specific class attributes (client_type, client_name, _default_model, _fallback_model, ...) and inherit the rest verbatim — no delegation object, no reimplementation (spec novaclient-amazon-aws §2/§3 Module 1).

Parameter Type Default Description
aws_id Optional[str] None Optional AWS_CREDENTIALS profile name (spec novaclient-amazon-aws §1/§2.2). Resolution: kwarg → named profile in parrot.conf::AWS_CREDENTIALS (falls back to the 'default' profile when the named profile is missing). No aws_id means no profile lookup at all — see aws_access_key/aws_bearer_token for what happens next.
region Optional[str] None AWS region for the Bedrock Runtime endpoint. Resolution order: explicit kwarg → AWS_CREDENTIALS profile region_name → BEDROCK_AWS_REGION → AWS_REGION_NAME → "us-east-1".
profile Optional[str] None Optional named AWS profile, passed to aioboto3.Session.
region_prefix Optional[str] None Cross-region inference-profile prefix (e.g. "us", "eu", "apac") applied by :func:~parrot.clients.amazon.models.translate.
guardrail_id Optional[str] None Bedrock guardrail identifier. Stored for use by Module 5 (TASK-1746, Advanced Features); not yet applied to requests in this Core implementation.
guardrail_version Optional[str] None Bedrock guardrail version. See guardrail_id.
max_retries int 4 Max retry attempts for the underlying botocore client (adaptive retry mode).
read_timeout int 120 Socket read timeout (seconds) for the botocore client.
aws_access_key Optional[str] None AWS access key ID. Resolution: kwarg → the aws_id profile's aws_key/aws_access_key_id. No generic conf-wide fallback (removed — it silently picked up whatever AWS account was configured for unrelated services, e.g. S3, which may lack Bedrock permissions entirely).
aws_secret_key Optional[str] None AWS secret access key. Same resolution order.
aws_session_token Optional[str] None Optional STS session token. Same resolution order.
aws_bearer_token Optional[str] None Bedrock API key (bearer token, "ABSK..." prefix) — an alternative to the access/secret keypair. Resolution: kwarg → the aws_id profile's aws_bearer_token → AWS_NOVA_API_KEY (conf). Only consulted when no static access key resolves above (a caller providing both is assumed to want the access/secret keypair). When resolved, :meth:get_client exports it as AWS_BEARER_TOKEN_BEDROCK for botocore's own bearer-auth support (botocore>=1.36) to pick up — leave every resolution step None to instead rely on AWS_BEARER_TOKEN_BEDROCK already set in the process environment (the SDK's own default).
**kwargs {} Forwarded to :class:~parrot.clients.base.AbstractClient.

Method BedrockConverseBase.get_client

Create and return an aioboto3 Bedrock Runtime client with the shared (adaptive) retry policy.

aioboto3 is imported lazily here so that importing this module does not require the optional bedrock-native extra (TASK-1747) to be installed until the client is actually used. The returned client is cached per event loop by :meth:~parrot.clients.base.AbstractClient._ensure_client.

get_client() -> Any

Returns: Any — An aiobotocore Bedrock Runtime client instance.

Method BedrockConverseBase.close

Close the shared client and every per-loop budgeted (no-retry) client (spec §2.4).

close() -> None

Method BedrockConverseBase.apply_guardrail_text

Apply the configured Bedrock guardrail to standalone text.

Calls Bedrock's apply_guardrail() API directly (not via converse()) — useful for filtering text that did not originate from a Converse call (e.g. transcriptions, as used by :class:~parrot.clients.amazon.nova.audio.NovaAudio via :meth:~parrot.clients.amazon.nova.audio.NovaAudio._apply_pii_guardrail, TASK-1748/FEAT-315).

apply_guardrail_text(text: str, source: str = 'OUTPUT') -> str

Parameter Type Default Description
text str The text to filter.
source str 'OUTPUT' Guardrail content source — "INPUT" or "OUTPUT" (default).

Returns: str — The guardrail-processed text, or the original text unchanged if no guardrail is configured on this client (guardrail_id/ guardrail_version were not passed to __init__).

Method BedrockConverseBase.ask

Ask Bedrock a question via the Converse API, with tool-use loop.

ask(prompt: str, model: Optional[str] = None, max_tokens: Optional[int] = None, temperature: Optional[float] = None, files: Optional[List[Union[str, Path]]] = None, system_prompt: Optional[str] = None, history: Optional[Sequence[HistoryMessage]] = None, structured_output: Union[type, StructuredOutputConfig, None] = None, tools: Optional[List[Dict[str, Any]]] = None, use_tools: Optional[bool] = None, deep_research: bool = False, background: bool = False, lazy_loading: bool = False, thinking_budget: Optional[int] = None, output_schema: Optional[Dict[str, Any]] = None, prompt_cache: bool = False, guardrail_id: Optional[str] = None, guardrail_version: Optional[str] = None) -> AIMessage

Parameter Type Default Description
prompt str
model Optional[str] None
max_tokens Optional[int] None
temperature Optional[float] None
files Optional[List[Union[str, Path]]] None
system_prompt Optional[str] None
history Optional[Sequence[HistoryMessage]] None
structured_output Union[type, StructuredOutputConfig, None] None
tools Optional[List[Dict[str, Any]]] None
use_tools Optional[bool] None
deep_research bool False Not yet supported for Bedrock — logged and ignored.
background bool False Not yet supported for Bedrock — logged and ignored.
lazy_loading bool False Not yet supported for Bedrock — falls back to eager tool preparation.
thinking_budget Optional[int] None When set, enables extended thinking via additionalModelRequestFields.thinking (Module 5). Only supported by specific models (Claude Sonnet 4 family, etc.); the resulting reasoningContent blocks (text + opaque signature) are preserved verbatim across tool-use rounds and are available on the returned AIMessage via raw_response (no dedicated field — see spec §6). FEAT-482 Module 3: on 2026-generation Anthropic models that reject budget_tokens (Opus 5, Fable 5, Opus 4.8/4.7, Sonnet 5, Mythos 5 — see :func:_requires_adaptive_thinking), the value is used only as an on/off switch and the request instead carries {"type": "adaptive"}. Amazon Nova and older Anthropic models keep the budget_tokens shape byte-identically.
output_schema Optional[Dict[str, Any]] None Optional raw JSON Schema dict. When provided, a schema-in-system-prompt instruction is injected (Module 5) and the final response text is parsed as JSON into AIMessage.structured_output (is_structured=True). Distinct from structured_output (which targets a Pydantic/dataclass type via :class:~parrot.models.outputs.StructuredOutputConfig) — use this when you only have a raw JSON Schema, not a type.
prompt_cache bool False When True, marks the system prompt as a cache point (Module 5) via system=[{"text": ...}, {"cachePoint": {"type": "default"}}] and additionalModelRequestFields.promptCaching. Cache hit/miss metrics arrive via cacheReadInputTokens / cacheWriteInputTokens in CompletionUsage.extra_usage (already surfaced by CompletionUsage.from_bedrock(), TASK-1742). For multi-round tool-use calls, these two counters are the sum across all rounds (FEAT-404, U1) — not the last round's values — because CompletionUsage.__add__ shallow-merges extra_usage right-hand-wins and would otherwise silently drop earlier rounds' cache accounting.
guardrail_id Optional[str] None Per-call guardrail identifier override. Falls back to the identifier passed to __init__.
guardrail_version Optional[str] None Per-call guardrail version override. Falls back to the version passed to __init__.

Returns: AIMessage

Method BedrockConverseBase.ask_stream

Stream a Bedrock Converse response with tool-use support.

Yields successive str chunks (mapped from contentBlockDelta events), then a single final :class:AIMessage sentinel — the same streaming convention followed by every other client (:meth:AnthropicClient.ask_stream, etc.).

When the model requests a tool during streaming, the tool is executed between streaming rounds: text from the current round is yielded as it arrives, then the tool executes (a brief pause the caller sees as a gap between chunks), and a new streaming round begins with the tool result injected into the conversation. This mirrors the while True tool loop in :meth:ask and the existing streaming tool support in the Google client.

ask_stream(prompt: str, model: Optional[str] = None, max_tokens: Optional[int] = None, temperature: Optional[float] = None, files: Optional[List[Union[str, Path]]] = None, system_prompt: Optional[str] = None, history: Optional[Sequence[HistoryMessage]] = None, tools: Optional[List[Dict[str, Any]]] = None, use_tools: bool = True, deep_research: bool = False, agent_config: Optional[Dict[str, Any]] = None, lazy_loading: bool = False, thinking_budget: Optional[int] = None, guardrail_id: Optional[str] = None, guardrail_version: Optional[str] = None, **kwargs) -> AsyncIterator[Union[str, AIMessage]]

Parameter Type Default Description
prompt str
model Optional[str] None
max_tokens Optional[int] None
temperature Optional[float] None
files Optional[List[Union[str, Path]]] None
system_prompt Optional[str] None
history Optional[Sequence[HistoryMessage]] None
tools Optional[List[Dict[str, Any]]] None
use_tools bool True Whether to include tool definitions and run the streaming tool-call loop. Defaults to True.
deep_research bool False
agent_config Optional[Dict[str, Any]] None
lazy_loading bool False
thinking_budget Optional[int] None See :meth:ask — enables extended thinking via additionalModelRequestFields.thinking (Module 5), including the FEAT-482 Module 3 adaptive-shape selection for 2026-generation Anthropic models.
guardrail_id Optional[str] None Per-call guardrail identifier override. Falls back to the identifier passed to __init__.
guardrail_version Optional[str] None Per-call guardrail version override. Falls back to the version passed to __init__.
**kwargs {}

Returns: AsyncIterator[Union[str, AIMessage]]

Method BedrockConverseBase.resume

Resume a suspended Bedrock tool-use execution.

resume(session_id: str, user_input: str, state: Dict[str, Any]) -> AIMessage

Parameter Type Default Description
session_id str The session ID.
user_input str The user's input, injected as the toolResult content for the pending toolUseId.
state Dict[str, Any] The suspended state — messages (Bedrock-shaped, as captured by :meth:ask's HumanInteractionInterrupt path), tool_call_id, and optional agent_name (model override).

Returns: AIMessage — class:AIMessage produced once the resumed tool-use loop reaches a non-tool_use stop reason.

Method BedrockConverseBase.invoke

Lightweight stateless invocation for BedrockConverseClient.

A single converse() call — no retry, no conversation history, no prompt builder. Uses schema-in-system-prompt for structured output (Bedrock-native outputConfig.textFormat support is added in Module 5 / TASK-1746).

invoke(prompt: str, *, output_type: Optional[type] = None, structured_output: Optional[StructuredOutputConfig] = None, model: Optional[str] = None, system_prompt: Optional[str] = None, max_tokens: Optional[int] = None, temperature: float = 0.0, use_tools: bool = False, tools: Optional[list] = None) -> InvokeResult

Parameter Type Default Description
prompt str User prompt.
output_type Optional[type] None Pydantic model or dataclass to parse the response into.
structured_output Optional[StructuredOutputConfig] None Full :class:StructuredOutputConfig; takes precedence over output_type.
model Optional[str] None Model override. Falls back to an explicitly selected self.model, then _lightweight_model.
system_prompt Optional[str] None System prompt override.
max_tokens Optional[int] None Maximum completion tokens.
temperature float 0.0 Sampling temperature.
use_tools bool False Whether to inject registered tools.
tools Optional[list] None Additional tool definitions (unused — registered tools are always sourced from the tool manager; kept for interface parity with other clients).

Returns: InvokeResult — class:InvokeResult with parsed output.

Raises:

  • InvokeError — On provider errors.

Class BedrockConverseClient

Client for AWS Bedrock's native Converse API — non-Nova families.

Thin :class:BedrockConverseBase subclass carrying only the family-specific defaults (Claude/Llama/Mistral/... on Bedrock). All behavior (ask/ask_stream/resume/invoke, credential resolution, guardrails, structured output) is inherited unchanged from :class:BedrockConverseBase — this class's public surface is byte-compatible with the pre-FEAT-315 monolithic implementation.

Attributes:

Attribute Type Description
client_type str
client_name str
provider_keys tuple[str, ...]
models type[Enum]

Alias BudgetAccountingError

Re-exported from parrot.core.exceptions.BudgetAccountingError.

Alias BudgetError

Re-exported from parrot.core.exceptions.BudgetError.

Alias BudgetExhausted

Re-exported from parrot.core.exceptions.BudgetExhausted.

Alias CompletionUsage

Re-exported from parrot.models.basic.CompletionUsage.

Alias HistoryMessage

Re-exported from parrot.memory.render.HistoryMessage.

Alias InvokeError

Re-exported from parrot.exceptions.InvokeError.

Alias InvokeResult

Re-exported from parrot.models.responses.InvokeResult.

Attribute NO_SAMPLING_MODEL_FAMILIES

Type: tuple[str, ...]

Alias StructuredOutputConfig

Re-exported from parrot.models.outputs.StructuredOutputConfig.

Alias TOKEN_BUDGET_STATE_KEY

Re-exported from parrot.clients.budget_scope.TOKEN_BUDGET_STATE_KEY.

Alias ToolCall

Re-exported from parrot.models.basic.ToolCall.

Alias ToolFormat

Re-exported from parrot.tools.manager.ToolFormat.

Alias current_budget_scope

Re-exported from parrot.clients.budget_scope.current_budget_scope.

Alias current_session_id

Re-exported from parrot.observability.context.current_session_id.

Alias current_user_id

Re-exported from parrot.observability.context.current_user_id.

Function rejects_sampling_params

Return True when model_id rejects sampling parameters.

rejects_sampling_params(model_id: str) -> bool

Parameter Type Default Description
model_id str A Bedrock model ID, already translated (it may carry a region prefix, a version suffix, or be a full ARN).

Returns: bool — True when temperature/topP/topK must be omitted from the request for this model.

Alias translate_bedrock_model

Re-exported from parrot.clients.amazon.models.translate.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally