deserialization.py
1 # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai> 2 # 3 # SPDX-License-Identifier: Apache-2.0 4 5 from typing import Any 6 7 from haystack.core.errors import DeserializationError 8 from haystack.core.serialization import component_from_dict, import_class_by_name 9 10 11 def deserialize_chatgenerator_inplace(data: dict[str, Any], key: str = "chat_generator") -> None: 12 """ 13 Deserialize a ChatGenerator in a dictionary inplace. 14 15 :param data: 16 The dictionary with the serialized data. 17 :param key: 18 The key in the dictionary where the ChatGenerator is stored. 19 20 :raises DeserializationError: 21 If the key is missing in the serialized data, the value is not a dictionary, 22 the type key is missing, the class cannot be imported, or the class lacks a 'from_dict' method. 23 """ 24 deserialize_component_inplace(data, key=key) 25 26 27 def deserialize_component_inplace(data: dict[str, Any], key: str = "chat_generator") -> None: 28 """ 29 Deserialize a Component in a dictionary inplace. 30 31 :param data: 32 The dictionary with the serialized data. 33 :param key: 34 The key in the dictionary where the Component is stored. Default is "chat_generator". 35 36 :raises DeserializationError: 37 If the key is missing in the serialized data, the value is not a dictionary, 38 the type key is missing, the class cannot be imported, or the class lacks a 'from_dict' method. 39 """ 40 if key not in data: 41 raise DeserializationError(f"Missing '{key}' in serialization data") 42 43 serialized_component = data[key] 44 45 if not isinstance(serialized_component, dict): 46 raise DeserializationError(f"The value of '{key}' is not a dictionary") 47 48 if "type" not in serialized_component: 49 raise DeserializationError(f"Missing 'type' in {key} serialization data") 50 51 try: 52 component_class = import_class_by_name(serialized_component["type"]) 53 except ImportError as e: 54 raise DeserializationError(f"Class '{serialized_component['type']}' not correctly imported") from e 55 56 data[key] = component_from_dict(cls=component_class, data=serialized_component, name=key)