| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import os |
| 4 |
import json |
| 5 |
from typing import Any, Set, TypeVar, Iterator, cast |
| 6 |
|
| 7 |
import httpx2 |
| 8 |
import pytest |
| 9 |
from respx import MockRouter |
| 10 |
|
| 11 |
from anthropic import Stream, Anthropic, AsyncStream, AsyncAnthropic |
| 12 |
from anthropic._utils import assert_signatures_in_sync |
| 13 |
from anthropic._compat import PYDANTIC_V1, get_model_fields |
| 14 |
from anthropic.lib.streaming import InputJsonEvent, ParsedMessageStreamEvent |
| 15 |
from anthropic.types.message import Message |
| 16 |
from anthropic.resources.messages import DEPRECATED_MODELS |
| 17 |
from anthropic.lib.streaming._messages import TRACKS_TOOL_INPUT |
| 18 |
from anthropic.types.message_delta_usage import MessageDeltaUsage |
| 19 |
from anthropic.types.raw_message_delta_event import Delta as RawMessageDelta, RawMessageDeltaEvent |
| 20 |
|
| 21 |
from .helpers import get_response, to_async_iter |
| 22 |
|
| 23 |
base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") |
| 24 |
api_key = "my-anthropic-api-key" |
| 25 |
|
| 26 |
sync_client = Anthropic(base_url=base_url, api_key=api_key, _strict_response_validation=True) |
| 27 |
async_client = AsyncAnthropic(base_url=base_url, api_key=api_key, _strict_response_validation=True) |
| 28 |
|
| 29 |
_T = TypeVar("_T") |
| 30 |
|
| 31 |
# the accumulator must wrap the raw parser error with context and echo the offending JSON |
| 32 |
INVALID_TOOL_JSON_ERROR = ( |
| 33 |
r"^Unable to parse tool parameter JSON from model\. Please retry your request or adjust your prompt\. " |
| 34 |
r'Error: .+\. JSON: \{"location": "Paris", "unit": celsius\}$' |
| 35 |
) |
| 36 |
|
| 37 |
|
| 38 |
FOLLOW_UP_MESSAGE = { |
| 39 |
"id": "msg_01FollowUp", |
| 40 |
"type": "message", |
| 41 |
"role": "assistant", |
| 42 |
"model": "claude-sonnet-4-5", |
| 43 |
"content": [{"type": "text", "text": "It is sunny in Paris."}], |
| 44 |
"stop_reason": "end_turn", |
| 45 |
"stop_sequence": None, |
| 46 |
"usage": {"input_tokens": 400, "output_tokens": 10}, |
| 47 |
} |
| 48 |
|
| 49 |
EXPECTED_TOOL_USE_PARAM = { |
| 50 |
"type": "tool_use", |
| 51 |
"id": "toolu_01NRLabsLyVHZPKxbKvkfSMn", |
| 52 |
"name": "get_weather", |
| 53 |
"input": {"location": "Paris"}, |
| 54 |
"caller": {"type": "direct"}, |
| 55 |
} |
| 56 |
|
| 57 |
|
| 58 |
def assert_basic_response(events: list[ParsedMessageStreamEvent[None]], message: Message) -> None: |
| 59 |
assert message.id == "msg_4QpJur2dWWDjF6C758FbBw5vm12BaVipnK" |
| 60 |
assert message.model == "claude-3-opus-latest" |
| 61 |
assert message.role == "assistant" |
| 62 |
assert message.stop_reason == "end_turn" |
| 63 |
assert message.stop_sequence is None |
| 64 |
assert message.type == "message" |
| 65 |
assert len(message.content) == 1 |
| 66 |
|
| 67 |
content = message.content[0] |
| 68 |
assert content.type == "text" |
| 69 |
assert content.text == "Hello there!" |
| 70 |
# accumulated blocks must serialize like a non-streaming response: keys the API didn't send stay unset |
| 71 |
assert content.to_dict() == {"type": "text", "text": "Hello there!"} |
| 72 |
|
| 73 |
assert [e.type for e in events] == [ |
| 74 |
"message_start", |
| 75 |
"content_block_start", |
| 76 |
"content_block_delta", |
| 77 |
"text", |
| 78 |
"content_block_delta", |
| 79 |
"text", |
| 80 |
"content_block_delta", |
| 81 |
"text", |
| 82 |
"content_block_stop", |
| 83 |
"message_delta", |
| 84 |
] |
| 85 |
|
| 86 |
|
| 87 |
def assert_tool_use_response(events: list[ParsedMessageStreamEvent[None]], message: Message) -> None: |
| 88 |
assert message.id == "msg_019Q1hrJbZG26Fb9BQhrkHEr" |
| 89 |
assert message.model == "claude-sonnet-4-20250514" |
| 90 |
assert message.role == "assistant" |
| 91 |
assert message.stop_reason == "tool_use" |
| 92 |
assert message.stop_sequence is None |
| 93 |
assert message.type == "message" |
| 94 |
assert len(message.content) == 2 |
| 95 |
|
| 96 |
content = message.content[0] |
| 97 |
assert content.type == "text" |
| 98 |
assert content.text == "I'll check the current weather in Paris for you." |
| 99 |
|
| 100 |
tool_use = message.content[1] |
| 101 |
assert tool_use.type == "tool_use" |
| 102 |
assert tool_use.id == "toolu_01NRLabsLyVHZPKxbKvkfSMn" |
| 103 |
assert tool_use.name == "get_weather" |
| 104 |
assert tool_use.input == { |
| 105 |
"location": "Paris", |
| 106 |
} |
| 107 |
|
| 108 |
assert message.usage.input_tokens == 377 |
| 109 |
assert message.usage.output_tokens == 65 |
| 110 |
assert message.usage.cache_creation_input_tokens == 0 |
| 111 |
assert message.usage.cache_read_input_tokens == 0 |
| 112 |
assert message.usage.service_tier == "standard" |
| 113 |
assert message.usage.server_tool_use == None |
| 114 |
|
| 115 |
assert [e.type for e in events] == [ |
| 116 |
"message_start", |
| 117 |
"content_block_start", |
| 118 |
"content_block_delta", |
| 119 |
"text", |
| 120 |
"content_block_delta", |
| 121 |
"text", |
| 122 |
"content_block_stop", |
| 123 |
"content_block_start", |
| 124 |
"content_block_delta", |
| 125 |
"input_json", |
| 126 |
"content_block_delta", |
| 127 |
"input_json", |
| 128 |
"content_block_delta", |
| 129 |
"input_json", |
| 130 |
"content_block_delta", |
| 131 |
"input_json", |
| 132 |
"content_block_delta", |
| 133 |
"input_json", |
| 134 |
"content_block_stop", |
| 135 |
"message_delta", |
| 136 |
] |
| 137 |
|
| 138 |
|
| 139 |
def assert_server_tool_use_response(events: list[ParsedMessageStreamEvent[None]], message: Message) -> None: |
| 140 |
assert [e.type for e in events] == [ |
| 141 |
"message_start", |
| 142 |
"content_block_start", |
| 143 |
*["content_block_delta", "input_json"] * 6, |
| 144 |
"content_block_stop", |
| 145 |
"content_block_start", |
| 146 |
"content_block_stop", |
| 147 |
"content_block_start", |
| 148 |
"content_block_delta", |
| 149 |
"citation", |
| 150 |
"content_block_delta", |
| 151 |
"text", |
| 152 |
"content_block_delta", |
| 153 |
"text", |
| 154 |
"content_block_stop", |
| 155 |
"message_delta", |
| 156 |
] |
| 157 |
|
| 158 |
server_tool_use = message.content[0] |
| 159 |
assert server_tool_use.type == "server_tool_use" |
| 160 |
assert server_tool_use.input == {"query": "anthropic claude release notes"} |
| 161 |
|
| 162 |
# input_json events must fire for server_tool_use blocks, not just client tool_use |
| 163 |
input_json_events = [e for e in events if isinstance(e, InputJsonEvent)] |
| 164 |
assert [e.partial_json for e in input_json_events] == [ |
| 165 |
"", |
| 166 |
'{"query": "', |
| 167 |
"anthropic cl", |
| 168 |
"aude re", |
| 169 |
"lease notes", |
| 170 |
'"}', |
| 171 |
] |
| 172 |
assert input_json_events[-1].snapshot == {"query": "anthropic claude release notes"} |
| 173 |
|
| 174 |
|
| 175 |
def get_tool_use_response_without_caller() -> Iterator[bytes]: |
| 176 |
return (line.replace(b'"caller":{"type":"direct"},', b"") for line in get_response("tool_use_response.txt")) |
| 177 |
|
| 178 |
|
| 179 |
def assert_tool_use_caller_unset(message: Message) -> None: |
| 180 |
tool_use = message.content[1] |
| 181 |
assert tool_use.type == "tool_use" |
| 182 |
assert tool_use.input == {"location": "Paris"} |
| 183 |
assert tool_use.caller is None |
| 184 |
# an omitted `caller` must stay unset so it doesn't round-trip as `"caller": null`, which the API rejects |
| 185 |
assert "caller" not in tool_use.model_fields_set |
| 186 |
assert "caller" not in tool_use.to_dict() |
| 187 |
|
| 188 |
|
| 189 |
def assert_refusal_response(message: Message) -> None: |
| 190 |
assert message.stop_reason == "refusal" |
| 191 |
assert message.stop_details is not None |
| 192 |
assert message.stop_details.type == "refusal" |
| 193 |
assert message.stop_details.category == "cyber" |
| 194 |
assert message.stop_details.explanation == "This request was refused due to policy." |
| 195 |
|
| 196 |
|
| 197 |
def assert_message_delta_fields_response(message: Message) -> None: |
| 198 |
# every field the final `message_delta` carried must land on the accumulated message |
| 199 |
assert message.container is not None |
| 200 |
assert message.container.id == "container_01AbCdEfGh" |
| 201 |
assert message.usage.output_tokens == 8 |
| 202 |
assert message.usage.input_tokens == 40 |
| 203 |
assert message.usage.cache_creation_input_tokens == 12 |
| 204 |
assert message.usage.cache_read_input_tokens == 7 |
| 205 |
assert message.usage.output_tokens_details is not None |
| 206 |
assert message.usage.output_tokens_details.thinking_tokens == 3 |
| 207 |
assert message.usage.server_tool_use is not None |
| 208 |
assert message.usage.server_tool_use.web_search_requests == 1 |
| 209 |
# never re-sent on `message_delta`, so these must survive from `message_start` |
| 210 |
assert message.usage.service_tier == "standard" |
| 211 |
assert message.usage.cache_creation is not None |
| 212 |
assert message.usage.cache_creation.ephemeral_5m_input_tokens == 10 |
| 213 |
|
| 214 |
|
| 215 |
def assert_message_delta_omitted_usage_response(message: Message) -> None: |
| 216 |
# the delta omitted every optional usage key, so the `message_start` values stand |
| 217 |
assert message.usage.output_tokens == 8 |
| 218 |
assert message.usage.input_tokens == 25 |
| 219 |
assert message.usage.cache_creation_input_tokens == 10 |
| 220 |
assert message.usage.cache_read_input_tokens == 5 |
| 221 |
assert message.usage.service_tier == "priority" |
| 222 |
assert message.usage.cache_creation is not None |
| 223 |
assert message.usage.cache_creation.ephemeral_5m_input_tokens == 10 |
| 224 |
assert message.container is None |
| 225 |
|
| 226 |
|
| 227 |
class TestSyncMessages: |
| 228 |
@pytest.mark.respx(base_url=base_url) |
| 229 |
def test_basic_response(self, respx_mock: MockRouter) -> None: |
| 230 |
respx_mock.post("/v1/messages").mock( |
| 231 |
return_value=httpx2.Response(200, content=get_response("basic_response.txt")) |
| 232 |
) |
| 233 |
|
| 234 |
with sync_client.messages.stream( |
| 235 |
max_tokens=1024, |
| 236 |
messages=[ |
| 237 |
{ |
| 238 |
"role": "user", |
| 239 |
"content": "Say hello there!", |
| 240 |
} |
| 241 |
], |
| 242 |
model="claude-3-opus-latest", |
| 243 |
) as stream: |
| 244 |
assert not isinstance(cast(Any, stream), Stream) |
| 245 |
|
| 246 |
assert_basic_response([event for event in stream], stream.get_final_message()) |
| 247 |
|
| 248 |
@pytest.mark.respx(base_url=base_url) |
| 249 |
def test_context_manager(self, respx_mock: MockRouter) -> None: |
| 250 |
respx_mock.post("/v1/messages").mock( |
| 251 |
return_value=httpx2.Response( |
| 252 |
200, |
| 253 |
headers={"request-id": "my-req-id", "anthropic-workspace-id": "wrkspc_123"}, |
| 254 |
content=get_response("basic_response.txt"), |
| 255 |
) |
| 256 |
) |
| 257 |
|
| 258 |
with sync_client.messages.stream( |
| 259 |
max_tokens=1024, |
| 260 |
messages=[ |
| 261 |
{ |
| 262 |
"role": "user", |
| 263 |
"content": "Say hello there!", |
| 264 |
} |
| 265 |
], |
| 266 |
model="claude-3-opus-latest", |
| 267 |
) as stream: |
| 268 |
assert not stream.response.is_closed |
| 269 |
assert stream.request_id == "my-req-id" |
| 270 |
assert stream.workspace_id == "wrkspc_123" |
| 271 |
|
| 272 |
# response should be closed even if the body isn't read |
| 273 |
assert stream.response.is_closed |
| 274 |
|
| 275 |
@pytest.mark.respx(base_url=base_url) |
| 276 |
def test_deprecated_model_warning_stream(self, respx_mock: MockRouter) -> None: |
| 277 |
for deprecated_model in DEPRECATED_MODELS: |
| 278 |
respx_mock.post("/v1/messages").mock( |
| 279 |
return_value=httpx2.Response(200, content=get_response("basic_response.txt")) |
| 280 |
) |
| 281 |
|
| 282 |
with pytest.warns(DeprecationWarning, match=f"The model '{deprecated_model}' is deprecated"): |
| 283 |
with sync_client.messages.stream( |
| 284 |
max_tokens=1024, |
| 285 |
messages=[{"role": "user", "content": "Hello"}], |
| 286 |
model=deprecated_model, |
| 287 |
) as stream: |
| 288 |
# Consume the stream to ensure the warning is triggered |
| 289 |
stream.until_done() |
| 290 |
|
| 291 |
@pytest.mark.respx(base_url=base_url) |
| 292 |
def test_tool_use(self, respx_mock: MockRouter) -> None: |
| 293 |
respx_mock.post("/v1/messages").mock( |
| 294 |
return_value=httpx2.Response(200, content=get_response("tool_use_response.txt")) |
| 295 |
) |
| 296 |
|
| 297 |
with sync_client.messages.stream( |
| 298 |
max_tokens=1024, |
| 299 |
messages=[ |
| 300 |
{ |
| 301 |
"role": "user", |
| 302 |
"content": "Say hello there!", |
| 303 |
} |
| 304 |
], |
| 305 |
model="claude-sonnet-4-5", |
| 306 |
) as stream: |
| 307 |
assert not isinstance(cast(Any, stream), Stream) |
| 308 |
|
| 309 |
assert_tool_use_response([event for event in stream], stream.get_final_message()) |
| 310 |
|
| 311 |
@pytest.mark.respx(base_url=base_url) |
| 312 |
def test_server_tool_use(self, respx_mock: MockRouter) -> None: |
| 313 |
respx_mock.post("/v1/messages").mock( |
| 314 |
return_value=httpx2.Response(200, content=get_response("server_tool_use_response.txt")) |
| 315 |
) |
| 316 |
|
| 317 |
with sync_client.messages.stream( |
| 318 |
max_tokens=1024, |
| 319 |
messages=[{"role": "user", "content": "Say hello there!"}], |
| 320 |
model="claude-sonnet-4-5", |
| 321 |
) as stream: |
| 322 |
assert_server_tool_use_response([event for event in stream], stream.get_final_message()) |
| 323 |
|
| 324 |
@pytest.mark.respx(base_url=base_url) |
| 325 |
def test_tool_use_invalid_json(self, respx_mock: MockRouter) -> None: |
| 326 |
respx_mock.post("/v1/messages").mock( |
| 327 |
return_value=httpx2.Response(200, content=get_response("tool_use_invalid_json_response.txt")) |
| 328 |
) |
| 329 |
|
| 330 |
with pytest.raises(ValueError, match=INVALID_TOOL_JSON_ERROR): |
| 331 |
with sync_client.messages.stream( |
| 332 |
max_tokens=1024, |
| 333 |
messages=[{"role": "user", "content": "What's the weather in Paris?"}], |
| 334 |
model="claude-sonnet-4-5", |
| 335 |
) as stream: |
| 336 |
stream.until_done() |
| 337 |
|
| 338 |
@pytest.mark.respx(base_url=base_url) |
| 339 |
def test_tool_use_caller_omitted(self, respx_mock: MockRouter) -> None: |
| 340 |
respx_mock.post("/v1/messages").mock( |
| 341 |
return_value=httpx2.Response(200, content=get_tool_use_response_without_caller()) |
| 342 |
) |
| 343 |
|
| 344 |
with sync_client.messages.stream( |
| 345 |
max_tokens=1024, |
| 346 |
messages=[{"role": "user", "content": "What is the weather in Paris?"}], |
| 347 |
model="claude-sonnet-4-5", |
| 348 |
) as stream: |
| 349 |
assert_tool_use_caller_unset(stream.get_final_message()) |
| 350 |
|
| 351 |
@pytest.mark.respx(base_url=base_url) |
| 352 |
def test_tool_use_round_trip(self, respx_mock: MockRouter) -> None: |
| 353 |
route = respx_mock.post("/v1/messages").mock( |
| 354 |
side_effect=[ |
| 355 |
httpx2.Response(200, content=get_response("tool_use_response.txt")), |
| 356 |
httpx2.Response(200, json=FOLLOW_UP_MESSAGE), |
| 357 |
] |
| 358 |
) |
| 359 |
|
| 360 |
with sync_client.messages.stream( |
| 361 |
max_tokens=1024, |
| 362 |
messages=[{"role": "user", "content": "What is the weather in Paris?"}], |
| 363 |
model="claude-sonnet-4-5", |
| 364 |
) as stream: |
| 365 |
message = stream.get_final_message() |
| 366 |
|
| 367 |
# accumulated blocks must be reusable as request params without leaking accumulator state |
| 368 |
sync_client.messages.create( |
| 369 |
max_tokens=1024, |
| 370 |
messages=[ |
| 371 |
{"role": "user", "content": "What is the weather in Paris?"}, |
| 372 |
{"role": "assistant", "content": message.content}, |
| 373 |
{ |
| 374 |
"role": "user", |
| 375 |
"content": [ |
| 376 |
{"type": "tool_result", "tool_use_id": "toolu_01NRLabsLyVHZPKxbKvkfSMn", "content": "Sunny"} |
| 377 |
], |
| 378 |
}, |
| 379 |
], |
| 380 |
model="claude-sonnet-4-5", |
| 381 |
) |
| 382 |
|
| 383 |
request_body = json.loads(route.calls.last.request.content) |
| 384 |
assert request_body["messages"][1]["content"][1] == EXPECTED_TOOL_USE_PARAM |
| 385 |
|
| 386 |
@pytest.mark.respx(base_url=base_url) |
| 387 |
def test_refusal_stop_details_propagated(self, respx_mock: MockRouter) -> None: |
| 388 |
respx_mock.post("/v1/messages").mock( |
| 389 |
return_value=httpx2.Response(200, content=get_response("refusal_response.txt")) |
| 390 |
) |
| 391 |
|
| 392 |
with sync_client.messages.stream( |
| 393 |
max_tokens=1024, |
| 394 |
messages=[{"role": "user", "content": "Say hello there!"}], |
| 395 |
model="claude-opus-4-7", |
| 396 |
) as stream: |
| 397 |
assert_refusal_response(stream.get_final_message()) |
| 398 |
|
| 399 |
@pytest.mark.respx(base_url=base_url) |
| 400 |
def test_message_delta_fields_propagated(self, respx_mock: MockRouter) -> None: |
| 401 |
respx_mock.post("/v1/messages").mock( |
| 402 |
return_value=httpx2.Response(200, content=get_response("message_delta_fields_response.txt")) |
| 403 |
) |
| 404 |
|
| 405 |
with sync_client.messages.stream( |
| 406 |
max_tokens=1024, |
| 407 |
messages=[{"role": "user", "content": "Say hello there!"}], |
| 408 |
model="claude-sonnet-4-5", |
| 409 |
) as stream: |
| 410 |
assert_message_delta_fields_response(stream.get_final_message()) |
| 411 |
|
| 412 |
@pytest.mark.respx(base_url=base_url) |
| 413 |
def test_message_delta_omitted_usage_keeps_message_start(self, respx_mock: MockRouter) -> None: |
| 414 |
respx_mock.post("/v1/messages").mock( |
| 415 |
return_value=httpx2.Response(200, content=get_response("message_delta_omitted_usage_response.txt")) |
| 416 |
) |
| 417 |
|
| 418 |
with sync_client.messages.stream( |
| 419 |
max_tokens=1024, |
| 420 |
messages=[{"role": "user", "content": "Say hello there!"}], |
| 421 |
model="claude-sonnet-4-5", |
| 422 |
) as stream: |
| 423 |
assert_message_delta_omitted_usage_response(stream.get_final_message()) |
| 424 |
|
| 425 |
@pytest.mark.respx(base_url=base_url) |
| 426 |
@pytest.mark.filterwarnings("error") |
| 427 |
def test_message_stop_event_serialization(self, respx_mock: MockRouter) -> None: |
| 428 |
# trailing blank line terminates the final `message_stop` SSE so it is dispatched |
| 429 |
respx_mock.post("/v1/messages").mock( |
| 430 |
return_value=httpx2.Response(200, content=iter([*get_response("basic_response.txt"), b"\n"])) |
| 431 |
) |
| 432 |
|
| 433 |
with sync_client.messages.stream( |
| 434 |
max_tokens=1024, |
| 435 |
messages=[{"role": "user", "content": "Say hello there!"}], |
| 436 |
model="claude-opus-4-7", |
| 437 |
) as stream: |
| 438 |
stop_event = [event for event in stream][-1] |
| 439 |
|
| 440 |
assert stop_event.type == "message_stop" |
| 441 |
assert stop_event.message.content[0].type == "text" |
| 442 |
# must not emit `PydanticSerializationUnexpectedValue` warnings |
| 443 |
stop_event.model_dump() |
| 444 |
stop_event.model_dump_json() |
| 445 |
|
| 446 |
|
| 447 |
class TestAsyncMessages: |
| 448 |
@pytest.mark.asyncio |
| 449 |
@pytest.mark.respx(base_url=base_url) |
| 450 |
async def test_basic_response(self, respx_mock: MockRouter) -> None: |
| 451 |
respx_mock.post("/v1/messages").mock( |
| 452 |
return_value=httpx2.Response(200, content=to_async_iter(get_response("basic_response.txt"))) |
| 453 |
) |
| 454 |
|
| 455 |
async with async_client.messages.stream( |
| 456 |
max_tokens=1024, |
| 457 |
messages=[ |
| 458 |
{ |
| 459 |
"role": "user", |
| 460 |
"content": "Say hello there!", |
| 461 |
} |
| 462 |
], |
| 463 |
model="claude-3-opus-latest", |
| 464 |
) as stream: |
| 465 |
assert not isinstance(cast(Any, stream), AsyncStream) |
| 466 |
|
| 467 |
assert_basic_response([event async for event in stream], await stream.get_final_message()) |
| 468 |
|
| 469 |
@pytest.mark.asyncio |
| 470 |
@pytest.mark.respx(base_url=base_url) |
| 471 |
async def test_context_manager(self, respx_mock: MockRouter) -> None: |
| 472 |
respx_mock.post("/v1/messages").mock( |
| 473 |
return_value=httpx2.Response( |
| 474 |
200, |
| 475 |
headers={"request-id": "my-req-id", "anthropic-workspace-id": "wrkspc_123"}, |
| 476 |
content=to_async_iter(get_response("basic_response.txt")), |
| 477 |
) |
| 478 |
) |
| 479 |
|
| 480 |
async with async_client.messages.stream( |
| 481 |
max_tokens=1024, |
| 482 |
messages=[ |
| 483 |
{ |
| 484 |
"role": "user", |
| 485 |
"content": "Say hello there!", |
| 486 |
} |
| 487 |
], |
| 488 |
model="claude-3-opus-latest", |
| 489 |
) as stream: |
| 490 |
assert not stream.response.is_closed |
| 491 |
assert stream.request_id == "my-req-id" |
| 492 |
assert stream.workspace_id == "wrkspc_123" |
| 493 |
|
| 494 |
# response should be closed even if the body isn't read |
| 495 |
assert stream.response.is_closed |
| 496 |
|
| 497 |
@pytest.mark.asyncio |
| 498 |
@pytest.mark.respx(base_url=base_url) |
| 499 |
async def test_deprecated_model_warning_stream(self, respx_mock: MockRouter) -> None: |
| 500 |
for deprecated_model in DEPRECATED_MODELS: |
| 501 |
respx_mock.post("/v1/messages").mock( |
| 502 |
return_value=httpx2.Response(200, content=to_async_iter(get_response("basic_response.txt"))) |
| 503 |
) |
| 504 |
|
| 505 |
with pytest.warns(DeprecationWarning, match=f"The model '{deprecated_model}' is deprecated"): |
| 506 |
async with async_client.messages.stream( |
| 507 |
max_tokens=1024, |
| 508 |
messages=[{"role": "user", "content": "Hello"}], |
| 509 |
model=deprecated_model, |
| 510 |
) as stream: |
| 511 |
# Consume the stream to ensure the warning is triggered |
| 512 |
await stream.get_final_message() |
| 513 |
|
| 514 |
@pytest.mark.asyncio |
| 515 |
@pytest.mark.respx(base_url=base_url) |
| 516 |
async def test_tool_use(self, respx_mock: MockRouter) -> None: |
| 517 |
respx_mock.post("/v1/messages").mock( |
| 518 |
return_value=httpx2.Response(200, content=to_async_iter(get_response("tool_use_response.txt"))) |
| 519 |
) |
| 520 |
|
| 521 |
async with async_client.messages.stream( |
| 522 |
max_tokens=1024, |
| 523 |
messages=[ |
| 524 |
{ |
| 525 |
"role": "user", |
| 526 |
"content": "Say hello there!", |
| 527 |
} |
| 528 |
], |
| 529 |
model="claude-sonnet-4-5", |
| 530 |
) as stream: |
| 531 |
assert not isinstance(cast(Any, stream), AsyncStream) |
| 532 |
|
| 533 |
assert_tool_use_response([event async for event in stream], await stream.get_final_message()) |
| 534 |
|
| 535 |
@pytest.mark.asyncio |
| 536 |
@pytest.mark.respx(base_url=base_url) |
| 537 |
async def test_server_tool_use(self, respx_mock: MockRouter) -> None: |
| 538 |
respx_mock.post("/v1/messages").mock( |
| 539 |
return_value=httpx2.Response(200, content=to_async_iter(get_response("server_tool_use_response.txt"))) |
| 540 |
) |
| 541 |
|
| 542 |
async with async_client.messages.stream( |
| 543 |
max_tokens=1024, |
| 544 |
messages=[{"role": "user", "content": "Say hello there!"}], |
| 545 |
model="claude-sonnet-4-5", |
| 546 |
) as stream: |
| 547 |
assert_server_tool_use_response([event async for event in stream], await stream.get_final_message()) |
| 548 |
|
| 549 |
@pytest.mark.asyncio |
| 550 |
@pytest.mark.respx(base_url=base_url) |
| 551 |
async def test_tool_use_invalid_json(self, respx_mock: MockRouter) -> None: |
| 552 |
respx_mock.post("/v1/messages").mock( |
| 553 |
return_value=httpx2.Response(200, content=to_async_iter(get_response("tool_use_invalid_json_response.txt"))) |
| 554 |
) |
| 555 |
|
| 556 |
with pytest.raises(ValueError, match=INVALID_TOOL_JSON_ERROR): |
| 557 |
async with async_client.messages.stream( |
| 558 |
max_tokens=1024, |
| 559 |
messages=[{"role": "user", "content": "What's the weather in Paris?"}], |
| 560 |
model="claude-sonnet-4-5", |
| 561 |
) as stream: |
| 562 |
await stream.until_done() |
| 563 |
|
| 564 |
@pytest.mark.asyncio |
| 565 |
@pytest.mark.respx(base_url=base_url) |
| 566 |
async def test_tool_use_caller_omitted(self, respx_mock: MockRouter) -> None: |
| 567 |
respx_mock.post("/v1/messages").mock( |
| 568 |
return_value=httpx2.Response(200, content=to_async_iter(get_tool_use_response_without_caller())) |
| 569 |
) |
| 570 |
|
| 571 |
async with async_client.messages.stream( |
| 572 |
max_tokens=1024, |
| 573 |
messages=[{"role": "user", "content": "What is the weather in Paris?"}], |
| 574 |
model="claude-sonnet-4-5", |
| 575 |
) as stream: |
| 576 |
assert_tool_use_caller_unset(await stream.get_final_message()) |
| 577 |
|
| 578 |
@pytest.mark.asyncio |
| 579 |
@pytest.mark.respx(base_url=base_url) |
| 580 |
async def test_refusal_stop_details_propagated(self, respx_mock: MockRouter) -> None: |
| 581 |
respx_mock.post("/v1/messages").mock( |
| 582 |
return_value=httpx2.Response(200, content=to_async_iter(get_response("refusal_response.txt"))) |
| 583 |
) |
| 584 |
|
| 585 |
async with async_client.messages.stream( |
| 586 |
max_tokens=1024, |
| 587 |
messages=[{"role": "user", "content": "Say hello there!"}], |
| 588 |
model="claude-opus-4-7", |
| 589 |
) as stream: |
| 590 |
assert_refusal_response(await stream.get_final_message()) |
| 591 |
|
| 592 |
@pytest.mark.asyncio |
| 593 |
@pytest.mark.respx(base_url=base_url) |
| 594 |
async def test_message_delta_fields_propagated(self, respx_mock: MockRouter) -> None: |
| 595 |
respx_mock.post("/v1/messages").mock( |
| 596 |
return_value=httpx2.Response(200, content=to_async_iter(get_response("message_delta_fields_response.txt"))) |
| 597 |
) |
| 598 |
|
| 599 |
async with async_client.messages.stream( |
| 600 |
max_tokens=1024, |
| 601 |
messages=[{"role": "user", "content": "Say hello there!"}], |
| 602 |
model="claude-sonnet-4-5", |
| 603 |
) as stream: |
| 604 |
assert_message_delta_fields_response(await stream.get_final_message()) |
| 605 |
|
| 606 |
@pytest.mark.asyncio |
| 607 |
@pytest.mark.respx(base_url=base_url) |
| 608 |
async def test_message_delta_omitted_usage_keeps_message_start(self, respx_mock: MockRouter) -> None: |
| 609 |
respx_mock.post("/v1/messages").mock( |
| 610 |
return_value=httpx2.Response( |
| 611 |
200, content=to_async_iter(get_response("message_delta_omitted_usage_response.txt")) |
| 612 |
) |
| 613 |
) |
| 614 |
|
| 615 |
async with async_client.messages.stream( |
| 616 |
max_tokens=1024, |
| 617 |
messages=[{"role": "user", "content": "Say hello there!"}], |
| 618 |
model="claude-sonnet-4-5", |
| 619 |
) as stream: |
| 620 |
assert_message_delta_omitted_usage_response(await stream.get_final_message()) |
| 621 |
|
| 622 |
@pytest.mark.asyncio |
| 623 |
@pytest.mark.respx(base_url=base_url) |
| 624 |
@pytest.mark.filterwarnings("error") |
| 625 |
async def test_message_stop_event_serialization(self, respx_mock: MockRouter) -> None: |
| 626 |
# trailing blank line terminates the final `message_stop` SSE so it is dispatched |
| 627 |
respx_mock.post("/v1/messages").mock( |
| 628 |
return_value=httpx2.Response(200, content=to_async_iter(iter([*get_response("basic_response.txt"), b"\n"]))) |
| 629 |
) |
| 630 |
|
| 631 |
async with async_client.messages.stream( |
| 632 |
max_tokens=1024, |
| 633 |
messages=[{"role": "user", "content": "Say hello there!"}], |
| 634 |
model="claude-opus-4-7", |
| 635 |
) as stream: |
| 636 |
stop_event = [event async for event in stream][-1] |
| 637 |
|
| 638 |
assert stop_event.type == "message_stop" |
| 639 |
assert stop_event.message.content[0].type == "text" |
| 640 |
# must not emit `PydanticSerializationUnexpectedValue` warnings |
| 641 |
stop_event.model_dump() |
| 642 |
stop_event.model_dump_json() |
| 643 |
|
| 644 |
|
| 645 |
def test_message_delta_fields_are_all_accumulated() -> None: |
| 646 |
# tripwire: handle a new field in accumulate_event (src/anthropic/lib/streaming/_messages.py), then list it here |
| 647 |
assert set(get_model_fields(RawMessageDeltaEvent)) == { |
| 648 |
"delta", |
| 649 |
"type", |
| 650 |
"usage", |
| 651 |
} |
| 652 |
assert set(get_model_fields(RawMessageDelta)) == { |
| 653 |
"container", |
| 654 |
"stop_details", |
| 655 |
"stop_reason", |
| 656 |
"stop_sequence", |
| 657 |
} |
| 658 |
assert set(get_model_fields(MessageDeltaUsage)) == { |
| 659 |
"cache_creation_input_tokens", |
| 660 |
"cache_read_input_tokens", |
| 661 |
"input_tokens", |
| 662 |
"output_tokens", |
| 663 |
"output_tokens_details", |
| 664 |
"server_tool_use", |
| 665 |
} |
| 666 |
|
| 667 |
|
| 668 |
@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) |
| 669 |
def test_stream_method_definition_in_sync(sync: bool) -> None: |
| 670 |
client: Anthropic | AsyncAnthropic = sync_client if sync else async_client |
| 671 |
assert_signatures_in_sync( |
| 672 |
client.messages.create, |
| 673 |
client.messages.stream, |
| 674 |
exclude_params={"stream"}, |
| 675 |
) |
| 676 |
|
| 677 |
|
| 678 |
# go through all the ContentBlock types to make sure the type alias is up to date |
| 679 |
# with any type that has an input property of type object |
| 680 |
@pytest.mark.skipif(PYDANTIC_V1, reason="only applicable in pydantic v2") |
| 681 |
def test_tracks_tool_input_type_alias_is_up_to_date() -> None: |
| 682 |
from typing import get_args |
| 683 |
|
| 684 |
from pydantic import BaseModel |
| 685 |
|
| 686 |
from anthropic.types.content_block import ContentBlock |
| 687 |
|
| 688 |
content_block_union = get_args(ContentBlock)[0] |
| 689 |
|
| 690 |
content_block_types = get_args(content_block_union) |
| 691 |
|
| 692 |
types_with_input: Set[Any] = set() |
| 693 |
|
| 694 |
for block_type in content_block_types: |
| 695 |
if issubclass(block_type, BaseModel) and "input" in block_type.model_fields: |
| 696 |
types_with_input.add(block_type) |
| 697 |
|
| 698 |
tracked_types = TRACKS_TOOL_INPUT |
| 699 |
|
| 700 |
for block_type in types_with_input: |
| 701 |
assert block_type in tracked_types, ( |
| 702 |
f"ContentBlock type {block_type.__name__} has an input property, " |
| 703 |
f"but is not included in TRACKS_TOOL_INPUT. You probably need to update the TRACKS_TOOL_INPUT type alias." |
| 704 |
) |