Debian Codegraph @

tests/lib/streaming/test_partial_json.py

raw
1 import copy
2 from typing import List, cast
3
4 import httpx2
5
6 from anthropic.types.beta import BetaDirectCaller, BetaToolUseBlock, BetaInputJSONDelta, BetaRawContentBlockDeltaEvent
7 from anthropic.types.tool_use_block import ToolUseBlock
8 from anthropic.types.beta.beta_usage import BetaUsage
9 from anthropic.lib.streaming._beta_messages import accumulate_event
10 from anthropic.types.beta.parsed_beta_message import ParsedBetaMessage
11
12
13 class TestPartialJson:
14 def test_trailing_strings_mode_header(self) -> None:
15 """Test behavior differences with and without the beta header for JSON parsing."""
16 message = ParsedBetaMessage(
17 id="msg_123",
18 type="message",
19 role="assistant",
20 content=[
21 BetaToolUseBlock(
22 type="tool_use",
23 input={},
24 id="tool_123",
25 name="test_tool",
26 caller=BetaDirectCaller(type="direct"),
27 )
28 ],
29 model="claude-sonnet-4-5",
30 stop_reason=None,
31 stop_sequence=None,
32 usage=BetaUsage(input_tokens=10, output_tokens=10),
33 )
34
35 # Test case 1: Complete JSON
36 complete_json = '{"key": "value"}'
37 event_complete = BetaRawContentBlockDeltaEvent(
38 type="content_block_delta",
39 index=0,
40 delta=BetaInputJSONDelta(type="input_json_delta", partial_json=complete_json),
41 )
42
43 # Both modes should handle complete JSON the same way
44 message1 = accumulate_event(
45 event=event_complete,
46 current_snapshot=copy.deepcopy(message),
47 json_bufs={},
48 request_headers=httpx2.Headers({"some-header": "value"}),
49 )
50 message2 = accumulate_event(
51 event=event_complete,
52 current_snapshot=copy.deepcopy(message),
53 json_bufs={},
54 request_headers=httpx2.Headers({"anthropic-beta": "fine-grained-tool-streaming-2025-05-14"}),
55 )
56
57 assert cast(ToolUseBlock, message1.content[0]).input == {"key": "value"}
58 assert cast(ToolUseBlock, message2.content[0]).input == {"key": "value"}
59
60 # Test case 2: Incomplete JSON with trailing string that will be treated differently
61 # Here we want to create a situation where regular mode and trailing strings mode behave differently
62 incomplete_json = '{"items": ["item1", "item2"], "unfinished_field": "incomplete value'
63 event_incomplete = BetaRawContentBlockDeltaEvent(
64 type="content_block_delta",
65 index=0,
66 delta=BetaInputJSONDelta(type="input_json_delta", partial_json=incomplete_json),
67 )
68
69 # Without beta header (standard mode)
70 message_standard = accumulate_event(
71 event=event_incomplete,
72 current_snapshot=copy.deepcopy(message),
73 json_bufs={},
74 request_headers=httpx2.Headers({"some-header": "value"}),
75 )
76
77 # With beta header (trailing strings mode)
78 message_trailing = accumulate_event(
79 event=event_incomplete,
80 current_snapshot=copy.deepcopy(message),
81 json_bufs={},
82 request_headers=httpx2.Headers({"anthropic-beta": "fine-grained-tool-streaming-2025-05-14"}),
83 )
84
85 standard_tool = cast(ToolUseBlock, message_standard.content[0])
86 trailing_tool = cast(ToolUseBlock, message_trailing.content[0])
87
88 # Both should have the valid complete part of the JSON
89 assert isinstance(standard_tool.input, dict)
90 assert isinstance(trailing_tool.input, dict)
91
92 standard_input = standard_tool.input # type: ignore
93 trailing_input = trailing_tool.input # type: ignore
94
95 items_standard = cast(List[str], standard_input["items"])
96 items_trailing = cast(List[str], trailing_input["items"])
97 assert items_standard == ["item1", "item2"]
98 assert items_trailing == ["item1", "item2"]
99
100 # The key difference is how they handle the incomplete field:
101 # Standard mode should not include the incomplete field
102 assert "unfinished_field" not in standard_input
103
104 # Trailing strings mode should include the incomplete field
105 assert "unfinished_field" in trailing_input
106 assert trailing_input["unfinished_field"] == "incomplete value"
107
108 def test_partial_json_with_invalid_json(self) -> None:
109 """Test that invalid JSON raises an error."""
110 message = ParsedBetaMessage(
111 id="msg_123",
112 type="message",
113 role="assistant",
114 content=[
115 BetaToolUseBlock(
116 type="tool_use",
117 input={},
118 id="tool_123",
119 name="test_tool",
120 caller=BetaDirectCaller(type="direct"),
121 )
122 ],
123 model="claude-sonnet-4-5",
124 stop_reason=None,
125 stop_sequence=None,
126 usage=BetaUsage(input_tokens=10, output_tokens=10),
127 )
128
129 invalid_json = '{"key": "value", "incomplete_field": bad_value'
130 event_invalid = BetaRawContentBlockDeltaEvent(
131 type="content_block_delta",
132 index=0,
133 delta=BetaInputJSONDelta(type="input_json_delta", partial_json=invalid_json),
134 )
135 try:
136 accumulate_event(
137 event=event_invalid,
138 current_snapshot=copy.deepcopy(message),
139 json_bufs={},
140 request_headers=httpx2.Headers({"anthropic-beta": "fine-grained-tool-streaming-2025-05-14"}),
141 )
142 raise AssertionError("Expected ValueError for invalid JSON, but no error was raised.")
143 except ValueError as e:
144 assert str(e).startswith(
145 "Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt."
146 )
147 except Exception as e:
148 raise AssertionError(f"Unexpected error type: {type(e).__name__} with message: {str(e)}") from e