| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import copy |
| 4 |
import json |
| 5 |
from typing import Any, Set, cast |
| 6 |
from typing_extensions import get_args, get_origin |
| 7 |
|
| 8 |
import httpx2 |
| 9 |
import pytest |
| 10 |
|
| 11 |
from anthropic._compat import model_copy |
| 12 |
from anthropic._models import construct_type_unchecked |
| 13 |
from anthropic.types.beta import BetaFallbackBlock |
| 14 |
from anthropic.types.content_block import ContentBlock |
| 15 |
from anthropic.types.parsed_message import ParsedTextBlock, ParsedContentBlock |
| 16 |
from anthropic.types.beta.beta_usage import BetaUsage |
| 17 |
from anthropic.lib.streaming._beta_messages import accumulate_event |
| 18 |
from anthropic.types.beta.beta_content_block import BetaContentBlock |
| 19 |
from anthropic.types.beta.parsed_beta_message import ParsedBetaMessage, ParsedBetaTextBlock, ParsedBetaContentBlock |
| 20 |
|
| 21 |
|
| 22 |
def _union_members(union: Any) -> Set[type]: |
| 23 |
"""Return the runtime classes in an `Annotated[Union[...], ...]` type alias.""" |
| 24 |
annotated_args = get_args(union) |
| 25 |
assert annotated_args, f"expected an Annotated union, got {union!r}" |
| 26 |
members: Set[type] = set() |
| 27 |
for member in get_args(annotated_args[0]): |
| 28 |
# unwrap generic subscriptions, e.g. ParsedBetaTextBlock[ResponseFormatT] |
| 29 |
members.add(get_origin(member) or member) |
| 30 |
return members |
| 31 |
|
| 32 |
|
| 33 |
def _to_generated(member: type) -> type: |
| 34 |
"""Map a Parsed* wrapper to the generated block class it stands in for.""" |
| 35 |
if member.__name__.startswith("Parsed"): |
| 36 |
return member.__bases__[0] |
| 37 |
return member |
| 38 |
|
| 39 |
|
| 40 |
@pytest.mark.parametrize( |
| 41 |
("parsed_union", "generated_union", "parsed_file"), |
| 42 |
[ |
| 43 |
(ParsedBetaContentBlock, BetaContentBlock, "src/anthropic/types/beta/parsed_beta_message.py"), |
| 44 |
(ParsedContentBlock, ContentBlock, "src/anthropic/types/parsed_message.py"), |
| 45 |
], |
| 46 |
ids=["beta", "non-beta"], |
| 47 |
) |
| 48 |
def test_parsed_union_matches_generated_union(parsed_union: Any, generated_union: Any, parsed_file: str) -> None: |
| 49 |
"""The hand-written Parsed*ContentBlock unions must track the generated unions. |
| 50 |
|
| 51 |
If a block type only exists in the generated union, streaming snapshots |
| 52 |
construct it through the parsed union's permissive fallback and it lands |
| 53 |
as the wrong class at runtime (and the wrong type statically). |
| 54 |
""" |
| 55 |
parsed_members = {_to_generated(member) for member in _union_members(parsed_union)} |
| 56 |
generated_members = _union_members(generated_union) |
| 57 |
|
| 58 |
missing = sorted(member.__name__ for member in generated_members - parsed_members) |
| 59 |
extra = sorted(member.__name__ for member in parsed_members - generated_members) |
| 60 |
assert not missing and not extra, ( |
| 61 |
f"the hand-written parsed content block union in {parsed_file} is out of sync " |
| 62 |
f"with the generated union: missing={missing} extra={extra}. " |
| 63 |
f"Update the union in {parsed_file} to match the generated content block union." |
| 64 |
) |
| 65 |
|
| 66 |
|
| 67 |
def test_streamed_fallback_block_is_constructed_as_fallback_block() -> None: |
| 68 |
snapshot = ParsedBetaMessage( |
| 69 |
id="msg_123", |
| 70 |
type="message", |
| 71 |
role="assistant", |
| 72 |
content=[], |
| 73 |
model="claude-sonnet-4-5", |
| 74 |
stop_reason=None, |
| 75 |
stop_sequence=None, |
| 76 |
usage=BetaUsage(input_tokens=10, output_tokens=10), |
| 77 |
) |
| 78 |
|
| 79 |
event = { |
| 80 |
"type": "content_block_start", |
| 81 |
"index": 0, |
| 82 |
"content_block": { |
| 83 |
"type": "fallback", |
| 84 |
"from": {"model": "claude-sonnet-4-5"}, |
| 85 |
"to": {"model": "claude-haiku-4-5"}, |
| 86 |
"trigger": {"type": "refusal", "category": None}, |
| 87 |
}, |
| 88 |
} |
| 89 |
message = accumulate_event( |
| 90 |
event=cast(Any, event), |
| 91 |
current_snapshot=snapshot, |
| 92 |
json_bufs={}, |
| 93 |
request_headers=httpx2.Headers(), |
| 94 |
) |
| 95 |
|
| 96 |
block = message.content[0] |
| 97 |
assert isinstance(block, BetaFallbackBlock) |
| 98 |
assert block.type == "fallback" |
| 99 |
assert block.from_.model == "claude-sonnet-4-5" |
| 100 |
assert block.to.model == "claude-haiku-4-5" |
| 101 |
|
| 102 |
|
| 103 |
@pytest.mark.parametrize("block_type", [ParsedTextBlock, ParsedBetaTextBlock], ids=["non-beta", "beta"]) |
| 104 |
def test_parsed_output_is_readable_but_not_dumped(block_type: Any) -> None: |
| 105 |
block = construct_type_unchecked(value={"type": "text", "text": "{}", "citations": None}, type_=block_type) |
| 106 |
# the stream accumulator sets the parsed value after it builds the block |
| 107 |
block.parsed_output = {"greeting": "hi"} |
| 108 |
|
| 109 |
# the API rejects `parsed_output`, so a dumped block must not carry it |
| 110 |
assert "parsed_output" not in block.model_dump() |
| 111 |
assert "parsed_output" not in block.to_dict() |
| 112 |
assert "parsed_output" not in json.loads(block.to_json()) |
| 113 |
|
| 114 |
assert block.parsed_output == {"greeting": "hi"} |
| 115 |
|
| 116 |
# copies keep the parsed value but still dump without it |
| 117 |
for copied in [model_copy(block), model_copy(block, deep=True), copy.copy(block), copy.deepcopy(block)]: |
| 118 |
assert copied.parsed_output == block.parsed_output |
| 119 |
assert "parsed_output" not in copied.model_dump() |
| 120 |
assert "parsed_output" not in copied.to_dict() |
| 121 |
assert "parsed_output" not in json.loads(copied.to_json()) |