
    3fi                    ,   U d dl mZ d dlZd dlZd dlmZ d dlmZmZm	Z	m
Z
mZmZmZ d dlmZ d dlmZ d dlmZ d dlmZmZ d d	lmZ d d
lmZ ej6                  Zej:                  dej6                  diZded<    edddd       G d de             Z eZ!y)    )annotationsN)Enum)AnyCallableIterableListOptionalTupleType)
deprecated)Document)
Embeddings)VectorStoreVectorStoreRetriever)	QueuePool)DistanceStrategy DESCdictORDERING_DIRECTIVEz0.3.22a  This class is pending deprecation and may be removed in a future version. You can swap to using the `SingleStoreVectorStore` implementation in `langchain_singlestore`. See <https://github.com/singlestore-labs/langchain-singlestore> for details about the new implementation.z8from langchain_singlestore import SingleStoreVectorStoreT)sincemessagealternativependingc                  B   e Zd ZdZ G d dee      Zd"dZeddddd	d
dddd
dddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d#dZ	e
d$d       Zd%dZd&dZd'dZ	 	 	 d(	 	 	 	 	 	 	 	 	 	 	 d)dZ	 	 	 d(	 	 	 	 	 	 	 	 	 	 	 d*dZd+d,dZddej$                  ddddf	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d-dZddej$                  ddddf	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d.dZededdddd	d
dddd
dddf	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d/d        Zd0d!Zy)1SingleStoreDBat  `SingleStore DB` vector store.

    The prerequisite for using this class is the installation of the ``singlestoredb``
    Python package.

    The SingleStoreDB vectorstore can be created by providing an embedding function and
    the relevant parameters for the database connection, connection pool, and
    optionally, the names of the table and the fields to use.
    c                  $    e Zd ZdZdZdZdZdZdZy)SingleStoreDB.SearchStrategyzEEnumerator of the Search strategies for searching in the vectorstore.VECTOR_ONLY	TEXT_ONLYFILTER_BY_TEXTFILTER_BY_VECTORWEIGHTED_SUMN)	__name__
__module____qualname____doc__r   r    r!   r"   r#        l/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_community/vectorstores/singlestoredb.pySearchStrategyr   7   s    S#	)-%r)   r+   c                t    	 dd l } |j                  di | j                  S # t        $ r t        d      w xY w)Nr   zbCould not import singlestoredb python package. Please install it with `pip install singlestoredb`.r(   )singlestoredbImportErrorconnectconnection_kwargs)selfs2s     r*   _get_connectionzSingleStoreDB._get_connection@   sJ    	& rzz3D2233  	F 	s   " 7
embeddingscontentmetadatavectoridFr   Ni      
      )distance_strategy
table_namecontent_fieldmetadata_fieldvector_fieldid_fielduse_vector_indexvector_index_namevector_index_optionsvector_sizeuse_full_text_search	pool_sizemax_overflowtimeoutc                  || _         || _        | j                  |      | _        | j                  |      | _        | j                  |      | _        | j                  |      | _        | j                  |      | _        t        |      | _	        | j                  |	      | _
        t        |
