Debian Codegraph @

tests/api_resources/beta/test_output_format_conversion.py

raw
1 """Tests for output_format to output_config.format conversion."""
2
3 import json
4 import warnings
5
6 import httpx2
7 import pytest
8 from respx import MockRouter
9 from pydantic import BaseModel
10
11 from anthropic import Anthropic, AnthropicError, AsyncAnthropic, _compat
12
13
14 class TestOutputFormatConversion:
15 """Test that output_format is properly converted to output_config.format."""
16
17 @pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse with Pydantic models requires Pydantic v2")
18 def test_parse_converts_pydantic_to_output_config(self, client: Anthropic, respx_mock: MockRouter) -> None:
19 """Verify .parse() converts Pydantic models to output_config.format."""
20
21 class User(BaseModel):
22 name: str
23 age: int
24
25 respx_mock.post("/v1/messages?beta=true").mock(
26 return_value=httpx2.Response(
27 200,
28 json={
29 "id": "msg_123",
30 "type": "message",
31 "role": "assistant",
32 "model": "claude-sonnet-4-5",
33 "content": [{"text": '{"name": "John", "age": 30}', "type": "text"}],
34 "stop_reason": "end_turn",
35 "usage": {"input_tokens": 10, "output_tokens": 20},
36 },
37 )
38 )
39
40 client.beta.messages.parse(
41 max_tokens=1024,
42 messages=[{"role": "user", "content": "Test"}],
43 model="claude-sonnet-4-5",
44 output_format=User,
45 )
46
47 request = respx_mock.calls.last.request
48 body = json.loads(request.content)
49
50 # Should have output_config with format containing the User schema
51 assert "output_config" in body
52 assert "format" in body["output_config"]
53 assert body["output_config"]["format"]["type"] == "json_schema"
54 assert "properties" in body["output_config"]["format"]["schema"]
55 assert "name" in body["output_config"]["format"]["schema"]["properties"]
56 assert "age" in body["output_config"]["format"]["schema"]["properties"]
57
58 # Should NOT have output_format in request
59 assert "output_format" not in body
60
61 def test_stream_rejects_schema_dict(self, client: Anthropic) -> None:
62 """A raw schema dict is no longer accepted by `.stream()`; it belongs in `output_config.format`."""
63 with pytest.raises(TypeError, match="output_config"):
64 client.beta.messages.stream(
65 max_tokens=1024,
66 messages=[{"role": "user", "content": "Test"}],
67 model="claude-sonnet-4-5",
68 output_format={"type": "json_schema", "schema": {"type": "string"}}, # type: ignore[arg-type]
69 )
70
71
72 class TestOutputFormatNoDeprecationWarning:
73 """The typed `output_format=` of the helpers is the supported form and must not warn."""
74
75 @pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse with Pydantic models requires Pydantic v2")
76 def test_parse_does_not_warn_for_type(self, client: Anthropic, respx_mock: MockRouter) -> None:
77 """`.parse(output_format=Model)` is silent."""
78
79 class SimpleModel(BaseModel):
80 value: str
81
82 respx_mock.post("/v1/messages?beta=true").mock(
83 return_value=httpx2.Response(
84 200,
85 json={
86 "id": "msg_123",
87 "type": "message",
88 "role": "assistant",
89 "model": "claude-sonnet-4-5",
90 "content": [{"text": '{"value": "test"}', "type": "text"}],
91 "stop_reason": "end_turn",
92 "usage": {"input_tokens": 10, "output_tokens": 20},
93 },
94 )
95 )
96
97 with warnings.catch_warnings():
98 warnings.simplefilter("error", DeprecationWarning)
99 client.beta.messages.parse(
100 max_tokens=1024,
101 messages=[{"role": "user", "content": "Test"}],
102 model="claude-sonnet-4-5",
103 output_format=SimpleModel,
104 )
105
106 @pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse with Pydantic models requires Pydantic v2")
107 def test_stream_does_not_warn_for_type(self, client: Anthropic, respx_mock: MockRouter) -> None:
108 """`.stream(output_format=Model)` is silent."""
109 respx_mock.post("/v1/messages?beta=true").mock(
110 return_value=httpx2.Response(
111 200,
112 json={
113 "id": "msg_123",
114 "type": "message",
115 "role": "assistant",
116 "model": "claude-sonnet-4-5",
117 "content": [{"text": "test", "type": "text"}],
118 "stop_reason": "end_turn",
119 "usage": {"input_tokens": 10, "output_tokens": 20},
120 },
121 )
122 )
123
124 class Answer(BaseModel):
125 text: str
126
127 with warnings.catch_warnings():
128 warnings.simplefilter("error", DeprecationWarning)
129 with client.beta.messages.stream(
130 max_tokens=1024,
131 messages=[{"role": "user", "content": "Test"}],
132 model="claude-sonnet-4-5",
133 output_format=Answer,
134 ):
135 pass
136
137 body = json.loads(respx_mock.calls.last.request.content)
138 assert body["output_config"]["format"]["type"] == "json_schema"
139 assert "output_format" not in body
140
141 def test_no_warning_when_output_format_not_provided(self, client: Anthropic, respx_mock: MockRouter) -> None:
142 """Verify no deprecation warning when output_format is not used."""
143 respx_mock.post("/v1/messages?beta=true").mock(
144 return_value=httpx2.Response(
145 200,
146 json={
147 "id": "msg_123",
148 "type": "message",
149 "role": "assistant",
150 "model": "claude-sonnet-4-5",
151 "content": [{"text": "test", "type": "text"}],
152 "stop_reason": "end_turn",
153 "usage": {"input_tokens": 10, "output_tokens": 20},
154 },
155 )
156 )
157
158 with warnings.catch_warnings():
159 warnings.simplefilter("error", DeprecationWarning)
160 # Should not raise any warnings
161 client.beta.messages.create(
162 max_tokens=1024,
163 messages=[{"role": "user", "content": "Test"}],
164 model="claude-sonnet-4-5",
165 )
166
167 def test_no_warning_when_using_output_config(self, client: Anthropic, respx_mock: MockRouter) -> None:
168 """Verify no deprecation warning when using output_config.format directly."""
169 respx_mock.post("/v1/messages?beta=true").mock(
170 return_value=httpx2.Response(
171 200,
172 json={
173 "id": "msg_123",
174 "type": "message",
175 "role": "assistant",
176 "model": "claude-sonnet-4-5",
177 "content": [{"text": "test", "type": "text"}],
178 "stop_reason": "end_turn",
179 "usage": {"input_tokens": 10, "output_tokens": 20},
180 },
181 )
182 )
183
184 with warnings.catch_warnings():
185 warnings.simplefilter("error", DeprecationWarning)
186 # Should not raise any warnings
187 client.beta.messages.create(
188 max_tokens=1024,
189 messages=[{"role": "user", "content": "Test"}],
190 model="claude-sonnet-4-5",
191 output_config={"format": {"type": "json_schema", "schema": {"type": "object"}}},
192 )
193
194
195 class TestOutputConfigConflict:
196 """Test that providing both output_format and output_config.format raises an error."""
197
198 def test_parse_rejects_both_output_format_and_config(self, client: Anthropic) -> None:
199 """Verify .parse() raises error when both output_format and output_config.format are provided."""
200
201 class TestModel(BaseModel):
202 value: str
203
204 with pytest.raises(AnthropicError, match="Both output_format and output_config.format were provided"):
205 client.beta.messages.parse(
206 max_tokens=1024,
207 messages=[{"role": "user", "content": "Test"}],
208 model="claude-sonnet-4-5",
209 output_format=TestModel,
210 output_config={"format": {"type": "json_schema", "schema": {"type": "string"}}},
211 )
212
213
214 class TestStructuredOutputsBetaHeader:
215 """Test that structured-outputs-2025-12-15 beta header is added for .parse()."""
216
217 @pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse with Pydantic models requires Pydantic v2")
218 def test_parse_adds_structured_outputs_beta_header(self, client: Anthropic, respx_mock: MockRouter) -> None:
219 """Verify .parse() auto-adds structured-outputs-2025-12-15 beta header."""
220
221 class DataModel(BaseModel):
222 value: int
223
224 respx_mock.post("/v1/messages?beta=true").mock(
225 return_value=httpx2.Response(
226 200,
227 json={
228 "id": "msg_123",
229 "type": "message",
230 "role": "assistant",
231 "model": "claude-sonnet-4-5",
232 "content": [{"text": '{"value": 42}', "type": "text"}],
233 "stop_reason": "end_turn",
234 "usage": {"input_tokens": 10, "output_tokens": 20},
235 },
236 )
237 )
238
239 client.beta.messages.parse(
240 max_tokens=1024,
241 messages=[{"role": "user", "content": "Test"}],
242 model="claude-sonnet-4-5",
243 output_format=DataModel,
244 )
245
246 request = respx_mock.calls.last.request
247 assert "anthropic-beta" in request.headers
248 assert "structured-outputs-2025-12-15" in request.headers["anthropic-beta"]
249
250 @pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse with Pydantic models requires Pydantic v2")
251 def test_parse_preserves_existing_betas(self, client: Anthropic, respx_mock: MockRouter) -> None:
252 """Verify .parse() preserves other beta headers when adding structured-outputs."""
253
254 class DataModel(BaseModel):
255 value: int
256
257 respx_mock.post("/v1/messages?beta=true").mock(
258 return_value=httpx2.Response(
259 200,
260 json={
261 "id": "msg_123",
262 "type": "message",
263 "role": "assistant",
264 "model": "claude-sonnet-4-5",
265 "content": [{"text": '{"value": 42}', "type": "text"}],
266 "stop_reason": "end_turn",
267 "usage": {"input_tokens": 10, "output_tokens": 20},
268 },
269 )
270 )
271
272 client.beta.messages.parse(
273 max_tokens=1024,
274 messages=[{"role": "user", "content": "Test"}],
275 model="claude-sonnet-4-5",
276 output_format=DataModel,
277 betas=["some-other-beta-feature"],
278 )
279
280 request = respx_mock.calls.last.request
281 beta_header = request.headers["anthropic-beta"]
282 assert "structured-outputs-2025-12-15" in beta_header
283 assert "some-other-beta-feature" in beta_header
284
285 @pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse with Pydantic models requires Pydantic v2")
286 def test_parse_does_not_duplicate_beta_header(self, client: Anthropic, respx_mock: MockRouter) -> None:
287 """Verify .parse() doesn't duplicate structured-outputs beta if already present."""
288
289 class DataModel(BaseModel):
290 value: int
291
292 respx_mock.post("/v1/messages?beta=true").mock(
293 return_value=httpx2.Response(
294 200,
295 json={
296 "id": "msg_123",
297 "type": "message",
298 "role": "assistant",
299 "model": "claude-sonnet-4-5",
300 "content": [{"text": '{"value": 42}', "type": "text"}],
301 "stop_reason": "end_turn",
302 "usage": {"input_tokens": 10, "output_tokens": 20},
303 },
304 )
305 )
306
307 client.beta.messages.parse(
308 max_tokens=1024,
309 messages=[{"role": "user", "content": "Test"}],
310 model="claude-sonnet-4-5",
311 output_format=DataModel,
312 betas=["structured-outputs-2025-12-15"],
313 )
314
315 request = respx_mock.calls.last.request
316 beta_header = request.headers["anthropic-beta"]
317 # Should only appear once
318 assert beta_header.count("structured-outputs-2025-12-15") == 1
319
320
321 class TestAsyncOutputFormatConversion:
322 """Test async variants of output_format conversion."""
323
324 @pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse with Pydantic models requires Pydantic v2")
325 async def test_async_parse_converts_pydantic(self, async_client: AsyncAnthropic, respx_mock: MockRouter) -> None:
326 """Verify async .parse() converts Pydantic models to output_config.format."""
327
328 class User(BaseModel):
329 name: str
330
331 respx_mock.post("/v1/messages?beta=true").mock(
332 return_value=httpx2.Response(
333 200,
334 json={
335 "id": "msg_123",
336 "type": "message",
337 "role": "assistant",
338 "model": "claude-sonnet-4-5",
339 "content": [{"text": '{"name": "John"}', "type": "text"}],
340 "stop_reason": "end_turn",
341 "usage": {"input_tokens": 10, "output_tokens": 20},
342 },
343 )
344 )
345
346 await async_client.beta.messages.parse(
347 max_tokens=1024,
348 messages=[{"role": "user", "content": "Test"}],
349 model="claude-sonnet-4-5",
350 output_format=User,
351 )
352
353 request = respx_mock.calls.last.request
354 body = json.loads(request.content)
355
356 assert "output_config" in body
357 assert "format" in body["output_config"]
358 assert "output_format" not in body