Debian Codegraph @

tests/lib/streaming/test_beta_messages.py

raw
1 from __future__ import annotations
2
3 import os
4 import json
5 from typing import Any, Set, Dict, List, Tuple, TypeVar, cast
6
7 import httpx2
8 import pytest
9 from respx import MockRouter
10
11 from anthropic import Anthropic, AsyncAnthropic
12 from anthropic._utils import assert_overloads_in_sync, assert_signatures_in_sync
13 from anthropic._compat import PYDANTIC_V1, get_model_fields
14 from anthropic.types.beta.beta_message import BetaMessage
15 from anthropic.lib.streaming._beta_types import (
16 BetaInputJsonEvent,
17 BetaCompactionEvent,
18 ParsedBetaMessageStreamEvent,
19 )
20 from anthropic.types.beta.beta_tool_param import BetaToolParam
21 from anthropic.resources.messages.messages import DEPRECATED_MODELS
22 from anthropic.lib.streaming._beta_messages import TRACKS_TOOL_INPUT, BetaMessageStream, BetaAsyncMessageStream
23 from anthropic.types.beta.beta_message_delta_usage import BetaMessageDeltaUsage
24 from anthropic.types.beta.beta_raw_message_delta_event import Delta as BetaRawMessageDelta, BetaRawMessageDeltaEvent
25
26 from .helpers import get_response, to_async_iter
27
28 base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010")
29 api_key = "my-anthropic-api-key"
30
31 sync_client = Anthropic(base_url=base_url, api_key=api_key, _strict_response_validation=True)
32 async_client = AsyncAnthropic(base_url=base_url, api_key=api_key, _strict_response_validation=True)
33
34 _T = TypeVar("_T")
35
36
37 class WeatherTool:
38 """Stands in for a `@beta_tool` / toolset object: `tools=` takes anything with a `to_dict()`."""
39
40 def to_dict(self) -> BetaToolParam:
41 return {"name": "get_weather", "description": "Weather lookup.", "input_schema": {"type": "object"}}
42
43
44 # Expected message fixtures
45 EXPECTED_BASIC_MESSAGE = {
46 "id": "msg_4QpJur2dWWDjF6C758FbBw5vm12BaVipnK",
47 "model": "claude-3-opus-latest",
48 "role": "assistant",
49 "stop_reason": "end_turn",
50 "type": "message",
51 "content": [{"type": "text", "text": "Hello there!"}],
52 "usage": {"input_tokens": 11, "output_tokens": 6},
53 }
54
55 EXPECTED_BASIC_EVENT_TYPES = [
56 "message_start",
57 "content_block_start",
58 "content_block_delta",
59 "text",
60 "content_block_delta",
61 "text",
62 "content_block_delta",
63 "text",
64 "content_block_stop",
65 "message_delta",
66 ]
67
68 EXPECTED_TOOL_USE_MESSAGE = {
69 "id": "msg_019Q1hrJbZG26Fb9BQhrkHEr",
70 "model": "claude-sonnet-4-20250514",
71 "role": "assistant",
72 "stop_reason": "tool_use",
73 "type": "message",
74 "content": [
75 {"type": "text", "text": "I'll check the current weather in Paris for you."},
76 {
77 "type": "tool_use",
78 "caller": {"type": "direct"},
79 "id": "toolu_01NRLabsLyVHZPKxbKvkfSMn",
80 "name": "get_weather",
81 "input": {"location": "Paris"},
82 },
83 ],
84 "usage": {
85 "input_tokens": 377,
86 "output_tokens": 65,
87 "cache_creation_input_tokens": 0,
88 "cache_read_input_tokens": 0,
89 "service_tier": "standard",
90 },
91 }
92
93 EXPECTED_TOOL_USE_EVENT_TYPES = [
94 "message_start",
95 "content_block_start",
96 "content_block_delta",
97 "text",
98 "content_block_delta",
99 "text",
100 "content_block_stop",
101 "content_block_start",
102 "content_block_delta",
103 "input_json",
104 "content_block_delta",
105 "input_json",
106 "content_block_delta",
107 "input_json",
108 "content_block_delta",
109 "input_json",
110 "content_block_delta",
111 "input_json",
112 "content_block_stop",
113 "message_delta",
114 ]
115
116 EXPECTED_INCOMPLETE_MESSAGE = {
117 "id": "msg_01UdjYBBipA9omjYhicnevgq",
118 "model": "claude-3-7-sonnet-20250219",
119 "role": "assistant",
120 "stop_reason": "max_tokens",
121 "type": "message",
122 "content": [
123 {
124 "type": "text",
125 "text": "I'll create a comprehensive tax guide for someone with multiple W2s and save it in a file called taxes.txt. Let me do that for you now.",
126 },
127 {
128 "type": "tool_use",
129 "id": "toolu_01EKqbqmZrGRXy18eN7m9kvY",
130 "name": "make_file",
131 "input": {
132 "filename": "taxes.txt",
133 "lines_of_text": [
134 "# COMPREHENSIVE TAX GUIDE FOR INDIVIDUALS WITH MULTIPLE W-2s",
135 "",
136 "## INTRODUCTION",
137 "",
138 ],
139 },
140 },
141 ],
142 "usage": {
143 "input_tokens": 450,
144 "output_tokens": 124,
145 "cache_creation_input_tokens": 0,
146 "cache_read_input_tokens": 0,
147 "service_tier": "standard",
148 },
149 }
150
151 EXPECTED_INCOMPLETE_EVENT_TYPES = [
152 "message_start",
153 "content_block_start",
154 "content_block_delta",
155 "text",
156 "content_block_delta",
157 "text",
158 "content_block_delta",
159 "text",
160 "content_block_delta",
161 "text",
162 "content_block_delta",
163 "text",
164 "content_block_stop",
165 "content_block_start",
166 "content_block_delta",
167 "input_json",
168 "content_block_delta",
169 "input_json",
170 "content_block_delta",
171 "input_json",
172 "content_block_delta",
173 "input_json",
174 "message_delta",
175 ]
176
177 EXPECTED_COMPACTION_MESSAGE = {
178 "id": "msg_01CompactionEncryptedContent01",
179 "model": "claude-opus-4-7",
180 "role": "assistant",
181 "stop_reason": "end_turn",
182 "type": "message",
183 "content": [
184 {
185 "type": "compaction",
186 "content": "Earlier conversation summarized.",
187 "encrypted_content": "EpwBCioIDxgCEAEYASJALd_opaque_compaction_payload",
188 },
189 {"type": "text", "text": "Hello there!"},
190 ],
191 "usage": {"input_tokens": 30, "output_tokens": 8},
192 }
193
194 EXPECTED_COMPACTION_EVENT_TYPES = [
195 "message_start",
196 "content_block_start",
197 "content_block_delta",
198 "compaction",
199 "content_block_stop",
200 "content_block_start",
201 "content_block_delta",
202 "text",
203 "content_block_stop",
204 "message_delta",
205 ]
206
207
208 FOLLOW_UP_MESSAGE = {
209 "id": "msg_01FollowUp",
210 "type": "message",
211 "role": "assistant",
212 "model": "claude-sonnet-4-5",
213 "content": [{"type": "text", "text": "It is sunny in Paris."}],
214 "stop_reason": "end_turn",
215 "stop_sequence": None,
216 "usage": {"input_tokens": 400, "output_tokens": 10},
217 }
218
219 EXPECTED_TOOL_USE_PARAM = {
220 "type": "tool_use",
221 "id": "toolu_01NRLabsLyVHZPKxbKvkfSMn",
222 "name": "get_weather",
223 "input": {"location": "Paris"},
224 "caller": {"type": "direct"},
225 }
226
227
228 def assert_message_matches(message: BetaMessage, expected: Dict[str, Any]) -> None:
229 actual_message_json = message.model_dump_json(indent=2, exclude_none=True)
230
231 assert json.loads(actual_message_json) == expected
232
233
234 def assert_basic_response(events: list[ParsedBetaMessageStreamEvent], message: BetaMessage) -> None:
235 assert_message_matches(message, EXPECTED_BASIC_MESSAGE)
236 assert [e.type for e in events] == EXPECTED_BASIC_EVENT_TYPES
237
238
239 def assert_tool_use_response(events: list[ParsedBetaMessageStreamEvent], message: BetaMessage) -> None:
240 assert_message_matches(message, EXPECTED_TOOL_USE_MESSAGE)
241 assert [e.type for e in events] == EXPECTED_TOOL_USE_EVENT_TYPES
242
243
244 def assert_incomplete_partial_input_response(events: list[ParsedBetaMessageStreamEvent], message: BetaMessage) -> None:
245 assert_message_matches(message, EXPECTED_INCOMPLETE_MESSAGE)
246 assert [e.type for e in events] == EXPECTED_INCOMPLETE_EVENT_TYPES
247
248
249 def assert_compaction_response(events: list[ParsedBetaMessageStreamEvent], message: BetaMessage) -> None:
250 assert_message_matches(message, EXPECTED_COMPACTION_MESSAGE)
251 assert [e.type for e in events] == EXPECTED_COMPACTION_EVENT_TYPES
252
253 # the emitted compaction event must carry encrypted_content, not just the accumulated block
254 compaction_events = [e for e in events if isinstance(e, BetaCompactionEvent)]
255 assert len(compaction_events) == 1
256 assert compaction_events[0].encrypted_content == "EpwBCioIDxgCEAEYASJALd_opaque_compaction_payload"
257
258
259 def assert_refusal_response(message: BetaMessage) -> None:
260 assert message.stop_reason == "refusal"
261 assert message.stop_details is not None
262 assert message.stop_details.type == "refusal"
263 assert message.stop_details.category == "cyber"
264 assert message.stop_details.explanation == "This request was refused due to policy."
265
266
267 EXPECTED_FALLBACK_EVENT_TYPES = [
268 "message_start",
269 "content_block_start",
270 "content_block_stop",
271 "content_block_start",
272 "content_block_delta",
273 "text",
274 "content_block_stop",
275 "message_delta",
276 ]
277
278
279 def assert_fallback_response(events: list[ParsedBetaMessageStreamEvent], message: BetaMessage) -> None:
280 assert [e.type for e in events] == EXPECTED_FALLBACK_EVENT_TYPES
281
282 # `message_start` carried the declined model; the accumulated message must
283 # be relabeled to the serving model from the fallback block
284 assert message.model == "claude-sonnet-4-5"
285
286 assert message.content[0].type == "fallback"
287
288 text_block = message.content[1]
289 assert text_block.type == "text"
290 assert text_block.text == "Hello there!"
291
292
293 EXPECTED_SERVER_TOOL_USE_EVENT_TYPES = [
294 "message_start",
295 "content_block_start",
296 *["content_block_delta", "input_json"] * 6,
297 "content_block_stop",
298 "content_block_start",
299 "content_block_stop",
300 "content_block_start",
301 "content_block_delta",
302 "citation",
303 "content_block_delta",
304 "text",
305 "content_block_delta",
306 "text",
307 "content_block_stop",
308 "message_delta",
309 ]
310
311
312 def assert_server_tool_use_response(events: list[ParsedBetaMessageStreamEvent], message: BetaMessage) -> None:
313 assert [e.type for e in events] == EXPECTED_SERVER_TOOL_USE_EVENT_TYPES
314
315 server_tool_use = message.content[0]
316 assert server_tool_use.type == "server_tool_use"
317 assert server_tool_use.input == {"query": "anthropic claude release notes"}
318
319 # input_json events must fire for server_tool_use blocks, not just client tool_use
320 input_json_events = [e for e in events if isinstance(e, BetaInputJsonEvent)]
321 assert [e.partial_json for e in input_json_events] == [
322 "",
323 '{"query": "',
324 "anthropic cl",
325 "aude re",
326 "lease notes",
327 '"}',
328 ]
329 assert input_json_events[-1].snapshot == {"query": "anthropic claude release notes"}
330
331
332 def assert_fallback_credit_response(message: BetaMessage) -> None:
333 # `message_delta` carried `usage.fallback_credit`; the accumulated final
334 # message must surface it rather than dropping it
335 assert message.usage.fallback_credit is not None
336 assert message.usage.fallback_credit.status.type == "redeemed"
337 assert message.usage.output_tokens == 8
338
339
340 def assert_message_delta_fields_response(message: BetaMessage) -> None:
341 # every field the final `message_delta` carried must land on the accumulated message
342 assert message.container is not None
343 assert message.container.id == "container_01AbCdEfGh"
344 assert message.usage.output_tokens == 8
345 assert message.usage.input_tokens == 40
346 assert message.usage.cache_creation_input_tokens == 12
347 assert message.usage.cache_read_input_tokens == 7
348 assert message.usage.output_tokens_details is not None
349 assert message.usage.output_tokens_details.thinking_tokens == 3
350 assert message.usage.server_tool_use is not None
351 assert message.usage.server_tool_use.web_search_requests == 1
352 # never re-sent on `message_delta`, so these must survive from `message_start`
353 assert message.usage.service_tier == "standard"
354 assert message.usage.cache_creation is not None
355 assert message.usage.cache_creation.ephemeral_5m_input_tokens == 10
356
357
358 def assert_context_management_response(message: BetaMessage) -> None:
359 # `context_management` is a top-level key of the `message_delta` event and is
360 # never sent on `message_start`, so the event is its only source
361 assert message.context_management is not None
362 applied_edit = message.context_management.applied_edits[0]
363 assert applied_edit.type == "clear_tool_uses_20250919"
364 assert applied_edit.cleared_tool_uses == 2
365 assert applied_edit.cleared_input_tokens == 1500
366
367
368 # a `message_delta` array (mid-stream fallback) replaces the `message_start` value, even
369 # when empty, while a delta without the key must leave the `message_start` value in place
370 INPUT_TRANSFORMATIONS_CASES: List[Tuple[str, List[Dict[str, str]]]] = [
371 (
372 "input_transformations_delta_response.txt",
373 [{"type": "thinking_dropped", "path": "messages.0.content.0", "reason": "model_binding_mismatch"}],
374 ),
375 (
376 "input_transformations_start_only_response.txt",
377 [{"type": "thinking_dropped", "path": "messages.0.content.0", "reason": "model_binding_mismatch"}],
378 ),
379 ("input_transformations_empty_delta_response.txt", []),
380 ]
381
382
383 def assert_input_transformations_response(message: BetaMessage, expected: List[Dict[str, str]]) -> None:
384 assert message.input_transformations is not None
385 assert [entry.to_dict() for entry in message.input_transformations] == expected
386
387
388 class TestSyncMessages:
389 @pytest.mark.respx(base_url=base_url)
390 def test_basic_response(self, respx_mock: MockRouter) -> None:
391 respx_mock.post("/v1/messages").mock(
392 return_value=httpx2.Response(200, content=get_response("basic_response.txt"))
393 )
394
395 with sync_client.beta.messages.stream(
396 max_tokens=1024,
397 messages=[
398 {
399 "role": "user",
400 "content": "Say hello there!",
401 }
402 ],
403 model="claude-3-opus-latest",
404 ) as stream:
405 assert isinstance(cast(Any, stream), BetaMessageStream)
406
407 assert_basic_response([event for event in stream], stream.get_final_message())
408
409 @pytest.mark.respx(base_url=base_url)
410 def test_tool_use(self, respx_mock: MockRouter) -> None:
411 respx_mock.post("/v1/messages").mock(
412 return_value=httpx2.Response(200, content=get_response("tool_use_response.txt"))
413 )
414
415 with sync_client.beta.messages.stream(
416 max_tokens=1024,
417 messages=[
418 {
419 "role": "user",
420 "content": "Say hello there!",
421 }
422 ],
423 model="claude-sonnet-4-5",
424 tools=[WeatherTool()],
425 ) as stream:
426 assert isinstance(cast(Any, stream), BetaMessageStream)
427
428 assert_tool_use_response([event for event in stream], stream.get_final_message())
429
430 assert json.loads(respx_mock.calls.last.request.content)["tools"] == [WeatherTool().to_dict()]
431
432 @pytest.mark.respx(base_url=base_url)
433 def test_tool_use_round_trip(self, respx_mock: MockRouter) -> None:
434 route = respx_mock.post("/v1/messages").mock(
435 side_effect=[
436 httpx2.Response(200, content=get_response("tool_use_response.txt")),
437 httpx2.Response(200, json=FOLLOW_UP_MESSAGE),
438 ]
439 )
440
441 with sync_client.beta.messages.stream(
442 max_tokens=1024,
443 messages=[{"role": "user", "content": "What is the weather in Paris?"}],
444 model="claude-sonnet-4-5",
445 ) as stream:
446 message = stream.get_final_message()
447
448 # accumulated blocks must be reusable as request params without leaking accumulator state
449 sync_client.beta.messages.create(
450 max_tokens=1024,
451 messages=[
452 {"role": "user", "content": "What is the weather in Paris?"},
453 {"role": "assistant", "content": message.content},
454 {
455 "role": "user",
456 "content": [
457 {"type": "tool_result", "tool_use_id": "toolu_01NRLabsLyVHZPKxbKvkfSMn", "content": "Sunny"}
458 ],
459 },
460 ],
461 model="claude-sonnet-4-5",
462 )
463
464 request_body = json.loads(route.calls.last.request.content)
465 assert request_body["messages"][1]["content"][1] == EXPECTED_TOOL_USE_PARAM
466
467 @pytest.mark.respx(base_url=base_url)
468 def test_server_tool_use(self, respx_mock: MockRouter) -> None:
469 respx_mock.post("/v1/messages").mock(
470 return_value=httpx2.Response(200, content=get_response("server_tool_use_response.txt"))
471 )
472
473 with sync_client.beta.messages.stream(
474 max_tokens=1024,
475 messages=[{"role": "user", "content": "Say hello there!"}],
476 model="claude-sonnet-4-5",
477 ) as stream:
478 assert_server_tool_use_response([event for event in stream], stream.get_final_message())
479
480 @pytest.mark.respx(base_url=base_url)
481 def test_context_manager(self, respx_mock: MockRouter) -> None:
482 respx_mock.post("/v1/messages").mock(
483 return_value=httpx2.Response(
484 200,
485 headers={"request-id": "my-req-id", "anthropic-workspace-id": "wrkspc_123"},
486 content=get_response("basic_response.txt"),
487 )
488 )
489
490 with sync_client.beta.messages.stream(
491 max_tokens=1024,
492 messages=[
493 {
494 "role": "user",
495 "content": "Say hello there!",
496 }
497 ],
498 model="claude-3-opus-latest",
499 ) as stream:
500 assert not stream.response.is_closed
501 assert stream.request_id == "my-req-id"
502 assert stream.workspace_id == "wrkspc_123"
503
504 # response should be closed even if the body isn't read
505 assert stream.response.is_closed
506
507 @pytest.mark.respx(base_url=base_url)
508 def test_deprecated_model_warning_stream(self, respx_mock: MockRouter) -> None:
509 for deprecated_model in DEPRECATED_MODELS:
510 respx_mock.post("/v1/messages").mock(
511 return_value=httpx2.Response(200, content=get_response("basic_response.txt"))
512 )
513
514 with pytest.warns(DeprecationWarning, match=f"The model '{deprecated_model}' is deprecated"):
515 with sync_client.beta.messages.stream(
516 max_tokens=1024,
517 messages=[{"role": "user", "content": "Hello"}],
518 model=deprecated_model,
519 ) as stream:
520 # Consume the stream to ensure the warning is triggered
521 stream.until_done()
522
523 @pytest.mark.respx(base_url=base_url)
524 def test_refusal_stop_details_propagated(self, respx_mock: MockRouter) -> None:
525 respx_mock.post("/v1/messages").mock(
526 return_value=httpx2.Response(200, content=get_response("refusal_response.txt"))
527 )
528
529 with sync_client.beta.messages.stream(
530 max_tokens=1024,
531 messages=[{"role": "user", "content": "Say hello there!"}],
532 model="claude-opus-4-7",
533 ) as stream:
534 assert_refusal_response(stream.get_final_message())
535
536 @pytest.mark.respx(base_url=base_url)
537 @pytest.mark.filterwarnings("error")
538 def test_message_stop_event_serialization(self, respx_mock: MockRouter) -> None:
539 # trailing blank line terminates the final `message_stop` SSE so it is dispatched
540 respx_mock.post("/v1/messages").mock(
541 return_value=httpx2.Response(200, content=iter([*get_response("basic_response.txt"), b"\n"]))
542 )
543
544 with sync_client.beta.messages.stream(
545 max_tokens=1024,
546 messages=[{"role": "user", "content": "Say hello there!"}],
547 model="claude-opus-4-7",
548 ) as stream:
549 stop_event = [event for event in stream][-1]
550
551 assert stop_event.type == "message_stop"
552 assert stop_event.message.content[0].type == "text"
553 # must not emit `PydanticSerializationUnexpectedValue` warnings
554 stop_event.model_dump()
555 stop_event.model_dump_json()
556
557 @pytest.mark.respx(base_url=base_url)
558 def test_compaction(self, respx_mock: MockRouter) -> None:
559 respx_mock.post("/v1/messages").mock(
560 return_value=httpx2.Response(200, content=get_response("compaction_response.txt"))
561 )
562
563 with sync_client.beta.messages.stream(
564 max_tokens=1024,
565 messages=[{"role": "user", "content": "Say hello there!"}],
566 model="claude-opus-4-7",
567 ) as stream:
568 assert isinstance(cast(Any, stream), BetaMessageStream)
569
570 assert_compaction_response([event for event in stream], stream.get_final_message())
571
572 @pytest.mark.respx(base_url=base_url)
573 def test_fallback_relabels_model(self, respx_mock: MockRouter) -> None:
574 respx_mock.post("/v1/messages").mock(
575 return_value=httpx2.Response(200, content=get_response("fallback_response.txt"))
576 )
577
578 with sync_client.beta.messages.stream(
579 max_tokens=1024,
580 messages=[{"role": "user", "content": "Say hello there!"}],
581 model="claude-opus-4-7",
582 ) as stream:
583 assert isinstance(cast(Any, stream), BetaMessageStream)
584
585 assert_fallback_response([event for event in stream], stream.get_final_message())
586
587 @pytest.mark.respx(base_url=base_url)
588 def test_fallback_credit_usage_propagated(self, respx_mock: MockRouter) -> None:
589 respx_mock.post("/v1/messages").mock(
590 return_value=httpx2.Response(200, content=get_response("fallback_credit_response.txt"))
591 )
592
593 with sync_client.beta.messages.stream(
594 max_tokens=1024,
595 messages=[{"role": "user", "content": "Say hello there!"}],
596 model="claude-sonnet-4-5",
597 ) as stream:
598 assert_fallback_credit_response(stream.get_final_message())
599
600 @pytest.mark.respx(base_url=base_url)
601 def test_message_delta_fields_propagated(self, respx_mock: MockRouter) -> None:
602 respx_mock.post("/v1/messages").mock(
603 return_value=httpx2.Response(200, content=get_response("message_delta_fields_response.txt"))
604 )
605
606 with sync_client.beta.messages.stream(
607 max_tokens=1024,
608 messages=[{"role": "user", "content": "Say hello there!"}],
609 model="claude-sonnet-4-5",
610 ) as stream:
611 assert_message_delta_fields_response(stream.get_final_message())
612
613 @pytest.mark.respx(base_url=base_url)
614 def test_context_management_propagated(self, respx_mock: MockRouter) -> None:
615 respx_mock.post("/v1/messages").mock(
616 return_value=httpx2.Response(200, content=get_response("context_management_response.txt"))
617 )
618
619 with sync_client.beta.messages.stream(
620 max_tokens=1024,
621 messages=[{"role": "user", "content": "Say hello there!"}],
622 model="claude-sonnet-4-5",
623 ) as stream:
624 assert_context_management_response(stream.get_final_message())
625
626 @pytest.mark.respx(base_url=base_url)
627 @pytest.mark.parametrize("fixture, expected", INPUT_TRANSFORMATIONS_CASES)
628 def test_input_transformations_propagated(
629 self, respx_mock: MockRouter, fixture: str, expected: List[Dict[str, str]]
630 ) -> None:
631 respx_mock.post("/v1/messages").mock(return_value=httpx2.Response(200, content=get_response(fixture)))
632
633 with sync_client.beta.messages.stream(
634 max_tokens=1024,
635 messages=[{"role": "user", "content": "Say hello there!"}],
636 model="claude-sonnet-4-5",
637 ) as stream:
638 assert_input_transformations_response(stream.get_final_message(), expected)
639
640
641 class TestAsyncMessages:
642 @pytest.mark.asyncio
643 @pytest.mark.respx(base_url=base_url)
644 async def test_basic_response(self, respx_mock: MockRouter) -> None:
645 respx_mock.post("/v1/messages").mock(
646 return_value=httpx2.Response(200, content=to_async_iter(get_response("basic_response.txt")))
647 )
648
649 async with async_client.beta.messages.stream(
650 max_tokens=1024,
651 messages=[
652 {
653 "role": "user",
654 "content": "Say hello there!",
655 }
656 ],
657 model="claude-opus-4-5",
658 ) as stream:
659 assert isinstance(cast(Any, stream), BetaAsyncMessageStream)
660
661 assert_basic_response([event async for event in stream], await stream.get_final_message())
662
663 @pytest.mark.asyncio
664 @pytest.mark.respx(base_url=base_url)
665 async def test_context_manager(self, respx_mock: MockRouter) -> None:
666 respx_mock.post("/v1/messages").mock(
667 return_value=httpx2.Response(
668 200,
669 headers={"request-id": "my-req-id", "anthropic-workspace-id": "wrkspc_123"},
670 content=to_async_iter(get_response("basic_response.txt")),
671 )
672 )
673
674 async with async_client.beta.messages.stream(
675 max_tokens=1024,
676 messages=[
677 {
678 "role": "user",
679 "content": "Say hello there!",
680 }
681 ],
682 model="claude-3-opus-latest",
683 ) as stream:
684 assert not stream.response.is_closed
685 assert stream.request_id == "my-req-id"
686 assert stream.workspace_id == "wrkspc_123"
687
688 # response should be closed even if the body isn't read
689 assert stream.response.is_closed
690
691 @pytest.mark.asyncio
692 @pytest.mark.respx(base_url=base_url)
693 async def test_deprecated_model_warning_stream(self, respx_mock: MockRouter) -> None:
694 for deprecated_model in DEPRECATED_MODELS:
695 respx_mock.post("/v1/messages").mock(
696 return_value=httpx2.Response(200, content=to_async_iter(get_response("basic_response.txt")))
697 )
698
699 with pytest.warns(DeprecationWarning, match=f"The model '{deprecated_model}' is deprecated"):
700 async with async_client.beta.messages.stream(
701 max_tokens=1024,
702 messages=[{"role": "user", "content": "Hello"}],
703 model=deprecated_model,
704 ) as stream:
705 # Consume the stream to ensure the warning is triggered
706 await stream.get_final_message()
707
708 @pytest.mark.asyncio
709 @pytest.mark.respx(base_url=base_url)
710 async def test_tool_use(self, respx_mock: MockRouter) -> None:
711 respx_mock.post("/v1/messages").mock(
712 return_value=httpx2.Response(200, content=to_async_iter(get_response("tool_use_response.txt")))
713 )
714
715 async with async_client.beta.messages.stream(
716 max_tokens=1024,
717 messages=[
718 {
719 "role": "user",
720 "content": "Say hello there!",
721 }
722 ],
723 model="claude-sonnet-4-5",
724 tools=[WeatherTool()],
725 ) as stream:
726 assert isinstance(cast(Any, stream), BetaAsyncMessageStream)
727
728 assert_tool_use_response([event async for event in stream], await stream.get_final_message())
729
730 assert json.loads(respx_mock.calls.last.request.content)["tools"] == [WeatherTool().to_dict()]
731
732 @pytest.mark.asyncio
733 @pytest.mark.respx(base_url=base_url)
734 async def test_server_tool_use(self, respx_mock: MockRouter) -> None:
735 respx_mock.post("/v1/messages").mock(
736 return_value=httpx2.Response(200, content=to_async_iter(get_response("server_tool_use_response.txt")))
737 )
738
739 async with async_client.beta.messages.stream(
740 max_tokens=1024,
741 messages=[{"role": "user", "content": "Say hello there!"}],
742 model="claude-sonnet-4-5",
743 ) as stream:
744 assert_server_tool_use_response([event async for event in stream], await stream.get_final_message())
745
746 @pytest.mark.asyncio
747 @pytest.mark.respx(base_url=base_url)
748 async def test_incomplete_response(self, respx_mock: MockRouter) -> None:
749 respx_mock.post("/v1/messages").mock(
750 return_value=httpx2.Response(
751 200, content=to_async_iter(get_response("incomplete_partial_json_response.txt"))
752 )
753 )
754
755 async with async_client.beta.messages.stream(
756 max_tokens=1024,
757 messages=[
758 {
759 "role": "user",
760 "content": "Say hello there!",
761 }
762 ],
763 model="claude-sonnet-4-5",
764 ) as stream:
765 assert isinstance(cast(Any, stream), BetaAsyncMessageStream)
766
767 assert_incomplete_partial_input_response(
768 [event async for event in stream], await stream.get_final_message()
769 )
770
771 @pytest.mark.asyncio
772 @pytest.mark.respx(base_url=base_url)
773 async def test_refusal_stop_details_propagated(self, respx_mock: MockRouter) -> None:
774 respx_mock.post("/v1/messages").mock(
775 return_value=httpx2.Response(200, content=to_async_iter(get_response("refusal_response.txt")))
776 )
777
778 async with async_client.beta.messages.stream(
779 max_tokens=1024,
780 messages=[{"role": "user", "content": "Say hello there!"}],
781 model="claude-opus-4-7",
782 ) as stream:
783 assert_refusal_response(await stream.get_final_message())
784
785 @pytest.mark.asyncio
786 @pytest.mark.respx(base_url=base_url)
787 @pytest.mark.filterwarnings("error")
788 async def test_message_stop_event_serialization(self, respx_mock: MockRouter) -> None:
789 # trailing blank line terminates the final `message_stop` SSE so it is dispatched
790 respx_mock.post("/v1/messages").mock(
791 return_value=httpx2.Response(200, content=to_async_iter(iter([*get_response("basic_response.txt"), b"\n"])))
792 )
793
794 async with async_client.beta.messages.stream(
795 max_tokens=1024,
796 messages=[{"role": "user", "content": "Say hello there!"}],
797 model="claude-opus-4-7",
798 ) as stream:
799 stop_event = [event async for event in stream][-1]
800
801 assert stop_event.type == "message_stop"
802 assert stop_event.message.content[0].type == "text"
803 # must not emit `PydanticSerializationUnexpectedValue` warnings
804 stop_event.model_dump()
805 stop_event.model_dump_json()
806
807 @pytest.mark.asyncio
808 @pytest.mark.respx(base_url=base_url)
809 async def test_compaction(self, respx_mock: MockRouter) -> None:
810 respx_mock.post("/v1/messages").mock(
811 return_value=httpx2.Response(200, content=to_async_iter(get_response("compaction_response.txt")))
812 )
813
814 async with async_client.beta.messages.stream(
815 max_tokens=1024,
816 messages=[{"role": "user", "content": "Say hello there!"}],
817 model="claude-opus-4-7",
818 ) as stream:
819 assert isinstance(cast(Any, stream), BetaAsyncMessageStream)
820
821 assert_compaction_response([event async for event in stream], await stream.get_final_message())
822
823 @pytest.mark.asyncio
824 @pytest.mark.respx(base_url=base_url)
825 async def test_fallback_relabels_model(self, respx_mock: MockRouter) -> None:
826 respx_mock.post("/v1/messages").mock(
827 return_value=httpx2.Response(200, content=to_async_iter(get_response("fallback_response.txt")))
828 )
829
830 async with async_client.beta.messages.stream(
831 max_tokens=1024,
832 messages=[{"role": "user", "content": "Say hello there!"}],
833 model="claude-opus-4-7",
834 ) as stream:
835 assert isinstance(cast(Any, stream), BetaAsyncMessageStream)
836
837 assert_fallback_response([event async for event in stream], await stream.get_final_message())
838
839 @pytest.mark.asyncio
840 @pytest.mark.respx(base_url=base_url)
841 async def test_fallback_credit_usage_propagated(self, respx_mock: MockRouter) -> None:
842 respx_mock.post("/v1/messages").mock(
843 return_value=httpx2.Response(200, content=to_async_iter(get_response("fallback_credit_response.txt")))
844 )
845
846 async with async_client.beta.messages.stream(
847 max_tokens=1024,
848 messages=[{"role": "user", "content": "Say hello there!"}],
849 model="claude-sonnet-4-5",
850 ) as stream:
851 assert_fallback_credit_response(await stream.get_final_message())
852
853 @pytest.mark.asyncio
854 @pytest.mark.respx(base_url=base_url)
855 async def test_message_delta_fields_propagated(self, respx_mock: MockRouter) -> None:
856 respx_mock.post("/v1/messages").mock(
857 return_value=httpx2.Response(200, content=to_async_iter(get_response("message_delta_fields_response.txt")))
858 )
859
860 async with async_client.beta.messages.stream(
861 max_tokens=1024,
862 messages=[{"role": "user", "content": "Say hello there!"}],
863 model="claude-sonnet-4-5",
864 ) as stream:
865 assert_message_delta_fields_response(await stream.get_final_message())
866
867 @pytest.mark.asyncio
868 @pytest.mark.respx(base_url=base_url)
869 async def test_context_management_propagated(self, respx_mock: MockRouter) -> None:
870 respx_mock.post("/v1/messages").mock(
871 return_value=httpx2.Response(200, content=to_async_iter(get_response("context_management_response.txt")))
872 )
873
874 async with async_client.beta.messages.stream(
875 max_tokens=1024,
876 messages=[{"role": "user", "content": "Say hello there!"}],
877 model="claude-sonnet-4-5",
878 ) as stream:
879 assert_context_management_response(await stream.get_final_message())
880
881 @pytest.mark.asyncio
882 @pytest.mark.respx(base_url=base_url)
883 @pytest.mark.parametrize("fixture, expected", INPUT_TRANSFORMATIONS_CASES)
884 async def test_input_transformations_propagated(
885 self, respx_mock: MockRouter, fixture: str, expected: List[Dict[str, str]]
886 ) -> None:
887 respx_mock.post("/v1/messages").mock(
888 return_value=httpx2.Response(200, content=to_async_iter(get_response(fixture)))
889 )
890
891 async with async_client.beta.messages.stream(
892 max_tokens=1024,
893 messages=[{"role": "user", "content": "Say hello there!"}],
894 model="claude-sonnet-4-5",
895 ) as stream:
896 assert_input_transformations_response(await stream.get_final_message(), expected)
897
898
899 def test_message_delta_fields_are_all_accumulated() -> None:
900 # tripwire: handle a new field in accumulate_event, then list it here
901 assert set(get_model_fields(BetaRawMessageDeltaEvent)) == {
902 "context_management",
903 "delta",
904 "input_transformations",
905 "type",
906 "usage",
907 }
908 assert set(get_model_fields(BetaRawMessageDelta)) == {
909 "container",
910 "stop_details",
911 "stop_reason",
912 "stop_sequence",
913 }
914 assert set(get_model_fields(BetaMessageDeltaUsage)) == {
915 "cache_creation_input_tokens",
916 "cache_read_input_tokens",
917 "fallback_credit",
918 "input_tokens",
919 "iterations",
920 "output_tokens",
921 "output_tokens_details",
922 "server_tool_use",
923 }
924
925
926 @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
927 def test_stream_method_definition_in_sync(sync: bool) -> None:
928 client: Anthropic | AsyncAnthropic = sync_client if sync else async_client
929 assert_signatures_in_sync(
930 client.beta.messages.create,
931 client.beta.messages.stream,
932 exclude_params={"stream", "output_format"},
933 )
934
935
936 @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
937 def test_parse_method_definition_in_sync(sync: bool) -> None:
938 client: Anthropic | AsyncAnthropic = sync_client if sync else async_client
939 assert_signatures_in_sync(
940 client.beta.messages.create,
941 client.beta.messages.parse,
942 exclude_params={"stream", "output_format"},
943 )
944
945
946 @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
947 def test_tool_runner_method_definition_in_sync(sync: bool) -> None:
948 client: Anthropic | AsyncAnthropic = sync_client if sync else async_client
949 assert_overloads_in_sync(
950 client.beta.messages.create,
951 client.beta.messages.tool_runner,
952 # A tool runner can't take `compaction`: every request of the loop would compact again.
953 exclude_params={"stream", "tools", "max_iterations", "output_format", "compaction"},
954 )
955
956
957 # go through all the ContentBlock types to make sure the type alias is up to date
958 # with any type that has an input property of type object
959 def test_tracks_tool_input_type_alias_is_up_to_date() -> None:
960 if PYDANTIC_V1:
961 pytest.skip("This test is only applicable for Pydantic v2")
962 from typing import get_args
963
964 from pydantic import BaseModel
965
966 from anthropic.types.beta.beta_content_block import BetaContentBlock
967
968 content_block_union = get_args(BetaContentBlock)[0]
969
970 content_block_types = get_args(content_block_union)
971
972 types_with_input: Set[Any] = set()
973
974 for block_type in content_block_types:
975 if issubclass(block_type, BaseModel) and "input" in block_type.model_fields:
976 types_with_input.add(block_type)
977
978 tracked_types = TRACKS_TOOL_INPUT
979
980 for block_type in types_with_input:
981 assert block_type in tracked_types, (
982 f"ContentBlock type {block_type.__name__} has an input property, "
983 f"but is not included in TRACKS_TOOL_INPUT. You probably need to update the TRACKS_TOOL_INPUT type alias."
984 )