hammad-python 0.0.10__py3-none-any.whl → 0.0.12__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. hammad/__init__.py +177 -10
  2. hammad/_core/__init__.py +1 -0
  3. hammad/_core/_utils/__init__.py +4 -0
  4. hammad/_core/_utils/_import_utils.py +182 -0
  5. hammad/ai/__init__.py +59 -0
  6. hammad/ai/_utils.py +142 -0
  7. hammad/ai/completions/__init__.py +44 -0
  8. hammad/ai/completions/client.py +729 -0
  9. hammad/ai/completions/create.py +686 -0
  10. hammad/ai/completions/types.py +711 -0
  11. hammad/ai/completions/utils.py +374 -0
  12. hammad/ai/embeddings/__init__.py +35 -0
  13. hammad/ai/embeddings/client/__init__.py +1 -0
  14. hammad/ai/embeddings/client/base_embeddings_client.py +26 -0
  15. hammad/ai/embeddings/client/fastembed_text_embeddings_client.py +200 -0
  16. hammad/ai/embeddings/client/litellm_embeddings_client.py +288 -0
  17. hammad/ai/embeddings/create.py +159 -0
  18. hammad/ai/embeddings/types.py +69 -0
  19. hammad/base/__init__.py +35 -0
  20. hammad/base/fields.py +546 -0
  21. hammad/base/model.py +1078 -0
  22. hammad/base/utils.py +280 -0
  23. hammad/cache/__init__.py +48 -0
  24. hammad/cache/base_cache.py +181 -0
  25. hammad/cache/cache.py +169 -0
  26. hammad/cache/decorators.py +261 -0
  27. hammad/cache/file_cache.py +80 -0
  28. hammad/cache/ttl_cache.py +74 -0
  29. hammad/cli/__init__.py +33 -0
  30. hammad/cli/animations.py +604 -0
  31. hammad/cli/plugins.py +781 -0
  32. hammad/cli/styles/__init__.py +55 -0
  33. hammad/cli/styles/settings.py +139 -0
  34. hammad/cli/styles/types.py +358 -0
  35. hammad/cli/styles/utils.py +480 -0
  36. hammad/configuration/__init__.py +35 -0
  37. hammad/configuration/configuration.py +564 -0
  38. hammad/data/__init__.py +39 -0
  39. hammad/data/collections/__init__.py +34 -0
  40. hammad/data/collections/base_collection.py +58 -0
  41. hammad/data/collections/collection.py +452 -0
  42. hammad/data/collections/searchable_collection.py +556 -0
  43. hammad/data/collections/vector_collection.py +603 -0
  44. hammad/data/databases/__init__.py +21 -0
  45. hammad/data/databases/database.py +902 -0
  46. hammad/json/__init__.py +21 -0
  47. hammad/{utils/json → json}/converters.py +4 -1
  48. hammad/logging/__init__.py +35 -0
  49. hammad/logging/decorators.py +834 -0
  50. hammad/logging/logger.py +954 -0
  51. hammad/multimodal/__init__.py +24 -0
  52. hammad/multimodal/audio.py +96 -0
  53. hammad/multimodal/image.py +80 -0
  54. hammad/multithreading/__init__.py +304 -0
  55. hammad/pydantic/__init__.py +43 -0
  56. hammad/{utils/pydantic → pydantic}/converters.py +2 -1
  57. hammad/pydantic/models/__init__.py +28 -0
  58. hammad/pydantic/models/arbitrary_model.py +46 -0
  59. hammad/pydantic/models/cacheable_model.py +79 -0
  60. hammad/pydantic/models/fast_model.py +318 -0
  61. hammad/pydantic/models/function_model.py +176 -0
  62. hammad/pydantic/models/subscriptable_model.py +63 -0
  63. hammad/text/__init__.py +82 -0
  64. hammad/text/converters.py +723 -0
  65. hammad/{utils/markdown/formatting.py → text/markdown.py} +25 -23
  66. hammad/text/text.py +1066 -0
  67. hammad/types/__init__.py +11 -0
  68. hammad/types/file.py +358 -0
  69. hammad/{utils/typing/utils.py → typing/__init__.py} +142 -15
  70. hammad/web/__init__.py +43 -0
  71. hammad/web/http/__init__.py +1 -0
  72. hammad/web/http/client.py +944 -0
  73. hammad/web/models.py +245 -0
  74. hammad/web/openapi/client.py +740 -0
  75. hammad/web/search/__init__.py +1 -0
  76. hammad/web/search/client.py +988 -0
  77. hammad/web/utils.py +472 -0
  78. hammad/yaml/__init__.py +30 -0
  79. hammad/yaml/converters.py +19 -0
  80. {hammad_python-0.0.10.dist-info → hammad_python-0.0.12.dist-info}/METADATA +16 -7
  81. hammad_python-0.0.12.dist-info/RECORD +85 -0
  82. hammad/cache.py +0 -675
  83. hammad/database.py +0 -447
  84. hammad/logger.py +0 -273
  85. hammad/types/color.py +0 -951
  86. hammad/utils/markdown/__init__.py +0 -0
  87. hammad/utils/markdown/converters.py +0 -506
  88. hammad/utils/pydantic/__init__.py +0 -0
  89. hammad/utils/text/__init__.py +0 -0
  90. hammad/utils/text/converters.py +0 -229
  91. hammad/utils/typing/__init__.py +0 -0
  92. hammad_python-0.0.10.dist-info/RECORD +0 -22
  93. /hammad/{utils/__init__.py → py.typed} +0 -0
  94. /hammad/{utils/json → web/openapi}/__init__.py +0 -0
  95. {hammad_python-0.0.10.dist-info → hammad_python-0.0.12.dist-info}/WHEEL +0 -0
  96. {hammad_python-0.0.10.dist-info → hammad_python-0.0.12.dist-info}/licenses/LICENSE +0 -0