xs i       | _        | j                  | j                  d<   t        |      | _        t        |      | _        || _        d| j                   vrt               | j                   d<   d| j                   d   d<   d| j                   d   d<   t#        | j$                  |||      | _        | j)                          y)	av   Initialize with necessary components.

        Args:
            embedding (Embeddings): A text embedding model.

            distance_strategy (DistanceStrategy, optional):
                Determines the strategy employed for calculating
                the distance between vectors in the embedding space.
                Defaults to DOT_PRODUCT.
                Available options are:
                - DOT_PRODUCT: Computes the scalar product of two vectors.
                    This is the default behavior
                - EUCLIDEAN_DISTANCE: Computes the Euclidean distance between
                    two vectors. This metric considers the geometric distance in
                    the vector space, and might be more suitable for embeddings
                    that rely on spatial relationships. This metric is not
                    compatible with the WEIGHTED_SUM search strategy.

            table_name (str, optional): Specifies the name of the table in use.
                Defaults to "embeddings".
            content_field (str, optional): Specifies the field to store the content.
                Defaults to "content".
            metadata_field (str, optional): Specifies the field to store metadata.
                Defaults to "metadata".
            vector_field (str, optional): Specifies the field to store the vector.
                Defaults to "vector".
            id_field (str, optional): Specifies the field to store the id.
                Defaults to "id".

            use_vector_index (bool, optional): Toggles the use of a vector index.
                Works only with SingleStoreDB 8.5 or later. Defaults to False.
                If set to True, vector_size parameter is required to be set to
                a proper value.

            vector_index_name (str, optional): Specifies the name of the vector index.
                Defaults to empty. Will be ignored if use_vector_index is set to False.

            vector_index_options (dict, optional): Specifies the options for
                the vector index. Defaults to {}.
                Will be ignored if use_vector_index is set to False. The options are:
                index_type (str, optional): Specifies the type of the index.
                    Defaults to IVF_PQFS.
                For more options, please refer to the SingleStoreDB documentation:
                https://docs.singlestore.com/cloud/reference/sql-reference/vector-functions/vector-indexing/

            vector_size (int, optional): Specifies the size of the vector.
                Defaults to 1536. Required if use_vector_index is set to True.
                Should be set to the same value as the size of the vectors
                stored in the vector_field.

            use_full_text_search (bool, optional): Toggles the use a full-text index
                on the document content. Defaults to False. If set to True, the table
                will be created with a full-text index on the content field,
                and the simularity_search method will all using TEXT_ONLY,
                FILTER_BY_TEXT, FILTER_BY_VECTOR, and WIGHTED_SUM search strategies.
                If set to False, the simularity_search method will only allow
                VECTOR_ONLY search strategy.

            Following arguments pertain to the connection pool:

            pool_size (int, optional): Determines the number of active connections in
                the pool. Defaults to 5.
            max_overflow (int, optional): Determines the maximum number of connections
                allowed beyond the pool_size. Defaults to 10.
            timeout (float, optional): Specifies the maximum wait time in seconds for
                establishing a connection. Defaults to 30.

            Following arguments pertain to the database connection:

            host (str, optional): Specifies the hostname, IP address, or URL for the
                database connection. The default scheme is "mysql".
            user (str, optional): Database username.
            password (str, optional): Database password.
            port (int, optional): Database port. Defaults to 3306 for non-HTTP
                connections, 80 for HTTP connections, and 443 for HTTPS connections.
            database (str, optional): Database name.

            Additional optional arguments provide further customization over the
            database connection:

            pure_python (bool, optional): Toggles the connector mode. If True,
                operates in pure Python mode.
            local_infile (bool, optional): Allows local file uploads.
            charset (str, optional): Specifies the character set for string values.
            ssl_key (str, optional): Specifies the path of the file containing the SSL
                key.
            ssl_cert (str, optional): Specifies the path of the file containing the SSL
                certificate.
            ssl_ca (str, optional): Specifies the path of the file containing the SSL
                certificate authority.
            ssl_cipher (str, optional): Sets the SSL cipher list.
            ssl_disabled (bool, optional): Disables SSL usage.
            ssl_verify_cert (bool, optional): Verifies the server's certificate.
                Automatically enabled if ``ssl_ca`` is specified.
            ssl_verify_identity (bool, optional): Verifies the server's identity.
            conv (dict[int, Callable], optional): A dictionary of data conversion
                functions.
            credential_type (str, optional): Specifies the type of authentication to
                use: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO.
            autocommit (bool, optional): Enables autocommits.
            results_type (str, optional): Determines the structure of the query results:
                tuples, namedtuples, dicts.
            results_format (str, optional): Deprecated. This option has been renamed to
                results_type.

        Examples:
            Basic Usage:

            .. code-block:: python

                from langchain_openai import OpenAIEmbeddings
                from langchain_community.vectorstores import SingleStoreDB

                vectorstore = SingleStoreDB(
                    OpenAIEmbeddings(),
                    host="https://user:password@127.0.0.1:3306/database"
                )

            Advanced Usage:

            .. code-block:: python

                from langchain_openai import OpenAIEmbeddings
                from langchain_community.vectorstores import SingleStoreDB

                vectorstore = SingleStoreDB(
                    OpenAIEmbeddings(),
                    distance_strategy=DistanceStrategy.EUCLIDEAN_DISTANCE,
                    host="127.0.0.1",
                    port=3306,
                    user="user",
                    password="password",
                    database="db",
                    table_name="my_custom_table",
                    pool_size=10,
                    timeout=60,
                )

            Using environment variables:

            .. code-block:: python

                from langchain_openai import OpenAIEmbeddings
                from langchain_community.vectorstores import SingleStoreDB

                os.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db'
                vectorstore = SingleStoreDB(OpenAIEmbeddings())

            Using vector index:

            .. code-block:: python

                from langchain_openai import OpenAIEmbeddings
                from langchain_community.vectorstores import SingleStoreDB

                os.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db'
                vectorstore = SingleStoreDB(
                    OpenAIEmbeddings(),
                    use_vector_index=True,
                )

            Using full-text index:

            .. code-block:: python
                from langchain_openai import OpenAIEmbeddings
                from langchain_community.vectorstores import SingleStoreDB

                os.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db'
                vectorstore = SingleStoreDB(
                    OpenAIEmbeddings(),
                    use_full_text_search=True,
                )
        metric_type
