id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
59
127
1323debf1f02-2
return embeddings def _generate_embeddings(self, texts: List[str]) -> List[List[float]]: """Generate embeddings using the Embaas API.""" payload = self._generate_payload(texts) try: return self._handle_request(payload) except requests.exceptions.RequestException as e: ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/embaas.html
1fff811542ca-0
Source code for langchain.embeddings.huggingface """Wrapper around HuggingFace embedding models.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, Field from langchain.embeddings.base import Embeddings DEFAULT_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2" DEFAULT_INSTRUCT_M...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/huggingface.html
1fff811542ca-1
"""Key word arguments to pass when calling the `encode` method of the model.""" def __init__(self, **kwargs: Any): """Initialize the sentence_transformer.""" super().__init__(**kwargs) try: import sentence_transformers except ImportError as exc: raise ImportEr...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/huggingface.html
1fff811542ca-2
To use, you should have the ``sentence_transformers`` and ``InstructorEmbedding`` python packages installed. Example: .. code-block:: python from langchain.embeddings import HuggingFaceInstructEmbeddings model_name = "hkunlp/instructor-large" model_kwargs = {'device':...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/huggingface.html
1fff811542ca-3
raise ValueError("Dependencies for InstructorEmbedding not found.") from e class Config: """Configuration for this pydantic object.""" extra = Extra.forbid [docs] def embed_documents(self, texts: List[str]) -> List[List[float]]: """Compute doc embeddings using a HuggingFace instruct model...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/huggingface.html
22afd4a09680-0
Source code for langchain.embeddings.elasticsearch from __future__ import annotations from typing import TYPE_CHECKING, List, Optional from langchain.utils import get_from_env if TYPE_CHECKING: from elasticsearch import Elasticsearch from elasticsearch.client import MlClient from langchain.embeddings.base impor...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/elasticsearch.html
22afd4a09680-1
es_user: Optional[str] = None, es_password: Optional[str] = None, input_field: str = "text_field", ) -> ElasticsearchEmbeddings: """Instantiate embeddings from Elasticsearch credentials. Args: model_id (str): The model_id of the model deployed in the Elasticsearch ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/elasticsearch.html
22afd4a09680-2
from elasticsearch.client import MlClient except ImportError: raise ImportError( "elasticsearch package not found, please install with 'pip install " "elasticsearch'" ) es_cloud_id = es_cloud_id or get_from_env("es_cloud_id", "ES_CLOUD_ID") ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/elasticsearch.html
22afd4a09680-3
Example: .. code-block:: python from elasticsearch import Elasticsearch from langchain.embeddings import ElasticsearchEmbeddings # Define the model ID and input field name (if different from default) model_id = "your_model_id" #...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/elasticsearch.html
22afd4a09680-4
list. """ response = self.client.infer_trained_model( model_id=self.model_id, docs=[{self.input_field: text} for text in texts] ) embeddings = [doc["predicted_value"] for doc in response["inference_results"]] return embeddings [docs] def embed_documents(self, texts...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/elasticsearch.html
1d62e06344ee-0
Source code for langchain.embeddings.huggingface_hub """Wrapper around HuggingFace Hub embedding models.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.utils import get_from_dict_or_env DEFAULT_REPO_ID...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/huggingface_hub.html
1d62e06344ee-1
@root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" huggingfacehub_api_token = get_from_dict_or_env( values, "huggingfacehub_api_token", "HUGGINGFACEHUB_API_TOKEN" ) try: ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/huggingface_hub.html
1d62e06344ee-2
texts = [text.replace("\n", " ") for text in texts] _model_kwargs = self.model_kwargs or {} responses = self.client(inputs=texts, params=_model_kwargs) return responses [docs] def embed_query(self, text: str) -> List[float]: """Call out to HuggingFaceHub's embedding endpoint for embed...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/huggingface_hub.html
c42c6d64d304-0
Source code for langchain.embeddings.openai """Wrapper around OpenAI embedding models.""" from __future__ import annotations import logging from typing import ( Any, Callable, Dict, List, Literal, Optional, Sequence, Set, Tuple, Union, ) import numpy as np from pydantic import Ba...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/openai.html
c42c6d64d304-1
"""Use tenacity to retry the embedding call.""" retry_decorator = _create_retry_decorator(embeddings) @retry_decorator def _embed_with_retry(**kwargs: Any) -> Any: return embeddings.client.create(**kwargs) return _embed_with_retry(**kwargs) [docs]class OpenAIEmbeddings(BaseModel, Embeddings): ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/openai.html
c42c6d64d304-2
embeddings = OpenAIEmbeddings( deployment="your-embeddings-deployment-name", model="your-embeddings-model-name", openai_api_base="https://your-endpoint.openai.azure.com/", openai_api_type="azure", ) text = "This is a test query." ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/openai.html
c42c6d64d304-3
extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" values["openai_api_key"] = get_from_dict_or_env( values, "openai_api_key", "OPENAI_API_KEY" ) values["open...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/openai.html
c42c6d64d304-4
) return values @property def _invocation_params(self) -> Dict: openai_args = { "engine": self.deployment, "request_timeout": self.request_timeout, "headers": self.headers, "api_key": self.openai_api_key, "organization": self.openai_org...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/openai.html
c42c6d64d304-5
for i, text in enumerate(texts): if self.model.endswith("001"): # See: https://github.com/openai/openai-python/issues/418#issuecomment-1525939500 # replace newlines, which can negatively affect performance. text = text.replace("\n", " ") token = en...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/openai.html
c42c6d64d304-6
)[ "data" ][0]["embedding"] else: average = np.average(_result, axis=0, weights=num_tokens_in_batch[i]) embeddings[i] = (average / np.linalg.norm(average)).tolist() return embeddings def _embedding_func(self, text: str, *, engine: s...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/openai.html
c42c6d64d304-7
return self._get_len_safe_embeddings(texts, engine=self.deployment) [docs] def embed_query(self, text: str) -> List[float]: """Call out to OpenAI's embedding endpoint for embedding query text. Args: text: The text to embed. Returns: Embedding for the text. """ ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/openai.html
56a492739365-0
Source code for langchain.embeddings.cohere """Wrapper around Cohere embedding models.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.utils import get_from_dict_or_env [docs]class CohereEmbeddings(Base...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/cohere.html
56a492739365-1
except ImportError: raise ValueError( "Could not import cohere python package. " "Please install it with `pip install cohere`." ) return values [docs] def embed_documents(self, texts: List[str]) -> List[List[float]]: """Call out to Cohere's embe...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/cohere.html
66b5c35a9500-0
Source code for langchain.embeddings.bedrock import json import os from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings [docs]class BedrockEmbeddings(BaseModel, Embeddings): """Embeddings provider to invoke Bedrock embedd...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/bedrock.html
66b5c35a9500-1
If not specified, the default credential profile or, if on an EC2 instance, credentials from IMDS will be used. See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html """ model_id: str = "amazon.titan-e1t-medium" """Id of the model to call, e.g., amazon.titan-e1t-medium,...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/bedrock.html
66b5c35a9500-2
"profile name are valid." ) from e return values def _embedding_func(self, text: str) -> List[float]: """Call out to Bedrock embedding endpoint.""" # replace newlines, which can negatively affect performance. text = text.replace(os.linesep, " ") _model_kwargs = se...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/bedrock.html
66b5c35a9500-3
[docs] def embed_query(self, text: str) -> List[float]: """Compute query embeddings using a Bedrock model. Args: text: The text to embed. Returns: Embeddings for the text. """ return self._embedding_func(text) By Harrison Chase © Copyright 20...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/bedrock.html
4d74740bd703-0
Source code for langchain.embeddings.fake from typing import List import numpy as np from pydantic import BaseModel from langchain.embeddings.base import Embeddings [docs]class FakeEmbeddings(Embeddings, BaseModel): size: int def _get_embedding(self) -> List[float]: return list(np.random.normal(size=sel...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/fake.html
aaf41fb41b63-0
Source code for langchain.embeddings.llamacpp """Wrapper around llama.cpp embedding models.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, Field, root_validator from langchain.embeddings.base import Embeddings [docs]class LlamaCppEmbeddings(BaseModel, Embeddings): """Wrapper ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/llamacpp.html
aaf41fb41b63-1
use_mlock: bool = Field(False, alias="use_mlock") """Force system to keep model in RAM.""" n_threads: Optional[int] = Field(None, alias="n_threads") """Number of threads to use. If None, the number of threads is automatically determined.""" n_batch: Optional[int] = Field(8, alias="n_batch") """...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/llamacpp.html
aaf41fb41b63-2
raise ModuleNotFoundError( "Could not import llama-cpp-python library. " "Please install the llama-cpp-python library to " "use this embedding model: pip install llama-cpp-python" ) except Exception as e: raise ValueError( f...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/llamacpp.html
b61282c78106-0
Source code for langchain.embeddings.modelscope_hub """Wrapper around ModelScopeHub embedding models.""" from typing import Any, List from pydantic import BaseModel, Extra from langchain.embeddings.base import Embeddings [docs]class ModelScopeEmbeddings(BaseModel, Embeddings): """Wrapper around modelscope_hub embed...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/modelscope_hub.html
b61282c78106-1
texts = list(map(lambda x: x.replace("\n", " "), texts)) inputs = {"source_sentence": texts} embeddings = self.embed(input=inputs)["text_embedding"] return embeddings.tolist() [docs] def embed_query(self, text: str) -> List[float]: """Compute query embeddings using a modelscope embedd...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/modelscope_hub.html
47053ab09af7-0
Source code for langchain.embeddings.minimax """Wrapper around MiniMax APIs.""" from __future__ import annotations import logging from typing import Any, Callable, Dict, List, Optional import requests from pydantic import BaseModel, Extra, root_validator from tenacity import ( before_sleep_log, retry, stop_...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/minimax.html
47053ab09af7-1
the constructor. Example: .. code-block:: python from langchain.embeddings import MiniMaxEmbeddings embeddings = MiniMaxEmbeddings() query_text = "This is a test query." query_result = embeddings.embed_query(query_text) document_text = "This is a t...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/minimax.html
47053ab09af7-2
self, texts: List[str], embed_type: str, ) -> List[List[float]]: payload = { "model": self.model, "type": embed_type, "texts": texts, } # HTTP headers for authorization headers = { "Authorization": f"Bearer {self.minimax...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/minimax.html
47053ab09af7-3
) return embeddings[0] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/minimax.html
8b4bdebcb88d-0
Source code for langchain.embeddings.self_hosted """Running custom embedding models on self-hosted remote hardware.""" from typing import Any, Callable, List from pydantic import Extra from langchain.embeddings.base import Embeddings from langchain.llms import SelfHostedPipeline def _embed_documents(pipeline: Any, *arg...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/self_hosted.html
8b4bdebcb88d-1
model_load_fn=get_pipeline, hardware=gpu model_reqs=["./", "torch", "transformers"], ) Example passing in a pipeline path: .. code-block:: python from langchain.embeddings import SelfHostedHFEmbeddings import runhouse as rh from...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/self_hosted.html
8b4bdebcb88d-2
[docs] def embed_query(self, text: str) -> List[float]: """Compute query embeddings using a HuggingFace transformer model. Args: text: The text to embed. Returns: Embeddings for the text. """ text = text.replace("\n", " ") embeddings = self.clie...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/self_hosted.html
13be03d534cc-0
Source code for langchain.embeddings.aleph_alpha from typing import Any, Dict, List, Optional from pydantic import BaseModel, root_validator from langchain.embeddings.base import Embeddings from langchain.utils import get_from_dict_or_env [docs]class AlephAlphaAsymmetricSemanticEmbedding(BaseModel, Embeddings): """...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/aleph_alpha.html
13be03d534cc-1
"""Attention control parameters only apply to those tokens that have explicitly been set in the request.""" control_log_additive: Optional[bool] = True """Apply controls on prompt items by adding the log(control_factor) to attention scores.""" aleph_alpha_api_key: Optional[str] = None """API k...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/aleph_alpha.html
13be03d534cc-2
document_params = { "prompt": Prompt.from_text(text), "representation": SemanticRepresentation.Document, "compress_to_size": self.compress_to_size, "normalize": self.normalize, "contextual_control_threshold": self.contextual_control_thresho...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/aleph_alpha.html
13be03d534cc-3
request=symmetric_request, model=self.model ) return symmetric_response.embedding [docs]class AlephAlphaSymmetricSemanticEmbedding(AlephAlphaAsymmetricSemanticEmbedding): """The symmetric version of the Aleph Alpha's semantic embeddings. The main difference is that here, both the documents and ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/aleph_alpha.html
13be03d534cc-4
"""Call out to Aleph Alpha's Document endpoint. Args: texts: The list of texts to embed. Returns: List of embeddings, one for each text. """ document_embeddings = [] for text in texts: document_embeddings.append(self._embed(text)) retur...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/aleph_alpha.html
9f2ad041044a-0
Source code for langchain.embeddings.tensorflow_hub """Wrapper around TensorflowHub embedding models.""" from typing import Any, List from pydantic import BaseModel, Extra from langchain.embeddings.base import Embeddings DEFAULT_MODEL_URL = "https://tfhub.dev/google/universal-sentence-encoder-multilingual/3" [docs]clas...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/tensorflow_hub.html
9f2ad041044a-1
"""Compute doc embeddings using a TensorflowHub embedding model. Args: texts: The list of texts to embed. Returns: List of embeddings, one for each text. """ texts = list(map(lambda x: x.replace("\n", " "), texts)) embeddings = self.embed(texts).numpy() ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/tensorflow_hub.html
2571249fc599-0
Source code for langchain.embeddings.dashscope """Wrapper around DashScope embedding models.""" from __future__ import annotations import logging from typing import ( Any, Callable, Dict, List, Optional, ) from pydantic import BaseModel, Extra, root_validator from requests.exceptions import HTTPErro...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/dashscope.html
2571249fc599-1
elif resp.status_code in [400, 401]: raise ValueError( f"status_code: {resp.status_code} \n " f"code: {resp.code} \n message: {resp.message}" ) else: raise HTTPError( f"HTTP error occurred: status_code: {resp.status_code} \n " ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/dashscope.html
2571249fc599-2
class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: import dashscope """Validate that api key and python package exists in environment.""" values["dashscope_api_key"] = get...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/dashscope.html
2571249fc599-3
Embedding for the text. """ embedding = embed_with_retry( self, input=text, text_type="query", model=self.model )[0]["embedding"] return embedding By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/embeddings/dashscope.html
9d94d312d47a-0
Source code for langchain.vectorstores.azuresearch """Wrapper around Azure Cognitive Search.""" from __future__ import annotations import base64 import json import logging import uuid from typing import ( TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Tuple, Type, ) im...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/azuresearch.html
9d94d312d47a-1
from azure.core.credentials import AzureKeyCredential from azure.core.exceptions import ResourceNotFoundError from azure.identity import DefaultAzureCredential from azure.search.documents import SearchClient from azure.search.documents.indexes import SearchIndexClient from azure.search.documents.ind...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/azuresearch.html
9d94d312d47a-2
algorithm_configurations=[ VectorSearchAlgorithmConfiguration( name="default", kind="hnsw", hnsw_parameters={ "m": 4, "efConstruction": 400, "efSearch": 500, ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/azuresearch.html
9d94d312d47a-3
azure_search_endpoint, azure_search_key, index_name, embedding_function, semantic_configuration_name, ) self.search_type = search_type self.semantic_configuration_name = semantic_configuration_name self.semantic_query_language = semantic_qu...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/azuresearch.html
9d94d312d47a-4
raise Exception(response) # Reset data data = [] # Considering case where data is an exact multiple of batch-size entries if len(data) == 0: return ids # Upload data to index response = self.client.upload_documents(documents=data) # Che...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/azuresearch.html
9d94d312d47a-5
query, k=k, filters=kwargs.get("filters", None) ) return [doc for doc, _ in docs_and_scores] [docs] def vector_search_with_score( self, query: str, k: int = 4, filters: Optional[str] = None ) -> List[Tuple[Document, float]]: """Return docs most similar to query. Args: ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/azuresearch.html
9d94d312d47a-6
Returns: List[Document]: A list of documents that are most similar to the query text. """ docs_and_scores = self.hybrid_search_with_score( query, k=k, filters=kwargs.get("filters", None) ) return [doc for doc, _ in docs_and_scores] [docs] def hybrid_search_with...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/azuresearch.html
9d94d312d47a-7
) -> List[Document]: """ Returns the most similar indexed documents to the query text. 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 d...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/azuresearch.html
9d94d312d47a-8
query_answer="extractive", top=k, ) # Get Semantic Answers semantic_answers = results.get_answers() semantic_answers_dict = {} for semantic_answer in semantic_answers: semantic_answers_dict[semantic_answer.key] = { "text": semantic_answer.t...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/azuresearch.html
9d94d312d47a-9
azure_search_key, index_name, embedding.embed_query, ) azure_search.add_texts(texts, metadatas, **kwargs) return azure_search class AzureSearchVectorStoreRetriever(BaseRetriever, BaseModel): vectorstore: AzureSearch search_type: str = "hybrid" k: int = 4 c...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/azuresearch.html
34c8fa439699-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/analyticdb.html
34c8fa439699-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/analyticdb.html
34c8fa439699-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/analyticdb.html
34c8fa439699-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/analyticdb.html
34c8fa439699-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/analyticdb.html
34c8fa439699-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/analyticdb.html
34c8fa439699-6
) .filter(filter_by) .order_by(EmbeddingStore.embedding.op("<->")(embedding)) .join( CollectionStore, EmbeddingStore.collection_id == CollectionStore.uuid, ) .limit(k) .all() ) docs = [ ( ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/analyticdb.html
34c8fa439699-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. ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/analyticdb.html
34c8fa439699-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/analyticdb.html
2b11536e38cf-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, ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/base.html
2b11536e38cf-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/base.html
2b11536e38cf-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/base.html
2b11536e38cf-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/base.html
2b11536e38cf-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/base.html
2b11536e38cf-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/base.html
2b11536e38cf-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/base.html
2b11536e38cf-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, ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/base.html
2b11536e38cf-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....
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/base.html
2b11536e38cf-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/base.html
27adabc26c75-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
27adabc26c75-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 ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
27adabc26c75-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
27adabc26c75-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. ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
27adabc26c75-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
27adabc26c75-5
docs = [] for j, i in enumerate(indices[0]): if i == -1: # 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): ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
27adabc26c75-6
fetch_k=fetch_k, **kwargs, ) return docs [docs] def similarity_search_by_vector( self, embedding: List[float], k: int = 4, filter: Optional[Dict[str, Any]] = None, fetch_k: int = 20, **kwargs: Any, ) -> List[Document]: """Return ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
27adabc26c75-7
fetch_k: (Optional[int]) Number of Documents to fetch before filtering. Defaults to 20. Returns: List of Documents most similar to the query. """ docs_and_scores = self.similarity_search_with_score( query, k, filter=filter, fetch_k=fetch_k, **kwargs ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
27adabc26c75-8
for i in indices[0]: if i == -1: # 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): rai...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
27adabc26c75-9
**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 ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
27adabc26c75-10
# Get id and docs from target FAISS object full_info = [] for i, target_id in target.index_to_docstore_id.items(): doc = target.docstore.search(target_id) if not isinstance(doc, Document): raise ValueError("Document should be returned") full_info.appen...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
27adabc26c75-11
return cls( embedding.embed_query, index, docstore, index_to_id, normalize_L2=normalize_L2, **kwargs, ) [docs] @classmethod def from_texts( cls, texts: List[str], embedding: Embeddings, metadatas: Opti...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
27adabc26c75-12
This is a user friendly interface that: 1. Embeds documents. 2. Creates an in memory docstore 3. Initializes the FAISS database This is intended to be a quick way to get started. Example: .. code-block:: python from langchain import FAISS ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
27adabc26c75-13
) # save docstore and index_to_docstore_id with open(path / "{index_name}.pkl".format(index_name=index_name), "wb") as f: pickle.dump((self.docstore, self.index_to_docstore_id), f) [docs] @classmethod def load_local( cls, folder_path: str, embeddings: Embeddings, index_name: s...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
27adabc26c75-14
**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" " FAISS constructor to normalize scores" ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/faiss.html
d0972190eae7-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/typesense.html
d0972190eae7-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. "...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/typesense.html
d0972190eae7-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( ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/typesense.html
d0972190eae7-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...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/typesense.html
d0972190eae7-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) ...
rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/vectorstores/typesense.html