hammad/cache.py DELETED
@@ -1,675 +0,0 @@
1
- """✼ agentspace.cache
2
-
3
- Contains helpful resources for creating simple cache systems, and
4
- decorators that implement "automatic" hashing & caching of function calls.
5
- """
6
-
7
- from __future__ import annotations
8
-
9
- import hashlib
10
- import os
11
- from functools import wraps
12
- import inspect
13
- import pickle
14
- import time
15
- from dataclasses import dataclass
16
- from collections import OrderedDict
17
- from pathlib import Path
18
- from typing import (
19
- Any,
20
- Callable,
21
- TypeVar,
22
- Tuple,
23
- Optional,
24
- Protocol,
25
- overload,
26
- ParamSpec,
27
- Literal,
28
- get_args,
29
- TypeAlias,
30
- Union,
31
- )
32
-
33
- __all__ = [
34
- "cached",
35
- "auto_cached",
36
- "Cache",
37
- "TTLCache",
38
- "DiskCache",
39
- "CacheType",
40
- "CacheParams",
41
- "CacheReturn",
42
- ]
43
-
44
-
45
- # -----------------------------------------------------------------------------
46
- # TYPES
47
- # -----------------------------------------------------------------------------
48
-
49
- CacheType: TypeAlias = Literal["ttl", "disk"]
50
- """Type of caches that can be created using `agentspace`.
51
-
52
- - `"ttl"`: Time-to-live cache.
53
- - `"disk"`: Disk-based cache.
54
- """
55
-
56
- CacheParams = ParamSpec("CacheParams")
57
- """Parameter specification for cache functions."""
58
-
59
- CacheReturn = TypeVar("CacheReturn")
60
- """Return type for cache functions."""
61
-
62
-
63
- # -----------------------------------------------------------------------------
64
- # GLOBAL (Internal) CACHE
65
- # -----------------------------------------------------------------------------
66
-
67
-
68
- _agentspace_CACHE: None | BaseCache = None
69
- """Internal cache for the `agentspace` package. Instantiated when needed."""
70
-
71
-
72
- def _get_cache() -> BaseCache:
73
- """Returns the global cache instance, creating it if necessary."""
74
- global _agentspace_CACHE
75
- if _agentspace_CACHE is None:
76
- _agentspace_CACHE = TTLCache(maxsize=1000, ttl=3600)
77
- return _agentspace_CACHE
78
-
79
-
80
- # -----------------------------------------------------------------------------
81
- # BASE
82
- # -----------------------------------------------------------------------------
83
-
84
-
85
- @dataclass
86
- class BaseCache:
87
- """Base class for all caches created using `agentspace`."""
88
-
89
- type: CacheType
90
- """Type of cache."""
91
-
92
- def __post_init__(self) -> None:
93
- """Post-initialization hook."""
94
- if self.type not in get_args(CacheType):
95
- raise ValueError(f"Invalid cache type: {self.type}")
96
-
97
- def __contains__(self, key: str) -> bool:
98
- """Check if key exists in cache."""
99
- raise NotImplementedError("Subclasses must implement __contains__")
100
-
101
- def __getitem__(self, key: str) -> Any:
102
- """Get value for key."""
103
- raise NotImplementedError("Subclasses must implement __getitem__")
104
-
105
- def __setitem__(self, key: str, value: Any) -> None:
106
- """Set value for key."""
107
- raise NotImplementedError("Subclasses must implement __setitem__")
108
-
109
- def get(self, key: str, default: Any = None) -> Any:
110
- """Get value with default if key doesn't exist."""
111
- try:
112
- return self[key]
113
- except KeyError:
114
- return default
115
-
116
- def clear(self) -> None:
117
- """Clear all cached items."""
118
- raise NotImplementedError("Subclasses must implement clear")
119
-
120
- def make_hashable(self, obj: Any) -> str:
121
- """
122
- Convert any object to a stable hash string.
123
-
124
- Uses SHA-256 to generate consistent hash representations.
125
- Handles nested structures recursively.
126
-
127
- Args:
128
- obj: Object to hash
129
-
130
- Returns:
131
- Hexadecimal hash string
132
- """
133
-
134
- def _hash_obj(data: Any) -> str:
135
- """Internal recursive hashing function with memoization."""
136
- # Handle None first
137
- if data is None:
138
- return "null"
139
-
140
- if isinstance(data, bool):
141
- return f"bool:{data}"
142
- elif isinstance(data, int):
143
- return f"int:{data}"
144
- elif isinstance(data, float):
145
- if data != data: # NaN
146
- return "float:nan"
147
- elif data == float("inf"):
148
- return "float:inf"
149
- elif data == float("-inf"):
150
- return "float:-inf"
151
- else:
152
- return f"float:{data}"
153
- elif isinstance(data, str):
154
- return f"str:{data}"
155
- elif isinstance(data, bytes):
156
- return f"bytes:{data.hex()}"
157
-
158
- # Handle collections
159
- elif isinstance(data, (list, tuple)):
160
- collection_type = "list" if isinstance(data, list) else "tuple"
161
- items = [_hash_obj(item) for item in data]
162
- return f"{collection_type}:[{','.join(items)}]"
163
-
164
- elif isinstance(data, set):
165
- try:
166
- sorted_items = sorted(data, key=lambda x: str(x))
167
- except TypeError:
168
- sorted_items = sorted(
169
- data, key=lambda x: (type(x).__name__, str(x))
170
- )
171
- items = [_hash_obj(item) for item in sorted_items]
172
- return f"set:{{{','.join(items)}}}"
173
-
174
- elif isinstance(data, dict):
175
- try:
176
- sorted_items = sorted(data.items(), key=lambda x: str(x[0]))
177
- except TypeError:
178
- # Fallback for non-comparable keys
179
- sorted_items = sorted(
180
- data.items(), key=lambda x: (type(x[0]).__name__, str(x[0]))
181
- )
182
- pairs = [f"{_hash_obj(k)}:{_hash_obj(v)}" for k, v in sorted_items]
183
- return f"dict:{{{','.join(pairs)}}}"
184
-
185
- elif isinstance(data, type):
186
- module = getattr(data, "__module__", "builtins")
187
- qualname = getattr(data, "__qualname__", data.__name__)
188
- return f"type:{module}.{qualname}"
189
-
190
- elif callable(data):
191
- module = getattr(data, "__module__", "unknown")
192
- qualname = getattr(
193
- data, "__qualname__", getattr(data, "__name__", "unknown_callable")
194
- )
195
-
196
- try:
197
- source = inspect.getsource(data)
198
- normalized_source = " ".join(source.split())
199
- return f"callable:{module}.{qualname}:{hash(normalized_source)}"
200
- except (OSError, TypeError, IndentationError):
201
- return f"callable:{module}.{qualname}"
202
-
203
- elif hasattr(data, "__dict__"):
204
- class_info = (
205
- f"{data.__class__.__module__}.{data.__class__.__qualname__}"
206
- )
207
- obj_dict = {"__class__": class_info, **data.__dict__}
208
- return f"object:{_hash_obj(obj_dict)}"
209
-
210
- elif hasattr(data, "__slots__"):
211
- class_info = (
212
- f"{data.__class__.__module__}.{data.__class__.__qualname__}"
213
- )
214
- slot_dict = {
215
- slot: getattr(data, slot, None)
216
- for slot in data.__slots__
217
- if hasattr(data, slot)
218
- }
219
- obj_dict = {"__class__": class_info, **slot_dict}
220
- return f"slotted_object:{_hash_obj(obj_dict)}"
221
-
222
- else:
223
- try:
224
- repr_str = repr(data)
225
- return f"repr:{type(data).__name__}:{repr_str}"
226
- except Exception:
227
- # Ultimate fallback
228
- return f"unknown:{type(data).__name__}:{id(data)}"
229
-
230
- # Generate the hash representation
231
- hash_representation = _hash_obj(obj)
232
-
233
- # Create final SHA-256 hash
234
- return hashlib.sha256(
235
- hash_representation.encode("utf-8", errors="surrogatepass")
236
- ).hexdigest()
237
-
238
-
239
- # -----------------------------------------------------------------------------
240
- # TTL CACHE
241
- # -----------------------------------------------------------------------------
242
-
243
-
244
- @dataclass
245
- class TTLCache(BaseCache):
246
- """
247
- Thread-safe TTL cache implementation with LRU eviction.
248
-
249
- Uses OrderedDict for efficient LRU tracking and automatic cleanup
250
- of expired entries on access.
251
- """
252
-
253
- maxsize: int = 1000
254
- ttl: int = 3600
255
- type: Literal["ttl"] = "ttl"
256
-
257
- def __post_init__(self):
258
- """Initialize TTL cache after dataclass initialization."""
259
- super().__post_init__()
260
- self._cache: OrderedDict[str, Tuple[Any, float]] = OrderedDict()
261
-
262
- def __contains__(self, key: str) -> bool:
263
- """Check if key exists and is not expired."""
264
- if key in self._cache:
265
- _value, timestamp = self._cache[key]
266
- if time.time() - timestamp <= self.ttl:
267
- self._cache.move_to_end(key)
268
- return True
269
- else:
270
- # Expired, remove it
271
- del self._cache[key]
272
- return False
273
-
274
- def __getitem__(self, key: str) -> Any:
275
- """Get value for key if not expired."""
276
- if key in self:
277
- return self._cache[key][0]
278
- raise KeyError(key)
279
-
280
- def __setitem__(self, key: str, value: Any) -> None:
281
- """Set value with current timestamp."""
282
- if len(self._cache) >= self.maxsize and key not in self._cache:
283
- self._cleanup_expired()
284
-
285
- if len(self._cache) >= self.maxsize:
286
- self._cache.popitem(last=False)
287
-
288
- self._cache[key] = (value, time.time())
289
- self._cache.move_to_end(key)
290
-
291
- def _cleanup_expired(self) -> None:
292
- """Remove all expired entries."""
293
- current_time = time.time()
294
-
295
- expired_keys = [
296
- k
297
- for k, (_, ts) in list(self._cache.items())
298
- if current_time - ts > self.ttl
299
- ]
300
- for k in expired_keys:
301
- if k in self._cache:
302
- del self._cache[k]
303
-
304
- def clear(self) -> None:
305
- """Clear all cached items."""
306
- self._cache.clear()
307
-
308
-
309
- # -----------------------------------------------------------------------------
310
- # DISK CACHE
311
- # -----------------------------------------------------------------------------
312
-
313
-
314
- @dataclass
315
- class DiskCache(BaseCache):
316
- """
317
- Persistent disk-based cache that stores data in a directory.
318
-
319
- Uses pickle for serialization and automatically uses __pycache__ directory
320
- if no cache directory is specified.
321
- """
322
-
323
- location: Optional[str] = None
324
- type: Literal["disk"] = "disk"
325
-
326
- def __post_init__(self):
327
- """Initialize disk cache after dataclass initialization."""
328
- super().__post_init__()
329
- if self.location is None:
330
- self.location = os.path.join(os.getcwd(), "__pycache__")
331
-
332
- self.location_path = Path(self.location)
333
- self.location_path.mkdir(exist_ok=True)
334
-
335
- def _get_cache_path(self, key: str) -> Path:
336
- """Get the file path for a cache key."""
337
- safe_key = hashlib.sha256(key.encode("utf-8")).hexdigest()
338
- return self.location_path / f"cache_{safe_key}.pkl"
339
-
340
- def __contains__(self, key: str) -> bool:
341
- """Check if key exists in cache."""
342
- return self._get_cache_path(key).exists()
343
-
344
- def __getitem__(self, key: str) -> Any:
345
- """Get value for key."""
346
- cache_path = self._get_cache_path(key)
347
- if not cache_path.exists():
348
- raise KeyError(key)
349
-
350
- try:
351
- with open(cache_path, "rb") as f:
352
- return pickle.load(f)
353
- except (pickle.PickleError, OSError) as e:
354
- cache_path.unlink(missing_ok=True)
355
- raise KeyError(key) from e
356
-
357
- def __setitem__(self, key: str, value: Any) -> None:
358
- """Set value for key."""
359
- cache_path = self._get_cache_path(key)
360
- try:
361
- with open(cache_path, "wb") as f:
362
- pickle.dump(value, f)
363
- except (pickle.PickleError, OSError) as e:
364
- cache_path.unlink(missing_ok=True)
365
- raise RuntimeError(f"Failed to cache value for key '{key}': {e}") from e
366
-
367
- def clear(self) -> None:
368
- """Clear all cached items."""
369
- for cache_file in self.location_path.glob("cache_*.pkl"):
370
- try:
371
- cache_file.unlink()
372
- except OSError:
373
- pass
374
-
375
-
376
- # -----------------------------------------------------------------------------
377
- # Primary `Cache` Class -- Used For Factory Initialization
378
- # -----------------------------------------------------------------------------
379
-
380
-
381
- class Cache:
382
- """
383
- Helper factory class for creating cache instances.
384
-
385
- Example usage:
386
- ttl_cache = Cache(type="ttl", maxsize=100, ttl=60)
387
- disk_cache = Cache(type="disk", location="/tmp/cache")
388
- """
389
-
390
- @overload
391
- def __new__(
392
- cls,
393
- type: Literal["ttl"] = "ttl",
394
- *,
395
- maxsize: Optional[int] = None,
396
- ttl: Optional[int] = None,
397
- ) -> TTLCache:
398
- """
399
- Create a new TTL (Time To Live) cache instance.
400
-
401
- Args:
402
- type: The type of cache to create.
403
- maxsize: The maximum number of items to store in the cache.
404
- ttl: The time to live for items in the cache.
405
-
406
- Returns:
407
- A new TTL cache instance.
408
- """
409
- ...
410
-
411
- @overload
412
- def __new__(
413
- cls, type: Literal["disk"], *, location: Optional[str] = None
414
- ) -> DiskCache:
415
- """
416
- Create a new disk cache instance.
417
-
418
- Args:
419
- type: The type of cache to create.
420
- location: The directory to store the cache files.
421
-
422
- Returns:
423
- A new disk cache instance.
424
- """
425
- ...
426
-
427
- def __new__(cls, type: CacheType = "ttl", **kwargs: Any) -> BaseCache:
428
- """
429
- Create a new cache instance.
430
- """
431
- if type == "ttl":
432
- valid_ttl_params = {"maxsize", "ttl"}
433
- ttl_constructor_kwargs = {
434
- k: v
435
- for k, v in kwargs.items()
436
- if k in valid_ttl_params and v is not None
437
- }
438
- return TTLCache(type=type, **ttl_constructor_kwargs)
439
- elif type == "disk":
440
- valid_disk_params = {"location"}
441
- disk_constructor_kwargs = {
442
- k: v
443
- for k, v in kwargs.items()
444
- if k in valid_disk_params and v is not None
445
- }
446
- return DiskCache(type=type, **disk_constructor_kwargs)
447
- else:
448
- supported_types_tuple = get_args(CacheType)
449
- raise ValueError(
450
- f"Unsupported cache type: {type}. Supported types are: {supported_types_tuple}"
451
- )
452
-
453
-
454
- # -----------------------------------------------------------------------------
455
- # Decorators
456
- # -----------------------------------------------------------------------------
457
-
458
-
459
- @overload
460
- def cached(
461
- func: Callable[CacheParams, CacheReturn],
462
- ) -> Callable[CacheParams, CacheReturn]:
463
- """Decorator with automatic key generation, using the global CACHE."""
464
- ...
465
-
466
-
467
- @overload
468
- def cached(
469
- *,
470
- key: Optional[Callable[..., str]] = None,
471
- ttl: Optional[int] = None,
472
- maxsize: Optional[int] = None,
473
- cache: Optional[BaseCache] = None,
474
- ) -> Callable[[Callable[CacheParams, CacheReturn]], Callable[CacheParams, CacheReturn]]:
475
- """Decorator with custom key function and/or cache settings."""
476
- ...
477
-
478
-
479
- def cached(
480
- func: Optional[Callable[CacheParams, CacheReturn]] = None,
481
- *,
482
- key: Optional[Callable[..., str]] = None,
483
- ttl: Optional[int] = None,
484
- maxsize: Optional[int] = None,
485
- cache: Optional[BaseCache] = None,
486
- ) -> Union[
487
- Callable[CacheParams, CacheReturn],
488
- Callable[[Callable[CacheParams, CacheReturn]], Callable[CacheParams, CacheReturn]],
489
- ]:
490
- """
491
- Flexible caching decorator that preserves type hints and signatures.
492
-
493
- Can be used with or without arguments:
494
- - `@cached`: Uses automatic key generation with the global `agentspace.runtime.cache.CACHE`.
495
- - `@cached(key=custom_key_func)`: Uses a custom key generation function.
496
- - `@cached(ttl=300, maxsize=50)`: Creates a new `TTLCache` instance specifically
497
- for the decorated function with the given TTL and maxsize.
498
- - `@cached(cache=my_cache_instance)`: Uses a user-provided cache instance.
499
-
500
- Args:
501
- func: The function to be cached (implicitly passed when used as `@cached`).
502
- key: An optional function that takes the same arguments as `func` and
503
- returns a string key. If `None`, a key is automatically generated.
504
- ttl: Optional. Time-to-live in seconds. If `cache` is not provided and `ttl`
505
- or `maxsize` is set, a new `TTLCache` is created for this function using
506
- these settings.
507
- maxsize: Optional. Maximum number of items in the cache. See `ttl`.
508
- cache: Optional. A specific cache instance (conforming to `BaseCache`)
509
- to use. If provided, `ttl` and `maxsize` arguments (intended for
510
- creating a new per-function cache) are ignored, as the provided
511
- cache instance manages its own lifecycle and capacity.
512
-
513
- Returns:
514
- The decorated function with caching capabilities.
515
- """
516
- effective_cache: BaseCache = _get_cache()
517
-
518
- if cache is not None:
519
- effective_cache = cache
520
- elif ttl is not None or maxsize is not None:
521
- default_maxsize = _get_cache().maxsize
522
- default_ttl = _get_cache().ttl
523
-
524
- effective_cache = TTLCache(
525
- type="ttl",
526
- maxsize=maxsize if maxsize is not None else default_maxsize,
527
- ttl=ttl if ttl is not None else default_ttl,
528
- )
529
- else:
530
- effective_cache = _get_cache()
531
-
532
- def decorator(
533
- f_to_decorate: Callable[CacheParams, CacheReturn],
534
- ) -> Callable[CacheParams, CacheReturn]:
535
- key_func_to_use: Callable[..., str]
536
- if key is None:
537
- sig = inspect.signature(f_to_decorate)
538
-
539
- def auto_key_func(
540
- *args: CacheParams.args, **kwargs: CacheParams.kwargs
541
- ) -> str:
542
- bound_args = sig.bind(*args, **kwargs)
543
- bound_args.apply_defaults()
544
-
545
- key_parts = []
546
- for param_name, param_value in bound_args.arguments.items():
547
- key_parts.append(
548
- f"{param_name}={effective_cache.make_hashable(param_value)}"
549
- )
550
-
551
- return f"{f_to_decorate.__module__}.{f_to_decorate.__qualname__}({','.join(key_parts)})"
552
-
553
- key_func_to_use = auto_key_func
554
- else:
555
- key_func_to_use = key
556
-
557
- @wraps(f_to_decorate)
558
- def wrapper(
559
- *args: CacheParams.args, **kwargs: CacheParams.kwargs
560
- ) -> CacheReturn:
561
- try:
562
- cache_key_value = key_func_to_use(*args, **kwargs)
563
-
564
- if cache_key_value in effective_cache:
565
- return effective_cache[cache_key_value]
566
-
567
- result = f_to_decorate(*args, **kwargs)
568
- effective_cache[cache_key_value] = result
569
- return result
570
-
571
- except Exception:
572
- return f_to_decorate(*args, **kwargs)
573
-
574
- setattr(wrapper, "__wrapped__", f_to_decorate)
575
- return wrapper
576
-
577
- if func is None:
578
- return decorator
579
- else:
580
- return decorator(func)
581
-
582
-
583
- def auto_cached(
584
- *,
585
- ignore: Optional[Tuple[str, ...]] = None,
586
- include: Optional[Tuple[str, ...]] = None,
587
- ttl: Optional[int] = None,
588
- maxsize: Optional[int] = None,
589
- cache: Optional[BaseCache] = None,
590
- ) -> Callable[[Callable[CacheParams, CacheReturn]], Callable[CacheParams, CacheReturn]]:
591
- """
592
- Advanced caching decorator with automatic parameter selection for key generation.
593
-
594
- Automatically generates cache keys based on a selection of the function's
595
- parameters. This decorator internally uses the `cached` decorator.
596
-
597
- Args:
598
- ignore: A tuple of parameter names to exclude from cache key generation.
599
- Cannot be used with `include`.
600
- include: A tuple of parameter names to exclusively include in cache key
601
- generation. All other parameters will be ignored. Cannot be used
602
- with `ignore`.
603
- ttl: Optional. Time-to-live in seconds. Passed to the underlying `cached`
604
- decorator. If `cache` is not provided, this can lead to the creation
605
- of a new `TTLCache` for the decorated function.
606
- maxsize: Optional. Max cache size. Passed to `cached`. See `ttl`.
607
- cache: Optional. A specific cache instance (conforming to `BaseCache`)
608
- to use. This is passed directly to the underlying `cached` decorator.
609
- If provided, `ttl` and `maxsize` arguments might be interpreted
610
- differently by `cached` (see `cached` docstring).
611
-
612
- Returns:
613
- A decorator function that, when applied, will cache the results of
614
- the decorated function.
615
-
616
- Example:
617
- ```python
618
- from agentspace.runtime.cache import auto_cached, create_cache
619
-
620
- # Example of using a custom cache instance
621
- my_user_cache = create_cache(cache_type="ttl", ttl=600, maxsize=50)
622
-
623
- @auto_cached(ignore=('debug_mode', 'logger'), cache=my_user_cache)
624
- def fetch_user_data(user_id: int, debug_mode: bool = False, logger: Any = None):
625
- # ... expensive operation to fetch data ...
626
- print(f"Fetching data for user {user_id}")
627
- return {"id": user_id, "data": "some_data"}
628
-
629
- # Example of per-function TTL without a pre-defined cache
630
- @auto_cached(include=('url',), ttl=30)
631
- def fetch_url_content(url: str, timeout: int = 10):
632
- # ... expensive operation to fetch URL ...
633
- print(f"Fetching content from {url}")
634
- return f"Content from {url}"
635
- ```
636
- """
637
- if ignore and include:
638
- raise ValueError("Cannot specify both 'ignore' and 'include' in auto_cached")
639
-
640
- def actual_decorator(
641
- func_to_decorate: Callable[CacheParams, CacheReturn],
642
- ) -> Callable[CacheParams, CacheReturn]:
643
- sig = inspect.signature(func_to_decorate)
644
-
645
- def auto_key_generator(
646
- *args: CacheParams.args, **kwargs: CacheParams.kwargs
647
- ) -> str:
648
- bound_args = sig.bind(*args, **kwargs)
649
- bound_args.apply_defaults()
650
-
651
- params_for_key = bound_args.arguments.copy()
652
-
653
- if include is not None:
654
- params_for_key = {
655
- k: v for k, v in params_for_key.items() if k in include
656
- }
657
- elif ignore is not None:
658
- params_for_key = {
659
- k: v for k, v in params_for_key.items() if k not in ignore
660
- }
661
-
662
- # Use the effective cache's make_hashable method
663
- effective_cache = cache if cache is not None else _get_cache()
664
- key_parts = [
665
- f"{k}={effective_cache.make_hashable(v)}"
666
- for k, v in sorted(params_for_key.items())
667
- ]
668
- return f"{func_to_decorate.__module__}.{func_to_decorate.__qualname__}({','.join(key_parts)})"
669
-
670
- configured_cached_decorator = cached(
671
- key=auto_key_generator, ttl=ttl, maxsize=maxsize, cache=cache
672
- )
673
- return configured_cached_decorator(func_to_decorate)
674
-
675
- return actual_decorator