
    NgY                        d dl mZ d dlZd dlmZ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 erd dlmZ  ed	d
d           G d de                      ZdS )    )annotationsN)TYPE_CHECKINGAnyDictIterableListOptionalTupleType)
deprecated)Document)
Embeddings)VectorStoreClusterz0.2.4z1.0z(langchain_couchbase.CouchbaseVectorStore)sinceremovalalternative_importc                     e Zd ZU dZdZded<   dZded<   dZded	<   d
Zded<   dDdZ	dDdZ
dDdZeedddEdZ	 	 	 dFdGd,ZdHdId.ZedJd/            ZdKd2Zd3i fdLd9Zd3i fdMd<Zd3i fdNd=Zd3i fdOd>ZedPdA            Ze	 dHdQdC            Zd S )RCouchbaseVectorStoreah  `Couchbase Vector Store` vector store.

    To use it, you need
    - a recent installation of the `couchbase` library
    - a Couchbase database with a pre-defined Search index with support for
        vector fields

    Example:
        .. code-block:: python

            from langchain_community.vectorstores import CouchbaseVectorStore
            from langchain_openai import OpenAIEmbeddings

            from couchbase.cluster import Cluster
            from couchbase.auth import PasswordAuthenticator
            from couchbase.options import ClusterOptions
            from datetime import timedelta

            auth = PasswordAuthenticator(username, password)
            options = ClusterOptions(auth)
            connect_string = "couchbases://localhost"
            cluster = Cluster(connect_string, options)

            # Wait until the cluster is ready for use.
            cluster.wait_until_ready(timedelta(seconds=5))

            embeddings = OpenAIEmbeddings()

            vectorstore = CouchbaseVectorStore(
                cluster=cluster,
                bucket_name="",
                scope_name="",
                collection_name="",
                embedding=embeddings,
                index_name="vector-index",
            )

            vectorstore.add_texts(["hello", "world"])
            results = vectorstore.similarity_search("ola", k=1)
    d   intDEFAULT_BATCH_SIZEmetadatastr_metadata_keytext_default_text_key	embedding_default_embedding_keyreturnboolc                    | j                                         }	 |                    | j                   dS # t          $ r Y dS w xY w)z:Check if the bucket exists in the linked Couchbase clusterTF)_clusterbuckets
get_bucket_bucket_name	Exception)selfbucket_managers     f/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/vectorstores/couchbase.py_check_bucket_existsz)CouchbaseVectorStore._check_bucket_existsD   sX    ..00	%%d&78884 	 	 	55	s   7 
AAc                   i }| j                                                                         D ];}g ||j        <   |j        D ]'}||j                                     |j                   (<| j        |                                vrt          d| j         d| j                   | j	        || j                 vr't          d| j	         d| j         d| j                   dS )zzCheck if the scope and collection exists in the linked Couchbase bucket
        Raises a ValueError if either is not foundzScope z not found in Couchbase bucket zCollection z not found in scope z in Couchbase bucket T)
_bucketcollectionsget_all_scopesnameappend_scope_namekeys
ValueErrorr'   _collection_name)r)   scope_collection_mapscope
collections       r+   "_check_scope_and_collection_existsz7CouchbaseVectorStore._check_scope_and_collection_existsM   s@    02 \--//>>@@ 	I 	IE/1 , $/ I I
$UZ077
HHHHI #7#<#<#>#>>>.) . .+. .    (<T=M(NNNNd3 N N#N N:>:KN N  
 t    c                n   | j         rWd | j                                                                        D             }| j        |vrt          d| j         d          nVd | j                                                                        D             }| j        |vrt          d| j         d          dS )zxCheck if the Search index exists in the linked Couchbase cluster
        Raises a ValueError if the index does not existc                    g | ]	}|j         
S  r1   .0indexs     r+   
<listcomp>z<CouchbaseVectorStore._check_index_exists.<locals>.<listcomp>n   '       $
  r;   zIndex z; does not exist.  Please create the index before searching.c                    g | ]	}|j         
