
    3fi+                       d dl mZ d dlZd dlmZ d dlmZmZmZm	Z	 d dl
mZmZmZmZmZ d dlmZ d dl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!m"Z"  ejF                  e$      Z%ddZ&dZ' edde'       G d de             Z(	 	 	 	 	 	 	 	 ddZ)ddZ* edde'      dd       Z+ edde'       G d de             Z, edde'       G d de             Z-y)     )annotationsN)abstractmethod)AsyncIterable
CollectionIterableIterator)AnyClassVarOptionalSequencecast)
deprecated)#AsyncCallbackManagerForRetrieverRunCallbackManagerForRetrieverRun)Document)Serializable)run_in_executor)VectorStoreVectorStoreRetriever)Field)METADATA_LINKS_KEYLinkc                2    t               }t        | |      |uS )z\Checks if the iterator has more elements.
    Warning: consumes an element from the iterator)objectnext)iteratorsentinels     i/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_community/graph_vectorstores/base.py	_has_nextr      s     xH(#833    zuSee https://datastax.github.io/graph-rag/guide/migration/#from-langchain-graphvectorstore for migration instructions.z0.3.21z0.5)sinceremovaladdendumc                  h    e Zd ZU dZdZded<   	 ded<   	  ee      Zded	<   	  ee	      Z
d
ed<   y)Nodea  Node in the GraphVectorStore.

    Edges exist from nodes with an outgoing link to nodes with a matching incoming link.

    For instance two nodes `a` and `b` connected over a hyperlink ``https://some-url``
    would look like:

    .. code-block:: python

        [
            Node(
                id="a",
                text="some text a",
                links= [
                    Link(kind="hyperlink", tag="https://some-url", direction="incoming")
                ],
            ),
            Node(
                id="b",
                text="some text b",
                links= [
                    Link(kind="hyperlink", tag="https://some-url", direction="outgoing")
                ],
            )
        ]
    NzOptional[str]idstrtext)default_factorydictmetadataz
list[Link]links)__name__
__module____qualname____doc__r&   __annotations__r   r*   r+   listr,    r    r   r%   r%   +   sB    6 BW
I%40Hd0 d3E:3)r    r%   c              #    K   |rt        |      nd }|rt        |      nd }| D ]r  }	 |rt        |      j                         ni }	 |rt        |      nd }|j                  t        g       }	t        |	t              st        |	      }	t        ||||	       t |rt        |      rt	        d      |rt        |      rt	        d      y y # t        $ r}t	        d      |d }~ww xY w# t        $ r}t	        d      |d }~ww xY ww)Nz$texts iterable longer than metadatasztexts iterable longer than idsr&   r+   r(   r,   zids iterable longer than textsz$metadatas iterable longer than texts)iterr   copyStopIteration
ValueErrorpopr   
isinstancer2   r%   r   )
texts	metadatasidsmetadatas_itids_itr(   	_metadatae_idr,   s
             r   _texts_to_nodesrD   V   s    
 '04	?TLT#Y4F 
	L5A\*//1rI	F"($v,dC 0"5%&KE	
 	

& )F#9::	,/?@@ 0|%  	LCD!K	L  	F=>AE	FsG   $DC
C'A6D
	C$CC$$D'	D0C<<DDc              #     K   | D ]r  }|j                   j                         }|j                  t        g       }t	        |t
              st        |      }t        |j                  ||j                  |       t y w)Nr5   )	r+   r7   r:   r   r;   r2   r%   r&   page_content)	documentsdocr+   r,   s       r   _documents_to_nodesrI   v   sn      

<<$$&/4%&KEvv!!	
 	


s   A9A;c           	   #  6  K   | D ]  }|j                   j                         }|j                  D cg c].  }t        |j                  |j
                  |j                        0 c}|t        <   t        |j                  |j                  |        yc c}w w)zConvert nodes to documents.

    Args:
        nodes: The nodes to convert to documents.
    Returns:
        The documents generated from the nodes.
    )kind	directiontag)r&   rF   r+   N)r+   r7   r,   r   rK   rL   rM   r   r   r&   r(   )nodesnoder+   links       r   nodes_to_documentsrQ      s       
