Skip to content

Metal

MetalVectorStore #

Bases: BasePydanticVectorStore

金属向量存储。

示例

pip install llama-index-vector-stores-metal

from llama_index.vector_stores.metal import MetalVectorStore

# 注册Metal并生成API密钥和客户端ID
api_key = "your_api_key_here"
client_id = "your_client_id_here"
index_id = "your_index_id_here"

# 初始化Metal向量存储
vector_store = MetalVectorStore(
    api_key=api_key,
    client_id=client_id,
    index_id=index_id,
)
Source code in llama_index/vector_stores/metal/base.py
 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
class MetalVectorStore(BasePydanticVectorStore):
    """金属向量存储。

    示例:
        `pip install llama-index-vector-stores-metal`

        ```python
        from llama_index.vector_stores.metal import MetalVectorStore

        # 注册Metal并生成API密钥和客户端ID
        api_key = "your_api_key_here"
        client_id = "your_client_id_here"
        index_id = "your_index_id_here"

        # 初始化Metal向量存储
        vector_store = MetalVectorStore(
            api_key=api_key,
            client_id=client_id,
            index_id=index_id,
        )
        ```"""

    stores_text: bool = True
    flat_metadata: bool = False
    is_embedding_query: bool = True

    api_key: str
    client_id: str
    index_id: str
    metal_client: Metal

    def __init__(
        self,
        api_key: str,
        client_id: str,
        index_id: str,
    ):
        """初始化参数。"""
        super().__init__(
            api_key=api_key,
            client_id=client_id,
            index_id=index_id,
            metal_client=Metal(api_key, client_id, index_id),
        )

    @classmethod
    def class_name(cls) -> str:
        return "MetalVectorStore"

    def query(self, query: VectorStoreQuery, **kwargs: Any) -> VectorStoreQueryResult:
        if query.filters is not None:
            if "filters" in kwargs:
                raise ValueError(
                    "Cannot specify filter via both query and kwargs. "
                    "Use kwargs only for metal specific items that are "
                    "not supported via the generic query interface."
                )
            filters = _to_metal_filters(query.filters)
        else:
            filters = kwargs.get("filters", {})

        payload = {
            "embedding": query.query_embedding,  # Query Embedding
            "filters": filters,  # Metadata Filters
        }
        response = self.metal_client.search(payload, limit=query.similarity_top_k)

        nodes = []
        ids = []
        similarities = []

        for item in response["data"]:
            text = item["text"]
            id_ = item["id"]

            # load additional Node data
            try:
                node = metadata_dict_to_node(item["metadata"])
                node.text = text
            except Exception:
                # NOTE: deprecated legacy logic for backward compatibility
                metadata, node_info, relationships = legacy_metadata_dict_to_node(
                    item["metadata"]
                )

                node = TextNode(
                    text=text,
                    id_=id_,
                    metadata=metadata,
                    start_char_idx=node_info.get("start", None),
                    end_char_idx=node_info.get("end", None),
                    relationships=relationships,
                )

            nodes.append(node)
            ids.append(id_)

            similarity_score = 1.0 - math.exp(-item["dist"])
            similarities.append(similarity_score)

        return VectorStoreQueryResult(nodes=nodes, similarities=similarities, ids=ids)

    @property
    def client(self) -> Any:
        """返回Metal客户端。"""
        return self.metal_client

    def add(self, nodes: List[BaseNode], **add_kwargs: Any) -> List[str]:
        """将节点添加到索引中。

Args:
    nodes: List[BaseNode]: 带有嵌入的节点列表。
"""
        if not self.metal_client:
            raise ValueError("metal_client not initialized")

        ids = []
        for node in nodes:
            ids.append(node.node_id)

            metadata = {}
            metadata["text"] = node.get_content(metadata_mode=MetadataMode.NONE) or ""

            additional_metadata = node_to_metadata_dict(
                node, remove_text=True, flat_metadata=self.flat_metadata
            )
            metadata.update(additional_metadata)

            payload = {
                "embedding": node.get_embedding(),
                "metadata": metadata,
                "id": node.node_id,
            }

            self.metal_client.index(payload)

        return ids

    def delete(self, ref_doc_id: str, **delete_kwargs: Any) -> None:
        """使用ref_doc_id删除节点。

Args:
    ref_doc_id(str):要删除的文档的doc_id。
"""
        if not self.metal_client:
            raise ValueError("metal_client not initialized")

        self.metal_client.deleteOne(ref_doc_id)

client property #

client: Any

返回Metal客户端。

add #

add(nodes: List[BaseNode], **add_kwargs: Any) -> List[str]

将节点添加到索引中。

Parameters:

Name Type Description Default
nodes List[BaseNode]

List[BaseNode]: 带有嵌入的节点列表。

required
Source code in llama_index/vector_stores/metal/base.py
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
    def add(self, nodes: List[BaseNode], **add_kwargs: Any) -> List[str]:
        """将节点添加到索引中。

Args:
    nodes: List[BaseNode]: 带有嵌入的节点列表。
"""
        if not self.metal_client:
            raise ValueError("metal_client not initialized")

        ids = []
        for node in nodes:
            ids.append(node.node_id)

            metadata = {}
            metadata["text"] = node.get_content(metadata_mode=MetadataMode.NONE) or ""

            additional_metadata = node_to_metadata_dict(
                node, remove_text=True, flat_metadata=self.flat_metadata
            )
            metadata.update(additional_metadata)

            payload = {
                "embedding": node.get_embedding(),
                "metadata": metadata,
                "id": node.node_id,
            }

            self.metal_client.index(payload)

        return ids

delete #

delete(ref_doc_id: str, **delete_kwargs: Any) -> None

使用ref_doc_id删除节点。

Source code in llama_index/vector_stores/metal/base.py
170
171
172
173
174
175
176
177
178
179
    def delete(self, ref_doc_id: str, **delete_kwargs: Any) -> None:
        """使用ref_doc_id删除节点。

Args:
    ref_doc_id(str):要删除的文档的doc_id。
"""
        if not self.metal_client:
            raise ValueError("metal_client not initialized")

        self.metal_client.deleteOne(ref_doc_id)