conn_attrszlangchain python sdk_connector_namez2.1.0_connector_version)rH   rG   rI   N)	embeddingr<   _sanitize_inputr=   r>   r?   r@   rA   boolrB   rC   r   rD   intrE   rF   r0   r   r3   connection_pool_create_table)r1   rO   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   kwargss                    r*   __init__zSingleStoreDB.__init__J   s^   D #!2..z:!11-@"22>B 00>,,X6 $%5 6!%!5!56G!H$()=)C$D!373I3I!!-0{+$()=$>! "( t555376D""<0BX|,->?EL|,-AB  )  %	 
 	r)   c                    | j                   S N)rO   r1   s    r*   r4   zSingleStoreDB.embeddings/  s    ~~r)   c                0    t        j                  dd|      S )Nz[^a-zA-Z0-9_]r   )resub)r1   	input_strs     r*   rP   zSingleStoreDB._sanitize_input3  s    vv&I66r)   c                    | j                   S rX   )%_max_inner_product_relevance_score_fnrY   s    r*   _select_relevance_score_fnz(SingleStoreDB._select_relevance_score_fn7  s    999r)   c                   | j                   j                         }	 |j                         }	 d}| j                  rdj	                  | j
                        }| j                  rd}| j                  rFt        | j                        dkD  r.dj	                  t        j                  | j                              }|j                  dj	                  | j                  | j                  | j
                  | j                  | j                  | j                   | j"                  | j                  ||
             nW|j                  dj	                  | j                  | j                  | j
                  | j                  | j                   |             |j%                          	 |j%                          y# |j%                          w xY w# |j%                          w xY w)z!Create table if it doesn't exist.r   z, FULLTEXT({})r   zINDEX_OPTIONS '{}'a  CREATE TABLE IF NOT EXISTS {}
                        ({} BIGINT AUTO_INCREMENT PRIMARY KEY, {} LONGTEXT CHARACTER
                        SET utf8mb4 COLLATE utf8mb4_general_ci, {} VECTOR({}, F32)
                        NOT NULL, {} JSON, VECTOR INDEX {} ({}) {}{});zCREATE TABLE IF NOT EXISTS {}
                        ({} BIGINT AUTO_INCREMENT PRIMARY KEY, {} LONGTEXT CHARACTER
                        SET utf8mb4 COLLATE utf8mb4_general_ci, {} BLOB, {} JSON{});
                        N)rS   r/   cursorrF   formatr>   rB   rD   lenjsondumpsexecuter=   rA   r@   rE   r?   rC   close)r1   conncurfull_text_indexindex_optionss        r*   rT   zSingleStoreDB._create_table:  s~   ##++-.	++-C*"$,,&6&=&=d>P>P&QO(($&M00S9R9R5SVW5W(<(C(C JJt'@'@A) KKJ KQ& OO MM .. -- ,, // 22 --)+K	$ KK #F OO MM .. -- //+	 		JJL 		JJLs#   F> EF) F> )F;;F> >Gc                    |>| j                   2t        | j                   d      r| j                   j                  |      } | j                  |||fd|i|S )ah  Run images through the embeddings and add to the vectorstore.

        Args:
            uris List[str]: File path to images.
                Each URI will be added to the vectorstore as document content.
            metadatas (Optional[List[dict]], optional): Optional list of metadatas.
                Defaults to None.
            embeddings (Optional[List[List[float]]], optional): Optional pre-generated
                embeddings. Defaults to None.

        Returns:
            List[str]: list of document ids added to the vectorstore
                if return_ids is True. Otherwise, an empty list.
        embed_image)uris
return_ids)rO   hasattrrn   	add_texts)r1   ro   	metadatasr4   rp   rU   s         r*   
add_imageszSingleStoreDB.add_imagesm  sc    0 *6333>Jt~~)Z
4>
BH
 	