==%%' 

(
  dii4>>txxH(
#$ ww
 	

(
s   .B3B#6Bc            
      <   e Zd ZdZe	 	 	 	 	 	 dd       Z	 	 	 	 	 	 ddZ	 d dd	 	 	 	 	 	 	 	 	 d!dZ	 d dd	 	 	 	 	 	 	 	 	 d!dZ	 	 	 	 	 	 d"dZ		 	 	 	 	 	 d"d	Z
ed
ddd	 	 	 	 	 	 	 	 	 	 	 d#d       Zd
ddd	 	 	 	 	 	 	 	 	 	 	 d$dZedd
dddd ed      dd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d%d       Zdd
dddd ed      dd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d&dZ	 d'	 	 	 	 	 	 	 d(dZ	 	 	 d)	 	 	 	 	 	 	 	 	 	 	 d*dZ	 d'	 	 	 	 	 	 	 d(dZd+dZ	 	 	 	 	 	 	 	 d+dZd,dZy)-GraphVectorStorezA hybrid vector-and-graph graph store.

    Document chunks support vector-similarity search as well as edges linking
    chunks based on structural and semantic properties.

    .. versionadded:: 0.3.1
    c                     yzAdd nodes to the graph store.

        Args:
            nodes: the nodes to add.
            **kwargs: Additional keyword arguments.
        Nr3   )selfrN   kwargss      r   	add_nodeszGraphVectorStore.add_nodes       r    c                  K   t        t        d| j                  |fi | d{         }t               }	 t        dt        ||       d{   }||u ry| %7 87 wrU   )r6   r   rX   r   r   )rV   rN   rW   r   donerH   s         r   
aadd_nodeszGraphVectorStore.aadd_nodes   se      odDNNETVTTUx'dHdCCCd{I	  U Ds!   !A A(A AA A N)r>   c               T    t        |||      }t         | j                  |fi |      S )a  Run more texts through the embeddings and add to the vector store.

        The Links present in the metadata field `links` will be extracted to create
        the `Node` links.

        Eg if nodes `a` and `b` are connected over a hyperlink `https://some-url`, the
        function call would look like:

        .. code-block:: python

            store.add_texts(
                ids=["a", "b"],
                texts=["some text a", "some text b"],
                metadatas=[
                    {
                        "links": [
                            Link.incoming(kind="hyperlink", tag="https://some-url")
                        ]
                    },
                    {
                        "links": [
                            Link.outgoing(kind="hyperlink", tag="https://some-url")
                        ]
                    },
                ],
            )

        Args:
            texts: Iterable of strings to add to the vector store.
            metadatas: Optional list of metadatas associated with the texts.
                The metadata key `links` shall be an iterable of
                :py:class:`~langchain_community.graph_vectorstores.links.Link`.
            ids: Optional list of IDs associated with the texts.
            **kwargs: vector store specific parameters.

        Returns:
            List of ids from adding the texts into the vector store.
        )rD   r2   rX   )rV   r<   r=   r>   rW   rN   s         r   	add_textszGraphVectorStore.add_texts   s.    \  y#6NDNN53F344r    c                  K   t        |||      } | j                  |fi |2 cg c3 d{   }|7 6 c}S c c}w w)a  Run more texts through the embeddings and add to the vector store.

        The Links present in the metadata field `links` will be extracted to create
        the `Node` links.

        Eg if nodes `a` and `b` are connected over a hyperlink `https://some-url`, the
        function call would look like:

        .. code-block:: python

            await store.aadd_texts(
                ids=["a", "b"],
                texts=["some text a", "some text b"],
                metadatas=[
                    {
                        "links": [
                            Link.incoming(kind="hyperlink", tag="https://some-url")
                        ]
                    },
                    {
                        "links": [
                            Link.outgoing(kind="hyperlink", tag="https://some-url")
                        ]
                    },
                ],
            )

        Args:
            texts: Iterable of strings to add to the vector store.
            metadatas: Optional list of metadatas associated with the texts.
                The metadata key `links` shall be an iterable of
                :py:class:`~langchain_community.graph_vectorstores.links.Link`.
            ids: Optional list of IDs associated with the texts.
            **kwargs: vector store specific parameters.

        Returns:
            List of ids from adding the texts into the vector store.
        N)rD   r\   )rV   r<   r=   r>   rW   rN   rC   s          r   