S r>   r?   r@   s     r+   rC   z<CouchbaseVectorStore._check_index_exists.<locals>.<listcomp>w   rD   r;   T)_scoped_index_scopesearch_indexesget_all_indexes_index_namer5   r$   )r)   all_indexess     r+   _check_index_existsz(CouchbaseVectorStore._check_index_existsj   s	     	 (,(B(B(D(D(T(T(V(V  K {22 AT- A A A   3 (,(D(D(F(F(V(V(X(X  K {22 AT- A A A  
 tr;   T)text_keyembedding_keyscoped_indexclusterr   bucket_name
scope_namecollection_namer   
index_namerM   Optional[str]rN   rO   Nonec                  	 ddl m}
 n"# t          $ r}t          d          |d}~ww xY wt          ||
          st	          dt          |                     || _        |st	          d          |st	          d          |st	          d          |st	          d	          |st	          d
          || _        || _        || _	        || _
        || _        || _        || _        |	| _        |                                 st	          d| j         d          	 | j                            | j                  | _        | j                            | j                  | _        | j                            | j	                  | _        n"# t,          $ r}t	          d          |d}~ww xY w	 |                                  n# t,          $ r}|d}~ww xY w	 |                                  dS # t,          $ r}|d}~ww xY w)av  
        Initialize the Couchbase Vector Store.

        Args:

            cluster (Cluster): couchbase cluster object with active connection.
            bucket_name (str): name of bucket to store documents in.
            scope_name (str): name of scope in the bucket to store documents in.
            collection_name (str): name of collection in the scope to store documents in
            embedding (Embeddings): embedding function to use.
            index_name (str): name of the Search index to use.
            text_key (optional[str]): key in document to use as text.
                Set to text by default.
            embedding_key (optional[str]): key in document to use for the embeddings.
                Set to embedding by default.
            scoped_index (optional[bool]): specify whether the index is a scoped index.
                Set to True by default.
        r   r   zfCould not import couchbase python package. Please install couchbase SDK  with `pip install couchbase`.Nz8cluster should be an instance of couchbase.Cluster, got z%Embeddings instance must be provided.zbucket_name must be provided.zscope_name must be provided.z!collection_name must be provided.zindex_name must be provided.zBucket z< does not exist.  Please create the bucket before searching.zKError connecting to couchbase. Please check the connection and credentials.)couchbase.clusterr   ImportError
isinstancer5   typer$   r'   r3   r6   _embedding_function	_text_key_embedding_keyrJ   rF   r,   bucketr.   r8   rG   r9   _collectionr(   r:   rL   )r)   rP   rQ   rR   rS   r   rT   rM   rN   rO   r   es               r+   __init__zCouchbaseVectorStore.__init__   s   >	1111111 	 	 	N  	 '7++ 	'G}}' '  
   	FDEEE 	><=== 	=;<<< 	B@AAA 	=;<<<'% /#, !+%) ((** 	>$+ > > >  
	=//0ABBDL,,,T-=>>DK#{55d6KLLD 	 	 	?  		335555 	 	 	G		$$&&&&& 	 	 	G	sY   	 
(#(A,F 
F'F""F'+G   
G
GGG+ +
G<5G77G<NtextsIterable[str]	metadatasOptional[List[Dict[str, Any]]]idsOptional[List[str]]
batch_sizeOptional[int]kwargsr   	List[str]c                2    ddl m} |s j        }g }|d |D             }|d |D             } j                            t          |                    } fdt          ||||          D             g}	t          dt          |	          |          D ]}
|	|
|
|z            }	  j	        
                    |d                   }|j        r-|                    |d                                                    e# |$ r}t          d|           d}~ww xY w|S )aK  Run texts through the embeddings and persist in vectorstore.

        If the document IDs are passed, the existing documents (if any) will be
        overwritten with the new ones.

        Args:
            texts (Iterable[str]): Iterable of strings to add to the vectorstore.
            metadatas (Optional[List[Dict]]): Optional list of metadatas associated
                with the texts.
            ids (Optional[List[str]]): Optional list of ids associated with the texts.
                IDs have to be unique strings across the collection.
                If it is not specified uuids are generated and used as ids.
            batch_size (Optional[int]): Optional batch size for bulk insertions.
                Default is 100.

        Returns:
            List[str]:List of ids from adding the texts into the vectorstore.
        r   )DocumentExistsExceptionNc                >    g | ]}t          j                    j        S r>   )uuiduuid4hexrA   _s     r+   rC   z2CouchbaseVectorStore.add_texts.<locals>.<listcomp>  s!    3334:<<#333r;   c                    g | ]}i S r>   r>   rs   s     r+   rC   z2CouchbaseVectorStore.add_texts.<locals>.<listcomp>
  s    ++++++r;   c           	     J    i | ]\  }}}}|j         |j        |j        |i S r>   )r]   r^   r   )rA   idr   vectorr   r)   s        r+   
