id
stringlengths
14
16
text
stringlengths
13
2.7k
source
stringlengths
57
178
0f45dd3b4937-0
Source code for langchain.embeddings.localai from __future__ import annotations import logging import warnings from typing import ( Any, Callable, Dict, List, Literal, Optional, Sequence, Set, Tuple, Union, ) from tenacity import ( AsyncRetrying, before_sleep_log, ret...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html
0f45dd3b4937-1
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, stop=stop_after_attempt(embeddings.max_retries), wait=wait_expone...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html
0f45dd3b4937-2
retry_decorator = _create_retry_decorator(embeddings) @retry_decorator def _embed_with_retry(**kwargs: Any) -> Any: response = embeddings.client.create(**kwargs) return _check_response(response) return _embed_with_retry(**kwargs) [docs]async def async_embed_with_retry(embeddings: LocalAIEmbe...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html
0f45dd3b4937-3
openai_api_base: Optional[str] = None # to support explicit proxy for LocalAI openai_proxy: Optional[str] = None embedding_ctx_length: int = 8191 """The maximum number of tokens to embed at once.""" openai_api_key: Optional[str] = None openai_organization: Optional[str] = None allowed_specia...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html
0f45dd3b4937-4
if field_name not in all_required_field_names: warnings.warn( f"""WARNING! {field_name} is not default parameter. {field_name} was transferred to model_kwargs. Please confirm that {field_name} is what you intended.""" ) ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html
0f45dd3b4937-5
"OPENAI_ORGANIZATION", default="", ) try: import openai values["client"] = openai.Embedding except ImportError: raise ImportError( "Could not import openai python package. " "Please install it with `pip install opena...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html
0f45dd3b4937-6
**self._invocation_params, )["data"][0]["embedding"] async def _aembedding_func(self, text: str, *, engine: str) -> List[float]: """Call out to LocalAI's embedding endpoint.""" # handle large input text if self.model.endswith("001"): # See: https://github.com/openai/opena...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html
0f45dd3b4937-7
specified by the class. Returns: List of embeddings, one for each text. """ embeddings = [] for text in texts: response = await self._aembedding_func(text, engine=self.deployment) embeddings.append(response) return embeddings [docs] def embe...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html
25a7ac7afa19-0
Source code for langchain.embeddings.embaas from typing import Any, Dict, List, Mapping, Optional import requests from typing_extensions import NotRequired, TypedDict from langchain.pydantic_v1 import BaseModel, Extra, root_validator from langchain.schema.embeddings import Embeddings from langchain.utils import get_fro...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/embaas.html
25a7ac7afa19-1
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_environment(cls, values: Dict) -> Dict: """Validate ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/embaas.html
25a7ac7afa19-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: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/embaas.html
0145e31d213d-0
Source code for langchain.embeddings.cache """Module contains code for a cache backed embedder. The cache backed embedder is a wrapper around an embedder that caches embeddings in a key-value store. The cache is used to avoid recomputing embeddings for the same text. The text is hashed and the hash is used as the key i...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/cache.html
0145e31d213d-1
The interface allows works with any store that implements the abstract store interface accepting keys of type str and values of list of floats. If need be, the interface can be extended to accept other implementations of the value serializer and deserializer, as well as the key encoder. Examples: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/cache.html
0145e31d213d-2
to embed the documents and stores the results in the cache. Args: texts: A list of texts to embed. Returns: A list of embeddings for the given texts. """ vectors: List[Union[List[float], None]] = self.document_embedding_store.mget( texts ) ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/cache.html
0145e31d213d-3
def from_bytes_store( cls, underlying_embeddings: Embeddings, document_embedding_cache: BaseStore[str, bytes], *, namespace: str = "", ) -> CacheBackedEmbeddings: """On-ramp that adds the necessary serialization and encoding to the store. Args: und...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/cache.html
e413f5101d1f-0
Source code for langchain.embeddings.tensorflow_hub from typing import Any, List from langchain.pydantic_v1 import BaseModel, Extra from langchain.schema.embeddings import Embeddings DEFAULT_MODEL_URL = "https://tfhub.dev/google/universal-sentence-encoder-multilingual/3" [docs]class TensorflowHubEmbeddings(BaseModel, E...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html
e413f5101d1f-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() ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html
d1618f411224-0
Source code for langchain.embeddings.fake import hashlib from typing import List import numpy as np from langchain.pydantic_v1 import BaseModel from langchain.schema.embeddings import Embeddings [docs]class FakeEmbeddings(Embeddings, BaseModel): """Fake embedding model.""" size: int """The size of the embed...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/fake.html
8486bf4035d9-0
Source code for langchain.embeddings.clarifai import logging from typing import Any, Dict, List, Optional from langchain.pydantic_v1 import BaseModel, Extra, root_validator from langchain.schema.embeddings import Embeddings from langchain.utils import get_from_dict_or_env logger = logging.getLogger(__name__) [docs]clas...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/clarifai.html
8486bf4035d9-1
extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" values["pat"] = get_from_dict_or_env(values, "pat", "CLARIFAI_PAT") user_id = values.get("user_id") app_id = values.ge...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/clarifai.html
8486bf4035d9-2
List of embeddings, one for each text. """ try: from clarifai_grpc.grpc.api import ( resources_pb2, service_pb2, ) from clarifai_grpc.grpc.api.status import status_code_pb2 except ImportError: raise ImportError( ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/clarifai.html
8486bf4035d9-3
for o in post_model_outputs_response.outputs ] ) return embeddings [docs] def embed_query(self, text: str) -> List[float]: """Call out to Clarifai's embedding models. Args: text: The text to embed. Returns: Embeddings for the text. ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/clarifai.html
8486bf4035d9-4
for o in post_model_outputs_response.outputs ] return embeddings[0]
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/clarifai.html
e33a6c51373b-0
Source code for langchain.embeddings.mosaicml from typing import Any, Dict, List, Mapping, Optional, Tuple import requests from langchain.pydantic_v1 import BaseModel, Extra, root_validator from langchain.schema.embeddings import Embeddings from langchain.utils import get_from_dict_or_env [docs]class MosaicMLInstructor...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html
e33a6c51373b-1
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...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html
e33a6c51373b-2
# to be robust to multiple response formats. if isinstance(parsed_response, dict): output_keys = ["data", "output", "outputs"] for key in output_keys: if key in parsed_response: output_item = parsed_response[key] ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html
b9d18d92cb29-0
Source code for langchain.embeddings.gradient_ai import asyncio import logging import os from concurrent.futures import ThreadPoolExecutor from typing import Any, Callable, Dict, List, Optional, Tuple import aiohttp import numpy as np import requests from langchain.pydantic_v1 import BaseModel, Extra, root_validator fr...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html
b9d18d92cb29-1
"""Gradient client.""" # LLM call kwargs class Config: """Configuration for this pydantic object.""" extra = Extra.forbid @root_validator(allow_reuse=True) def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html
b9d18d92cb29-2
model=self.model, texts=texts, ) return embeddings [docs] async def aembed_documents(self, texts: List[str]) -> List[List[float]]: """Async call out to Gradient's embedding endpoint. Args: texts: The list of texts to embed. Returns: List of ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html
b9d18d92cb29-3
workspace_id="12345614fc0_workspace", access_token="gradientai-access_token", ) embeds = mini_client.embed( model="bge-large", text=["doc1", "doc2"] ) # or embeds = await mini_client.aembed( model...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html
b9d18d92cb29-4
self._batch_size = 128 @staticmethod def _permute( texts: List[str], sorter: Callable = len ) -> Tuple[List[str], Callable]: """Sort texts in ascending order, and delivers a lambda expr, which can sort a same length list https://github.com/UKPLab/sentence-transformers/blob/ ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html
b9d18d92cb29-5
Returns: List[List[str]]: Batches of List of sentences """ if len(texts) == 1: # special case query return [texts] batches = [] for start_index in range(0, len(texts), self._batch_size): batches.append(texts[start_index : start_index + self...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html
b9d18d92cb29-6
) -> List[List[float]]: response = requests.post( **self._kwargs_post_request(model=model, texts=batch_texts) ) if response.status_code != 200: raise Exception( f"Gradient returned an unexpected response with status " f"{response.status_cod...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html
b9d18d92cb29-7
raise Exception( f"Gradient returned an unexpected response with status " f"{response.status}: {response.text}" ) embedding = (await response.json())["embeddings"] return [e["embedding"] for e in embedding] [docs] async def aembed(self, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/gradient_ai.html
00ab8dda6dd1-0
Source code for langchain.embeddings.spacy_embeddings import importlib.util from typing import Any, Dict, List from langchain.pydantic_v1 import BaseModel, Extra, root_validator from langchain.schema.embeddings import Embeddings [docs]class SpacyEmbeddings(BaseModel, Embeddings): """Embeddings by SpaCy models. ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/spacy_embeddings.html
00ab8dda6dd1-1
import spacy values["nlp"] = spacy.load("en_core_web_sm") except OSError: # If the model is not found, raise a ValueError raise ValueError( "Spacy model 'en_core_web_sm' not found. " "Please install it with" " `python -m spacy d...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/spacy_embeddings.html
00ab8dda6dd1-2
""" Asynchronously generates an embedding for a single piece of text. This method is not implemented and raises a NotImplementedError. Args: text (str): The text to generate an embedding for. Raises: NotImplementedError: This method is not implemented. """...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/spacy_embeddings.html
326b3068e98e-0
Source code for langchain.embeddings.bedrock import asyncio import json import os from functools import partial from typing import Any, Dict, List, Optional from langchain.pydantic_v1 import BaseModel, Extra, root_validator from langchain.schema.embeddings import Embeddings [docs]class BedrockEmbeddings(BaseModel, Embe...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html
326b3068e98e-1
has either access keys or role information specified. 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-embed-text-v1" ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html
326b3068e98e-2
raise ModuleNotFoundError( "Could not import boto3 python package. " "Please install it with `pip install boto3`." ) except Exception as e: raise ValueError( "Could not load credentials to authenticate with AWS client. " "Pl...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html
326b3068e98e-3
return response_body.get("embedding") except Exception as e: raise ValueError(f"Error raised by inference endpoint: {e}") [docs] def embed_documents(self, texts: List[str]) -> List[List[float]]: """Compute doc embeddings using a Bedrock model. Args: texts: The list of ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html
47325573394b-0
Source code for langchain.embeddings.llamacpp from typing import Any, Dict, List, Optional from langchain.pydantic_v1 import BaseModel, Extra, Field, root_validator from langchain.schema.embeddings import Embeddings [docs]class LlamaCppEmbeddings(BaseModel, Embeddings): """llama.cpp embedding models. To use, yo...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html
47325573394b-1
"""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") """Number of tokens to process in parallel. Should be...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html
47325573394b-2
except ImportError: 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: rai...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html
0a2b118f60fc-0
Source code for langchain.embeddings.sagemaker_endpoint from typing import Any, Dict, List, Optional from langchain.llms.sagemaker_endpoint import ContentHandlerBase from langchain.pydantic_v1 import BaseModel, Extra, root_validator from langchain.schema.embeddings import Embeddings [docs]class EmbeddingsContentHandler...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
0a2b118f60fc-1
) #Use with boto3 client client = boto3.client( "sagemaker-runtime", region_name=region_name ) se = SagemakerEndpointEmbeddings( endpoint_name=endpoint_name, client=client ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
0a2b118f60fc-2
def transform_output(self, output: bytes) -> List[List[float]]: response_json = json.loads(output.read().decode("utf-8")) return response_json["vectors"] """ # noqa: E501 model_kwargs: Optional[Dict] = None """Keyword arguments to pass to the model.""" endpoint_k...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
0a2b118f60fc-3
raise ImportError( "Could not import boto3 python package. " "Please install it with `pip install boto3`." ) return values def _embedding_func(self, texts: List[str]) -> List[List[float]]: """Call out to SageMaker Inference embedding endpoint.""" #...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
0a2b118f60fc-4
for i in range(0, len(texts), _chunk_size): response = self._embedding_func(texts[i : i + _chunk_size]) results.extend(response) return results [docs] def embed_query(self, text: str) -> List[float]: """Compute query embeddings using a SageMaker inference endpoint. Arg...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
df7ccf0cb694-0
Source code for langchain.embeddings.ernie import asyncio import logging import threading from functools import partial from typing import Dict, List, Optional import requests from langchain.pydantic_v1 import BaseModel, root_validator from langchain.schema.embeddings import Embeddings from langchain.utils import get_f...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/ernie.html
df7ccf0cb694-1
) resp = requests.post( f"{base_url}/embedding-v1", headers={ "Content-Type": "application/json", }, params={"access_token": self.access_token}, json=json, ) return resp.json() def _refresh_access_token_with_lock(sel...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/ernie.html
df7ccf0cb694-2
self._refresh_access_token_with_lock() resp = self._embedding({"input": [text for text in chunk]}) else: raise ValueError(f"Error from Ernie: {resp}") lst.extend([i["embedding"] for i in resp["data"]]) return lst [docs] def embed_query(self,...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/ernie.html
df7ccf0cb694-3
List[List[float]]: List of embeddings, one for each text. """ result = await asyncio.gather(*[self.aembed_query(text) for text in texts]) return list(result)
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/ernie.html
451253574251-0
Source code for langchain.embeddings.aleph_alpha from typing import Any, Dict, List, Optional from langchain.pydantic_v1 import BaseModel, root_validator from langchain.schema.embeddings import Embeddings from langchain.utils import get_from_dict_or_env [docs]class AlephAlphaAsymmetricSemanticEmbedding(BaseModel, Embed...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
451253574251-1
explicitly been set in the request.""" control_log_additive: bool = True """Apply controls on prompt items by adding the log(control_factor) to attention scores.""" # Client params aleph_alpha_api_key: Optional[str] = None """API key for Aleph Alpha API.""" host: str = "https://api.aleph-al...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
451253574251-2
retry made. So with the default setting of 8 retries a total wait time of 63.5 s is added between the retries.""" nice: bool = False """Setting this to True, will signal to the API that you intend to be nice to other users by de-prioritizing your request below concurrent ones.""" @root_val...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
451253574251-3
SemanticRepresentation, ) except ImportError: raise ValueError( "Could not import aleph_alpha_client python package. " "Please install it with `pip install aleph_alpha_client`." ) document_embeddings = [] for text in texts: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
451253574251-4
"control_log_additive": self.control_log_additive, } symmetric_request = SemanticEmbeddingRequest(**symmetric_params) symmetric_response = self.client.semantic_embed( request=symmetric_request, model=self.model ) return symmetric_response.embedding [docs]class AlephAl...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
451253574251-5
query_response = self.client.semantic_embed( request=query_request, model=self.model ) return query_response.embedding [docs] def embed_documents(self, texts: List[str]) -> List[List[float]]: """Call out to Aleph Alpha's Document endpoint. Args: texts: The list...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
29877826ff73-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.schema.embeddings imp...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
29877826ff73-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 ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
29877826ff73-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") ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
29877826ff73-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" #...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
29877826ff73-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
cc0e57560807-0
Source code for langchain.embeddings.voyageai from __future__ import annotations import json import logging from typing import ( Any, Callable, Dict, List, Optional, Tuple, Union, cast, ) import requests from tenacity import ( before_sleep_log, retry, stop_after_attempt, ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/voyageai.html
cc0e57560807-1
@retry_decorator def _embed_with_retry(**kwargs: Any) -> Any: response = requests.post(**kwargs) return _check_response(response.json()) return _embed_with_retry(**kwargs) [docs]class VoyageEmbeddings(BaseModel, Embeddings): """Voyage embedding models. To use, you should have the environ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/voyageai.html
cc0e57560807-2
values["voyage_api_key"] = convert_to_secret_str( get_from_dict_or_env(values, "voyage_api_key", "VOYAGE_API_KEY") ) return values def _invocation_params( self, input: List[str], input_type: Optional[str] = None ) -> Dict: api_key = cast(SecretStr, self.voyage_api_key...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/voyageai.html
cc0e57560807-3
self, **self._invocation_params( input=texts[i : i + batch_size], input_type=input_type ), ) embeddings.extend(r["embedding"] for r in response["data"]) return embeddings [docs] def embed_documents(self, texts: List[str]) -> List[Lis...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/voyageai.html
493efd198652-0
Source code for langchain.embeddings.llm_rails """ This file is for LLMRails Embedding """ import logging import os from typing import List, Optional import requests from langchain.pydantic_v1 import BaseModel, Extra from langchain.schema.embeddings import Embeddings [docs]class LLMRailsEmbeddings(BaseModel, Embeddings...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/llm_rails.html
493efd198652-1
response = requests.post( "https://api.llmrails.com/v1/embeddings", headers={"X-API-KEY": api_key}, json={"input": texts, "model": self.model}, timeout=60, ) return [item["embedding"] for item in response.json()["data"]] [docs] def embed_query(self, tex...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/llm_rails.html
f55490bf7f65-0
Source code for langchain.embeddings.self_hosted_hugging_face import importlib import logging from typing import Any, Callable, List, Optional from langchain.embeddings.self_hosted import SelfHostedEmbeddings DEFAULT_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2" DEFAULT_INSTRUCT_MODEL = "hkunlp/instructor-larg...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
f55490bf7f65-1
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...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
f55490bf7f65-2
"""Function to load the model remotely on the server.""" load_fn_kwargs: Optional[dict] = None """Keyword arguments to pass to the model load function.""" inference_fn: Callable = _embed_documents """Inference function to extract the embeddings.""" def __init__(self, **kwargs: Any): """Initi...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
f55490bf7f65-3
""" model_id: str = DEFAULT_INSTRUCT_MODEL """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] = ["...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
f55490bf7f65-4
Returns: Embeddings for the text. """ instruction_pair = [self.query_instruction, text] embedding = self.client(self.pipeline_ref, [instruction_pair])[0] return embedding.tolist()
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
55f1e90718f2-0
Source code for langchain.embeddings.awa from typing import Any, Dict, List from langchain.pydantic_v1 import BaseModel, root_validator from langchain.schema.embeddings import Embeddings [docs]class AwaEmbeddings(BaseModel, Embeddings): """Embedding documents and queries with Awa DB. Attributes: client:...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/awa.html
55f1e90718f2-1
Returns: List of embeddings, one for each text. """ return self.client.EmbeddingBatch(texts) [docs] def embed_query(self, text: str) -> List[float]: """Compute query embeddings using AwaEmbedding. Args: text: The text to embed. Returns: Embe...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/awa.html
9451bfd14ba2-0
Source code for langchain.embeddings.baidu_qianfan_endpoint from __future__ import annotations import logging from typing import Any, Dict, List, Optional from langchain.pydantic_v1 import BaseModel, root_validator from langchain.schema.embeddings import Embeddings from langchain.utils import get_from_dict_or_env logge...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/baidu_qianfan_endpoint.html
9451bfd14ba2-1
configuration file are available or not. init qianfan embedding client with `ak`, `sk`, `model`, `endpoint` Args: values: a dictionary containing configuration information, must include the fields of qianfan_ak and qianfan_sk Returns: a dictionary containing c...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/baidu_qianfan_endpoint.html
9451bfd14ba2-2
resp = self.embed_documents([text]) return resp[0] [docs] def embed_documents(self, texts: List[str]) -> List[List[float]]: """ Embeds a list of text documents using the AutoVOT algorithm. Args: texts (List[str]): A list of text documents to embed. Returns: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/baidu_qianfan_endpoint.html
d314afe4a826-0
Source code for langchain.embeddings.javelin_ai_gateway from __future__ import annotations from typing import Any, Iterator, List, Optional from langchain.pydantic_v1 import BaseModel from langchain.schema.embeddings import Embeddings def _chunk(texts: List[str], size: int) -> Iterator[List[str]]: for i in range(0,...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/javelin_ai_gateway.html
d314afe4a826-1
raise ImportError( "Could not import javelin_sdk python package. " "Please install it with `pip install javelin_sdk`." ) super().__init__(**kwargs) if self.gateway_uri: try: self.client = JavelinClient( base_url=...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/javelin_ai_gateway.html
d314afe4a826-2
print("Failed to query route: " + str(e)) return embeddings [docs] def embed_documents(self, texts: List[str]) -> List[List[float]]: return self._query(texts) [docs] def embed_query(self, text: str) -> List[float]: return self._query([text])[0] [docs] async def aembed_documents(self, te...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/javelin_ai_gateway.html
4274382abceb-0
Source code for langchain.embeddings.self_hosted from typing import Any, Callable, List from langchain.llms.self_hosted import SelfHostedPipeline from langchain.pydantic_v1 import Extra from langchain.schema.embeddings import Embeddings def _embed_documents(pipeline: Any, *args: Any, **kwargs: Any) -> List[List[float]]...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
4274382abceb-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
4274382abceb-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...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
671b55d78689-0
Source code for langchain.embeddings.nlpcloud from typing import Any, Dict, List from langchain.pydantic_v1 import BaseModel, root_validator from langchain.schema.embeddings import Embeddings from langchain.utils import get_from_dict_or_env [docs]class NLPCloudEmbeddings(BaseModel, Embeddings): """NLP Cloud embeddi...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/nlpcloud.html
671b55d78689-1
"Please install it with `pip install nlpcloud`." ) return values [docs] def embed_documents(self, texts: List[str]) -> List[List[float]]: """Embed a list of documents using NLP Cloud. Args: texts: The list of texts to embed. Returns: List of embeddi...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/nlpcloud.html
567d392a6389-0
Source code for langchain.embeddings.cohere from typing import Any, Dict, List, Optional from langchain.pydantic_v1 import BaseModel, Extra, root_validator from langchain.schema.embeddings import Embeddings from langchain.utils import get_from_dict_or_env [docs]class CohereEmbeddings(BaseModel, Embeddings): """Cohe...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html
567d392a6389-1
extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" cohere_api_key = get_from_dict_or_env( values, "cohere_api_key", "COHERE_API_KEY" ) max_retries = values.g...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html
567d392a6389-2
"""Async call out to Cohere's embedding endpoint. Args: texts: The list of texts to embed. Returns: List of embeddings, one for each text. """ embeddings = await self.async_client.embed( model=self.model, texts=texts, input_type...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html
3f0ad75bcb3a-0
Source code for langchain.embeddings.mlflow_gateway from __future__ import annotations from typing import Any, Iterator, List, Optional from langchain.pydantic_v1 import BaseModel from langchain.schema.embeddings import Embeddings def _chunk(texts: List[str], size: int) -> Iterator[List[str]]: for i in range(0, len...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/mlflow_gateway.html
3f0ad75bcb3a-1
if self.gateway_uri: mlflow.gateway.set_gateway_uri(self.gateway_uri) def _query(self, texts: List[str]) -> List[List[float]]: try: import mlflow.gateway except ImportError as e: raise ImportError( "Could not import `mlflow.gateway` module. " ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/mlflow_gateway.html
0b8b0f0e24a0-0
Source code for langchain.embeddings.ollama from typing import Any, Dict, List, Mapping, Optional import requests from langchain.pydantic_v1 import BaseModel, Extra from langchain.schema.embeddings import Embeddings [docs]class OllamaEmbeddings(BaseModel, Embeddings): """Ollama locally runs large language models. ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/ollama.html
0b8b0f0e24a0-1
from the generated text. A lower learning rate will result in slower adjustments, while a higher learning rate will make the algorithm more responsive. (Default: 0.1)""" mirostat_tau: Optional[float] = None """Controls the balance between coherence and diversity of the output. A lower value will res...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/ollama.html
0b8b0f0e24a0-2
make the model answer more creatively. (Default: 0.8)""" stop: Optional[List[str]] = None """Sets the stop tokens to use.""" tfs_z: Optional[float] = None """Tail free sampling is used to reduce the impact of less probable tokens from the output. A higher value (e.g., 2.0) will reduce the impact...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/ollama.html
0b8b0f0e24a0-3
"repeat_penalty": self.repeat_penalty, "temperature": self.temperature, "stop": self.stop, "tfs_z": self.tfs_z, "top_k": self.top_k, "top_p": self.top_p, }, } model_kwargs: Optional[dict] = None """Other model ke...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/ollama.html
0b8b0f0e24a0-4
except requests.exceptions.JSONDecodeError as e: raise ValueError( f"Error raised by inference API: {e}.\nResponse: {res.text}" ) def _embed(self, input: List[str]) -> List[List[float]]: embeddings_list: List[List[float]] = [] for prompt in input: ...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/ollama.html
053d28d89110-0
Source code for langchain.embeddings.edenai from typing import Any, Dict, List, Optional from langchain.pydantic_v1 import BaseModel, Extra, Field, root_validator from langchain.schema.embeddings import Embeddings from langchain.utilities.requests import Requests from langchain.utils import get_from_dict_or_env [docs]c...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/edenai.html
053d28d89110-1
"""Compute embeddings using EdenAi api.""" url = "https://api.edenai.run/v2/text/embeddings" headers = { "accept": "application/json", "content-type": "application/json", "authorization": f"Bearer {self.edenai_api_key}", "User-Agent": self.get_user_agent()...
lang/api.python.langchain.com/en/latest/_modules/langchain/embeddings/edenai.html