id stringlengths 14 16 | text stringlengths 31 2.41k | source stringlengths 54 121 |
|---|---|---|
5c4d318f409e-2 | # Custom api parameters (create embeddings automatically)
from langchain.document_loaders.embaas import EmbaasBlobLoader
loader = EmbaasBlobLoader(
params={
"should_embed": True,
"model": "e5-large-v2",
"chunk_size": 256... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html |
5c4d318f409e-3 | payload["mime_type"] = blob.mimetype
return payload
def _handle_request(
self, payload: EmbaasDocumentExtractionPayload
) -> List[Document]:
"""Sends a request to the embaas API and handles the response."""
headers = {
"Authorization": f"Bearer {self.embaas_api_key}",... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html |
5c4d318f409e-4 | it as a named parameter to the constructor.
Example:
.. code-block:: python
# Default parsing
from langchain.document_loaders.embaas import EmbaasLoader
loader = EmbaasLoader(file_path="example.mp3")
documents = loader.load()
# Custom api parameter... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html |
5c4d318f409e-5 | yield from self.blob_loader.lazy_parse(blob=blob)
[docs] def load(self) -> List[Document]:
return list(self.lazy_load())
[docs] def load_and_split(
self, text_splitter: Optional[TextSplitter] = None
) -> List[Document]:
if self.params.get("should_embed", False):
warnings.wa... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html |
f38123c92a07-0 | Source code for langchain.document_loaders.airtable
from typing import Iterator, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class AirtableLoader(BaseLoader):
"""Loader for Airtable tables."""
def __init__(self, api_token: str, table_id: str... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airtable.html |
1de94920bfbf-0 | Source code for langchain.document_loaders.pdf
"""Loader that loads PDF files."""
import json
import logging
import os
import tempfile
import time
from abc import ABC
from io import StringIO
from pathlib import Path
from typing import Any, Iterator, List, Mapping, Optional
from urllib.parse import urlparse
import reque... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
1de94920bfbf-1 | if not os.path.isfile(self.file_path) and self._is_valid_url(self.file_path):
r = requests.get(self.file_path)
if r.status_code != 200:
raise ValueError(
"Check the url of your file; returned status code %s"
% r.status_code
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
1de94920bfbf-2 | """
def __init__(self, file_path: str) -> None:
"""Initialize with file path."""
try:
import pypdf # noqa:F401
except ImportError:
raise ImportError(
"pypdf package not found, please install it with " "`pip install pypdf`"
)
self.p... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
1de94920bfbf-3 | """
def __init__(
self,
path: str,
glob: str = "**/[!.]*.pdf",
silent_errors: bool = False,
load_hidden: bool = False,
recursive: bool = False,
):
self.path = path
self.glob = glob
self.load_hidden = load_hidden
self.recursive = rec... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
1de94920bfbf-4 | "`pip install pdfminer.six`"
)
super().__init__(file_path)
self.parser = PDFMinerParser()
[docs] def load(self) -> List[Document]:
"""Eagerly load the content."""
return list(self.lazy_load())
[docs] def lazy_load(
self,
) -> Iterator[Document]:
"""L... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
1de94920bfbf-5 | [docs]class PyMuPDFLoader(BasePDFLoader):
"""Loader that uses PyMuPDF to load PDF files."""
def __init__(self, file_path: str) -> None:
"""Initialize with file path."""
try:
import fitz # noqa:F401
except ImportError:
raise ImportError(
"`PyMuPDF`... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
1de94920bfbf-6 | self.should_clean_pdf = should_clean_pdf
@property
def headers(self) -> dict:
return {"app_id": self.mathpix_api_id, "app_key": self.mathpix_api_key}
@property
def url(self) -> str:
return "https://api.mathpix.com/v3/pdf"
@property
def data(self) -> dict:
options = {"conv... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
1de94920bfbf-7 | self.wait_for_processing(pdf_id)
url = f"{self.url}/{pdf_id}.{self.processed_file_format}"
response = requests.get(url, headers=self.headers)
return response.content.decode("utf-8")
[docs] def clean_pdf(self, contents: str) -> str:
contents = "\n".join(
[line for line in c... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
1de94920bfbf-8 | "`pip install pdfplumber`"
)
super().__init__(file_path)
self.text_kwargs = text_kwargs or {}
[docs] def load(self) -> List[Document]:
"""Load file."""
parser = PDFPlumberParser(text_kwargs=self.text_kwargs)
blob = Blob.from_path(self.file_path)
return pars... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
f22a0d7f4b22-0 | Source code for langchain.document_loaders.epub
"""Loader that loads EPub files."""
from typing import List
from langchain.document_loaders.unstructured import (
UnstructuredFileLoader,
satisfies_min_unstructured_version,
)
[docs]class UnstructuredEPubLoader(UnstructuredFileLoader):
"""Loader that uses unst... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/epub.html |
92ecc64fdba1-0 | Source code for langchain.document_loaders.mastodon
"""Mastodon document loader."""
from __future__ import annotations
import os
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Sequence
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
if TYPE... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mastodon.html |
92ecc64fdba1-1 | access_token = access_token or os.environ.get("MASTODON_ACCESS_TOKEN")
self.api = mastodon.Mastodon(
access_token=access_token, api_base_url=api_base_url
)
self.mastodon_accounts = mastodon_accounts
self.number_toots = number_toots
self.exclude_replies = exclude_repli... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mastodon.html |
81c44ed2e5b0-0 | Source code for langchain.document_loaders.college_confidential
"""Loader that loads College Confidential."""
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.web_base import WebBaseLoader
[docs]class CollegeConfidentialLoader(WebBaseLoader):
"""Loader that lo... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/college_confidential.html |
28db0ec19fed-0 | Source code for langchain.document_loaders.whatsapp_chat
import re
from pathlib import Path
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
def concatenate_rows(date: str, sender: str, text: str) -> str:
"""Combine message information i... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/whatsapp_chat.html |
28db0ec19fed-1 | )
if result:
date, sender, text = result.groups()
text_content += concatenate_rows(date, sender, text)
metadata = {"source": str(p)}
return [Document(page_content=text_content, metadata=metadata)] | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/whatsapp_chat.html |
19c5666fb2f6-0 | Source code for langchain.document_loaders.spreedly
"""Loader that fetches data from Spreedly API."""
import json
import urllib.request
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.utils import stringify_dict
SPREEDLY_ENDP... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/spreedly.html |
19c5666fb2f6-1 | text = stringify_dict(json_data)
metadata = {"source": url}
return [Document(page_content=text, metadata=metadata)]
def _get_resource(self) -> List[Document]:
endpoint = SPREEDLY_ENDPOINTS.get(self.resource)
if endpoint is None:
return []
return self._make... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/spreedly.html |
36f947ba3d39-0 | Source code for langchain.document_loaders.youtube
"""Loader that loads YouTube transcript."""
from __future__ import annotations
import logging
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Union
from urllib.parse import parse_qs, urlparse
from pydantic import root_validator
from pyd... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
36f947ba3d39-1 | """Validate that either folder_id or document_ids is set, but not both."""
if not values.get("credentials_path") and not values.get(
"service_account_path"
):
raise ValueError("Must specify either channel_name or video_ids")
return values
def _load_credentials(self) -... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
36f947ba3d39-2 | token.write(creds.to_json())
return creds
ALLOWED_SCHEMAS = {"http", "https"}
ALLOWED_NETLOCK = {
"youtu.be",
"m.youtube.com",
"youtube.com",
"www.youtube.com",
"www.youtube-nocookie.com",
"vid.plus",
}
def _parse_video_id(url: str) -> Optional[str]:
"""Parse a youtube url and return... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
36f947ba3d39-3 | self.add_video_info = add_video_info
self.language = language
if isinstance(language, str):
self.language = [language]
else:
self.language = language
self.translation = translation
self.continue_on_failure = continue_on_failure
[docs] @staticmethod
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
36f947ba3d39-4 | except TranscriptsDisabled:
return []
try:
transcript = transcript_list.find_transcript(self.language)
except NoTranscriptFound:
en_transcript = transcript_list.find_transcript(["en"])
transcript = en_transcript.translate(self.translation)
transcri... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
36f947ba3d39-5 | To use, you should have the ``googleapiclient,youtube_transcript_api``
python package installed.
As the service needs a google_api_client, you first have to initialize
the GoogleApiClient.
Additionally you have to either provide a channel name or a list of videoids
"https://developers.google.com/doc... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
36f947ba3d39-6 | "to use the Google Drive loader"
)
return build("youtube", "v3", credentials=creds)
[docs] @root_validator
def validate_channel_or_videoIds_is_set(
cls, values: Dict[str, Any]
) -> Dict[str, Any]:
"""Validate that either folder_id or document_ids is set, but not both."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
36f947ba3d39-7 | request = self.youtube_client.search().list(
part="id",
q=channel_name,
type="channel",
maxResults=1, # we only need one result since channel names are unique
)
response = request.execute()
channel_id = response["items"][0]["id"]["channelId"]
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
36f947ba3d39-8 | metadata=meta_data,
)
)
except (TranscriptsDisabled, NoTranscriptFound) as e:
if self.continue_on_failure:
logger.error(
"Error fetching transscript "
+ f" {ite... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
891c40061533-0 | Source code for langchain.document_loaders.hugging_face_dataset
"""Loader that loads HuggingFace datasets."""
from typing import Iterator, List, Mapping, Optional, Sequence, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class HuggingFaceDatasetLoader... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/hugging_face_dataset.html |
891c40061533-1 | self.page_content_column = page_content_column
self.name = name
self.data_dir = data_dir
self.data_files = data_files
self.cache_dir = cache_dir
self.keep_in_memory = keep_in_memory
self.save_infos = save_infos
self.use_auth_token = use_auth_token
self.num... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/hugging_face_dataset.html |
91d21b22bcfb-0 | Source code for langchain.document_loaders.chatgpt
"""Load conversations from ChatGPT data export"""
import datetime
import json
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
def concatenate_rows(message: dict, title: str) -> str:
"""... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/chatgpt.html |
91d21b22bcfb-1 | if not (
idx == 0
and messages[key]["message"]["author"]["role"] == "system"
)
]
)
metadata = {"source": str(self.log_file)}
documents.append(Document(page_content=text, metadata=metadata))
re... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/chatgpt.html |
8ddb0e8d3225-0 | Source code for langchain.document_loaders.html_bs
"""Loader that uses bs4 to load HTML files, enriching metadata with page title."""
import logging
from typing import Dict, List, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
logger = logging.getLogger(__n... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/html_bs.html |
8ddb0e8d3225-1 | title = ""
metadata: Dict[str, Union[str, None]] = {
"source": self.file_path,
"title": title,
}
return [Document(page_content=text, metadata=metadata)] | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/html_bs.html |
ee50ed2b6b8a-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 |
ee50ed2b6b8a-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 |
ee50ed2b6b8a-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 |
a79319187544-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 |
630e86db8368-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 |
630e86db8368-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 |
630e86db8368-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 |
630e86db8368-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 |
403043167ebc-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 |
403043167ebc-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 |
403043167ebc-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 |
403043167ebc-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 |
42d5f293a7ae-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 |
42d5f293a7ae-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 |
42d5f293a7ae-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 |
404d517de522-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 |
404d517de522-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 |
404d517de522-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 |
404d517de522-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 |
404d517de522-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 |
28c15b4d6d9a-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 |
28c15b4d6d9a-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 |
cf7b0c5a9aee-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 |
cf7b0c5a9aee-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 |
cf7b0c5a9aee-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 |
cf7b0c5a9aee-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 |
dcb5b9f19eb0-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 |
dcb5b9f19eb0-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 |
b382cfa16473-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 |
50499e181c79-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 |
50499e181c79-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 |
50499e181c79-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 |
50499e181c79-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 |
50499e181c79-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 |
50499e181c79-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 |
50499e181c79-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 |
50499e181c79-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 |
50499e181c79-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 |
50499e181c79-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 |
50499e181c79-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 |
50499e181c79-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 |
a84e06b6b154-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 |
a84e06b6b154-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 |
a84e06b6b154-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 |
c7aeab3668e3-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 |
c7aeab3668e3-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 |
c7aeab3668e3-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 |
96a544e9c5b8-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 |
96a544e9c5b8-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 |
96a544e9c5b8-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 |
96a544e9c5b8-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 |
96a544e9c5b8-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 |
1ab3deffae77-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 |
1ab3deffae77-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 |
1ab3deffae77-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 |
117861fd0743-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 |
117861fd0743-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 |
d367230609e3-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 |
d367230609e3-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 |
d367230609e3-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 |
d367230609e3-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 |
c9e3e15a7952-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 |
c9e3e15a7952-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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.