Debian Codegraph @

src/anthropic/_base_client.py

raw
1 from __future__ import annotations
2
3 import sys
4 import json
5 import time
6 import uuid
7 import email
8 import socket
9 import asyncio
10 import inspect
11 import logging
12 import platform
13 import email.utils
14 from types import TracebackType
15 from random import random
16 from typing import (
17 TYPE_CHECKING,
18 Any,
19 Dict,
20 List,
21 Type,
22 Tuple,
23 Union,
24 Generic,
25 Mapping,
26 TypeVar,
27 Iterable,
28 Iterator,
29 Optional,
30 Sequence,
31 Generator,
32 AsyncIterator,
33 cast,
34 overload,
35 )
36 from typing_extensions import Literal, override, get_origin
37
38 import anyio
39 import httpx2
40 import pydantic
41 from httpx2 import URL, Proxy, HTTPTransport, AsyncHTTPTransport
42 from pydantic import PrivateAttr
43
44 from . import _exceptions
45 from ._qs import Querystring
46 from ._files import to_httpx_files, async_to_httpx_files
47 from ._types import (
48 Body,
49 Omit,
50 Query,
51 Headers,
52 Timeout,
53 NotGiven,
54 ResponseT,
55 AnyMapping,
56 PostParser,
57 BinaryTypes,
58 RequestFiles,
59 HttpxSendArgs,
60 RequestOptions,
61 AsyncBinaryTypes,
62 HttpxRequestFiles,
63 ModelBuilderProtocol,
64 omit,
65 not_given,
66 )
67 from ._utils import (
68 is_dict,
69 is_list,
70 asyncify,
71 is_given,
72 lru_cache,
73 is_mapping,
74 strip_omit,
75 prepare_request_data,
76 async_prepare_request_data,
77 )
78 from ._compat import PYDANTIC_V1, model_copy, model_dump
79 from ._models import GenericModel, FinalRequestOptions, validate_type, construct_type
80 from ._request import APIRequest
81 from ._response import (
82 APIResponse,
83 BaseAPIResponse,
84 AsyncAPIResponse,
85 extract_response_type,
86 )
87 from ._constants import (
88 DEFAULT_TIMEOUT,
89 MAX_RETRY_DELAY,
90 DEFAULT_MAX_RETRIES,
91 INITIAL_RETRY_DELAY,
92 RAW_RESPONSE_HEADER,
93 OVERRIDE_CAST_TO_HEADER,
94 DEFAULT_CONNECTION_LIMITS,
95 )
96 from ._streaming import Stream, SSEDecoder, AsyncStream, SSEBytesDecoder
97 from ._exceptions import (
98 AnthropicError,
99 APIStatusError,
100 RetryableError,
101 APITimeoutError,
102 APIConnectionError,
103 APIResponseValidationError,
104 )
105 from ._middleware import (
106 CallNext,
107 Middleware,
108 AsyncCallNext,
109 MiddlewareInput,
110 MiddlewareCallable,
111 AsyncMiddlewareCallable,
112 validate_sync_middleware,
113 validate_async_middleware,
114 )
115 from ._utils._json import openapi_dumps
116 from ._utils._httpx import get_environment_proxies
117
118 log: logging.Logger = logging.getLogger(__name__)
119
120 # TODO: make base page type vars covariant
121 SyncPageT = TypeVar("SyncPageT", bound="BaseSyncPage[Any]")
122 AsyncPageT = TypeVar("AsyncPageT", bound="BaseAsyncPage[Any]")
123
124
125 _T = TypeVar("_T")
126 _T_co = TypeVar("_T_co", covariant=True)
127
128 _StreamT = TypeVar("_StreamT", bound=Stream[Any])
129 _AsyncStreamT = TypeVar("_AsyncStreamT", bound=AsyncStream[Any])
130
131 if TYPE_CHECKING:
132 from httpx2._config import (
133 DEFAULT_TIMEOUT_CONFIG, # pyright: ignore[reportPrivateImportUsage]
134 )
135
136 HTTPX_DEFAULT_TIMEOUT = DEFAULT_TIMEOUT_CONFIG
137 else:
138 try:
139 from httpx2._config import DEFAULT_TIMEOUT_CONFIG as HTTPX_DEFAULT_TIMEOUT
140 except ImportError:
141 # taken from https://github.com/encode/httpx/blob/3ba5fe0d7ac70222590e759c31442b1cab263791/httpx/_config.py#L366
142 HTTPX_DEFAULT_TIMEOUT = Timeout(5.0)
143
144
145 def _reject_httpx_object(name: str, value: object) -> None:
146 """`httpx` objects don't work with `httpx2`, and would otherwise fail deep inside a request."""
147 for cls in type(value).__mro__:
148 module = getattr(cls, "__module__", None)
149 if isinstance(module, str) and module.partition(".")[0] == "httpx":
150 raise TypeError(
151 f"Invalid `{name}` argument; `httpx.{cls.__name__}` is from the `httpx` package, but this SDK uses `httpx2`. Use `httpx2.{cls.__name__}` instead."
152 )
153
154
155 class PageInfo:
156 """Stores the necessary information to build the request to retrieve the next page.
157
158 Either `url` or `params` must be set.
159 """
160
161 url: URL | NotGiven
162 params: Query | NotGiven
163 json: Body | NotGiven
164
165 @overload
166 def __init__(
167 self,
168 *,
169 url: URL,
170 ) -> None: ...
171
172 @overload
173 def __init__(
174 self,
175 *,
176 params: Query,
177 ) -> None: ...
178
179 @overload
180 def __init__(
181 self,
182 *,
183 json: Body,
184 ) -> None: ...
185
186 def __init__(
187 self,
188 *,
189 url: URL | NotGiven = not_given,
190 json: Body | NotGiven = not_given,
191 params: Query | NotGiven = not_given,
192 ) -> None:
193 self.url = url
194 self.json = json
195 self.params = params
196
197 @override
198 def __repr__(self) -> str:
199 if self.url:
200 return f"{self.__class__.__name__}(url={self.url})"
201 if self.json:
202 return f"{self.__class__.__name__}(json={self.json})"
203 return f"{self.__class__.__name__}(params={self.params})"
204
205
206 class BasePage(GenericModel, Generic[_T]):
207 """
208 Defines the core interface for pagination.
209
210 Type Args:
211 ModelT: The pydantic model that represents an item in the response.
212
213 Methods:
214 has_next_page(): Check if there is another page available
215 next_page_info(): Get the necessary information to make a request for the next page
216 """
217
218 _options: FinalRequestOptions = PrivateAttr()
219 _model: Type[_T] = PrivateAttr()
220
221 def has_next_page(self) -> bool:
222 items = self._get_page_items()
223 if not items:
224 return False
225 return self.next_page_info() is not None
226
227 def next_page_info(self) -> Optional[PageInfo]: ...
228
229 def _get_page_items(self) -> Iterable[_T]: # type: ignore[empty-body]
230 ...
231
232 def _params_from_url(self, url: URL) -> httpx2.QueryParams:
233 # TODO: do we have to preprocess params here?
234 return httpx2.QueryParams(cast(Any, self._options.params)).merge(url.params)
235
236 def _info_to_options(self, info: PageInfo) -> FinalRequestOptions:
237 options = model_copy(self._options)
238 options._strip_raw_response_header()
239
240 if not isinstance(info.params, NotGiven):
241 options.params = {**options.params, **info.params}
242 return options
243
244 if not isinstance(info.url, NotGiven):
245 params = self._params_from_url(info.url)
246 url = info.url.copy_with(params=params)
247 options.params = dict(url.params)
248 options.url = str(url)
249 return options
250
251 if not isinstance(info.json, NotGiven):
252 if not is_mapping(info.json):
253 raise TypeError("Pagination is only supported with mappings")
254
255 if not options.json_data:
256 options.json_data = {**info.json}
257 else:
258 if not is_mapping(options.json_data):
259 raise TypeError("Pagination is only supported with mappings")
260
261 options.json_data = {**options.json_data, **info.json}
262 return options
263
264 raise ValueError("Unexpected PageInfo state")
265
266
267 class BaseSyncPage(BasePage[_T], Generic[_T]):
268 _client: SyncAPIClient = pydantic.PrivateAttr()
269
270 def _set_private_attributes(
271 self,
272 client: SyncAPIClient,
273 model: Type[_T],
274 options: FinalRequestOptions,
275 ) -> None:
276 if (not PYDANTIC_V1) and getattr(self, "__pydantic_private__", None) is None:
277 self.__pydantic_private__ = {}
278
279 self._model = model
280 self._client = client
281 self._options = options
282
283 # Pydantic uses a custom `__iter__` method to support casting BaseModels
284 # to dictionaries. e.g. dict(model).
285 # As we want to support `for item in page`, this is inherently incompatible
286 # with the default pydantic behaviour. It is not possible to support both
287 # use cases at once. Fortunately, this is not a big deal as all other pydantic
288 # methods should continue to work as expected as there is an alternative method
289 # to cast a model to a dictionary, model.dict(), which is used internally
290 # by pydantic.
291 def __iter__(self) -> Iterator[_T]: # type: ignore
292 for page in self.iter_pages():
293 for item in page._get_page_items():
294 yield item
295
296 def iter_pages(self: SyncPageT) -> Iterator[SyncPageT]:
297 page = self
298 while True:
299 yield page
300 if page.has_next_page():
301 page = page.get_next_page()
302 else:
303 return
304
305 def get_next_page(self: SyncPageT) -> SyncPageT:
306 info = self.next_page_info()
307 if not info:
308 raise RuntimeError(
309 "No next page expected; please check `.has_next_page()` before calling `.get_next_page()`."
310 )
311
312 options = self._info_to_options(info)
313 return self._client._request_api_list(self._model, page=self.__class__, options=options)
314
315
316 class AsyncPaginator(Generic[_T, AsyncPageT]):
317 def __init__(
318 self,
319 client: AsyncAPIClient,
320 options: FinalRequestOptions,
321 page_cls: Type[AsyncPageT],
322 model: Type[_T],
323 ) -> None:
324 self._model = model
325 self._client = client
326 self._options = options
327 self._page_cls = page_cls
328
329 def __await__(self) -> Generator[Any, None, AsyncPageT]:
330 return self._get_page().__await__()
331
332 async def _get_page(self) -> AsyncPageT:
333 # the page sends its options again for the next page, so it has to keep the prepared ones
334 self._options = options = await self._client._copy_and_prepare(self._options)
335
336 def _parser(resp: AsyncPageT) -> AsyncPageT:
337 resp._set_private_attributes(
338 model=self._model,
339 options=options,
340 client=self._client,
341 )
342 return resp
343
344 options.post_parser = _parser
345
346 return await self._client.request(self._page_cls, options)
347
348 async def __aiter__(self) -> AsyncIterator[_T]:
349 # https://github.com/microsoft/pyright/issues/3464
350 page = cast(
351 AsyncPageT,
352 await self, # type: ignore
353 )
354 async for item in page:
355 yield item
356
357
358 class BaseAsyncPage(BasePage[_T], Generic[_T]):
359 _client: AsyncAPIClient = pydantic.PrivateAttr()
360
361 def _set_private_attributes(
362 self,
363 model: Type[_T],
364 client: AsyncAPIClient,
365 options: FinalRequestOptions,
366 ) -> None:
367 if (not PYDANTIC_V1) and getattr(self, "__pydantic_private__", None) is None:
368 self.__pydantic_private__ = {}
369
370 self._model = model
371 self._client = client
372 self._options = options
373
374 async def __aiter__(self) -> AsyncIterator[_T]:
375 async for page in self.iter_pages():
376 for item in page._get_page_items():
377 yield item
378
379 async def iter_pages(self: AsyncPageT) -> AsyncIterator[AsyncPageT]:
380 page = self
381 while True:
382 yield page
383 if page.has_next_page():
384 page = await page.get_next_page()
385 else:
386 return
387
388 async def get_next_page(self: AsyncPageT) -> AsyncPageT:
389 info = self.next_page_info()
390 if not info:
391 raise RuntimeError(
392 "No next page expected; please check `.has_next_page()` before calling `.get_next_page()`."
393 )
394
395 options = self._info_to_options(info)
396 return await self._client._request_api_list(self._model, page=self.__class__, options=options)
397
398
399 _HttpxClientT = TypeVar("_HttpxClientT", bound=Union[httpx2.Client, httpx2.AsyncClient])
400 _DefaultStreamT = TypeVar("_DefaultStreamT", bound=Union[Stream[Any], AsyncStream[Any]])
401
402
403 class BaseClient(Generic[_HttpxClientT, _DefaultStreamT]):
404 _client: _HttpxClientT
405 _version: str
406 _base_url: URL
407 max_retries: int
408 timeout: Union[float, Timeout, None]
409 _strict_response_validation: bool
410 _idempotency_header: str | None
411 _default_stream_cls: type[_DefaultStreamT] | None = None
412 _middleware: tuple[MiddlewareInput, ...]
413
414 def __init__(
415 self,
416 *,
417 version: str,
418 base_url: str | URL,
419 _strict_response_validation: bool,
420 max_retries: int = DEFAULT_MAX_RETRIES,
421 timeout: float | Timeout | None = DEFAULT_TIMEOUT,
422 custom_headers: Mapping[str, str] | None = None,
423 custom_query: Mapping[str, object] | None = None,
424 middleware: Sequence[MiddlewareInput] | None = None,
425 ) -> None:
426 _reject_httpx_object("timeout", timeout)
427
428 self._version = version
429 self._base_url = self._enforce_trailing_slash(URL(base_url))
430 self.max_retries = max_retries
431 self.timeout = timeout
432 self._custom_headers = custom_headers or {}
433 self._custom_query = custom_query or {}
434 self._strict_response_validation = _strict_response_validation
435 self._idempotency_header = None
436 self._platform: Platform | None = None
437 self._middleware = tuple(middleware or ())
438
439 if max_retries is None: # pyright: ignore[reportUnnecessaryComparison]
440 raise TypeError(
441 "max_retries cannot be None. If you want to disable retries, pass `0`; if you want unlimited retries, pass `math.inf` or a very high number; if you want the default behavior, pass `anthropic.DEFAULT_MAX_RETRIES`"
442 )
443
444 def _enforce_trailing_slash(self, url: URL) -> URL:
445 if url.raw_path.endswith(b"/"):
446 return url
447 return url.copy_with(raw_path=url.raw_path + b"/")
448
449 def _make_status_error_from_response(
450 self,
451 response: httpx2.Response,
452 ) -> APIStatusError:
453 if response.is_closed and not response.is_stream_consumed:
454 # We can't read the response body as it has been closed
455 # before it was read. This can happen if an event hook
456 # raises a status error.
457 body = None
458 err_msg = f"Error code: {response.status_code}"
459 else:
460 err_text = response.text.strip()
461 body = err_text
462
463 try:
464 body = json.loads(err_text)
465 err_msg = f"Error code: {response.status_code} - {body}"
466 except Exception:
467 err_msg = err_text or f"Error code: {response.status_code}"
468
469 return self._make_status_error(err_msg, body=body, response=response)
470
471 def _make_status_error(
472 self,
473 err_msg: str,
474 *,
475 body: object,
476 response: httpx2.Response,
477 ) -> _exceptions.APIStatusError:
478 raise NotImplementedError()
479
480 def _build_headers(self, options: FinalRequestOptions, *, retries_taken: int = 0) -> httpx2.Headers:
481 timeout = self.timeout if isinstance(options.timeout, NotGiven) else options.timeout
482 read_timeout = timeout.read if isinstance(timeout, Timeout) else timeout
483 idempotency_header = self._idempotency_header
484 idempotency_key = options.idempotency_key
485
486 # lowest precedence first; any of these can be overridden or `Omit`-ted by the layers after it
487 headers, omitted = build_headers(
488 {
489 "x-stainless-timeout": str(options.timeout.read)
490 if isinstance(options.timeout, Timeout)
491 else str(options.timeout),
492 "x-stainless-retry-count": str(retries_taken),
493 **({"x-stainless-read-timeout": str(read_timeout)} if read_timeout is not None else {}),
494 **({idempotency_header: idempotency_key} if idempotency_header and idempotency_key else {}),
495 **self.default_headers,
496 },
497 # `default_headers` already includes these, but as a layer of their own they also
498 # win over any default a subclass adds after spreading them in
499 self._custom_headers,
500 options.headers or {},
501 )
502 self._validate_headers(headers, omitted)
503
504 return headers
505
506 def _prepare_url(self, url: str) -> URL:
507 """
508 Merge a URL argument together with any 'base_url' on the client,
509 to create the URL used for the outgoing request.
510 """
511 # Copied from httpx's `_merge_url` method.
512 merge_url = URL(url)
513 if merge_url.is_relative_url:
514 merge_raw_path = self.base_url.raw_path + merge_url.raw_path.lstrip(b"/")
515 return self.base_url.copy_with(raw_path=merge_raw_path)
516
517 return merge_url
518
519 def _make_sse_decoder(self) -> SSEDecoder | SSEBytesDecoder:
520 return SSEDecoder()
521
522 def _build_request(
523 self,
524 options: FinalRequestOptions,
525 *,
526 retries_taken: int = 0,
527 ) -> httpx2.Request:
528 _reject_httpx_object("timeout", options.timeout)
529
530 if log.isEnabledFor(logging.DEBUG):
531 log.debug(
532 "Request options: %s",
533 model_dump(
534 options,
535 exclude_unset=True,
536 # Pydantic v1's `.dict()` can't copy every value these fields may hold: some `content`
537 # types, and the `extra_body` of a GET, which is left unprepared (e.g. a generator).
538 exclude={
539 "content",
540 "extra_json",
541 }
542 if PYDANTIC_V1
543 else {},
544 ),
545 )
546 kwargs: dict[str, Any] = {}
547
548 json_data = options.json_data
549 if options.extra_json is not None:
550 if json_data is None:
551 json_data = cast(Body, options.extra_json)
552 elif is_mapping(json_data):
553 json_data = _merge_mappings(json_data, options.extra_json)
554 else:
555 raise RuntimeError(f"Unexpected JSON data type, {type(json_data)}, cannot merge with `extra_body`")
556
557 headers = self._build_headers(options, retries_taken=retries_taken)
558 params = _merge_mappings(self.default_query, options.params)
559 content_type = headers.get("Content-Type")
560 files = options.files
561
562 # If the given Content-Type header is multipart/form-data then it
563 # has to be removed so that httpx can generate the header with
564 # additional information for us as it has to be in this form
565 # for the server to be able to correctly parse the request:
566 # multipart/form-data; boundary=---abc--
567 if content_type is not None and content_type.lower().startswith("multipart/form-data"):
568 if "boundary" not in content_type.lower():
569 # only remove the header if the boundary hasn't been explicitly set
570 # as the caller doesn't want httpx to come up with their own boundary
571 headers.pop("Content-Type")
572
573 # As we are now sending multipart/form-data instead of application/json
574 # we need to tell httpx to use it, https://httpx2.pydantic.dev/advanced/clients/#multipart-file-encoding
575 if json_data:
576 if not is_dict(json_data):
577 raise TypeError(
578 f"Expected query input to be a dictionary for multipart requests but got {type(json_data)} instead."
579 )
580 kwargs["data"] = self._serialize_multipartform(json_data)
581
582 # httpx determines whether or not to send a "multipart/form-data"
583 # request based on the truthiness of the "files" argument.
584 # This gets around that issue by generating a dict value that
585 # evaluates to true.
586 #
587 # https://github.com/encode/httpx/discussions/2399#discussioncomment-3814186
588 if not files:
589 files = cast(HttpxRequestFiles, ForceMultipartDict())
590
591 prepared_url = self._prepare_url(options.url)
592 # preserve hard-coded query params from the url
593 if params and prepared_url.query:
594 params = {**dict(prepared_url.params.items()), **params}
595 prepared_url = prepared_url.copy_with(raw_path=prepared_url.raw_path.split(b"?", 1)[0])
596 if "_" in prepared_url.host:
597 # work around https://github.com/encode/httpx/discussions/2880
598 kwargs["extensions"] = {"sni_hostname": prepared_url.host.replace("_", "-")}
599
600 is_body_allowed = options.method.lower() != "get"
601
602 if is_body_allowed:
603 if options.content is not None and json_data is not None:
604 raise TypeError("Passing both `content` and `json_data` is not supported")
605 if options.content is not None and files is not None:
606 raise TypeError("Passing both `content` and `files` is not supported")
607 if isinstance(json_data, bytes):
608 raise TypeError("Passing raw bytes as `body` is not supported, pass them as `content` instead")
609 if options.content is not None:
610 kwargs["content"] = options.content
611 elif not files:
612 # Don't set content when JSON is sent as multipart/form-data,
613 # since httpx's content param overrides other body arguments
614 kwargs["content"] = openapi_dumps(json_data) if is_given(json_data) and json_data is not None else None
615 kwargs["files"] = files
616 else:
617 headers.pop("Content-Type", None)
618 kwargs.pop("data", None)
619
620 # TODO: report this error to httpx
621 return self._client.build_request( # pyright: ignore[reportUnknownMemberType]
622 headers=headers,
623 timeout=self.timeout if isinstance(options.timeout, NotGiven) else options.timeout,
624 method=options.method,
625 url=prepared_url,
626 # the `Query` type that we use is incompatible with qs'
627 # `Params` type as it needs to be typed as `Mapping[str, object]`
628 # so that passing a `TypedDict` doesn't cause an error.
629 # https://github.com/microsoft/pyright/issues/3526#event-6715453066
630 params=self.qs.stringify(cast(Mapping[str, Any], params)) if params else None,
631 **kwargs,
632 )
633
634 def _serialize_multipartform(self, data: Mapping[object, object]) -> dict[str, object]:
635 items = self.qs.stringify_items(
636 # TODO: type ignore is required as stringify_items is well typed but we can't be
637 # well typed without heavy validation.
638 data, # type: ignore
639 array_format="brackets",
640 )
641 serialized: dict[str, object] = {}
642 for key, value in items:
643 existing = serialized.get(key)
644
645 if not existing:
646 serialized[key] = value
647 continue
648
649 # If a value has already been set for this key then that
650 # means we're sending data like `array[]=[1, 2, 3]` and we
651 # need to tell httpx that we want to send multiple values with
652 # the same key which is done by using a list or a tuple.
653 #
654 # Note: 2d arrays should never result in the same key at both
655 # levels so it's safe to assume that if the value is a list,
656 # it was because we changed it to be a list.
657 if is_list(existing):
658 existing.append(value)
659 else:
660 serialized[key] = [existing, value]
661
662 return serialized
663
664 def _maybe_override_cast_to(self, cast_to: type[ResponseT], options: FinalRequestOptions) -> type[ResponseT]:
665 if not is_given(options.headers):
666 return cast_to
667
668 # make a copy of the headers so we don't mutate user-input
669 headers = dict(options.headers)
670
671 # we internally support defining a temporary header to override the
672 # default `cast_to` type for use with `.with_raw_response` and `.with_streaming_response`
673 # see _response.py for implementation details
674 override_cast_to = headers.pop(OVERRIDE_CAST_TO_HEADER, not_given)
675 if is_given(override_cast_to):
676 options.headers = headers
677 return cast(Type[ResponseT], override_cast_to)
678
679 return cast_to
680
681 def _should_stream_response_body(self, request: httpx2.Request) -> bool:
682 return request.headers.get(RAW_RESPONSE_HEADER) == "stream" # type: ignore[no-any-return]
683
684 def _process_response_data(
685 self,
686 *,
687 data: object,
688 cast_to: type[ResponseT],
689 response: httpx2.Response,
690 ) -> ResponseT:
691 if data is None:
692 return cast(ResponseT, None)
693
694 if cast_to is object:
695 return cast(ResponseT, data)
696
697 try:
698 if inspect.isclass(cast_to) and issubclass(cast_to, ModelBuilderProtocol):
699 return cast(ResponseT, cast_to.build(response=response, data=data))
700
701 if self._strict_response_validation:
702 return cast(ResponseT, validate_type(type_=cast_to, value=data))
703
704 return cast(ResponseT, construct_type(type_=cast_to, value=data))
705 except pydantic.ValidationError as err:
706 raise APIResponseValidationError(response=response, body=data) from err
707
708 @property
709 def qs(self) -> Querystring:
710 return Querystring()
711
712 @property
713 def custom_auth(self) -> httpx2.Auth | None:
714 return None
715
716 @property
717 def auth_headers(self) -> dict[str, str]:
718 return {}
719
720 @property
721 def default_headers(self) -> dict[str, str | Omit]:
722 return {
723 "Accept": "application/json",
724 "Content-Type": "application/json",
725 "User-Agent": self.user_agent,
726 **self.platform_headers(),
727 **self.auth_headers,
728 **self._custom_headers,
729 }
730
731 @property
732 def default_query(self) -> dict[str, object]:
733 return {
734 **self._custom_query,
735 }
736
737 def _validate_headers(
738 self,
739 headers: httpx2.Headers, # noqa: ARG002
740 omitted: frozenset[str], # noqa: ARG002
741 ) -> None:
742 """Validate the headers a request is about to be sent with.
743
744 `omitted` holds the (lowercase) names a header layer explicitly removed with `Omit`.
745
746 Does nothing by default.
747 """
748 return
749
750 @property
751 def user_agent(self) -> str:
752 return f"{self.__class__.__name__}/Python {self._version}"
753
754 @property
755 def base_url(self) -> URL:
756 return self._base_url
757
758 @base_url.setter
759 def base_url(self, url: URL | str) -> None:
760 self._base_url = self._enforce_trailing_slash(url if isinstance(url, URL) else URL(url))
761
762 @property
763 def middleware(self) -> tuple[MiddlewareInput, ...]:
764 """The client-level middleware, outermost first.
765
766 To run extra middleware for specific calls, derive a client with
767 `client.with_options(middleware=[*client.middleware, extra])`.
768 """
769 return self._middleware
770
771 def platform_headers(self) -> Dict[str, str]:
772 # the actual implementation is in a separate `lru_cache` decorated
773 # function because adding `lru_cache` to methods will leak memory
774 # https://github.com/python/cpython/issues/88476
775 return platform_headers(self._version, platform=self._platform)
776
777 def _calculate_nonstreaming_timeout(self, max_tokens: int, max_nonstreaming_tokens: int | None) -> Timeout:
778 maximum_time = 60 * 60
779 default_time = 60 * 10
780
781 expected_time = maximum_time * max_tokens / 128_000
782 if expected_time > default_time or (max_nonstreaming_tokens and max_tokens > max_nonstreaming_tokens):
783 raise ValueError(
784 "Streaming is required for operations that may take longer than 10 minutes. "
785 + "See https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/python#long-requests for more details",
786 )
787 return Timeout(
788 default_time,
789 connect=5.0,
790 )
791
792 def _parse_retry_after_header(self, response_headers: Optional[httpx2.Headers] = None) -> float | None:
793 """Returns a float of the number of seconds (not milliseconds) to wait after retrying, or None if unspecified.
794
795 About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
796 See also https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#syntax
797 """
798 if response_headers is None:
799 return None
800
801 # First, try the non-standard `retry-after-ms` header for milliseconds,
802 # which is more precise than integer-seconds `retry-after`
803 try:
804 retry_ms_header = response_headers.get("retry-after-ms", None)
805 return float(retry_ms_header) / 1000
806 except (TypeError, ValueError):
807 pass
808
809 # Next, try parsing `retry-after` header as seconds (allowing nonstandard floats).
810 retry_header = response_headers.get("retry-after")
811 try:
812 # note: the spec indicates that this should only ever be an integer
813 # but if someone sends a float there's no reason for us to not respect it
814 return float(retry_header)
815 except (TypeError, ValueError):
816 pass
817
818 # Last, try parsing `retry-after` as a date.
819 retry_date_tuple = email.utils.parsedate_tz(retry_header)
820 if retry_date_tuple is None:
821 return None
822
823 retry_date = email.utils.mktime_tz(retry_date_tuple)
824 return float(retry_date - time.time())
825
826 def _calculate_retry_timeout(
827 self,
828 remaining_retries: int,
829 options: FinalRequestOptions,
830 response_headers: Optional[httpx2.Headers] = None,
831 ) -> float:
832 max_retries = options.get_max_retries(self.max_retries)
833
834 # If the API asks us to wait a certain amount of time, just do what it says.
835 retry_after = self._parse_retry_after_header(response_headers)
836 if retry_after is not None and retry_after > 0:
837 # `time.sleep` raises above a platform limit, as low as 2**32 milliseconds on Windows,
838 # so wait at most that long.
839 return min(retry_after, 4_294_967.0)
840
841 # Also cap retry count to 1000 to avoid any potential overflows with `pow`
842 nb_retries = min(max_retries - remaining_retries, 1000)
843
844 # Apply exponential backoff, but not more than the max.
845 sleep_seconds = min(INITIAL_RETRY_DELAY * pow(2.0, nb_retries), MAX_RETRY_DELAY)
846
847 # Apply some jitter, plus-or-minus half a second.
848 jitter = 1 - 0.25 * random()
849 timeout = sleep_seconds * jitter
850 return timeout if timeout >= 0 else 0
851
852 def _should_retry(self, response: httpx2.Response) -> bool:
853 # Note: this is not a standard header
854 should_retry_header = response.headers.get("x-should-retry")
855
856 # If the server explicitly says whether or not to retry, obey.
857 if should_retry_header == "true":
858 log.debug("Retrying as header `x-should-retry` is set to `true`")
859 return True
860 if should_retry_header == "false":
861 log.debug("Not retrying as header `x-should-retry` is set to `false`")
862 return False
863
864 # Retry on request timeouts.
865 if response.status_code == 408:
866 log.debug("Retrying due to status code %i", response.status_code)
867 return True
868
869 # Retry on lock timeouts.
870 if response.status_code == 409:
871 log.debug("Retrying due to status code %i", response.status_code)
872 return True
873
874 # Retry on rate limits.
875 if response.status_code == 429:
876 log.debug("Retrying due to status code %i", response.status_code)
877 return True
878
879 # Retry internal errors.
880 if response.status_code >= 500:
881 log.debug("Retrying due to status code %i", response.status_code)
882 return True
883
884 log.debug("Not retrying")
885 return False
886
887 def _should_retry_exception(self, err: BaseException) -> tuple[bool, httpx2.Response | None]:
888 """Whether an exception raised by a request attempt should be retried.
889
890 Also returns the HTTP response behind the failure, when there is one, so
891 retry timing can honor `retry-after` headers.
892
893 Exceptions raised by middleware propagate to the caller as-is, except the
894 ones that opt into the retry policy by type: `APIStatusError` (subject to
895 the usual status-code policy), `APIConnectionError` / `APITimeoutError`,
896 and `RetryableError`. The check walks each error's `__cause__` chain, so
897 wrapping a retryable failure via `raise ... from err` preserves retries.
898 """
899 seen: set[int] = set()
900 current: BaseException | None = err
901 while current is not None and id(current) not in seen:
902 seen.add(id(current))
903 if isinstance(current, RetryableError):
904 return True, None
905 if isinstance(current, APIStatusError):
906 return self._should_retry(current.response), current.response
907 if isinstance(current, APIConnectionError):
908 return True, None
909 current = current.__cause__
910 return False, None
911
912 def _idempotency_key(self) -> str:
913 return f"stainless-python-retry-{uuid.uuid4()}"
914
915
916 class _DefaultHttpxClient(httpx2.Client):
917 def __init__(self, **kwargs: Any) -> None:
918 _reject_httpx_object("transport", kwargs.get("transport"))
919 kwargs.setdefault("timeout", DEFAULT_TIMEOUT)
920 kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS)
921 kwargs.setdefault("follow_redirects", True)
922
923 if "transport" not in kwargs:
924 socket_options: List[Tuple[int, int, Union[int, bool]]] = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, True)]
925
926 TCP_KEEPINTVL = getattr(socket, "TCP_KEEPINTVL", None)
927
928 if TCP_KEEPINTVL is not None:
929 socket_options.append((socket.IPPROTO_TCP, TCP_KEEPINTVL, 60))
930 elif sys.platform == "darwin":
931 TCP_KEEPALIVE = getattr(socket, "TCP_KEEPALIVE", 0x10)
932 socket_options.append((socket.IPPROTO_TCP, TCP_KEEPALIVE, 60))
933
934 TCP_KEEPCNT = getattr(socket, "TCP_KEEPCNT", None)
935 if TCP_KEEPCNT is not None:
936 socket_options.append((socket.IPPROTO_TCP, TCP_KEEPCNT, 5))
937
938 TCP_KEEPIDLE = getattr(socket, "TCP_KEEPIDLE", None)
939 if TCP_KEEPIDLE is not None:
940 socket_options.append((socket.IPPROTO_TCP, TCP_KEEPIDLE, 60))
941
942 proxy_map = {key: None if url is None else Proxy(url=url) for key, url in get_environment_proxies().items()}
943
944 transport_kwargs = {
945 arg: kwargs[arg] for arg in ("verify", "cert", "trust_env", "http1", "http2", "limits") if arg in kwargs
946 }
947
948 transport_kwargs["socket_options"] = socket_options
949
950 proxy_mounts = {
951 key: None if proxy is None else HTTPTransport(proxy=proxy, **transport_kwargs)
952 for key, proxy in proxy_map.items()
953 }
954 default_transport = HTTPTransport(**transport_kwargs)
955
956 # Prioritize the mounts set by the user over the environment variables.
957 proxy_mounts.update(kwargs.get("mounts", {}))
958 kwargs["mounts"] = proxy_mounts
959
960 # Sets the default transport so that HTTPX won't automatically configure proxies.
961 kwargs["transport"] = default_transport
962
963 super().__init__(**kwargs)
964
965
966 if TYPE_CHECKING:
967 DefaultHttpxClient = httpx2.Client
968 """An alias to `httpx2.Client` that provides the same defaults that this SDK
969 uses internally.
970
971 This is useful because overriding the `http_client` with your own instance of
972 `httpx2.Client` will result in httpx's defaults being used, not ours.
973 """
974 else:
975 DefaultHttpxClient = _DefaultHttpxClient
976
977
978 class SyncHttpxClientWrapper(DefaultHttpxClient):
979 def __del__(self) -> None:
980 if self.is_closed:
981 return
982
983 try:
984 self.close()
985 except Exception:
986 pass
987
988
989 class SyncAPIClient(BaseClient[httpx2.Client, Stream[Any]]):
990 _client: httpx2.Client
991 _default_stream_cls: type[Stream[Any]] | None = None
992 _middleware_chain: CallNext | None = None
993 webhook_key: str | None = None
994
995 def __init__(
996 self,
997 *,
998 version: str,
999 base_url: str | URL,
1000 max_retries: int = DEFAULT_MAX_RETRIES,
1001 timeout: float | Timeout | None | NotGiven = not_given,
1002 http_client: httpx2.Client | None = None,
1003 custom_headers: Mapping[str, str] | None = None,
1004 custom_query: Mapping[str, object] | None = None,
1005 middleware: Sequence[MiddlewareInput] | None = None,
1006 _strict_response_validation: bool,
1007 ) -> None:
1008 _reject_httpx_object("http_client", http_client)
1009
1010 if not is_given(timeout):
1011 # if the user passed in a custom http client with a non-default
1012 # timeout set then we use that timeout.
1013 #
1014 # note: there is an edge case here where the user passes in a client
1015 # where they've explicitly set the timeout to match the default timeout
1016 # as this check is structural, meaning that we'll think they didn't
1017 # pass in a timeout and will ignore it
1018 if http_client and http_client.timeout != HTTPX_DEFAULT_TIMEOUT:
1019 timeout = http_client.timeout
1020 else:
1021 timeout = DEFAULT_TIMEOUT
1022
1023 if http_client is not None and not isinstance(http_client, httpx2.Client): # pyright: ignore[reportUnnecessaryIsInstance]
1024 raise TypeError(
1025 f"Invalid `http_client` argument; Expected an instance of `httpx2.Client` but got {type(http_client)}"
1026 )
1027
1028 # materialize the middleware before validating it so that passing an
1029 # iterator/generator doesn't result in validation consuming it and the
1030 # middleware silently never running
1031 middleware = tuple(middleware or ())
1032 if middleware:
1033 validate_sync_middleware(middleware)
1034
1035 super().__init__(
1036 version=version,
1037 # cast to a valid type because mypy doesn't understand our type narrowing
1038 timeout=cast(Timeout, timeout),
1039 base_url=base_url,
1040 max_retries=max_retries,
1041 custom_query=custom_query,
1042 custom_headers=custom_headers,
1043 middleware=middleware,
1044 _strict_response_validation=_strict_response_validation,
1045 )
1046 self._middleware_chain = self._build_middleware_chain()
1047 self._client = http_client or SyncHttpxClientWrapper(
1048 base_url=base_url,
1049 # cast to a valid type because mypy doesn't understand our type narrowing
1050 timeout=cast(Timeout, timeout),
1051 )
1052
1053 def is_closed(self) -> bool:
1054 return self._client.is_closed
1055
1056 def close(self) -> None:
1057 """Close the underlying HTTPX client.
1058
1059 The client will *not* be usable after this.
1060 """
1061 # If an error is thrown while constructing a client, self._client
1062 # may not be present
1063 if hasattr(self, "_client"):
1064 self._client.close()
1065
1066 def __enter__(self: _T) -> _T:
1067 return self
1068
1069 def __exit__(
1070 self,
1071 exc_type: type[BaseException] | None,
1072 exc: BaseException | None,
1073 exc_tb: TracebackType | None,
1074 ) -> None:
1075 self.close()
1076
1077 def _prepare_options(
1078 self,
1079 options: FinalRequestOptions, # noqa: ARG002
1080 ) -> FinalRequestOptions:
1081 """Hook for mutating the given options"""
1082 return options
1083
1084 def _prepare_request(
1085 self,
1086 request: httpx2.Request, # noqa: ARG002
1087 ) -> None:
1088 """This method is used as a callback for mutating the `Request` object
1089 after it has been constructed.
1090 This is useful for cases where you want to add certain headers based off of
1091 the request properties, e.g. `url`, `method` etc.
1092 """
1093 return None
1094
1095 @overload
1096 def request(
1097 self,
1098 cast_to: Type[ResponseT],
1099 options: FinalRequestOptions,
1100 *,
1101 stream: Literal[True],
1102 stream_cls: Type[_StreamT],
1103 ) -> _StreamT: ...
1104
1105 @overload
1106 def request(
1107 self,
1108 cast_to: Type[ResponseT],
1109 options: FinalRequestOptions,
1110 *,
1111 stream: Literal[False] = False,
1112 ) -> ResponseT: ...
1113
1114 @overload
1115 def request(
1116 self,
1117 cast_to: Type[ResponseT],
1118 options: FinalRequestOptions,
1119 *,
1120 stream: bool = False,
1121 stream_cls: Type[_StreamT] | None = None,
1122 ) -> ResponseT | _StreamT: ...
1123
1124 def request(
1125 self,
1126 cast_to: Type[ResponseT],
1127 options: FinalRequestOptions,
1128 *,
1129 stream: bool = False,
1130 stream_cls: type[_StreamT] | None = None,
1131 ) -> ResponseT | _StreamT:
1132 cast_to = self._maybe_override_cast_to(cast_to, options)
1133
1134 # create a copy of the options we were given so that if the
1135 # options are mutated later & we then retry, the retries are
1136 # given the original options
1137 input_options = self._copy_and_prepare(options)
1138 if input_options.idempotency_key is None and input_options.method.lower() != "get":
1139 # ensure the idempotency key is reused between requests
1140 input_options.idempotency_key = self._idempotency_key()
1141
1142 chain = self._middleware_chain
1143 max_retries = input_options.get_max_retries(self.max_retries)
1144
1145 for retries_taken in range(max_retries + 1):
1146 remaining_retries = max_retries - retries_taken
1147
1148 try:
1149 if chain is None:
1150 response, prepared = self._attempt_request(
1151 model_copy(input_options), stream=stream, retries_taken=retries_taken
1152 )
1153 if response.is_success:
1154 return self._process_response(
1155 cast_to=cast_to,
1156 options=prepared,
1157 response=response,
1158 stream=stream,
1159 stream_cls=stream_cls,
1160 retries_taken=retries_taken,
1161 )
1162 else:
1163 request = APIRequest(
1164 options=model_copy(input_options),
1165 cast_to=cast_to,
1166 stream=stream,
1167 stream_cls=stream_cls,
1168 retries_taken=retries_taken,
1169 )
1170 result: Any = chain(request)
1171 if not isinstance(result, BaseAPIResponse) or result.http_response.is_success:
1172 return cast(Union[ResponseT, _StreamT], self._finalize_middleware_result(result, request))
1173 response = result.http_response
1174 except Exception as err:
1175 should_retry, failed_response = self._should_retry_exception(err)
1176 if remaining_retries <= 0 or not should_retry:
1177 raise
1178
1179 if failed_response is not None and not failed_response.is_closed:
1180 failed_response.close()
1181
1182 self._sleep_for_retry(
1183 retries_taken=retries_taken,
1184 max_retries=max_retries,
1185 options=input_options,
1186 response=failed_response,
1187 )
1188 continue
1189
1190 # the attempt produced an error-status response — possibly inspected,
1191 # replaced or passed through by middleware
1192 if remaining_retries > 0 and self._should_retry(response):
1193 if not response.is_closed:
1194 response.close()
1195 self._sleep_for_retry(
1196 retries_taken=retries_taken,
1197 max_retries=max_retries,
1198 options=input_options,
1199 response=response,
1200 )
1201 continue
1202
1203 # If the response is streamed then we need to explicitly read the response
1204 # to completion before attempting to access the response text.
1205 if not response.is_closed:
1206 response.read()
1207
1208 raise self._make_status_error_from_response(response) from None
1209
1210 raise RuntimeError("could not resolve response (should never happen)")
1211
1212 def _build_middleware_chain(self) -> CallNext | None:
1213 """Build the middleware invocation chain.
1214
1215 The chain only depends on the immutable `self._middleware` tuple so it is built
1216 once at construction time. It is invoked once per HTTP attempt, inside the
1217 SDK's retry loop, with that attempt's `APIRequest`.
1218 """
1219 if not self._middleware:
1220 return None
1221
1222 def base_handler(req: APIRequest) -> APIResponse[Any]:
1223 options = _prepare_middleware_options(req)
1224 response, prepared = self._attempt_request(options, stream=req.stream, retries_taken=req.retries_taken)
1225 return cast(
1226 "APIResponse[Any]",
1227 self._process_response(
1228 cast_to=req.cast_to,
1229 options=prepared,
1230 response=response,
1231 stream=req.stream,
1232 stream_cls=req.stream_cls,
1233 retries_taken=req.retries_taken,
1234 ),
1235 )
1236
1237 def wrap(middleware: MiddlewareInput, call_next: CallNext) -> CallNext:
1238 handler = middleware.handle if isinstance(middleware, Middleware) else cast(MiddlewareCallable, middleware)
1239
1240 def handle(req: APIRequest) -> APIResponse[Any]:
1241 return handler(req, call_next)
1242
1243 return handle
1244
1245 chain: CallNext = base_handler
1246 for entry in reversed(self._middleware):
1247 chain = wrap(entry, chain)
1248 return chain
1249
1250 def _finalize_middleware_result(self, result: Any, request: APIRequest) -> Any:
1251 """Convert the `APIResponse` returned by the middleware chain into the value the original caller expects.
1252
1253 The middleware chain operates on `APIResponse` objects; the original caller may
1254 have asked for a parsed model (the default) or for the `APIResponse` wrapper itself
1255 (`.with_raw_response` / `.with_streaming_response` / a `cast_to` that is itself a
1256 response class).
1257 """
1258 if not isinstance(result, BaseAPIResponse):
1259 # the middleware short-circuited with an already materialized value
1260 # (e.g. a cached model); hand it back verbatim
1261 return result
1262 response = cast("APIResponse[Any]", result)
1263
1264 if _middleware_entry_mode(request) is not None:
1265 # the original caller expects the `APIResponse` wrapper itself
1266 return response
1267
1268 if _expects_response_wrapper(request.cast_to):
1269 return response
1270
1271 return response.parse()
1272
1273 def _attempt_request(
1274 self,
1275 options: FinalRequestOptions,
1276 *,
1277 stream: bool = False,
1278 retries_taken: int = 0,
1279 ) -> tuple[httpx2.Response, FinalRequestOptions]:
1280 """Prepare, build and send a single HTTP attempt.
1281
1282 Returns the response regardless of its status code, along with the prepared
1283 options it was sent with — status handling (the retry policy, raising typed
1284 errors for the caller) happens above, where middleware can inspect error
1285 responses first. Connection failures raise typed errors (`APITimeoutError`,
1286 `APIConnectionError`).
1287 """
1288 options = self._prepare_options(options)
1289
1290 request = self._build_request(options, retries_taken=retries_taken)
1291 self._prepare_request(request)
1292
1293 kwargs: HttpxSendArgs = {}
1294 if self.custom_auth is not None:
1295 kwargs["auth"] = self.custom_auth
1296
1297 if options.follow_redirects is not None:
1298 kwargs["follow_redirects"] = options.follow_redirects
1299
1300 log.debug("Sending HTTP Request: %s %s", request.method, request.url)
1301
1302 try:
1303 response = self._client.send(
1304 request,
1305 stream=stream or self._should_stream_response_body(request=request),
1306 **kwargs,
1307 )
1308 except httpx2.TimeoutException as err:
1309 log.debug("Encountered httpx2.TimeoutException", exc_info=True)
1310 raise APITimeoutError(request=request) from err
1311 except Exception as err:
1312 if isinstance(err, AnthropicError):
1313 # SDK-originated errors already carry their own type; don't wrap.
1314 raise
1315
1316 log.debug("Encountered Exception", exc_info=True)
1317 raise APIConnectionError(request=request) from err
1318
1319 log.debug(
1320 'HTTP Response: %s %s "%i %s" %s',
1321 request.method,
1322 request.url,
1323 response.status_code,
1324 response.reason_phrase,
1325 response.headers,
1326 )
1327 log.debug("request_id: %s", response.headers.get("request-id"))
1328 log.debug("workspace_id: %s", response.headers.get("anthropic-workspace-id"))
1329
1330 return response, options
1331
1332 def _copy_and_prepare(self, options: FinalRequestOptions) -> FinalRequestOptions:
1333 """A copy of `options` with `extra_body` merged into the body, and the body and query prepared.
1334
1335 The data is walked once per request, before the retry loop, as it may hold one-shot iterators
1336 and file reads, which a retry cannot repeat. A GET sends no body, so its data is not read at all.
1337 """
1338 options = model_copy(options)
1339 if options.method.lower() != "get":
1340 _merge_extra_json(options)
1341 options.json_data = prepare_request_data(options.json_data, location="body")
1342
1343 if options.params:
1344 options.params = prepare_request_data(options.params, location="query", keep_top_level_omit=True)
1345
1346 return options
1347
1348 def _sleep_for_retry(
1349 self, *, retries_taken: int, max_retries: int, options: FinalRequestOptions, response: httpx2.Response | None
1350 ) -> None:
1351 remaining_retries = max_retries - retries_taken
1352 if remaining_retries == 1:
1353 log.debug("1 retry left")
1354 else:
1355 log.debug("%i retries left", remaining_retries)
1356
1357 timeout = self._calculate_retry_timeout(remaining_retries, options, response.headers if response else None)
1358 log.info("Retrying request to %s in %f seconds", options.url, timeout)
1359
1360 time.sleep(timeout)
1361
1362 def _process_response(
1363 self,
1364 *,
1365 cast_to: Type[ResponseT],
1366 options: FinalRequestOptions,
1367 response: httpx2.Response,
1368 stream: bool,
1369 stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None,
1370 retries_taken: int = 0,
1371 ) -> ResponseT:
1372 origin = get_origin(cast_to) or cast_to
1373
1374 if (
1375 inspect.isclass(origin)
1376 and issubclass(origin, BaseAPIResponse)
1377 # we only want to actually return the custom BaseAPIResponse class if we're
1378 # returning the raw response, or if we're not streaming SSE, as if we're streaming
1379 # SSE then `cast_to` doesn't actively reflect the type we need to parse into
1380 and (not stream or bool(response.request.headers.get(RAW_RESPONSE_HEADER)))
1381 ):
1382 if not issubclass(origin, APIResponse):
1383 raise TypeError(f"API Response types must subclass {APIResponse}; Received {origin}")
1384
1385 response_cls = cast("type[BaseAPIResponse[Any]]", cast_to)
1386 return cast(
1387 ResponseT,
1388 response_cls(
1389 raw=response,
1390 client=self,
1391 cast_to=extract_response_type(response_cls),
1392 stream=stream,
1393 stream_cls=stream_cls,
1394 options=options,
1395 retries_taken=retries_taken,
1396 ),
1397 )
1398
1399 if cast_to == httpx2.Response:
1400 return cast(ResponseT, response)
1401
1402 api_response = APIResponse(
1403 raw=response,
1404 client=self,
1405 cast_to=cast("type[ResponseT]", cast_to), # pyright: ignore[reportUnnecessaryCast]
1406 stream=stream,
1407 stream_cls=stream_cls,
1408 options=options,
1409 retries_taken=retries_taken,
1410 )
1411 if bool(response.request.headers.get(RAW_RESPONSE_HEADER)):
1412 return cast(ResponseT, api_response)
1413
1414 return api_response.parse()
1415
1416 def _request_api_list(
1417 self,
1418 model: Type[object],
1419 page: Type[SyncPageT],
1420 options: FinalRequestOptions,
1421 ) -> SyncPageT:
1422 # the page sends its options again for the next page, so it has to keep the prepared ones
1423 options = self._copy_and_prepare(options)
1424
1425 def _parser(resp: SyncPageT) -> SyncPageT:
1426 resp._set_private_attributes(
1427 client=self,
1428 model=model,
1429 options=options,
1430 )
1431 return resp
1432
1433 options.post_parser = _parser
1434
1435 return self.request(page, options, stream=False)
1436
1437 @overload
1438 def get(
1439 self,
1440 path: str,
1441 *,
1442 cast_to: Type[ResponseT],
1443 options: RequestOptions = {},
1444 stream: Literal[False] = False,
1445 ) -> ResponseT: ...
1446
1447 @overload
1448 def get(
1449 self,
1450 path: str,
1451 *,
1452 cast_to: Type[ResponseT],
1453 options: RequestOptions = {},
1454 stream: Literal[True],
1455 stream_cls: type[_StreamT],
1456 ) -> _StreamT: ...
1457
1458 @overload
1459 def get(
1460 self,
1461 path: str,
1462 *,
1463 cast_to: Type[ResponseT],
1464 options: RequestOptions = {},
1465 stream: bool,
1466 stream_cls: type[_StreamT] | None = None,
1467 ) -> ResponseT | _StreamT: ...
1468
1469 def get(
1470 self,
1471 path: str,
1472 *,
1473 cast_to: Type[ResponseT],
1474 options: RequestOptions = {},
1475 stream: bool = False,
1476 stream_cls: type[_StreamT] | None = None,
1477 ) -> ResponseT | _StreamT:
1478 opts = FinalRequestOptions.construct(method="get", url=path, **options)
1479 # cast is required because mypy complains about returning Any even though
1480 # it understands the type variables
1481 return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls))
1482
1483 @overload
1484 def post(
1485 self,
1486 path: str,
1487 *,
1488 cast_to: Type[ResponseT],
1489 body: Body | None = None,
1490 content: BinaryTypes | None = None,
1491 options: RequestOptions = {},
1492 files: RequestFiles | None = None,
1493 stream: Literal[False] = False,
1494 ) -> ResponseT: ...
1495
1496 @overload
1497 def post(
1498 self,
1499 path: str,
1500 *,
1501 cast_to: Type[ResponseT],
1502 body: Body | None = None,
1503 content: BinaryTypes | None = None,
1504 options: RequestOptions = {},
1505 files: RequestFiles | None = None,
1506 stream: Literal[True],
1507 stream_cls: type[_StreamT],
1508 ) -> _StreamT: ...
1509
1510 @overload
1511 def post(
1512 self,
1513 path: str,
1514 *,
1515 cast_to: Type[ResponseT],
1516 body: Body | None = None,
1517 content: BinaryTypes | None = None,
1518 options: RequestOptions = {},
1519 files: RequestFiles | None = None,
1520 stream: bool,
1521 stream_cls: type[_StreamT] | None = None,
1522 ) -> ResponseT | _StreamT: ...
1523
1524 def post(
1525 self,
1526 path: str,
1527 *,
1528 cast_to: Type[ResponseT],
1529 body: Body | None = None,
1530 content: BinaryTypes | None = None,
1531 options: RequestOptions = {},
1532 files: RequestFiles | None = None,
1533 stream: bool = False,
1534 stream_cls: type[_StreamT] | None = None,
1535 ) -> ResponseT | _StreamT:
1536 if body is not None and content is not None:
1537 raise TypeError("Passing both `body` and `content` is not supported")
1538 if files is not None and content is not None:
1539 raise TypeError("Passing both `files` and `content` is not supported")
1540 opts = FinalRequestOptions.construct(
1541 method="post", url=path, json_data=body, content=content, files=to_httpx_files(files), **options
1542 )
1543 return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls))
1544
1545 def patch(
1546 self,
1547 path: str,
1548 *,
1549 cast_to: Type[ResponseT],
1550 body: Body | None = None,
1551 content: BinaryTypes | None = None,
1552 files: RequestFiles | None = None,
1553 options: RequestOptions = {},
1554 ) -> ResponseT:
1555 if body is not None and content is not None:
1556 raise TypeError("Passing both `body` and `content` is not supported")
1557 if files is not None and content is not None:
1558 raise TypeError("Passing both `files` and `content` is not supported")
1559 opts = FinalRequestOptions.construct(
1560 method="patch", url=path, json_data=body, content=content, files=to_httpx_files(files), **options
1561 )
1562 return self.request(cast_to, opts)
1563
1564 def put(
1565 self,
1566 path: str,
1567 *,
1568 cast_to: Type[ResponseT],
1569 body: Body | None = None,
1570 content: BinaryTypes | None = None,
1571 files: RequestFiles | None = None,
1572 options: RequestOptions = {},
1573 ) -> ResponseT:
1574 if body is not None and content is not None:
1575 raise TypeError("Passing both `body` and `content` is not supported")
1576 if files is not None and content is not None:
1577 raise TypeError("Passing both `files` and `content` is not supported")
1578 opts = FinalRequestOptions.construct(
1579 method="put", url=path, json_data=body, content=content, files=to_httpx_files(files), **options
1580 )
1581 return self.request(cast_to, opts)
1582
1583 def delete(
1584 self,
1585 path: str,
1586 *,
1587 cast_to: Type[ResponseT],
1588 body: Body | None = None,
1589 content: BinaryTypes | None = None,
1590 options: RequestOptions = {},
1591 ) -> ResponseT:
1592 if body is not None and content is not None:
1593 raise TypeError("Passing both `body` and `content` is not supported")
1594 opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, content=content, **options)
1595 return self.request(cast_to, opts)
1596
1597 def get_api_list(
1598 self,
1599 path: str,
1600 *,
1601 model: Type[object],
1602 page: Type[SyncPageT],
1603 body: Body | None = None,
1604 options: RequestOptions = {},
1605 method: str = "get",
1606 ) -> SyncPageT:
1607 opts = FinalRequestOptions.construct(method=method, url=path, json_data=body, **options)
1608 return self._request_api_list(model, page, opts)
1609
1610
1611 class _DefaultAsyncHttpxClient(httpx2.AsyncClient):
1612 def __init__(self, **kwargs: Any) -> None:
1613 _reject_httpx_object("transport", kwargs.get("transport"))
1614 kwargs.setdefault("timeout", DEFAULT_TIMEOUT)
1615 kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS)
1616 kwargs.setdefault("follow_redirects", True)
1617
1618 if "transport" not in kwargs:
1619 socket_options: List[Tuple[int, int, Union[int, bool]]] = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, True)]
1620
1621 TCP_KEEPINTVL = getattr(socket, "TCP_KEEPINTVL", None)
1622
1623 if TCP_KEEPINTVL is not None:
1624 socket_options.append((socket.IPPROTO_TCP, TCP_KEEPINTVL, 60))
1625 elif sys.platform == "darwin":
1626 TCP_KEEPALIVE = getattr(socket, "TCP_KEEPALIVE", 0x10)
1627 socket_options.append((socket.IPPROTO_TCP, TCP_KEEPALIVE, 60))
1628
1629 TCP_KEEPCNT = getattr(socket, "TCP_KEEPCNT", None)
1630 if TCP_KEEPCNT is not None:
1631 socket_options.append((socket.IPPROTO_TCP, TCP_KEEPCNT, 5))
1632
1633 TCP_KEEPIDLE = getattr(socket, "TCP_KEEPIDLE", None)
1634 if TCP_KEEPIDLE is not None:
1635 socket_options.append((socket.IPPROTO_TCP, TCP_KEEPIDLE, 60))
1636
1637 proxy_map = {key: None if url is None else Proxy(url=url) for key, url in get_environment_proxies().items()}
1638
1639 transport_kwargs = {
1640 arg: kwargs[arg] for arg in ("verify", "cert", "trust_env", "http1", "http2", "limits") if arg in kwargs
1641 }
1642
1643 transport_kwargs["socket_options"] = socket_options
1644
1645 proxy_mounts = {
1646 key: None if proxy is None else AsyncHTTPTransport(proxy=proxy, **transport_kwargs)
1647 for key, proxy in proxy_map.items()
1648 }
1649 default_transport = AsyncHTTPTransport(**transport_kwargs)
1650
1651 # Prioritize the mounts set by the user over the environment variables.
1652 proxy_mounts.update(kwargs.get("mounts", {}))
1653 kwargs["mounts"] = proxy_mounts
1654
1655 # Sets the default transport so that HTTPX won't automatically configure proxies.
1656 kwargs["transport"] = default_transport
1657
1658 super().__init__(**kwargs)
1659
1660
1661 try:
1662 from ._vendor import httpx_aiohttp
1663 except (ImportError, AttributeError):
1664
1665 class _DefaultAioHttpClient(httpx2.AsyncClient):
1666 def __init__(self, **_kwargs: Any) -> None:
1667 raise RuntimeError("To use the aiohttp client you must have installed the package with the `aiohttp` extra")
1668 else:
1669
1670 class _DefaultAioHttpClient(httpx_aiohttp.Httpx2AiohttpClient): # type: ignore
1671 def __init__(self, **kwargs: Any) -> None:
1672 kwargs.setdefault("timeout", DEFAULT_TIMEOUT)
1673 kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS)
1674 kwargs.setdefault("follow_redirects", True)
1675
1676 super().__init__(**kwargs)
1677
1678
1679 if TYPE_CHECKING:
1680 DefaultAsyncHttpxClient = httpx2.AsyncClient
1681 """An alias to `httpx2.AsyncClient` that provides the same defaults that this SDK
1682 uses internally.
1683
1684 This is useful because overriding the `http_client` with your own instance of
1685 `httpx2.AsyncClient` will result in httpx's defaults being used, not ours.
1686 """
1687
1688 DefaultAioHttpClient = httpx2.AsyncClient
1689 """An alias to `httpx2.AsyncClient` that changes the default HTTP transport to `aiohttp`."""
1690 else:
1691 DefaultAsyncHttpxClient = _DefaultAsyncHttpxClient
1692 DefaultAioHttpClient = _DefaultAioHttpClient
1693
1694
1695 class AsyncHttpxClientWrapper(DefaultAsyncHttpxClient):
1696 def __del__(self) -> None:
1697 if self.is_closed:
1698 return
1699
1700 try:
1701 # TODO(someday): support non asyncio runtimes here
1702 asyncio.get_running_loop().create_task(self.aclose())
1703 except Exception:
1704 pass
1705
1706
1707 class AsyncAPIClient(BaseClient[httpx2.AsyncClient, AsyncStream[Any]]):
1708 _client: httpx2.AsyncClient
1709 _default_stream_cls: type[AsyncStream[Any]] | None = None
1710 _middleware_chain: AsyncCallNext | None = None
1711 webhook_key: str | None = None
1712
1713 def __init__(
1714 self,
1715 *,
1716 version: str,
1717 base_url: str | URL,
1718 _strict_response_validation: bool,
1719 max_retries: int = DEFAULT_MAX_RETRIES,
1720 timeout: float | Timeout | None | NotGiven = not_given,
1721 http_client: httpx2.AsyncClient | None = None,
1722 custom_headers: Mapping[str, str] | None = None,
1723 custom_query: Mapping[str, object] | None = None,
1724 middleware: Sequence[MiddlewareInput] | None = None,
1725 ) -> None:
1726 _reject_httpx_object("http_client", http_client)
1727
1728 if not is_given(timeout):
1729 # if the user passed in a custom http client with a non-default
1730 # timeout set then we use that timeout.
1731 #
1732 # note: there is an edge case here where the user passes in a client
1733 # where they've explicitly set the timeout to match the default timeout
1734 # as this check is structural, meaning that we'll think they didn't
1735 # pass in a timeout and will ignore it
1736 if http_client and http_client.timeout != HTTPX_DEFAULT_TIMEOUT:
1737 timeout = http_client.timeout
1738 else:
1739 timeout = DEFAULT_TIMEOUT
1740
1741 if http_client is not None and not isinstance(http_client, httpx2.AsyncClient): # pyright: ignore[reportUnnecessaryIsInstance]
1742 raise TypeError(
1743 f"Invalid `http_client` argument; Expected an instance of `httpx2.AsyncClient` but got {type(http_client)}"
1744 )
1745
1746 # materialize the middleware before validating it so that passing an
1747 # iterator/generator doesn't result in validation consuming it and the
1748 # middleware silently never running
1749 middleware = tuple(middleware or ())
1750 if middleware:
1751 validate_async_middleware(middleware)
1752
1753 super().__init__(
1754 version=version,
1755 base_url=base_url,
1756 # cast to a valid type because mypy doesn't understand our type narrowing
1757 timeout=cast(Timeout, timeout),
1758 max_retries=max_retries,
1759 custom_query=custom_query,
1760 custom_headers=custom_headers,
1761 middleware=middleware,
1762 _strict_response_validation=_strict_response_validation,
1763 )
1764 self._middleware_chain = self._build_middleware_chain()
1765 self._client = http_client or AsyncHttpxClientWrapper(
1766 base_url=base_url,
1767 # cast to a valid type because mypy doesn't understand our type narrowing
1768 timeout=cast(Timeout, timeout),
1769 )
1770
1771 def is_closed(self) -> bool:
1772 return self._client.is_closed
1773
1774 async def close(self) -> None:
1775 """Close the underlying HTTPX client.
1776
1777 The client will *not* be usable after this.
1778 """
1779 await self._client.aclose()
1780
1781 async def __aenter__(self: _T) -> _T:
1782 return self
1783
1784 async def __aexit__(
1785 self,
1786 exc_type: type[BaseException] | None,
1787 exc: BaseException | None,
1788 exc_tb: TracebackType | None,
1789 ) -> None:
1790 await self.close()
1791
1792 async def _prepare_options(
1793 self,
1794 options: FinalRequestOptions, # noqa: ARG002
1795 ) -> FinalRequestOptions:
1796 """Hook for mutating the given options"""
1797 return options
1798
1799 async def _prepare_request(
1800 self,
1801 request: httpx2.Request, # noqa: ARG002
1802 ) -> None:
1803 """This method is used as a callback for mutating the `Request` object
1804 after it has been constructed.
1805 This is useful for cases where you want to add certain headers based off of
1806 the request properties, e.g. `url`, `method` etc.
1807 """
1808 return None
1809
1810 @overload
1811 async def request(
1812 self,
1813 cast_to: Type[ResponseT],
1814 options: FinalRequestOptions,
1815 *,
1816 stream: Literal[False] = False,
1817 ) -> ResponseT: ...
1818
1819 @overload
1820 async def request(
1821 self,
1822 cast_to: Type[ResponseT],
1823 options: FinalRequestOptions,
1824 *,
1825 stream: Literal[True],
1826 stream_cls: type[_AsyncStreamT],
1827 ) -> _AsyncStreamT: ...
1828
1829 @overload
1830 async def request(
1831 self,
1832 cast_to: Type[ResponseT],
1833 options: FinalRequestOptions,
1834 *,
1835 stream: bool,
1836 stream_cls: type[_AsyncStreamT] | None = None,
1837 ) -> ResponseT | _AsyncStreamT: ...
1838
1839 async def request(
1840 self,
1841 cast_to: Type[ResponseT],
1842 options: FinalRequestOptions,
1843 *,
1844 stream: bool = False,
1845 stream_cls: type[_AsyncStreamT] | None = None,
1846 ) -> ResponseT | _AsyncStreamT:
1847 if self._platform is None:
1848 # `get_platform()` may block (e.g. `platform.uname()` runs a WMI query on Windows),
1849 # so resolve it in a worker thread rather than on the event loop
1850 self._platform = await asyncify(get_platform)()
1851
1852 cast_to = self._maybe_override_cast_to(cast_to, options)
1853
1854 # create a copy of the options we were given so that if the
1855 # options are mutated later & we then retry, the retries are
1856 # given the original options
1857 input_options = await self._copy_and_prepare(options)
1858 if input_options.idempotency_key is None and input_options.method.lower() != "get":
1859 # ensure the idempotency key is reused between requests
1860 input_options.idempotency_key = self._idempotency_key()
1861
1862 chain = self._middleware_chain
1863 max_retries = input_options.get_max_retries(self.max_retries)
1864
1865 for retries_taken in range(max_retries + 1):
1866 remaining_retries = max_retries - retries_taken
1867
1868 try:
1869 if chain is None:
1870 response, prepared = await self._attempt_request(
1871 model_copy(input_options), stream=stream, retries_taken=retries_taken
1872 )
1873 if response.is_success:
1874 return await self._process_response(
1875 cast_to=cast_to,
1876 options=prepared,
1877 response=response,
1878 stream=stream,
1879 stream_cls=stream_cls,
1880 retries_taken=retries_taken,
1881 )
1882 else:
1883 request = APIRequest(
1884 options=model_copy(input_options),
1885 cast_to=cast_to,
1886 stream=stream,
1887 stream_cls=stream_cls,
1888 retries_taken=retries_taken,
1889 )
1890 result: Any = await chain(request)
1891 if not isinstance(result, BaseAPIResponse) or result.http_response.is_success:
1892 return cast(
1893 Union[ResponseT, _AsyncStreamT], await self._finalize_middleware_result(result, request)
1894 )
1895 response = result.http_response
1896 except Exception as err:
1897 should_retry, failed_response = self._should_retry_exception(err)
1898 if remaining_retries <= 0 or not should_retry:
1899 raise
1900
1901 if failed_response is not None and not failed_response.is_closed:
1902 await failed_response.aclose()
1903
1904 await self._sleep_for_retry(
1905 retries_taken=retries_taken,
1906 max_retries=max_retries,
1907 options=input_options,
1908 response=failed_response,
1909 )
1910 continue
1911
1912 # the attempt produced an error-status response — possibly inspected,
1913 # replaced or passed through by middleware
1914 if remaining_retries > 0 and self._should_retry(response):
1915 if not response.is_closed:
1916 await response.aclose()
1917 await self._sleep_for_retry(
1918 retries_taken=retries_taken,
1919 max_retries=max_retries,
1920 options=input_options,
1921 response=response,
1922 )
1923 continue
1924
1925 # If the response is streamed then we need to explicitly read the response
1926 # to completion before attempting to access the response text.
1927 if not response.is_closed:
1928 await response.aread()
1929
1930 raise self._make_status_error_from_response(response) from None
1931
1932 raise RuntimeError("could not resolve response (should never happen)")
1933
1934 def _build_middleware_chain(self) -> AsyncCallNext | None:
1935 """Build the middleware invocation chain.
1936
1937 The chain only depends on the immutable `self._middleware` tuple so it is built
1938 once at construction time. It is invoked once per HTTP attempt, inside the
1939 SDK's retry loop, with that attempt's `APIRequest`.
1940 """
1941 if not self._middleware:
1942 return None
1943
1944 async def base_handler(req: APIRequest) -> AsyncAPIResponse[Any]:
1945 options = _prepare_middleware_options(req)
1946 response, prepared = await self._attempt_request(
1947 options, stream=req.stream, retries_taken=req.retries_taken
1948 )
1949 return cast(
1950 "AsyncAPIResponse[Any]",
1951 await self._process_response(
1952 cast_to=req.cast_to,
1953 options=prepared,
1954 response=response,
1955 stream=req.stream,
1956 stream_cls=req.stream_cls,
1957 retries_taken=req.retries_taken,
1958 ),
1959 )
1960
1961 def wrap(middleware: MiddlewareInput, call_next: AsyncCallNext) -> AsyncCallNext:
1962 handler = (
1963 middleware.handle_async
1964 if isinstance(middleware, Middleware)
1965 else cast(AsyncMiddlewareCallable, middleware)
1966 )
1967
1968 async def handle(req: APIRequest) -> AsyncAPIResponse[Any]:
1969 return await handler(req, call_next)
1970
1971 return handle
1972
1973 chain: AsyncCallNext = base_handler
1974 for entry in reversed(self._middleware):
1975 chain = wrap(entry, chain)
1976 return chain
1977
1978 async def _finalize_middleware_result(self, result: Any, request: APIRequest) -> Any:
1979 """Convert the `AsyncAPIResponse` returned by the middleware chain into the value the original caller expects.
1980
1981 The middleware chain operates on `AsyncAPIResponse` objects; the original caller
1982 may have asked for a parsed model (the default) or for the `AsyncAPIResponse` wrapper
1983 itself (`.with_raw_response` / `.with_streaming_response` / a `cast_to` that is itself
1984 a response class).
1985 """
1986 if not isinstance(result, BaseAPIResponse):
1987 # the middleware short-circuited with an already materialized value
1988 # (e.g. a cached model); hand it back verbatim
1989 return result
1990 response = cast("AsyncAPIResponse[Any]", result)
1991
1992 if _middleware_entry_mode(request) is not None:
1993 # the original caller expects the `AsyncAPIResponse` wrapper itself
1994 return response
1995
1996 if _expects_response_wrapper(request.cast_to):
1997 return response
1998
1999 return await response.parse()
2000
2001 async def _attempt_request(
2002 self,
2003 options: FinalRequestOptions,
2004 *,
2005 stream: bool = False,
2006 retries_taken: int = 0,
2007 ) -> tuple[httpx2.Response, FinalRequestOptions]:
2008 """Prepare, build and send a single HTTP attempt.
2009
2010 Returns the response regardless of its status code, along with the prepared
2011 options it was sent with — status handling (the retry policy, raising typed
2012 errors for the caller) happens above, where middleware can inspect error
2013 responses first. Connection failures raise typed errors (`APITimeoutError`,
2014 `APIConnectionError`).
2015 """
2016 options = await self._prepare_options(options)
2017
2018 request = self._build_request(options, retries_taken=retries_taken)
2019 await self._prepare_request(request)
2020
2021 kwargs: HttpxSendArgs = {}
2022 if self.custom_auth is not None:
2023 kwargs["auth"] = self.custom_auth
2024
2025 if options.follow_redirects is not None:
2026 kwargs["follow_redirects"] = options.follow_redirects
2027
2028 log.debug("Sending HTTP Request: %s %s", request.method, request.url)
2029
2030 try:
2031 response = await self._client.send(
2032 request,
2033 stream=stream or self._should_stream_response_body(request=request),
2034 **kwargs,
2035 )
2036 except httpx2.TimeoutException as err:
2037 log.debug("Encountered httpx2.TimeoutException", exc_info=True)
2038 raise APITimeoutError(request=request) from err
2039 except Exception as err:
2040 if isinstance(err, AnthropicError):
2041 # SDK-originated errors already carry their own type; don't wrap.
2042 raise
2043
2044 log.debug("Encountered Exception", exc_info=True)
2045 raise APIConnectionError(request=request) from err
2046
2047 log.debug(
2048 'HTTP Response: %s %s "%i %s" %s',
2049 request.method,
2050 request.url,
2051 response.status_code,
2052 response.reason_phrase,
2053 response.headers,
2054 )
2055 log.debug("request_id: %s", response.headers.get("request-id"))
2056 log.debug("workspace_id: %s", response.headers.get("anthropic-workspace-id"))
2057
2058 return response, options
2059
2060 async def _copy_and_prepare(self, options: FinalRequestOptions) -> FinalRequestOptions:
2061 """A copy of `options` with `extra_body` merged into the body, and the body and query prepared.
2062
2063 The data is walked once per request, before the retry loop, as it may hold one-shot iterators
2064 and file reads, which a retry cannot repeat. A GET sends no body, so its data is not read at all.
2065 """
2066 options = model_copy(options)
2067 if options.method.lower() != "get":
2068 _merge_extra_json(options)
2069 options.json_data = await async_prepare_request_data(options.json_data, location="body")
2070
2071 if options.params:
2072 options.params = await async_prepare_request_data(
2073 options.params, location="query", keep_top_level_omit=True
2074 )
2075
2076 return options
2077
2078 async def _sleep_for_retry(
2079 self, *, retries_taken: int, max_retries: int, options: FinalRequestOptions, response: httpx2.Response | None
2080 ) -> None:
2081 remaining_retries = max_retries - retries_taken
2082 if remaining_retries == 1:
2083 log.debug("1 retry left")
2084 else:
2085 log.debug("%i retries left", remaining_retries)
2086
2087 timeout = self._calculate_retry_timeout(remaining_retries, options, response.headers if response else None)
2088 log.info("Retrying request to %s in %f seconds", options.url, timeout)
2089
2090 await anyio.sleep(timeout)
2091
2092 async def _process_response(
2093 self,
2094 *,
2095 cast_to: Type[ResponseT],
2096 options: FinalRequestOptions,
2097 response: httpx2.Response,
2098 stream: bool,
2099 stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None,
2100 retries_taken: int = 0,
2101 ) -> ResponseT:
2102 origin = get_origin(cast_to) or cast_to
2103
2104 if (
2105 inspect.isclass(origin)
2106 and issubclass(origin, BaseAPIResponse)
2107 # we only want to actually return the custom BaseAPIResponse class if we're
2108 # returning the raw response, or if we're not streaming SSE, as if we're streaming
2109 # SSE then `cast_to` doesn't actively reflect the type we need to parse into
2110 and (not stream or bool(response.request.headers.get(RAW_RESPONSE_HEADER)))
2111 ):
2112 if not issubclass(origin, AsyncAPIResponse):
2113 raise TypeError(f"API Response types must subclass {AsyncAPIResponse}; Received {origin}")
2114
2115 response_cls = cast("type[BaseAPIResponse[Any]]", cast_to)
2116 return cast(
2117 "ResponseT",
2118 response_cls(
2119 raw=response,
2120 client=self,
2121 cast_to=extract_response_type(response_cls),
2122 stream=stream,
2123 stream_cls=stream_cls,
2124 options=options,
2125 retries_taken=retries_taken,
2126 ),
2127 )
2128
2129 if cast_to == httpx2.Response:
2130 return cast(ResponseT, response)
2131
2132 api_response = AsyncAPIResponse(
2133 raw=response,
2134 client=self,
2135 cast_to=cast("type[ResponseT]", cast_to), # pyright: ignore[reportUnnecessaryCast]
2136 stream=stream,
2137 stream_cls=stream_cls,
2138 options=options,
2139 retries_taken=retries_taken,
2140 )
2141 if bool(response.request.headers.get(RAW_RESPONSE_HEADER)):
2142 return cast(ResponseT, api_response)
2143
2144 return await api_response.parse()
2145
2146 def _request_api_list(
2147 self,
2148 model: Type[_T],
2149 page: Type[AsyncPageT],
2150 options: FinalRequestOptions,
2151 ) -> AsyncPaginator[_T, AsyncPageT]:
2152 return AsyncPaginator(client=self, options=options, page_cls=page, model=model)
2153
2154 @overload
2155 async def get(
2156 self,
2157 path: str,
2158 *,
2159 cast_to: Type[ResponseT],
2160 options: RequestOptions = {},
2161 stream: Literal[False] = False,
2162 ) -> ResponseT: ...
2163
2164 @overload
2165 async def get(
2166 self,
2167 path: str,
2168 *,
2169 cast_to: Type[ResponseT],
2170 options: RequestOptions = {},
2171 stream: Literal[True],
2172 stream_cls: type[_AsyncStreamT],
2173 ) -> _AsyncStreamT: ...
2174
2175 @overload
2176 async def get(
2177 self,
2178 path: str,
2179 *,
2180 cast_to: Type[ResponseT],
2181 options: RequestOptions = {},
2182 stream: bool,
2183 stream_cls: type[_AsyncStreamT] | None = None,
2184 ) -> ResponseT | _AsyncStreamT: ...
2185
2186 async def get(
2187 self,
2188 path: str,
2189 *,
2190 cast_to: Type[ResponseT],
2191 options: RequestOptions = {},
2192 stream: bool = False,
2193 stream_cls: type[_AsyncStreamT] | None = None,
2194 ) -> ResponseT | _AsyncStreamT:
2195 opts = FinalRequestOptions.construct(method="get", url=path, **options)
2196 return await self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)
2197
2198 @overload
2199 async def post(
2200 self,
2201 path: str,
2202 *,
2203 cast_to: Type[ResponseT],
2204 body: Body | None = None,
2205 content: AsyncBinaryTypes | None = None,
2206 files: RequestFiles | None = None,
2207 options: RequestOptions = {},
2208 stream: Literal[False] = False,
2209 ) -> ResponseT: ...
2210
2211 @overload
2212 async def post(
2213 self,
2214 path: str,
2215 *,
2216 cast_to: Type[ResponseT],
2217 body: Body | None = None,
2218 content: AsyncBinaryTypes | None = None,
2219 files: RequestFiles | None = None,
2220 options: RequestOptions = {},
2221 stream: Literal[True],
2222 stream_cls: type[_AsyncStreamT],
2223 ) -> _AsyncStreamT: ...
2224
2225 @overload
2226 async def post(
2227 self,
2228 path: str,
2229 *,
2230 cast_to: Type[ResponseT],
2231 body: Body | None = None,
2232 content: AsyncBinaryTypes | None = None,
2233 files: RequestFiles | None = None,
2234 options: RequestOptions = {},
2235 stream: bool,
2236 stream_cls: type[_AsyncStreamT] | None = None,
2237 ) -> ResponseT | _AsyncStreamT: ...
2238
2239 async def post(
2240 self,
2241 path: str,
2242 *,
2243 cast_to: Type[ResponseT],
2244 body: Body | None = None,
2245 content: AsyncBinaryTypes | None = None,
2246 files: RequestFiles | None = None,
2247 options: RequestOptions = {},
2248 stream: bool = False,
2249 stream_cls: type[_AsyncStreamT] | None = None,
2250 ) -> ResponseT | _AsyncStreamT:
2251 if body is not None and content is not None:
2252 raise TypeError("Passing both `body` and `content` is not supported")
2253 if files is not None and content is not None:
2254 raise TypeError("Passing both `files` and `content` is not supported")
2255 opts = FinalRequestOptions.construct(
2256 method="post", url=path, json_data=body, content=content, files=await async_to_httpx_files(files), **options
2257 )
2258 return await self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)
2259
2260 async def patch(
2261 self,
2262 path: str,
2263 *,
2264 cast_to: Type[ResponseT],
2265 body: Body | None = None,
2266 content: AsyncBinaryTypes | None = None,
2267 files: RequestFiles | None = None,
2268 options: RequestOptions = {},
2269 ) -> ResponseT:
2270 if body is not None and content is not None:
2271 raise TypeError("Passing both `body` and `content` is not supported")
2272 if files is not None and content is not None:
2273 raise TypeError("Passing both `files` and `content` is not supported")
2274 opts = FinalRequestOptions.construct(
2275 method="patch",
2276 url=path,
2277 json_data=body,
2278 content=content,
2279 files=await async_to_httpx_files(files),
2280 **options,
2281 )
2282 return await self.request(cast_to, opts)
2283
2284 async def put(
2285 self,
2286 path: str,
2287 *,
2288 cast_to: Type[ResponseT],
2289 body: Body | None = None,
2290 content: AsyncBinaryTypes | None = None,
2291 files: RequestFiles | None = None,
2292 options: RequestOptions = {},
2293 ) -> ResponseT:
2294 if body is not None and content is not None:
2295 raise TypeError("Passing both `body` and `content` is not supported")
2296 if files is not None and content is not None:
2297 raise TypeError("Passing both `files` and `content` is not supported")
2298 opts = FinalRequestOptions.construct(
2299 method="put", url=path, json_data=body, content=content, files=await async_to_httpx_files(files), **options
2300 )
2301 return await self.request(cast_to, opts)
2302
2303 async def delete(
2304 self,
2305 path: str,
2306 *,
2307 cast_to: Type[ResponseT],
2308 body: Body | None = None,
2309 content: AsyncBinaryTypes | None = None,
2310 options: RequestOptions = {},
2311 ) -> ResponseT:
2312 if body is not None and content is not None:
2313 raise TypeError("Passing both `body` and `content` is not supported")
2314 opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, content=content, **options)
2315 return await self.request(cast_to, opts)
2316
2317 def get_api_list(
2318 self,
2319 path: str,
2320 *,
2321 model: Type[_T],
2322 page: Type[AsyncPageT],
2323 body: Body | None = None,
2324 options: RequestOptions = {},
2325 method: str = "get",
2326 ) -> AsyncPaginator[_T, AsyncPageT]:
2327 opts = FinalRequestOptions.construct(method=method, url=path, json_data=body, **options)
2328 return self._request_api_list(model, page, opts)
2329
2330
2331 def make_request_options(
2332 *,
2333 query: Query | None = None,
2334 extra_headers: Headers | None = None,
2335 extra_query: Query | None = None,
2336 extra_body: Body | None = None,
2337 timeout: float | httpx2.Timeout | None | NotGiven = not_given,
2338 post_parser: PostParser | NotGiven = not_given,
2339 ) -> RequestOptions:
2340 """Create a dict of type RequestOptions without keys of NotGiven values."""
2341 options: RequestOptions = {}
2342 if extra_headers is not None:
2343 options["headers"] = extra_headers
2344
2345 if extra_body is not None:
2346 options["extra_json"] = cast(AnyMapping, extra_body)
2347
2348 if query is not None:
2349 options["params"] = strip_omit(query)
2350
2351 if extra_query is not None:
2352 options["params"] = {**options.get("params", {}), **extra_query}
2353
2354 if not isinstance(timeout, NotGiven):
2355 options["timeout"] = timeout
2356
2357 if is_given(post_parser):
2358 # internal
2359 options["post_parser"] = post_parser # type: ignore
2360
2361 return options
2362
2363
2364 class ForceMultipartDict(Dict[str, None]):
2365 def __bool__(self) -> bool:
2366 return True
2367
2368
2369 class OtherPlatform:
2370 def __init__(self, name: str) -> None:
2371 self.name = name
2372
2373 @override
2374 def __str__(self) -> str:
2375 return f"Other:{self.name}"
2376
2377
2378 Platform = Union[
2379 OtherPlatform,
2380 Literal[
2381 "MacOS",
2382 "Linux",
2383 "Windows",
2384 "FreeBSD",
2385 "OpenBSD",
2386 "iOS",
2387 "Android",
2388 "Unknown",
2389 ],
2390 ]
2391
2392
2393 def get_platform() -> Platform:
2394 # NOTE: we deliberately avoid `platform.platform()` (and `platform.uname().processor`)
2395 # as they shell out to `uname -p`, which would fork the process on the first request.
2396 try:
2397 system = platform.system().lower()
2398 machine = platform.machine().lower()
2399 release = platform.release().lower()
2400 except Exception:
2401 return "Unknown"
2402
2403 if system in ("ios", "ipados") or machine.startswith(("iphone", "ipad")):
2404 # CPython 3.13+ reports the system as iOS / iPadOS; older builds (e.g. Pythonista)
2405 # report Darwin with a machine like `iPhone12,1` / `iPad7,11`
2406 return "iOS"
2407
2408 if system == "darwin":
2409 return "MacOS"
2410
2411 if system == "windows":
2412 return "Windows"
2413
2414 if system == "android" or hasattr(sys, "getandroidapilevel") or "android" in release:
2415 # CPython 3.13+ reports the system as Android; older builds (e.g. Pydroid 3) report
2416 # Linux with a release like `5.10.81-android12-9-00001-geba40aecb3b7-ab8534902`
2417 return "Android"
2418
2419 if system == "linux":
2420 return "Linux"
2421
2422 if system == "freebsd":
2423 return "FreeBSD"
2424
2425 if system == "openbsd":
2426 return "OpenBSD"
2427
2428 if system:
2429 return OtherPlatform(system)
2430
2431 return "Unknown"
2432
2433
2434 @lru_cache(maxsize=None)
2435 def platform_headers(version: str, *, platform: Platform | None) -> Dict[str, str]:
2436 return {
2437 "X-Stainless-Lang": "python",
2438 "X-Stainless-Package-Version": version,
2439 "X-Stainless-OS": str(platform or get_platform()),
2440 "X-Stainless-Arch": str(get_architecture()),
2441 "X-Stainless-Runtime": get_python_runtime(),
2442 "X-Stainless-Runtime-Version": get_python_version(),
2443 }
2444
2445
2446 class OtherArch:
2447 def __init__(self, name: str) -> None:
2448 self.name = name
2449
2450 @override
2451 def __str__(self) -> str:
2452 return f"other:{self.name}"
2453
2454
2455 Arch = Union[OtherArch, Literal["x32", "x64", "arm", "arm64", "unknown"]]
2456
2457
2458 def get_python_runtime() -> str:
2459 try:
2460 return platform.python_implementation()
2461 except Exception:
2462 return "unknown"
2463
2464
2465 def get_python_version() -> str:
2466 try:
2467 return platform.python_version()
2468 except Exception:
2469 return "unknown"
2470
2471
2472 def get_architecture() -> Arch:
2473 try:
2474 machine = platform.machine().lower()
2475 except Exception:
2476 return "unknown"
2477
2478 if machine in ("arm64", "aarch64"):
2479 return "arm64"
2480
2481 # TODO: untested
2482 if machine == "arm":
2483 return "arm"
2484
2485 if machine == "x86_64":
2486 return "x64"
2487
2488 # TODO: untested
2489 if sys.maxsize <= 2**32:
2490 return "x32"
2491
2492 if machine:
2493 return OtherArch(machine)
2494
2495 return "unknown"
2496
2497
2498 def _merge_mappings(
2499 obj1: Mapping[_T_co, Union[_T, Omit]],
2500 obj2: Mapping[_T_co, Union[_T, Omit]],
2501 ) -> Dict[_T_co, _T]:
2502 """Merge two mappings of the same type, removing any values that are instances of `Omit`.
2503
2504 In cases with duplicate keys the second mapping takes precedence.
2505 """
2506 merged = {**obj1, **obj2}
2507 return {key: value for key, value in merged.items() if not isinstance(value, Omit)}
2508
2509
2510 def _merge_extra_json(options: FinalRequestOptions) -> None:
2511 """Merge `extra_json` into `json_data` in place, as `_build_request` would.
2512
2513 This runs before `_prepare_options` so that client hooks, such as Bedrock and Vertex
2514 routing, see `extra_body` values.
2515 """
2516 extra_json = options.extra_json
2517 if extra_json is None:
2518 return
2519
2520 json_data = options.json_data
2521 if json_data is None:
2522 options.json_data = cast(Body, extra_json)
2523 elif is_mapping(json_data):
2524 options.json_data = _merge_mappings(json_data, extra_json)
2525 else:
2526 raise RuntimeError(f"Unexpected JSON data type, {type(json_data)}, cannot merge with `extra_body`")
2527
2528 options.extra_json = None
2529
2530
2531 # `x-stainless-helper` is the one header whose values accumulate across layers into a single
2532 # comma-separated, deduplicated value instead of the later layer's value replacing the
2533 # earlier one (hand-written, upstream to Stainless).
2534 _APPEND_HEADERS = frozenset({"x-stainless-helper"})
2535
2536
2537 def _append_header_value(existing: str, addition: str) -> str:
2538 """Append `addition` to a comma-separated header value, skipping tokens that
2539 are already present so the same helper isn't recorded twice.
2540
2541 Values are joined with `", "`, the same format `lib._stainless_helpers` uses
2542 when it builds the `x-stainless-helper` header.
2543 """
2544 tokens = [token for token in (raw.strip() for raw in existing.split(",")) if token]
2545 for token in (raw.strip() for raw in addition.split(",")):
2546 if token and token not in tokens:
2547 tokens.append(token)
2548 return ", ".join(tokens)
2549
2550
2551 def build_headers(*layers: Mapping[str, Union[str, Omit]]) -> tuple[httpx2.Headers, frozenset[str]]:
2552 """Fold header layers into one `httpx2.Headers`, later layers taking precedence whatever a name's casing.
2553
2554 An `Omit` value removes the header set by an earlier layer; the second item holds the (lowercase)
2555 names removed that way and not set again by a later layer.
2556 """
2557 headers = httpx2.Headers(encoding="utf-8")
2558 omitted: set[str] = set()
2559 for layer in layers:
2560 for name, value in layer.items():
2561 if isinstance(value, Omit):
2562 headers.pop(name, None)
2563 omitted.add(name.lower())
2564 else:
2565 if name.lower() in _APPEND_HEADERS:
2566 value = _append_header_value(headers.get(name, ""), value)
2567 headers[name] = value
2568 omitted.discard(name.lower())
2569 return headers, frozenset(omitted)
2570
2571
2572 def merge_headers(*layers: Mapping[str, Union[str, Omit]]) -> Dict[str, str]:
2573 """Compose header layers into a single layer: a plain mapping, as `default_headers=` and
2574 `extra_headers=` accept, that still carries an `Omit` for every header the layers remove.
2575
2576 The `Dict[str, str]` return type is the same fudge the rest of the header plumbing uses for
2577 `Omit`-bearing header mappings.
2578 """
2579 headers, omitted = build_headers(*layers)
2580 layer: Dict[str, Union[str, Omit]] = dict.fromkeys(omitted, omit)
2581 layer.update((name.decode("utf-8"), value.decode("utf-8")) for name, value in headers.raw)
2582 return cast("Dict[str, str]", layer)
2583
2584
2585 def _middleware_entry_mode(request: APIRequest) -> Literal["raw", "stream"] | None:
2586 """The raw-response mode the original caller entered the middleware chain with."""
2587 headers = request.options.headers
2588 mode = headers.get(RAW_RESPONSE_HEADER) if is_given(headers) else None
2589 if isinstance(mode, str) and mode in ("raw", "stream"):
2590 # mypy for some reason cannot narrow the type
2591 return mode # type: ignore
2592 return None
2593
2594
2595 def _prepare_middleware_options(request: APIRequest) -> FinalRequestOptions:
2596 """Build the options the base middleware handler hands to `_attempt_request()`.
2597
2598 Returns a copy so that mutations made by the request pipeline never leak back
2599 into the `APIRequest` between separate `call_next(...)` invocations, with the
2600 raw-response header set so that the pipeline produces an `APIResponse` /
2601 `AsyncAPIResponse` for the middleware chain.
2602 """
2603 options = model_copy(request.options)
2604 headers = dict(options.headers) if is_given(options.headers) else {}
2605 if headers.get(RAW_RESPONSE_HEADER) not in ("raw", "stream"):
2606 # plain calls (no raw-response header) are upgraded to "raw" so that the
2607 # middleware chain always operates on an `APIResponse` / `AsyncAPIResponse`;
2608 # the "stream" mode set by `.with_streaming_response` already produces one and
2609 # is left as-is so that the response body is not eagerly read.
2610 # `_finalize_middleware_result()` restores the value the original caller expects.
2611 headers[RAW_RESPONSE_HEADER] = "raw"
2612 options.headers = headers
2613 return options
2614
2615
2616 def _expects_response_wrapper(cast_to: Any) -> bool:
2617 """Whether the given `cast_to` asks for the `APIResponse` wrapper itself."""
2618 origin = get_origin(cast_to) or cast_to
2619 return inspect.isclass(origin) and issubclass(origin, BaseAPIResponse)