MCPcopy
hub / github.com/567-labs/instructor / load_cached_response

Function load_cached_response

instructor/cache/__init__.py:189–238  ·  view source on GitHub ↗

Return parsed model if *key* exists in *cache* else None.

(cache: BaseCache, key: str, response_model: type[BaseModel])

Source from the content-addressed store, hash-verified

187
188
189def load_cached_response(cache: BaseCache, key: str, response_model: type[BaseModel]): # noqa: ANN201
190 """Return parsed model if *key* exists in *cache* else None."""
191 cached = cache.get(key)
192 if cached is None:
193 return None
194 import json
195
196 try:
197 data = json.loads(cached)
198 model_json = data["model"]
199 raw_json = data.get("raw")
200 except Exception: # noqa: BLE001
201 model_json = cached
202 raw_json = None
203
204 obj = response_model.model_validate_json(model_json)
205 if raw_json is not None:
206 # `_raw_response` is an internal attribute used by Instructor; it may not
207 # be declared on the Pydantic model type.
208 try:
209 # Try to deserialize as JSON and reconstruct object structure
210 import json
211
212 raw_data = json.loads(raw_json)
213
214 # Check if this looks like a Pydantic-serialized object (has proper structure)
215 if isinstance(raw_data, dict) and any(
216 key in raw_data for key in ["id", "object", "model", "choices"]
217 ):
218 # Looks like a proper completion object - use SimpleNamespace reconstruction
219 from types import SimpleNamespace
220
221 object.__setattr__(
222 obj,
223 "_raw_response",
224 json.loads(raw_json, object_hook=lambda d: SimpleNamespace(**d)),
225 )
226 logger.debug("Restored raw response as SimpleNamespace object")
227 else:
228 # Plain dict/list - keep as-is
229 object.__setattr__(obj, "_raw_response", raw_data)
230 logger.debug("Restored raw response as plain data structure")
231 except (json.JSONDecodeError, TypeError):
232 # Not valid JSON - probably string fallback
233 object.__setattr__(obj, "_raw_response", raw_json)
234 logger.debug(
235 "Restored raw response as string (original could not be fully serialized)"
236 )
237 logger.debug("cache hit: %s", key)
238 return obj
239
240
241def store_cached_response(

Callers 2

new_create_syncFunction · 0.90
new_create_asyncFunction · 0.90

Calls 1

getMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…