File size: 8,879 Bytes
35b22df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
"""Weaviate-specific serializers for LlamaIndex data structures.

Contain conversion to and from dataclasses that LlamaIndex uses.

"""

import json
from abc import abstractmethod
from typing import Any, Dict, Generic, List, Optional, TypeVar, cast

from gpt_index.data_structs.data_structs import IndexStruct, Node
from gpt_index.readers.weaviate.utils import (
    get_by_id,
    parse_get_response,
    validate_client,
)
from gpt_index.utils import get_new_id

IS = TypeVar("IS", bound=IndexStruct)


class BaseWeaviateIndexStruct(Generic[IS]):
    """Base Weaviate index struct."""

    @classmethod
    @abstractmethod
    def _class_name(cls, class_prefix: str) -> str:
        """Return class name."""

    @classmethod
    def _get_common_properties(cls) -> List[Dict]:
        """Get common properties."""
        return [
            {
                "dataType": ["string"],
                "description": "Text property",
                "name": "text",
            },
            {
                "dataType": ["string"],
                "description": "Document id",
                "name": "doc_id",
            },
            {
                "dataType": ["string"],
                "description": "extra_info (in JSON)",
                "name": "extra_info",
            },
        ]

    @classmethod
    @abstractmethod
    def _get_properties(cls) -> List[Dict]:
        """Get properties specific to each index struct.

        Used in creating schema.

        """

    @classmethod
    def _get_by_id(cls, client: Any, object_id: str, class_prefix: str) -> Dict:
        """Get entry by id."""
        validate_client(client)
        class_name = cls._class_name(class_prefix)
        properties = cls._get_common_properties() + cls._get_properties()
        prop_names = [p["name"] for p in properties]
        entry = get_by_id(client, object_id, class_name, prop_names)
        return entry

    @classmethod
    def create_schema(cls, client: Any, class_prefix: str) -> None:
        """Create schema."""
        validate_client(client)
        # first check if schema exists
        schema = client.schema.get()
        classes = schema["classes"]
        existing_class_names = {c["class"] for c in classes}
        # if schema already exists, don't create
        class_name = cls._class_name(class_prefix)
        if class_name in existing_class_names:
            return

        # get common properties
        properties = cls._get_common_properties()
        # get specific properties
        properties.extend(cls._get_properties())
        class_obj = {
            "class": cls._class_name(class_prefix),  # <= note the capital "A".
            "description": f"Class for {class_name}",
            "properties": properties,
        }
        client.schema.create_class(class_obj)

    @classmethod
    @abstractmethod
    def _entry_to_gpt_index(cls, entry: Dict) -> IS:
        """Convert to LlamaIndex list."""

    @classmethod
    def to_gpt_index_list(
        cls,
        client: Any,
        class_prefix: str,
        vector: Optional[List[float]] = None,
        object_limit: Optional[int] = None,
    ) -> List[IS]:
        """Convert to LlamaIndex list."""
        validate_client(client)
        class_name = cls._class_name(class_prefix)
        properties = cls._get_common_properties() + cls._get_properties()
        prop_names = [p["name"] for p in properties]
        query = client.query.get(class_name, prop_names).with_additional(
            ["id", "vector"]
        )
        if vector is not None:
            query = query.with_near_vector(
                {
                    "vector": vector,
                }
            )
        if object_limit is not None:
            query = query.with_limit(object_limit)
        query_result = query.do()
        parsed_result = parse_get_response(query_result)
        entries = parsed_result[class_name]

        results: List[IS] = []
        for entry in entries:
            results.append(cls._entry_to_gpt_index(entry))

        return results

    @classmethod
    @abstractmethod
    def _from_gpt_index(
        cls, client: Any, index: IS, class_prefix: str, batch: Optional[Any] = None
    ) -> str:
        """Convert from LlamaIndex."""

    @classmethod
    def from_gpt_index(cls, client: Any, index: IS, class_prefix: str) -> str:
        """Convert from LlamaIndex."""
        validate_client(client)
        index_id = cls._from_gpt_index(client, index, class_prefix)
        client.batch.flush()
        return index_id


