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 .parse() sends the caller's betas and adds none of its own."""
216
217 @pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse with Pydantic models requires Pydantic v2")
218 def test_parse_does_not_add_beta_header(self, client: Anthropic, respx_mock: MockRouter) -> None:
219 """Verify .parse() sends no beta header when the caller passes no betas."""
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" not in request.headers
248
249 @pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse with Pydantic models requires Pydantic v2")
250 def test_parse_sends_caller_betas_unchanged(self, client: Anthropic, respx_mock: MockRouter) -> None:
251 """Verify .parse() sends exactly the betas the caller passes."""
252
253 class DataModel(BaseModel):
254 value: int
255
256 respx_mock.post("/v1/messages?beta=true").mock(
257 return_value=httpx2.Response(
258 200,
259 json={
260 "id": "msg_123",
261 "type": "message",
262 "role": "assistant",
263 "model": "claude-sonnet-4-5",
264 "content": [{"text": '{"value": 42}', "type": "text"}],
265 "stop_reason": "end_turn",
266 "usage": {"input_tokens": 10, "output_tokens": 20},
267 },
268 )
269 )
270
271 client.beta.messages.parse(
272 max_tokens=1024,
273 messages=[{"role": "user", "content": "Test"}],
274 model="claude-sonnet-4-5",
275 output_format=DataModel,
276 betas=["some-other-beta-feature"],
277 )
278
279 request = respx_mock.calls.last.request
280 assert request.headers["anthropic-beta"] == "some-other-beta-feature"
281
282 @pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse with Pydantic models requires Pydantic v2")
283 def test_parse_sends_explicit_structured_outputs_beta_once(self, client: Anthropic, respx_mock: MockRouter) -> None:
284 """Verify .parse() sends the structured-outputs beta once when the caller passes it."""
285
286 class DataModel(BaseModel):
287 value: int
288
289 respx_mock.post("/v1/messages?beta=true").mock(
290 return_value=httpx2.Response(
291 200,
292 json={
293 "id": "msg_123",
294 "type": "message",
295 "role": "assistant",
296 "model": "claude-sonnet-4-5",
297 "content": [{"text": '{"value": 42}', "type": "text"}],
298 "stop_reason": "end_turn",
299 "usage": {"input_tokens": 10, "output_tokens": 20},
300 },
301 )
302 )
303
304 client.beta.messages.parse(
305 max_tokens=1024,
306 messages=[{"role": "user", "content": "Test"}],
307 model="claude-sonnet-4-5",
308 output_format=DataModel,
309 betas=["structured-outputs-2025-12-15"],
310 )
311
312 request = respx_mock.calls.last.request
313 assert request.headers["anthropic-beta"] == "structured-outputs-2025-12-15"
314
315
316 class TestAsyncOutputFormatConversion:
317 """Test async variants of output_format conversion."""
318
319 @pytest.mark.skipif(_compat.PYDANTIC_V1, reason="parse with Pydantic models requires Pydantic v2")
320 async def test_async_parse_converts_pydantic(self, async_client: AsyncAnthropic, respx_mock: MockRouter) -> None:
321 """Verify async .parse() converts Pydantic models to output_config.format."""
322
323 class User(BaseModel):
324 name: str
325
326 respx_mock.post("/v1/messages?beta=true").mock(
327 return_value=httpx2.Response(
328 200,
329 json={
330 "id": "msg_123",
331 "type": "message",
332 "role": "assistant",
333 "model": "claude-sonnet-4-5",
334 "content": [{"text": '{"name": "John"}', "type": "text"}],
335 "stop_reason": "end_turn",
336 "usage": {"input_tokens": 10, "output_tokens": 20},
337 },
338 )
339 )
340
341 await async_client.beta.messages.parse(
342 max_tokens=1024,
343 messages=[{"role": "user", "content": "Test"}],
344 model="claude-sonnet-4-5",
345 output_format=User,
346 )
347
348 request = respx_mock.calls.last.request
349 body = json.loads(request.content)
350
351 assert "output_config" in body
352 assert "format" in body["output_config"]
353 assert "output_format" not in body