id
stringlengths
14
16
text
stringlengths
4
1.28k
source
stringlengths
54
121
3637c2e10665-3
"Please install it with `pip install aleph_alpha_client`." ) values["client"] = Client(token=aleph_alpha_api_key) return values [docs] def embed_documents(self, texts: List[str]) -> List[List[float]]: """Call out to Aleph Alpha's asymmetric Document endpoint. Args: ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
3637c2e10665-4
for text in texts: document_params = { "prompt": Prompt.from_text(text), "representation": SemanticRepresentation.Document, "compress_to_size": self.compress_to_size, "normalize": self.normalize, "contextual_control_threshold": ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
3637c2e10665-5
""" try: from aleph_alpha_client import ( Prompt, SemanticEmbeddingRequest, SemanticRepresentation, ) except ImportError: raise ValueError( "Could not import aleph_alpha_client python package. " ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
3637c2e10665-6
) 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 queries are embedded with a SemanticRepresentatio...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
3637c2e10665-7
) except ImportError: raise ValueError( "Could not import aleph_alpha_client python package. " "Please install it with `pip install aleph_alpha_client`." ) query_params = { "prompt": Prompt.from_text(text), "representation":...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
3637c2e10665-8
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)) return document_embeddings [docs] def embed_query(self, te...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
d13c89548180-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/modelscope_hub.html
d13c89548180-1
"""Initialize the modelscope""" super().__init__(**kwargs) try: from modelscope.pipelines import pipeline from modelscope.utils.constant import Tasks self.embed = pipeline(Tasks.sentence_embedding, model=self.model_id) except ImportError as e: rais...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/modelscope_hub.html
d13c89548180-2
""" 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 model...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/modelscope_hub.html
5f76bddcf670-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
5f76bddcf670-1
model_name = "sentence-transformers/all-mpnet-base-v2" model_kwargs = {'device': 'cpu'} encode_kwargs = {'normalize_embeddings': False} hf = HuggingFaceEmbeddings( model_name=model_name, model_kwargs=model_kwargs, encode_kwargs=encode_k...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
5f76bddcf670-2
"""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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
5f76bddcf670-3
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.client.encode(texts, **self.encode_kwargs) return embeddings.tolist() [docs] def embe...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
5f76bddcf670-4
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':...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
5f76bddcf670-5
model_kwargs: Dict[str, Any] = Field(default_factory=dict) """Key word arguments to pass to the model.""" encode_kwargs: Dict[str, Any] = Field(default_factory=dict) """Key word arguments to pass when calling the `encode` method of the model.""" embed_instruction: str = DEFAULT_EMBED_INSTRUCTION """...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
5f76bddcf670-6
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. Args: texts: The list of texts to embed. Returns:...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
5f76bddcf670-7
""" instruction_pair = [self.query_instruction, text] embedding = self.client.encode([instruction_pair], **self.encode_kwargs)[0] return embedding.tolist()
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
17b7a0fac055-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html
17b7a0fac055-1
model_url: str = DEFAULT_MODEL_URL """Model name to use.""" def __init__(self, **kwargs: Any): """Initialize the tensorflow_hub and tensorflow_text.""" super().__init__(**kwargs) try: import tensorflow_hub except ImportError: raise ImportError( ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html
17b7a0fac055-2
extra = Extra.forbid [docs] def embed_documents(self, texts: List[str]) -> List[List[float]]: """Compute doc embeddings using a TensorflowHub embedding model. Args: texts: The list of texts to embed. Returns: List of embeddings, one for each text. """ t...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html
fd79a69d24d3-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/fake.html
03853e9368cd-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-1
min_seconds = 4 max_seconds = 10 # Wait 2^x * 1 second between each retry starting with # 4 seconds, then up to 10 seconds, then 10 seconds afterwards return retry( reraise=True, stop=stop_after_attempt(embeddings.max_retries), wait=wait_exponential(multiplier=1, min=min_seconds,...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-2
) def _async_retry_decorator(embeddings: OpenAIEmbeddings) -> Any: import openai min_seconds = 4 max_seconds = 10 # Wait 2^x * 1 second between each retry starting with # 4 seconds, then up to 10 seconds, then 10 seconds afterwards async_retrying = AsyncRetrying( reraise=True, st...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-3
), before_sleep=before_sleep_log(logger, logging.WARNING), ) def wrap(func: Callable) -> Callable: async def wrapped_f(*args: Any, **kwargs: Any) -> Callable: async for _ in async_retrying: return await func(*args, **kwargs) raise AssertionError("this is u...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-4
"""Use tenacity to retry the embedding call.""" @_async_retry_decorator(embeddings) async def _async_embed_with_retry(**kwargs: Any) -> Any: return await embeddings.client.acreate(**kwargs) return await _async_embed_with_retry(**kwargs) [docs]class OpenAIEmbeddings(BaseModel, Embeddings): """Wra...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-5
the OPENAI_API_TYPE, OPENAI_API_BASE, OPENAI_API_KEY and OPENAI_API_VERSION. The OPENAI_API_TYPE must be set to 'azure' and the others correspond to the properties of your endpoint. In addition, the deployment name must be passed as the model parameter. Example: .. code-block:: python ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-6
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." ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-7
# to support explicit proxy for OpenAI openai_proxy: Optional[str] = None embedding_ctx_length: int = 8191 openai_api_key: Optional[str] = None openai_organization: Optional[str] = None allowed_special: Union[Literal["all"], Set[str]] = set() disallowed_special: Union[Literal["all"], Set[str], S...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-8
"""The model name to pass to tiktoken when using this class. Tiktoken is used to count the number of tokens in documents to constrain them to be under a certain limit. By default, when set to None, this will be the same as the embedding model name. However, there are some cases where you may want to...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-9
@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["openai_api_base"] = get_from_...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-10
default="", ) if values["openai_api_type"] in ("azure", "azure_ad", "azuread"): default_api_version = "2022-12-01" else: default_api_version = "" values["openai_api_version"] = get_from_dict_or_env( values, "openai_api_version", ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-11
) 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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-12
# please refer to # https://github.com/openai/openai-cookbook/blob/main/examples/Embedding_long_inputs.ipynb def _get_len_safe_embeddings( self, texts: List[str], *, engine: str, chunk_size: Optional[int] = None ) -> List[List[float]]: embeddings: List[List[float]] = [[] for _ in range(len(t...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-13
except KeyError: logger.warning("Warning: model not found. Using cl100k_base encoding.") model = "cl100k_base" encoding = tiktoken.get_encoding(model) for i, text in enumerate(texts): if self.model.endswith("001"): # See: https://github.com/openai/...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-14
batched_embeddings = [] _chunk_size = chunk_size or self.chunk_size for i in range(0, len(tokens), _chunk_size): response = embed_with_retry( self, input=tokens[i : i + _chunk_size], **self._invocation_params, ) batched_...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-15
average = embed_with_retry( self, input="", **self._invocation_params, )[ "data" ][0]["embedding"] else: average = np.average(_result, axis=0, weights=num_tokens_in_batch[i]) ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-16
except ImportError: raise ImportError( "Could not import tiktoken python package. " "This is needed in order to for OpenAIEmbeddings. " "Please install it with `pip install tiktoken`." ) tokens = [] indices = [] model_name =...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-17
text = text.replace("\n", " ") token = encoding.encode( text, allowed_special=self.allowed_special, disallowed_special=self.disallowed_special, ) for j in range(0, len(token), self.embedding_ctx_length): tokens += [token...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-18
num_tokens_in_batch: List[List[int]] = [[] for _ in range(len(texts))] for i in range(len(indices)): results[indices[i]].append(batched_embeddings[i]) num_tokens_in_batch[indices[i]].append(len(tokens[i])) for i in range(len(texts)): _result = results[i] i...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-19
"""Call out to OpenAI's embedding endpoint.""" # handle large input text if len(text) > self.embedding_ctx_length: return self._get_len_safe_embeddings([text], engine=engine)[0] else: if self.model.endswith("001"): # See: https://github.com/openai/openai-p...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-20
# handle large input text if len(text) > self.embedding_ctx_length: return (await self._aget_len_safe_embeddings([text], engine=engine))[0] else: if self.model.endswith("001"): # See: https://github.com/openai/openai-python/issues/418#issuecomment-1525939500 ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-21
Args: texts: The list of texts to embed. chunk_size: The chunk size of embeddings. If None, will use the chunk size specified by the class. Returns: List of embeddings, one for each text. """ # NOTE: to keep things simple, we assume the list ma...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-22
specified by the class. Returns: List of embeddings, one for each text. """ # NOTE: to keep things simple, we assume the list may contain texts longer # than the maximum context and use length-safe embedding function. return await self._aget_len_safe_embeddings(...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
03853e9368cd-23
Args: text: The text to embed. Returns: Embedding for the text. """ embedding = await self._aembedding_func(text, engine=self.deployment) return embedding
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
3f4fad71d899-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html
3f4fad71d899-1
.. code-block:: python from langchain.embeddings import HuggingFaceHubEmbeddings repo_id = "sentence-transformers/all-mpnet-base-v2" hf = HuggingFaceHubEmbeddings( repo_id=repo_id, task="feature-extraction", huggingfacehub_api_token="my...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html
3f4fad71d899-2
extra = Extra.forbid @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" ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html
3f4fad71d899-3
) if client.task not in VALID_TASKS: raise ValueError( f"Got invalid task {client.task}, " f"currently only {VALID_TASKS} are supported" ) values["client"] = client except ImportError: raise ValueError( ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html
3f4fad71d899-4
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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html
446fd1452acb-0
Source code for langchain.embeddings.deepinfra from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.utils import get_from_dict_or_env DEFAULT_MODEL_ID = "sentence-transformers/clip-ViT-...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/deepinfra.html
446fd1452acb-1
deepinfra_emb = DeepInfraEmbeddings( model_id="sentence-transformers/clip-ViT-B-32", deepinfra_api_token="my-api-key" ) r1 = deepinfra_emb.embed_documents( [ "Alpha is the first letter of Greek alphabet", "Be...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/deepinfra.html
446fd1452acb-2
"""Instruction used to embed the query.""" model_kwargs: Optional[dict] = None """Other model keyword args""" deepinfra_api_token: Optional[str] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_environment(cls,...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/deepinfra.html
446fd1452acb-3
def _embed(self, input: List[str]) -> List[List[float]]: _model_kwargs = self.model_kwargs or {} # HTTP headers for authorization headers = { "Authorization": f"bearer {self.deepinfra_api_token}", "Content-Type": "application/json", } # send request ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/deepinfra.html
446fd1452acb-4
) try: t = res.json() embeddings = t["embeddings"] except requests.exceptions.JSONDecodeError as e: raise ValueError( f"Error raised by inference API: {e}.\nResponse: {res.text}" ) return embeddings [docs] def embed_documents(sel...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/deepinfra.html
446fd1452acb-5
"""Embed a query using a Deep Infra deployed embedding model. Args: text: The text to embed. Returns: Embeddings for the text. """ instruction_pair = f"{self.query_instruction}{text}" embedding = self._embed([instruction_pair])[0] return embedding
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/deepinfra.html
4f6f9f594d0b-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
4f6f9f594d0b-1
""" # noqa: E501 def __init__( self, client: MlClient, model_id: str, *, input_field: str = "text_field", ): """ Initialize the ElasticsearchEmbeddings instance. Args: client (MlClient): An Elasticsearch ML client object. m...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
4f6f9f594d0b-2
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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
4f6f9f594d0b-3
model_id = "your_model_id" # Optional, only if different from 'text_field' input_field = "your_input_field" # Credentials can be passed in two ways. Either set the env vars # ES_CLOUD_ID, ES_USER, ES_PASSWORD and they will be automatically ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
4f6f9f594d0b-4
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") es_user = es_user or get_from_env("es_user", "ES_...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
4f6f9f594d0b-5
) -> ElasticsearchEmbeddings: """ Instantiate embeddings from an existing Elasticsearch connection. This method provides a way to create an instance of the ElasticsearchEmbeddings class using an existing Elasticsearch connection. The connection object is used to create an MlClien...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
4f6f9f594d0b-6
# Define the model ID and input field name (if different from default) model_id = "your_model_id" # Optional, only if different from 'text_field' input_field = "your_input_field" # Create Elasticsearch connection es_connection = Elasticsear...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
4f6f9f594d0b-7
from elasticsearch.client import MlClient # Create an MlClient from the given Elasticsearch connection client = MlClient(es_connection) # Return a new instance of the ElasticsearchEmbeddings class with # the MlClient, model_id, and input_field return cls(client, model_id, input_f...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
4f6f9f594d0b-8
) embeddings = [doc["predicted_value"] for doc in response["inference_results"]] return embeddings [docs] def embed_documents(self, texts: List[str]) -> List[List[float]]: """ Generate embeddings for a list of documents. Args: texts (List[str]): A list of document ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
4f6f9f594d0b-9
""" return self._embedding_func([text])[0]
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
0ae9510e2d56-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_...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html
0ae9510e2d56-1
wait=wait_exponential(multiplier=multiplier, min=min_seconds, max=max_seconds), before_sleep=before_sleep_log(logger, logging.WARNING), ) def embed_with_retry(embeddings: MiniMaxEmbeddings, *args: Any, **kwargs: Any) -> Any: """Use tenacity to retry the completion call.""" retry_decorator = _create_...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html
0ae9510e2d56-2
``MINIMAX_API_KEY`` set with your API token, or pass it as a named parameter to the constructor. Example: .. code-block:: python from langchain.embeddings import MiniMaxEmbeddings embeddings = MiniMaxEmbeddings() query_text = "This is a test query." query_...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html
0ae9510e2d56-3
"""For embed_query""" minimax_group_id: Optional[str] = None """Group ID for MiniMax API.""" minimax_api_key: Optional[str] = None """API Key for MiniMax API.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_en...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html
0ae9510e2d56-4
values["minimax_api_key"] = minimax_api_key return values def embed( self, texts: List[str], embed_type: str, ) -> List[List[float]]: payload = { "model": self.model, "type": embed_type, "texts": texts, } # HTTP headers ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html
0ae9510e2d56-5
raise ValueError( f"MiniMax API returned an error: {parsed_response['base_resp']}" ) embeddings = parsed_response["vectors"] return embeddings [docs] def embed_documents(self, texts: List[str]) -> List[List[float]]: """Embed documents using a MiniMax embedding endp...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html
0ae9510e2d56-6
embeddings = embed_with_retry( self, texts=[text], embed_type=self.embed_type_query ) return embeddings[0]
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html
19d4c5653c1b-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html
19d4c5653c1b-1
) """ client: Any #: :meta private: model: str = "embed-english-v2.0" """Model name to use.""" truncate: Optional[str] = None """Truncate embeddings that are too long from start or end ("NONE"|"START"|"END")""" cohere_api_key: Optional[str] = None class Config: """Configuration ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html
19d4c5653c1b-2
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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html
19d4c5653c1b-3
Returns: Embeddings for the text. """ embedding = self.client.embed( model=self.model, texts=[text], truncate=self.truncate ).embeddings[0] return list(map(float, embedding))
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html
902140f2f17c-0
Source code for langchain.embeddings.mosaicml """Wrapper around MosaicML APIs.""" from typing import Any, Dict, List, Mapping, Optional, Tuple import requests from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.utils import get_from_dict_or_env [docs]cla...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html
902140f2f17c-1
) mosaic_llm = MosaicMLInstructorEmbeddings( endpoint_url=endpoint_url, mosaicml_api_token="my-api-key" ) """ endpoint_url: str = ( "https://models.hosted-on.mosaicml.hosting/instructor-xl/v1/predict" ) """Endpoint URL to use.""" embed_...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html
902140f2f17c-2
extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" mosaicml_api_token = get_from_dict_or_env( values, "mosaicml_api_token", "MOSAICML_API_TOKEN" ) values["mo...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html
902140f2f17c-3
headers = { "Authorization": f"{self.mosaicml_api_token}", "Content-Type": "application/json", } # send request try: response = requests.post(self.endpoint_url, headers=headers, json=payload) except requests.exceptions.RequestException as e: ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html
902140f2f17c-4
) # The inference API has changed a couple of times, so we add some handling # to be robust to multiple response formats. if isinstance(parsed_response, dict): if "data" in parsed_response: output_item = parsed_response["data"] elif...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html
902140f2f17c-5
if "output" in first_item: embeddings = [item["output"] for item in parsed_response] else: raise ValueError( f"No key data or output in response: {parsed_response}" ) else: ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html
902140f2f17c-6
""" instruction_pairs = [(self.embed_instruction, text) for text in texts] embeddings = self._embed(instruction_pairs) return embeddings [docs] def embed_query(self, text: str) -> List[float]: """Embed a query using a MosaicML deployed instructor embedding model. Args: ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html
d6e7ae57a822-0
Source code for langchain.embeddings.self_hosted_hugging_face """Wrapper around HuggingFace embedding models for self-hosted remote hardware.""" import importlib import logging from typing import Any, Callable, List, Optional from langchain.embeddings.self_hosted import SelfHostedEmbeddings DEFAULT_MODEL_NAME = "senten...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
d6e7ae57a822-1
""" return client.encode(*args, **kwargs) def load_embedding_model(model_id: str, instruct: bool = False, device: int = 0) -> Any: """Load the embedding model.""" if not instruct: import sentence_transformers client = sentence_transformers.SentenceTransformer(model_id) else: from...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
d6e7ae57a822-2
logger.warning( "Device has %d GPUs available. " "Provide device={deviceId} to `from_model_id` to use available" "GPUs for execution. deviceId is -1 for CPU and " "can be a positive integer associated with CUDA device id.", cuda_device_coun...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
d6e7ae57a822-3
Example: .. code-block:: python from langchain.embeddings import SelfHostedHuggingFaceEmbeddings import runhouse as rh model_name = "sentence-transformers/all-mpnet-base-v2" gpu = rh.cluster(name="rh-a10x", instance_type="A100:1") hf = SelfHostedHuggin...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
d6e7ae57a822-4
load_fn_kwargs: Optional[dict] = None """Key word arguments to pass to the model load function.""" inference_fn: Callable = _embed_documents """Inference function to extract the embeddings.""" def __init__(self, **kwargs: Any): """Initialize the remote inference function.""" load_fn_kwar...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
d6e7ae57a822-5
"""Runs InstructorEmbedding embedding models on self-hosted remote hardware. Supported hardware includes auto-launched instances on AWS, GCP, Azure, and Lambda, as well as servers specified by IP address and SSH credentials (such as on-prem, or another cloud like Paperspace, Coreweave, etc.). To use...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
d6e7ae57a822-6
"""Model name to use.""" embed_instruction: str = DEFAULT_EMBED_INSTRUCTION """Instruction to use for embedding documents.""" query_instruction: str = DEFAULT_QUERY_INSTRUCTION """Instruction to use for embedding query.""" model_reqs: List[str] = ["./", "InstructorEmbedding", "torch"] """Require...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
d6e7ae57a822-7
super().__init__(load_fn_kwargs=load_fn_kwargs, **kwargs) [docs] def embed_documents(self, texts: List[str]) -> List[List[float]]: """Compute doc embeddings using a HuggingFace instruct model. Args: texts: The list of texts to embed. Returns: List of embeddings, one fo...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
d6e7ae57a822-8
""" instruction_pair = [self.query_instruction, text] embedding = self.client(self.pipeline_ref, [instruction_pair])[0] return embedding.tolist()
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
09186a9d7fbb-0
Source code for langchain.embeddings.embaas """Wrapper around embaas embeddings API.""" from typing import Any, Dict, List, Mapping, Optional import requests from pydantic import BaseModel, Extra, root_validator from typing_extensions import NotRequired, TypedDict from langchain.embeddings.base import Embeddings from l...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/embaas.html
09186a9d7fbb-1
To use, you should have the environment variable ``EMBAAS_API_KEY`` set with your API key, or pass it as a named parameter to the constructor. Example: .. code-block:: python # Initialise with default model and instruction from langchain.embeddings import EmbaasEmbeddings ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/embaas.html
09186a9d7fbb-2
"""Instruction used for domain-specific embeddings.""" api_url: str = EMBAAS_API_URL """The URL for the embaas embeddings API.""" embaas_api_key: Optional[str] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator() def validate_e...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/embaas.html
09186a9d7fbb-3
"""Get the identifying params.""" return {"model": self.model, "instruction": self.instruction} def _generate_payload(self, texts: List[str]) -> EmbaasEmbeddingsPayload: """Generates payload for the API request.""" payload = EmbaasEmbeddingsPayload(texts=texts, model=self.model) if s...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/embaas.html
09186a9d7fbb-4
response.raise_for_status() parsed_response = response.json() embeddings = [item["embedding"] for item in parsed_response["data"]] return embeddings def _generate_embeddings(self, texts: List[str]) -> List[List[float]]: """Generate embeddings using the Embaas API.""" payload ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/embaas.html
09186a9d7fbb-5
) raise [docs] def embed_documents(self, texts: List[str]) -> List[List[float]]: """Get embeddings for a list of texts. Args: texts: The list of texts to get embeddings for. Returns: List of embeddings, one for each text. """ batches = [ ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/embaas.html
09186a9d7fbb-6
Returns: List of embeddings. """ return self.embed_documents([text])[0]
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/embaas.html