aadd_textszGraphVectorStore.aadd_texts   sB     \  y#6%4T__U%Ef%EFFcFFFFs$   #>953
5959>c                P    t        |      }t         | j                  |fi |      S )  Run more documents through the embeddings and add to the vector store.

        The Links present in the document metadata field `links` will be extracted to
        create the `Node` links.

        Eg if nodes `a` and `b` are connected over a hyperlink `https://some-url`, the
        function call would look like:

        .. code-block:: python

            store.add_documents(
                [
                    Document(
                        id="a",
                        page_content="some text a",
                        metadata={
                            "links": [
                                Link.incoming(kind="hyperlink", tag="http://some-url")
                            ]
                        }
                    ),
                    Document(
                        id="b",
                        page_content="some text b",
                        metadata={
                            "links": [
                                Link.outgoing(kind="hyperlink", tag="http://some-url")
                            ]
                        }
                    ),
                ]

            )

        Args:
            documents: Documents to add to the vector store.
                The document's metadata key `links` shall be an iterable of
                :py:class:`~langchain_community.graph_vectorstores.links.Link`.

        Returns:
            List of IDs of the added texts.
        )rI   r2   rX   )rV   rG   rW   rN   s       r   add_documentszGraphVectorStore.add_documents0  s*    ^ $I.NDNN53F344r    c                |   K   t        |      } | j                  |fi |2 cg c3 d{   }|7 6 c}S c c}w w)rb   N)rI   r\   )rV   rG   rW   rN   rC   s        r   aadd_documentszGraphVectorStore.aadd_documentsb  s>     ^ $I.%4T__U%Ef%EFFcFFFFs$   !<731
3737<      kdepthfilterc                    y)  Retrieve documents from traversing this graph store.

        First, `k` nodes are retrieved using a search for each `query` string.
        Then, additional nodes are discovered up to the given `depth` from those
        starting nodes.

        Args:
            query: The query string.
            k: The number of Documents to return from the initial search.
                Defaults to 4. Applies to each of the query strings.
            depth: The maximum depth of edges to traverse. Defaults to 1.
            filter: Optional metadata to filter the results.
            **kwargs: Additional keyword arguments.
        Returns:
            Collection of retrieved documents.
        Nr3   )rV   queryri   rj   rk   rW   s         r   traversal_searchz!GraphVectorStore.traversal_search  rY   r    c          	       K   t        t        d| j                  |f|||d| d{         }t               }	 t        dt        ||       d{   }||u ry| %7 87 w)rm   Nrh   )r6   r   ro   r   r   )	rV   rn   ri   rj   rk   rW   r   r[   rH   s	            r   atraversal_searchz"GraphVectorStore.atraversal_search  s     2 !%%   

 x'dHdCCCd{I	  Ds!   %A$A (A$A"A$"A$r3      d   
         ?z-inf)initial_rootsri   rj   fetch_k