r)   c                   g }| j                   j                         }	 |j                         }	 t        |      D ]  \  }	}
|r||	   ni }|r||	   n| j                  j                  |
g      d   }|j                  dj                  | j                  | j                  | j                  | j                        |
dj                  dj                  t        t        |                  t        j                   |      f       |s|j                  d       |j#                         }|s|j%                  t        |d                
 | j&                  s| j(                  r*|j                  dj                  | j                               |j+                          	 |j+                          |S # |j+                          w xY w# |j+                          w xY w)a$  Add more texts to the vectorstore.

        Args:
            texts (Iterable[str]): Iterable of strings/text to add to the vectorstore.
            metadatas (Optional[List[dict]], optional): Optional list of metadatas.
                Defaults to None.
            embeddings (Optional[List[List[float]]], optional): Optional pre-generated
                embeddings. Defaults to None.

        Returns:
            List[str]: list of document ids added to the vectorstore
                if return_ids is True. Otherwise, an empty list.
        r   zWINSERT INTO {}({}, {}, {})
                        VALUES (%s, JSON_ARRAY_PACK(%s), %s)[{}],zSELECT LAST_INSERT_ID();OPTIMIZE TABLE {} FLUSH;)rS   r/   rb   	enumeraterO   embed_documentsrg   rc   r=   r>   r@   r?   joinmapstrre   rf   fetchoneappendrB   rF   rh   )r1   textsrs   r4   rp   rU   idsri   rj   itextr6   rO   rows                 r*   rr   zSingleStoreDB.add_texts  s   * ##++-$	++-C (/ 4GAt/8y|bH & #1!^^;;TFCAF 
 KK@@F OO .. -- //	A !"MM#((3sI3F*GH JJx0 "$>?!llnJJs3q6{3546 ((D,E,EKK : A A$// RS		JJL
 		JJLs0   F? CF* #F* %A"F* F? *F<<F? ?Gc           	        |y| j                   j                         }	 |j                         }	 |j                  dj	                  | j
                  | j                  dj                  |                   | j                  s| j                  r*|j                  dj	                  | j
                               |j                          	 |j                          y# |j                          w xY w# |j                          w xY w)a%  Delete documents from the vectorstore.

        Args:
            ids (List[str], optional): List of document ids to delete.
                If None, all documents will be deleted. Defaults to None.

        Returns:
            bool: True if deletion was successful, False otherwise.
        TzDELETE FROM {} WHERE {} IN ({})rw   rx   )rS   r/   rb   rg   rc   r=   rA   r{   rB   rF   rh   )r1   r   rU   ri   rj   s        r*   deletezSingleStoreDB.delete  s     ;##++-	++-C	5<<
 ((D,E,EKK : A A$// RS		JJL 		JJLs#   C. BC 7C. C++C. .D    r   g      ?c	                n     | j                   d||||||||d|	}
|
D cg c]  \  }}|	 c}}S c c}}w )a  Returns the most similar indexed documents to the query text.

        Uses cosine similarity.

        Args:
            query (str): The query text for which to find similar documents.
            k (int): The number of documents to return. Default is 4.
            filter (dict): A dictionary of metadata fields and values to filter by.
                Default is None.
            search_strategy (SearchStrategy): The search strategy to use.
                Default is SearchStrategy.VECTOR_ONLY.
                Available options are:
                - SearchStrategy.VECTOR_ONLY: Searches only by vector similarity.
                - SearchStrategy.TEXT_ONLY: Searches only by text similarity. This
                    option is only available if use_full_text_search is True.
                - SearchStrategy.FILTER_BY_TEXT: Filters by text similarity and
                    searches by vector similarity. This option is only available if
                    use_full_text_search is True.
                - SearchStrategy.FILTER_BY_VECTOR: Filters by vector similarity and
                    searches by text similarity. This option is only available if
                    use_full_text_search is True.
                - SearchStrategy.WEIGHTED_SUM: Searches by a weighted sum of text and
                    vector similarity. This option is only available if
                    use_full_text_search is True and distance_strategy is DOT_PRODUCT.
            filter_threshold (float): The threshold for filtering by text or vector
                similarity. Default is 0. This option has effect only if search_strategy
                is SearchStrategy.FILTER_BY_TEXT or SearchStrategy.FILTER_BY_VECTOR.
            text_weight (float): The weight of text similarity in the weighted sum
                search strategy. Default is 0.5. This option has effect only if
                search_strategy is SearchStrategy.WEIGHTED_SUM.
            vector_weight (float): The weight of vector similarity in the weighted sum
                search strategy. Default is 0.5. This option has effect only if
                search_strategy is SearchStrategy.WEIGHTED_SUM.
            vector_select_count_multiplier (int): The multiplier for the number of
                vectors to select when using the vector index. Default is 10.
                This parameter has effect only if use_vector_index is True and
                search_strategy is SearchStrategy.WEIGHTED_SUM or
                SearchStrategy.FILTER_BY_TEXT.
                The number of vectors selected will
                be k * vector_select_count_multiplier.
                This is needed due to the limitations of the vector index.


        Returns:
            List[Document]: A list of documents that are most similar to the query text.

        Examples:

            Basic Usage:
            .. code-block:: python

                from langchain_community.vectorstores import SingleStoreDB
                from langchain_openai import OpenAIEmbeddings

                s2 = SingleStoreDB.from_documents(
                    docs,
                    OpenAIEmbeddings(),
                    host="username:password@localhost:3306/database"
                )
                results = s2.similarity_search("query text", 1,
                                    {"metadata_field": "metadata_value"})

            Different Search Strategies:
            .. code-block:: python

                from langchain_community.vectorstores import SingleStoreDB
                from langchain_openai import OpenAIEmbeddings

                s2 = SingleStoreDB.from_documents(
                    docs,
                    OpenAIEmbeddings(),
                    host="username:password@localhost:3306/database",
                    use_full_text_search=True,
                    use_vector_index=True,
                )
                results = s2.similarity_search("query text", 1,
                        search_strategy=SingleStoreDB.SearchStrategy.FILTER_BY_TEXT,
                        filter_threshold=0.5)

            Weighted Sum Search Strategy:
            .. code-block:: python

                from langchain_community.vectorstores import SingleStoreDB
                from langchain_openai import OpenAIEmbeddings

                s2 = SingleStoreDB.from_documents(
                    docs,
                    OpenAIEmbeddings(),
                    host="username:password@localhost:3306/database",
                    use_full_text_search=True,
                    use_vector_index=True,
                )
                results = s2.similarity_search("query text", 1,
                    search_strategy=SingleStoreDB.SearchStrategy.WEIGHTED_SUM,
                    text_weight=0.3,
                    vector_weight=0.7)
        )querykfiltersearch_strategyfilter_thresholdtext_weightvector_weightvector_select_count_multiplierr(   )similarity_search_with_score)r1   r   r   r   r   r   r   r   r   rU   docs_and_scoresdoc_s                r*   similarity_searchzSingleStoreDB.similarity_search  sX    Z <$;; 

