|
3 | 3 | import logging |
4 | 4 | from pathlib import Path |
5 | 5 | import concurrent.futures |
6 | | -from typing import List, TYPE_CHECKING, Union, cast, Optional |
| 6 | +from typing import List, TYPE_CHECKING, Union, cast, Optional, Dict |
| 7 | +from functools import lru_cache |
7 | 8 |
|
8 | 9 | from humanloop.types import FileType, PromptResponse, AgentResponse, ToolResponse, DatasetResponse, EvaluatorResponse, FlowResponse |
9 | 10 | from humanloop.core.api_error import ApiError |
|
21 | 22 | logger.addHandler(console_handler) |
22 | 23 |
|
23 | 24 | class SyncClient: |
24 | | - """Client for managing synchronization between local filesystem and Humanloop.""" |
| 25 | + """Client for managing synchronization between local filesystem and Humanloop. |
| 26 | + |
| 27 | + This client provides file synchronization between Humanloop and the local filesystem, |
| 28 | + with built-in caching for improved performance. The cache uses Python's LRU (Least |
| 29 | + Recently Used) cache to automatically manage memory usage by removing least recently |
| 30 | + accessed files when the cache is full. |
| 31 | + |
| 32 | + The cache is automatically updated when files are pulled or saved, and can be |
| 33 | + manually cleared using the clear_cache() method. |
| 34 | + """ |
25 | 35 |
|
26 | 36 | def __init__( |
27 | 37 | self, |
28 | 38 | client: "BaseHumanloop", |
29 | 39 | base_dir: str = "humanloop", |
30 | | - max_workers: Optional[int] = None |
| 40 | + cache_size: int = 100 |
31 | 41 | ): |
32 | 42 | """ |
33 | 43 | Parameters |
34 | 44 | ---------- |
35 | 45 | client: Humanloop client instance |
36 | 46 | base_dir: Base directory for synced files (default: "humanloop") |
37 | | - max_workers: Maximum number of worker threads (default: CPU count * 2) |
| 47 | + cache_size: Maximum number of files to cache (default: 100) |
38 | 48 | """ |
39 | 49 | self.client = client |
40 | 50 | self.base_dir = Path(base_dir) |
41 | | - self.max_workers = max_workers or multiprocessing.cpu_count() * 2 |
| 51 | + self._cache_size = cache_size |
| 52 | + # Create a new cached version of get_file_content with the specified cache size |
| 53 | + self.get_file_content = lru_cache(maxsize=cache_size)(self._get_file_content_impl) |
| 54 | + |
| 55 | + def _get_file_content_impl(self, path: str, file_type: FileType) -> Optional[str]: |
| 56 | + """Implementation of get_file_content without the cache decorator. |
| 57 | + |
| 58 | + This is the actual implementation that gets wrapped by lru_cache. |
| 59 | + """ |
| 60 | + try: |
| 61 | + # Construct path to local file |
| 62 | + local_path = self.base_dir / path |
| 63 | + # Add appropriate extension |
| 64 | + local_path = local_path.parent / f"{local_path.stem}.{file_type}" |
| 65 | + |
| 66 | + if local_path.exists(): |
| 67 | + # Read the file content |
| 68 | + with open(local_path) as f: |
| 69 | + file_content = f.read() |
| 70 | + logger.debug(f"Using local file content from {local_path}") |
| 71 | + return file_content |
| 72 | + else: |
| 73 | + logger.warning(f"Local file not found: {local_path}, falling back to API") |
| 74 | + return None |
| 75 | + except Exception as e: |
| 76 | + logger.error(f"Error reading local file: {e}, falling back to API") |
| 77 | + return None |
| 78 | + |
| 79 | + def get_file_content(self, path: str, file_type: FileType) -> Optional[str]: |
| 80 | + """Get the content of a file from cache or filesystem. |
| 81 | + |
| 82 | + This method uses an LRU cache to store file contents. When the cache is full, |
| 83 | + the least recently accessed files are automatically removed to make space. |
| 84 | + |
| 85 | + Args: |
| 86 | + path: The normalized path to the file (without extension) |
| 87 | + file_type: The type of file (prompt or agent) |
| 88 | + |
| 89 | + Returns: |
| 90 | + The file content if found, None otherwise |
| 91 | + """ |
| 92 | + return self._get_file_content_impl(path, file_type) |
| 93 | + |
| 94 | + def clear_cache(self) -> None: |
| 95 | + """Clear the LRU cache.""" |
| 96 | + self.get_file_content.cache_clear() |
42 | 97 |
|
43 | 98 | def _normalize_path(self, path: str) -> str: |
44 | 99 | """Normalize the path by: |
@@ -103,6 +158,10 @@ def _save_serialized_file(self, serialized_content: str, file_path: str, file_ty |
103 | 158 | # Write content to file |
104 | 159 | with open(new_path, "w") as f: |
105 | 160 | f.write(serialized_content) |
| 161 | + |
| 162 | + # Clear the cache for this file to ensure we get fresh content next time |
| 163 | + self.clear_cache() |
| 164 | + |
106 | 165 | logger.info(f"Syncing {file_type} {file_path}") |
107 | 166 | except Exception as e: |
108 | 167 | logger.error(f"Failed to sync {file_type} {file_path}: {str(e)}") |
|
0 commit comments