adjacent_klambda_multscore_thresholdrk   c                    y)  Retrieve documents from this graph store using MMR-traversal.

        This strategy first retrieves the top `fetch_k` results by similarity to
        the question. It then selects the top `k` results based on
        maximum-marginal relevance using the given `lambda_mult`.

        At each step, it considers the (remaining) documents from `fetch_k` as
        well as any documents connected by edges to a selected document
        retrieved based on similarity (a "root").

        Args:
            query: The query string to search for.
            initial_roots: Optional list of document IDs to use for initializing search.
                The top `adjacent_k` nodes adjacent to each initial root will be
                included in the set of initial candidates. To fetch only in the
                neighborhood of these nodes, set `fetch_k = 0`.
            k: Number of Documents to return. Defaults to 4.
            fetch_k: Number of Documents to fetch via similarity.
                Defaults to 100.
            adjacent_k: Number of adjacent Documents to fetch.
                Defaults to 10.
            depth: Maximum depth of a node (number of edges) from a node
                retrieved via similarity. Defaults to 2.
            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.
            score_threshold: Only documents with a score greater than or equal
                this threshold will be chosen. Defaults to negative infinity.
            filter: Optional metadata to filter the results.
            **kwargs: Additional keyword arguments.
        Nr3   )rV   rn   rv   ri   rj   rw   rx   ry   rz   rk   rW   s              r   mmr_traversal_searchz%GraphVectorStore.mmr_traversal_search  rY   r    c                 K   t        t        d| j                  |f||||||||	d|
 d{         }t               }	 t        dt        ||       d{   }||u ry| %7 87 w)r|   N)rv   ri   rw   rx   rj   ry   rz   rk   )r6   r   r}   r   r   )rV   rn   rv   ri   rj   rw   rx   ry   rz   rk   rW   r   r[   rH   s                 r   ammr_traversal_searchz&GraphVectorStore.ammr_traversal_search	  s     Z !)) ,%' /  
  x'dHdCCCd{I	 !" Ds!   *A)A%(A)A'A)'A)c                <    t        | j                  ||d            S Nr   )ri   rj   )r2   ro   )rV   rn   ri   rW   s       r   similarity_searchz"GraphVectorStore.similarity_searchM  s!     D))%1A)>??r    c           	         |j                  dd      dkD  rt        j                  d       t        | j	                  ||||d            S )Nrj   r   zT'mmr' search started with depth > 0. Maybe you meant to do a 'mmr_traversal' search?)ri   rw   ry   rj   )getloggerwarningr2   r}   )rV   rn   ri   rw   ry   rW   s         r   max_marginal_relevance_searchz.GraphVectorStore.max_marginal_relevance_searchR  sV     ::gq!A%NNB %%GA & 
 	
