The Amazon Bedrock Runtime Converse API client (Effect's
AmazonBedrockClient).
layer(...) provides AmazonBedrockClient over the HttpClient
service, signing each request with AWS Signature Version 4 on the Digest
and Mac services the caller provides (pyfect.crypto.native's layers,
or the Web Crypto ones), or sending a Bedrock API key as a bearer token::
client = yield from AmazonBedrockClient()
response = yield from client.converse({"modelId": model, "messages": [...]})The client authenticates with, in this order: api_key (a Bedrock API
key); credentials, an effect run before every request (wrap a credential
provider in it; cache it with cached_with_ttl to avoid resolving on every
request); access_key_id and secret_access_key with an optional
session_token. Without any of them every request fails with an
AuthenticationError of kind MissingKey. Every failure is an
AiError; an exception frame in a stream (a throttlingException,
...) fails the stream with the reason its REST counterpart has.
Re-exports#
- From
pyfect.ai.ai_error:AiError
Values#
| Attribute | Type | Description |
|---|---|---|
DEFAULT_REGION | Literal['us-east-1'] = 'us-east-1' |
Classes#
Functions#
make#
make(*, region=None, api_url=None, access_key_id=None, secret_access_key=None, session_token=None, api_key=None, credentials=None, transform_client=None, max_response_bytes=None) -> Effect[Service, Never, HttpClient | Digest | Mac]An Amazon Bedrock client over the HttpClient service, signing
with the Digest and Mac services in context (required however
it authenticates, though an api_key client never calls them; a
CryptoError of Mac is a defect). Requests go to api_url
(https://bedrock-runtime.<region>.amazonaws.com, region
defaulting to us-east-1); transform_client changes the
underlying client (and so does an AmazonBedrockConfig, per call). A
response body larger than max_response_bytes (256 MiB) fails the
call.
| Parameter | Type | Description |
|---|---|---|
region | str | None = None | |
api_url | str | None = None | |
access_key_id | str | None = None | |
secret_access_key | Redacted[str] | None = None | |
session_token | Redacted[str] | None = None | |
api_key | Redacted[str] | None = None | |
credentials | Effect[Credentials, AiError] | None = None | |
transform_client | ClientTransform | None = None | |
max_response_bytes | byte_size.Input | None = None |
Returns Effect[Service, Never, HttpClient | Digest | Mac]
def make(
*,
region: str | None = None,
api_url: str | None = None,
access_key_id: str | None = None,
secret_access_key: Redacted[str] | None = None,
session_token: Redacted[str] | None = None,
api_key: Redacted[str] | None = None,
credentials: Effect[Credentials, AiError] | None = None,
transform_client: ClientTransform | None = None,
max_response_bytes: byte_size.Input | None = None,
) -> Effect[Service, Never, HttpClient | Digest | Mac]:
"""An Amazon Bedrock client over the ``HttpClient`` service, signing
with the ``Digest`` and ``Mac`` services in context (required however
it authenticates, though an ``api_key`` client never calls them; a
``CryptoError`` of ``Mac`` is a defect). Requests go to ``api_url``
(``https://bedrock-runtime.<region>.amazonaws.com``, ``region``
defaulting to ``us-east-1``); ``transform_client`` changes the
underlying client (and so does an ``AmazonBedrockConfig``, per call). A
response body larger than ``max_response_bytes`` (256 MiB) fails the
call."""
if credentials is not None:
require_effect(credentials, "credentials")
resolved_region = P.or_default(region, DEFAULT_REGION)
base_url = P.or_default(api_url, f"https://bedrock-runtime.{resolved_region}.amazonaws.com")
limit: ByteSize = P.response_limit(max_response_bytes)
resolve = _resolve_credentials(
api_key=api_key,
credentials=credentials,
access_key_id=access_key_id,
secret_access_key=secret_access_key,
session_token=session_token,
)
def with_credentials[A, E](method: str, effect: Effect[A, E]) -> Effect[A, E | AiError]:
return resolve(method).flat_map(
lambda found: effect.pipe(fx.provide_service(_CurrentRequestCredentials, found))
)
def build(
base: HttpClientService[HttpClientError], digest: DigestService, mac: MacService
) -> Service:
prepared = base.map_request(
lambda request: request.prepend_url(base_url).accept_json()
).map_request_effect(_authenticate(Signer(resolved_region, digest, mac)))
http_client = prepared if transform_client is None else transform_client(prepared)
def send(
requesting: Effect[HttpClientRequest, Any, Any],
) -> Effect[HttpClientResponse, HttpClientError | AiError]:
sending: Effect[HttpClientResponse, Any, Any] = requesting.flat_map(
lambda request: with_credentials("execute", http_client.execute(request))
)
return sending.pipe(_redacted)
exposed: HttpClientService[HttpClientError | AiError] = HttpClientService(send, fx.succeed)
client_ok = P.limit_responses(http_client, limit).filter_status_ok()
def execute(
operation: str, method: str, request: W.ConverseRequest
) -> Effect[HttpClientResponse, HttpClientError | AiError]:
body = {key: value for key, value in request.items() if key != "modelId"}
path = f"/model/{_encode_uri_component(request['modelId'])}/{operation}"
sending = P.resolve_client(AmazonBedrockConfig, client_ok).flat_map(
lambda client: client.execute(http_request.post(path).body_json_unsafe(body))
)
return with_credentials(method, sending)
def converse(request: W.ConverseRequest) -> Effect[W.ConverseResponse, AiError]:
sent: Effect[W.ConverseResponse, Any] = execute(
"converse", "converse", request
).flat_map(lambda response: response.json.flat_map(W.decode_converse_response))
return sent.catch_all(ERRORS.catch("converse")).pipe(_redacted)
def converse_stream(request: W.ConverseRequest) -> Stream[W.ConverseStreamEvent, AiError]:
frames = ES.decode(
http_response.stream(execute("converse-stream", "converseStream", request))
)
events: Stream[W.ConverseStreamEvent, Any] = frames.map_effect(
_decode_frame
).filter_map(lambda event: Err(None) if event is None else Ok(event))
return events.catch_all(_stream_failure).update_service(
CurrentRedactedNames, lambda names: (*names, *SECRET_HEADERS)
)
return Service(exposed, converse, converse_stream)
return fx.all(HttpClient(), Digest(), Mac()).map(lambda found: build(*found)).pipe(_redacted)layer#
layer(*, region=None, api_url=None, access_key_id=None, secret_access_key=None, session_token=None, api_key=None, credentials=None, transform_client=None, max_response_bytes=None) -> L.Layer[AmazonBedrockClient, Never, HttpClient | Digest | Mac]AmazonBedrockClient from these options (see make).
| Parameter | Type | Description |
|---|---|---|
region | str | None = None | |
api_url | str | None = None | |
access_key_id | str | None = None | |
secret_access_key | Redacted[str] | None = None | |
session_token | Redacted[str] | None = None | |
api_key | Redacted[str] | None = None | |
credentials | Effect[Credentials, AiError] | None = None | |
transform_client | ClientTransform | None = None | |
max_response_bytes | byte_size.Input | None = None |
Returns L.Layer[AmazonBedrockClient, Never, HttpClient | Digest | Mac]
def layer(
*,
region: str | None = None,
api_url: str | None = None,
access_key_id: str | None = None,
secret_access_key: Redacted[str] | None = None,
session_token: Redacted[str] | None = None,
api_key: Redacted[str] | None = None,
credentials: Effect[Credentials, AiError] | None = None,
transform_client: ClientTransform | None = None,
max_response_bytes: byte_size.Input | None = None,
) -> L.Layer[AmazonBedrockClient, Never, HttpClient | Digest | Mac]:
"""``AmazonBedrockClient`` from these options (see ``make``)."""
return L.effect(
AmazonBedrockClient,
make(
region=region,
api_url=api_url,
access_key_id=access_key_id,
secret_access_key=secret_access_key,
session_token=session_token,
api_key=api_key,
credentials=credentials,
transform_client=transform_client,
max_response_bytes=max_response_bytes,
),
)layer_config#
layer_config(*, region=None, api_url=None, access_key_id=None, secret_access_key=None, session_token=None, api_key=None, credentials=None, transform_client=None, max_response_bytes=None) -> L.Layer[AmazonBedrockClient, ConfigError, HttpClient | Digest | Mac]AmazonBedrockClient with its settings read from Config. Each
defaults to the variable the AWS tools read: AWS_REGION,
AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN
and, for a Bedrock API key, AWS_BEARER_TOKEN_BEDROCK; all are
optional (see make for which wins when several are set).
| Parameter | Type | Description |
|---|---|---|
region | Config[str | None] | None = None | |
api_url | Config[str | None] | None = None | |
access_key_id | Config[str | None] | None = None | |
secret_access_key | Config[Redacted[str] | None] | None = None | |
session_token | Config[Redacted[str] | None] | None = None | |
api_key | Config[Redacted[str] | None] | None = None | |
credentials | Effect[Credentials, AiError] | None = None | |
transform_client | ClientTransform | None = None | |
max_response_bytes | byte_size.Input | None = None |
Returns L.Layer[AmazonBedrockClient, ConfigError, HttpClient | Digest | Mac]
def layer_config(
*,
region: Config[str | None] | None = None,
api_url: Config[str | None] | None = None,
access_key_id: Config[str | None] | None = None,
secret_access_key: Config[Redacted[str] | None] | None = None,
session_token: Config[Redacted[str] | None] | None = None,
api_key: Config[Redacted[str] | None] | None = None,
credentials: Effect[Credentials, AiError] | None = None,
transform_client: ClientTransform | None = None,
max_response_bytes: byte_size.Input | None = None,
) -> L.Layer[AmazonBedrockClient, ConfigError, HttpClient | Digest | Mac]:
"""``AmazonBedrockClient`` with its settings read from ``Config``. Each
defaults to the variable the AWS tools read: ``AWS_REGION``,
``AWS_ACCESS_KEY_ID``, ``AWS_SECRET_ACCESS_KEY``, ``AWS_SESSION_TOKEN``
and, for a Bedrock API key, ``AWS_BEARER_TOKEN_BEDROCK``; all are
optional (see ``make`` for which wins when several are set)."""
if credentials is not None:
require_effect(credentials, "credentials")
@fx.gen
def built():
return (
yield from make(
region=(yield from region or config_string("AWS_REGION").with_default(None)),
api_url=(yield from P.optional_config(api_url)),
access_key_id=(
yield from access_key_id
or config_string("AWS_ACCESS_KEY_ID").with_default(None)
),
secret_access_key=(
yield from secret_access_key
or config_redacted("AWS_SECRET_ACCESS_KEY").with_default(None)
),
session_token=(
yield from session_token
or config_redacted("AWS_SESSION_TOKEN").with_default(None)
),
api_key=(
yield from api_key
or config_redacted("AWS_BEARER_TOKEN_BEDROCK").with_default(None)
),
credentials=credentials,
transform_client=transform_client,
max_response_bytes=max_response_bytes,
)
)
return L.effect(AmazonBedrockClient, built)