Coverage for langsmith/_internal/_cache_utils.py: 0%
27 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-11-05 18:36 -0800
« prev ^ index » next coverage.py v7.6.1, created at 2024-11-05 18:36 -0800
1"""Provide utilities for managing caching in LangSmith.
3Includes a CacheManager class that handles the lifecycle of caching
4operations, allowing for easy setup and teardown of caching contexts.
5"""
7import pathlib
8from typing import Optional, Sequence, Union
10from langsmith import utils
13class CacheManager:
14 """Manage caching operations for LangSmith.
16 Provides methods to start and stop caching, and can be used
17 as a context manager for automatic cache management.
19 Attributes:
20 path (Optional[Union[str, pathlib.Path]]): The path to the cache file.
21 ignore_hosts (Optional[Sequence[str]]): A list of hosts to ignore in caching.
22 context_manager: The context manager for caching operations.
23 context: The context object for the current caching session.
24 """
26 def __init__(
27 self,
28 path: Optional[Union[str, pathlib.Path]],
29 ignore_hosts: Optional[Sequence[str]] = None,
30 ):
31 """Initialize the CacheManager.
33 Args:
34 path: The path to the cache file.
35 ignore_hosts: A list of hosts to ignore in caching.
36 """
37 self.path = path
38 self.ignore_hosts = ignore_hosts
39 self.context_manager = None
40 self.context = None
42 def start_caching(self):
43 """Start the caching session.
45 Returns:
46 self: The CacheManager instance.
48 Raises:
49 RuntimeError: If caching is already started.
50 """
51 if self.context is not None:
52 raise RuntimeError("Caching is already started")
54 self.context_manager = utils.with_optional_cache(self.path, self.ignore_hosts)
55 if self.context_manager:
56 self.context = self.context_manager.__enter__()
57 return self
59 def close(self):
60 """Close the current caching session.
62 Raises:
63 RuntimeError: If caching is not started.
64 """
65 if self.context_manager is not None:
66 self.context_manager.__exit__(None, None, None)
67 if self.context is None:
68 raise RuntimeError("Caching is not started")
69 self.context = None
70 self.context_manager = None
72 def __enter__(self):
73 """Enter the context manager, starting the caching session.
75 Returns:
76 self: The CacheManager instance with caching started.
77 """
78 return self.start_caching()
80 def __exit__(self, exc_type, exc_value, traceback):
81 """Exit the context manager, closing the caching session.
83 Args:
84 exc_type: The type of the exception that caused the context to be exited.
85 exc_value: The instance of the exception.
86 traceback: A traceback object encoding the stack trace.
87 """
88 self.close()