| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import os |
| 4 |
import inspect |
| 5 |
import logging |
| 6 |
import datetime |
| 7 |
import functools |
| 8 |
from types import TracebackType |
| 9 |
from typing import ( |
| 10 |
TYPE_CHECKING, |
| 11 |
Any, |
| 12 |
Union, |
| 13 |
Generic, |
| 14 |
TypeVar, |
| 15 |
Callable, |
| 16 |
Iterator, |
| 17 |
AsyncIterator, |
| 18 |
cast, |
| 19 |
overload, |
| 20 |
) |
| 21 |
from typing_extensions import Awaitable, ParamSpec, override, get_origin |
| 22 |
|
| 23 |
import anyio |
| 24 |
import httpx2 |
| 25 |
import pydantic |
| 26 |
|
| 27 |
from ._types import NoneType |
| 28 |
from ._utils import is_given, extract_type_arg, is_annotated_type, is_type_alias_type, extract_type_var_from_base |
| 29 |
from ._models import BaseModel, is_basemodel, add_response_ids |
| 30 |
from ._constants import RAW_RESPONSE_HEADER, OVERRIDE_CAST_TO_HEADER |
| 31 |
from ._streaming import Stream, AsyncStream, is_stream_class_type, extract_stream_chunk_type |
| 32 |
from ._exceptions import AnthropicError, APIResponseValidationError |
| 33 |
from ._utils._typing import is_union_type |
| 34 |
from ._decoders.jsonl import JSONLDecoder, AsyncJSONLDecoder |
| 35 |
|
| 36 |
if TYPE_CHECKING: |
| 37 |
from ._models import FinalRequestOptions |
| 38 |
from ._base_client import BaseClient |
| 39 |
|
| 40 |
|
| 41 |
P = ParamSpec("P") |
| 42 |
R = TypeVar("R") |
| 43 |
_T = TypeVar("_T") |
| 44 |
_APIResponseT = TypeVar("_APIResponseT", bound="APIResponse[Any]") |
| 45 |
_AsyncAPIResponseT = TypeVar("_AsyncAPIResponseT", bound="AsyncAPIResponse[Any]") |
| 46 |
|
| 47 |
log: logging.Logger = logging.getLogger(__name__) |
| 48 |
|
| 49 |
|
| 50 |
class BaseAPIResponse(Generic[R]): |
| 51 |
_cast_to: type[R] |
| 52 |
_client: BaseClient[Any, Any] |
| 53 |
_parsed_by_type: dict[type[Any], Any] |
| 54 |
_is_sse_stream: bool |
| 55 |
_stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None |
| 56 |
_options: FinalRequestOptions |
| 57 |
|
| 58 |
http_response: httpx2.Response |
| 59 |
|
| 60 |
retries_taken: int |
| 61 |
"""The number of retries made. If no retries happened this will be `0`""" |
| 62 |
|
| 63 |
def __init__( |
| 64 |
self, |
| 65 |
*, |
| 66 |
raw: httpx2.Response, |
| 67 |
cast_to: type[R], |
| 68 |
client: BaseClient[Any, Any], |
| 69 |
stream: bool, |
| 70 |
stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None, |
| 71 |
options: FinalRequestOptions, |
| 72 |
retries_taken: int = 0, |
| 73 |
) -> None: |
| 74 |
self._cast_to = cast_to |
| 75 |
self._client = client |
| 76 |
self._parsed_by_type = {} |
| 77 |
self._is_sse_stream = stream |
| 78 |
self._stream_cls = stream_cls |
| 79 |
self._options = options |
| 80 |
self.http_response = raw |
| 81 |
self.retries_taken = retries_taken |
| 82 |
|
| 83 |
@property |
| 84 |
def headers(self) -> httpx2.Headers: |
| 85 |
return self.http_response.headers |
| 86 |
|
| 87 |
@property |
| 88 |
def http_request(self) -> httpx2.Request: |
| 89 |
"""Returns the httpx Request instance associated with the current response.""" |
| 90 |
return self.http_response.request |
| 91 |
|
| 92 |
@property |
| 93 |
def status_code(self) -> int: |
| 94 |
return self.http_response.status_code |
| 95 |
|
| 96 |
@property |
| 97 |
def url(self) -> httpx2.URL: |
| 98 |
"""Returns the URL for which the request was made.""" |
| 99 |
return self.http_response.url |
| 100 |
|
| 101 |
@property |
| 102 |
def method(self) -> str: |
| 103 |
return self.http_request.method |
| 104 |
|
| 105 |
@property |
| 106 |
def http_version(self) -> str: |
| 107 |
return self.http_response.http_version |
| 108 |
|
| 109 |
@property |
| 110 |
def elapsed(self) -> datetime.timedelta: |
| 111 |
"""The time taken for the complete request/response cycle to complete.""" |
| 112 |
return self.http_response.elapsed |
| 113 |
|
| 114 |
@property |
| 115 |
def is_closed(self) -> bool: |
| 116 |
"""Whether or not the response body has been closed. |
| 117 |
|
| 118 |
If this is False then there is response data that has not been read yet. |
| 119 |
You must either fully consume the response body or call `.close()` |
| 120 |
before discarding the response to prevent resource leaks. |
| 121 |
""" |
| 122 |
return self.http_response.is_closed |
| 123 |
|
| 124 |
@override |
| 125 |
def __repr__(self) -> str: |
| 126 |
return ( |
| 127 |
f"<{self.__class__.__name__} [{self.status_code} {self.http_response.reason_phrase}] type={self._cast_to}>" |
| 128 |
) |
| 129 |
|
| 130 |
def _parse(self, *, to: type[_T] | None = None) -> R | _T: |
| 131 |
cast_to = to if to is not None else self._cast_to |
| 132 |
|
| 133 |
# unwrap `TypeAlias('Name', T)` -> `T` |
| 134 |
if is_type_alias_type(cast_to): |
| 135 |
cast_to = cast_to.__value__ # type: ignore[unreachable] |
| 136 |
|
| 137 |
# unwrap `Annotated[T, ...]` -> `T` |
| 138 |
if cast_to and is_annotated_type(cast_to): |
| 139 |
cast_to = extract_type_arg(cast_to, 0) |
| 140 |
|
| 141 |
origin = get_origin(cast_to) or cast_to |
| 142 |
|
| 143 |
if inspect.isclass(origin): |
| 144 |
if issubclass(cast(Any, origin), JSONLDecoder): |
| 145 |
return cast( |
| 146 |
R, |
| 147 |
cast("type[JSONLDecoder[Any]]", cast_to)( |
| 148 |
raw_iterator=self.http_response.iter_bytes(chunk_size=64), |
| 149 |
line_type=extract_type_arg(cast_to, 0), |
| 150 |
http_response=self.http_response, |
| 151 |
), |
| 152 |
) |
| 153 |
|
| 154 |
if issubclass(cast(Any, origin), AsyncJSONLDecoder): |
| 155 |
return cast( |
| 156 |
R, |
| 157 |
cast("type[AsyncJSONLDecoder[Any]]", cast_to)( |
| 158 |
raw_iterator=self.http_response.aiter_bytes(chunk_size=64), |
| 159 |
line_type=extract_type_arg(cast_to, 0), |
| 160 |
http_response=self.http_response, |
| 161 |
), |
| 162 |
) |
| 163 |
|
| 164 |
if self._is_sse_stream: |
| 165 |
if to: |
| 166 |
if not is_stream_class_type(to): |
| 167 |
raise TypeError(f"Expected custom parse type to be a subclass of {Stream} or {AsyncStream}") |
| 168 |
|
| 169 |
return cast( |
| 170 |
_T, |
| 171 |
to( |
| 172 |
cast_to=extract_stream_chunk_type( |
| 173 |
to, |
| 174 |
failure_message="Expected custom stream type to be passed with a type argument, e.g. Stream[ChunkType]", |
| 175 |
), |
| 176 |
response=self.http_response, |
| 177 |
client=cast(Any, self._client), |
| 178 |
options=self._options, |
| 179 |
), |
| 180 |
) |
| 181 |
|
| 182 |
if self._stream_cls: |
| 183 |
return cast( |
| 184 |
R, |
| 185 |
self._stream_cls( |
| 186 |
cast_to=extract_stream_chunk_type(self._stream_cls), |
| 187 |
response=self.http_response, |
| 188 |
client=cast(Any, self._client), |
| 189 |
options=self._options, |
| 190 |
), |
| 191 |
) |
| 192 |
|
| 193 |
stream_cls = cast("type[Stream[Any]] | type[AsyncStream[Any]] | None", self._client._default_stream_cls) |
| 194 |
if stream_cls is None: |
| 195 |
raise MissingStreamClassError() |
| 196 |
|
| 197 |
return cast( |
| 198 |
R, |
| 199 |
stream_cls( |
| 200 |
cast_to=cast_to, |
| 201 |
response=self.http_response, |
| 202 |
client=cast(Any, self._client), |
| 203 |
options=self._options, |
| 204 |
), |
| 205 |
) |
| 206 |
|
| 207 |
if cast_to is NoneType: |
| 208 |
return cast(R, None) |
| 209 |
|
| 210 |
response = self.http_response |
| 211 |
if cast_to == str: |
| 212 |
return cast(R, response.text) |
| 213 |
|
| 214 |
if cast_to == bytes: |
| 215 |
return cast(R, response.content) |
| 216 |
|
| 217 |
if cast_to == int: |
| 218 |
return cast(R, int(response.text)) |
| 219 |
|
| 220 |
if cast_to == float: |
| 221 |
return cast(R, float(response.text)) |
| 222 |
|
| 223 |
if cast_to == bool: |
| 224 |
return cast(R, response.text.lower() == "true") |
| 225 |
|
| 226 |
if origin == APIResponse: |
| 227 |
raise RuntimeError("Unexpected state - cast_to is `APIResponse`") |
| 228 |
|
| 229 |
if inspect.isclass( |
| 230 |
origin # pyright: ignore[reportUnknownArgumentType] |
| 231 |
) and issubclass(origin, httpx2.Response): |
| 232 |
# Because of the invariance of our ResponseT TypeVar, users can subclass httpx2.Response |
| 233 |
# and pass that class to our request functions. We cannot change the variance to be either |
| 234 |
# covariant or contravariant as that makes our usage of ResponseT illegal. We could construct |
| 235 |
# the response class ourselves but that is something that should be supported directly in httpx |
| 236 |
# as it would be easy to incorrectly construct the Response object due to the multitude of arguments. |
| 237 |
if cast_to != httpx2.Response: |
| 238 |
raise ValueError(f"Subclasses of httpx2.Response cannot be passed to `cast_to`") |
| 239 |
return cast(R, response) |
| 240 |
|
| 241 |
if ( |
| 242 |
inspect.isclass( |
| 243 |
origin # pyright: ignore[reportUnknownArgumentType] |
| 244 |
) |
| 245 |
and not issubclass(origin, BaseModel) |
| 246 |
and issubclass(origin, pydantic.BaseModel) |
| 247 |
): |
| 248 |
raise TypeError("Pydantic models must subclass our base model type, e.g. `from anthropic import BaseModel`") |
| 249 |
|
| 250 |
if ( |
| 251 |
cast_to is not object |
| 252 |
and not origin is list |
| 253 |
and not origin is dict |
| 254 |
and not is_union_type(cast_to) |
| 255 |
and not issubclass(origin, BaseModel) |
| 256 |
): |
| 257 |
raise RuntimeError( |
| 258 |
f"Unsupported type, expected {cast_to} to be a subclass of {BaseModel}, {dict}, {list}, {Union}, {NoneType}, {str} or {httpx2.Response}." |
| 259 |
) |
| 260 |
|
| 261 |
# split is required to handle cases where additional information is included |
| 262 |
# in the response, e.g. application/json; charset=utf-8 |
| 263 |
content_type, *_ = response.headers.get("content-type", "*").split(";") |
| 264 |
if not content_type.lower().endswith("json"): |
| 265 |
if is_basemodel(cast_to): |
| 266 |
try: |
| 267 |
data = response.json() |
| 268 |
except Exception as exc: |
| 269 |
log.debug("Could not read JSON from response data due to %s - %s", type(exc), exc) |
| 270 |
else: |
| 271 |
return self._client._process_response_data( |
| 272 |
data=data, |
| 273 |
cast_to=cast_to, # type: ignore |
| 274 |
response=response, |
| 275 |
) |
| 276 |
|
| 277 |
if self._client._strict_response_validation: |
| 278 |
raise APIResponseValidationError( |
| 279 |
response=response, |
| 280 |
message=f"Expected Content-Type response header to be `application/json` but received `{content_type}` instead.", |
| 281 |
body=response.text, |
| 282 |
) |
| 283 |
|
| 284 |
# If the API responds with content that isn't JSON then we just return |
| 285 |
# the (decoded) text without performing any parsing so that you can still |
| 286 |
# handle the response however you need to. |
| 287 |
return response.text # type: ignore |
| 288 |
|
| 289 |
data = response.json() |
| 290 |
|
| 291 |
return self._client._process_response_data( |
| 292 |
data=data, |
| 293 |
cast_to=cast_to, # type: ignore |
| 294 |
response=response, |
| 295 |
) |
| 296 |
|
| 297 |
|
| 298 |
class APIResponse(BaseAPIResponse[R]): |
| 299 |
@property |
| 300 |
def request_id(self) -> str | None: |
| 301 |
return self.http_response.headers.get("request-id") # type: ignore[no-any-return] |
| 302 |
|
| 303 |
@property |
| 304 |
def workspace_id(self) -> str | None: |
| 305 |
return self.http_response.headers.get("anthropic-workspace-id") # type: ignore[no-any-return] |
| 306 |
|
| 307 |
@overload |
| 308 |
def parse(self, *, to: type[_T]) -> _T: ... |
| 309 |
|
| 310 |
@overload |
| 311 |
def parse(self) -> R: ... |
| 312 |
|
| 313 |
def parse(self, *, to: type[_T] | None = None) -> R | _T: |
| 314 |
"""Returns the rich python representation of this response's data. |
| 315 |
|
| 316 |
For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`. |
| 317 |
|
| 318 |
You can customise the type that the response is parsed into through |
| 319 |
the `to` argument, e.g. |
| 320 |
|
| 321 |
```py |
| 322 |
from anthropic import BaseModel |
| 323 |
|
| 324 |
|
| 325 |
class MyModel(BaseModel): |
| 326 |
foo: str |
| 327 |
|
| 328 |
|
| 329 |
obj = response.parse(to=MyModel) |
| 330 |
print(obj.foo) |
| 331 |
``` |
| 332 |
|
| 333 |
We support parsing: |
| 334 |
- `BaseModel` |
| 335 |
- `dict` |
| 336 |
- `list` |
| 337 |
- `Union` |
| 338 |
- `str` |
| 339 |
- `int` |
| 340 |
- `float` |
| 341 |
- `httpx2.Response` |
| 342 |
""" |
| 343 |
cache_key = to if to is not None else self._cast_to |
| 344 |
cached = self._parsed_by_type.get(cache_key) |
| 345 |
if cached is not None: |
| 346 |
return cached # type: ignore[no-any-return] |
| 347 |
|
| 348 |
if not self._is_sse_stream: |
| 349 |
self.read() |
| 350 |
|
| 351 |
parsed = self._parse(to=to) |
| 352 |
if is_given(self._options.post_parser): |
| 353 |
parsed = self._options.post_parser(parsed) |
| 354 |
|
| 355 |
if isinstance(parsed, BaseModel): |
| 356 |
add_response_ids(parsed, request_id=self.request_id, workspace_id=self.workspace_id) |
| 357 |
|
| 358 |
self._parsed_by_type[cache_key] = parsed |
| 359 |
return cast(R, parsed) |
| 360 |
|
| 361 |
def read(self) -> bytes: |
| 362 |
"""Read and return the binary response content.""" |
| 363 |
try: |
| 364 |
return self.http_response.read() |
| 365 |
except httpx2.StreamConsumed as exc: |
| 366 |
# The default error raised by httpx isn't very |
| 367 |
# helpful in our case so we re-raise it with |
| 368 |
# a different error message. |
| 369 |
raise StreamAlreadyConsumed() from exc |
| 370 |
|
| 371 |
def text(self) -> str: |
| 372 |
"""Read and decode the response content into a string.""" |
| 373 |
self.read() |
| 374 |
return self.http_response.text |
| 375 |
|
| 376 |
def json(self) -> object: |
| 377 |
"""Read and decode the JSON response content.""" |
| 378 |
self.read() |
| 379 |
return self.http_response.json() |
| 380 |
|
| 381 |
def close(self) -> None: |
| 382 |
"""Close the response and release the connection. |
| 383 |
|
| 384 |
Automatically called if the response body is read to completion. |
| 385 |
""" |
| 386 |
self.http_response.close() |
| 387 |
|
| 388 |
def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]: |
| 389 |
""" |
| 390 |
A byte-iterator over the decoded response content. |
| 391 |
|
| 392 |
This automatically handles gzip, deflate and brotli encoded responses. |
| 393 |
""" |
| 394 |
for chunk in self.http_response.iter_bytes(chunk_size): |
| 395 |
yield chunk |
| 396 |
|
| 397 |
def iter_text(self, chunk_size: int | None = None) -> Iterator[str]: |
| 398 |
"""A str-iterator over the decoded response content |
| 399 |
that handles both gzip, deflate, etc but also detects the content's |
| 400 |
string encoding. |
| 401 |
""" |
| 402 |
for chunk in self.http_response.iter_text(chunk_size): |
| 403 |
yield chunk |
| 404 |
|
| 405 |
def iter_lines(self) -> Iterator[str]: |
| 406 |
"""Like `iter_text()` but will only yield chunks for each line""" |
| 407 |
for chunk in self.http_response.iter_lines(): |
| 408 |
yield chunk |
| 409 |
|
| 410 |
|
| 411 |
class AsyncAPIResponse(BaseAPIResponse[R]): |
| 412 |
@property |
| 413 |
def request_id(self) -> str | None: |
| 414 |
return self.http_response.headers.get("request-id") # type: ignore[no-any-return] |
| 415 |
|
| 416 |
@property |
| 417 |
def workspace_id(self) -> str | None: |
| 418 |
return self.http_response.headers.get("anthropic-workspace-id") # type: ignore[no-any-return] |
| 419 |
|
| 420 |
@overload |
| 421 |
async def parse(self, *, to: type[_T]) -> _T: ... |
| 422 |
|
| 423 |
@overload |
| 424 |
async def parse(self) -> R: ... |
| 425 |
|
| 426 |
async def parse(self, *, to: type[_T] | None = None) -> R | _T: |
| 427 |
"""Returns the rich python representation of this response's data. |
| 428 |
|
| 429 |
For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`. |
| 430 |
|
| 431 |
You can customise the type that the response is parsed into through |
| 432 |
the `to` argument, e.g. |
| 433 |
|
| 434 |
```py |
| 435 |
from anthropic import BaseModel |
| 436 |
|
| 437 |
|
| 438 |
class MyModel(BaseModel): |
| 439 |
foo: str |
| 440 |
|
| 441 |
|
| 442 |
obj = response.parse(to=MyModel) |
| 443 |
print(obj.foo) |
| 444 |
``` |
| 445 |
|
| 446 |
We support parsing: |
| 447 |
- `BaseModel` |
| 448 |
- `dict` |
| 449 |
- `list` |
| 450 |
- `Union` |
| 451 |
- `str` |
| 452 |
- `httpx2.Response` |
| 453 |
""" |
| 454 |
cache_key = to if to is not None else self._cast_to |
| 455 |
cached = self._parsed_by_type.get(cache_key) |
| 456 |
if cached is not None: |
| 457 |
return cached # type: ignore[no-any-return] |
| 458 |
|
| 459 |
if not self._is_sse_stream: |
| 460 |
await self.read() |
| 461 |
|
| 462 |
parsed = self._parse(to=to) |
| 463 |
if is_given(self._options.post_parser): |
| 464 |
parsed = self._options.post_parser(parsed) |
| 465 |
|
| 466 |
if isinstance(parsed, BaseModel): |
| 467 |
add_response_ids(parsed, request_id=self.request_id, workspace_id=self.workspace_id) |
| 468 |
|
| 469 |
self._parsed_by_type[cache_key] = parsed |
| 470 |
return cast(R, parsed) |
| 471 |
|
| 472 |
async def read(self) -> bytes: |
| 473 |
"""Read and return the binary response content.""" |
| 474 |
try: |
| 475 |
return await self.http_response.aread() |
| 476 |
except httpx2.StreamConsumed as exc: |
| 477 |
# the default error raised by httpx isn't very |
| 478 |
# helpful in our case so we re-raise it with |
| 479 |
# a different error message |
| 480 |
raise StreamAlreadyConsumed() from exc |
| 481 |
|
| 482 |
async def text(self) -> str: |
| 483 |
"""Read and decode the response content into a string.""" |
| 484 |
await self.read() |
| 485 |
return self.http_response.text |
| 486 |
|
| 487 |
async def json(self) -> object: |
| 488 |
"""Read and decode the JSON response content.""" |
| 489 |
await self.read() |
| 490 |
return self.http_response.json() |
| 491 |
|
| 492 |
async def close(self) -> None: |
| 493 |
"""Close the response and release the connection. |
| 494 |
|
| 495 |
Automatically called if the response body is read to completion. |
| 496 |
""" |
| 497 |
await self.http_response.aclose() |
| 498 |
|
| 499 |
async def iter_bytes(self, chunk_size: int | None = None) -> AsyncIterator[bytes]: |
| 500 |
""" |
| 501 |
A byte-iterator over the decoded response content. |
| 502 |
|
| 503 |
This automatically handles gzip, deflate and brotli encoded responses. |
| 504 |
""" |
| 505 |
async for chunk in self.http_response.aiter_bytes(chunk_size): |
| 506 |
yield chunk |
| 507 |
|
| 508 |
async def iter_text(self, chunk_size: int | None = None) -> AsyncIterator[str]: |
| 509 |
"""A str-iterator over the decoded response content |
| 510 |
that handles both gzip, deflate, etc but also detects the content's |
| 511 |
string encoding. |
| 512 |
""" |
| 513 |
async for chunk in self.http_response.aiter_text(chunk_size): |
| 514 |
yield chunk |
| 515 |
|
| 516 |
async def iter_lines(self) -> AsyncIterator[str]: |
| 517 |
"""Like `iter_text()` but will only yield chunks for each line""" |
| 518 |
async for chunk in self.http_response.aiter_lines(): |
| 519 |
yield chunk |
| 520 |
|
| 521 |
|
| 522 |
class BinaryAPIResponse(APIResponse[bytes]): |
| 523 |
"""Subclass of APIResponse providing helpers for dealing with binary data. |
| 524 |
|
| 525 |
Note: If you want to stream the response data instead of eagerly reading it |
| 526 |
all at once then you should use `.with_streaming_response` when making |
| 527 |
the API request, e.g. `.with_streaming_response.get_binary_response()` |
| 528 |
""" |
| 529 |
|
| 530 |
def write_to_file( |
| 531 |
self, |
| 532 |
file: str | os.PathLike[str], |
| 533 |
) -> None: |
| 534 |
"""Write the output to the given file. |
| 535 |
|
| 536 |
Accepts a filename or any path-like object, e.g. pathlib.Path |
| 537 |
|
| 538 |
Note: if you want to stream the data to the file instead of writing |
| 539 |
all at once then you should use `.with_streaming_response` when making |
| 540 |
the API request, e.g. `.with_streaming_response.get_binary_response()` |
| 541 |
""" |
| 542 |
with open(file, mode="wb") as f: |
| 543 |
for data in self.iter_bytes(): |
| 544 |
f.write(data) |
| 545 |
|
| 546 |
|
| 547 |
class AsyncBinaryAPIResponse(AsyncAPIResponse[bytes]): |
| 548 |
"""Subclass of APIResponse providing helpers for dealing with binary data. |
| 549 |
|
| 550 |
Note: If you want to stream the response data instead of eagerly reading it |
| 551 |
all at once then you should use `.with_streaming_response` when making |
| 552 |
the API request, e.g. `.with_streaming_response.get_binary_response()` |
| 553 |
""" |
| 554 |
|
| 555 |
async def write_to_file( |
| 556 |
self, |
| 557 |
file: str | os.PathLike[str], |
| 558 |
) -> None: |
| 559 |
"""Write the output to the given file. |
| 560 |
|
| 561 |
Accepts a filename or any path-like object, e.g. pathlib.Path |
| 562 |
|
| 563 |
Note: if you want to stream the data to the file instead of writing |
| 564 |
all at once then you should use `.with_streaming_response` when making |
| 565 |
the API request, e.g. `.with_streaming_response.get_binary_response()` |
| 566 |
""" |
| 567 |
path = anyio.Path(file) |
| 568 |
async with await path.open(mode="wb") as f: |
| 569 |
async for data in self.iter_bytes(): |
| 570 |
await f.write(data) |
| 571 |
|
| 572 |
|
| 573 |
class StreamedBinaryAPIResponse(APIResponse[bytes]): |
| 574 |
def stream_to_file( |
| 575 |
self, |
| 576 |
file: str | os.PathLike[str], |
| 577 |
*, |
| 578 |
chunk_size: int | None = None, |
| 579 |
) -> None: |
| 580 |
"""Streams the output to the given file. |
| 581 |
|
| 582 |
Accepts a filename or any path-like object, e.g. pathlib.Path |
| 583 |
""" |
| 584 |
with open(file, mode="wb") as f: |
| 585 |
for data in self.iter_bytes(chunk_size): |
| 586 |
f.write(data) |
| 587 |
|
| 588 |
|
| 589 |
class AsyncStreamedBinaryAPIResponse(AsyncAPIResponse[bytes]): |
| 590 |
async def stream_to_file( |
| 591 |
self, |
| 592 |
file: str | os.PathLike[str], |
| 593 |
*, |
| 594 |
chunk_size: int | None = None, |
| 595 |
) -> None: |
| 596 |
"""Streams the output to the given file. |
| 597 |
|
| 598 |
Accepts a filename or any path-like object, e.g. pathlib.Path |
| 599 |
""" |
| 600 |
path = anyio.Path(file) |
| 601 |
async with await path.open(mode="wb") as f: |
| 602 |
async for data in self.iter_bytes(chunk_size): |
| 603 |
await f.write(data) |
| 604 |
|
| 605 |
|
| 606 |
class MissingStreamClassError(TypeError): |
| 607 |
def __init__(self) -> None: |
| 608 |
super().__init__( |
| 609 |
"The `stream` argument was set to `True` but the `stream_cls` argument was not given. See `anthropic._streaming` for reference", |
| 610 |
) |
| 611 |
|
| 612 |
|
| 613 |
class StreamAlreadyConsumed(AnthropicError): |
| 614 |
""" |
| 615 |
Attempted to read or stream content, but the content has already |
| 616 |
been streamed. |
| 617 |
|
| 618 |
This can happen if you use a method like `.iter_lines()` and then attempt |
| 619 |
to read th entire response body afterwards, e.g. |
| 620 |
|
| 621 |
```py |
| 622 |
response = await client.post(...) |
| 623 |
async for line in response.iter_lines(): |
| 624 |
... # do something with `line` |
| 625 |
|
| 626 |
content = await response.read() |
| 627 |
# ^ error |
| 628 |
``` |
| 629 |
|
| 630 |
If you want this behaviour you'll need to either manually accumulate the response |
| 631 |
content or call `await response.read()` before iterating over the stream. |
| 632 |
""" |
| 633 |
|
| 634 |
def __init__(self) -> None: |
| 635 |
message = ( |
| 636 |
"Attempted to read or stream some content, but the content has " |
| 637 |
"already been streamed. " |
| 638 |
"This could be due to attempting to stream the response " |
| 639 |
"content more than once." |
| 640 |
"\n\n" |
| 641 |
"You can fix this by manually accumulating the response content while streaming " |
| 642 |
"or by calling `.read()` before starting to stream." |
| 643 |
) |
| 644 |
super().__init__(message) |
| 645 |
|
| 646 |
|
| 647 |
class ResponseContextManager(Generic[_APIResponseT]): |
| 648 |
"""Context manager for ensuring that a request is not made |
| 649 |
until it is entered and that the response will always be closed |
| 650 |
when the context manager exits |
| 651 |
""" |
| 652 |
|
| 653 |
def __init__(self, request_func: Callable[[], _APIResponseT]) -> None: |
| 654 |
self._request_func = request_func |
| 655 |
self.__response: _APIResponseT | None = None |
| 656 |
|
| 657 |
def __enter__(self) -> _APIResponseT: |
| 658 |
self.__response = self._request_func() |
| 659 |
return self.__response |
| 660 |
|
| 661 |
def __exit__( |
| 662 |
self, |
| 663 |
exc_type: type[BaseException] | None, |
| 664 |
exc: BaseException | None, |
| 665 |
exc_tb: TracebackType | None, |
| 666 |
) -> None: |
| 667 |
if self.__response is not None: |
| 668 |
self.__response.close() |
| 669 |
|
| 670 |
|
| 671 |
class AsyncResponseContextManager(Generic[_AsyncAPIResponseT]): |
| 672 |
"""Context manager for ensuring that a request is not made |
| 673 |
until it is entered and that the response will always be closed |
| 674 |
when the context manager exits |
| 675 |
""" |
| 676 |
|
| 677 |
def __init__(self, api_request: Awaitable[_AsyncAPIResponseT]) -> None: |
| 678 |
self._api_request = api_request |
| 679 |
self.__response: _AsyncAPIResponseT | None = None |
| 680 |
|
| 681 |
async def __aenter__(self) -> _AsyncAPIResponseT: |
| 682 |
self.__response = await self._api_request |
| 683 |
return self.__response |
| 684 |
|
| 685 |
async def __aexit__( |
| 686 |
self, |
| 687 |
exc_type: type[BaseException] | None, |
| 688 |
exc: BaseException | None, |
| 689 |
exc_tb: TracebackType | None, |
| 690 |
) -> None: |
| 691 |
if self.__response is not None: |
| 692 |
await self.__response.close() |
| 693 |
|
| 694 |
|
| 695 |
def to_streamed_response_wrapper(func: Callable[P, R]) -> Callable[P, ResponseContextManager[APIResponse[R]]]: |
| 696 |
"""Higher order function that takes one of our bound API methods and wraps it |
| 697 |
to support streaming and returning the raw `APIResponse` object directly. |
| 698 |
""" |
| 699 |
|
| 700 |
@functools.wraps(func) |
| 701 |
def wrapped(*args: P.args, **kwargs: P.kwargs) -> ResponseContextManager[APIResponse[R]]: |
| 702 |
extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} |
| 703 |
extra_headers[RAW_RESPONSE_HEADER] = "stream" |
| 704 |
|
| 705 |
kwargs["extra_headers"] = extra_headers |
| 706 |
|
| 707 |
make_request = functools.partial(func, *args, **kwargs) |
| 708 |
|
| 709 |
return ResponseContextManager(cast(Callable[[], APIResponse[R]], make_request)) |
| 710 |
|
| 711 |
return wrapped |
| 712 |
|
| 713 |
|
| 714 |
def async_to_streamed_response_wrapper( |
| 715 |
func: Callable[P, Awaitable[R]], |
| 716 |
) -> Callable[P, AsyncResponseContextManager[AsyncAPIResponse[R]]]: |
| 717 |
"""Higher order function that takes one of our bound API methods and wraps it |
| 718 |
to support streaming and returning the raw `APIResponse` object directly. |
| 719 |
""" |
| 720 |
|
| 721 |
@functools.wraps(func) |
| 722 |
def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncResponseContextManager[AsyncAPIResponse[R]]: |
| 723 |
extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} |
| 724 |
extra_headers[RAW_RESPONSE_HEADER] = "stream" |
| 725 |
|
| 726 |
kwargs["extra_headers"] = extra_headers |
| 727 |
|
| 728 |
make_request = func(*args, **kwargs) |
| 729 |
|
| 730 |
return AsyncResponseContextManager(cast(Awaitable[AsyncAPIResponse[R]], make_request)) |
| 731 |
|
| 732 |
return wrapped |
| 733 |
|
| 734 |
|
| 735 |
def to_custom_streamed_response_wrapper( |
| 736 |
func: Callable[P, object], |
| 737 |
response_cls: type[_APIResponseT], |
| 738 |
) -> Callable[P, ResponseContextManager[_APIResponseT]]: |
| 739 |
"""Higher order function that takes one of our bound API methods and an `APIResponse` class |
| 740 |
and wraps the method to support streaming and returning the given response class directly. |
| 741 |
|
| 742 |
Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])` |
| 743 |
""" |
| 744 |
|
| 745 |
@functools.wraps(func) |
| 746 |
def wrapped(*args: P.args, **kwargs: P.kwargs) -> ResponseContextManager[_APIResponseT]: |
| 747 |
extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})} |
| 748 |
extra_headers[RAW_RESPONSE_HEADER] = "stream" |
| 749 |
extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls |
| 750 |
|
| 751 |
kwargs["extra_headers"] = extra_headers |
| 752 |
|
| 753 |
make_request = functools.partial(func, *args, **kwargs) |
| 754 |
|
| 755 |
return ResponseContextManager(cast(Callable[[], _APIResponseT], make_request)) |
| 756 |
|
| 757 |
return wrapped |
| 758 |
|
| 759 |
|
| 760 |
def async_to_custom_streamed_response_wrapper( |
| 761 |
func: Callable[P, Awaitable[object]], |
| 762 |
response_cls: type[_AsyncAPIResponseT], |
| 763 |
) -> Callable[P, AsyncResponseContextManager[_AsyncAPIResponseT]]: |
| 764 |
"""Higher order function that takes one of our bound API methods and an `APIResponse` class |
| 765 |
and wraps the method to support streaming and returning the given response class directly. |
| 766 |
|
| 767 |
Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])` |
| 768 |
""" |
| 769 |
|
| 770 |
@functools.wraps(func) |
| 771 |
def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncResponseContextManager[_AsyncAPIResponseT]: |
| 772 |
extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})} |
| 773 |
extra_headers[RAW_RESPONSE_HEADER] = "stream" |
| 774 |
extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls |
| 775 |
|
| 776 |
kwargs["extra_headers"] = extra_headers |
| 777 |
|
| 778 |
make_request = func(*args, **kwargs) |
| 779 |
|
| 780 |
return AsyncResponseContextManager(cast(Awaitable[_AsyncAPIResponseT], make_request)) |
| 781 |
|
| 782 |
return wrapped |
| 783 |
|
| 784 |
|
| 785 |
def to_raw_response_wrapper(func: Callable[P, R]) -> Callable[P, APIResponse[R]]: |
| 786 |
"""Higher order function that takes one of our bound API methods and wraps it |
| 787 |
to support returning the raw `APIResponse` object directly. |
| 788 |
""" |
| 789 |
|
| 790 |
@functools.wraps(func) |
| 791 |
def wrapped(*args: P.args, **kwargs: P.kwargs) -> APIResponse[R]: |
| 792 |
extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} |
| 793 |
extra_headers[RAW_RESPONSE_HEADER] = "raw" |
| 794 |
|
| 795 |
kwargs["extra_headers"] = extra_headers |
| 796 |
|
| 797 |
return cast(APIResponse[R], func(*args, **kwargs)) |
| 798 |
|
| 799 |
return wrapped |
| 800 |
|
| 801 |
|
| 802 |
def async_to_raw_response_wrapper(func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[AsyncAPIResponse[R]]]: |
| 803 |
"""Higher order function that takes one of our bound API methods and wraps it |
| 804 |
to support returning the raw `APIResponse` object directly. |
| 805 |
""" |
| 806 |
|
| 807 |
@functools.wraps(func) |
| 808 |
async def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncAPIResponse[R]: |
| 809 |
extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} |
| 810 |
extra_headers[RAW_RESPONSE_HEADER] = "raw" |
| 811 |
|
| 812 |
kwargs["extra_headers"] = extra_headers |
| 813 |
|
| 814 |
return cast(AsyncAPIResponse[R], await func(*args, **kwargs)) |
| 815 |
|
| 816 |
return wrapped |
| 817 |
|
| 818 |
|
| 819 |
def to_custom_raw_response_wrapper( |
| 820 |
func: Callable[P, object], |
| 821 |
response_cls: type[_APIResponseT], |
| 822 |
) -> Callable[P, _APIResponseT]: |
| 823 |
"""Higher order function that takes one of our bound API methods and an `APIResponse` class |
| 824 |
and wraps the method to support returning the given response class directly. |
| 825 |
|
| 826 |
Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])` |
| 827 |
""" |
| 828 |
|
| 829 |
@functools.wraps(func) |
| 830 |
def wrapped(*args: P.args, **kwargs: P.kwargs) -> _APIResponseT: |
| 831 |
extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})} |
| 832 |
extra_headers[RAW_RESPONSE_HEADER] = "raw" |
| 833 |
extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls |
| 834 |
|
| 835 |
kwargs["extra_headers"] = extra_headers |
| 836 |
|
| 837 |
return cast(_APIResponseT, func(*args, **kwargs)) |
| 838 |
|
| 839 |
return wrapped |
| 840 |
|
| 841 |
|
| 842 |
def async_to_custom_raw_response_wrapper( |
| 843 |
func: Callable[P, Awaitable[object]], |
| 844 |
response_cls: type[_AsyncAPIResponseT], |
| 845 |
) -> Callable[P, Awaitable[_AsyncAPIResponseT]]: |
| 846 |
"""Higher order function that takes one of our bound API methods and an `APIResponse` class |
| 847 |
and wraps the method to support returning the given response class directly. |
| 848 |
|
| 849 |
Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])` |
| 850 |
""" |
| 851 |
|
| 852 |
@functools.wraps(func) |
| 853 |
def wrapped(*args: P.args, **kwargs: P.kwargs) -> Awaitable[_AsyncAPIResponseT]: |
| 854 |
extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})} |
| 855 |
extra_headers[RAW_RESPONSE_HEADER] = "raw" |
| 856 |
extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls |
| 857 |
|
| 858 |
kwargs["extra_headers"] = extra_headers |
| 859 |
|
| 860 |
return cast(Awaitable[_AsyncAPIResponseT], func(*args, **kwargs)) |
| 861 |
|
| 862 |
return wrapped |
| 863 |
|
| 864 |
|
| 865 |
def extract_response_type(typ: type[BaseAPIResponse[Any]]) -> type: |
| 866 |
"""Given a type like `APIResponse[T]`, returns the generic type variable `T`. |
| 867 |
|
| 868 |
This also handles the case where a concrete subclass is given, e.g. |
| 869 |
```py |
| 870 |
class MyResponse(APIResponse[bytes]): |
| 871 |
... |
| 872 |
|
| 873 |
extract_response_type(MyResponse) -> bytes |
| 874 |
``` |
| 875 |
""" |
| 876 |
return extract_type_var_from_base( |
| 877 |
typ, |
| 878 |
generic_bases=cast("tuple[type, ...]", (BaseAPIResponse, APIResponse, AsyncAPIResponse)), |
| 879 |
index=0, |
| 880 |
) |