id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
4acc52497869-0
Source code for langchain.vectorstores.typesense """Wrapper around Typesense vector search""" from __future__ import annotations import uuid from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Union from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings fro...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
4acc52497869-1
*, typesense_collection_name: Optional[str] = None, text_key: str = "text", ): """Initialize with Typesense client.""" try: from typesense import Client except ImportError: raise ValueError( "Could not import typesense python package. "...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
4acc52497869-2
] def _create_collection(self, num_dim: int) -> None: fields = [ {"name": "vec", "type": "float[]", "num_dim": num_dim}, {"name": f"{self._text_key}", "type": "string"}, {"name": ".*", "type": "auto"}, ] self._typesense_client.collections.create( ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
4acc52497869-3
self, query: str, k: int = 4, filter: Optional[str] = "", ) -> List[Tuple[Document, float]]: """Return typesense documents most similar to query, along with scores. Args: query: Text to look up documents similar to. k: Number of Documents to return. De...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
4acc52497869-4
k: Number of Documents to return. Defaults to 4. filter: typesense filter_by expression to filter documents on Returns: List of Documents most similar to the query and score for each """ docs_and_score = self.similarity_search_with_score(query, k=k, filter=filter) ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
4acc52497869-5
} typesense_api_key = typesense_api_key or get_from_env( "typesense_api_key", "TYPESENSE_API_KEY" ) client_config = { "nodes": [node], "api_key": typesense_api_key, "connection_timeout_seconds": connection_timeout_seconds, } return ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
60ad5c3c5adc-0
Source code for langchain.vectorstores.singlestoredb """Wrapper around SingleStore DB.""" from __future__ import annotations import json from typing import ( Any, ClassVar, Collection, Iterable, List, Optional, Tuple, Type, ) from sqlalchemy.pool import QueuePool from langchain.docstore....
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
60ad5c3c5adc-1
timeout: float = 30, **kwargs: Any, ): """Initialize with necessary components. Args: embedding (Embeddings): A text embedding model. table_name (str, optional): Specifies the name of the table in use. Defaults to "embeddings". content_fiel...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
60ad5c3c5adc-2
local_infile (bool, optional): Allows local file uploads. charset (str, optional): Specifies the character set for string values. ssl_key (str, optional): Specifies the path of the file containing the SSL key. ssl_cert (str, optional): Specifies the path of the file c...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
60ad5c3c5adc-3
.. code-block:: python from langchain.embeddings import OpenAIEmbeddings from langchain.vectorstores import SingleStoreDB vectorstore = SingleStoreDB( OpenAIEmbeddings(), host="127.0.0.1", port=3306, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
60ad5c3c5adc-4
{} BLOB, {} JSON);""".format( self.table_name, self.content_field, self.vector_field, self.metadata_field, ), ) finally: cur.close() finally: ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
60ad5c3c5adc-5
finally: cur.close() finally: conn.close() return [] [docs] def similarity_search( self, query: str, k: int = 4, **kwargs: Any ) -> List[Document]: """Returns the most similar indexed documents to the query text. Uses cosine similarity. ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
60ad5c3c5adc-6
self.vector_field, self.table_name, ), ( "[{}]".format(",".join(map(str, embedding))), k, ), ) for row in cur.fetchall(): doc = Document...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
60ad5c3c5adc-7
) """ instance = cls( embedding, table_name=table_name, content_field=content_field, metadata_field=metadata_field, vector_field=vector_field, pool_size=pool_size, max_overflow=max_overflow, timeout=timeout, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/singlestoredb.html
bc839bff3176-0
Source code for langchain.vectorstores.vectara """Wrapper around Vectara vector database.""" from __future__ import annotations import json import logging import os from hashlib import md5 from typing import Any, Iterable, List, Optional, Tuple, Type import requests from pydantic import Field from langchain.embeddings....
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
bc839bff3176-1
or self._vectara_api_key is None ): logging.warning( "Cant find Vectara credentials, customer_id or corpus_id in " "environment." ) else: logging.debug(f"Using corpus id {self._vectara_corpus_id}") self._session = requests.Sessi...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
bc839bff3176-2
f"{response.status_code}, reason {response.reason}, text " f"{response.text}" ) return False return True def _index_doc(self, doc: dict) -> bool: request: dict[str, Any] = {} request["customer_id"] = self._vectara_customer_id request["corpus_id...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
bc839bff3176-3
metadatas = [{} for _ in texts] doc = { "document_id": doc_id, "metadataJson": json.dumps({"source": "langchain"}), "parts": [ {"text": text, "metadataJson": json.dumps(md)} for text, md in zip(texts, metadatas) ], } ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
bc839bff3176-4
{ "query": [ { "query": query, "start": 0, "num_results": k, "context_config": { "sentences_before": n_sentence_context, "sentences_...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
bc839bff3176-5
self, query: str, k: int = 5, lambda_val: float = 0.025, filter: Optional[str] = None, n_sentence_context: int = 0, **kwargs: Any, ) -> List[Document]: """Return Vectara documents most similar to query, along with scores. Args: query: Text ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
bc839bff3176-6
Example: .. code-block:: python from langchain import Vectara vectara = Vectara.from_texts( texts, vectara_customer_id=customer_id, vectara_corpus_id=corpus_id, vectara_api_key=api_key, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
bc839bff3176-7
) -> None: """Add text to the Vectara vectorstore. Args: texts (List[str]): The text metadatas (List[dict]): Metadata dicts, must line up with existing store """ self.vectorstore.add_texts(texts, metadatas) By Harrison Chase © Copyright 2023, Harrison C...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/vectara.html
e4b7ea968c42-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
e4b7ea968c42-1
""" Get or create a collection. Returns [Collection, bool] where the bool is True if the collection was created. """ created = False collection = cls.get_by_name(session, name) if collection: return collection, created collection = cls(name=name, cmeta...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
e4b7ea968c42-2
""" VectorStore implementation using AnalyticDB. AnalyticDB is a distributed full PostgresSQL syntax cloud-native database. - `connection_string` is a postgres connection string. - `embedding_function` any embedding function implementing `langchain.embeddings.base.Embeddings` interface. - `c...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
e4b7ea968c42-3
engine = sqlalchemy.create_engine(self.connection_string) conn = engine.connect() 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_col...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
e4b7ea968c42-4
""" if ids is None: ids = [str(uuid.uuid1()) for _ in texts] 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(sessi...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
e4b7ea968c42-5
self, query: str, k: int = 4, filter: Optional[dict] = None, ) -> List[Tuple[Document, float]]: """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...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
e4b7ea968c42-6
) .filter(filter_by) .order_by(EmbeddingStore.embedding.op("<->")(embedding)) .join( CollectionStore, EmbeddingStore.collection_id == CollectionStore.uuid, ) .limit(k) .all() ) docs = [ ( ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
e4b7ea968c42-7
pre_delete_collection: bool = False, **kwargs: Any, ) -> AnalyticDB: """ Return VectorStore initialized from texts and embeddings. Postgres connection string is required Either pass it as a parameter or set the PGVECTOR_CONNECTION_STRING environment variable. ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
e4b7ea968c42-8
or set the PGVECTOR_CONNECTION_STRING environment variable. """ texts = [d.page_content for d in documents] metadatas = [d.metadata for d in documents] connection_string = cls.get_connection_string(kwargs) kwargs["connection_string"] = connection_string return cls.from_te...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
40fade8f9055-0
Source code for langchain.vectorstores.faiss """Wrapper around FAISS vector database.""" from __future__ import annotations import math import os 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 imp...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
40fade8f9055-1
return faiss def _default_relevance_score_fn(score: float) -> float: """Return a similarity score on a scale [0, 1].""" # The 'correct' relevance function # may differ depending on a few things, including: # - the distance / similarity metric used by the VectorStore # - the scale of your embeddings ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
40fade8f9055-2
self._normalize_L2 = normalize_L2 def __add( self, texts: Iterable[str], embeddings: Iterable[List[float]], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any, ) -> List[str]: if not isinstance(self.docstore, AddableMixi...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
40fade8f9055-3
return [_id for _, _id, _ in full_info] [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[List[str]] = None, **kwargs: Any, ) -> List[str]: """Run more texts through the embeddings and add to the vectorstore. ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
40fade8f9055-4
ids: Optional list of unique IDs. Returns: List of ids from adding the texts into the vectorstore. """ if not isinstance(self.docstore, AddableMixin): raise ValueError( "If trying to add texts, the underlying docstore should support " f"add...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
40fade8f9055-5
raise ValueError(f"Could not find document for id {_id}, got {doc}") docs.append((doc, scores[0][j])) return docs [docs] def similarity_search_with_score( self, query: str, k: int = 4 ) -> List[Tuple[Document, float]]: """Return docs most similar to query. Args: ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
40fade8f9055-6
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(query, k) return [doc for doc, _ in docs_and_scores] [docs] def max_marginal_relevance_search_by_vector( s...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
40fade8f9055-7
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 docs are returned. continue ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
40fade8f9055-8
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
40fade8f9055-9
**kwargs: Any, ) -> FAISS: faiss = dependable_faiss_import() index = faiss.IndexFlatL2(len(embeddings[0])) vector = np.array(embeddings, dtype=np.float32) if normalize_L2: faiss.normalize_L2(vector) index.add(vector) documents = [] if ids is None: ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
40fade8f9055-10
embeddings = OpenAIEmbeddings() faiss = FAISS.from_texts(texts, embeddings) """ embeddings = embedding.embed_documents(texts) return cls.__from( texts, embeddings, embedding, metadatas=metadatas, ids=ids, **k...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
40fade8f9055-11
ids=ids, **kwargs, ) [docs] def save_local(self, folder_path: str, index_name: str = "index") -> None: """Save FAISS index, docstore, and index_to_docstore_id to disk. Args: folder_path: folder path to save index, docstore, and index_to_docstore_id to. ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
40fade8f9055-12
faiss = dependable_faiss_import() index = faiss.read_index( str(path / "{index_name}.faiss".format(index_name=index_name)) ) # load docstore and index_to_docstore_id with open(path / "{index_name}.pkl".format(index_name=index_name), "rb") as f: docstore, index_to_...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/faiss.html
a52838bcc4b3-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
a52838bcc4b3-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
a52838bcc4b3-2
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, embedding=embeddin...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
a52838bcc4b3-3
) -> 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( metadata=search.get("metadata", {}), # ty...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
a52838bcc4b3-4
) -> 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, metadata in zip(texts, metadatas) ] return docs...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
a52838bcc4b3-5
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. Maximal marginal relevance optimizes for similarity to query AND diversity ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
a52838bcc4b3-6
**kwargs: Any, ) -> List[Document]: """Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args: query: Text to look up documents similar to. k: Number ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
a52838bcc4b3-7
) return docs By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/supabase.html
6199e161a542-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
6199e161a542-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
6199e161a542-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
ff2ee3f76089-0
Source code for langchain.vectorstores.qdrant """Wrapper around Qdrant vector database.""" from __future__ import annotations import uuid import warnings from itertools import islice from operator import itemgetter from typing import ( TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Opti...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
ff2ee3f76089-1
metadata_payload_key: str = METADATA_KEY, embedding_function: Optional[Callable] = None, # deprecated ): """Initialize with necessary components.""" try: import qdrant_client except ImportError: raise ValueError( "Could not import qdrant-clien...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
ff2ee3f76089-2
"Using `embeddings` as `embedding_function` which is deprecated" ) self._embeddings_function = embeddings self.embeddings = None [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Optional[Sequence[str]] =...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
ff2ee3f76089-3
ids=batch_ids, vectors=self._embed_texts(batch_texts), payloads=self._build_payloads( batch_texts, batch_metadatas, self.content_payload_key, self.metadata_payload_key, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
ff2ee3f76089-4
- int - number of replicas to query, values should present in all queried replicas - 'majority' - query all replicas, but return values present in the majority of replicas - 'quorum' - query the majority of replicas, return values pr...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
ff2ee3f76089-5
score_threshold: Define a minimal score threshold for the result. If defined, less similar results will not be returned. Score of the returned result might be higher or smaller than the threshold depending on the Distance function used. E.g...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
ff2ee3f76089-6
with_vectors=False, # Langchain does not expect vectors to be returned score_threshold=score_threshold, consistency=consistency, **kwargs, ) return [ ( self._document_from_scored_point( result, self.content_payload_key,...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
ff2ee3f76089-7
Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. fetch_k: Number of Documents to fetch to pass to MMR algorithm. Defaults to 20. lambda_mult: Number between 0 and 1 that determines the degree ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
ff2ee3f76089-8
api_key: Optional[str] = None, prefix: Optional[str] = None, timeout: Optional[float] = None, host: Optional[str] = None, path: Optional[str] = None, collection_name: Optional[str] = None, distance_func: str = "Cosine", content_payload_key: str = CONTENT_KEY, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
ff2ee3f76089-9
location: If `:memory:` - use in-memory Qdrant instance. If `str` - use it as a `url` parameter. If `None` - fallback to relying on `host` and `port` parameters. url: either host or str of "Optional[scheme], host, Optional[port], Optional[prefi...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
ff2ee3f76089-10
Default: "Cosine" content_payload_key: A payload key used to store the content of the document. Default: "page_content" metadata_payload_key: A payload key used to store the metadata of the document. Default: "metadata" ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
ff2ee3f76089-11
**kwargs: Additional arguments passed directly into REST client initialization This is a user-friendly interface that: 1. Creates embeddings, one for each text 2. Initializes the Qdrant database as an in-memory docstore by default (and overridable to a remote docstore)...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
ff2ee3f76089-12
) client.recreate_collection( collection_name=collection_name, vectors_config=rest.VectorParams( size=vector_size, distance=rest.Distance[distance_func], ), shard_number=shard_number, replication_factor=replication_facto...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
ff2ee3f76089-13
embeddings=embedding, content_payload_key=content_payload_key, metadata_payload_key=metadata_payload_key, ) @classmethod def _build_payloads( cls, texts: Iterable[str], metadatas: Optional[List[dict]], content_payload_key: str, metadata_pay...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
ff2ee3f76089-14
for _value in value: if isinstance(_value, dict): out.extend(self._build_condition(f"{key}[]", _value)) else: out.extend(self._build_condition(f"{key}", _value)) else: out.append( rest.FieldCondition( ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
ff2ee3f76089-15
Args: texts: Iterable of texts to embed. Returns: List of floats representing the texts embedding. """ if self.embeddings is not None: embeddings = self.embeddings.embed_documents(list(texts)) if hasattr(embeddings, "tolist"): embed...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/qdrant.html
388733eb6075-0
Source code for langchain.vectorstores.base """Interface for vector stores.""" from __future__ import annotations import asyncio import warnings from abc import ABC, abstractmethod from functools import partial from typing import ( Any, ClassVar, Collection, Dict, Iterable, List, Optional, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
388733eb6075-1
"""Run more documents through the embeddings and add to the vectorstore. Args: documents (List[Document]: Documents to add to the vectorstore. Returns: List[str]: List of IDs of the added texts. """ # TODO: Handle the case where the user doesn't provide ids on the...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
388733eb6075-2
) [docs] async def asearch( self, query: str, search_type: str, **kwargs: Any ) -> List[Document]: """Return docs most similar to query using specified search type.""" if search_type == "similarity": return await self.asimilarity_search(query, **kwargs) elif search_typ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
388733eb6075-3
query, k=k, **kwargs ) if any( similarity < 0.0 or similarity > 1.0 for _, similarity in docs_and_similarities ): warnings.warn( "Relevance scores must be between" f" 0 and 1, got {docs_and_similarities}" ) s...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
388733eb6075-4
return await asyncio.get_event_loop().run_in_executor(None, func) [docs] async def asimilarity_search( self, query: str, k: int = 4, **kwargs: Any ) -> List[Document]: """Return docs most similar to query.""" # This is a temporary workaround to make the similarity search # asynchr...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
388733eb6075-5
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/base.html
388733eb6075-6
[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. Maximal marg...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
388733eb6075-7
texts = [d.page_content for d in documents] metadatas = [d.metadata for d in documents] return cls.from_texts(texts, embedding, metadatas=metadatas, **kwargs) [docs] @classmethod async def afrom_documents( cls: Type[VST], documents: List[Document], embedding: Embeddings, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
388733eb6075-8
vectorstore: VectorStore search_type: str = "similarity" search_kwargs: dict = Field(default_factory=dict) allowed_search_types: ClassVar[Collection[str]] = ( "similarity", "similarity_score_threshold", "mmr", ) class Config: """Configuration for this pydantic object....
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
388733eb6075-9
docs = self.vectorstore.max_marginal_relevance_search( query, **self.search_kwargs ) else: raise ValueError(f"search_type of {self.search_type} not allowed.") return docs async def aget_relevant_documents(self, query: str) -> List[Document]: if self.se...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/base.html
e8414c2133c8-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
e8414c2133c8-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
e8414c2133c8-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
e8414c2133c8-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
e8414c2133c8-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
e8414c2133c8-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
e8414c2133c8-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
e8414c2133c8-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
cf1e7617c4b5-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
cf1e7617c4b5-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
cf1e7617c4b5-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
cf1e7617c4b5-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
cf1e7617c4b5-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
cf1e7617c4b5-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
cf1e7617c4b5-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
cf1e7617c4b5-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
cf1e7617c4b5-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
cf1e7617c4b5-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
cf1e7617c4b5-10
] except Exception as e: logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") return [] [docs] def drop(self) -> None: """ Helper function: Drop data """ self.client.command( f"DROP TABLE IF EXISTS {self.config.database}....
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html