|
7 | 7 |
|
8 | 8 | from __future__ import annotations |
9 | 9 |
|
| 10 | +from collections.abc import Awaitable, Callable |
10 | 11 | from datetime import timedelta |
11 | | -from typing import Any |
| 12 | +from typing import Any, Generic, Literal, TypeVar |
| 13 | + |
| 14 | +T = TypeVar("T") |
| 15 | + |
| 16 | +CacheStatus = Literal["miss", "fresh", "stale", "expired"] |
12 | 17 |
|
13 | 18 | try: |
14 | 19 | from langgraph_api.cache import ( # type: ignore[unresolved-import] |
|
22 | 27 | _cache_set = None |
23 | 28 |
|
24 | 29 |
|
| 30 | +try: |
| 31 | + from langgraph_api.cache import SWRResult # type: ignore[unresolved-import] |
| 32 | + from langgraph_api.cache import swr as _api_swr # type: ignore[unresolved-import] |
| 33 | + |
| 34 | +except ImportError: |
| 35 | + _api_swr = None |
| 36 | + |
| 37 | + class SWRResult(Generic[T]): |
| 38 | + """Result wrapper returned by :func:`swr`.""" |
| 39 | + |
| 40 | + value: T |
| 41 | + status: CacheStatus |
| 42 | + |
| 43 | + async def mutate(self, value: T = ...) -> T: # type: ignore[assignment] |
| 44 | + """Update or revalidate the cached value.""" |
| 45 | + ... |
| 46 | + |
| 47 | + |
25 | 48 | __all__ = [ |
| 49 | + "SWRResult", |
26 | 50 | "cache_get", |
27 | 51 | "cache_set", |
| 52 | + "swr", |
28 | 53 | ] |
29 | 54 |
|
30 | 55 |
|
@@ -60,3 +85,56 @@ async def cache_set(key: str, value: Any, *, ttl: timedelta | None = None) -> No |
60 | 85 | "(https://docs.langchain.com/langsmith/deployments)." |
61 | 86 | ) |
62 | 87 | await _cache_set(key, value, ttl) |
| 88 | + |
| 89 | + |
| 90 | +async def swr( |
| 91 | + key: str, |
| 92 | + loader: Callable[[], Awaitable[T]], |
| 93 | + *, |
| 94 | + fresh_for: timedelta | None = None, |
| 95 | + max_age: timedelta | None = None, |
| 96 | + model: type[T] | None = None, |
| 97 | +) -> SWRResult[T]: |
| 98 | + """Load a cached value using stale-while-revalidate semantics. |
| 99 | +
|
| 100 | + This helper is server-side only and is intended for caching internal async |
| 101 | + dependencies such as auth or metadata lookups. |
| 102 | +
|
| 103 | + Args: |
| 104 | + key: Cache key. |
| 105 | + loader: Async callable that fetches the value on miss/revalidation. |
| 106 | + fresh_for: How long a cached value is considered fresh (no revalidation). |
| 107 | + Defaults to ``timedelta(0)`` so every access triggers a background |
| 108 | + revalidate while still returning the cached value instantly. Values |
| 109 | + above :data:`MAX_CACHE_TTL` are clamped to the backend maximum. |
| 110 | + max_age: Total lifetime of a cached entry. After this, the next access |
| 111 | + blocks on the loader. Defaults to :data:`MAX_CACHE_TTL` (24 h by |
| 112 | + default). Values above :data:`MAX_CACHE_TTL` are clamped to the |
| 113 | + backend maximum. |
| 114 | + model: Optional Pydantic model class. When provided, values are |
| 115 | + serialized via ``model_dump(mode="json")`` before storage and |
| 116 | + deserialized via ``model.model_validate()`` on read. |
| 117 | +
|
| 118 | + Returns: |
| 119 | + An :class:`SWRResult` with ``.value``, ``.status``, and an async |
| 120 | + ``.mutate()`` method. |
| 121 | +
|
| 122 | + Semantics: |
| 123 | + - cache miss: await ``loader()``, store the value, return it |
| 124 | + - fresh hit (age < fresh_for): return the cached value |
| 125 | + - stale hit (fresh_for <= age < max_age): return the cached value |
| 126 | + immediately and trigger a best-effort background refresh |
| 127 | + - expired (age >= max_age): await ``loader()``, store the value, return it |
| 128 | + """ |
| 129 | + if _api_swr is None: |
| 130 | + raise RuntimeError( |
| 131 | + "Cache is only available server-side within the LangGraph Agent Server " |
| 132 | + "(https://docs.langchain.com/langsmith/deployments)." |
| 133 | + ) |
| 134 | + if fresh_for is None: |
| 135 | + fresh_for = timedelta(0) |
| 136 | + if max_age is None: |
| 137 | + max_age = timedelta(days=1) |
| 138 | + return await _api_swr( |
| 139 | + key, loader, fresh_for=fresh_for, max_age=max_age, model=model |
| 140 | + ) |
0 commit comments