r    c                h   K   | j                  ||d      2 cg c3 d {   }|7 6 c}S c c}w wr   )rq   )rV   rn   ri   rW   rH   s        r   asimilarity_searchz#GraphVectorStore.asimilarity_searche  s5      &*%;%;EQa%;%PQQcQQQQs$   2-)'
)-)-2c                j   |dk(  r | j                   |fi |S |dk(  r( | j                  |fi |}|D cg c]  \  }}|	 c}}S |dk(  r | j                  |fi |S |dk(  rt         | j                  |fi |      S |dk(  rt         | j
                  |fi |      S t        d| d      c c}}w N
similaritysimilarity_score_thresholdmmr	traversalmmr_traversalzsearch_type of z| not allowed. Expected search_type to be 'similarity', 'similarity_score_threshold', 'mmr', 'traversal', or 'mmr_traversal'.)r   'similarity_search_with_relevance_scoresr   r2   ro   r}   r9   rV   rn   search_typerW   docs_and_similaritiesrH   _s          r   searchzGraphVectorStore.searchj  s    ,&)4))%:6::88$PD$P$P%%! '<<FCC<<E!5455eFvFFK'---e>v>??O+111%B6BCC!+ /: :  =s   B/c                  K   |dk(  r | j                   |fi | d {   S |dk(  r0 | j                  |fi | d {   }|D cg c]  \  }}|	 c}}S |dk(  r | j                  |fi | d {   S |dk(  r# | j                  |fi |2 cg c3 d {   }||dk(  r# | j                  |fi |2 cg c3 d {   }|t        d| d      7 7 c c}}w 7 m7 J6 c}S c c}w 7 -6 c}S c c}w wr   )r   (asimilarity_search_with_relevance_scoresamax_marginal_relevance_searchrq   r   r9   r   s          r   asearchzGraphVectorStore.asearch  s.     ,&000A&AAA88*W$*W*W++ %! '<<FCC<<E!<<<UMfMMMK')?)?)?)P)PQQ#CO+)C)C)CE)TV)TUU#C!+ /: :  B% =MQQQQUUUUs   C9CC9C	C9CC93C!4C9C)C%C#
C%C) C9:C4<C0 C.
C0C4C9C9C9#C%%C)&C9.C00C41C9c                    t        dd| i|S )a	  Return GraphVectorStoreRetriever initialized from this GraphVectorStore.

        Args:
            **kwargs: Keyword arguments to pass to the search function.
                Can include:

                - search_type (Optional[str]): Defines the type of search that
                  the Retriever should perform.
                  Can be ``traversal`` (default), ``similarity``, ``mmr``,
                   ``mmr_traversal``, or ``similarity_score_threshold``.
                - search_kwargs (Optional[Dict]): Keyword arguments to pass to the
                  search function. Can include things like:

                  - k(int): Amount of documents to return (Default: 4).
                  - depth(int): The maximum depth of edges to traverse (Default: 1).
                    Only applies to search_type: ``traversal`` and ``mmr_traversal``.
                  - score_threshold(float): Minimum relevance threshold
                    for similarity_score_threshold.
                  - fetch_k(int): Amount of documents to pass to MMR algorithm
                    (Default: 20).
                  - lambda_mult(float): Diversity of results returned by MMR;
                    1 for minimum diversity and 0 for maximum. (Default: 0.5).
        Returns:
            Retriever for this GraphVectorStore.

        Examples:

        .. code-block:: python

            # Retrieve documents traversing edges
            docsearch.as_retriever(
                search_type="traversal",
                search_kwargs={'k': 6, 'depth': 2}
            )

            # Retrieve documents with higher diversity
            # Useful if your dataset has many similar documents
            docsearch.as_retriever(
                search_type="mmr_traversal",
                search_kwargs={'k': 6, 'lambda_mult': 0.25, 'depth': 2}
            )

            # Fetch more documents for the MMR algorithm to consider
            # But only return the top 5
            docsearch.as_retriever(
                search_type="mmr_traversal",
                search_kwargs={'k': 5, 'fetch_k': 50, 'depth': 2}
            )

            # Only retrieve documents that have a relevance score
            # Above a certain threshold
            docsearch.as_retriever(
                search_type="similarity_score_threshold",
                search_kwargs={'score_threshold': 0.8}
            )

            # Only get the single most similar document from the dataset
            docsearch.as_retriever(search_kwargs={'k': 1})

        vectorstorer3   )GraphVectorStoreRetriever)rV   rW   s     r   as_retrieverzGraphVectorStore.as_retriever  s    z )DTDVDDr    )rN   Iterable[Node]rW   r	   returnIterable[str])rN   r   rW   r	   r   zAsyncIterable[str]N)
