Debian Codegraph @

tests/test_client.py

raw
1 from __future__ import annotations
2
3 import gc
4 import os
5 import sys
6 import copy
7 import json
8 import asyncio
9 import inspect
10 import dataclasses
11 import tracemalloc
12 from typing import Any, Union, TypeVar, Callable, Iterable, Iterator, Optional, Coroutine, cast
13 from pathlib import Path
14 from datetime import date, datetime, timezone
15 from typing_extensions import Literal, AsyncIterator, override
16
17 import httpx2
18 import pytest
19 from respx import MockRouter
20 from pydantic import ValidationError
21
22 from anthropic import Anthropic, AsyncAnthropic, APIResponseValidationError
23 from anthropic._types import Omit
24 from anthropic._utils import asyncify
25 from anthropic._models import BaseModel, FinalRequestOptions
26 from anthropic._streaming import Stream, AsyncStream
27 from anthropic._exceptions import APIStatusError, APITimeoutError, APIResponseValidationError
28 from anthropic._base_client import (
29 DEFAULT_TIMEOUT,
30 HTTPX_DEFAULT_TIMEOUT,
31 BaseClient,
32 OtherPlatform,
33 DefaultHttpxClient,
34 DefaultAsyncHttpxClient,
35 get_platform,
36 get_architecture,
37 make_request_options,
38 )
39
40 from .utils import update_env
41
42 T = TypeVar("T")
43 base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010")
44 api_key = "my-anthropic-api-key"
45
46
47 def _get_params(client: BaseClient[Any, Any]) -> dict[str, str]:
48 request = client._build_request(FinalRequestOptions(method="get", url="/foo"))
49 url = httpx2.URL(request.url)
50 return dict(url.params)
51
52
53 def _low_retry_timeout(*_args: Any, **_kwargs: Any) -> float:
54 return 0.1
55
56
57 def mirror_request_content(request: httpx2.Request) -> httpx2.Response:
58 return httpx2.Response(200, content=request.content)
59
60
61 # note: we can't use the httpx2.MockTransport class as it consumes the request
62 # body itself, which means we can't test that the body is read lazily
63 class MockTransport(httpx2.BaseTransport, httpx2.AsyncBaseTransport):
64 def __init__(
65 self,
66 handler: Callable[[httpx2.Request], httpx2.Response]
67 | Callable[[httpx2.Request], Coroutine[Any, Any, httpx2.Response]],
68 ) -> None:
69 self.handler = handler
70
71 @override
72 def handle_request(
73 self,
74 request: httpx2.Request,
75 ) -> httpx2.Response:
76 assert not inspect.iscoroutinefunction(self.handler), "handler must not be a coroutine function"
77 assert inspect.isfunction(self.handler), "handler must be a function"
78 return self.handler(request)
79
80 @override
81 async def handle_async_request(
82 self,
83 request: httpx2.Request,
84 ) -> httpx2.Response:
85 assert inspect.iscoroutinefunction(self.handler), "handler must be a coroutine function"
86 return await self.handler(request)
87
88
89 @dataclasses.dataclass
90 class Counter:
91 value: int = 0
92
93
94 def _make_sync_iterator(iterable: Iterable[T], counter: Optional[Counter] = None) -> Iterator[T]:
95 for item in iterable:
96 if counter:
97 counter.value += 1
98 yield item
99
100
101 async def _make_async_iterator(iterable: Iterable[T], counter: Optional[Counter] = None) -> AsyncIterator[T]:
102 for item in iterable:
103 if counter:
104 counter.value += 1
105 yield item
106
107
108 def _get_open_connections(client: Anthropic | AsyncAnthropic) -> int:
109 transport = client._client._transport
110 assert isinstance(transport, httpx2.HTTPTransport) or isinstance(transport, httpx2.AsyncHTTPTransport)
111
112 pool = transport._pool
113 return len(pool._requests)
114
115
116 @pytest.mark.parametrize("status_code", [400, 401, 403, 404, 409, 413, 422, 429, 500, 503, 529])
117 def test_make_status_error_sync_async_parity(status_code: int) -> None:
118 # Anthropic._make_status_error and AsyncAnthropic._make_status_error are
119 # separate manually-maintained copies; this guards against them drifting.
120 sync_client = Anthropic(base_url=base_url, api_key=api_key, _strict_response_validation=True)
121 async_client = AsyncAnthropic(base_url=base_url, api_key=api_key, _strict_response_validation=True)
122 response = httpx2.Response(status_code, request=httpx2.Request("GET", "/"))
123
124 sync_err = sync_client._make_status_error("msg", body=None, response=response)
125 async_err = async_client._make_status_error("msg", body=None, response=response)
126
127 assert type(sync_err) is type(async_err), (
128 f"sync returned {type(sync_err).__name__}, async returned {type(async_err).__name__}"
129 )
130
131
132 class TestAnthropic:
133 @pytest.mark.respx(base_url=base_url)
134 def test_raw_response(self, respx_mock: MockRouter, client: Anthropic) -> None:
135 respx_mock.post("/foo").mock(return_value=httpx2.Response(200, json={"foo": "bar"}))
136
137 response = client.post("/foo", cast_to=httpx2.Response)
138 assert response.status_code == 200
139 assert isinstance(response, httpx2.Response)
140 assert response.json() == {"foo": "bar"}
141
142 @pytest.mark.respx(base_url=base_url)
143 def test_raw_response_for_binary(self, respx_mock: MockRouter, client: Anthropic) -> None:
144 respx_mock.post("/foo").mock(
145 return_value=httpx2.Response(200, headers={"Content-Type": "application/binary"}, content='{"foo": "bar"}')
146 )
147
148 response = client.post("/foo", cast_to=httpx2.Response)
149 assert response.status_code == 200
150 assert isinstance(response, httpx2.Response)
151 assert response.json() == {"foo": "bar"}
152
153 def test_copy(self, client: Anthropic) -> None:
154 copied = client.copy()
155 assert id(copied) != id(client)
156
157 copied = client.copy(api_key="another my-anthropic-api-key")
158 assert copied.api_key == "another my-anthropic-api-key"
159 assert client.api_key == "my-anthropic-api-key"
160
161 def test_copy_default_options(self, client: Anthropic) -> None:
162 # options that have a default are overridden correctly
163 copied = client.copy(max_retries=7)
164 assert copied.max_retries == 7
165 assert client.max_retries == 2
166
167 copied2 = copied.copy(max_retries=6)
168 assert copied2.max_retries == 6
169 assert copied.max_retries == 7
170
171 # timeout
172 assert isinstance(client.timeout, httpx2.Timeout)
173 copied = client.copy(timeout=None)
174 assert copied.timeout is None
175 assert isinstance(client.timeout, httpx2.Timeout)
176
177 def test_copy_default_headers(self) -> None:
178 client = Anthropic(
179 base_url=base_url, api_key=api_key, _strict_response_validation=True, default_headers={"X-Foo": "bar"}
180 )
181 assert client.default_headers["X-Foo"] == "bar"
182
183 # does not override the already given value when not specified
184 copied = client.copy()
185 assert copied.default_headers["X-Foo"] == "bar"
186
187 # merges already given headers
188 copied = client.copy(default_headers={"X-Bar": "stainless"})
189 assert copied.default_headers["X-Foo"] == "bar"
190 assert copied.default_headers["X-Bar"] == "stainless"
191
192 # uses new values for any already given headers
193 copied = client.copy(default_headers={"X-Foo": "stainless"})
194 assert copied.default_headers["X-Foo"] == "stainless"
195
196 # set_default_headers
197
198 # completely overrides already set values
199 copied = client.copy(set_default_headers={})
200 assert copied.default_headers.get("X-Foo") is None
201
202 copied = client.copy(set_default_headers={"X-Bar": "Robert"})
203 assert copied.default_headers["X-Bar"] == "Robert"
204
205 with pytest.raises(
206 ValueError,
207 match="`default_headers` and `set_default_headers` arguments are mutually exclusive",
208 ):
209 client.copy(set_default_headers={}, default_headers={"X-Foo": "Bar"})
210 client.close()
211
212 def test_copy_default_query(self) -> None:
213 client = Anthropic(
214 base_url=base_url, api_key=api_key, _strict_response_validation=True, default_query={"foo": "bar"}
215 )
216 assert _get_params(client)["foo"] == "bar"
217
218 # does not override the already given value when not specified
219 copied = client.copy()
220 assert _get_params(copied)["foo"] == "bar"
221
222 # merges already given params
223 copied = client.copy(default_query={"bar": "stainless"})
224 params = _get_params(copied)
225 assert params["foo"] == "bar"
226 assert params["bar"] == "stainless"
227
228 # uses new values for any already given headers
229 copied = client.copy(default_query={"foo": "stainless"})
230 assert _get_params(copied)["foo"] == "stainless"
231
232 # set_default_query
233
234 # completely overrides already set values
235 copied = client.copy(set_default_query={})
236 assert _get_params(copied) == {}
237
238 copied = client.copy(set_default_query={"bar": "Robert"})
239 assert _get_params(copied)["bar"] == "Robert"
240
241 with pytest.raises(
242 ValueError,
243 # TODO: update
244 match="`default_query` and `set_default_query` arguments are mutually exclusive",
245 ):
246 client.copy(set_default_query={}, default_query={"foo": "Bar"})
247
248 client.close()
249
250 def test_copy_signature(self, client: Anthropic) -> None:
251 # ensure the same parameters that can be passed to the client are defined in the `.copy()` method
252 init_signature = inspect.signature(
253 # mypy doesn't like that we access the `__init__` property.
254 client.__init__, # type: ignore[misc]
255 )
256 copy_signature = inspect.signature(client.copy)
257 exclude_params = {"transport", "proxies", "_strict_response_validation", "_token_cache"}
258
259 for name in init_signature.parameters.keys():
260 if name in exclude_params:
261 continue
262
263 copy_param = copy_signature.parameters.get(name)
264 assert copy_param is not None, f"copy() signature is missing the {name} param"
265
266 @pytest.mark.skipif(sys.version_info >= (3, 10), reason="fails because of a memory leak that started from 3.12")
267 def test_copy_build_request(self, client: Anthropic) -> None:
268 options = FinalRequestOptions(method="get", url="/foo")
269
270 def build_request(options: FinalRequestOptions) -> None:
271 client_copy = client.copy()
272 client_copy._build_request(options)
273
274 # ensure that the machinery is warmed up before tracing starts.
275 build_request(options)
276 gc.collect()
277
278 tracemalloc.start(1000)
279
280 snapshot_before = tracemalloc.take_snapshot()
281
282 ITERATIONS = 10
283 for _ in range(ITERATIONS):
284 build_request(options)
285
286 gc.collect()
287 snapshot_after = tracemalloc.take_snapshot()
288
289 tracemalloc.stop()
290
291 def add_leak(leaks: list[tracemalloc.StatisticDiff], diff: tracemalloc.StatisticDiff) -> None:
292 if diff.count == 0:
293 # Avoid false positives by considering only leaks (i.e. allocations that persist).
294 return
295
296 if diff.count % ITERATIONS != 0:
297 # Avoid false positives by considering only leaks that appear per iteration.
298 return
299
300 for frame in diff.traceback:
301 if any(
302 frame.filename.endswith(fragment)
303 for fragment in [
304 # to_raw_response_wrapper leaks through the @functools.wraps() decorator.
305 #
306 # removing the decorator fixes the leak for reasons we don't understand.
307 "anthropic/_response.py",
308 # pydantic.BaseModel.model_dump || pydantic.BaseModel.dict leak memory for some reason.
309 "anthropic/_compat.py",
310 # Standard library leaks we don't care about.
311 "/logging/__init__.py",
312 ]
313 ):
314 return
315
316 leaks.append(diff)
317
318 leaks: list[tracemalloc.StatisticDiff] = []
319 for diff in snapshot_after.compare_to(snapshot_before, "traceback"):
320 add_leak(leaks, diff)
321 if leaks:
322 for leak in leaks:
323 print("MEMORY LEAK:", leak)
324 for frame in leak.traceback:
325 print(frame)
326 raise AssertionError()
327
328 def test_request_timeout(self, client: Anthropic) -> None:
329 request = client._build_request(FinalRequestOptions(method="get", url="/foo"))
330 timeout = httpx2.Timeout(**request.extensions["timeout"]) # type: ignore
331 assert timeout == DEFAULT_TIMEOUT
332
333 request = client._build_request(FinalRequestOptions(method="get", url="/foo", timeout=httpx2.Timeout(100.0)))
334 timeout = httpx2.Timeout(**request.extensions["timeout"]) # type: ignore
335 assert timeout == httpx2.Timeout(100.0)
336
337 def test_client_timeout_option(self) -> None:
338 client = Anthropic(
339 base_url=base_url, api_key=api_key, _strict_response_validation=True, timeout=httpx2.Timeout(0)
340 )
341
342 request = client._build_request(FinalRequestOptions(method="get", url="/foo"))
343 timeout = httpx2.Timeout(**request.extensions["timeout"]) # type: ignore
344 assert timeout == httpx2.Timeout(0)
345
346 client.close()
347
348 def test_http_client_timeout_option(self) -> None:
349 # custom timeout given to the httpx client should be used
350 with httpx2.Client(timeout=None) as http_client:
351 client = Anthropic(
352 base_url=base_url, api_key=api_key, _strict_response_validation=True, http_client=http_client
353 )
354
355 request = client._build_request(FinalRequestOptions(method="get", url="/foo"))
356 timeout = httpx2.Timeout(**request.extensions["timeout"]) # type: ignore
357 assert timeout == httpx2.Timeout(None)
358
359 client.close()
360
361 # no timeout given to the httpx client should not use the httpx default
362 with httpx2.Client() as http_client:
363 client = Anthropic(
364 base_url=base_url, api_key=api_key, _strict_response_validation=True, http_client=http_client
365 )
366
367 request = client._build_request(FinalRequestOptions(method="get", url="/foo"))
368 timeout = httpx2.Timeout(**request.extensions["timeout"]) # type: ignore
369 assert timeout == DEFAULT_TIMEOUT
370
371 client.close()
372
373 # explicitly passing the default timeout currently results in it being ignored
374 with httpx2.Client(timeout=HTTPX_DEFAULT_TIMEOUT) as http_client:
375 client = Anthropic(
376 base_url=base_url, api_key=api_key, _strict_response_validation=True, http_client=http_client
377 )
378
379 request = client._build_request(FinalRequestOptions(method="get", url="/foo"))
380 timeout = httpx2.Timeout(**request.extensions["timeout"]) # type: ignore
381 assert timeout == DEFAULT_TIMEOUT # our default
382
383 client.close()
384
385 async def test_invalid_http_client(self) -> None:
386 with pytest.raises(TypeError, match="Invalid `http_client` arg"):
387 async with httpx2.AsyncClient() as http_client:
388 Anthropic(
389 base_url=base_url,
390 api_key=api_key,
391 _strict_response_validation=True,
392 http_client=cast(Any, http_client),
393 )
394
395 def test_httpx_objects_rejected(self, client: Anthropic) -> None:
396 # `import httpx` resolves to `httpx2` in this test suite, so fake the `httpx` classes
397 class Timeout:
398 __module__ = "httpx"
399
400 class HTTPTransport:
401 __module__ = "httpx._transports.default"
402
403 class Client:
404 __module__ = "httpx"
405
406 class MyClient(Client):
407 pass
408
409 timeout: Any = Timeout()
410 transport: Any = HTTPTransport()
411 http_client: Any = MyClient()
412
413 with pytest.raises(TypeError, match="Use `httpx2.Client` instead"):
414 Anthropic(base_url=base_url, api_key=api_key, _strict_response_validation=True, http_client=http_client)
415
416 with pytest.raises(TypeError, match="Use `httpx2.Timeout` instead"):
417 Anthropic(base_url=base_url, api_key=api_key, _strict_response_validation=True, timeout=timeout)
418
419 with pytest.raises(TypeError, match="Use `httpx2.Timeout` instead"):
420 client.post("/foo", cast_to=httpx2.Response, options={"timeout": timeout})
421
422 with pytest.raises(TypeError, match="Use `httpx2.HTTPTransport` instead"):
423 DefaultHttpxClient(transport=transport)
424
425 def test_default_headers_option(self) -> None:
426 test_client = Anthropic(
427 base_url=base_url, api_key=api_key, _strict_response_validation=True, default_headers={"X-Foo": "bar"}
428 )
429 request = test_client._build_request(FinalRequestOptions(method="get", url="/foo"))
430 assert request.headers.get("x-foo") == "bar"
431 assert request.headers.get("x-stainless-lang") == "python"
432
433 test_client2 = Anthropic(
434 base_url=base_url,
435 api_key=api_key,
436 _strict_response_validation=True,
437 default_headers={
438 "X-Foo": "stainless",
439 "X-Stainless-Lang": "my-overriding-header",
440 },
441 )
442 request = test_client2._build_request(FinalRequestOptions(method="get", url="/foo"))
443 assert request.headers.get("x-foo") == "stainless"
444 assert request.headers.get("x-stainless-lang") == "my-overriding-header"
445
446 test_client.close()
447 test_client2.close()
448
449 def test_validate_headers(self) -> None:
450 client = Anthropic(base_url=base_url, api_key=api_key, _strict_response_validation=True)
451 request = client._build_request(FinalRequestOptions(method="get", url="/foo"))
452 assert request.headers.get("X-Api-Key") == api_key
453
454 def no_default_credentials(**_kwargs: object) -> None:
455 return None
456
457 with pytest.MonkeyPatch.context() as monkeypatch:
458 monkeypatch.setattr("anthropic._client.default_credentials", no_default_credentials)
459 with update_env(**{"ANTHROPIC_API_KEY": Omit()}):
460 client2 = Anthropic(base_url=base_url, api_key=None, _strict_response_validation=True)
461
462 with pytest.raises(
463 TypeError,
464 match="Could not resolve authentication method. Expected one of api_key, auth_token, or credentials to be set. Or for one of the `X-Api-Key` or `Authorization` headers to be explicitly omitted",
465 ):
466 client2._build_request(FinalRequestOptions(method="get", url="/foo"))
467
468 request2 = client2._build_request(FinalRequestOptions(method="get", url="/foo", headers={"X-Api-Key": Omit()}))
469 assert request2.headers.get("X-Api-Key") is None
470 request3 = client2._build_request(FinalRequestOptions(method="get", url="/foo", headers={"x-api-key": Omit()}))
471 assert request3.headers.get("X-Api-Key") is None
472 request4 = client2._build_request(
473 FinalRequestOptions(method="get", url="/foo", headers={"x-api-key": "from-header"})
474 )
475 assert request4.headers.get_list("X-Api-Key") == ["from-header"]
476
477 def test_default_headers_case_insensitive(self) -> None:
478 # replaces the SDK's own `User-Agent` rather than being sent next to it
479 test_client = Anthropic(
480 base_url=base_url,
481 api_key=api_key,
482 _strict_response_validation=True,
483 default_headers={"user-agent": "my-app/1.0"},
484 )
485 request = test_client._build_request(FinalRequestOptions(method="get", url="/foo"))
486 assert request.headers.get_list("user-agent") == ["my-app/1.0"]
487
488 test_client.close()
489
490 def test_extra_headers_case_insensitive(self, client: Anthropic) -> None:
491 request = client.with_options(default_headers={"X-Foo": "client"})._build_request(
492 FinalRequestOptions(method="post", url="/foo", **make_request_options(extra_headers={"x-foo": "request"}))
493 )
494 assert request.headers.get_list("x-foo") == ["request"]
495
496 def test_omit_headers_case_insensitive(self, client: Anthropic) -> None:
497 request = client.with_options(default_headers={"X-Foo": "bar"})._build_request(
498 FinalRequestOptions(method="post", url="/foo", **make_request_options(extra_headers={"x-foo": Omit()}))
499 )
500 assert "x-foo" not in request.headers
501
502 request = client.with_options(default_headers=cast("dict[str, str]", {"X-FOO": Omit()}))._build_request(
503 FinalRequestOptions(method="post", url="/foo")
504 )
505 assert "x-foo" not in request.headers
506
507 request = client._build_request(
508 FinalRequestOptions(
509 method="post", url="/foo", **make_request_options(extra_headers={"X-STAINLESS-LANG": Omit()})
510 )
511 )
512 assert "x-stainless-lang" not in request.headers
513
514 # request-time SDK headers sit in the lowest layer too, so a client-level `Omit()` also removes them
515 request = client.with_options(
516 default_headers=cast("dict[str, str]", {"X-Stainless-Retry-Count": Omit()})
517 )._build_request(FinalRequestOptions(method="post", url="/foo"))
518 assert "x-stainless-retry-count" not in request.headers
519
520 def test_with_options_headers_case_insensitive(self, client: Anthropic) -> None:
521 copied = client.with_options(default_headers={"X-Foo": "one"}).with_options(default_headers={"x-foo": "two"})
522 request = copied._build_request(FinalRequestOptions(method="get", url="/foo"))
523 assert request.headers.get_list("x-foo") == ["two"]
524 assert copied.default_headers["x-foo"] == "two"
525 assert "X-Foo" not in copied.default_headers
526
527 def test_multipart_content_type_case_insensitive(self, client: Anthropic) -> None:
528 request = client._build_request(
529 FinalRequestOptions.construct(
530 method="post",
531 url="/foo",
532 headers={"content-type": "Multipart/Form-Data"},
533 json_data={"foo": "bar"},
534 files=[("file", ("foo.txt", b"hello world"))],
535 )
536 )
537 content_types = request.headers.get_list("content-type")
538 assert len(content_types) == 1, content_types
539 assert content_types[0].startswith("multipart/form-data; boundary=")
540 assert b'name="foo"' in request.read()
541
542 def test_default_query_option(self) -> None:
543 client = Anthropic(
544 base_url=base_url, api_key=api_key, _strict_response_validation=True, default_query={"query_param": "bar"}
545 )
546 request = client._build_request(FinalRequestOptions(method="get", url="/foo"))
547 url = httpx2.URL(request.url)
548 assert dict(url.params) == {"query_param": "bar"}
549
550 request = client._build_request(
551 FinalRequestOptions(
552 method="get",
553 url="/foo",
554 params={"foo": "baz", "query_param": "overridden"},
555 )
556 )
557 url = httpx2.URL(request.url)
558 assert dict(url.params) == {"foo": "baz", "query_param": "overridden"}
559
560 client.close()
561
562 def test_hardcoded_query_params_in_url(self, client: Anthropic) -> None:
563 request = client._build_request(FinalRequestOptions(method="get", url="/foo?beta=true"))
564 url = httpx2.URL(request.url)
565 assert dict(url.params) == {"beta": "true"}
566
567 request = client._build_request(
568 FinalRequestOptions(
569 method="get",
570 url="/foo?beta=true",
571 params={"limit": "10", "page": "abc"},
572 )
573 )
574 url = httpx2.URL(request.url)
575 assert dict(url.params) == {"beta": "true", "limit": "10", "page": "abc"}
576
577 request = client._build_request(
578 FinalRequestOptions(
579 method="get",
580 url="/files/a%2Fb?beta=true",
581 params={"limit": "10"},
582 )
583 )
584 assert request.url.raw_path == b"/files/a%2Fb?beta=true&limit=10"
585
586 def test_request_extra_json(self, client: Anthropic) -> None:
587 request = client._build_request(
588 FinalRequestOptions(
589 method="post",
590 url="/foo",
591 json_data={"foo": "bar"},
592 extra_json={"baz": False},
593 ),
594 )
595 data = json.loads(request.content.decode("utf-8"))
596 assert data == {"foo": "bar", "baz": False}
597
598 request = client._build_request(
599 FinalRequestOptions(
600 method="post",
601 url="/foo",
602 extra_json={"baz": False},
603 ),
604 )
605 data = json.loads(request.content.decode("utf-8"))
606 assert data == {"baz": False}
607
608 # `extra_json` takes priority over `json_data` when keys clash
609 request = client._build_request(
610 FinalRequestOptions(
611 method="post",
612 url="/foo",
613 json_data={"foo": "bar", "baz": True},
614 extra_json={"baz": None},
615 ),
616 )
617 data = json.loads(request.content.decode("utf-8"))
618 assert data == {"foo": "bar", "baz": None}
619
620 @pytest.mark.respx(base_url=base_url)
621 def test_request_extra_json_merged_before_prepare_options(self, respx_mock: MockRouter) -> None:
622 # client hooks (e.g. a `_prepare_options` that derives the URL from the body) see the body with `extra_body` applied
623 seen: list[FinalRequestOptions] = []
624
625 class Client(Anthropic):
626 @override
627 def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions:
628 seen.append(copy.deepcopy(options))
629 return super()._prepare_options(options)
630
631 respx_mock.post("/foo").mock(return_value=httpx2.Response(200, json={}))
632 client = Client(base_url=base_url, api_key=api_key, _strict_response_validation=True)
633
634 response = client.post(
635 "/foo",
636 cast_to=httpx2.Response,
637 body={"foo": "bar", "baz": True},
638 options=make_request_options(extra_body={"baz": None}),
639 )
640
641 assert len(seen) == 1
642 assert seen[0].json_data == {"foo": "bar", "baz": None}
643 assert seen[0].extra_json is None
644 assert json.loads(response.request.content) == {"foo": "bar", "baz": None}
645
646 @pytest.mark.respx(base_url=base_url)
647 def test_request_data_prepared_before_prepare_options(
648 self, respx_mock: MockRouter, client: Anthropic, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
649 ) -> None:
650 # client hooks see the data as it is sent: files read, omitted keys dropped, iterables materialised, dates formatted
651 seen: list[FinalRequestOptions] = []
652 prepare_options = client._prepare_options
653
654 def record(options: FinalRequestOptions) -> FinalRequestOptions:
655 seen.append(copy.deepcopy(options))
656 return prepare_options(options)
657
658 monkeypatch.setattr(client, "_prepare_options", record)
659 respx_mock.post("/foo").mock(return_value=httpx2.Response(200, json={}))
660 monkeypatch.setattr("anthropic._utils._prepare.FILE_INPUT_MARKERS", (("type", "base64", "data"),))
661 path = tmp_path / "file.bin"
662 path.write_bytes(b"Hello")
663
664 client.post(
665 "/foo",
666 cast_to=httpx2.Response,
667 body={
668 "source": {"type": "base64", "data": path},
669 "dropped": Omit(),
670 "at": datetime(2024, 1, 2, 3, 4, 5, tzinfo=timezone.utc),
671 },
672 options=make_request_options(
673 query={"since": datetime(2024, 1, 2, 3, 4, 5)},
674 extra_body={"baz": (1, 2), "on": date(2024, 1, 2)},
675 extra_query={"filter": {"q": Omit(), "r": 1}},
676 ),
677 )
678
679 assert len(seen) == 1
680 assert seen[0].json_data == {
681 "source": {"type": "base64", "data": "SGVsbG8="},
682 "at": "2024-01-02T03:04:05+00:00",
683 "baz": [1, 2],
684 "on": "2024-01-02",
685 }
686 assert seen[0].params == {"since": "2024-01-02T03:04:05", "filter": {"r": 1}}
687
688 @pytest.mark.respx(base_url=base_url)
689 def test_request_does_not_modify_the_options_it_is_given(self, respx_mock: MockRouter, client: Anthropic) -> None:
690 respx_mock.post("/foo").mock(return_value=httpx2.Response(200, json={}))
691 options = FinalRequestOptions.construct(
692 method="post",
693 url="/foo",
694 json_data={"foo": "bar", "at": datetime(2024, 1, 2, 3, 4, 5, tzinfo=timezone.utc)},
695 extra_json={"baz": (1, 2)},
696 params={"since": date(2024, 1, 2)},
697 )
698 json_data, extra_json, params = options.json_data, options.extra_json, options.params
699
700 response = client.request(httpx2.Response, options)
701
702 # what is sent is merged and prepared
703 assert json.loads(response.request.content) == {"foo": "bar", "at": "2024-01-02T03:04:05+00:00", "baz": [1, 2]}
704 assert response.request.url.params["since"] == "2024-01-02"
705 # on a copy: the caller's options still hold the objects they were given, unchanged
706 assert options.json_data is json_data
707 assert options.extra_json is extra_json
708 assert options.params is params
709 assert json_data == {"foo": "bar", "at": datetime(2024, 1, 2, 3, 4, 5, tzinfo=timezone.utc)}
710 assert extra_json == {"baz": (1, 2)}
711 assert params == {"since": date(2024, 1, 2)}
712
713 def test_request_extra_headers(self, client: Anthropic) -> None:
714 request = client._build_request(
715 FinalRequestOptions(
716 method="post",
717 url="/foo",
718 **make_request_options(extra_headers={"X-Foo": "Foo"}),
719 ),
720 )
721 assert request.headers.get("X-Foo") == "Foo"
722
723 # `extra_headers` takes priority over `default_headers` when keys clash
724 request = client.with_options(default_headers={"X-Bar": "true"})._build_request(
725 FinalRequestOptions(
726 method="post",
727 url="/foo",
728 **make_request_options(
729 extra_headers={"X-Bar": "false"},
730 ),
731 ),
732 )
733 assert request.headers.get("X-Bar") == "false"
734
735 def test_request_extra_headers_httpx_headers(self, client: Anthropic) -> None:
736 # `httpx2.Headers` is accepted anywhere a header mapping is, in addition to a plain dict
737 request = client.with_options(default_headers=httpx2.Headers({"X-Bar": "true"}))._build_request(
738 FinalRequestOptions(
739 method="post",
740 url="/foo",
741 **make_request_options(extra_headers=httpx2.Headers({"X-Foo": "Foo", "X-Bar": "false"})),
742 ),
743 )
744 assert request.headers.get("X-Foo") == "Foo"
745 # `extra_headers` still takes priority over `default_headers` when keys clash
746 assert request.headers.get("X-Bar") == "false"
747
748 def test_request_x_stainless_helper_header_appends(self, client: Anthropic) -> None:
749 # `x-stainless-helper` accumulates across mappings instead of being clobbered,
750 # so a helper set on the client and one passed per-request both survive.
751 request = client.with_options(default_headers={"x-stainless-helper": "session_runner"})._build_request(
752 FinalRequestOptions(
753 method="post",
754 url="/foo",
755 **make_request_options(extra_headers={"x-stainless-helper": "message_batches"}),
756 ),
757 )
758 assert request.headers.get("x-stainless-helper") == "session_runner, message_batches"
759
760 def test_request_x_stainless_helper_header_dedupes(self, client: Anthropic) -> None:
761 # the same helper set in both places is recorded once
762 request = client.with_options(default_headers={"x-stainless-helper": "session_runner"})._build_request(
763 FinalRequestOptions(
764 method="post",
765 url="/foo",
766 **make_request_options(extra_headers={"x-stainless-helper": "session_runner"}),
767 ),
768 )
769 assert request.headers.get("x-stainless-helper") == "session_runner"
770
771 def test_request_x_stainless_helper_header_collapses_case_variants(self, client: Anthropic) -> None:
772 # differently-cased duplicates of the helper header fold into a single
773 # deduplicated value instead of being sent as conflicting entries
774 copied = client.with_options(
775 default_headers={"X-Stainless-Helper": "parent", "x-stainless-helper": "scoped"},
776 )
777 request = copied._build_request(
778 FinalRequestOptions(
779 method="post",
780 url="/foo",
781 **make_request_options(extra_headers={"x-stainless-helper": "message_batches"}),
782 ),
783 )
784 assert request.headers.get("x-stainless-helper") == "parent, scoped, message_batches"
785
786 def test_request_x_stainless_helper_header_dedupes_multi_value(self, client: Anthropic) -> None:
787 # comma-separated values (e.g. several tagged tools) are deduplicated per token
788 copied = client.with_options(default_headers={"x-stainless-helper": "session_runner, memory_tool"})
789 request = copied._build_request(
790 FinalRequestOptions(
791 method="post",
792 url="/foo",
793 **make_request_options(extra_headers={"x-stainless-helper": "memory_tool, message_batches"}),
794 ),
795 )
796 assert request.headers.get("x-stainless-helper") == "session_runner, memory_tool, message_batches"
797
798 def test_copy_x_stainless_helper_header_appends(self, client: Anthropic) -> None:
799 # stacking `default_headers` via copy()/with_options accumulates the
800 # helper instead of clobbering, so e.g. a scoped sub-client's tag adds to
801 # one already carried by the parent.
802 copied = client.with_options(default_headers={"x-stainless-helper": "parent"}).with_options(
803 default_headers={"x-stainless-helper": "child"}
804 )
805 request = copied._build_request(FinalRequestOptions(method="post", url="/foo"))
806 assert request.headers.get("x-stainless-helper") == "parent, child"
807
808 def test_copy_preserves_header_removal(self, client: Anthropic) -> None:
809 # an Omit removal set on the client still survives a subsequent copy()
810 copied = client.with_options(
811 default_headers=cast("dict[str, str]", {"X-Foo": Omit()}),
812 ).with_options(default_headers={"X-Bar": "true"})
813 request = copied._build_request(FinalRequestOptions(method="post", url="/foo"))
814 assert request.headers.get("X-Foo") is None
815 assert request.headers.get("X-Bar") == "true"
816
817 def test_request_extra_query(self, client: Anthropic) -> None:
818 request = client._build_request(
819 FinalRequestOptions(
820 method="post",
821 url="/foo",
822 **make_request_options(
823 extra_query={"my_query_param": "Foo"},
824 ),
825 ),
826 )
827 params = dict(request.url.params)
828 assert params == {"my_query_param": "Foo"}
829
830 # if both `query` and `extra_query` are given, they are merged
831 request = client._build_request(
832 FinalRequestOptions(
833 method="post",
834 url="/foo",
835 **make_request_options(
836 query={"bar": "1"},
837 extra_query={"foo": "2"},
838 ),
839 ),
840 )
841 params = dict(request.url.params)
842 assert params == {"bar": "1", "foo": "2"}
843
844 # `extra_query` takes priority over `query` when keys clash
845 request = client._build_request(
846 FinalRequestOptions(
847 method="post",
848 url="/foo",
849 **make_request_options(
850 query={"foo": "1"},
851 extra_query={"foo": "2"},
852 ),
853 ),
854 )
855 params = dict(request.url.params)
856 assert params == {"foo": "2"}
857
858 def test_multipart_repeating_array(self, client: Anthropic) -> None:
859 request = client._build_request(
860 FinalRequestOptions.construct(
861 method="post",
862 url="/foo",
863 headers={"Content-Type": "multipart/form-data; boundary=6b7ba517decee4a450543ea6ae821c82"},
864 json_data={"array": ["foo", "bar"]},
865 files=[("foo.txt", b"hello world")],
866 )
867 )
868
869 assert request.read().split(b"\r\n") == [
870 b"--6b7ba517decee4a450543ea6ae821c82",
871 b'Content-Disposition: form-data; name="array[]"',
872 b"",
873 b"foo",
874 b"--6b7ba517decee4a450543ea6ae821c82",
875 b'Content-Disposition: form-data; name="array[]"',
876 b"",
877 b"bar",
878 b"--6b7ba517decee4a450543ea6ae821c82",
879 b'Content-Disposition: form-data; name="foo.txt"; filename="upload"',
880 b"Content-Type: application/octet-stream",
881 b"",
882 b"hello world",
883 b"--6b7ba517decee4a450543ea6ae821c82--",
884 b"",
885 ]
886
887 @pytest.mark.respx(base_url=base_url)
888 def test_binary_content_upload(self, respx_mock: MockRouter, client: Anthropic) -> None:
889 respx_mock.post("/upload").mock(side_effect=mirror_request_content)
890
891 file_content = b"Hello, this is a test file."
892
893 response = client.post(
894 "/upload",
895 content=file_content,
896 cast_to=httpx2.Response,
897 options={"headers": {"Content-Type": "application/octet-stream"}},
898 )
899
900 assert response.status_code == 200
901 assert response.request.headers["Content-Type"] == "application/octet-stream"
902 assert response.content == file_content
903
904 def test_binary_content_upload_with_iterator(self) -> None:
905 file_content = b"Hello, this is a test file."
906 counter = Counter()
907 iterator = _make_sync_iterator([file_content], counter=counter)
908
909 def mock_handler(request: httpx2.Request) -> httpx2.Response:
910 assert counter.value == 0, "the request body should not have been read"
911 return httpx2.Response(200, content=request.read())
912
913 with Anthropic(
914 base_url=base_url,
915 api_key=api_key,
916 _strict_response_validation=True,
917 http_client=httpx2.Client(transport=MockTransport(handler=mock_handler)),
918 ) as client:
919 response = client.post(
920 "/upload",
921 content=iterator,
922 cast_to=httpx2.Response,
923 options={"headers": {"Content-Type": "application/octet-stream"}},
924 )
925
926 assert response.status_code == 200
927 assert response.request.headers["Content-Type"] == "application/octet-stream"
928 assert response.content == file_content
929 assert counter.value == 1
930
931 def test_binary_content_upload_with_body_is_rejected(self, client: Anthropic) -> None:
932 with pytest.raises(
933 TypeError, match="Passing raw bytes as `body` is not supported, pass them as `content` instead"
934 ):
935 client.post(
936 "/upload",
937 body=b"Hello, this is a test file.",
938 cast_to=httpx2.Response,
939 options={"headers": {"Content-Type": "application/octet-stream"}},
940 )
941
942 @pytest.mark.respx(base_url=base_url)
943 def test_basic_union_response(self, respx_mock: MockRouter, client: Anthropic) -> None:
944 class Model1(BaseModel):
945 name: str
946
947 class Model2(BaseModel):
948 foo: str
949
950 respx_mock.get("/foo").mock(return_value=httpx2.Response(200, json={"foo": "bar"}))
951
952 response = client.get("/foo", cast_to=cast(Any, Union[Model1, Model2]))
953 assert isinstance(response, Model2)
954 assert response.foo == "bar"
955
956 @pytest.mark.respx(base_url=base_url)
957 def test_union_response_different_types(self, respx_mock: MockRouter, client: Anthropic) -> None:
958 """Union of objects with the same field name using a different type"""
959
960 class Model1(BaseModel):
961 foo: int
962
963 class Model2(BaseModel):
964 foo: str
965
966 respx_mock.get("/foo").mock(return_value=httpx2.Response(200, json={"foo": "bar"}))
967
968 response = client.get("/foo", cast_to=cast(Any, Union[Model1, Model2]))
969 assert isinstance(response, Model2)
970 assert response.foo == "bar"
971
972 respx_mock.get("/foo").mock(return_value=httpx2.Response(200, json={"foo": 1}))
973
974 response = client.get("/foo", cast_to=cast(Any, Union[Model1, Model2]))
975 assert isinstance(response, Model1)
976 assert response.foo == 1
977
978 @pytest.mark.respx(base_url=base_url)
979 def test_non_application_json_content_type_for_json_data(self, respx_mock: MockRouter, client: Anthropic) -> None:
980 """
981 Response that sets Content-Type to something other than application/json but returns json data
982 """
983
984 class Model(BaseModel):
985 foo: int
986
987 respx_mock.get("/foo").mock(
988 return_value=httpx2.Response(
989 200,
990 content=json.dumps({"foo": 2}),
991 headers={"Content-Type": "application/text"},
992 )
993 )
994
995 response = client.get("/foo", cast_to=Model)
996 assert isinstance(response, Model)
997 assert response.foo == 2
998
999 def test_base_url_setter(self) -> None:
1000 client = Anthropic(base_url="https://example.com/from_init", api_key=api_key, _strict_response_validation=True)
1001 assert client.base_url == "https://example.com/from_init/"
1002
1003 client.base_url = "https://example.com/from_setter" # type: ignore[assignment]
1004
1005 assert client.base_url == "https://example.com/from_setter/"
1006
1007 client.close()
1008
1009 def test_base_url_env(self) -> None:
1010 with update_env(ANTHROPIC_BASE_URL="http://localhost:5000/from/env"):
1011 client = Anthropic(api_key=api_key, _strict_response_validation=True)
1012 assert client.base_url == "http://localhost:5000/from/env/"
1013
1014 @pytest.mark.parametrize(
1015 "client",
1016 [
1017 Anthropic(base_url="http://localhost:5000/custom/path/", api_key=api_key, _strict_response_validation=True),
1018 Anthropic(
1019 base_url="http://localhost:5000/custom/path/",
1020 api_key=api_key,
1021 _strict_response_validation=True,
1022 http_client=httpx2.Client(),
1023 ),
1024 ],
1025 ids=["standard", "custom http client"],
1026 )
1027 def test_base_url_trailing_slash(self, client: Anthropic) -> None:
1028 request = client._build_request(
1029 FinalRequestOptions(
1030 method="post",
1031 url="/foo",
1032 json_data={"foo": "bar"},
1033 ),
1034 )
1035 assert request.url == "http://localhost:5000/custom/path/foo"
1036 client.close()
1037
1038 @pytest.mark.parametrize(
1039 "client",
1040 [
1041 Anthropic(base_url="http://localhost:5000/custom/path/", api_key=api_key, _strict_response_validation=True),
1042 Anthropic(
1043 base_url="http://localhost:5000/custom/path/",
1044 api_key=api_key,
1045 _strict_response_validation=True,
1046 http_client=httpx2.Client(),
1047 ),
1048 ],
1049 ids=["standard", "custom http client"],
1050 )
1051 def test_base_url_no_trailing_slash(self, client: Anthropic) -> None:
1052 request = client._build_request(
1053 FinalRequestOptions(
1054 method="post",
1055 url="/foo",
1056 json_data={"foo": "bar"},
1057 ),
1058 )
1059 assert request.url == "http://localhost:5000/custom/path/foo"
1060 client.close()
1061
1062 @pytest.mark.parametrize(
1063 "client",
1064 [
1065 Anthropic(base_url="http://localhost:5000/custom/path/", api_key=api_key, _strict_response_validation=True),
1066 Anthropic(
1067 base_url="http://localhost:5000/custom/path/",
1068 api_key=api_key,
1069 _strict_response_validation=True,
1070 http_client=httpx2.Client(),
1071 ),
1072 ],
1073 ids=["standard", "custom http client"],
1074 )
1075 def test_absolute_request_url(self, client: Anthropic) -> None:
1076 request = client._build_request(
1077 FinalRequestOptions(
1078 method="post",
1079 url="https://myapi.com/foo",
1080 json_data={"foo": "bar"},
1081 ),
1082 )
1083 assert request.url == "https://myapi.com/foo"
1084 client.close()
1085
1086 def test_copied_client_does_not_close_http(self) -> None:
1087 test_client = Anthropic(base_url=base_url, api_key=api_key, _strict_response_validation=True)
1088 assert not test_client.is_closed()
1089
1090 copied = test_client.copy()
1091 assert copied is not test_client
1092
1093 del copied
1094
1095 assert not test_client.is_closed()
1096
1097 def test_client_context_manager(self) -> None:
1098 test_client = Anthropic(base_url=base_url, api_key=api_key, _strict_response_validation=True)
1099 with test_client as c2:
1100 assert c2 is test_client
1101 assert not c2.is_closed()
1102 assert not test_client.is_closed()
1103 assert test_client.is_closed()
1104
1105 @pytest.mark.respx(base_url=base_url)
1106 def test_client_response_validation_error(self, respx_mock: MockRouter, client: Anthropic) -> None:
1107 class Model(BaseModel):
1108 foo: str
1109
1110 respx_mock.get("/foo").mock(return_value=httpx2.Response(200, json={"foo": {"invalid": True}}))
1111
1112 with pytest.raises(APIResponseValidationError) as exc:
1113 client.get("/foo", cast_to=Model)
1114
1115 assert isinstance(exc.value.__cause__, ValidationError)
1116
1117 def test_client_max_retries_validation(self) -> None:
1118 with pytest.raises(TypeError, match=r"max_retries cannot be None"):
1119 Anthropic(base_url=base_url, api_key=api_key, _strict_response_validation=True, max_retries=cast(Any, None))
1120
1121 @pytest.mark.respx(base_url=base_url)
1122 def test_default_stream_cls(self, respx_mock: MockRouter, client: Anthropic) -> None:
1123 class Model(BaseModel):
1124 name: str
1125
1126 respx_mock.post("/foo").mock(return_value=httpx2.Response(200, json={"foo": "bar"}))
1127
1128 stream = client.post("/foo", cast_to=Model, stream=True, stream_cls=Stream[Model])
1129 assert isinstance(stream, Stream)
1130 stream.response.close()
1131
1132 @pytest.mark.respx(base_url=base_url)
1133 def test_received_text_for_expected_json(self, respx_mock: MockRouter) -> None:
1134 class Model(BaseModel):
1135 name: str
1136
1137 respx_mock.get("/foo").mock(return_value=httpx2.Response(200, text="my-custom-format"))
1138
1139 strict_client = Anthropic(base_url=base_url, api_key=api_key, _strict_response_validation=True)
1140
1141 with pytest.raises(APIResponseValidationError):
1142 strict_client.get("/foo", cast_to=Model)
1143
1144 non_strict_client = Anthropic(base_url=base_url, api_key=api_key, _strict_response_validation=False)
1145
1146 response = non_strict_client.get("/foo", cast_to=Model)
1147 assert isinstance(response, str) # type: ignore[unreachable]
1148
1149 strict_client.close()
1150 non_strict_client.close()
1151
1152 @pytest.mark.parametrize(
1153 "remaining_retries,retry_after,timeout",
1154 [
1155 [3, "20", 20],
1156 [3, "0", 0.5],
1157 [3, "-10", 0.5],
1158 [3, "60", 60],
1159 [3, "61", 61],
1160 [3, "Fri, 29 Sep 2023 16:26:57 GMT", 20],
1161 [3, "Fri, 29 Sep 2023 16:26:37 GMT", 0.5],
1162 [3, "Fri, 29 Sep 2023 16:26:27 GMT", 0.5],
1163 [3, "Fri, 29 Sep 2023 16:27:37 GMT", 60],
1164 [3, "Fri, 29 Sep 2023 16:27:38 GMT", 61],
1165 [3, "99999999999999999999999999999999999", 4294967],
1166 [3, "inf", 4294967],
1167 [3, "nan", 0.5],
1168 [3, "Zun, 29 Sep 2023 16:26:27 GMT", 0.5],
1169 [3, "", 0.5],
1170 [2, "", 0.5 * 2.0],
1171 [1, "", 0.5 * 4.0],
1172 [-1100, "", 8], # test large number potentially overflowing
1173 ],
1174 )
1175 def test_parse_retry_after_header(
1176 self,
1177 remaining_retries: int,
1178 retry_after: str,
1179 timeout: float,
1180 client: Anthropic,
1181 monkeypatch: pytest.MonkeyPatch,
1182 ) -> None:
1183 monkeypatch.setattr("time.time", lambda: 1696004797)
1184
1185 headers = httpx2.Headers({"retry-after": retry_after})
1186 options = FinalRequestOptions(method="get", url="/foo", max_retries=3)
1187 calculated = client._calculate_retry_timeout(remaining_retries, options, headers)
1188 assert calculated == pytest.approx(timeout, 0.5 * 0.875) # pyright: ignore[reportUnknownMemberType]
1189
1190 @pytest.mark.respx(base_url=base_url)
1191 def test_retrying_timeout_errors_doesnt_leak(
1192 self, respx_mock: MockRouter, client: Anthropic, monkeypatch: pytest.MonkeyPatch
1193 ) -> None:
1194 monkeypatch.setattr(BaseClient, "_calculate_retry_timeout", _low_retry_timeout)
1195
1196 respx_mock.post("/v1/messages").mock(side_effect=httpx2.TimeoutException("Test timeout error"))
1197
1198 with pytest.raises(APITimeoutError):
1199 client.messages.with_streaming_response.create(
1200 max_tokens=1024,
1201 messages=[
1202 {
1203 "content": "Hello, world",
1204 "role": "user",
1205 }
1206 ],
1207 model="claude-opus-5",
1208 ).__enter__()
1209
1210 assert _get_open_connections(client) == 0
1211
1212 @pytest.mark.respx(base_url=base_url)
1213 def test_retrying_status_errors_doesnt_leak(
1214 self, respx_mock: MockRouter, client: Anthropic, monkeypatch: pytest.MonkeyPatch
1215 ) -> None:
1216 monkeypatch.setattr(BaseClient, "_calculate_retry_timeout", _low_retry_timeout)
1217
1218 respx_mock.post("/v1/messages").mock(return_value=httpx2.Response(500))
1219
1220 with pytest.raises(APIStatusError):
1221 client.messages.with_streaming_response.create(
1222 max_tokens=1024,
1223 messages=[
1224 {
1225 "content": "Hello, world",
1226 "role": "user",
1227 }
1228 ],
1229 model="claude-opus-5",
1230 ).__enter__()
1231 assert _get_open_connections(client) == 0
1232
1233 @pytest.mark.parametrize("failures_before_success", [0, 2, 4])
1234 @pytest.mark.respx(base_url=base_url)
1235 @pytest.mark.parametrize("failure_mode", ["status", "exception"])
1236 def test_retries_taken(
1237 self,
1238 client: Anthropic,
1239 failures_before_success: int,
1240 failure_mode: Literal["status", "exception"],
1241 respx_mock: MockRouter,
1242 monkeypatch: pytest.MonkeyPatch,
1243 ) -> None:
1244 monkeypatch.setattr(BaseClient, "_calculate_retry_timeout", _low_retry_timeout)
1245
1246 client = client.with_options(max_retries=4)
1247
1248 nb_retries = 0
1249
1250 def retry_handler(_request: httpx2.Request) -> httpx2.Response:
1251 nonlocal nb_retries
1252 if nb_retries < failures_before_success:
1253 nb_retries += 1
1254 if failure_mode == "exception":
1255 raise RuntimeError("oops")
1256 return httpx2.Response(500)
1257 return httpx2.Response(200)
1258
1259 respx_mock.post("/v1/messages").mock(side_effect=retry_handler)
1260
1261 response = client.messages.with_raw_response.create(
1262 max_tokens=1024,
1263 messages=[
1264 {
1265 "content": "Hello, world",
1266 "role": "user",
1267 }
1268 ],
1269 model="claude-opus-5",
1270 )
1271
1272 assert response.retries_taken == failures_before_success
1273 assert int(response.http_request.headers.get("x-stainless-retry-count")) == failures_before_success
1274
1275 @pytest.mark.parametrize("failures_before_success", [0, 2, 4])
1276 @pytest.mark.respx(base_url=base_url)
1277 def test_omit_retry_count_header(
1278 self,
1279 client: Anthropic,
1280 failures_before_success: int,
1281 respx_mock: MockRouter,
1282 monkeypatch: pytest.MonkeyPatch,
1283 ) -> None:
1284 monkeypatch.setattr(BaseClient, "_calculate_retry_timeout", _low_retry_timeout)
1285
1286 client = client.with_options(max_retries=4)
1287
1288 nb_retries = 0
1289
1290 def retry_handler(_request: httpx2.Request) -> httpx2.Response:
1291 nonlocal nb_retries
1292 if nb_retries < failures_before_success:
1293 nb_retries += 1
1294 return httpx2.Response(500)
1295 return httpx2.Response(200)
1296
1297 respx_mock.post("/v1/messages").mock(side_effect=retry_handler)
1298
1299 response = client.messages.with_raw_response.create(
1300 max_tokens=1024,
1301 messages=[
1302 {
1303 "content": "Hello, world",
1304 "role": "user",
1305 }
1306 ],
1307 model="claude-opus-5",
1308 extra_headers={"x-stainless-retry-count": Omit()},
1309 )
1310
1311 assert len(response.http_request.headers.get_list("x-stainless-retry-count")) == 0
1312
1313 @pytest.mark.parametrize("failures_before_success", [0, 2, 4])
1314 @pytest.mark.respx(base_url=base_url)
1315 def test_overwrite_retry_count_header(
1316 self,
1317 client: Anthropic,
1318 failures_before_success: int,
1319 respx_mock: MockRouter,
1320 monkeypatch: pytest.MonkeyPatch,
1321 ) -> None:
1322 monkeypatch.setattr(BaseClient, "_calculate_retry_timeout", _low_retry_timeout)
1323
1324 client = client.with_options(max_retries=4)
1325
1326 nb_retries = 0
1327
1328 def retry_handler(_request: httpx2.Request) -> httpx2.Response:
1329 nonlocal nb_retries
1330 if nb_retries < failures_before_success:
1331 nb_retries += 1
1332 return httpx2.Response(500)
1333 return httpx2.Response(200)
1334
1335 respx_mock.post("/v1/messages").mock(side_effect=retry_handler)
1336
1337 response = client.messages.with_raw_response.create(
1338 max_tokens=1024,
1339 messages=[
1340 {
1341 "content": "Hello, world",
1342 "role": "user",
1343 }
1344 ],
1345 model="claude-opus-5",
1346 extra_headers={"x-stainless-retry-count": "42"},
1347 )
1348
1349 assert response.http_request.headers.get("x-stainless-retry-count") == "42"
1350
1351 def test_proxy_environment_variables(self, monkeypatch: pytest.MonkeyPatch) -> None:
1352 # Test that the proxy environment variables are set correctly
1353 monkeypatch.setenv("HTTPS_PROXY", "https://example.org")
1354 # Delete in case our environment has any proxy env vars set
1355 monkeypatch.delenv("HTTP_PROXY", raising=False)
1356 monkeypatch.delenv("ALL_PROXY", raising=False)
1357 monkeypatch.delenv("NO_PROXY", raising=False)
1358 monkeypatch.delenv("http_proxy", raising=False)
1359 monkeypatch.delenv("https_proxy", raising=False)
1360 monkeypatch.delenv("all_proxy", raising=False)
1361 monkeypatch.delenv("no_proxy", raising=False)
1362
1363 client = DefaultHttpxClient()
1364
1365 mounts = tuple(client._mounts.items())
1366 assert len(mounts) == 1
1367 assert mounts[0][0].pattern == "https://"
1368
1369 def test_default_client_creation(self) -> None:
1370 # Ensure that the client can be initialized without any exceptions
1371 DefaultHttpxClient(
1372 verify=True,
1373 cert=None,
1374 trust_env=True,
1375 http1=True,
1376 http2=False,
1377 limits=httpx2.Limits(max_connections=100, max_keepalive_connections=20),
1378 )
1379
1380 @pytest.mark.respx(base_url=base_url)
1381 def test_follow_redirects(self, respx_mock: MockRouter, client: Anthropic) -> None:
1382 # Test that the default follow_redirects=True allows following redirects
1383 respx_mock.post("/redirect").mock(
1384 return_value=httpx2.Response(302, headers={"Location": f"{base_url}/redirected"})
1385 )
1386 respx_mock.get("/redirected").mock(return_value=httpx2.Response(200, json={"status": "ok"}))
1387
1388 response = client.post("/redirect", body={"key": "value"}, cast_to=httpx2.Response)
1389 assert response.status_code == 200
1390 assert response.json() == {"status": "ok"}
1391
1392 @pytest.mark.respx(base_url=base_url)
1393 def test_follow_redirects_disabled(self, respx_mock: MockRouter, client: Anthropic) -> None:
1394 # Test that follow_redirects=False prevents following redirects
1395 respx_mock.post("/redirect").mock(
1396 return_value=httpx2.Response(302, headers={"Location": f"{base_url}/redirected"})
1397 )
1398
1399 with pytest.raises(APIStatusError) as exc_info:
1400 client.post(
1401 "/redirect", body={"key": "value"}, options={"follow_redirects": False}, cast_to=httpx2.Response
1402 )
1403
1404 assert exc_info.value.response.status_code == 302
1405 assert exc_info.value.response.headers["Location"] == f"{base_url}/redirected"
1406
1407 @pytest.mark.respx(base_url=base_url)
1408 def test_status_error_type_field(self, respx_mock: MockRouter, client: Anthropic) -> None:
1409 respx_mock.post("/v1/messages").mock(
1410 return_value=httpx2.Response(
1411 400,
1412 json={"type": "error", "error": {"type": "invalid_request_error", "message": "Bad request"}},
1413 )
1414 )
1415 with pytest.raises(APIStatusError) as exc_info:
1416 client.messages.create(
1417 max_tokens=1024,
1418 messages=[{"role": "user", "content": "Hello"}],
1419 model="claude-opus-4-6",
1420 )
1421 assert exc_info.value.type == "invalid_request_error"
1422 assert exc_info.value.status_code == 400
1423
1424
1425 class TestAsyncAnthropic:
1426 @pytest.mark.respx(base_url=base_url)
1427 async def test_raw_response(self, respx_mock: MockRouter, async_client: AsyncAnthropic) -> None:
1428 respx_mock.post("/foo").mock(return_value=httpx2.Response(200, json={"foo": "bar"}))
1429
1430 response = await async_client.post("/foo", cast_to=httpx2.Response)
1431 assert response.status_code == 200
1432 assert isinstance(response, httpx2.Response)
1433 assert response.json() == {"foo": "bar"}
1434
1435 @pytest.mark.respx(base_url=base_url)
1436 async def test_raw_response_for_binary(self, respx_mock: MockRouter, async_client: AsyncAnthropic) -> None:
1437 respx_mock.post("/foo").mock(
1438 return_value=httpx2.Response(200, headers={"Content-Type": "application/binary"}, content='{"foo": "bar"}')
1439 )
1440
1441 response = await async_client.post("/foo", cast_to=httpx2.Response)
1442 assert response.status_code == 200
1443 assert isinstance(response, httpx2.Response)
1444 assert response.json() == {"foo": "bar"}
1445
1446 def test_copy(self, async_client: AsyncAnthropic) -> None:
1447 copied = async_client.copy()
1448 assert id(copied) != id(async_client)
1449
1450 copied = async_client.copy(api_key="another my-anthropic-api-key")
1451 assert copied.api_key == "another my-anthropic-api-key"
1452 assert async_client.api_key == "my-anthropic-api-key"
1453
1454 def test_copy_default_options(self, async_client: AsyncAnthropic) -> None:
1455 # options that have a default are overridden correctly
1456 copied = async_client.copy(max_retries=7)
1457 assert copied.max_retries == 7
1458 assert async_client.max_retries == 2
1459
1460 copied2 = copied.copy(max_retries=6)
1461 assert copied2.max_retries == 6
1462 assert copied.max_retries == 7
1463
1464 # timeout
1465 assert isinstance(async_client.timeout, httpx2.Timeout)
1466 copied = async_client.copy(timeout=None)
1467 assert copied.timeout is None
1468 assert isinstance(async_client.timeout, httpx2.Timeout)
1469
1470 async def test_copy_default_headers(self) -> None:
1471 client = AsyncAnthropic(
1472 base_url=base_url, api_key=api_key, _strict_response_validation=True, default_headers={"X-Foo": "bar"}
1473 )
1474 assert client.default_headers["X-Foo"] == "bar"
1475
1476 # does not override the already given value when not specified
1477 copied = client.copy()
1478 assert copied.default_headers["X-Foo"] == "bar"
1479
1480 # merges already given headers
1481 copied = client.copy(default_headers={"X-Bar": "stainless"})
1482 assert copied.default_headers["X-Foo"] == "bar"
1483 assert copied.default_headers["X-Bar"] == "stainless"
1484
1485 # uses new values for any already given headers
1486 copied = client.copy(default_headers={"X-Foo": "stainless"})
1487 assert copied.default_headers["X-Foo"] == "stainless"
1488
1489 # set_default_headers
1490
1491 # completely overrides already set values
1492 copied = client.copy(set_default_headers={})
1493 assert copied.default_headers.get("X-Foo") is None
1494
1495 copied = client.copy(set_default_headers={"X-Bar": "Robert"})
1496 assert copied.default_headers["X-Bar"] == "Robert"
1497
1498 with pytest.raises(
1499 ValueError,
1500 match="`default_headers` and `set_default_headers` arguments are mutually exclusive",
1501 ):
1502 client.copy(set_default_headers={}, default_headers={"X-Foo": "Bar"})
1503 await client.close()
1504
1505 async def test_copy_default_query(self) -> None:
1506 client = AsyncAnthropic(
1507 base_url=base_url, api_key=api_key, _strict_response_validation=True, default_query={"foo": "bar"}
1508 )
1509 assert _get_params(client)["foo"] == "bar"
1510
1511 # does not override the already given value when not specified
1512 copied = client.copy()
1513 assert _get_params(copied)["foo"] == "bar"
1514
1515 # merges already given params
1516 copied = client.copy(default_query={"bar": "stainless"})
1517 params = _get_params(copied)
1518 assert params["foo"] == "bar"
1519 assert params["bar"] == "stainless"
1520
1521 # uses new values for any already given headers
1522 copied = client.copy(default_query={"foo": "stainless"})
1523 assert _get_params(copied)["foo"] == "stainless"
1524
1525 # set_default_query
1526
1527 # completely overrides already set values
1528 copied = client.copy(set_default_query={})
1529 assert _get_params(copied) == {}
1530
1531 copied = client.copy(set_default_query={"bar": "Robert"})
1532 assert _get_params(copied)["bar"] == "Robert"
1533
1534 with pytest.raises(
1535 ValueError,
1536 # TODO: update
1537 match="`default_query` and `set_default_query` arguments are mutually exclusive",
1538 ):
1539 client.copy(set_default_query={}, default_query={"foo": "Bar"})
1540
1541 await client.close()
1542
1543 def test_copy_signature(self, async_client: AsyncAnthropic) -> None:
1544 # ensure the same parameters that can be passed to the client are defined in the `.copy()` method
1545 init_signature = inspect.signature(
1546 # mypy doesn't like that we access the `__init__` property.
1547 async_client.__init__, # type: ignore[misc]
1548 )
1549 copy_signature = inspect.signature(async_client.copy)
1550 exclude_params = {"transport", "proxies", "_strict_response_validation", "_token_cache"}
1551
1552 for name in init_signature.parameters.keys():
1553 if name in exclude_params:
1554 continue
1555
1556 copy_param = copy_signature.parameters.get(name)
1557 assert copy_param is not None, f"copy() signature is missing the {name} param"
1558
1559 @pytest.mark.skipif(sys.version_info >= (3, 10), reason="fails because of a memory leak that started from 3.12")
1560 def test_copy_build_request(self, async_client: AsyncAnthropic) -> None:
1561 options = FinalRequestOptions(method="get", url="/foo")
1562
1563 def build_request(options: FinalRequestOptions) -> None:
1564 client_copy = async_client.copy()
1565 client_copy._build_request(options)
1566
1567 # ensure that the machinery is warmed up before tracing starts.
1568 build_request(options)
1569 gc.collect()
1570
1571 tracemalloc.start(1000)
1572
1573 snapshot_before = tracemalloc.take_snapshot()
1574
1575 ITERATIONS = 10
1576 for _ in range(ITERATIONS):
1577 build_request(options)
1578
1579 gc.collect()
1580 snapshot_after = tracemalloc.take_snapshot()
1581
1582 tracemalloc.stop()
1583
1584 def add_leak(leaks: list[tracemalloc.StatisticDiff], diff: tracemalloc.StatisticDiff) -> None:
1585 if diff.count == 0:
1586 # Avoid false positives by considering only leaks (i.e. allocations that persist).
1587 return
1588
1589 if diff.count % ITERATIONS != 0:
1590 # Avoid false positives by considering only leaks that appear per iteration.
1591 return
1592
1593 for frame in diff.traceback:
1594 if any(
1595 frame.filename.endswith(fragment)
1596 for fragment in [
1597 # to_raw_response_wrapper leaks through the @functools.wraps() decorator.
1598 #
1599 # removing the decorator fixes the leak for reasons we don't understand.
1600 "anthropic/_response.py",
1601 # pydantic.BaseModel.model_dump || pydantic.BaseModel.dict leak memory for some reason.
1602 "anthropic/_compat.py",
1603 # Standard library leaks we don't care about.
1604 "/logging/__init__.py",
1605 ]
1606 ):
1607 return
1608
1609 leaks.append(diff)
1610
1611 leaks: list[tracemalloc.StatisticDiff] = []
1612 for diff in snapshot_after.compare_to(snapshot_before, "traceback"):
1613 add_leak(leaks, diff)
1614 if leaks:
1615 for leak in leaks:
1616 print("MEMORY LEAK:", leak)
1617 for frame in leak.traceback:
1618 print(frame)
1619 raise AssertionError()
1620
1621 async def test_request_timeout(self, async_client: AsyncAnthropic) -> None:
1622 request = async_client._build_request(FinalRequestOptions(method="get", url="/foo"))
1623 timeout = httpx2.Timeout(**request.extensions["timeout"]) # type: ignore
1624 assert timeout == DEFAULT_TIMEOUT
1625
1626 request = async_client._build_request(
1627 FinalRequestOptions(method="get", url="/foo", timeout=httpx2.Timeout(100.0))
1628 )
1629 timeout = httpx2.Timeout(**request.extensions["timeout"]) # type: ignore
1630 assert timeout == httpx2.Timeout(100.0)
1631
1632 async def test_client_timeout_option(self) -> None:
1633 client = AsyncAnthropic(
1634 base_url=base_url, api_key=api_key, _strict_response_validation=True, timeout=httpx2.Timeout(0)
1635 )
1636
1637 request = client._build_request(FinalRequestOptions(method="get", url="/foo"))
1638 timeout = httpx2.Timeout(**request.extensions["timeout"]) # type: ignore
1639 assert timeout == httpx2.Timeout(0)
1640
1641 await client.close()
1642
1643 async def test_http_client_timeout_option(self) -> None:
1644 # custom timeout given to the httpx client should be used
1645 async with httpx2.AsyncClient(timeout=None) as http_client:
1646 client = AsyncAnthropic(
1647 base_url=base_url, api_key=api_key, _strict_response_validation=True, http_client=http_client
1648 )
1649
1650 request = client._build_request(FinalRequestOptions(method="get", url="/foo"))
1651 timeout = httpx2.Timeout(**request.extensions["timeout"]) # type: ignore
1652 assert timeout == httpx2.Timeout(None)
1653
1654 await client.close()
1655
1656 # no timeout given to the httpx client should not use the httpx default
1657 async with httpx2.AsyncClient() as http_client:
1658 client = AsyncAnthropic(
1659 base_url=base_url, api_key=api_key, _strict_response_validation=True, http_client=http_client
1660 )
1661
1662 request = client._build_request(FinalRequestOptions(method="get", url="/foo"))
1663 timeout = httpx2.Timeout(**request.extensions["timeout"]) # type: ignore
1664 assert timeout == DEFAULT_TIMEOUT
1665
1666 await client.close()
1667
1668 # explicitly passing the default timeout currently results in it being ignored
1669 async with httpx2.AsyncClient(timeout=HTTPX_DEFAULT_TIMEOUT) as http_client:
1670 client = AsyncAnthropic(
1671 base_url=base_url, api_key=api_key, _strict_response_validation=True, http_client=http_client
1672 )
1673
1674 request = client._build_request(FinalRequestOptions(method="get", url="/foo"))
1675 timeout = httpx2.Timeout(**request.extensions["timeout"]) # type: ignore
1676 assert timeout == DEFAULT_TIMEOUT # our default
1677
1678 await client.close()
1679
1680 def test_invalid_http_client(self) -> None:
1681 with pytest.raises(TypeError, match="Invalid `http_client` arg"):
1682 with httpx2.Client() as http_client:
1683 AsyncAnthropic(
1684 base_url=base_url,
1685 api_key=api_key,
1686 _strict_response_validation=True,
1687 http_client=cast(Any, http_client),
1688 )
1689
1690 async def test_httpx_objects_rejected(self, async_client: AsyncAnthropic) -> None:
1691 # `import httpx` resolves to `httpx2` in this test suite, so fake the `httpx` classes
1692 class Timeout:
1693 __module__ = "httpx"
1694
1695 class HTTPTransport:
1696 __module__ = "httpx._transports.default"
1697
1698 class Client:
1699 __module__ = "httpx"
1700
1701 class MyClient(Client):
1702 pass
1703
1704 timeout: Any = Timeout()
1705 transport: Any = HTTPTransport()
1706 http_client: Any = MyClient()
1707
1708 with pytest.raises(TypeError, match="Use `httpx2.Client` instead"):
1709 AsyncAnthropic(
1710 base_url=base_url, api_key=api_key, _strict_response_validation=True, http_client=http_client
1711 )
1712
1713 with pytest.raises(TypeError, match="Use `httpx2.Timeout` instead"):
1714 AsyncAnthropic(base_url=base_url, api_key=api_key, _strict_response_validation=True, timeout=timeout)
1715
1716 with pytest.raises(TypeError, match="Use `httpx2.Timeout` instead"):
1717 await async_client.post("/foo", cast_to=httpx2.Response, options={"timeout": timeout})
1718
1719 with pytest.raises(TypeError, match="Use `httpx2.HTTPTransport` instead"):
1720 DefaultAsyncHttpxClient(transport=transport)
1721
1722 async def test_default_headers_option(self) -> None:
1723 test_client = AsyncAnthropic(
1724 base_url=base_url, api_key=api_key, _strict_response_validation=True, default_headers={"X-Foo": "bar"}
1725 )
1726 request = test_client._build_request(FinalRequestOptions(method="get", url="/foo"))
1727 assert request.headers.get("x-foo") == "bar"
1728 assert request.headers.get("x-stainless-lang") == "python"
1729
1730 test_client2 = AsyncAnthropic(
1731 base_url=base_url,
1732 api_key=api_key,
1733 _strict_response_validation=True,
1734 default_headers={
1735 "X-Foo": "stainless",
1736 "X-Stainless-Lang": "my-overriding-header",
1737 },
1738 )
1739 request = test_client2._build_request(FinalRequestOptions(method="get", url="/foo"))
1740 assert request.headers.get("x-foo") == "stainless"
1741 assert request.headers.get("x-stainless-lang") == "my-overriding-header"
1742
1743 await test_client.close()
1744 await test_client2.close()
1745
1746 def test_validate_headers(self) -> None:
1747 client = AsyncAnthropic(base_url=base_url, api_key=api_key, _strict_response_validation=True)
1748 request = client._build_request(FinalRequestOptions(method="get", url="/foo"))
1749 assert request.headers.get("X-Api-Key") == api_key
1750
1751 def no_default_credentials(**_kwargs: object) -> None:
1752 return None
1753
1754 with pytest.MonkeyPatch.context() as monkeypatch:
1755 monkeypatch.setattr("anthropic._client.default_credentials", no_default_credentials)
1756 with update_env(**{"ANTHROPIC_API_KEY": Omit()}):
1757 client2 = AsyncAnthropic(base_url=base_url, api_key=None, _strict_response_validation=True)
1758
1759 with pytest.raises(
1760 TypeError,
1761 match="Could not resolve authentication method. Expected one of api_key, auth_token, or credentials to be set. Or for one of the `X-Api-Key` or `Authorization` headers to be explicitly omitted",
1762 ):
1763 client2._build_request(FinalRequestOptions(method="get", url="/foo"))
1764
1765 request2 = client2._build_request(FinalRequestOptions(method="get", url="/foo", headers={"X-Api-Key": Omit()}))
1766 assert request2.headers.get("X-Api-Key") is None
1767 request3 = client2._build_request(FinalRequestOptions(method="get", url="/foo", headers={"x-api-key": Omit()}))
1768 assert request3.headers.get("X-Api-Key") is None
1769 request4 = client2._build_request(
1770 FinalRequestOptions(method="get", url="/foo", headers={"x-api-key": "from-header"})
1771 )
1772 assert request4.headers.get_list("X-Api-Key") == ["from-header"]
1773
1774 async def test_default_headers_case_insensitive(self) -> None:
1775 # replaces the SDK's own `User-Agent` rather than being sent next to it
1776 test_client = AsyncAnthropic(
1777 base_url=base_url,
1778 api_key=api_key,
1779 _strict_response_validation=True,
1780 default_headers={"user-agent": "my-app/1.0"},
1781 )
1782 request = test_client._build_request(FinalRequestOptions(method="get", url="/foo"))
1783 assert request.headers.get_list("user-agent") == ["my-app/1.0"]
1784
1785 await test_client.close()
1786
1787 def test_extra_headers_case_insensitive(self, async_client: AsyncAnthropic) -> None:
1788 request = async_client.with_options(default_headers={"X-Foo": "client"})._build_request(
1789 FinalRequestOptions(method="post", url="/foo", **make_request_options(extra_headers={"x-foo": "request"}))
1790 )
1791 assert request.headers.get_list("x-foo") == ["request"]
1792
1793 def test_omit_headers_case_insensitive(self, async_client: AsyncAnthropic) -> None:
1794 request = async_client.with_options(default_headers={"X-Foo": "bar"})._build_request(
1795 FinalRequestOptions(method="post", url="/foo", **make_request_options(extra_headers={"x-foo": Omit()}))
1796 )
1797 assert "x-foo" not in request.headers
1798
1799 request = async_client.with_options(default_headers=cast("dict[str, str]", {"X-FOO": Omit()}))._build_request(
1800 FinalRequestOptions(method="post", url="/foo")
1801 )
1802 assert "x-foo" not in request.headers
1803
1804 request = async_client._build_request(
1805 FinalRequestOptions(
1806 method="post", url="/foo", **make_request_options(extra_headers={"X-STAINLESS-LANG": Omit()})
1807 )
1808 )
1809 assert "x-stainless-lang" not in request.headers
1810
1811 # request-time SDK headers sit in the lowest layer too, so a client-level `Omit()` also removes them
1812 request = async_client.with_options(
1813 default_headers=cast("dict[str, str]", {"X-Stainless-Retry-Count": Omit()})
1814 )._build_request(FinalRequestOptions(method="post", url="/foo"))
1815 assert "x-stainless-retry-count" not in request.headers
1816
1817 def test_with_options_headers_case_insensitive(self, async_client: AsyncAnthropic) -> None:
1818 copied = async_client.with_options(default_headers={"X-Foo": "one"}).with_options(
1819 default_headers={"x-foo": "two"}
1820 )
1821 request = copied._build_request(FinalRequestOptions(method="get", url="/foo"))
1822 assert request.headers.get_list("x-foo") == ["two"]
1823 assert copied.default_headers["x-foo"] == "two"
1824 assert "X-Foo" not in copied.default_headers
1825
1826 def test_multipart_content_type_case_insensitive(self, async_client: AsyncAnthropic) -> None:
1827 request = async_client._build_request(
1828 FinalRequestOptions.construct(
1829 method="post",
1830 url="/foo",
1831 headers={"content-type": "Multipart/Form-Data"},
1832 json_data={"foo": "bar"},
1833 files=[("file", ("foo.txt", b"hello world"))],
1834 )
1835 )
1836 content_types = request.headers.get_list("content-type")
1837 assert len(content_types) == 1, content_types
1838 assert content_types[0].startswith("multipart/form-data; boundary=")
1839 assert b'name="foo"' in request.read()
1840
1841 async def test_default_query_option(self) -> None:
1842 client = AsyncAnthropic(
1843 base_url=base_url, api_key=api_key, _strict_response_validation=True, default_query={"query_param": "bar"}
1844 )
1845 request = client._build_request(FinalRequestOptions(method="get", url="/foo"))
1846 url = httpx2.URL(request.url)
1847 assert dict(url.params) == {"query_param": "bar"}
1848
1849 request = client._build_request(
1850 FinalRequestOptions(
1851 method="get",
1852 url="/foo",
1853 params={"foo": "baz", "query_param": "overridden"},
1854 )
1855 )
1856 url = httpx2.URL(request.url)
1857 assert dict(url.params) == {"foo": "baz", "query_param": "overridden"}
1858
1859 await client.close()
1860
1861 async def test_hardcoded_query_params_in_url(self, async_client: AsyncAnthropic) -> None:
1862 request = async_client._build_request(FinalRequestOptions(method="get", url="/foo?beta=true"))
1863 url = httpx2.URL(request.url)
1864 assert dict(url.params) == {"beta": "true"}
1865
1866 request = async_client._build_request(
1867 FinalRequestOptions(
1868 method="get",
1869 url="/foo?beta=true",
1870 params={"limit": "10", "page": "abc"},
1871 )
1872 )
1873 url = httpx2.URL(request.url)
1874 assert dict(url.params) == {"beta": "true", "limit": "10", "page": "abc"}
1875
1876 request = async_client._build_request(
1877 FinalRequestOptions(
1878 method="get",
1879 url="/files/a%2Fb?beta=true",
1880 params={"limit": "10"},
1881 )
1882 )
1883 assert request.url.raw_path == b"/files/a%2Fb?beta=true&limit=10"
1884
1885 def test_request_extra_json(self, client: Anthropic) -> None:
1886 request = client._build_request(
1887 FinalRequestOptions(
1888 method="post",
1889 url="/foo",
1890 json_data={"foo": "bar"},
1891 extra_json={"baz": False},
1892 ),
1893 )
1894 data = json.loads(request.content.decode("utf-8"))
1895 assert data == {"foo": "bar", "baz": False}
1896
1897 request = client._build_request(
1898 FinalRequestOptions(
1899 method="post",
1900 url="/foo",
1901 extra_json={"baz": False},
1902 ),
1903 )
1904 data = json.loads(request.content.decode("utf-8"))
1905 assert data == {"baz": False}
1906
1907 # `extra_json` takes priority over `json_data` when keys clash
1908 request = client._build_request(
1909 FinalRequestOptions(
1910 method="post",
1911 url="/foo",
1912 json_data={"foo": "bar", "baz": True},
1913 extra_json={"baz": None},
1914 ),
1915 )
1916 data = json.loads(request.content.decode("utf-8"))
1917 assert data == {"foo": "bar", "baz": None}
1918
1919 @pytest.mark.respx(base_url=base_url)
1920 async def test_request_extra_json_merged_before_prepare_options(self, respx_mock: MockRouter) -> None:
1921 # client hooks (e.g. a `_prepare_options` that derives the URL from the body) see the body with `extra_body` applied
1922 seen: list[FinalRequestOptions] = []
1923
1924 class Client(AsyncAnthropic):
1925 @override
1926 async def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions:
1927 seen.append(copy.deepcopy(options))
1928 return await super()._prepare_options(options)
1929
1930 respx_mock.post("/foo").mock(return_value=httpx2.Response(200, json={}))
1931 client = Client(base_url=base_url, api_key=api_key, _strict_response_validation=True)
1932
1933 response = await client.post(
1934 "/foo",
1935 cast_to=httpx2.Response,
1936 body={"foo": "bar", "baz": True},
1937 options=make_request_options(extra_body={"baz": None}),
1938 )
1939
1940 assert len(seen) == 1
1941 assert seen[0].json_data == {"foo": "bar", "baz": None}
1942 assert seen[0].extra_json is None
1943 assert json.loads(response.request.content) == {"foo": "bar", "baz": None}
1944
1945 @pytest.mark.respx(base_url=base_url)
1946 async def test_request_data_prepared_before_prepare_options(
1947 self, respx_mock: MockRouter, async_client: AsyncAnthropic, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
1948 ) -> None:
1949 # client hooks see the data as it is sent: files read, omitted keys dropped, iterables materialised, dates formatted
1950 seen: list[FinalRequestOptions] = []
1951 prepare_options = async_client._prepare_options
1952
1953 async def record(options: FinalRequestOptions) -> FinalRequestOptions:
1954 seen.append(copy.deepcopy(options))
1955 return await prepare_options(options)
1956
1957 monkeypatch.setattr(async_client, "_prepare_options", record)
1958 respx_mock.post("/foo").mock(return_value=httpx2.Response(200, json={}))
1959 monkeypatch.setattr("anthropic._utils._prepare.FILE_INPUT_MARKERS", (("type", "base64", "data"),))
1960 path = tmp_path / "file.bin"
1961 path.write_bytes(b"Hello")
1962
1963 await async_client.post(
1964 "/foo",
1965 cast_to=httpx2.Response,
1966 body={
1967 "source": {"type": "base64", "data": path},
1968 "dropped": Omit(),
1969 "at": datetime(2024, 1, 2, 3, 4, 5, tzinfo=timezone.utc),
1970 },
1971 options=make_request_options(
1972 query={"since": datetime(2024, 1, 2, 3, 4, 5)},
1973 extra_body={"baz": (1, 2), "on": date(2024, 1, 2)},
1974 extra_query={"filter": {"q": Omit(), "r": 1}},
1975 ),
1976 )
1977
1978 assert len(seen) == 1
1979 assert seen[0].json_data == {
1980 "source": {"type": "base64", "data": "SGVsbG8="},
1981 "at": "2024-01-02T03:04:05+00:00",
1982 "baz": [1, 2],
1983 "on": "2024-01-02",
1984 }
1985 assert seen[0].params == {"since": "2024-01-02T03:04:05", "filter": {"r": 1}}
1986
1987 @pytest.mark.respx(base_url=base_url)
1988 async def test_request_does_not_modify_the_options_it_is_given(
1989 self, respx_mock: MockRouter, async_client: AsyncAnthropic
1990 ) -> None:
1991 respx_mock.post("/foo").mock(return_value=httpx2.Response(200, json={}))
1992 options = FinalRequestOptions.construct(
1993 method="post",
1994 url="/foo",
1995 json_data={"foo": "bar", "at": datetime(2024, 1, 2, 3, 4, 5, tzinfo=timezone.utc)},
1996 extra_json={"baz": (1, 2)},
1997 params={"since": date(2024, 1, 2)},
1998 )
1999 json_data, extra_json, params = options.json_data, options.extra_json, options.params
2000
2001 response = await async_client.request(httpx2.Response, options)
2002
2003 # what is sent is merged and prepared
2004 assert json.loads(response.request.content) == {"foo": "bar", "at": "2024-01-02T03:04:05+00:00", "baz": [1, 2]}
2005 assert response.request.url.params["since"] == "2024-01-02"
2006 # on a copy: the caller's options still hold the objects they were given, unchanged
2007 assert options.json_data is json_data
2008 assert options.extra_json is extra_json
2009 assert options.params is params
2010 assert json_data == {"foo": "bar", "at": datetime(2024, 1, 2, 3, 4, 5, tzinfo=timezone.utc)}
2011 assert extra_json == {"baz": (1, 2)}
2012 assert params == {"since": date(2024, 1, 2)}
2013
2014 def test_request_extra_headers(self, client: Anthropic) -> None:
2015 request = client._build_request(
2016 FinalRequestOptions(
2017 method="post",
2018 url="/foo",
2019 **make_request_options(extra_headers={"X-Foo": "Foo"}),
2020 ),
2021 )
2022 assert request.headers.get("X-Foo") == "Foo"
2023
2024 # `extra_headers` takes priority over `default_headers` when keys clash
2025 request = client.with_options(default_headers={"X-Bar": "true"})._build_request(
2026 FinalRequestOptions(
2027 method="post",
2028 url="/foo",
2029 **make_request_options(
2030 extra_headers={"X-Bar": "false"},
2031 ),
2032 ),
2033 )
2034 assert request.headers.get("X-Bar") == "false"
2035
2036 def test_request_extra_headers_httpx_headers(self, async_client: AsyncAnthropic) -> None:
2037 # `httpx2.Headers` is accepted anywhere a header mapping is, in addition to a plain dict
2038 request = async_client.with_options(default_headers=httpx2.Headers({"X-Bar": "true"}))._build_request(
2039 FinalRequestOptions(
2040 method="post",
2041 url="/foo",
2042 **make_request_options(extra_headers=httpx2.Headers({"X-Foo": "Foo", "X-Bar": "false"})),
2043 ),
2044 )
2045 assert request.headers.get("X-Foo") == "Foo"
2046 # `extra_headers` still takes priority over `default_headers` when keys clash
2047 assert request.headers.get("X-Bar") == "false"
2048
2049 def test_request_x_stainless_helper_header_appends(self, async_client: AsyncAnthropic) -> None:
2050 # `x-stainless-helper` accumulates across mappings instead of being clobbered,
2051 # so a helper set on the client and one passed per-request both survive.
2052 request = async_client.with_options(default_headers={"x-stainless-helper": "session_runner"})._build_request(
2053 FinalRequestOptions(
2054 method="post",
2055 url="/foo",
2056 **make_request_options(extra_headers={"x-stainless-helper": "message_batches"}),
2057 ),
2058 )
2059 assert request.headers.get("x-stainless-helper") == "session_runner, message_batches"
2060
2061 def test_request_x_stainless_helper_header_dedupes(self, async_client: AsyncAnthropic) -> None:
2062 # the same helper set in both places is recorded once
2063 request = async_client.with_options(default_headers={"x-stainless-helper": "session_runner"})._build_request(
2064 FinalRequestOptions(
2065 method="post",
2066 url="/foo",
2067 **make_request_options(extra_headers={"x-stainless-helper": "session_runner"}),
2068 ),
2069 )
2070 assert request.headers.get("x-stainless-helper") == "session_runner"
2071
2072 def test_request_x_stainless_helper_header_collapses_case_variants(self, async_client: AsyncAnthropic) -> None:
2073 # differently-cased duplicates of the helper header fold into a single
2074 # deduplicated value instead of being sent as conflicting entries
2075 copied = async_client.with_options(
2076 default_headers={"X-Stainless-Helper": "parent", "x-stainless-helper": "scoped"},
2077 )
2078 request = copied._build_request(
2079 FinalRequestOptions(
2080 method="post",
2081 url="/foo",
2082 **make_request_options(extra_headers={"x-stainless-helper": "message_batches"}),
2083 ),
2084 )
2085 assert request.headers.get("x-stainless-helper") == "parent, scoped, message_batches"
2086
2087 def test_request_x_stainless_helper_header_dedupes_multi_value(self, async_client: AsyncAnthropic) -> None:
2088 # comma-separated values (e.g. several tagged tools) are deduplicated per token
2089 copied = async_client.with_options(default_headers={"x-stainless-helper": "session_runner, memory_tool"})
2090 request = copied._build_request(
2091 FinalRequestOptions(
2092 method="post",
2093 url="/foo",
2094 **make_request_options(extra_headers={"x-stainless-helper": "memory_tool, message_batches"}),
2095 ),
2096 )
2097 assert request.headers.get("x-stainless-helper") == "session_runner, memory_tool, message_batches"
2098
2099 def test_copy_x_stainless_helper_header_appends(self, async_client: AsyncAnthropic) -> None:
2100 # stacking `default_headers` via copy()/with_options accumulates the
2101 # helper instead of clobbering, so e.g. a scoped sub-client's tag adds to
2102 # one already carried by the parent.
2103 copied = async_client.with_options(default_headers={"x-stainless-helper": "parent"}).with_options(
2104 default_headers={"x-stainless-helper": "child"}
2105 )
2106 request = copied._build_request(FinalRequestOptions(method="post", url="/foo"))
2107 assert request.headers.get("x-stainless-helper") == "parent, child"
2108
2109 def test_copy_preserves_header_removal(self, async_client: AsyncAnthropic) -> None:
2110 # an Omit removal set on the client still survives a subsequent copy()
2111 copied = async_client.with_options(
2112 default_headers=cast("dict[str, str]", {"X-Foo": Omit()}),
2113 ).with_options(default_headers={"X-Bar": "true"})
2114 request = copied._build_request(FinalRequestOptions(method="post", url="/foo"))
2115 assert request.headers.get("X-Foo") is None
2116 assert request.headers.get("X-Bar") == "true"
2117
2118 def test_request_extra_query(self, client: Anthropic) -> None:
2119 request = client._build_request(
2120 FinalRequestOptions(
2121 method="post",
2122 url="/foo",
2123 **make_request_options(
2124 extra_query={"my_query_param": "Foo"},
2125 ),
2126 ),
2127 )
2128 params = dict(request.url.params)
2129 assert params == {"my_query_param": "Foo"}
2130
2131 # if both `query` and `extra_query` are given, they are merged
2132 request = client._build_request(
2133 FinalRequestOptions(
2134 method="post",
2135 url="/foo",
2136 **make_request_options(
2137 query={"bar": "1"},
2138 extra_query={"foo": "2"},
2139 ),
2140 ),
2141 )
2142 params = dict(request.url.params)
2143 assert params == {"bar": "1", "foo": "2"}
2144
2145 # `extra_query` takes priority over `query` when keys clash
2146 request = client._build_request(
2147 FinalRequestOptions(
2148 method="post",
2149 url="/foo",
2150 **make_request_options(
2151 query={"foo": "1"},
2152 extra_query={"foo": "2"},
2153 ),
2154 ),
2155 )
2156 params = dict(request.url.params)
2157 assert params == {"foo": "2"}
2158
2159 def test_multipart_repeating_array(self, async_client: AsyncAnthropic) -> None:
2160 request = async_client._build_request(
2161 FinalRequestOptions.construct(
2162 method="post",
2163 url="/foo",
2164 headers={"Content-Type": "multipart/form-data; boundary=6b7ba517decee4a450543ea6ae821c82"},
2165 json_data={"array": ["foo", "bar"]},
2166 files=[("foo.txt", b"hello world")],
2167 )
2168 )
2169
2170 assert request.read().split(b"\r\n") == [
2171 b"--6b7ba517decee4a450543ea6ae821c82",
2172 b'Content-Disposition: form-data; name="array[]"',
2173 b"",
2174 b"foo",
2175 b"--6b7ba517decee4a450543ea6ae821c82",
2176 b'Content-Disposition: form-data; name="array[]"',
2177 b"",
2178 b"bar",
2179 b"--6b7ba517decee4a450543ea6ae821c82",
2180 b'Content-Disposition: form-data; name="foo.txt"; filename="upload"',
2181 b"Content-Type: application/octet-stream",
2182 b"",
2183 b"hello world",
2184 b"--6b7ba517decee4a450543ea6ae821c82--",
2185 b"",
2186 ]
2187
2188 @pytest.mark.respx(base_url=base_url)
2189 async def test_binary_content_upload(self, respx_mock: MockRouter, async_client: AsyncAnthropic) -> None:
2190 respx_mock.post("/upload").mock(side_effect=mirror_request_content)
2191
2192 file_content = b"Hello, this is a test file."
2193
2194 response = await async_client.post(
2195 "/upload",
2196 content=file_content,
2197 cast_to=httpx2.Response,
2198 options={"headers": {"Content-Type": "application/octet-stream"}},
2199 )
2200
2201 assert response.status_code == 200
2202 assert response.request.headers["Content-Type"] == "application/octet-stream"
2203 assert response.content == file_content
2204
2205 async def test_binary_content_upload_with_asynciterator(self) -> None:
2206 file_content = b"Hello, this is a test file."
2207 counter = Counter()
2208 iterator = _make_async_iterator([file_content], counter=counter)
2209
2210 async def mock_handler(request: httpx2.Request) -> httpx2.Response:
2211 assert counter.value == 0, "the request body should not have been read"
2212 return httpx2.Response(200, content=await request.aread())
2213
2214 async with AsyncAnthropic(
2215 base_url=base_url,
2216 api_key=api_key,
2217 _strict_response_validation=True,
2218 http_client=httpx2.AsyncClient(transport=MockTransport(handler=mock_handler)),
2219 ) as client:
2220 response = await client.post(
2221 "/upload",
2222 content=iterator,
2223 cast_to=httpx2.Response,
2224 options={"headers": {"Content-Type": "application/octet-stream"}},
2225 )
2226
2227 assert response.status_code == 200
2228 assert response.request.headers["Content-Type"] == "application/octet-stream"
2229 assert response.content == file_content
2230 assert counter.value == 1
2231
2232 async def test_binary_content_upload_with_body_is_rejected(self, async_client: AsyncAnthropic) -> None:
2233 with pytest.raises(
2234 TypeError, match="Passing raw bytes as `body` is not supported, pass them as `content` instead"
2235 ):
2236 await async_client.post(
2237 "/upload",
2238 body=b"Hello, this is a test file.",
2239 cast_to=httpx2.Response,
2240 options={"headers": {"Content-Type": "application/octet-stream"}},
2241 )
2242
2243 @pytest.mark.respx(base_url=base_url)
2244 async def test_basic_union_response(self, respx_mock: MockRouter, async_client: AsyncAnthropic) -> None:
2245 class Model1(BaseModel):
2246 name: str
2247
2248 class Model2(BaseModel):
2249 foo: str
2250
2251 respx_mock.get("/foo").mock(return_value=httpx2.Response(200, json={"foo": "bar"}))
2252
2253 response = await async_client.get("/foo", cast_to=cast(Any, Union[Model1, Model2]))
2254 assert isinstance(response, Model2)
2255 assert response.foo == "bar"
2256
2257 @pytest.mark.respx(base_url=base_url)
2258 async def test_union_response_different_types(self, respx_mock: MockRouter, async_client: AsyncAnthropic) -> None:
2259 """Union of objects with the same field name using a different type"""
2260
2261 class Model1(BaseModel):
2262 foo: int
2263
2264 class Model2(BaseModel):
2265 foo: str
2266
2267 respx_mock.get("/foo").mock(return_value=httpx2.Response(200, json={"foo": "bar"}))
2268
2269 response = await async_client.get("/foo", cast_to=cast(Any, Union[Model1, Model2]))
2270 assert isinstance(response, Model2)
2271 assert response.foo == "bar"
2272
2273 respx_mock.get("/foo").mock(return_value=httpx2.Response(200, json={"foo": 1}))
2274
2275 response = await async_client.get("/foo", cast_to=cast(Any, Union[Model1, Model2]))
2276 assert isinstance(response, Model1)
2277 assert response.foo == 1
2278
2279 @pytest.mark.respx(base_url=base_url)
2280 async def test_non_application_json_content_type_for_json_data(
2281 self, respx_mock: MockRouter, async_client: AsyncAnthropic
2282 ) -> None:
2283 """
2284 Response that sets Content-Type to something other than application/json but returns json data
2285 """
2286
2287 class Model(BaseModel):
2288 foo: int
2289
2290 respx_mock.get("/foo").mock(
2291 return_value=httpx2.Response(
2292 200,
2293 content=json.dumps({"foo": 2}),
2294 headers={"Content-Type": "application/text"},
2295 )
2296 )
2297
2298 response = await async_client.get("/foo", cast_to=Model)
2299 assert isinstance(response, Model)
2300 assert response.foo == 2
2301
2302 async def test_base_url_setter(self) -> None:
2303 client = AsyncAnthropic(
2304 base_url="https://example.com/from_init", api_key=api_key, _strict_response_validation=True
2305 )
2306 assert client.base_url == "https://example.com/from_init/"
2307
2308 client.base_url = "https://example.com/from_setter" # type: ignore[assignment]
2309
2310 assert client.base_url == "https://example.com/from_setter/"
2311
2312 await client.close()
2313
2314 async def test_base_url_env(self) -> None:
2315 with update_env(ANTHROPIC_BASE_URL="http://localhost:5000/from/env"):
2316 client = AsyncAnthropic(api_key=api_key, _strict_response_validation=True)
2317 assert client.base_url == "http://localhost:5000/from/env/"
2318
2319 @pytest.mark.parametrize(
2320 "client",
2321 [
2322 AsyncAnthropic(
2323 base_url="http://localhost:5000/custom/path/", api_key=api_key, _strict_response_validation=True
2324 ),
2325 AsyncAnthropic(
2326 base_url="http://localhost:5000/custom/path/",
2327 api_key=api_key,
2328 _strict_response_validation=True,
2329 http_client=httpx2.AsyncClient(),
2330 ),
2331 ],
2332 ids=["standard", "custom http client"],
2333 )
2334 async def test_base_url_trailing_slash(self, client: AsyncAnthropic) -> None:
2335 request = client._build_request(
2336 FinalRequestOptions(
2337 method="post",
2338 url="/foo",
2339 json_data={"foo": "bar"},
2340 ),
2341 )
2342 assert request.url == "http://localhost:5000/custom/path/foo"
2343 await client.close()
2344
2345 @pytest.mark.parametrize(
2346 "client",
2347 [
2348 AsyncAnthropic(
2349 base_url="http://localhost:5000/custom/path/", api_key=api_key, _strict_response_validation=True
2350 ),
2351 AsyncAnthropic(
2352 base_url="http://localhost:5000/custom/path/",
2353 api_key=api_key,
2354 _strict_response_validation=True,
2355 http_client=httpx2.AsyncClient(),
2356 ),
2357 ],
2358 ids=["standard", "custom http client"],
2359 )
2360 async def test_base_url_no_trailing_slash(self, client: AsyncAnthropic) -> None:
2361 request = client._build_request(
2362 FinalRequestOptions(
2363 method="post",
2364 url="/foo",
2365 json_data={"foo": "bar"},
2366 ),
2367 )
2368 assert request.url == "http://localhost:5000/custom/path/foo"
2369 await client.close()
2370
2371 @pytest.mark.parametrize(
2372 "client",
2373 [
2374 AsyncAnthropic(
2375 base_url="http://localhost:5000/custom/path/", api_key=api_key, _strict_response_validation=True
2376 ),
2377 AsyncAnthropic(
2378 base_url="http://localhost:5000/custom/path/",
2379 api_key=api_key,
2380 _strict_response_validation=True,
2381 http_client=httpx2.AsyncClient(),
2382 ),
2383 ],
2384 ids=["standard", "custom http client"],
2385 )
2386 async def test_absolute_request_url(self, client: AsyncAnthropic) -> None:
2387 request = client._build_request(
2388 FinalRequestOptions(
2389 method="post",
2390 url="https://myapi.com/foo",
2391 json_data={"foo": "bar"},
2392 ),
2393 )
2394 assert request.url == "https://myapi.com/foo"
2395 await client.close()
2396
2397 async def test_copied_client_does_not_close_http(self) -> None:
2398 test_client = AsyncAnthropic(base_url=base_url, api_key=api_key, _strict_response_validation=True)
2399 assert not test_client.is_closed()
2400
2401 copied = test_client.copy()
2402 assert copied is not test_client
2403
2404 del copied
2405
2406 await asyncio.sleep(0.2)
2407 assert not test_client.is_closed()
2408
2409 async def test_client_context_manager(self) -> None:
2410 test_client = AsyncAnthropic(base_url=base_url, api_key=api_key, _strict_response_validation=True)
2411 async with test_client as c2:
2412 assert c2 is test_client
2413 assert not c2.is_closed()
2414 assert not test_client.is_closed()
2415 assert test_client.is_closed()
2416
2417 @pytest.mark.respx(base_url=base_url)
2418 async def test_client_response_validation_error(self, respx_mock: MockRouter, async_client: AsyncAnthropic) -> None:
2419 class Model(BaseModel):
2420 foo: str
2421
2422 respx_mock.get("/foo").mock(return_value=httpx2.Response(200, json={"foo": {"invalid": True}}))
2423
2424 with pytest.raises(APIResponseValidationError) as exc:
2425 await async_client.get("/foo", cast_to=Model)
2426
2427 assert isinstance(exc.value.__cause__, ValidationError)
2428
2429 async def test_client_max_retries_validation(self) -> None:
2430 with pytest.raises(TypeError, match=r"max_retries cannot be None"):
2431 AsyncAnthropic(
2432 base_url=base_url, api_key=api_key, _strict_response_validation=True, max_retries=cast(Any, None)
2433 )
2434
2435 @pytest.mark.respx(base_url=base_url)
2436 async def test_default_stream_cls(self, respx_mock: MockRouter, async_client: AsyncAnthropic) -> None:
2437 class Model(BaseModel):
2438 name: str
2439
2440 respx_mock.post("/foo").mock(return_value=httpx2.Response(200, json={"foo": "bar"}))
2441
2442 stream = await async_client.post("/foo", cast_to=Model, stream=True, stream_cls=AsyncStream[Model])
2443 assert isinstance(stream, AsyncStream)
2444 await stream.response.aclose()
2445
2446 @pytest.mark.respx(base_url=base_url)
2447 async def test_received_text_for_expected_json(self, respx_mock: MockRouter) -> None:
2448 class Model(BaseModel):
2449 name: str
2450
2451 respx_mock.get("/foo").mock(return_value=httpx2.Response(200, text="my-custom-format"))
2452
2453 strict_client = AsyncAnthropic(base_url=base_url, api_key=api_key, _strict_response_validation=True)
2454
2455 with pytest.raises(APIResponseValidationError):
2456 await strict_client.get("/foo", cast_to=Model)
2457
2458 non_strict_client = AsyncAnthropic(base_url=base_url, api_key=api_key, _strict_response_validation=False)
2459
2460 response = await non_strict_client.get("/foo", cast_to=Model)
2461 assert isinstance(response, str) # type: ignore[unreachable]
2462
2463 await strict_client.close()
2464 await non_strict_client.close()
2465
2466 @pytest.mark.parametrize(
2467 "remaining_retries,retry_after,timeout",
2468 [
2469 [3, "20", 20],
2470 [3, "0", 0.5],
2471 [3, "-10", 0.5],
2472 [3, "60", 60],
2473 [3, "61", 61],
2474 [3, "Fri, 29 Sep 2023 16:26:57 GMT", 20],
2475 [3, "Fri, 29 Sep 2023 16:26:37 GMT", 0.5],
2476 [3, "Fri, 29 Sep 2023 16:26:27 GMT", 0.5],
2477 [3, "Fri, 29 Sep 2023 16:27:37 GMT", 60],
2478 [3, "Fri, 29 Sep 2023 16:27:38 GMT", 61],
2479 [3, "99999999999999999999999999999999999", 4294967],
2480 [3, "inf", 4294967],
2481 [3, "nan", 0.5],
2482 [3, "Zun, 29 Sep 2023 16:26:27 GMT", 0.5],
2483 [3, "", 0.5],
2484 [2, "", 0.5 * 2.0],
2485 [1, "", 0.5 * 4.0],
2486 [-1100, "", 8], # test large number potentially overflowing
2487 ],
2488 )
2489 async def test_parse_retry_after_header(
2490 self,
2491 remaining_retries: int,
2492 retry_after: str,
2493 timeout: float,
2494 async_client: AsyncAnthropic,
2495 monkeypatch: pytest.MonkeyPatch,
2496 ) -> None:
2497 monkeypatch.setattr("time.time", lambda: 1696004797)
2498
2499 headers = httpx2.Headers({"retry-after": retry_after})
2500 options = FinalRequestOptions(method="get", url="/foo", max_retries=3)
2501 calculated = async_client._calculate_retry_timeout(remaining_retries, options, headers)
2502 assert calculated == pytest.approx(timeout, 0.5 * 0.875) # pyright: ignore[reportUnknownMemberType]
2503
2504 @pytest.mark.respx(base_url=base_url)
2505 async def test_retrying_timeout_errors_doesnt_leak(
2506 self, respx_mock: MockRouter, async_client: AsyncAnthropic, monkeypatch: pytest.MonkeyPatch
2507 ) -> None:
2508 monkeypatch.setattr(BaseClient, "_calculate_retry_timeout", _low_retry_timeout)
2509
2510 respx_mock.post("/v1/messages").mock(side_effect=httpx2.TimeoutException("Test timeout error"))
2511
2512 with pytest.raises(APITimeoutError):
2513 await async_client.messages.with_streaming_response.create(
2514 max_tokens=1024,
2515 messages=[
2516 {
2517 "content": "Hello, world",
2518 "role": "user",
2519 }
2520 ],
2521 model="claude-opus-5",
2522 ).__aenter__()
2523
2524 assert _get_open_connections(async_client) == 0
2525
2526 @pytest.mark.respx(base_url=base_url)
2527 async def test_retrying_status_errors_doesnt_leak(
2528 self, respx_mock: MockRouter, async_client: AsyncAnthropic, monkeypatch: pytest.MonkeyPatch
2529 ) -> None:
2530 monkeypatch.setattr(BaseClient, "_calculate_retry_timeout", _low_retry_timeout)
2531
2532 respx_mock.post("/v1/messages").mock(return_value=httpx2.Response(500))
2533
2534 with pytest.raises(APIStatusError):
2535 await async_client.messages.with_streaming_response.create(
2536 max_tokens=1024,
2537 messages=[
2538 {
2539 "content": "Hello, world",
2540 "role": "user",
2541 }
2542 ],
2543 model="claude-opus-5",
2544 ).__aenter__()
2545 assert _get_open_connections(async_client) == 0
2546
2547 @pytest.mark.parametrize("failures_before_success", [0, 2, 4])
2548 @pytest.mark.respx(base_url=base_url)
2549 @pytest.mark.parametrize("failure_mode", ["status", "exception"])
2550 async def test_retries_taken(
2551 self,
2552 async_client: AsyncAnthropic,
2553 failures_before_success: int,
2554 failure_mode: Literal["status", "exception"],
2555 respx_mock: MockRouter,
2556 monkeypatch: pytest.MonkeyPatch,
2557 ) -> None:
2558 monkeypatch.setattr(BaseClient, "_calculate_retry_timeout", _low_retry_timeout)
2559
2560 client = async_client.with_options(max_retries=4)
2561
2562 nb_retries = 0
2563
2564 def retry_handler(_request: httpx2.Request) -> httpx2.Response:
2565 nonlocal nb_retries
2566 if nb_retries < failures_before_success:
2567 nb_retries += 1
2568 if failure_mode == "exception":
2569 raise RuntimeError("oops")
2570 return httpx2.Response(500)
2571 return httpx2.Response(200)
2572
2573 respx_mock.post("/v1/messages").mock(side_effect=retry_handler)
2574
2575 response = await client.messages.with_raw_response.create(
2576 max_tokens=1024,
2577 messages=[
2578 {
2579 "content": "Hello, world",
2580 "role": "user",
2581 }
2582 ],
2583 model="claude-opus-5",
2584 )
2585
2586 assert response.retries_taken == failures_before_success
2587 assert int(response.http_request.headers.get("x-stainless-retry-count")) == failures_before_success
2588
2589 @pytest.mark.parametrize("failures_before_success", [0, 2, 4])
2590 @pytest.mark.respx(base_url=base_url)
2591 async def test_omit_retry_count_header(
2592 self,
2593 async_client: AsyncAnthropic,
2594 failures_before_success: int,
2595 respx_mock: MockRouter,
2596 monkeypatch: pytest.MonkeyPatch,
2597 ) -> None:
2598 monkeypatch.setattr(BaseClient, "_calculate_retry_timeout", _low_retry_timeout)
2599
2600 client = async_client.with_options(max_retries=4)
2601
2602 nb_retries = 0
2603
2604 def retry_handler(_request: httpx2.Request) -> httpx2.Response:
2605 nonlocal nb_retries
2606 if nb_retries < failures_before_success:
2607 nb_retries += 1
2608 return httpx2.Response(500)
2609 return httpx2.Response(200)
2610
2611 respx_mock.post("/v1/messages").mock(side_effect=retry_handler)
2612
2613 response = await client.messages.with_raw_response.create(
2614 max_tokens=1024,
2615 messages=[
2616 {
2617 "content": "Hello, world",
2618 "role": "user",
2619 }
2620 ],
2621 model="claude-opus-5",
2622 extra_headers={"x-stainless-retry-count": Omit()},
2623 )
2624
2625 assert len(response.http_request.headers.get_list("x-stainless-retry-count")) == 0
2626
2627 @pytest.mark.parametrize("failures_before_success", [0, 2, 4])
2628 @pytest.mark.respx(base_url=base_url)
2629 async def test_overwrite_retry_count_header(
2630 self,
2631 async_client: AsyncAnthropic,
2632 failures_before_success: int,
2633 respx_mock: MockRouter,
2634 monkeypatch: pytest.MonkeyPatch,
2635 ) -> None:
2636 monkeypatch.setattr(BaseClient, "_calculate_retry_timeout", _low_retry_timeout)
2637
2638 client = async_client.with_options(max_retries=4)
2639
2640 nb_retries = 0
2641
2642 def retry_handler(_request: httpx2.Request) -> httpx2.Response:
2643 nonlocal nb_retries
2644 if nb_retries < failures_before_success:
2645 nb_retries += 1
2646 return httpx2.Response(500)
2647 return httpx2.Response(200)
2648
2649 respx_mock.post("/v1/messages").mock(side_effect=retry_handler)
2650
2651 response = await client.messages.with_raw_response.create(
2652 max_tokens=1024,
2653 messages=[
2654 {
2655 "content": "Hello, world",
2656 "role": "user",
2657 }
2658 ],
2659 model="claude-opus-5",
2660 extra_headers={"x-stainless-retry-count": "42"},
2661 )
2662
2663 assert response.http_request.headers.get("x-stainless-retry-count") == "42"
2664
2665 async def test_get_platform(self) -> None:
2666 platform = await asyncify(get_platform)()
2667 assert isinstance(platform, (str, OtherPlatform))
2668
2669 def test_platform_headers_do_not_spawn_subprocesses(self, monkeypatch: pytest.MonkeyPatch) -> None:
2670 # a cold process resolves `platform.uname().processor` lazily by running `uname -p`
2671 monkeypatch.setattr("platform._uname_cache", None, raising=False)
2672
2673 spawned: list[object] = []
2674
2675 def fake_popen(*args: object, **kwargs: object) -> None:
2676 spawned.append(args[0] if args else kwargs.get("args"))
2677 raise OSError("unexpected subprocess")
2678
2679 monkeypatch.setattr("subprocess.Popen", fake_popen)
2680
2681 get_platform()
2682 get_architecture()
2683
2684 assert spawned == []
2685
2686 async def test_proxy_environment_variables(self, monkeypatch: pytest.MonkeyPatch) -> None:
2687 # Test that the proxy environment variables are set correctly
2688 monkeypatch.setenv("HTTPS_PROXY", "https://example.org")
2689 # Delete in case our environment has any proxy env vars set
2690 monkeypatch.delenv("HTTP_PROXY", raising=False)
2691 monkeypatch.delenv("ALL_PROXY", raising=False)
2692 monkeypatch.delenv("NO_PROXY", raising=False)
2693 monkeypatch.delenv("http_proxy", raising=False)
2694 monkeypatch.delenv("https_proxy", raising=False)
2695 monkeypatch.delenv("all_proxy", raising=False)
2696 monkeypatch.delenv("no_proxy", raising=False)
2697
2698 client = DefaultAsyncHttpxClient()
2699
2700 mounts = tuple(client._mounts.items())
2701 assert len(mounts) == 1
2702 assert mounts[0][0].pattern == "https://"
2703
2704 async def test_default_client_creation(self) -> None:
2705 # Ensure that the client can be initialized without any exceptions
2706 DefaultAsyncHttpxClient(
2707 verify=True,
2708 cert=None,
2709 trust_env=True,
2710 http1=True,
2711 http2=False,
2712 limits=httpx2.Limits(max_connections=100, max_keepalive_connections=20),
2713 )
2714
2715 @pytest.mark.respx(base_url=base_url)
2716 async def test_follow_redirects(self, respx_mock: MockRouter, async_client: AsyncAnthropic) -> None:
2717 # Test that the default follow_redirects=True allows following redirects
2718 respx_mock.post("/redirect").mock(
2719 return_value=httpx2.Response(302, headers={"Location": f"{base_url}/redirected"})
2720 )
2721 respx_mock.get("/redirected").mock(return_value=httpx2.Response(200, json={"status": "ok"}))
2722
2723 response = await async_client.post("/redirect", body={"key": "value"}, cast_to=httpx2.Response)
2724 assert response.status_code == 200
2725 assert response.json() == {"status": "ok"}
2726
2727 @pytest.mark.respx(base_url=base_url)
2728 async def test_follow_redirects_disabled(self, respx_mock: MockRouter, async_client: AsyncAnthropic) -> None:
2729 # Test that follow_redirects=False prevents following redirects
2730 respx_mock.post("/redirect").mock(
2731 return_value=httpx2.Response(302, headers={"Location": f"{base_url}/redirected"})
2732 )
2733
2734 with pytest.raises(APIStatusError) as exc_info:
2735 await async_client.post(
2736 "/redirect", body={"key": "value"}, options={"follow_redirects": False}, cast_to=httpx2.Response
2737 )
2738
2739 assert exc_info.value.response.status_code == 302
2740 assert exc_info.value.response.headers["Location"] == f"{base_url}/redirected"
2741
2742 @pytest.mark.respx(base_url=base_url)
2743 async def test_status_error_type_field(self, respx_mock: MockRouter, async_client: AsyncAnthropic) -> None:
2744 respx_mock.post("/v1/messages").mock(
2745 return_value=httpx2.Response(
2746 400,
2747 json={"type": "error", "error": {"type": "invalid_request_error", "message": "Bad request"}},
2748 )
2749 )
2750 with pytest.raises(APIStatusError) as exc_info:
2751 await async_client.messages.create(
2752 max_tokens=1024,
2753 messages=[{"role": "user", "content": "Hello"}],
2754 model="claude-opus-4-6",
2755 )
2756 assert exc_info.value.type == "invalid_request_error"
2757 assert exc_info.value.status_code == 400