id
stringlengths
14
16
text
stringlengths
31
2.41k
source
stringlengths
53
121
12f9bd8b091f-0
Source code for langchain.document_loaders.airbyte_json """Loader that loads local airbyte json files.""" import json from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.utils import stringify_dict [docs]class AirbyteJSONLoader(B...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte_json.html
cb52392989a3-0
Source code for langchain.document_loaders.image """Loader that loads image files.""" from typing import List from langchain.document_loaders.unstructured import UnstructuredFileLoader [docs]class UnstructuredImageLoader(UnstructuredFileLoader): """Loader that uses unstructured to load image files, such as PNGs and...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/image.html
486368f79bf6-0
Source code for langchain.document_loaders.readthedocs """Loader that loads ReadTheDocs documentation directory dump.""" from pathlib import Path from typing import Any, List, Optional, Tuple, Union from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class ReadT...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/readthedocs.html
486368f79bf6-1
from bs4 import BeautifulSoup except ImportError: raise ImportError( "Could not import python packages. " "Please install it with `pip install beautifulsoup4`. " ) try: _ = BeautifulSoup( "<html><body>Parser builder libr...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/readthedocs.html
486368f79bf6-2
if text is not None: break if text is not None: text = text.get_text() else: text = "" # trim empty lines return "\n".join([t for t in text.split("\n") if t])
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/readthedocs.html
5200ed9fd3e9-0
Source code for langchain.document_loaders.weather """Simple reader that reads weather data from OpenWeatherMap API""" from __future__ import annotations from datetime import datetime from typing import Iterator, List, Optional, Sequence from langchain.docstore.document import Document from langchain.document_loaders.b...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/weather.html
a9ddb222db34-0
Source code for langchain.document_loaders.html """Loader that uses unstructured to load HTML files.""" from typing import List from langchain.document_loaders.unstructured import UnstructuredFileLoader [docs]class UnstructuredHTMLLoader(UnstructuredFileLoader): """Loader that uses unstructured to load HTML files."...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/html.html
6fd690e8b81b-0
Source code for langchain.document_loaders.srt """Loader for .srt (subtitle) files.""" from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class SRTLoader(BaseLoader): """Loader for .srt (subtitle) files.""" def __init__(self, fil...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/srt.html
65b765c0755c-0
Source code for langchain.document_loaders.onedrive_file from __future__ import annotations import tempfile from typing import TYPE_CHECKING, List from pydantic import BaseModel, Field from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.document_loaders...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/onedrive_file.html
5d522e33f4ed-0
Source code for langchain.document_loaders.s3_directory """Loading logic for loading documents from an s3 directory.""" from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.document_loaders.s3_file import S3FileLoader [docs]class ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/s3_directory.html
eaa2451f71cb-0
Source code for langchain.document_loaders.mhtml """Loader to load MHTML files, enriching metadata with page title.""" import email import logging from typing import Dict, List, Union from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader logger = logging.getLogger(__nam...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mhtml.html
eaa2451f71cb-1
for part in parts: if part.get_content_type() == "text/html": html = part.get_payload(decode=True).decode() soup = BeautifulSoup(html, **self.bs_kwargs) text = soup.get_text(self.get_text_separator) if soup.title: ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mhtml.html
09ac36a936cd-0
Source code for langchain.document_loaders.gcs_file """Loading logic for loading documents from a GCS file.""" import os import tempfile from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.document_loaders.unstructured import Uns...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gcs_file.html
dd79b729aef4-0
Source code for langchain.document_loaders.toml import json from pathlib import Path from typing import Iterator, List, Union from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class TomlLoader(BaseLoader): """ A TOML document loader that inherits from ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/toml.html
4e1c5c8aab88-0
Source code for langchain.document_loaders.psychic """Loader that loads documents from Psychic.dev.""" from typing import List, Optional from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class PsychicLoader(BaseLoader): """Loader that loads documents from ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/psychic.html
bd7f58d718e6-0
Source code for langchain.document_loaders.iugu """Loader that fetches data from IUGU""" import json import urllib.request from typing import List, Optional from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.utils import get_from_env, stringify_dict IU...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/iugu.html
bd7f58d718e6-1
[docs] def load(self) -> List[Document]: return self._get_resource()
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/iugu.html
ead23bef666e-0
Source code for langchain.document_loaders.blob_loaders.youtube_audio from typing import Iterable, List from langchain.document_loaders.blob_loaders import FileSystemBlobLoader from langchain.document_loaders.blob_loaders.schema import Blob, BlobLoader [docs]class YoutubeAudioLoader(BlobLoader): """Load YouTube url...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/youtube_audio.html
5e9a2c7c2e0e-0
Source code for langchain.document_loaders.blob_loaders.file_system """Use to load blobs from the local file system.""" from pathlib import Path from typing import Callable, Iterable, Iterator, Optional, Sequence, TypeVar, Union from langchain.document_loaders.blob_loaders.schema import Blob, BlobLoader T = TypeVar("T"...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/file_system.html
5e9a2c7c2e0e-1
*, glob: str = "**/[!.]*", suffixes: Optional[Sequence[str]] = None, show_progress: bool = False, ) -> None: """Initialize with path to directory and how to glob over it. Args: path: Path to directory to load from glob: Glob pattern relative to the spe...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/file_system.html
5e9a2c7c2e0e-2
self, ) -> Iterable[Blob]: """Yield blobs that match the requested pattern.""" iterator = _make_iterator( length_func=self.count_matching_files, show_progress=self.show_progress ) for path in iterator(self._yield_paths()): yield Blob.from_path(path) def _y...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/file_system.html
8ed853cfb069-0
Source code for langchain.document_loaders.blob_loaders.schema """Schema for Blobs and Blob Loaders. The goal is to facilitate decoupling of content loading from content parsing code. In addition, content loading code should provide a lazy loading interface by default. """ from __future__ import annotations import cont...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/schema.html
8ed853cfb069-1
return str(self.path) if self.path else None @root_validator(pre=True) def check_blob_is_valid(cls, values: Mapping[str, Any]) -> Mapping[str, Any]: """Verify that either data or path is provided.""" if "data" not in values and "path" not in values: raise ValueError("Either data or p...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/schema.html
8ed853cfb069-2
yield f else: raise NotImplementedError(f"Unable to convert blob {self}") [docs] @classmethod def from_path( cls, path: PathLike, *, encoding: str = "utf-8", mime_type: Optional[str] = None, guess_type: bool = True, ) -> Blob: """Loa...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/schema.html
8ed853cfb069-3
mime_type: if provided, will be set as the mime-type of the data path: if provided, will be set as the source from which the data came Returns: Blob instance """ return cls(data=data, mimetype=mime_type, encoding=encoding, path=path) def __repr__(self) -> str: ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/schema.html
df7893028286-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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html
df7893028286-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") """...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html
df7893028286-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html
9b32e2c98154-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): """...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
9b32e2c98154-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
9b32e2c98154-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
9b32e2c98154-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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
9b32e2c98154-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html
1563c4147e59-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
1563c4147e59-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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
1563c4147e59-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") ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
1563c4147e59-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" #...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
1563c4147e59-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html
4670330e2570-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
4670330e2570-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html
2841e7409197-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html
2841e7409197-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 " ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html
2841e7409197-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html
2841e7409197-3
Embedding for the text. """ embedding = embed_with_retry( self, input=text, text_type="query", model=self.model )[0]["embedding"] return embedding
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html
48ed439d5783-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
48ed439d5783-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/modelscope_hub.html
ef46c4b0034c-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
ef46c4b0034c-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html
ef46c4b0034c-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html
30f90f7e0093-0
Source code for langchain.embeddings.sagemaker_endpoint """Wrapper around Sagemaker InvokeEndpoint API.""" from typing import Any, Dict, List, Optional from pydantic import BaseModel, Extra, root_validator from langchain.embeddings.base import Embeddings from langchain.llms.sagemaker_endpoint import ContentHandlerBase ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
30f90f7e0093-1
credentials_profile_name=credentials_profile_name ) """ client: Any #: :meta private: endpoint_name: str = "" """The name of the endpoint from the deployed Sagemaker model. Must be unique within an AWS Region.""" region_name: str = "" """The aws region where the Sagemaker model ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
30f90f7e0093-2
""" # noqa: E501 model_kwargs: Optional[Dict] = None """Key word arguments to pass to the model.""" endpoint_kwargs: Optional[Dict] = None """Optional attributes passed to the invoke_endpoint function. See `boto3`_. docs for more info. .. _boto3: <https://boto3.amazonaws.com/v1/documentation/ap...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
30f90f7e0093-3
# replace newlines, which can negatively affect performance. texts = list(map(lambda x: x.replace("\n", " "), texts)) _model_kwargs = self.model_kwargs or {} _endpoint_kwargs = self.endpoint_kwargs or {} body = self.content_handler.transform_input(texts, _model_kwargs) content_ty...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
30f90f7e0093-4
"""Compute query embeddings using a SageMaker inference endpoint. Args: text: The text to embed. Returns: Embeddings for the text. """ return self._embedding_func([text])[0]
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
6d6bcc548a9a-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
6d6bcc548a9a-1
"""Configuration for this pydantic object.""" 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_tok...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html
6d6bcc548a9a-2
f"Error raised by inference API: {parsed_response['error']}" ) # 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: ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html
6d6bcc548a9a-3
Args: texts: The list of texts to embed. Returns: List of embeddings, one for each text. """ instruction_pairs = [(self.embed_instruction, text) for text in texts] embeddings = self._embed(instruction_pairs) return embeddings [docs] def embed_query(self...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html
54985e2a7fc2-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
54985e2a7fc2-1
if device < 0 and cuda_device_count > 0: 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 wi...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
54985e2a7fc2-2
model_load_fn: Callable = load_embedding_model """Function to load the model remotely on the server.""" 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.""" ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
54985e2a7fc2-3
model_name=model_name, hardware=gpu) """ 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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html
54985e2a7fc2-4
Returns: Embeddings for the text. """ 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
112bb16d008b-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
112bb16d008b-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: ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html
112bb16d008b-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html
e31f29488f15-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
e31f29488f15-1
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, values: Dict) -> Dict: """Validate tha...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/deepinfra.html
e31f29488f15-2
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(self, texts: ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/deepinfra.html
c2be5813d9b8-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
c2be5813d9b8-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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/embaas.html
c2be5813d9b8-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: ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/embaas.html
05f193a1278d-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
004f8f89038f-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
004f8f89038f-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
004f8f89038f-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':...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
004f8f89038f-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html
97ffc8aaf9fa-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
97ffc8aaf9fa-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() ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html
2554362e1fe6-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html
2554362e1fe6-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,...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html
2554362e1fe6-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html
2554362e1fe6-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)
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html
7582608e26e2-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
7582608e26e2-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
7582608e26e2-2
@_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): """Wrapper around OpenAI embedding models. To use, you...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
7582608e26e2-3
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." query_result = embeddings.embed_query...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
7582608e26e2-4
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 use this Embedding class with a model name not supported by ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
7582608e26e2-5
default_api_version = "2022-12-01" else: default_api_version = "" values["openai_api_version"] = get_from_dict_or_env( values, "openai_api_version", "OPENAI_API_VERSION", default=default_api_version, ) values["openai_organizatio...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
7582608e26e2-6
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(texts))] try: import tiktoken except ImportError: raise ImportError( ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
7582608e26e2-7
response = embed_with_retry( self, input=tokens[i : i + _chunk_size], **self._invocation_params, ) batched_embeddings += [r["embedding"] for r in response["data"]] results: List[List[List[float]]] = [[] for _ in range(len(texts))] n...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
7582608e26e2-8
"Please install it with `pip install tiktoken`." ) tokens = [] indices = [] model_name = self.tiktoken_model_name or self.model try: encoding = tiktoken.encoding_for_model(model_name) except KeyError: logger.warning("Warning: model not found. U...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
7582608e26e2-9
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] if len(_result) == 0: average = ( await async_embed_with_retry( ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
7582608e26e2-10
else: 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", " ") return ( await async_...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
7582608e26e2-11
# 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(texts, engine=self.deployment) [docs] def embed_query(self, text: str) -> List[float]: """Call out to...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html
6aeb61bc6e4a-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
6aeb61bc6e4a-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
6aeb61bc6e4a-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...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html
0396fe8ac2f6-0
Source code for langchain.callbacks.file """Callback Handler that writes to a file.""" from typing import Any, Dict, Optional, TextIO, cast from langchain.callbacks.base import BaseCallbackHandler from langchain.input import print_text from langchain.schema import AgentAction, AgentFinish [docs]class FileCallbackHandle...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/file.html
0396fe8ac2f6-1
) -> Any: """Run on agent action.""" print_text(action.log, color=color if color else self.color, file=self.file) [docs] def on_tool_end( self, output: str, color: Optional[str] = None, observation_prefix: Optional[str] = None, llm_prefix: Optional[str] = None,...
https://api.python.langchain.com/en/latest/_modules/langchain/callbacks/file.html