Debian Codegraph @

src/anthropic/_utils/_utils.py

raw
1 from __future__ import annotations
2
3 import os
4 import re
5 import inspect
6 import functools
7 from typing import (
8 Any,
9 Tuple,
10 Mapping,
11 TypeVar,
12 Callable,
13 Iterable,
14 Sequence,
15 cast,
16 overload,
17 )
18 from pathlib import Path
19 from datetime import date, datetime
20 from typing_extensions import TypeGuard, get_args
21
22 import sniffio
23
24 from .._types import Omit, NotGiven, FileTypes, ArrayFormat, HeadersLike
25
26 _T = TypeVar("_T")
27 _TupleT = TypeVar("_TupleT", bound=Tuple[object, ...])
28 _MappingT = TypeVar("_MappingT", bound=Mapping[str, object])
29 _SequenceT = TypeVar("_SequenceT", bound=Sequence[object])
30 CallableT = TypeVar("CallableT", bound=Callable[..., Any])
31
32
33 def flatten(t: Iterable[Iterable[_T]]) -> list[_T]:
34 return [item for sublist in t for item in sublist]
35
36
37 def extract_files(
38 # TODO: this needs to take Dict but variance issues.....
39 # create protocol type ?
40 query: Mapping[str, object],
41 *,
42 paths: Sequence[Sequence[str]],
43 array_format: ArrayFormat = "brackets",
44 ) -> list[tuple[str, FileTypes]]:
45 """Recursively extract files from the given dictionary based on specified paths.
46
47 A path may look like this ['foo', 'files', '<array>', 'data'].
48
49 ``array_format`` controls how ``<array>`` segments contribute to the emitted
50 field name. Supported values: ``"brackets"`` (``foo[]``), ``"repeat"`` and
51 ``"comma"`` (``foo``), ``"indices"`` (``foo[0]``, ``foo[1]``).
52
53 Note: this mutates the given dictionary.
54 """
55 files: list[tuple[str, FileTypes]] = []
56 for path in paths:
57 files.extend(_extract_items(query, path, index=0, flattened_key=None, array_format=array_format))
58 return files
59
60
61 def _array_suffix(array_format: ArrayFormat, array_index: int) -> str:
62 if array_format == "brackets":
63 return "[]"
64 if array_format == "indices":
65 return f"[{array_index}]"
66 if array_format == "repeat" or array_format == "comma":
67 # Both repeat the bare field name for each file part; there is no
68 # meaningful way to comma-join binary parts.
69 return ""
70 raise NotImplementedError(
71 f"Unknown array_format value: {array_format}, choose from {', '.join(get_args(ArrayFormat))}"
72 )
73
74
75 def _extract_items(
76 obj: object,
77 path: Sequence[str],
78 *,
79 index: int,
80 flattened_key: str | None,
81 array_format: ArrayFormat,
82 ) -> list[tuple[str, FileTypes]]:
83 try:
84 key = path[index]
85 except IndexError:
86 if not is_given(obj):
87 # no value was provided - we can safely ignore
88 return []
89
90 # cyclical import
91 from .._files import assert_is_file_content
92
93 # We have exhausted the path, return the entry we found.
94 assert flattened_key is not None
95
96 if is_list(obj):
97 files: list[tuple[str, FileTypes]] = []
98 for array_index, entry in enumerate(obj):
99 suffix = _array_suffix(array_format, array_index)
100 emitted_key = (flattened_key + suffix) if flattened_key else suffix
101 assert_is_file_content(entry, key=emitted_key)
102 files.append((emitted_key, cast(FileTypes, entry)))
103 return files
104
105 assert_is_file_content(obj, key=flattened_key)
106 return [(flattened_key, cast(FileTypes, obj))]
107
108 index += 1
109 if is_dict(obj):
110 try:
111 # Remove the field if there are no more dict keys in the path,
112 # only "<array>" traversal markers or end.
113 if all(p == "<array>" for p in path[index:]):
114 item = obj.pop(key)
115 else:
116 item = obj[key]
117 except KeyError:
118 # Key was not present in the dictionary, this is not indicative of an error
119 # as the given path may not point to a required field. We also do not want
120 # to enforce required fields as the API may differ from the spec in some cases.
121 return []
122 if flattened_key is None:
123 flattened_key = key
124 else:
125 flattened_key += f"[{key}]"
126 return _extract_items(
127 item,
128 path,
129 index=index,
130 flattened_key=flattened_key,
131 array_format=array_format,
132 )
133 elif is_list(obj):
134 if key != "<array>":
135 return []
136
137 return flatten(
138 [
139 _extract_items(
140 item,
141 path,
142 index=index,
143 flattened_key=(
144 (flattened_key if flattened_key is not None else "") + _array_suffix(array_format, array_index)
145 ),
146 array_format=array_format,
147 )
148 for array_index, item in enumerate(obj)
149 ]
150 )
151
152 # Something unexpected was passed, just ignore it.
153 return []
154
155
156 def is_given(obj: _T | NotGiven | Omit) -> TypeGuard[_T]:
157 return not isinstance(obj, NotGiven) and not isinstance(obj, Omit)
158
159
160 # Type safe methods for narrowing types with TypeVars.
161 # The default narrowing for isinstance(obj, dict) is dict[unknown, unknown],
162 # however this cause Pyright to rightfully report errors. As we know we don't
163 # care about the contained types we can safely use `object` in its place.
164 #
165 # There are two separate functions defined, `is_*` and `is_*_t` for different use cases.
166 # `is_*` is for when you're dealing with an unknown input
167 # `is_*_t` is for when you're narrowing a known union type to a specific subset
168
169
170 def is_tuple(obj: object) -> TypeGuard[tuple[object, ...]]:
171 return isinstance(obj, tuple)
172
173
174 def is_tuple_t(obj: _TupleT | object) -> TypeGuard[_TupleT]:
175 return isinstance(obj, tuple)
176
177
178 def is_sequence(obj: object) -> TypeGuard[Sequence[object]]:
179 return isinstance(obj, Sequence)
180
181
182 def is_sequence_t(obj: _SequenceT | object) -> TypeGuard[_SequenceT]:
183 return isinstance(obj, Sequence)
184
185
186 def is_mapping(obj: object) -> TypeGuard[Mapping[str, object]]:
187 return isinstance(obj, Mapping)
188
189
190 def is_mapping_t(obj: _MappingT | object) -> TypeGuard[_MappingT]:
191 return isinstance(obj, Mapping)
192
193
194 def is_dict(obj: object) -> TypeGuard[dict[object, object]]:
195 return isinstance(obj, dict)
196
197
198 def is_list(obj: object) -> TypeGuard[list[object]]:
199 return isinstance(obj, list)
200
201
202 def is_iterable(obj: object) -> TypeGuard[Iterable[object]]:
203 return isinstance(obj, Iterable)
204
205
206 # copied from https://github.com/Rapptz/RoboDanny
207 def human_join(seq: Sequence[str], *, delim: str = ", ", final: str = "or") -> str:
208 size = len(seq)
209 if size == 0:
210 return ""
211
212 if size == 1:
213 return seq[0]
214
215 if size == 2:
216 return f"{seq[0]} {final} {seq[1]}"
217
218 return delim.join(seq[:-1]) + f" {final} {seq[-1]}"
219
220
221 def quote(string: str) -> str:
222 """Add single quotation marks around the given string. Does *not* do any escaping."""
223 return f"'{string}'"
224
225
226 def required_args(*variants: Sequence[str]) -> Callable[[CallableT], CallableT]:
227 """Decorator to enforce a given set of arguments or variants of arguments are passed to the decorated function.
228
229 Useful for enforcing runtime validation of overloaded functions.
230
231 Example usage:
232 ```py
233 @overload
234 def foo(*, a: str) -> str: ...
235
236
237 @overload
238 def foo(*, b: bool) -> str: ...
239
240
241 # This enforces the same constraints that a static type checker would
242 # i.e. that either a or b must be passed to the function
243 @required_args(["a"], ["b"])
244 def foo(*, a: str | None = None, b: bool | None = None) -> str: ...
245 ```
246 """
247
248 def inner(func: CallableT) -> CallableT:
249 params = inspect.signature(func).parameters
250 positional = [
251 name
252 for name, param in params.items()
253 if param.kind
254 in {
255 param.POSITIONAL_ONLY,
256 param.POSITIONAL_OR_KEYWORD,
257 }
258 ]
259
260 @functools.wraps(func)
261 def wrapper(*args: object, **kwargs: object) -> object:
262 given_params: set[str] = set()
263 for i, _ in enumerate(args):
264 try:
265 given_params.add(positional[i])
266 except IndexError:
267 raise TypeError(
268 f"{func.__name__}() takes {len(positional)} argument(s) but {len(args)} were given"
269 ) from None
270
271 for key in kwargs.keys():
272 given_params.add(key)
273
274 for variant in variants:
275 matches = all((param in given_params for param in variant))
276 if matches:
277 break
278 else: # no break
279 if len(variants) > 1:
280 variations = human_join(
281 ["(" + human_join([quote(arg) for arg in variant], final="and") + ")" for variant in variants]
282 )
283 msg = f"Missing required arguments; Expected either {variations} arguments to be given"
284 else:
285 assert len(variants) > 0
286
287 # TODO: this error message is not deterministic
288 missing = list(set(variants[0]) - given_params)
289 if len(missing) > 1:
290 msg = f"Missing required arguments: {human_join([quote(arg) for arg in missing])}"
291 else:
292 msg = f"Missing required argument: {quote(missing[0])}"
293 raise TypeError(msg)
294 return func(*args, **kwargs)
295
296 return wrapper # type: ignore
297
298 return inner
299
300
301 _K = TypeVar("_K")
302 _V = TypeVar("_V")
303
304
305 @overload
306 def strip_not_given(obj: None) -> None: ...
307
308
309 @overload
310 def strip_not_given(obj: Mapping[_K, _V | NotGiven]) -> dict[_K, _V]: ...
311
312
313 @overload
314 def strip_not_given(obj: object) -> object: ...
315
316
317 def strip_not_given(obj: object | None) -> object:
318 """Remove all top-level keys where their values are instances of `NotGiven`"""
319 if obj is None:
320 return None
321
322 if not is_mapping(obj):
323 return obj
324
325 return {key: value for key, value in obj.items() if not isinstance(value, NotGiven)}
326
327
328 @overload
329 def strip_omit(obj: None) -> None: ...
330
331
332 @overload
333 def strip_omit(obj: Mapping[_K, _V | Omit]) -> dict[_K, _V]: ...
334
335
336 @overload
337 def strip_omit(obj: object) -> object: ...
338
339
340 def strip_omit(obj: object | None) -> object:
341 """Remove all top-level keys where their values are instances of `Omit`"""
342 if obj is None:
343 return None
344
345 if not is_mapping(obj):
346 return obj
347
348 return {key: value for key, value in obj.items() if not isinstance(value, Omit)}
349
350
351 def coerce_integer(val: str) -> int:
352 return int(val, base=10)
353
354
355 def coerce_float(val: str) -> float:
356 return float(val)
357
358
359 def coerce_boolean(val: str) -> bool:
360 return val == "true" or val == "1" or val == "on"
361
362
363 def maybe_coerce_integer(val: str | None) -> int | None:
364 if val is None:
365 return None
366 return coerce_integer(val)
367
368
369 def maybe_coerce_float(val: str | None) -> float | None:
370 if val is None:
371 return None
372 return coerce_float(val)
373
374
375 def maybe_coerce_boolean(val: str | None) -> bool | None:
376 if val is None:
377 return None
378 return coerce_boolean(val)
379
380
381 def removeprefix(string: str, prefix: str) -> str:
382 """Remove a prefix from a string.
383
384 Backport of `str.removeprefix` for Python < 3.9
385 """
386 if string.startswith(prefix):
387 return string[len(prefix) :]
388 return string
389
390
391 def removesuffix(string: str, suffix: str) -> str:
392 """Remove a suffix from a string.
393
394 Backport of `str.removesuffix` for Python < 3.9
395 """
396 if string.endswith(suffix):
397 return string[: -len(suffix)]
398 return string
399
400
401 def file_from_path(path: str) -> FileTypes:
402 contents = Path(path).read_bytes()
403 file_name = os.path.basename(path)
404 return (file_name, contents)
405
406
407 def get_required_header(headers: HeadersLike, header: str) -> str:
408 lower_header = header.lower()
409 if is_mapping_t(headers):
410 # mypy doesn't understand the type narrowing here
411 for k, v in headers.items(): # type: ignore
412 if k.lower() == lower_header and isinstance(v, str):
413 return v
414
415 # to deal with the case where the header looks like Stainless-Event-Id
416 intercaps_header = re.sub(r"([^\w])(\w)", lambda pat: pat.group(1) + pat.group(2).upper(), header.capitalize())
417
418 for normalized_header in [header, lower_header, header.upper(), intercaps_header]:
419 value = headers.get(normalized_header)
420 if value:
421 return value
422
423 raise ValueError(f"Could not find {header} header")
424
425
426 def get_async_library() -> str:
427 try:
428 return sniffio.current_async_library()
429 except Exception:
430 return "false"
431
432
433 def lru_cache(*, maxsize: int | None = 128) -> Callable[[CallableT], CallableT]:
434 """A version of functools.lru_cache that retains the type signature
435 for the wrapped function arguments.
436 """
437 wrapper = functools.lru_cache( # noqa: TID251
438 maxsize=maxsize,
439 )
440 return cast(Any, wrapper) # type: ignore[no-any-return]
441
442
443 def json_safe(data: object) -> object:
444 """Translates a mapping / sequence recursively in the same fashion
445 as `pydantic` v2's `model_dump(mode="json")`.
446 """
447 if is_mapping(data):
448 return {json_safe(key): json_safe(value) for key, value in data.items()}
449
450 if is_iterable(data) and not isinstance(data, (str, bytes, bytearray)):
451 return [json_safe(item) for item in data]
452
453 if isinstance(data, (datetime, date)):
454 return data.isoformat()
455
456 return data