id
stringlengths
14
16
text
stringlengths
29
2.73k
source
stringlengths
49
115
df52c41c6f0c-1
return values [docs] def compress_documents( self, documents: Sequence[Document], query: str ) -> Sequence[Document]: """Filter documents based on similarity of their embeddings to the query.""" stateful_documents = get_stateful_documents(documents) embedded_documents = _get_embed...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html
6508c12ebb30-0
Source code for langchain.retrievers.document_compressors.cohere_rerank from __future__ import annotations from typing import TYPE_CHECKING, Dict, Sequence from pydantic import root_validator from langchain.retrievers.document_compressors.base import BaseDocumentCompressor from langchain.schema import Document from lan...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html
6508c12ebb30-1
doc.metadata["relevance_score"] = r.relevance_score final_results.append(doc) return final_results [docs] async def acompress_documents( self, documents: Sequence[Document], query: str ) -> Sequence[Document]: raise NotImplementedError By Harrison Chase © Copyright ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html
8dbe23d4a445-0
Source code for langchain.retrievers.document_compressors.base """Interface for retrieved document compressors.""" from abc import ABC, abstractmethod from typing import List, Sequence, Union from pydantic import BaseModel from langchain.schema import BaseDocumentTransformer, Document class BaseDocumentCompressor(BaseM...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html
8dbe23d4a445-1
self, documents: Sequence[Document], query: str ) -> Sequence[Document]: """Compress retrieved documents given the query context.""" for _transformer in self.transformers: if isinstance(_transformer, BaseDocumentCompressor): documents = await _transformer.acompress_docume...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html
7d4ec64c94f0-0
Source code for langchain.retrievers.document_compressors.chain_extract """DocumentFilter that uses an LLM chain to extract the relevant parts of documents.""" from __future__ import annotations import asyncio from typing import Any, Callable, Dict, Optional, Sequence from langchain import LLMChain, PromptTemplate from...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html
7d4ec64c94f0-1
[docs] def compress_documents( self, documents: Sequence[Document], query: str ) -> Sequence[Document]: """Compress page content of raw documents.""" compressed_docs = [] for doc in documents: _input = self.get_input(query, doc) output = self.llm_chain.pred...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html
7d4ec64c94f0-2
_get_input = get_input if get_input is not None else default_get_input llm_chain = LLMChain(llm=llm, prompt=_prompt, **(llm_chain_kwargs or {})) return cls(llm_chain=llm_chain, get_input=_get_input) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html
23709cdfa505-0
Source code for langchain.vectorstores.pinecone """Wrapper around Pinecone vector database.""" from __future__ import annotations import uuid from typing import Any, Callable, Iterable, List, Optional, Tuple from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings from langchain...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
23709cdfa505-1
self._embedding_function = embedding_function self._text_key = text_key self._namespace = namespace [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, namespace: Optional[str] = None, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
23709cdfa505-2
filter: Optional[dict] = None, namespace: Optional[str] = None, ) -> List[Tuple[Document, float]]: """Return pinecone documents most similar to query, along with scores. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
23709cdfa505-3
namespace: Namespace to search in. Default will search in '' namespace. Returns: List of Documents most similar to the query and score for each """ if namespace is None: namespace = self._namespace query_obj = self._embedding_function(query) docs = [] ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
23709cdfa505-4
pinecone.init(api_key="***", environment="...") embeddings = OpenAIEmbeddings() pinecone = Pinecone.from_texts( texts, embeddings, index_name="langchain-demo" ) """ try: import pinecon...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
23709cdfa505-5
metadata = metadatas[i:i_end] else: metadata = [{} for _ in range(i, i_end)] for j, line in enumerate(lines_batch): metadata[j][text_key] = line to_upsert = zip(ids_batch, embeds, metadata) # upsert to Pinecone index.upsert(vect...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
0ce1eb24cd30-0
Source code for langchain.vectorstores.elastic_vector_search """Wrapper around Elasticsearch vector database.""" from __future__ import annotations import uuid from abc import ABC from typing import Any, Dict, Iterable, List, Optional, Tuple from langchain.docstore.document import Document from langchain.embeddings.bas...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
0ce1eb24cd30-1
# and attributes. [docs]class ElasticVectorSearch(VectorStore, ABC): """Wrapper around Elasticsearch as a vector database. To connect to an Elasticsearch instance that does not require login credentials, pass the Elasticsearch URL and index name along with the embedding object to the constructor. Ex...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
0ce1eb24cd30-2
Example: .. code-block:: python from langchain import ElasticVectorSearch from langchain.embeddings import OpenAIEmbeddings embedding = OpenAIEmbeddings() elastic_host = "cluster_id.region_id.gcp.cloud.es.io" elasticsearch_url = f"https://username:pass...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
0ce1eb24cd30-3
[docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, refresh_indices: bool = True, **kwargs: Any, ) -> List[str]: """Run more texts through the embeddings and add to the vectorstore. Args: texts: Iterable of ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
0ce1eb24cd30-4
"metadata": metadata, "_id": _id, } ids.append(_id) requests.append(request) bulk(self.client, requests) if refresh_indices: self.client.indices.refresh(index=self.index_name) return ids [docs] def similarity_search( self...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
0ce1eb24cd30-5
( Document( page_content=hit["_source"]["text"], metadata=hit["_source"]["metadata"], ), hit["_score"], ) for hit in hits ] return docs_and_scores [docs] @classmethod def from_texts( ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
0ce1eb24cd30-6
except ValueError as e: raise ValueError( "Your elasticsearch client string is misformatted. " f"Got error: {e} " ) index_name = kwargs.get("index_name", uuid.uuid4().hex) embeddings = embedding.embed_documents(texts) dim = len(embeddings[0]) mappi...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
73e0ed260a80-0
Source code for langchain.vectorstores.atlas """Wrapper around Atlas by Nomic.""" from __future__ import annotations import logging import uuid from typing import Any, Iterable, List, Optional, Type import numpy as np from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings from...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
73e0ed260a80-1
is_public (bool): Whether your project is publicly accessible. True by default. reset_project_if_exists (bool): Whether to reset this project if it already exists. Default False. Generally userful during development and testing. """ try: ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
73e0ed260a80-2
metadatas (Optional[List[dict]], optional): Optional list of metadatas. ids (Optional[List[str]]): An optional list of ids. refresh(bool): Whether or not to refresh indices with the updated data. Default True. Returns: List[str]: List of IDs of the added texts...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
73e0ed260a80-3
else: if metadatas is None: data = [ {"text": text, AtlasDB._ATLAS_DEFAULT_ID_FIELD: ids[i]} for i, text in enumerate(texts) ] else: for i, text in enumerate(texts): metadatas[i]["text"] =...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
73e0ed260a80-4
""" if self._embedding_function is None: raise NotImplementedError( "AtlasDB requires an embedding_function for text similarity search!" ) _embedding = self._embedding_function.embed_documents([query])[0] embedding = np.array(_embedding).reshape(1, -1) ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
73e0ed260a80-5
ids (Optional[List[str]]): Optional list of document IDs. If None, ids will be auto created description (str): A description for your project. is_public (bool): Whether your project is publicly accessible. True by default. reset_project_if_exists (bool...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
73e0ed260a80-6
ids: Optional[List[str]] = None, name: Optional[str] = None, api_key: Optional[str] = None, persist_directory: Optional[str] = None, description: str = "A description for your project", is_public: bool = True, reset_project_if_exists: bool = False, index_kwargs: O...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
73e0ed260a80-7
return cls.from_texts( name=name, api_key=api_key, texts=texts, embedding=embedding, metadatas=metadatas, ids=ids, description=description, is_public=is_public, reset_project_if_exists=reset_project_if_exists, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/atlas.html
329a57d26012-0
Source code for langchain.vectorstores.supabase from __future__ import annotations from itertools import repeat from typing import ( TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Type, Union, ) import numpy as np from langchain.docstore.document import Document from langchain.embe...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
329a57d26012-1
embedding: Embeddings, table_name: str, query_name: Union[str, None] = None, ) -> None: """Initialize with supabase client.""" try: import supabase # noqa: F401 except ImportError: raise ValueError( "Could not import supabase python pa...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
329a57d26012-2
if not table_name: raise ValueError("Supabase document table_name is required.") embeddings = embedding.embed_documents(texts) docs = cls._texts_to_documents(texts, metadatas) _ids = cls._add_vectors(client, table_name, embeddings, docs) return cls( client=client,...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
329a57d26012-3
self, query: List[float], k: int ) -> List[Tuple[Document, float]]: match_documents_params = dict(query_embedding=query, match_count=k) res = self._client.rpc(self.query_name, match_documents_params).execute() match_result = [ ( Document( metad...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
329a57d26012-4
metadatas: Optional[Iterable[dict[Any, Any]]] = None, ) -> List[Document]: """Return list of Documents from list of texts and metadatas.""" if metadatas is None: metadatas = repeat({}) docs = [ Document(page_content=text, metadata=metadata) for text, metad...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
329a57d26012-5
return id_list [docs] def max_marginal_relevance_search_by_vector( self, embedding: List[float], k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any, ) -> List[Document]: """Return docs selected using the maximal marginal relevance. ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
329a57d26012-6
k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any, ) -> List[Document]: """Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
329a57d26012-7
$$;``` """ embedding = self._embedding.embed_documents([query]) docs = self.max_marginal_relevance_search_by_vector( embedding[0], k, fetch_k, lambda_mult=lambda_mult ) return docs By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
22671331ea2a-0
Source code for langchain.vectorstores.faiss """Wrapper around FAISS vector database.""" from __future__ import annotations import math import pickle import uuid from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple import numpy as np from langchain.docstore.base import Addabl...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
22671331ea2a-1
[docs]class FAISS(VectorStore): """Wrapper around FAISS vector database. To use, you should have the ``faiss`` python package installed. Example: .. code-block:: python from langchain import FAISS faiss = FAISS(embedding_function, index, docstore, index_to_docstore_id) ""...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
22671331ea2a-2
starting_len = len(self.index_to_docstore_id) self.index.add(np.array(embeddings, dtype=np.float32)) # Get list of index, id, and docs. full_info = [ (starting_len + i, str(uuid.uuid4()), doc) for i, doc in enumerate(documents) ] # Add information to docst...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
22671331ea2a-3
self, text_embeddings: Iterable[Tuple[str, List[float]]], metadatas: Optional[List[dict]] = None, **kwargs: Any, ) -> List[str]: """Run more texts through the embeddings and add to the vectorstore. Args: text_embeddings: Iterable pairs of string and embedding to ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
22671331ea2a-4
# This happens when not enough docs are returned. continue _id = self.index_to_docstore_id[i] doc = self.docstore.search(_id) if not isinstance(doc, Document): raise ValueError(f"Could not find document for id {_id}, got {doc}") docs.append...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
22671331ea2a-5
"""Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. Returns: List of Documents most similar to the query. """ docs_and_scores = self.similarity_search_with_score(quer...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
22671331ea2a-6
np.array([embedding], dtype=np.float32), embeddings, k=k, lambda_mult=lambda_mult, ) selected_indices = [indices[0][i] for i in mmr_selected] docs = [] for i in selected_indices: if i == -1: # This happens when not enough do...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
22671331ea2a-7
embedding, k, fetch_k, lambda_mult=lambda_mult ) return docs [docs] def merge_from(self, target: FAISS) -> None: """Merge another FAISS object with the current one. Add the target FAISS to the current one. Args: target: FAISS object you wish to merge into the curre...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
22671331ea2a-8
) -> FAISS: faiss = dependable_faiss_import() index = faiss.IndexFlatL2(len(embeddings[0])) index.add(np.array(embeddings, dtype=np.float32)) documents = [] for i, text in enumerate(texts): metadata = metadatas[i] if metadatas else {} documents.append(Docu...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
22671331ea2a-9
metadatas, **kwargs, ) [docs] @classmethod def from_embeddings( cls, text_embeddings: List[Tuple[str, List[float]]], embedding: Embeddings, metadatas: Optional[List[dict]] = None, **kwargs: Any, ) -> FAISS: """Construct FAISS wrapper from ra...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
22671331ea2a-10
path = Path(folder_path) path.mkdir(exist_ok=True, parents=True) # save index separately since it is not picklable faiss = dependable_faiss_import() faiss.write_index( self.index, str(path / "{index_name}.faiss".format(index_name=index_name)) ) # save docstore...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
22671331ea2a-11
self, query: str, k: int = 4, **kwargs: Any, ) -> List[Tuple[Document, float]]: """Return docs and their similarity scores on a scale from 0 to 1.""" if self.relevance_score_fn is None: raise ValueError( "normalize_score_fn must be provided to" ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
65111daf92ee-0
Source code for langchain.vectorstores.zilliz from __future__ import annotations import logging from typing import Any, List, Optional from langchain.embeddings.base import Embeddings from langchain.vectorstores.milvus import Milvus logger = logging.getLogger(__name__) [docs]class Zilliz(Milvus): def _create_index(...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html
65111daf92ee-1
"Failed to create an index on collection: %s", self.collection_name ) raise e [docs] @classmethod def from_texts( cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, collection_name: str = "LangChainCollecti...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html
65111daf92ee-2
Zilliz: Zilliz Vector Store """ vector_db = cls( embedding_function=embedding, collection_name=collection_name, connection_args=connection_args, consistency_level=consistency_level, index_params=index_params, search_params=search_pa...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/zilliz.html
14acadc75e2f-0
Source code for langchain.vectorstores.myscale """Wrapper around MyScale vector database.""" from __future__ import annotations import json import logging from hashlib import sha1 from threading import Thread from typing import Any, Dict, Iterable, List, Optional, Tuple from pydantic import BaseSettings from langchain....
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
14acadc75e2f-1
.. code-block:: python { 'id': 'text_id', 'vector': 'text_embedding', 'text': 'text_plain', 'metadata': 'metadata_dictionary_in_json', }...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
14acadc75e2f-2
config: Optional[MyScaleSettings] = None, **kwargs: Any, ) -> None: """MyScale Wrapper to LangChain embedding_function (Embeddings): config (MyScaleSettings): Configuration to MyScale Client Other keyword arguments will pass into [clickhouse-connect](https://docs....
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
14acadc75e2f-3
CREATE TABLE IF NOT EXISTS {self.config.database}.{self.config.table}( {self.config.column_map['id']} String, {self.config.column_map['text']} String, {self.config.column_map['vector']} Array(Float32), {self.config.column_map['metadata']} JSON, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
14acadc75e2f-4
_data.append(f"({n})") i_str = f""" INSERT INTO TABLE {self.config.database}.{self.config.table}({ks}) VALUES {','.join(_data)} """ return i_str def _insert(self, transac: Iterable, column_names: Iterable[str]) -> N...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
14acadc75e2f-5
column_names[colmap_["metadata"]] = map(json.dumps, metadatas) assert len(set(colmap_) - set(column_names)) >= 0 keys, values = zip(*column_names.items()) try: t = None for v in self.pgbar( zip(*values), desc="Inserting data...", total=len(metadatas) ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
14acadc75e2f-6
texts (Iterable[str]): List or tuple of strings to be added config (MyScaleSettings, Optional): Myscale configuration text_ids (Optional[Iterable], optional): IDs for the texts. Defaults to None. batch_size (int, optional): Batchsi...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
14acadc75e2f-7
).named_results(): _repr += ( f"|\033[94m{r['name']:24s}\033[0m|\033[96m{r['type']:24s}\033[0m|\n" ) _repr += "-" * 51 + "\n" return _repr def _build_qstr( self, q_emb: List[float], topk: int, where_str: Optional[str] = None ) -> str: q_emb...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
14acadc75e2f-8
of SQL injection. When dealing with metadatas, remember to use `{self.metadata_column}.attribute` instead of `attribute` alone. The default name for it is `metadata`. Returns: List[Document]: List of Documents """ return self.similarity_search_by_v...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
14acadc75e2f-9
] except Exception as e: logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") return [] [docs] def similarity_search_with_relevance_scores( self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any ) -> List[Tuple[Document, float]]: ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
14acadc75e2f-10
return [] [docs] def drop(self) -> None: """ Helper function: Drop data """ self.client.command( f"DROP TABLE IF EXISTS {self.config.database}.{self.config.table}" ) @property def metadata_column(self) -> str: return self.config.column_map["metadata...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
c711e22f0f73-0
Source code for langchain.vectorstores.lancedb """Wrapper around LanceDB vector database""" from __future__ import annotations import uuid from typing import Any, Iterable, List, Optional from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings from langchain.vectorstores.base i...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html
c711e22f0f73-1
self._id_key = id_key self._text_key = text_key [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any, ) -> List[str]: """Turn texts into embedding and add it to the database...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html
c711e22f0f73-2
""" embedding = self._embedding.embed_query(query) docs = self._connection.search(embedding).limit(k).to_df() return [ Document( page_content=row[self._text_key], metadata=row[docs.columns != self._text_key], ) for _, row in doc...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/lancedb.html
c9e9346875b9-0
Source code for langchain.vectorstores.tair """Wrapper around Tair Vector.""" from __future__ import annotations import json import logging import uuid from typing import Any, Iterable, List, Optional, Type from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings from langchain....
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
c9e9346875b9-1
data_type: str, **kwargs: Any, ) -> bool: index = self.client.tvs_get_index(self.index_name) if index is not None: logger.info("Index already exists") return False self.client.tvs_create_index( self.index_name, dim, distance...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
c9e9346875b9-2
Args: query (str): The query text for which to find similar documents. k (int): The number of documents to return. Default is 4. Returns: List[Document]: A list of documents that are most similar to the query text. """ # Creates embedding vector from user quer...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
c9e9346875b9-3
if "tair_url" in kwargs: kwargs.pop("tair_url") distance_type = tairvector.DistanceMetric.InnerProduct if "distance_type" in kwargs: distance_type = kwargs.pop("distance_typ") index_type = tairvector.IndexType.HNSW if "index_type" in kwargs: index_type...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
c9e9346875b9-4
cls, documents: List[Document], embedding: Embeddings, metadatas: Optional[List[dict]] = None, index_name: str = "langchain", content_key: str = "content", metadata_key: str = "metadata", **kwargs: Any, ) -> Tair: texts = [d.page_content for d in docum...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
c9e9346875b9-5
# index not exist logger.info("Index does not exist") return False return True [docs] @classmethod def from_existing_index( cls, embedding: Embeddings, index_name: str = "langchain", content_key: str = "content", metadata_key: str = "metadat...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
7ae0fff4890a-0
Source code for langchain.vectorstores.qdrant """Wrapper around Qdrant vector database.""" from __future__ import annotations import uuid from hashlib import md5 from operator import itemgetter from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Type, Union from langchain.docstore.document import D...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
7ae0fff4890a-1
if not isinstance(client, qdrant_client.QdrantClient): raise ValueError( f"client should be an instance of qdrant_client.QdrantClient, " f"got {type(client)}" ) self.client: qdrant_client.QdrantClient = client self.collection_name = collection_name...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
7ae0fff4890a-2
k: int = 4, filter: Optional[MetadataFilter] = None, **kwargs: Any, ) -> List[Document]: """Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter: Filter by met...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
7ae0fff4890a-3
self, query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any, ) -> List[Document]: """Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity amon...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
7ae0fff4890a-4
embedding: Embeddings, metadatas: Optional[List[dict]] = None, location: Optional[str] = None, url: Optional[str] = None, port: Optional[int] = 6333, grpc_port: int = 6334, prefer_grpc: bool = False, https: Optional[bool] = None, api_key: Optional[str] = N...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
7ae0fff4890a-5
grpc_port: Port of the gRPC interface. Default: 6334 prefer_grpc: If true - use gPRC interface whenever possible in custom methods. Default: False https: If true - use HTTPS(SSL) protocol. Default: None api_key: API key for authentication in Qdrant Clo...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
7ae0fff4890a-6
2. Initializes the Qdrant database as an in-memory docstore by default (and overridable to a remote docstore) 3. Adds the text embeddings to the Qdrant database This is intended to be a quick way to get started. Example: .. code-block:: python from ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
7ae0fff4890a-7
), ) # Now generate the embeddings for all the texts embeddings = embedding.embed_documents(texts) client.upsert( collection_name=collection_name, points=rest.Batch.construct( ids=[md5(text.encode("utf-8")).hexdigest() for text in texts], ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
7ae0fff4890a-8
metadata_payload_key: str, ) -> Document: return Document( page_content=scored_point.payload.get(content_payload_key), metadata=scored_point.payload.get(metadata_payload_key) or {}, ) def _qdrant_filter_from_dict(self, filter: Optional[MetadataFilter]) -> Any: if ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
39a24f0b5c5f-0
Source code for langchain.vectorstores.opensearch_vector_search """Wrapper around OpenSearch vector database.""" from __future__ import annotations import uuid from typing import Any, Dict, Iterable, List, Optional from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings from la...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
39a24f0b5c5f-1
try: opensearch = _import_opensearch() client = opensearch(opensearch_url, **kwargs) except ValueError as e: raise ValueError( f"OpenSearch client string provided is not in proper format. " f"Got error: {e} " ) return client def _validate_embeddings_and_bu...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
39a24f0b5c5f-2
request = { "_op_type": "index", "_index": index_name, vector_field: embeddings[i], text_field: text, "metadata": metadata, "_id": _id, } requests.append(request) ids.append(_id) bulk(client, requests) client.indices...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
39a24f0b5c5f-3
"parameters": {"ef_construction": ef_construction, "m": m}, }, } } }, } def _default_approximate_search_query( query_vector: List[float], size: int = 4, k: int = 4, vector_field: str = "vector_field", ) -> Dict: """For Approximate k-NN Sear...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
39a24f0b5c5f-4
query_vector, size, k, vector_field ) search_query["query"]["knn"][vector_field]["filter"] = lucene_filter return search_query def _default_script_query( query_vector: List[float], space_type: str = "l2", pre_filter: Dict = MATCH_ALL_QUERY, vector_field: str = "vector_field", ) -> Dict: ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
39a24f0b5c5f-5
vector_field: str = "vector_field", ) -> Dict: """For Painless Scripting Search, this is the default query.""" source = __get_painless_scripting_source(space_type, query_vector) return { "query": { "script_score": { "query": pre_filter, "script": { ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
39a24f0b5c5f-6
bulk_size: int = 500, **kwargs: Any, ) -> List[str]: """Run more texts through the embeddings and add to the vectorstore. Args: texts: Iterable of strings to add to the vectorstore. metadatas: Optional list of metadatas associated with the texts. bulk_size...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
39a24f0b5c5f-7
texts, metadatas, vector_field, text_field, mapping, ) [docs] def similarity_search( self, query: str, k: int = 4, **kwargs: Any ) -> List[Document]: """Return docs most similar to query. By default supports Approximate Search. ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
39a24f0b5c5f-8
search_type: "script_scoring"; default: "approximate_search" space_type: "l2", "l1", "linf", "cosinesimil", "innerproduct", "hammingbit"; default: "l2" pre_filter: script_score query to pre-filter documents before identifying nearest neighbors; default: {"match_all": {}} ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
39a24f0b5c5f-9
"is invalid" ) if boolean_filter != {}: search_query = _approximate_search_query_with_boolean_filter( embedding, boolean_filter, size, k, vector_field, subquery_clause ) elif lucene_filter != {}: search_query = _...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
39a24f0b5c5f-10
for hit in hits ] return documents [docs] @classmethod def from_texts( cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[dict]] = None, bulk_size: int = 500, **kwargs: Any, ) -> OpenSearchVectorSearch: """Construct O...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
39a24f0b5c5f-11
ef_construction: Size of the dynamic list used during k-NN graph creation. Higher values lead to more accurate graph but slower indexing speed; default: 512 m: Number of bidirectional links created for each new element. Large impact on memory consumption. Between 2 and 10...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
39a24f0b5c5f-12
if is_appx_search: engine = _get_kwargs_value(kwargs, "engine", "nmslib") space_type = _get_kwargs_value(kwargs, "space_type", "l2") ef_search = _get_kwargs_value(kwargs, "ef_search", 512) ef_construction = _get_kwargs_value(kwargs, "ef_construction", 512) m =...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/opensearch_vector_search.html
5350863b55b6-0
Source code for langchain.vectorstores.analyticdb """VectorStore wrapper around a Postgres/PGVector database.""" from __future__ import annotations import logging import uuid from typing import Any, Dict, Iterable, List, Optional, Tuple import sqlalchemy from sqlalchemy import REAL, Index from sqlalchemy.dialects.postg...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
5350863b55b6-1
""" created = False collection = cls.get_by_name(session, name) if collection: return collection, created collection = cls(name=name, cmetadata=cmetadata) session.add(collection) session.commit() created = True return collection, created class ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
5350863b55b6-2
- `connection_string` is a postgres connection string. - `embedding_function` any embedding function implementing `langchain.embeddings.base.Embeddings` interface. - `collection_name` is the name of the collection to use. (default: langchain) - NOTE: This is not the name of the table, but the na...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
5350863b55b6-3
return conn [docs] def create_tables_if_not_exists(self) -> None: Base.metadata.create_all(self._conn) [docs] def drop_tables(self) -> None: Base.metadata.drop_all(self._conn) [docs] def create_collection(self) -> None: if self.pre_delete_collection: self.delete_collection()...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
5350863b55b6-4
embeddings = self.embedding_function.embed_documents(list(texts)) if not metadatas: metadatas = [{} for _ in texts] with Session(self._conn) as session: collection = self.get_collection(session) if not collection: raise ValueError("Collection not found...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
5350863b55b6-5
"""Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. Returns: List of Documents most similar to th...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html