Skip to content

Wordlift

WordliftVectorStore #

Bases: VectorStore

Source code in llama_index/vector_stores/wordlift/base.py
 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
class WordliftVectorStore(VectorStore):
    stores_text = True

    vector_search_service: VectorSearchService

    @staticmethod
    def create(key: str):
        return WordliftVectorStore(KeyProvider(key), VectorSearchService())

    def __init__(
        self,
        key_provider: KeyProvider,
        vector_search_service: VectorSearchService,
    ):
        super(WordliftVectorStore, self).__init__(use_async=True)

        self.vector_search_service = vector_search_service
        self.key_provider = key_provider

    def add(self, nodes: List[BaseNode], **add_kwargs: Any) -> List[str]:
        log.debug("Add node(s)\n")
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        task = loop.create_task(self.async_add(nodes, **add_kwargs))
        add = loop.run_until_complete(task)
        loop.close()
        return add

    async def async_add(
        self,
        nodes: List[BaseNode],
        **kwargs: Any,
    ) -> List[str]:
        # Empty nodes, return empty list
        if not nodes:
            return []

        log.debug("{0} node(s) received\n".format(len(nodes)))

        # Get the key to use for the operation.
        key = await self.key_provider.for_add(nodes)

        requests = []
        for node in nodes:
            node_dict = node.dict()
            metadata: Dict[str, Any] = node_dict.get("metadata", {})
            entity_id = metadata.get("entity_id", None)

            entry = NodeRequest(
                entity_id=entity_id,
                node_id=node.node_id,
                embeddings=node.get_embedding(),
                text=node.get_content(metadata_mode=MetadataMode.NONE) or "",
                metadata=metadata,
            )
            requests.append(entry)

        log.debug("Inserting data, using key {0}: {1}".format(key, requests))

        try:
            await self.vector_search_service.update_nodes_collection(
                node_request=requests, key=key
            )
        except Exception:
            print(traceback.format_exc())
            return []

        return [node.node_id for node in nodes]

    def delete(self, ref_doc_id: str, **delete_kwargs: Any) -> None:
        raise NotImplementedError

    def query(self, query: VectorStoreQuery, **kwargs: Any) -> VectorStoreQueryResult:
        log.debug("Running in NON async mode")
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        task = loop.create_task(self.aquery(query, **kwargs))
        query = loop.run_until_complete(task)
        loop.close()
        return query

    async def aquery(
        self, query: VectorStoreQuery, **kwargs: Any
    ) -> VectorStoreQueryResult:
        request = VectorSearchQueryRequest(
            query_embedding=query.query_embedding,
            similarity_top_k=query.similarity_top_k,
        )

        # Get the key to use for the operation.
        key = await self.key_provider.for_query(query)

        try:
            page = await self.vector_search_service.query_nodes_collection(
                vector_search_query_request=request, key=key
            )
        except ServiceException as exception:
            raise WordliftVectorQueryServiceException(
                exception=exception, msg=exception.body
            )
        except Exception as exception:
            print(traceback.format_exc())
            raise WordliftVectorStoreException(
                exception=exception, msg="Failed to fetch query results"
            )

        nodes: List[TextNode] = []
        similarities: List[float] = []
        ids: List[str] = []

        for item in page.items:
            nodes.append(
                TextNode(
                    text=item.text,
                    id_=item.node_id,
                    embedding=item.embeddings,
                    metadata=item.metadata,
                )
            )
            similarities.append(item.score)
            ids.append(item.node_id)
        return VectorStoreQueryResult(nodes=nodes, similarities=similarities, ids=ids)