<dictcomp>z2CouchbaseVectorStore.add_texts.<locals>.<dictcomp>  sO     	 	 	 /Bfh ND'&	 	 	r;   zDocument already exists: )couchbase.exceptionsrn   r   r\   embed_documentslistziprangelenr`   upsert_multiall_okextendr4   r5   )r)   rc   re   rg   ri   rk   rn   doc_idsembedded_textsdocuments_to_insertibatchresultra   s   `             r+   	add_textszCouchbaseVectorStore.add_texts   s   4 	A@@@@@ 	10J;33U333C++U+++I1AA$u++NN	 	 	 	 36	3 3	 	 	
 q#122J?? 	B 	BA'A
N(:;EB)66uQx@@= 4NN58==??333* B B B !@Q!@!@AAAB s   #AC88D=DDOptional[bool]c                X   ddl m} |t          d          |                    d| j                  }d}t          dt          |          |          D ]V}||||z            }	 | j                            |          }n!# |$ r}	d}t          d|	           d}	~	ww xY w||j	        z  }W|S )	aF  Delete documents from the vector store by ids.

        Args:
            ids (List[str]): List of IDs of the documents to delete.
            batch_size (Optional[int]): Optional batch size for bulk deletions.

        Returns:
            bool: True if all the documents were deleted successfully, False otherwise.

        r   )DocumentNotFoundExceptionNz#No document ids provided to delete.ri   TFzDocument not found: )
rz   r   r5   getr   r~   r   r`   remove_multir   )
r)   rg   rk   r   ri   deletion_statusr   r   r   ra   s
             r+   deletezCouchbaseVectorStore.delete'  s     	CBBBBB;BCCCZZd.EFF
 q#c((J// 	- 	-AA
N*+E=)66u==, = = ="' !;!;!;<<<= v},OOs   #A>>BBBc                    | j         S )z"Return the query embedding object.)r\   )r)   s    r+   
embeddingszCouchbaseVectorStore.embeddingsG  s     ''r;   
row_fieldsDict[str, Any]c                    i }|                                 D ]M\  }}|                    | j                  r)|                    | j        dz             d         }|||<   H|||<   N|S )zHelper method to format the metadata from the Couchbase Search API.
        Args:
            row_fields (Dict[str, Any]): The fields to format.

        Returns:
            Dict[str, Any]: The formatted metadata.
        .)items
startswithr   split)r)   r   r   keyvaluenew_keys         r+   _format_metadataz%CouchbaseVectorStore._format_metadataL  s|     $**,, 	& 	&JC ~~d011 &))D$6$<==bA$)!! %r;      List[float]ksearch_optionsOptional[Dict[str, Any]]List[Tuple[Document, float]]c           	     @   ddl m} ddlm} ddlm}m} |                    ddg          }	|	dgk    r#| j        |	vr|		                    | j                   |j
                            |                     || j        ||                              }
	 | j        r.| j                            | j        |
 |||	|                    }n.| j                            | j        |
 |||	|                    }g }|                                D ]k}|j                            | j        d	          }|                     |j                  }|j        }t/          ||
          }|	                    ||f           ln$# t0          $ r}t3          d|           d}~ww xY w|S )a  Return docs most similar to embedding vector with their scores.

        Args:
            embedding (List[float]): Embedding vector to look up documents similar to.
            k (int): Number of Documents to return.
                Defaults to 4.
            search_options (Optional[Dict[str, Any]]): Optional search options that are
                passed to Couchbase search.
                Defaults to empty dictionary.
            fields (Optional[List[str]]): Optional list of fields to include in the
                metadata of results. Note that these need to be stored in the index.
                If nothing is specified, defaults to all the fields stored in the index.

        Returns:
            List of (Document, score) that are the most similar to the query vector.
        r   N)SearchOptions)VectorQueryVectorSearchfields*)limitr   raw)rB   requestoptions )page_contentr   zSearch failed with error: )couchbase.searchsearchcouchbase.optionsr   couchbase.vector_searchr   r   r   r]   r2   SearchRequestcreatefrom_vector_queryr^   rF   rG   rJ   r$   rowsr   popr   scorer   r(   r5   )r)   r   r   r   rk   r   r   r   r   r   
search_reqsearch_iterdocs_with_scorerowr   r   r   docra   s                      r+   &similarity_search_with_score_by_vectorz;CouchbaseVectorStore.similarity_search_with_score_by_vector`  s   . 	*)))))333333EEEEEEEEHse,, cU??t~V;;MM$.))))00**'  
 

