|
| 1 | +import fractale.utils as utils |
| 2 | +import shutil |
| 3 | +import os |
| 4 | +import re |
| 5 | +import tempfile |
| 6 | +import collections |
| 7 | + |
| 8 | +def get_context(context): |
| 9 | + """ |
| 10 | + Get or create the context. |
| 11 | + """ |
| 12 | + if isinstance(context, Context): |
| 13 | + return context |
| 14 | + return Context(context) |
| 15 | + |
| 16 | + |
| 17 | +class Context(collections.UserDict): |
| 18 | + """ |
| 19 | + A custom dictionary that allows attribute-style access to keys, |
| 20 | + and extends the 'get' method with a 'required' argument. |
| 21 | + """ |
| 22 | + def __init__(self, *args, **kwargs): |
| 23 | + super().__init__(*args, **kwargs) |
| 24 | + |
| 25 | + # Testing out this idea - instead of requiring specific inputs/outputs, we are going |
| 26 | + # to write to a common context directory, and allow each LLM to discover files and use them |
| 27 | + # as needed. |
| 28 | + workspace = kwargs.get("workspace") |
| 29 | + self.workspace = workspace or tempfile.mkdtemp() |
| 30 | + |
| 31 | + def __getattribute__(self, name): |
| 32 | + """ |
| 33 | + Intercepts all attribute lookups (including methods/functions) |
| 34 | + """ |
| 35 | + try: |
| 36 | + # Step 1: this would be a normal attribute |
| 37 | + attr = object.__getattribute__(self, name) |
| 38 | + except AttributeError: |
| 39 | + # Then handle lookup of dict key by attribute |
| 40 | + return super().__getattribute__(name) |
| 41 | + |
| 42 | + # Step 2: We allow "get" to be called with defaults / required. |
| 43 | + if name == 'get': |
| 44 | + original_get = attr |
| 45 | + |
| 46 | + def custom_get(key, default=None, required=False): |
| 47 | + """ |
| 48 | + Wrapper for the standard dict.get() method. |
| 49 | + Accepts the custom 'required' argument. |
| 50 | + """ |
| 51 | + # Load context if needed |
| 52 | + self.load(key) |
| 53 | + |
| 54 | + if required: |
| 55 | + if key not in self.data: |
| 56 | + raise KeyError(f"Key '{key}' is required but missing.") |
| 57 | + |
| 58 | + # If required and found, just return the value |
| 59 | + return self.data[key] |
| 60 | + else: |
| 61 | + # If not required, use the original dict.get behavior |
| 62 | + return original_get(key, default) |
| 63 | + |
| 64 | + # Return the wrapper function instead of the original method |
| 65 | + return custom_get |
| 66 | + |
| 67 | + # 4. For any other attribute (like keys(), items(), update(), or custom methods) |
| 68 | + # return the attribute we found earlier |
| 69 | + return attr |
| 70 | + |
| 71 | + # 5. Override __getattr__ to handle attribute-style access to dictionary keys |
| 72 | + def __getattr__(self, name): |
| 73 | + """ |
| 74 | + Allows access to dictionary keys as attributes. |
| 75 | + """ |
| 76 | + if name in self.data: |
| 77 | + return self.data[name] |
| 78 | + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") |
| 79 | + |
| 80 | + def __setattr__(self, name, value): |
| 81 | + """ |
| 82 | + Allows setting keys via attribute assignment. |
| 83 | + """ |
| 84 | + # If the attribute name is a reserved name (like 'data'), set it normally |
| 85 | + if name in ('data', '_data'): |
| 86 | + super().__setattr__(name, value) |
| 87 | + |
| 88 | + # Otherwise, treat it as a dictionary key |
| 89 | + else: |
| 90 | + self.data[name] = value |
| 91 | + |
| 92 | + def load(self, key): |
| 93 | + """ |
| 94 | + Load the entire context. We assume that text content has already been added |
| 95 | + to the variable context. |
| 96 | + """ |
| 97 | + context_dir = os.path.join(self.workspace, key) |
| 98 | + if not os.path.exists(context_dir): |
| 99 | + return |
| 100 | + |
| 101 | + # content must only include one file for now |
| 102 | + fullpaths = os.listdir(context_dir) |
| 103 | + if not fullpaths: |
| 104 | + return |
| 105 | + fullpath = os.path.join(context_dir, fullpaths[0]) |
| 106 | + content = self.read_file(fullpath) |
| 107 | + self.data[key] = content |
| 108 | + return content |
| 109 | + |
| 110 | + def load_all(self): |
| 111 | + """ |
| 112 | + Load the entire context. We assume that text content has already been added |
| 113 | + to the variable context. |
| 114 | + """ |
| 115 | + for key in os.listdir(self.workspace): |
| 116 | + context_dir = os.path.join(self.workspace, key) |
| 117 | + # content must only include one file for now |
| 118 | + fullpaths = os.listdir(context_dir) |
| 119 | + if not fullpaths: |
| 120 | + continue |
| 121 | + fullpath = os.path.join(context_dir, fullpaths[0]) |
| 122 | + self.context[key] = self.read_file(fullpath) |
| 123 | + |
| 124 | + def read_file(self, filename): |
| 125 | + """ |
| 126 | + Read the full file name |
| 127 | + """ |
| 128 | + if filename.endswith('json'): |
| 129 | + return utils.read_json(filename) |
| 130 | + elif re.search("(yaml|yml)$", filename): |
| 131 | + return utils.read_yaml(filename) |
| 132 | + return utils.read_file(filename) |
| 133 | + |
| 134 | + def save(self, name, content, filename): |
| 135 | + """ |
| 136 | + Save content to the context. The filename should be a relative path. |
| 137 | + Objects will be stored akin to a simple kvs like: |
| 138 | + |
| 139 | + ./<context>/ |
| 140 | + <key>/Dockerfile |
| 141 | + |
| 142 | + Right now we are going to assume that any file that isn't .json/yaml |
| 143 | + will be loaded as text. The relative path of the file is meaningful. If |
| 144 | + we need extended metadata we can add a metadata.json. |
| 145 | + """ |
| 146 | + context_dir = os.path.join(self.workspace, name) |
| 147 | + if not os.path.exists(context_dir): |
| 148 | + os.makedirs(context_dir) |
| 149 | + context_file = os.path.join(context_dir, filename) |
| 150 | + utils.save_file(content, context_file) |
| 151 | + |
| 152 | + def cleanup(self): |
| 153 | + """ |
| 154 | + Cleanup the context if not done yet. |
| 155 | + |
| 156 | + To start, let's make the default cleanup and we can reverse when |
| 157 | + we move out of development. |
| 158 | + """ |
| 159 | + if self.context.get('keep') is None: |
| 160 | + shutil.rmtree(self.workspace, ignore_errors=True) |
0 commit comments