class WeaviateNode(BaseWeaviateIndexStruct[Node]):
    """Weaviate node."""

    @classmethod
    def _class_name(cls, class_prefix: str) -> str:
        """Return class name."""
        return f"{class_prefix}_Node"

    @classmethod
    def _get_properties(cls) -> List[Dict]:
        """Create schema."""
        return [
            {
                "dataType": ["int"],
                "description": "The index of the Node",
                "name": "index",
            },
            {
                "dataType": ["int[]"],
                "description": "The child_indices of the Node",
                "name": "child_indices",
            },
            {
                "dataType": ["string"],
                "description": "The ref_doc_id of the Node",
                "name": "ref_doc_id",
            },
            {
                "dataType": ["string"],
                "description": "node_info (in JSON)",
                "name": "node_info",
            },
        ]

    @classmethod
    def _entry_to_gpt_index(cls, entry: Dict) -> Node:
        """Convert to LlamaIndex list."""
        extra_info_str = entry["extra_info"]
        if extra_info_str == "":
            extra_info = None
        else:
            extra_info = json.loads(extra_info_str)

        node_info_str = entry["node_info"]
        if node_info_str == "":
            node_info = None
        else:
            node_info = json.loads(node_info_str)
        return Node(
            text=entry["text"],
            doc_id=entry["doc_id"],
            index=int(entry["index"]),
            child_indices=entry["child_indices"],
            ref_doc_id=entry["ref_doc_id"],
            embedding=entry["_additional"]["vector"],
            extra_info=extra_info,
            node_info=node_info,
        )

    @classmethod
    def _from_gpt_index(
        cls, client: Any, node: Node, class_prefix: str, batch: Optional[Any] = None
    ) -> str:
        """Convert from LlamaIndex."""
        node_dict = node.to_dict()
        vector = node_dict.pop("embedding")
        extra_info = node_dict.pop("extra_info")
        # json-serialize the extra_info
        extra_info_str = ""
        if extra_info is not None:
            extra_info_str = json.dumps(extra_info)
        node_dict["extra_info"] = extra_info_str
        # json-serialize the node_info
        node_info = node_dict.pop("node_info")
        node_info_str = ""
        if node_info is not None:
            node_info_str = json.dumps(node_info)
        node_dict["node_info"] = node_info_str

        # TODO: account for existing nodes that are stored
        node_id = get_new_id(set())
        class_name = cls._class_name(class_prefix)

        # if batch object is provided (via a contexxt manager), use that instead
        if batch is not None:
            batch.add_data_object(node_dict, class_name, node_id, vector)
        else:
            client.batch.add_data_object(node_dict, class_name, node_id, vector)

        return node_id

    @classmethod
    def delete_document(cls, client: Any, ref_doc_id: str, class_prefix: str) -> None:
        """Delete entry."""
        validate_client(client)
        # make sure that each entry
        class_name = cls._class_name(class_prefix)
        where_filter = {
            "path": ["ref_doc_id"],
            "operator": "Equal",
            "valueString": ref_doc_id,
        }
        query = (
            client.query.get(class_name)
            .with_additional(["id"])
            .with_where(where_filter)
        )

        query_result = query.do()
        parsed_result = parse_get_response(query_result)
        entries = parsed_result[class_name]
        for entry in entries:
            client.data_object.delete(entry["_additional"]["id"], class_name)

    @classmethod
    def from_gpt_index_batch(
        cls, client: Any, nodes: List[Node], class_prefix: str
    ) -> List[str]:
        """Convert from gpt index."""
        from weaviate import Client  # noqa: F401

        client = cast(Client, client)
        validate_client(client)
        index_ids = []
        with client.batch as batch:
            for node in nodes:
                index_id = cls._from_gpt_index(client, node, class_prefix, batch=batch)
        index_ids.append(index_id)
        return index_ids