File size: 7,142 Bytes
db15762
 
 
 
 
 
 
 
 
733bea7
db15762
a5081b6
 
 
 
 
 
db15762
 
 
 
a5081b6
 
 
db15762
a5081b6
1863cbe
 
 
 
 
a5081b6
db15762
1863cbe
a5081b6
db15762
 
a5081b6
db15762
3fdc088
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1863cbe
 
3fdc088
 
733bea7
3fdc088
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
733bea7
 
 
 
 
 
db15762
 
 
 
 
 
 
 
 
 
 
 
 
 
1863cbe
db15762
 
 
 
a5081b6
db15762
 
 
 
 
 
 
a5081b6
db15762
 
 
 
 
 
 
 
 
 
a5081b6
db15762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1863cbe
db15762
 
 
 
 
a5081b6
db15762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5081b6
 
7a65857
b63d6c4
de93b1d
 
 
 
 
 
b63d6c4
a5081b6
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
import os
import pinecone
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import Pinecone
from typing import TYPE_CHECKING, Any, Callable, Iterable, List, Optional, Tuple, Union
from langchain.docstore.document import Document
from langchain.schema.embeddings import Embeddings
from langchain.vectorstores.utils import DistanceStrategy, maximal_marginal_relevance
import numpy as np
import json
import logging
import uuid
from langchain.utils.iter import batch_iterate
try:
    from script import export
except:
    pass

logger = logging.getLogger(__name__)

class VectorStore(Pinecone):
    REQUEST_TIMEOUT=10
    INDEX_NAME = "jarvis"
    NAMESPACE = "filecoin"

    def __init__(self) -> None:
        # pinecone.init(
        #     api_key=os.getenv("PINECONE_API_KEY"),  
        #     environment=os.getenv("PINECONE_ENV"),  
        # )
        pc = pinecone.Pinecone(api_key=os.getenv("PINECONE_API_KEY"))

        self.dims = 1536
        index = pc.Index(self.INDEX_NAME)
        super().__init__(index, OpenAIEmbeddings(),"text")  

    def add_docs(self,docs):
        Pinecone.from_documents(docs, self.embeddings, index_name=self.INDEX_NAME)

    def search(self,
        query: str,
        k: int = 4,
        filter: Optional[dict] = None,
        namespace: Optional[str] = None,
        **kwargs: Any,
    ) -> List[Document]:
        """Return pinecone documents most similar to query.

        Args:
            query: Text to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            filter: Dictionary of argument(s) to filter on metadata
            namespace: Namespace to search in. Default will search in '' namespace.

        Returns:
            List of Documents most similar to the query and score for each
        """
        docs_and_scores = self.similarity_search_by_vector_with_score(
            self._embed_query(query), k=k, filter=filter, namespace=namespace
        )
        return [doc for doc, _ in docs_and_scores]

    def marginal_search(self,
        query: str,
        k: int = 4,
        fetch_k: int = 20,
        lambda_mult: float = 0.5,
        filter: Optional[dict] = None,
        namespace: Optional[str] = None,
        **kwargs: Any,
    ) -> List[Document]:
        """Return docs selected using the maximal marginal relevance.

        Maximal marginal relevance optimizes for similarity to query AND diversity
        among selected documents.

        Args:
            query: Text to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            fetch_k: Number of Documents to fetch to pass to MMR algorithm.
            lambda_mult: Number between 0 and 1 that determines the degree of diversity among the results with 0 corresponding
                        to maximum diversity and 1 to minimum diversity.
                        Defaults to 0.5.
        Returns:
            List of Documents selected by maximal marginal relevance.
        """
        embedding = self._embed_query(query)
        return self.max_marginal_relevance_search_by_vector(
            embedding, k, fetch_k, lambda_mult, filter, namespace
        )
        
    def jsonfy(self,docs):
        docs = [doc.dict() for doc in docs]
        docs = json.dumps(docs)
        return docs

    def similarity_search_by_vector_with_score(
        self,
        embedding: List[float],
        *,
        k: int = 4,
        filter: Optional[dict] = None,
        namespace: Optional[str] = None,
    ) -> List[Tuple[Document, float]]:
        """Return pinecone documents most similar to embedding, along with scores."""

        if namespace is None:
            namespace = self._namespace
        docs = []
        results = self._index.query(
            vector=[embedding],
            top_k=k,
            include_metadata=True,
            namespace=namespace,
            filter=filter,
            _request_timeout=self.REQUEST_TIMEOUT
        )
        for res in results["matches"]:
            metadata = res["metadata"]
            if self._text_key in metadata:
                text = metadata.pop(self._text_key)
                score = res["score"]
                metadata['score'] = score
                # print(f"metadata {metadata}")
                docs.append((Document(page_content=text, metadata=metadata), score))
            else:
                logger.warning(
                    f"Found document with no `{self._text_key}` key. Skipping."
                )
        return docs
    
    def max_marginal_relevance_search_by_vector(
        self,
        embedding: List[float],
        k: int = 5,
        fetch_k: int = 20,
        lambda_mult: float = 0.5,
        filter: Optional[dict] = None,
        namespace: Optional[str] = None,
        **kwargs: Any,
    ) -> List[Document]:
        """Return docs selected using the maximal marginal relevance.

        Maximal marginal relevance optimizes for similarity to query AND diversity
        among selected documents.

        Args:
            embedding: Embedding to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            fetch_k: Number of Documents to fetch to pass to MMR algorithm.
            lambda_mult: Number between 0 and 1 that determines the degree
                        of diversity among the results with 0 corresponding
                        to maximum diversity and 1 to minimum diversity.
                        Defaults to 0.5.
        Returns:
            List of Documents selected by maximal marginal relevance.
        """
        if namespace is None:
            namespace = self._namespace
        results = self._index.query(
            vector=[embedding],
            top_k=fetch_k,
            include_values=True,
            include_metadata=True,
            namespace=namespace,
            filter=filter,
            _request_timeout=self.REQUEST_TIMEOUT
        )
        mmr_selected = maximal_marginal_relevance(
            np.array([embedding], dtype=np.float32),
            [item["values"] for item in results["matches"]],
            k=k,
            lambda_mult=lambda_mult,
        )
        selected = []
        for i in mmr_selected:
            metadata = results["matches"][i]["metadata"]
            score = results["matches"][i]["score"]
            metadata['score'] = score
            selected.append(metadata)
        # selected = [results["matches"][i]["metadata"] for i in mmr_selected]
        return [
            Document(page_content=metadata.pop((self._text_key)), metadata=metadata)
            for metadata in selected
        ]

    def upsert(self,text,id,source=''):
        embed = self.embeddings.embed_query(text)
        metadata = {"description":text,"text":text,"source":source}
        vector_store._index.update(id=id,values=embed,set_metadata=metadata)
        # vector_store._index.upsert(vectors=[
        #     {'id':id,'values':embed,'metadata':metadata}]
        # )
        print(f"upsert text:{text} with meta:{metadata}")

vector_store = VectorStore()