Skip to content

Commit 4dab499

Browse files
committed
fix(bedrock): improve region inference using boto3 client and support profile arg
1 parent df03caf commit 4dab499

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

src/anthropic/lib/bedrock/_client.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def _prepare_options(input_options: FinalRequestOptions) -> FinalRequestOptions:
6767
return options
6868

6969

70-
def _infer_region() -> str:
70+
def _infer_region(aws_profile: str | None = None) -> str:
7171
"""
7272
Infer the AWS region from the environment variables or
7373
from the boto3 session if available.
@@ -76,10 +76,19 @@ def _infer_region() -> str:
7676
if aws_region is None:
7777
try:
7878
import boto3
79+
import botocore
7980

80-
session = boto3.Session()
81+
session = boto3.Session(profile_name=aws_profile)
8182
if session.region_name:
8283
aws_region = session.region_name
84+
else:
85+
# If the region is not in the session, it might be in the config file
86+
# but not loaded because AWS_SDK_LOAD_CONFIG is not set.
87+
# creating a client might trigger the loading.
88+
try:
89+
aws_region = session.client("bedrock").meta.region_name
90+
except botocore.exceptions.NoRegionError:
91+
pass
8392
except ImportError:
8493
pass
8594

@@ -158,11 +167,10 @@ def __init__(
158167
_strict_response_validation: bool = False,
159168
) -> None:
160169
self.aws_secret_key = aws_secret_key
161-
162170
self.aws_access_key = aws_access_key
163171

164-
self.aws_region = _infer_region() if aws_region is None else aws_region
165172
self.aws_profile = aws_profile
173+
self.aws_region = _infer_region(aws_profile) if aws_region is None else aws_region
166174

167175
self.aws_session_token = aws_session_token
168176

@@ -300,11 +308,10 @@ def __init__(
300308
_strict_response_validation: bool = False,
301309
) -> None:
302310
self.aws_secret_key = aws_secret_key
303-
304311
self.aws_access_key = aws_access_key
305312

306-
self.aws_region = _infer_region() if aws_region is None else aws_region
307313
self.aws_profile = aws_profile
314+
self.aws_region = _infer_region(aws_profile) if aws_region is None else aws_region
308315

309316
self.aws_session_token = aws_session_token
310317

0 commit comments

Comments
 (0)