| 1 |
import re |
| 2 |
import json |
| 3 |
import base64 |
| 4 |
import struct |
| 5 |
import typing as t |
| 6 |
import binascii |
| 7 |
import tempfile |
| 8 |
import threading |
| 9 |
from typing import TypedDict, cast |
| 10 |
from typing_extensions import Protocol |
| 11 |
|
| 12 |
import httpx2 |
| 13 |
import pytest |
| 14 |
from respx import MockRouter |
| 15 |
|
| 16 |
from anthropic import APIStatusError, AnthropicBedrock, AsyncAnthropicBedrock, beta_tool, beta_async_tool |
| 17 |
from anthropic._compat import PYDANTIC_V1 |
| 18 |
from anthropic._models import FinalRequestOptions |
| 19 |
from anthropic.lib.bedrock._client import _prepare_options |
| 20 |
from anthropic.lib.bedrock._stream_decoder import _chunk_bytes_to_sse |
| 21 |
|
| 22 |
sync_client = AnthropicBedrock( |
| 23 |
aws_region="us-east-1", |
| 24 |
aws_access_key="example-access-key", |
| 25 |
aws_secret_key="example-secret-key", |
| 26 |
) |
| 27 |
async_client = AsyncAnthropicBedrock( |
| 28 |
aws_region="us-east-1", |
| 29 |
aws_access_key="example-access-key", |
| 30 |
aws_secret_key="example-secret-key", |
| 31 |
) |
| 32 |
|
| 33 |
|
| 34 |
class MockRequestCall(Protocol): |
| 35 |
request: httpx2.Request |
| 36 |
|
| 37 |
|
| 38 |
class AwsConfigProfile(TypedDict): |
| 39 |
# Available regions: https://docs.aws.amazon.com/global-infrastructure/latest/regions/aws-regions.html#available-regions |
| 40 |
name: t.Union[t.Literal["default"], str] |
| 41 |
region: str |
| 42 |
|
| 43 |
|
| 44 |
def profile_to_ini(profile: AwsConfigProfile) -> str: |
| 45 |
""" |
| 46 |
Convert an AWS config profile to an INI format string. |
| 47 |
""" |
| 48 |
|
| 49 |
profile_name = profile["name"] if profile["name"] == "default" else f"profile {profile['name']}" |
| 50 |
return f"[{profile_name}]\nregion = {profile['region']}\n" |
| 51 |
|
| 52 |
|
| 53 |
@pytest.fixture |
| 54 |
def profiles() -> t.List[AwsConfigProfile]: |
| 55 |
return [ |
| 56 |
{"name": "default", "region": "us-east-2"}, |
| 57 |
] |
| 58 |
|
| 59 |
|
| 60 |
@pytest.fixture |
| 61 |
def mock_aws_config( |
| 62 |
profiles: t.List[AwsConfigProfile], |
| 63 |
monkeypatch: t.Any, |
| 64 |
) -> t.Iterable[None]: |
| 65 |
with tempfile.NamedTemporaryFile(mode="w+", delete=True) as temp_file: |
| 66 |
for profile in profiles: |
| 67 |
temp_file.write(profile_to_ini(profile)) |
| 68 |
temp_file.flush() |
| 69 |
monkeypatch.setenv("AWS_CONFIG_FILE", str(temp_file.name)) |
| 70 |
yield |
| 71 |
|
| 72 |
|
| 73 |
@pytest.mark.respx() |
| 74 |
def test_messages_retries(respx_mock: MockRouter) -> None: |
| 75 |
respx_mock.post(re.compile(r"https://bedrock-runtime\.us-east-1\.amazonaws\.com/model/.*/invoke")).mock( |
| 76 |
side_effect=[ |
| 77 |
httpx2.Response(500, json={"error": "server error"}, headers={"retry-after-ms": "10"}), |
| 78 |
httpx2.Response(200, json={"foo": "bar"}), |
| 79 |
] |
| 80 |
) |
| 81 |
|
| 82 |
sync_client.messages.create( |
| 83 |
max_tokens=1024, |
| 84 |
messages=[ |
| 85 |
{ |
| 86 |
"role": "user", |
| 87 |
"content": "Say hello there!", |
| 88 |
} |
| 89 |
], |
| 90 |
model="anthropic.claude-3-5-sonnet-20241022-v2:0", |
| 91 |
) |
| 92 |
|
| 93 |
calls = cast("list[MockRequestCall]", respx_mock.calls) |
| 94 |
|
| 95 |
assert len(calls) == 2 |
| 96 |
|
| 97 |
assert ( |
| 98 |
calls[0].request.url |
| 99 |
== "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-3-5-sonnet-20241022-v2:0/invoke" |
| 100 |
) |
| 101 |
assert ( |
| 102 |
calls[1].request.url |
| 103 |
== "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-3-5-sonnet-20241022-v2:0/invoke" |
| 104 |
) |
| 105 |
|
| 106 |
|
| 107 |
@pytest.mark.respx() |
| 108 |
@pytest.mark.asyncio() |
| 109 |
async def test_messages_retries_async(respx_mock: MockRouter) -> None: |
| 110 |
respx_mock.post(re.compile(r"https://bedrock-runtime\.us-east-1\.amazonaws\.com/model/.*/invoke")).mock( |
| 111 |
side_effect=[ |
| 112 |
httpx2.Response(500, json={"error": "server error"}, headers={"retry-after-ms": "10"}), |
| 113 |
httpx2.Response(200, json={"foo": "bar"}), |
| 114 |
] |
| 115 |
) |
| 116 |
|
| 117 |
await async_client.messages.create( |
| 118 |
max_tokens=1024, |
| 119 |
messages=[ |
| 120 |
{ |
| 121 |
"role": "user", |
| 122 |
"content": "Say hello there!", |
| 123 |
} |
| 124 |
], |
| 125 |
model="anthropic.claude-3-5-sonnet-20241022-v2:0", |
| 126 |
) |
| 127 |
|
| 128 |
calls = cast("list[MockRequestCall]", respx_mock.calls) |
| 129 |
|
| 130 |
assert len(calls) == 2 |
| 131 |
|
| 132 |
assert ( |
| 133 |
calls[0].request.url |
| 134 |
== "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-3-5-sonnet-20241022-v2:0/invoke" |
| 135 |
) |
| 136 |
assert ( |
| 137 |
calls[1].request.url |
| 138 |
== "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-3-5-sonnet-20241022-v2:0/invoke" |
| 139 |
) |
| 140 |
|
| 141 |
|
| 142 |
@pytest.mark.respx() |
| 143 |
def test_application_inference_profile(respx_mock: MockRouter) -> None: |
| 144 |
respx_mock.post(re.compile(r"https://bedrock-runtime\.us-east-1\.amazonaws\.com/model/.*/invoke")).mock( |
| 145 |
side_effect=[ |
| 146 |
httpx2.Response(500, json={"error": "server error"}, headers={"retry-after-ms": "10"}), |
| 147 |
httpx2.Response(200, json={"foo": "bar"}), |
| 148 |
] |
| 149 |
) |
| 150 |
|
| 151 |
sync_client.messages.create( |
| 152 |
max_tokens=1024, |
| 153 |
messages=[ |
| 154 |
{ |
| 155 |
"role": "user", |
| 156 |
"content": "Say hello there!", |
| 157 |
} |
| 158 |
], |
| 159 |
model="arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/jf2sje1c0jnb", |
| 160 |
) |
| 161 |
|
| 162 |
calls = cast("list[MockRequestCall]", respx_mock.calls) |
| 163 |
assert len(calls) == 2 |
| 164 |
|
| 165 |
assert ( |
| 166 |
calls[0].request.url |
| 167 |
== "https://bedrock-runtime.us-east-1.amazonaws.com/model/arn:aws:bedrock:us-east-1:123456789012:application-inference-profile%2Fjf2sje1c0jnb/invoke" |
| 168 |
) |
| 169 |
assert ( |
| 170 |
calls[1].request.url |
| 171 |
== "https://bedrock-runtime.us-east-1.amazonaws.com/model/arn:aws:bedrock:us-east-1:123456789012:application-inference-profile%2Fjf2sje1c0jnb/invoke" |
| 172 |
) |
| 173 |
|
| 174 |
|
| 175 |
sync_api_key_client = AnthropicBedrock( |
| 176 |
aws_region="us-east-1", |
| 177 |
api_key="test-api-key", |
| 178 |
) |
| 179 |
async_api_key_client = AsyncAnthropicBedrock( |
| 180 |
aws_region="us-east-1", |
| 181 |
api_key="test-api-key", |
| 182 |
) |
| 183 |
|
| 184 |
|
| 185 |
@pytest.mark.respx() |
| 186 |
def test_api_key_auth(respx_mock: MockRouter) -> None: |
| 187 |
respx_mock.post(re.compile(r"https://bedrock-runtime\.us-east-1\.amazonaws\.com/model/.*/invoke")).mock( |
| 188 |
return_value=httpx2.Response(200, json={"foo": "bar"}), |
| 189 |
) |
| 190 |
|
| 191 |
sync_api_key_client.messages.create( |
| 192 |
max_tokens=1024, |
| 193 |
messages=[{"role": "user", "content": "Say hello there!"}], |
| 194 |
model="anthropic.claude-3-5-sonnet-20241022-v2:0", |
| 195 |
) |
| 196 |
|
| 197 |
calls = cast("list[MockRequestCall]", respx_mock.calls) |
| 198 |
assert len(calls) == 1 |
| 199 |
assert calls[0].request.headers["Authorization"] == "Bearer test-api-key" |
| 200 |
|
| 201 |
|
| 202 |
@pytest.mark.respx() |
| 203 |
@pytest.mark.asyncio() |
| 204 |
async def test_api_key_auth_async(respx_mock: MockRouter) -> None: |
| 205 |
respx_mock.post(re.compile(r"https://bedrock-runtime\.us-east-1\.amazonaws\.com/model/.*/invoke")).mock( |
| 206 |
return_value=httpx2.Response(200, json={"foo": "bar"}), |
| 207 |
) |
| 208 |
|
| 209 |
await async_api_key_client.messages.create( |
| 210 |
max_tokens=1024, |
| 211 |
messages=[{"role": "user", "content": "Say hello there!"}], |
| 212 |
model="anthropic.claude-3-5-sonnet-20241022-v2:0", |
| 213 |
) |
| 214 |
|
| 215 |
calls = cast("list[MockRequestCall]", respx_mock.calls) |
| 216 |
assert len(calls) == 1 |
| 217 |
assert calls[0].request.headers["Authorization"] == "Bearer test-api-key" |
| 218 |
|
| 219 |
|
| 220 |
def test_api_key_from_env(monkeypatch: t.Any) -> None: |
| 221 |
monkeypatch.setenv("AWS_BEARER_TOKEN_BEDROCK", "env-api-key") |
| 222 |
client = AnthropicBedrock(aws_region="us-east-1") |
| 223 |
assert client.api_key == "env-api-key" |
| 224 |
|
| 225 |
|
| 226 |
def test_api_key_mutual_exclusion() -> None: |
| 227 |
with pytest.raises(ValueError, match="Cannot specify both"): |
| 228 |
AnthropicBedrock( |
| 229 |
aws_region="us-east-1", |
| 230 |
api_key="test-api-key", |
| 231 |
aws_access_key="example-access-key", |
| 232 |
) |
| 233 |
|
| 234 |
|
| 235 |
def test_api_key_mutual_exclusion_async() -> None: |
| 236 |
with pytest.raises(ValueError, match="Cannot specify both"): |
| 237 |
AsyncAnthropicBedrock( |
| 238 |
aws_region="us-east-1", |
| 239 |
api_key="test-api-key", |
| 240 |
aws_secret_key="example-secret-key", |
| 241 |
) |
| 242 |
|
| 243 |
|
| 244 |
def test_api_key_env_mutual_exclusion(monkeypatch: t.Any) -> None: |
| 245 |
monkeypatch.setenv("AWS_BEARER_TOKEN_BEDROCK", "env-api-key") |
| 246 |
with pytest.raises(ValueError, match="Cannot specify both"): |
| 247 |
AnthropicBedrock( |
| 248 |
aws_region="us-east-1", |
| 249 |
aws_access_key="example-access-key", |
| 250 |
) |
| 251 |
|
| 252 |
|
| 253 |
def test_region_infer_from_profile( |
| 254 |
mock_aws_config: None, # noqa: ARG001 |
| 255 |
profiles: t.List[AwsConfigProfile], |
| 256 |
) -> None: |
| 257 |
client = AnthropicBedrock() |
| 258 |
assert client.aws_region == profiles[0]["region"] |
| 259 |
|
| 260 |
|
| 261 |
@pytest.mark.parametrize( |
| 262 |
"profiles, aws_profile", |
| 263 |
[ |
| 264 |
pytest.param([{"name": "default", "region": "us-east-2"}], "default", id="default profile"), |
| 265 |
pytest.param( |
| 266 |
[{"name": "default", "region": "us-east-2"}, {"name": "custom", "region": "us-west-1"}], |
| 267 |
"custom", |
| 268 |
id="custom profile", |
| 269 |
), |
| 270 |
], |
| 271 |
) |
| 272 |
def test_region_infer_from_specified_profile( |
| 273 |
mock_aws_config: None, # noqa: ARG001 |
| 274 |
profiles: t.List[AwsConfigProfile], |
| 275 |
aws_profile: str, |
| 276 |
monkeypatch: t.Any, |
| 277 |
) -> None: |
| 278 |
monkeypatch.setenv("AWS_PROFILE", aws_profile) |
| 279 |
client = AnthropicBedrock() |
| 280 |
|
| 281 |
assert client.aws_region == next(profile for profile in profiles if profile["name"] == aws_profile)["region"] |
| 282 |
|
| 283 |
|
| 284 |
@pytest.mark.parametrize( |
| 285 |
"profiles", |
| 286 |
[[{"name": "default", "region": "us-east-2"}, {"name": "custom", "region": "us-west-1"}]], |
| 287 |
) |
| 288 |
def test_region_infer_from_aws_profile_argument( |
| 289 |
mock_aws_config: None, # noqa: ARG001 |
| 290 |
monkeypatch: t.Any, |
| 291 |
) -> None: |
| 292 |
monkeypatch.delenv("AWS_PROFILE", raising=False) |
| 293 |
client = AnthropicBedrock(aws_profile="custom") |
| 294 |
|
| 295 |
assert client.aws_region == "us-west-1" |
| 296 |
|
| 297 |
|
| 298 |
@pytest.mark.parametrize("profiles", [[]]) |
| 299 |
def test_region_is_required( |
| 300 |
mock_aws_config: None, # noqa: ARG001 |
| 301 |
monkeypatch: t.Any, |
| 302 |
) -> None: |
| 303 |
for name in ("AWS_REGION", "AWS_DEFAULT_REGION", "AWS_PROFILE"): |
| 304 |
monkeypatch.delenv(name, raising=False) |
| 305 |
monkeypatch.setenv("AWS_EC2_METADATA_DISABLED", "true") |
| 306 |
|
| 307 |
with pytest.raises(ValueError, match="No AWS region was provided"): |
| 308 |
AnthropicBedrock() |
| 309 |
|
| 310 |
with pytest.raises(ValueError, match="No AWS region was provided"): |
| 311 |
AsyncAnthropicBedrock(api_key="test-api-key") |
| 312 |
|
| 313 |
# an explicit region always wins and skips inference entirely |
| 314 |
assert AnthropicBedrock(aws_region="eu-west-1").aws_region == "eu-west-1" |
| 315 |
|
| 316 |
|
| 317 |
def test_chunk_bytes_to_sse_typed_event() -> None: |
| 318 |
raw = ( |
| 319 |
b'{"type":"message_start","message":{"id":"msg_123","type":"message","role":"assistant",' |
| 320 |
b'"content":[],"model":"claude-x","stop_reason":null,"stop_sequence":null,' |
| 321 |
b'"usage":{"input_tokens":1,"output_tokens":1}}}' |
| 322 |
) |
| 323 |
sse = _chunk_bytes_to_sse(raw) |
| 324 |
assert sse is not None |
| 325 |
assert sse.event == "message_start" |
| 326 |
assert sse.data == raw.decode() |
| 327 |
|
| 328 |
|
| 329 |
def test_chunk_bytes_to_sse_legacy_completion() -> None: |
| 330 |
raw = b'{"completion":" Hello","stop_reason":null,"model":"claude-2"}' |
| 331 |
sse = _chunk_bytes_to_sse(raw) |
| 332 |
assert sse is not None |
| 333 |
assert sse.event == "completion" |
| 334 |
|
| 335 |
|
| 336 |
def test_chunk_bytes_to_sse_legacy_completion_with_metrics() -> None: |
| 337 |
raw = ( |
| 338 |
b'{"completion":" Hello","stop_reason":"stop_sequence","model":"claude-2",' |
| 339 |
b'"amazon-bedrock-invocationMetrics":{"inputTokenCount":1,"outputTokenCount":1}}' |
| 340 |
) |
| 341 |
sse = _chunk_bytes_to_sse(raw) |
| 342 |
assert sse is not None |
| 343 |
assert sse.event == "completion" |
| 344 |
|
| 345 |
|
| 346 |
def test_chunk_bytes_to_sse_drops_chunk_without_type_or_completion() -> None: |
| 347 |
raw = b'{"amazon-bedrock-invocationMetrics":{"inputTokenCount":1,"outputTokenCount":1}}' |
| 348 |
assert _chunk_bytes_to_sse(raw) is None |
| 349 |
|
| 350 |
|
| 351 |
def _eventstream_chunk_frame(payload: t.Mapping[str, object]) -> bytes: |
| 352 |
"""Encode `payload` as one `chunk` event in AWS eventstream binary framing.""" |
| 353 |
body = json.dumps({"bytes": base64.b64encode(json.dumps(payload).encode()).decode()}).encode() |
| 354 |
return _eventstream_frame( |
| 355 |
{":message-type": "event", ":event-type": "chunk", ":content-type": "application/json"}, body |
| 356 |
) |
| 357 |
|
| 358 |
|
| 359 |
def _eventstream_frame(header_values: t.Mapping[str, str], body: bytes) -> bytes: |
| 360 |
headers = b"" |
| 361 |
for name, value in header_values.items(): |
| 362 |
headers += bytes([len(name)]) + name.encode() + b"\x07" + struct.pack(">H", len(value)) + value.encode() |
| 363 |
prelude = struct.pack(">II", 12 + len(headers) + len(body) + 4, len(headers)) |
| 364 |
prelude += struct.pack(">I", binascii.crc32(prelude) & 0xFFFFFFFF) |
| 365 |
message = prelude + headers + body |
| 366 |
return message + struct.pack(">I", binascii.crc32(message) & 0xFFFFFFFF) |
| 367 |
|
| 368 |
|
| 369 |
_INVOCATION_METRICS = {"inputTokenCount": 5, "outputTokenCount": 3, "invocationLatency": 500, "firstByteLatency": 100} |
| 370 |
_TYPELESS_CHUNK_STREAM: t.List[t.Dict[str, object]] = [ |
| 371 |
{ |
| 372 |
"type": "message_start", |
| 373 |
"message": { |
| 374 |
"id": "msg_1", |
| 375 |
"type": "message", |
| 376 |
"role": "assistant", |
| 377 |
"content": [], |
| 378 |
"model": "claude", |
| 379 |
"stop_reason": None, |
| 380 |
"stop_sequence": None, |
| 381 |
"usage": {"input_tokens": 5, "output_tokens": 1}, |
| 382 |
}, |
| 383 |
}, |
| 384 |
# no `type` and no `completion`: there is no event name to route this by |
| 385 |
{"amazon-bedrock-invocationMetrics": _INVOCATION_METRICS}, |
| 386 |
{"type": "message_stop", "amazon-bedrock-invocationMetrics": _INVOCATION_METRICS}, |
| 387 |
] |
| 388 |
_STREAM_WITH_TYPELESS_CHUNK = b"".join(_eventstream_chunk_frame(payload) for payload in _TYPELESS_CHUNK_STREAM) |
| 389 |
_STREAM_URL = re.compile(r"https://bedrock-runtime\.us-east-1\.amazonaws\.com/model/.*/invoke-with-response-stream") |
| 390 |
|
| 391 |
|
| 392 |
@pytest.mark.respx() |
| 393 |
def test_stream_skips_typeless_chunk(respx_mock: MockRouter) -> None: |
| 394 |
respx_mock.post(_STREAM_URL).mock( |
| 395 |
return_value=httpx2.Response( |
| 396 |
200, content=_STREAM_WITH_TYPELESS_CHUNK, headers={"content-type": "application/vnd.amazon.eventstream"} |
| 397 |
) |
| 398 |
) |
| 399 |
stream = sync_client.messages.create( |
| 400 |
max_tokens=8, messages=[{"role": "user", "content": "hi"}], model="anthropic.claude-x", stream=True |
| 401 |
) |
| 402 |
events = list(stream) |
| 403 |
|
| 404 |
assert [e.type for e in events] == ["message_start", "message_stop"] |
| 405 |
assert events[0].type == "message_start" and events[0].message.id == "msg_1" |
| 406 |
assert events[1].to_dict()["amazon-bedrock-invocationMetrics"] == _INVOCATION_METRICS |
| 407 |
|
| 408 |
|
| 409 |
@pytest.mark.respx() |
| 410 |
@pytest.mark.asyncio() |
| 411 |
async def test_stream_skips_typeless_chunk_async(respx_mock: MockRouter) -> None: |
| 412 |
respx_mock.post(_STREAM_URL).mock( |
| 413 |
return_value=httpx2.Response( |
| 414 |
200, content=_STREAM_WITH_TYPELESS_CHUNK, headers={"content-type": "application/vnd.amazon.eventstream"} |
| 415 |
) |
| 416 |
) |
| 417 |
stream = await async_client.messages.create( |
| 418 |
max_tokens=8, messages=[{"role": "user", "content": "hi"}], model="anthropic.claude-x", stream=True |
| 419 |
) |
| 420 |
events = [e async for e in stream] |
| 421 |
|
| 422 |
assert [e.type for e in events] == ["message_start", "message_stop"] |
| 423 |
assert events[0].type == "message_start" and events[0].message.id == "msg_1" |
| 424 |
assert events[1].to_dict()["amazon-bedrock-invocationMetrics"] == _INVOCATION_METRICS |
| 425 |
|
| 426 |
|
| 427 |
_THROTTLING_MESSAGE = "Too many requests, please wait before trying again." |
| 428 |
_EXCEPTION_FRAME = _eventstream_frame( |
| 429 |
{":message-type": "exception", ":exception-type": "throttlingException", ":content-type": "application/json"}, |
| 430 |
json.dumps({"message": _THROTTLING_MESSAGE}).encode(), |
| 431 |
) |
| 432 |
_ERROR_FRAME = _eventstream_frame( |
| 433 |
{":message-type": "error", ":error-code": "InternalFailure", ":error-message": "Something went wrong."}, b"" |
| 434 |
) |
| 435 |
|
| 436 |
|
| 437 |
@pytest.mark.respx() |
| 438 |
@pytest.mark.asyncio() |
| 439 |
@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) |
| 440 |
@pytest.mark.parametrize( |
| 441 |
"frame, error", |
| 442 |
[ |
| 443 |
(_EXCEPTION_FRAME, {"type": "throttlingException", "message": _THROTTLING_MESSAGE}), |
| 444 |
(_ERROR_FRAME, {"type": "InternalFailure", "message": "Something went wrong."}), |
| 445 |
], |
| 446 |
ids=["exception", "error"], |
| 447 |
) |
| 448 |
async def test_stream_raises_api_error_for_error_frame( |
| 449 |
frame: bytes, error: t.Dict[str, str], sync: bool, respx_mock: MockRouter |
| 450 |
) -> None: |
| 451 |
respx_mock.post(_STREAM_URL).mock( |
| 452 |
return_value=httpx2.Response( |
| 453 |
200, |
| 454 |
content=_eventstream_chunk_frame(_TYPELESS_CHUNK_STREAM[0]) + frame, |
| 455 |
headers={"content-type": "application/vnd.amazon.eventstream"}, |
| 456 |
) |
| 457 |
) |
| 458 |
received: t.List[str] = [] |
| 459 |
|
| 460 |
with pytest.raises(APIStatusError) as exc_info: |
| 461 |
if sync: |
| 462 |
for event in sync_client.messages.create( |
| 463 |
max_tokens=8, messages=[{"role": "user", "content": "hi"}], model="anthropic.claude-x", stream=True |
| 464 |
): |
| 465 |
received.append(event.type) |
| 466 |
else: |
| 467 |
async for event in await async_client.messages.create( |
| 468 |
max_tokens=8, messages=[{"role": "user", "content": "hi"}], model="anthropic.claude-x", stream=True |
| 469 |
): |
| 470 |
received.append(event.type) |
| 471 |
|
| 472 |
assert received == ["message_start"] |
| 473 |
assert exc_info.type is APIStatusError |
| 474 |
assert exc_info.value.body == {"type": "error", "error": error} |
| 475 |
|
| 476 |
|
| 477 |
@pytest.mark.respx() |
| 478 |
@pytest.mark.asyncio() |
| 479 |
@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) |
| 480 |
async def test_sigv4_signs_binary_body(sync: bool, respx_mock: MockRouter) -> None: |
| 481 |
respx_mock.post("https://bedrock-runtime.us-east-1.amazonaws.com/foo").mock( |
| 482 |
return_value=httpx2.Response(200, json={}) |
| 483 |
) |
| 484 |
content = b"\x89PNG\r\n\x1a\n\x00\xff\xfe" |
| 485 |
|
| 486 |
if sync: |
| 487 |
sync_client.post("/foo", content=content, cast_to=httpx2.Response) |
| 488 |
else: |
| 489 |
await async_client.post("/foo", content=content, cast_to=httpx2.Response) |
| 490 |
|
| 491 |
calls = cast("list[MockRequestCall]", respx_mock.calls) |
| 492 |
assert len(calls) == 1 |
| 493 |
assert calls[0].request.content == content |
| 494 |
assert calls[0].request.headers["Authorization"].startswith("AWS4-HMAC-SHA256 ") |
| 495 |
|
| 496 |
|
| 497 |
def test_copy_x_stainless_helper_header_appends() -> None: |
| 498 |
# `x-stainless-helper` accumulates across copies instead of being clobbered |
| 499 |
client = sync_client.with_options(default_headers={"x-stainless-helper": "parent"}) |
| 500 |
copied = client.with_options(default_headers={"x-stainless-helper": "child"}) |
| 501 |
assert copied.default_headers["x-stainless-helper"] == "parent, child" |
| 502 |
|
| 503 |
|
| 504 |
def test_async_copy_x_stainless_helper_header_appends() -> None: |
| 505 |
# `x-stainless-helper` accumulates across copies instead of being clobbered |
| 506 |
client = async_client.with_options(default_headers={"x-stainless-helper": "parent"}) |
| 507 |
copied = client.with_options(default_headers={"x-stainless-helper": "child"}) |
| 508 |
assert copied.default_headers["x-stainless-helper"] == "parent, child" |
| 509 |
|
| 510 |
|
| 511 |
def _bedrock_message(content: t.List[t.Dict[str, t.Any]], stop_reason: str) -> httpx2.Response: |
| 512 |
return httpx2.Response( |
| 513 |
200, |
| 514 |
json={ |
| 515 |
"id": "msg_01", |
| 516 |
"type": "message", |
| 517 |
"role": "assistant", |
| 518 |
"model": "claude", |
| 519 |
"content": content, |
| 520 |
"stop_reason": stop_reason, |
| 521 |
"stop_sequence": None, |
| 522 |
"usage": {"input_tokens": 10, "output_tokens": 5}, |
| 523 |
}, |
| 524 |
) |
| 525 |
|
| 526 |
|
| 527 |
def _tool_runner_responses() -> t.List[httpx2.Response]: |
| 528 |
return [ |
| 529 |
_bedrock_message( |
| 530 |
[{"type": "tool_use", "id": "toolu_01", "name": "get_weather", "input": {"city": "Paris"}}], |
| 531 |
"tool_use", |
| 532 |
), |
| 533 |
_bedrock_message([{"type": "text", "text": "It is sunny in Paris."}], "end_turn"), |
| 534 |
] |
| 535 |
|
| 536 |
|
| 537 |
def _assert_tool_runner_calls(calls: t.List[MockRequestCall]) -> None: |
| 538 |
assert len(calls) == 2 |
| 539 |
for call in calls: |
| 540 |
assert call.request.url.path == "/model/anthropic.claude-haiku-4-5-20251001-v1:0/invoke" |
| 541 |
assert call.request.headers["Authorization"].startswith("AWS4-HMAC-SHA256 ") |
| 542 |
assert "x-amz-date" in call.request.headers |
| 543 |
body = json.loads(call.request.content) |
| 544 |
assert "model" not in body and "stream" not in body and "output_format" not in body |
| 545 |
assert body["anthropic_version"] == "bedrock-2023-05-31" |
| 546 |
second = json.loads(calls[1].request.content) |
| 547 |
assert [m["role"] for m in second["messages"]] == ["user", "assistant", "user"] |
| 548 |
assert second["messages"][1]["content"][0]["type"] == "tool_use" |
| 549 |
assert second["messages"][2]["content"][0] == { |
| 550 |
"type": "tool_result", |
| 551 |
"tool_use_id": "toolu_01", |
| 552 |
"content": "sunny in Paris", |
| 553 |
} |
| 554 |
|
| 555 |
|
| 556 |
@pytest.mark.skipif(PYDANTIC_V1, reason="tool functions are only supported with pydantic v2") |
| 557 |
@pytest.mark.respx() |
| 558 |
def test_beta_tool_runner_routes_through_invoke(respx_mock: MockRouter) -> None: |
| 559 |
@beta_tool |
| 560 |
def get_weather(city: str) -> str: |
| 561 |
"""Get the weather. |
| 562 |
|
| 563 |
Args: |
| 564 |
city: city name |
| 565 |
""" |
| 566 |
return f"sunny in {city}" |
| 567 |
|
| 568 |
respx_mock.post(re.compile(r"https://bedrock-runtime\.us-east-1\.amazonaws\.com/model/.*")).mock( |
| 569 |
side_effect=_tool_runner_responses() |
| 570 |
) |
| 571 |
|
| 572 |
final = sync_client.beta.messages.tool_runner( |
| 573 |
model="anthropic.claude-haiku-4-5-20251001-v1:0", |
| 574 |
max_tokens=256, |
| 575 |
messages=[{"role": "user", "content": "weather in Paris?"}], |
| 576 |
tools=[get_weather], |
| 577 |
).until_done() |
| 578 |
|
| 579 |
assert final.stop_reason == "end_turn" |
| 580 |
_assert_tool_runner_calls(cast("list[MockRequestCall]", respx_mock.calls)) |
| 581 |
|
| 582 |
|
| 583 |
@pytest.mark.skipif(PYDANTIC_V1, reason="tool functions are only supported with pydantic v2") |
| 584 |
@pytest.mark.respx() |
| 585 |
@pytest.mark.asyncio() |
| 586 |
async def test_beta_tool_runner_routes_through_invoke_async(respx_mock: MockRouter) -> None: |
| 587 |
@beta_async_tool |
| 588 |
async def get_weather(city: str) -> str: |
| 589 |
"""Get the weather. |
| 590 |
|
| 591 |
Args: |
| 592 |
city: city name |
| 593 |
""" |
| 594 |
return f"sunny in {city}" |
| 595 |
|
| 596 |
respx_mock.post(re.compile(r"https://bedrock-runtime\.us-east-1\.amazonaws\.com/model/.*")).mock( |
| 597 |
side_effect=_tool_runner_responses() |
| 598 |
) |
| 599 |
|
| 600 |
final = await async_client.beta.messages.tool_runner( |
| 601 |
model="anthropic.claude-haiku-4-5-20251001-v1:0", |
| 602 |
max_tokens=256, |
| 603 |
messages=[{"role": "user", "content": "weather in Paris?"}], |
| 604 |
tools=[get_weather], |
| 605 |
).until_done() |
| 606 |
|
| 607 |
assert final.stop_reason == "end_turn" |
| 608 |
_assert_tool_runner_calls(cast("list[MockRequestCall]", respx_mock.calls)) |
| 609 |
|
| 610 |
|
| 611 |
def test_beta_messages_helpers_are_bound() -> None: |
| 612 |
for client in (sync_client, async_client): |
| 613 |
for name in ("create", "parse", "stream", "tool_runner"): |
| 614 |
assert callable(getattr(client.beta.messages, name)) |
| 615 |
|
| 616 |
|
| 617 |
@pytest.mark.asyncio() |
| 618 |
async def test_sigv4_signing_runs_off_event_loop_async(monkeypatch: pytest.MonkeyPatch) -> None: |
| 619 |
signing_threads: t.List[int] = [] |
| 620 |
|
| 621 |
def fake_get_auth_headers(**_: object) -> t.Dict[str, str]: |
| 622 |
signing_threads.append(threading.get_ident()) |
| 623 |
return {"Authorization": "AWS4-HMAC-SHA256 stub"} |
| 624 |
|
| 625 |
monkeypatch.setattr("anthropic.lib.bedrock._auth.get_auth_headers", fake_get_auth_headers) |
| 626 |
|
| 627 |
request = httpx2.Request("POST", "https://bedrock-runtime.us-east-1.amazonaws.com/model/x/invoke", content=b"{}") |
| 628 |
await async_client._prepare_request(request) |
| 629 |
|
| 630 |
assert len(signing_threads) == 1 |
| 631 |
assert signing_threads[0] != threading.get_ident() |
| 632 |
assert request.headers["Authorization"] == "AWS4-HMAC-SHA256 stub" |
| 633 |
|
| 634 |
|
| 635 |
def test_prepare_options_lifts_anthropic_beta_header_case_insensitively() -> None: |
| 636 |
# Bedrock takes betas in the request body |
| 637 |
options = _prepare_options( |
| 638 |
FinalRequestOptions( |
| 639 |
method="post", |
| 640 |
url="/v1/messages", |
| 641 |
json_data={"model": "anthropic.claude-sonnet-4-5"}, |
| 642 |
headers={"Anthropic-Beta": "context-1m-2025-08-07,other-beta"}, |
| 643 |
) |
| 644 |
) |
| 645 |
|
| 646 |
assert cast("dict[str, object]", options.json_data).get("anthropic_beta") == [ |
| 647 |
"context-1m-2025-08-07", |
| 648 |
"other-beta", |
| 649 |
] |
| 650 |
|
| 651 |
|
| 652 |
@pytest.mark.respx() |
| 653 |
def test_betas_param_and_extra_headers_case_variant(respx_mock: MockRouter) -> None: |
| 654 |
# `extra_headers` overrides the header written by `betas`, on the wire and in the body |
| 655 |
respx_mock.post(re.compile(r"https://bedrock-runtime\.us-east-1\.amazonaws\.com/model/.*/invoke")).mock( |
| 656 |
return_value=httpx2.Response(200, json={"foo": "bar"}) |
| 657 |
) |
| 658 |
|
| 659 |
sync_api_key_client.beta.messages.create( |
| 660 |
max_tokens=1024, |
| 661 |
messages=[{"role": "user", "content": "Say hello there!"}], |
| 662 |
model="anthropic.claude-3-5-sonnet-20241022-v2:0", |
| 663 |
betas=["from-betas-param"], |
| 664 |
extra_headers={"Anthropic-Beta": "from-extra-headers"}, |
| 665 |
) |
| 666 |
|
| 667 |
calls = cast("list[MockRequestCall]", respx_mock.calls) |
| 668 |
assert len(calls) == 1 |
| 669 |
assert calls[0].request.headers.get_list("anthropic-beta") == ["from-extra-headers"] |
| 670 |
assert json.loads(calls[0].request.content)["anthropic_beta"] == ["from-extra-headers"] |