!	?! "k00$!M%*    #m22*&)M&nUUU 3   !O #'')) 5 5z~~dnb99  00<<	D8DDD&&U|44445  	? 	? 	?=!==>>>	? s   C%E: :
FFFqueryList[Document]c                n    | j                             |          } | j        |||fi |}d |D             S )a  Return documents most similar to embedding vector with their scores.

        Args:
            query (str): Query to look up for similar documents
            k (int): Number of Documents to return.
                Defaults to 4.
            search_options (Optional[Dict[str, Any]]): Optional search options that are
                passed to Couchbase search.
                Defaults to empty dictionary
            fields (Optional[List[str]]): Optional list of fields to include in the
                metadata of results. Note that these need to be stored in the index.
                If nothing is specified, defaults to all the fields stored in the index.

        Returns:
            List of Documents most similar to the query.
        c                    g | ]\  }}|S r>   r>   rA   r   rt   s      r+   rC   z:CouchbaseVectorStore.similarity_search.<locals>.<listcomp>  s    333Q333r;   r   embed_queryr   )r)   r   r   r   rk   query_embeddingdocs_with_scoress          r+   similarity_searchz&CouchbaseVectorStore.similarity_search  sY    . /55e<<F4FQ
 
28
 
 43"23333r;   c                Z    | j                             |          } | j        |||fi |}|S )a  Return documents that are most similar to the query with their scores.

        Args:
            query (str): Query to look up for similar documents
            k (int): Number of Documents to return.
                Defaults to 4.
            search_options (Optional[Dict[str, Any]]): Optional search options that are
                passed to Couchbase search.
                Defaults to empty dictionary.
            fields (Optional[List[str]]): Optional list of fields to include in the
                metadata of results. Note that these need to be stored in the index.
                If nothing is specified, defaults to text and metadata fields.

        Returns:
            List of (Document, score) that are most similar to the query.
        r   )r)   r   r   r   rk   r   r   s          r+   similarity_search_with_scorez1CouchbaseVectorStore.similarity_search_with_score  sI    . /55e<<E$EQ
 
28
 
 r;   c                :     | j         |||fi |}d |D             S )a  Return documents that are most similar to the vector embedding.

        Args:
            embedding (List[float]): Embedding to look up documents similar to.
            k (int): Number of Documents to return.
                Defaults to 4.
            search_options (Optional[Dict[str, Any]]): Optional search options that are
                passed to Couchbase search.
                Defaults to empty dictionary.
            fields (Optional[List[str]]): Optional list of fields to include in the
                metadata of results. Note that these need to be stored in the index.
                If nothing is specified, defaults to document text and metadata fields.

        Returns:
            List of Documents most similar to the query.
        c                    g | ]\  }}|S r>   r>   r   s      r+   rC   zDCouchbaseVectorStore.similarity_search_by_vector.<locals>.<listcomp>  s    222Q222r;   )r   )r)   r   r   r   rk   r   s         r+   similarity_search_by_vectorz0CouchbaseVectorStore.similarity_search_by_vector  sC    . F$Eq.
 
,2
 
 32/2222r;   clsType[CouchbaseVectorStore]c                   |                     dd          }|                     dd          }|                     dd          }|                     dd          }|                     dd          }|                     d| j                  }|                     d| j                  }	|                     d	d
          }
 | ||||||||	|
	  	        S )a4  Initialize the Couchbase vector store from keyword arguments for the
        vector store.

        Args:
            embedding: Embedding object to use to embed text.
            **kwargs: Keyword arguments to initialize the vector store with.
                Accepted arguments are:
                    - cluster
                    - bucket_name
                    - scope_name
                    - collection_name
                    - index_name
                    - text_key
                    - embedding_key
                    - scoped_index

        rP   NrQ   rR   rS   rT   rM   rN   rO   T)	r   rP   rQ   rR   rS   rT   rM   rN   rO   )r   r   r    )r   r   rk   rP   rQ   rR   rS   rT   rM   rN   rO   s              r+   _from_kwargsz!CouchbaseVectorStore._from_kwargs  s    . **Y--jj55ZZd33
 **%6==ZZd33