+-#'+I

 

 #22Q222s   1   c	                .    |t         j                  j                  k7  r& j                  st	        dj                  |            |t         j                  j                  k(  rB j                  t        j                  k7  r%t	        dj                  | j                              g }
|t         j                  j                  k7  r j                  j                  |      }
 j                  j                  |        j                  j                         }g }d}g }|s7|t         j                  j                  t         j                  j                   fv rd}g |t         j                  j                  k(  rUj#                  dj                   j$                               |j#                  |       |j#                  t'        |             |t         j                  j                   k(  rdj                  t)         j                  t              r j                  j*                  n j                   j,                        } j                  t        j.                  k(  r|dz  }n|dz  }j#                  |       |j#                  d	j                  d
j1                  t3        t4        |
                         |j#                  t'        |             	 d	 	 	 	 	 	 	 d fd|r	 ||       |dj1                        z  }	 |j7                         }	 |t         j                  j                  k(  s|t         j                  j                  k(  rd} j8                  r%|t         j                  j                  k(  rd||z  z  }|j;                  dj                   j$                   j<                  t)         j                  t              r j                  j*                  n j                   j,                   j>                  ||t@         j                           d	j                  d
j1                  t3        t4        |
                  ftC        |      z   |fz          n+|t         j                  j                   k(  s|t         j                  j                  k(  r`|j;                  dj                   j$                   j<                   j$                   j>                  |      |ftC        |      z   |fz          n|t         j                  j                  k(  rY|j;                  dj                   j$                   j<                   jD                   j$                   j<                   j$                   j>                  | jD                  t)         j                  t              r j                  j*                  n j                   j,                   j>                  |t@         j                      jD                   jD                  t@         j                           |||ftC        |      z   d	j                  d
j1                  t3        t4        |
                  fz   tC        |      z   ||z  |fz          nt	        dj                  |            |jG                         D ]4  }tI        |d   |d         }|j#                  |t'        |d         f       6 	 |jK                          	 |jK                          |S # |jK                          w xY w# |jK                          w xY w)a<  Return docs most similar to query. Uses cosine similarity.

        Args:
            query: Text to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            filter: A dictionary of metadata fields and values to filter by.
                    Defaults to None.
            search_strategy (SearchStrategy): The search strategy to use.
                Default is SearchStrategy.VECTOR_ONLY.
                Available options are:
                - SearchStrategy.VECTOR_ONLY: Searches only by vector similarity.
                - SearchStrategy.TEXT_ONLY: Searches only by text similarity. This
                    option is only available if use_full_text_search is True.
                - SearchStrategy.FILTER_BY_TEXT: Filters by text similarity and
                    searches by vector similarity. This option is only available if
                    use_full_text_search is True.
                - SearchStrategy.FILTER_BY_VECTOR: Filters by vector similarity and
                    searches by text similarity. This option is only available if
                    use_full_text_search is True.
                - SearchStrategy.WEIGHTED_SUM: Searches by a weighted sum of text and
                    vector similarity. This option is only available if
                    use_full_text_search is True and distance_strategy is DOT_PRODUCT.
            filter_threshold (float): The threshold for filtering by text or vector
                similarity. Default is 0. This option has effect only if search_strategy
                is SearchStrategy.FILTER_BY_TEXT or SearchStrategy.FILTER_BY_VECTOR.
            text_weight (float): The weight of text similarity in the weighted sum
                search strategy. Default is 0.5. This option has effect only if
                search_strategy is SearchStrategy.WEIGHTED_SUM.
            vector_weight (float): The weight of vector similarity in the weighted sum
                search strategy. Default is 0.5. This option has effect only if
                search_strategy is SearchStrategy.WEIGHTED_SUM.
            vector_select_count_multiplier (int): The multiplier for the number of
                vectors to select when using the vector index. Default is 10.
                This parameter has effect only if use_vector_index is True and
                search_strategy is SearchStrategy.WEIGHTED_SUM or
                SearchStrategy.FILTER_BY_TEXT.
                The number of vectors selected will
                be k * vector_select_count_multiplier.
                This is needed due to the limitations of the vector index.
        Returns:
            List of Documents most similar to the query and score for each
            document.

        Raises:
            ValueError: If the search strategy is not supported with the
                distance strategy.

        Examples:
            Basic Usage:
            .. code-block:: python

                from langchain_community.vectorstores import SingleStoreDB
                from langchain_openai import OpenAIEmbeddings

                s2 = SingleStoreDB.from_documents(
                    docs,
                    OpenAIEmbeddings(),
                    host="username:password@localhost:3306/database"
                )
                results = s2.similarity_search_with_score("query text", 1,
                                    {"metadata_field": "metadata_value"})

            Different Search Strategies:

            .. code-block:: python

                from langchain_community.vectorstores import SingleStoreDB
                from langchain_openai import OpenAIEmbeddings

                s2 = SingleStoreDB.from_documents(
                    docs,
                    OpenAIEmbeddings(),
                    host="username:password@localhost:3306/database",
                    use_full_text_search=True,
                    use_vector_index=True,
                )
                results = s2.similarity_search_with_score("query text", 1,
                        search_strategy=SingleStoreDB.SearchStrategy.FILTER_BY_VECTOR,
                        filter_threshold=0.5)

            Weighted Sum Search Strategy:
            .. code-block:: python

                from langchain_community.vectorstores import SingleStoreDB
                from langchain_openai import OpenAIEmbeddings

                s2 = SingleStoreDB.from_documents(
                    docs,
                    OpenAIEmbeddings(),
                    host="username:password@localhost:3306/database",
                    use_full_text_search=True,
                    use_vector_index=True,
                )
                results = s2.similarity_search_with_score("query text", 1,
                    search_strategy=SingleStoreDB.SearchStrategy.WEIGHTED_SUM,
                    text_weight=0.3,
                    vector_weight=0.7)
        zVSearch strategy {} is not supported
                when use_full_text_search is Falsez=Search strategy {} is not supported with distance strategy {}r   zWHERE zMATCH ({}) AGAINST (%s) > %sz{}({}, JSON_ARRAY_PACK(%s)) z< %sz> %srv   rw   c                z   |xs g }|j                         D ]  }t        ||   t              r | ||   ||gz          (j                  dj	                  j
                  dj                  dgt        |      dz   z                     | ||gz   z  } | j                  t        j                  ||                 y )NzJSON_EXTRACT_JSON({}, {}) = %sz, z%sr   )
keys
isinstancer   r   rc   r?   r{   rd   re   rf   )where_clause_values
sub_filterprefix_argskey	argumentsbuild_where_clauser1   s       r*   r   zFSingleStoreDB.similarity_search_with_score.<locals>.build_where_clause  s    
 */R%??, PC!*S/48*/C+QTPUBU "((<CC $ 3 3 $		4&C4Dq4H*I J ,{cU/BB++224::jo3NOPr)   z AND zSEARCH_OPTIONS '{"k":%d}'zwSELECT {}, {}, {}({}, JSON_ARRAY_PACK(%s)) as __score
                        FROM {} {} ORDER BY __score {}{} LIMIT %szsSELECT {}, {}, MATCH ({}) AGAINST (%s) as __score
                        FROM {} {} ORDER BY __score DESC LIMIT %sa  SELECT {}, {}, __score1 * %s + __score2 * %s as __score
                        FROM (
                            SELECT {}, {}, {}, MATCH ({}) AGAINST (%s) as __score1 
                        FROM {} {}) r1 FULL OUTER JOIN (
                            SELECT {}, {}({}, JSON_ARRAY_PACK(%s)) as __score2
                            FROM {} {} ORDER BY __score2 {} LIMIT %s
                        ) r2 ON r1.{} = r2.{} ORDER BY __score {} LIMIT %szInvalid search strategy: {}r   r   )page_contentr6      rX   )r   z	List[Any]r   r   r   Optional[List[str]]returnNone)&r   r+   r   rF   
ValueErrorrc   r#   r<   r   DOT_PRODUCTr    rO   embed_queryrS   r/   r!   r"   r   r>   floatr   namer@   EUCLIDEAN_DISTANCEr{   r|   r}   rb   rB   rg   r?   r=   r   tuplerA   fetchallr   rh   )r1   r   r   r   r   r   r   r   r   rU   rO   ri   resultwhere_clauser   	conditionrj   search_optionsr   r   r   r   s   `                   @@r*   r   z*SingleStoreDB.similarity_search_with_scored  s>   ` };;GGG--66<f_6M  };;HHH&&*:*F*FFOVV#T%;%;  	m::DDD2259I""5)##++-)+_((77((99)
 
 $LI-">">"M"MM  299$:L:LM $**51#**51A+BC-">">"O"OO:AA!$"8"8:JK **////%%		 ))-=-P-PP'I'I  +#**6==#c9BU9V+WX#**51A+BC
 48P%.P P 1P 	P* "#6?GLL33L_	++-C[#}'C'C'O'OO&-*F*F*U*UU%'N--+(77FFG *G >>* KKEEKV .. //)$*@*@BRS !2277!%!7!7 -- OO(*.t/E/EFF  sxxC0C'DEG 345$& $}'C'C'T'TT&-*F*F*P*PPKKEEKV .. // .. OO(F 5)<#==D
 %(D(D(Q(QQKKN OUf .. // MM .. // .. OO( MM)$*@*@BRS !2277!%!7!7 -- OO(.t/E/EF MM MM.t/E/EF'O* %mU; 345!==#c92E)FGIJ   345 ==qA	B9!F %5<<_M  <<> 8C"AQHCMM3c!f"678 		JJL 		JJLs%   >\ N:[- 
\ -[??\ \c                ~     | |f||||||	||||
||||d|} |j                   |||j                  |      fi | |S )ai  Create a SingleStoreDB vectorstore from raw documents.
        This is a user-friendly interface that:
            1. Embeds documents.
            2. Creates a new table for the embeddings in SingleStoreDB.
            3. Adds the documents to the newly created table.
        This is intended to be a quick way to get started.
        Args:
            texts (List[str]): List of texts to add to the vectorstore.
            embedding (Embeddings): A text embedding model.
            metadatas (Optional[List[dict]], optional): Optional list of metadatas.
                Defaults to None.
            distance_strategy (DistanceStrategy, optional):
                Determines the strategy employed for calculating
                the distance between vectors in the embedding space.
                Defaults to DOT_PRODUCT.
                Available options are:
                - DOT_PRODUCT: Computes the scalar product of two vectors.
                    This is the default behavior
                - EUCLIDEAN_DISTANCE: Computes the Euclidean distance between
                    two vectors. This metric considers the geometric distance in
                    the vector space, and might be more suitable for embeddings
                    that rely on spatial relationships. This metric is not
                    compatible with the WEIGHTED_SUM search strategy.
            table_name (str, optional): Specifies the name of the table in use.
                Defaults to "embeddings".
            content_field (str, optional): Specifies the field to store the content.
                Defaults to "content".
            metadata_field (str, optional): Specifies the field to store metadata.
                Defaults to "metadata".
            vector_field (str, optional): Specifies the field to store the vector.
                Defaults to "vector".
            id_field (str, optional): Specifies the field to store the id.
                Defaults to "id".
            use_vector_index (bool, optional): Toggles the use of a vector index.
                Works only with SingleStoreDB 8.5 or later. Defaults to False.
                If set to True, vector_size parameter is required to be set to
                a proper value.
            vector_index_name (str, optional): Specifies the name of the vector index.
                Defaults to empty. Will be ignored if use_vector_index is set to False.
            vector_index_options (dict, optional): Specifies the options for
                the vector index. Defaults to {}.
                Will be ignored if use_vector_index is set to False. The options are:
                index_type (str, optional): Specifies the type of the index.
                    Defaults to IVF_PQFS.
                For more options, please refer to the SingleStoreDB documentation:
                https://docs.singlestore.com/cloud/reference/sql-reference/vector-functions/vector-indexing/
            vector_size (int, optional): Specifies the size of the vector.
                Defaults to 1536. Required if use_vector_index is set to True.
                Should be set to the same value as the size of the vectors
                stored in the vector_field.
            use_full_text_search (bool, optional): Toggles the use a full-text index
                on the document content. Defaults to False. If set to True, the table
                will be created with a full-text index on the content field,
                and the simularity_search method will all using TEXT_ONLY,
                FILTER_BY_TEXT, FILTER_BY_VECTOR, and WIGHTED_SUM search strategies.
                If set to False, the simularity_search method will only allow
                VECTOR_ONLY search strategy.

            pool_size (int, optional): Determines the number of active connections in
                the pool. Defaults to 5.
            max_overflow (int, optional): Determines the maximum number of connections
                allowed beyond the pool_size. Defaults to 10.
            timeout (float, optional): Specifies the maximum wait time in seconds for
                establishing a connection. Defaults to 30.

            Additional optional arguments provide further customization over the
            database connection:

            pure_python (bool, optional): Toggles the connector mode. If True,
                operates in pure Python mode.
            local_infile (bool, optional): Allows local file uploads.
            charset (str, optional): Specifies the character set for string values.
            ssl_key (str, optional): Specifies the path of the file containing the SSL
                key.
            ssl_cert (str, optional): Specifies the path of the file containing the SSL
                certificate.
            ssl_ca (str, optional): Specifies the path of the file containing the SSL
                certificate authority.
            ssl_cipher (str, optional): Sets the SSL cipher list.
            ssl_disabled (bool, optional): Disables SSL usage.
            ssl_verify_cert (bool, optional): Verifies the server's certificate.
                Automatically enabled if ``ssl_ca`` is specified.
            ssl_verify_identity (bool, optional): Verifies the server's identity.
            conv (dict[int, Callable], optional): A dictionary of data conversion
                functions.
            credential_type (str, optional): Specifies the type of authentication to
                use: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO.
            autocommit (bool, optional): Enables autocommits.
            results_type (str, optional): Determines the structure of the query results:
                tuples, namedtuples, dicts.
            results_format (str, optional): Deprecated. This option has been renamed to
                results_type.

        Example:
            .. code-block:: python

                from langchain_community.vectorstores import SingleStoreDB
                from langchain_openai import OpenAIEmbeddings

                s2 = SingleStoreDB.from_texts(
                    texts,
                    OpenAIEmbeddings(),
                    host="username:password@localhost:3306/database"
                )
        )r<   r=   r>   r?   r@   rA   rG   rH   rI   rB   rC   rD   rE   rF   )rr   rz   )clsr   rO   rs   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rU   instances                       r*   
from_textszSingleStoreDB.from_texts  sw    @ 
/!')%%-/!5#!5
  !
$ 	5)Y-F-Fu-MXQWXr)   c                F   | j                   j                         }	 |j                         }	 |j                  dj	                  | j
                               |j                          	 |j                          y# |j                          w xY w# |j                          w xY w)z}Drop the table and delete all data from the vectorstore.
        Vector store will be unusable after this operation.
        zDROP TABLE IF EXISTS {}N)rS   r/   rb   rg   rc   r=   rh   )r1   ri   rj   s      r*   dropzSingleStoreDB.drop  sr     ##++-	++-C5<<T__MN		JJL 		JJLs"   B *A9 B 9BB B )r1   r   r   r   ) rO   r   r<   r   r=   r}   r>   r}   r?   r}   r@   r}   rA   r}   rB   rQ   rC   r}   rD   Optional[dict]rE   rR   rF   rQ   rG   rR   rH   rR   rI   r   rU   r   )r   r   )r]   r}   r   r}   )r   zCallable[[float], float])r1   r   r   r   )NNF)ro   	List[str]rs   Optional[List[dict]]r4   Optional[List[List[float]]]rp   rQ   rU   r   r   r   )r   zIterable[str]rs   r   r4   r   rp   rQ   rU   r   r   r   rX   )r   r   rU   r   r   zbool | None)r   r}   r   rR   r   r   r   r+   r   r   r   r   r   r   r   rR   rU   r   r   zList[Document])r   r}   r   rR   r   r   r   r+   r   r   r   r   r   r   r   rR   rU   r   r   zList[Tuple[Document, float]])(r   zType[SingleStoreDB]r   r   rO   r   rs   r   r<   r   r=   r}   r>   r}   r?   r}   r@   r}   rA   r}   rB   rQ   rC   r}   rD   r   rE   rR   rF   rQ   rG   rR   rH   rR   rI   r   rU   r   r   r   )r   r   )r$   r%   r&   r'   r}   r   r+   r3   DEFAULT_DISTANCE_STRATEGYrV   propertyr4   rP   r`   rT   rt   rr   r   r   r   r   classmethodr   r   r(   r)   r*   r   r       s   &d &4 /H&&($!&!#/3%*#cc ,	c
 c c c c c c c -c c #c c  !c" #c$ %cJ  7:1l +/26 

 (
 0	

 
 
 

H +/26 << (< 0	<
 < < 
<|B !%*8*D*D"# ".0x3x3 x3 	x3
 (x3  x3 x3 x3 ),x3 x3 
x3z !%*8*D*D"# ".0bb b 	b
 (b  b b b ),b b 
&bH	 
 +/.G&&($!&!#/3%*%R RR R (	R
 ,R R R R R R R R -R R #R  !R" #R$ %R& 'R( 
)R Rhr)   r   )"
__future__r   re   r[   enumr   typingr   r   r   r   r	   r
   r   langchain_core._apir   langchain_core.documentsr   langchain_core.embeddingsr   langchain_core.vectorstoresr   r   sqlalchemy.poolr   &langchain_community.vectorstores.utilsr   r   r   r   r   __annotations__r   SingleStoreDBRetrieverr(   r)   r*   <module>r      s    "  	    + - 0 I % C,88  ''  & D  
	( K}K }}B  . r)   