r<   r   r=   Optional[Iterable[dict]]r>   Optional[Iterable[str]]rW   r	   r   	list[str])rG   Iterable[Document]rW   r	   r   r   )rn   r'   ri   intrj   r   rk   dict[str, Any] | NonerW   r	   r   r   )rn   r'   ri   r   rj   r   rk   r   rW   r	   r   AsyncIterable[Document])rn   r'   rv   Sequence[str]ri   r   rj   r   rw   r   rx   r   ry   floatrz   r   rk   r   rW   r	   r   r   )rn   r'   rv   r   ri   r   rj   r   rw   r   rx   r   ry   r   rz   r   rk   r   rW   r	   r   r   )rf   )rn   r'   ri   r   rW   r	   r   list[Document])rf      ru   )rn   r'   ri   r   rw   r   ry   r   rW   r	   r   r   )rn   r'   r   r'   rW   r	   r   r   )rW   r	   r   r   )r-   r.   r/   r0   r   rX   r\   r^   r`   rc   re   ro   rq   r   r}   r   r   r   r   r   r   r   r3   r    r   rS   rS      s    

 
 
	
 
  
	, /3/5
 (,/5/5 ,/5
 %/5 /5 
/5h /3/G
 (,/G/G ,/G
 %/G /G 
/Gb05%05 05 
	05d0G%0G 0G 
	0Gd 
 (, 	
  &  
 < (,)) 	)
 ) &) ) 
!)V 
 (* !&v(,,, %	,
 , , , , , , &, , 
, ,d (* !&v(,BB %	B
 B B B B B B &B B 
!BJ $%@@ @03@	@  

 
 	

 
 
 

( $%RR R03R	R
*'*69	.=Er    rS   c                       e Zd ZU dZded<   	 dZded<   	 dZded	<   edd
       Z	 	 	 	 	 	 	 	 d fdZ		 	 	 	 	 	 	 	 d fdZ
 xZS )r   a  Retriever for GraphVectorStore.

    A graph vector store retriever is a retriever that uses a graph vector store to
    retrieve documents.
    It is similar to a vector store retriever, except that it uses both vector
    similarity and graph connections to retrieve documents.
    It uses the search methods implemented by a graph vector store, like traversal
    search and MMR traversal search, to query the texts in the graph vector store.

    Example::

        store = CassandraGraphVectorStore(...)
        retriever = store.as_retriever()
        retriever.invoke("What is ...")

    .. seealso::

        :mod:`How to use a graph vector store <langchain_community.graph_vectorstores>`

    How to use a graph vector store as a retriever
    ==============================================

    Creating a retriever from a graph vector store
    ----------------------------------------------

    You can build a retriever from a graph vector store using its
    :meth:`~langchain_community.graph_vectorstores.base.GraphVectorStore.as_retriever`
    method.

    First we instantiate a graph vector store.
    We will use a store backed by Cassandra
    :class:`~langchain_community.graph_vectorstores.cassandra.CassandraGraphVectorStore`
    graph vector store::

        from langchain_community.document_loaders import TextLoader
        from langchain_community.graph_vectorstores import CassandraGraphVectorStore
        from langchain_community.graph_vectorstores.extractors import (
            KeybertLinkExtractor,
            LinkExtractorTransformer,
        )
        from langchain_openai import OpenAIEmbeddings
        from langchain_text_splitters import CharacterTextSplitter

        loader = TextLoader("state_of_the_union.txt")
        documents = loader.load()

        text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
        texts = text_splitter.split_documents(documents)

        pipeline = LinkExtractorTransformer([KeybertLinkExtractor()])
        pipeline.transform_documents(texts)
        embeddings = OpenAIEmbeddings()
        graph_vectorstore = CassandraGraphVectorStore.from_documents(texts, embeddings)

    We can then instantiate a retriever::

        retriever = graph_vectorstore.as_retriever()

    This creates a retriever (specifically a ``GraphVectorStoreRetriever``), which we
    can use in the usual way::

        docs = retriever.invoke("what did the president say about ketanji brown jackson?")

    Maximum marginal relevance traversal retrieval
    ----------------------------------------------

    By default, the graph vector store retriever uses similarity search, then expands
    the retrieved set by following a fixed number of graph edges.
    If the underlying graph vector store supports maximum marginal relevance traversal,
    you can specify that as the search type.

    MMR-traversal is a retrieval method combining MMR and graph traversal.
    The strategy first retrieves the top fetch_k results by similarity to the question.
    It then iteratively expands the set of fetched documents by following adjacent_k
    graph edges and selects the top k results based on maximum-marginal relevance using
    the given ``lambda_mult``::

        retriever = graph_vectorstore.as_retriever(search_type="mmr_traversal")

    Passing search parameters
    -------------------------

    We can pass parameters to the underlying graph vector store's search methods using
    ``search_kwargs``.

    Specifying graph traversal depth
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    For example, we can set the graph traversal depth to only return documents
    reachable through a given number of graph edges::

        retriever = graph_vectorstore.as_retriever(search_kwargs={"depth": 3})

    Specifying MMR parameters
    ^^^^^^^^^^^^^^^^^^^^^^^^^

    When using search type ``mmr_traversal``, several parameters of the MMR algorithm
    can be configured.

    The ``fetch_k`` parameter determines how many documents are fetched using vector
    similarity and ``adjacent_k`` parameter determines how many documents are fetched
    using graph edges.
    The ``lambda_mult`` parameter controls how the MMR re-ranking weights similarity to
    the query string vs diversity among the retrieved documents as fetched documents
    are selected for the set of ``k`` final results::

        retriever = graph_vectorstore.as_retriever(
            search_type="mmr",
            search_kwargs={"fetch_k": 20, "adjacent_k": 20, "lambda_mult": 0.25},
        )

    Specifying top k
    ^^^^^^^^^^^^^^^^

    We can also limit the number of documents ``k`` returned by the retriever.

    Note that if ``depth`` is greater than zero, the retriever may return more documents
    than is specified by ``k``, since both the original ``k`` documents retrieved using
    vector similarity and any documents connected via graph edges will be returned::

        retriever = graph_vectorstore.as_retriever(search_kwargs={"k": 1})

    Similarity score threshold retrieval
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    For example, we can set a similarity score threshold and only return documents with
    a score above that threshold::

        retriever = graph_vectorstore.as_retriever(search_kwargs={"score_threshold": 0.5})
    r   r   r   r'   r   )r   r   r   r   r   zClassVar[Collection[str]]allowed_search_typesc                6    t        t        | j                        S r   )r   rS   r   )rV   s    r   graph_vectorstorez+GraphVectorStoreRetriever.graph_vectorstorek  s    $d&6&677r    c               "   | j                   dk(  r0t         | j                  j                  |fi | j                        S | j                   dk(  r0t         | j                  j
                  |fi | j                        S t        |   ||      S Nr   r   )run_manager)r   r2   r   ro   search_kwargsr}   super_get_relevant_documents)rV   rn   r   rW   	__class__s       r   r   z1GraphVectorStoreRetriever._get_relevant_documentso  s     {*7&&77TASAST  0;&&;;EXTEWEWX  725k2RRr    c                 K   | j                   dk(  r7 | j                  j                  |fi | j                  2 cg c3 d {   }|| j                   dk(  r7 | j                  j                  |fi | j                  2 cg c3 d {   }|t
        |   ||       d {   S 7 f6 c}S c c}w 7 +6 c}S c c}w 7 wr   )r   r   rq   r   r   r   _aget_relevant_documents)rV   rn   r   rW   rH   r   s        r   r   z2GraphVectorStoreRetriever._aget_relevant_documents}  s      {* "J!7!7!I!I"!//"  
 0 "N!7!7!M!M"!//"   9; :         s{   9CB/B+B)
B+B/
8CB:B6B4
	B6B:C$B?%C)B++B/,C4B66B:7	C)r   rS   )rn   r'   r   r   rW   r	   r   r   )rn   r'   r   r   rW   r	   r   r   )r-   r.   r/   r0   r1   r   r   propertyr   r   r   __classcell__)r   s   @r   r   r     s    AF +"K"=73  8 8SS*HSTWS	S 9	
  
 r    r   )r   r   r   bool)r<   r   r=   r   r>   r   r   Iterator[Node])rG   r   r   r   )rN   r   r   zIterator[Document]).
__future__r   loggingabcr   collections.abcr   r   r   r   typingr	   r
   r   r   r   langchain_core._apir   langchain_core.callbacksr   r   langchain_core.documentsr   langchain_core.loadr   langchain_core.runnablesr   langchain_core.vectorstoresr   r   pydanticr   ,langchain_community.graph_vectorstores.linksr   r   	getLoggerr-   r   r   DEPRECATION_ADDENDUMr%   rD   rI   rQ   rS   r   r3   r    r   <module>r      s;   "   I I  + . , 4 I  Q			8	$4C  
!
#*< #*
#*LAA'A 
!A 	A@
 
!



. 
!
nE{ nE
nEb 
!
z 4 z
zr    