Debian Codegraph @

src/anthropic/_types.py

raw
1 from __future__ import annotations
2
3 from os import PathLike
4 from typing import (
5 IO,
6 TYPE_CHECKING,
7 Any,
8 Dict,
9 List,
10 Type,
11 Tuple,
12 Union,
13 Mapping,
14 TypeVar,
15 Callable,
16 Iterable,
17 Iterator,
18 Optional,
19 Sequence,
20 AsyncIterable,
21 )
22 from typing_extensions import (
23 Set,
24 Literal,
25 Protocol,
26 TypeAlias,
27 TypedDict,
28 SupportsIndex,
29 overload,
30 override,
31 runtime_checkable,
32 )
33
34 import httpx2
35 import pydantic
36 from httpx2 import Timeout, Response
37
38 if TYPE_CHECKING:
39 from ._models import BaseModel
40 from ._response import APIResponse, AsyncAPIResponse
41
42 Query = Mapping[str, object]
43 Body = object
44 AnyMapping = Mapping[str, object]
45 ModelT = TypeVar("ModelT", bound=pydantic.BaseModel)
46 _T = TypeVar("_T")
47
48 ArrayFormat = Literal["comma", "repeat", "indices", "brackets"]
49 NestedFormat = Literal["dots", "brackets"]
50
51
52 # Approximates httpx internal RequestFiles types
53 # while adding support for `PathLike` instances
54 if TYPE_CHECKING:
55 Base64FileInput = Union[IO[bytes], PathLike[str]]
56 FileContent = Union[IO[bytes], bytes, PathLike[str]]
57 else:
58 Base64FileInput = Union[IO[bytes], PathLike]
59 FileContent = Union[IO[bytes], bytes, PathLike] # PathLike is not subscriptable in Python 3.8.
60
61
62 # Used for sending raw binary data / streaming data in request bodies
63 # e.g. for file uploads without multipart encoding
64 BinaryTypes = Union[bytes, bytearray, IO[bytes], Iterable[bytes]]
65 AsyncBinaryTypes = Union[bytes, bytearray, IO[bytes], AsyncIterable[bytes]]
66
67 FileTypes = Union[
68 # file (or bytes)
69 FileContent,
70 # (filename, file (or bytes))
71 Tuple[Optional[str], FileContent],
72 # (filename, file (or bytes), content_type)
73 Tuple[Optional[str], FileContent, Optional[str]],
74 # (filename, file (or bytes), content_type, headers)
75 Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]],
76 ]
77 RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]]
78
79 # duplicate of the above but without our custom file support
80 HttpxFileContent = Union[IO[bytes], bytes]
81 HttpxFileTypes = Union[
82 # file (or bytes)
83 HttpxFileContent,
84 # (filename, file (or bytes))
85 Tuple[Optional[str], HttpxFileContent],
86 # (filename, file (or bytes), content_type)
87 Tuple[Optional[str], HttpxFileContent, Optional[str]],
88 # (filename, file (or bytes), content_type, headers)
89 Tuple[Optional[str], HttpxFileContent, Optional[str], Mapping[str, str]],
90 ]
91 HttpxRequestFiles = Union[Mapping[str, HttpxFileTypes], Sequence[Tuple[str, HttpxFileTypes]]]
92
93 # Workaround to support (cast_to: Type[ResponseT]) -> ResponseT
94 # where ResponseT includes `None`. In order to support directly
95 # passing `None`, overloads would have to be defined for every
96 # method that uses `ResponseT` which would lead to an unacceptable
97 # amount of code duplication and make it unreadable. See _base_client.py
98 # for example usage.
99 #
100 # This unfortunately means that you will either have
101 # to import this type and pass it explicitly:
102 #
103 # from anthropic import NoneType
104 # client.get('/foo', cast_to=NoneType)
105 #
106 # or build it yourself:
107 #
108 # client.get('/foo', cast_to=type(None))
109 if TYPE_CHECKING:
110 NoneType: Type[None]
111 else:
112 NoneType = type(None)
113
114
115 class RequestOptions(TypedDict, total=False):
116 headers: Headers
117 max_retries: int
118 timeout: float | Timeout | None
119 params: Query
120 extra_json: AnyMapping
121 idempotency_key: str
122 """Deprecated: this option has no effect and will be removed in a future major version."""
123 follow_redirects: bool
124
125
126 # Sentinel class used until PEP 0661 is accepted
127 class NotGiven:
128 """
129 For parameters with a meaningful None value, we need to distinguish between
130 the user explicitly passing None, and the user not passing the parameter at
131 all.
132
133 User code shouldn't need to use not_given directly.
134
135 For example:
136
137 ```py
138 def create(timeout: Timeout | None | NotGiven = not_given): ...
139
140
141 create(timeout=1) # 1s timeout
142 create(timeout=None) # No timeout
143 create() # Default timeout behavior
144 ```
145 """
146
147 def __bool__(self) -> Literal[False]:
148 return False
149
150 @override
151 def __repr__(self) -> str:
152 return "NOT_GIVEN"
153
154
155 not_given = NotGiven()
156 # for backwards compatibility:
157 NOT_GIVEN = NotGiven()
158
159
160 class Omit:
161 """
162 To explicitly omit something from being sent in a request, use `omit`.
163
164 ```py
165 # as the default `Content-Type` header is `application/json` that will be sent
166 client.post("/upload/files", files={"file": b"my raw file content"})
167
168 # you can't explicitly override the header as it has to be dynamically generated
169 # to look something like: 'multipart/form-data; boundary=0d8382fcf5f8c3be01ca2e11002d2983'
170 client.post(..., headers={"Content-Type": "multipart/form-data"})
171
172 # instead you can remove the default `application/json` header by passing omit
173 client.post(..., headers={"Content-Type": omit})
174 ```
175 """
176
177 def __bool__(self) -> Literal[False]:
178 return False
179
180
181 omit = Omit()
182
183
184 @runtime_checkable
185 class ModelBuilderProtocol(Protocol):
186 @classmethod
187 def build(
188 cls: type[_T],
189 *,
190 response: Response,
191 data: object,
192 ) -> _T: ...
193
194
195 Headers = Mapping[str, Union[str, Omit]]
196
197
198 class HeadersLikeProtocol(Protocol):
199 def get(self, __key: str) -> str | None: ...
200
201
202 HeadersLike = Union[Headers, HeadersLikeProtocol]
203
204 ResponseT = TypeVar(
205 "ResponseT",
206 bound=Union[
207 object,
208 str,
209 None,
210 "BaseModel",
211 List[Any],
212 Dict[str, Any],
213 Response,
214 ModelBuilderProtocol,
215 "APIResponse[Any]",
216 "AsyncAPIResponse[Any]",
217 ],
218 )
219
220 StrBytesIntFloat = Union[str, bytes, int, float]
221
222 # Note: copied from Pydantic
223 # https://github.com/pydantic/pydantic/blob/6f31f8f68ef011f84357330186f603ff295312fd/pydantic/main.py#L79
224 IncEx: TypeAlias = Union[Set[int], Set[str], Mapping[int, Union["IncEx", bool]], Mapping[str, Union["IncEx", bool]]]
225
226 PostParser = Callable[[Any], Any]
227
228
229 @runtime_checkable
230 class InheritsGeneric(Protocol):
231 """Represents a type that has inherited from `Generic`
232
233 The `__orig_bases__` property can be used to determine the resolved
234 type variable for a given base class.
235 """
236
237 __orig_bases__: tuple[_GenericAlias]
238
239
240 class _GenericAlias(Protocol):
241 __origin__: type[object]
242
243
244 class HttpxSendArgs(TypedDict, total=False):
245 auth: httpx2.Auth
246 follow_redirects: bool
247
248
249 _T_co = TypeVar("_T_co", covariant=True)
250
251
252 if TYPE_CHECKING:
253 # This works because str.__contains__ does not accept object (either in typeshed or at runtime)
254 # https://github.com/hauntsaninja/useful_types/blob/5e9710f3875107d068e7679fd7fec9cfab0eff3b/useful_types/__init__.py#L285
255 #
256 # Note: index() and count() methods are intentionally omitted to allow pyright to properly
257 # infer TypedDict types when dict literals are used in lists assigned to SequenceNotStr.
258 class SequenceNotStr(Protocol[_T_co]):
259 @overload
260 def __getitem__(self, index: SupportsIndex, /) -> _T_co: ...
261 @overload
262 def __getitem__(self, index: slice, /) -> Sequence[_T_co]: ...
263 def __contains__(self, value: object, /) -> bool: ...
264 def __len__(self) -> int: ...
265 def __iter__(self) -> Iterator[_T_co]: ...
266 def __reversed__(self) -> Iterator[_T_co]: ...
267 else:
268 # just point this to a normal `Sequence` at runtime to avoid having to special case
269 # deserializing our custom sequence type
270 SequenceNotStr = Sequence