::j#*?@@

?C4NOOzz.$77s#!+!'%

 

 

 
	
r;   Optional[List[Dict[Any, Any]]]c                     | j         |fi |}|                    d|j                  }|                    dd          }|                    ||||           |S )a  Construct a Couchbase vector store from a list of texts.

        Example:
            .. code-block:: python

            from langchain_community.vectorstores import CouchbaseVectorStore
            from langchain_openai import OpenAIEmbeddings

            from couchbase.cluster import Cluster
            from couchbase.auth import PasswordAuthenticator
            from couchbase.options import ClusterOptions
            from datetime import timedelta

            auth = PasswordAuthenticator(username, password)
            options = ClusterOptions(auth)
            connect_string = "couchbases://localhost"
            cluster = Cluster(connect_string, options)

            # Wait until the cluster is ready for use.
            cluster.wait_until_ready(timedelta(seconds=5))

            embeddings = OpenAIEmbeddings()

            texts = ["hello", "world"]

            vectorstore = CouchbaseVectorStore.from_texts(
                texts,
                embedding=embeddings,
                cluster=cluster,
                bucket_name="",
                scope_name="",
                collection_name="",
                index_name="vector-index",
            )

        Args:
            texts (List[str]): list of texts to add to the vector store.
            embedding (Embeddings): embedding function to use.
            metadatas (optional[List[Dict]): list of metadatas to add to documents.
            **kwargs: Keyword arguments used to initialize the vector store with and/or
                passed to `add_texts` method. Check the constructor and/or `add_texts`
                for the list of accepted arguments.

        Returns:
            A Couchbase vector store.

        ri   rg   N)re   rg   ri   )r   r   r   r   )r   rc   r   re   rk   vector_storeri   rg   s           r+   
from_textszCouchbaseVectorStore.from_texts1  sv    n (s'	<<V<<ZZl.MNN
jj%%YCJ 	 	
 	
 	
 r;   )r!   r"   )rP   r   rQ   r   rR   r   rS   r   r   r   rT   r   rM   rU   rN   rU   rO   r"   r!   rV   )NNN)rc   rd   re   rf   rg   rh   ri   rj   rk   r   r!   rl   )N)rg   rh   rk   r   r!   r   )r!   r   )r   r   r!   r   )
r   r   r   r   r   r   rk   r   r!   r   )
r   r   r   r   r   r   rk   r   r!   r   )
r   r   r   r   r   r   rk   r   r!   r   )
r   r   r   r   r   r   rk   r   r!   r   )r   r   r   r   rk   r   r!   r   )r   r   rc   rl   r   r   re   r   rk   r   r!   r   )__name__
__module____qualname____doc__r   __annotations__r   r   r    r,   r:   rL   rb   r   r   propertyr   r   r   r   r   r   classmethodr   r   r>   r;   r+   r   r      s!        ' 'T "!!!!#M#########"-----      :   B #4'=!b b b b b bN 59#'$(? ? ? ? ?B    @ ( ( ( X(   . 35	M M M M Md 35	4 4 4 4 4@ 35	    @ 35	3 3 3 3 38 )
 )
 )
 [)
V 
 59	= = = = [= = =r;   r   )
__future__r   rp   typingr   r   r   r   r   r	   r
   r   langchain_core._api.deprecationr   langchain_core.documentsr   langchain_core.embeddingsr   langchain_core.vectorstoresr   rX   r   r   r>   r;   r+   <module>r      s%   " " " " " "  R R R R R R R R R R R R R R R R R R R R 6 6 6 6 6 6 - - - - - - 0 0 0 0 0 0 3 3 3 3 3 3 *)))))) 
A  
[	 [	 [	 [	 [	; [	 [	 
[	 [	 [	r;   