id stringlengths 14 15 | text stringlengths 44 2.47k | source stringlengths 61 181 |
|---|---|---|
8d556cc233b6-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html |
8d556cc233b6-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html |
8d556cc233b6-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]
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html |
8c8f8b9ee7cb-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/llm_rails.html |
8c8f8b9ee7cb-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/llm_rails.html |
3de7ba379247-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:... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/awa.html |
3de7ba379247-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/awa.html |
56840da0e0dc-0 | Source code for langchain.embeddings.gpt4all
from typing import Any, Dict, List
from langchain.pydantic_v1 import BaseModel, root_validator
from langchain.schema.embeddings import Embeddings
[docs]class GPT4AllEmbeddings(BaseModel, Embeddings):
"""GPT4All embedding models.
To use, you should have the gpt4all py... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/gpt4all.html |
56840da0e0dc-1 | Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
return self.embed_documents([text])[0] | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/gpt4all.html |
7fcc778d99d5-0 | Source code for langchain.embeddings.self_hosted
from typing import Any, Callable, List
from langchain.llms 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]]:
"""Inf... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html |
7fcc778d99d5-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 |
7fcc778d99d5-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 |
b1c079e03cf5-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,... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/javelin_ai_gateway.html |
b1c079e03cf5-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=... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/javelin_ai_gateway.html |
b1c079e03cf5-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/javelin_ai_gateway.html |
3f8831301fb2-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html |
3f8831301fb2-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"
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html |
3f8831301fb2-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html |
3f8831301fb2-3 | """Compute query embeddings using a Bedrock model.
Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
return self._embedding_func(text)
[docs] async def aembed_query(self, text: str) -> List[float]:
"""Asynchronous compute query embedd... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html |
77b2e5f1e012-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/clarifai.html |
77b2e5f1e012-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/clarifai.html |
77b2e5f1e012-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(
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/clarifai.html |
77b2e5f1e012-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.
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/clarifai.html |
77b2e5f1e012-4 | for o in post_model_outputs_response.outputs
]
return embeddings[0] | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/clarifai.html |
fde85cd4af8d-0 | Source code for langchain.embeddings.modelscope_hub
from typing import Any, List, Optional
from langchain.pydantic_v1 import BaseModel, Extra
from langchain.schema.embeddings import Embeddings
[docs]class ModelScopeEmbeddings(BaseModel, Embeddings):
"""ModelScopeHub embedding models.
To use, you should have the... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/modelscope_hub.html |
fde85cd4af8d-1 | 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))
inputs = {"source_sentence": texts}
embeddings = self.embed(input=inputs)["text_embedding"]
return... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/modelscope_hub.html |
57588d21068d-0 | Source code for langchain.embeddings.openai
from __future__ import annotations
import logging
import warnings
from typing import (
Any,
Callable,
Dict,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Union,
)
import numpy as np
from tenacity import (
AsyncRetrying,
before_... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
57588d21068d-1 | )
def _async_retry_decorator(embeddings: OpenAIEmbeddings) -> Any:
import openai
min_seconds = 4
max_seconds = 10
# Wait 2^x * 1 second between each retry starting with
# 4 seconds, then up to 10 seconds, then 10 seconds afterwards
async_retrying = AsyncRetrying(
reraise=True,
st... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
57588d21068d-2 | return response
[docs]def embed_with_retry(embeddings: OpenAIEmbeddings, **kwargs: Any) -> Any:
"""Use tenacity to retry the embedding call."""
retry_decorator = _create_retry_decorator(embeddings)
@retry_decorator
def _embed_with_retry(**kwargs: Any) -> Any:
response = embeddings.client.create(... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
57588d21068d-3 | the properties of your endpoint.
In addition, the deployment name must be passed as the model parameter.
Example:
.. code-block:: python
import os
os.environ["OPENAI_API_TYPE"] = "azure"
os.environ["OPENAI_API_BASE"] = "https://<your-endpoint.openai.azure.com/"
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
57588d21068d-4 | openai_api_key: Optional[str] = None
openai_organization: Optional[str] = None
allowed_special: Union[Literal["all"], Set[str]] = set()
disallowed_special: Union[Literal["all"], Set[str], Sequence[str]] = "all"
chunk_size: int = 1000
"""Maximum number of texts to embed in each batch"""
max_retri... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
57588d21068d-5 | """Whether to skip empty strings when embedding or raise an error.
Defaults to not skipping."""
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator(pre=True)
def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Build extr... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
57588d21068d-6 | values,
"openai_api_base",
"OPENAI_API_BASE",
default="",
)
values["openai_api_type"] = get_from_dict_or_env(
values,
"openai_api_type",
"OPENAI_API_TYPE",
default="",
)
values["openai_proxy"] = get_from_... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
57588d21068d-7 | )
return values
@property
def _invocation_params(self) -> Dict:
openai_args = {
"model": self.model,
"request_timeout": self.request_timeout,
"headers": self.headers,
"api_key": self.openai_api_key,
"organization": self.openai_organizat... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
57588d21068d-8 | "This is needed in order to for OpenAIEmbeddings. "
"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)
exce... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
57588d21068d-9 | **self._invocation_params,
)
batched_embeddings.extend(r["embedding"] for r in response["data"])
results: List[List[List[float]]] = [[] for _ in range(len(texts))]
num_tokens_in_batch: List[List[int]] = [[] for _ in range(len(texts))]
for i in range(len(indices)):
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
57588d21068d-10 | )
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. Using cl100k_base encoding.")
model = "cl100k_base... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
57588d21068d-11 | 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(
self,
input="",
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
57588d21068d-12 | specified by the class.
Returns:
List of embeddings, one for each text.
"""
# NOTE: to keep things simple, we assume the list may contain texts longer
# than the maximum context and use length-safe embedding function.
return await self._aget_len_safe_embeddings(... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
924e71099350-0 | Source code for langchain.embeddings.xinference
"""Wrapper around Xinference embedding models."""
from typing import Any, List, Optional
from langchain.schema.embeddings import Embeddings
[docs]class XinferenceEmbeddings(Embeddings):
"""Wrapper around xinference embedding models.
To use, you should have the xin... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/xinference.html |
924e71099350-1 | server_url: Optional[str]
"""URL of the xinference server"""
model_uid: Optional[str]
"""UID of the launched model"""
[docs] def __init__(
self, server_url: Optional[str] = None, model_uid: Optional[str] = None
):
try:
from xinference.client import RESTfulClient
ex... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/xinference.html |
924e71099350-2 | embedding_res = model.create_embedding(text)
embedding = embedding_res["data"][0]["embedding"]
return list(map(float, embedding)) | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/xinference.html |
7d5e184a8991-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/ernie.html |
7d5e184a8991-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/ernie.html |
7d5e184a8991-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,... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/ernie.html |
7d5e184a8991-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) | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/ernie.html |
0fc8f3fbed7e-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
0fc8f3fbed7e-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
0fc8f3fbed7e-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
0fc8f3fbed7e-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:
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
0fc8f3fbed7e-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
0fc8f3fbed7e-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
9401fa8f5e7d-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.
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/ollama.html |
9401fa8f5e7d-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]
"""Controls the balance between coherence and diversity
of the output. A lower value will result in ... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/ollama.html |
9401fa8f5e7d-2 | stop: Optional[List[str]]
"""Sets the stop tokens to use."""
tfs_z: Optional[float]
"""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 more, while a value of 1.0 disables this setting. (default: 1)"""
top_... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/ollama.html |
9401fa8f5e7d-3 | "top_k": self.top_k,
"top_p": self.top_p,
},
}
model_kwargs: Optional[dict] = None
"""Other model keyword args"""
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
return {**{"model": self.model}, **sel... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/ollama.html |
9401fa8f5e7d-4 | embeddings_list: List[List[float]] = []
for prompt in input:
embeddings = self._process_emb_response(prompt)
embeddings_list.append(embeddings)
return embeddings_list
[docs] def embed_documents(self, texts: List[str]) -> List[List[float]]:
"""Embed documents using a Ol... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/ollama.html |
47c01186b6ef-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/nlpcloud.html |
47c01186b6ef-1 | )
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 embeddings, one for each text.
"""
return self.clien... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/nlpcloud.html |
2d99115b5375-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html |
2d99115b5375-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 |
2d99115b5375-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 |
2d99115b5375-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 |
2d99115b5375-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 |
4e157f489f47-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mlflow_gateway.html |
4e157f489f47-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. "
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mlflow_gateway.html |
df2551d86668-0 | Source code for langchain.embeddings.octoai_embeddings
from typing import Any, Dict, List, Mapping, Optional
from langchain.pydantic_v1 import BaseModel, Extra, Field, root_validator
from langchain.schema.embeddings import Embeddings
from langchain.utils import get_from_dict_or_env
DEFAULT_EMBED_INSTRUCTION = "Represen... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/octoai_embeddings.html |
df2551d86668-1 | )
values["endpoint_url"] = get_from_dict_or_env(
values, "endpoint_url", "ENDPOINT_URL"
)
return values
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Return the identifying parameters."""
return {
"endpoint_url": self.endpoint_ur... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/octoai_embeddings.html |
df2551d86668-2 | text = text.replace("\n", " ")
return self._compute_embeddings([text], self.query_instruction)[0] | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/octoai_embeddings.html |
21a57c2d30ae-0 | Source code for langchain.embeddings.jina
import os
from typing import Any, Dict, List, Optional
import requests
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 JinaEmbeddings(BaseModel, Embedding... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/jina.html |
21a57c2d30ae-1 | headers={"Authorization": jina_auth_token},
)
if resp.status_code == 401:
raise ValueError(
"The given Jina auth token is invalid. "
"Please check your Jina auth token."
)
elif resp.status_code == 404:
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/jina.html |
21a57c2d30ae-2 | Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
from docarray import Document, DocumentArray
embedding = self._post(docs=DocumentArray([Document(text=text)])).embeddings[0]
return list(map(float, embedding)) | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/jina.html |
ea89d1fd7727-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
ea89d1fd7727-1 | )
"""
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 is deployed, eg. `us-west-2`."""
credentials_profile_name:... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
ea89d1fd7727-2 | """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/api/latest/index.html>
"""
class Config:
"""Conf... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
ea89d1fd7727-3 | 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_type = self.content_handler.content_type
accepts = self.content... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
ea89d1fd7727-4 | 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 |
6f509ac7a4eb-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/fake.html |
1a5ab41f7b4f-0 | Source code for langchain.embeddings.dashscope
from __future__ import annotations
import logging
from typing import (
Any,
Callable,
Dict,
List,
Optional,
)
from requests.exceptions import HTTPError
from tenacity import (
before_sleep_log,
retry,
retry_if_exception_type,
stop_after_a... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html |
1a5ab41f7b4f-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 |
1a5ab41f7b4f-2 | """Maximum number of retries to make when generating."""
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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html |
1a5ab41f7b4f-3 | Returns:
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 |
310312f235c4-0 | Source code for langchain.embeddings.minimax
from __future__ import annotations
import logging
from typing import Any, Callable, Dict, List, Optional
import requests
from tenacity import (
before_sleep_log,
retry,
stop_after_attempt,
wait_exponential,
)
from langchain.pydantic_v1 import BaseModel, Extra... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html |
310312f235c4-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 |
310312f235c4-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 |
9823ed4ac0ec-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/embaas.html |
9823ed4ac0ec-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 |
9823ed4ac0ec-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 |
984471ee482c-0 | Source code for langchain.embeddings.google_palm
from __future__ import annotations
import logging
from typing import Any, Callable, Dict, List, Optional
from tenacity import (
before_sleep_log,
retry,
retry_if_exception_type,
stop_after_attempt,
wait_exponential,
)
from langchain.pydantic_v1 import... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/google_palm.html |
984471ee482c-1 | return embeddings.client.generate_embeddings(*args, **kwargs)
return _embed_with_retry(*args, **kwargs)
[docs]class GooglePalmEmbeddings(BaseModel, Embeddings):
"""Google's PaLM Embeddings APIs."""
client: Any
google_api_key: Optional[str]
model_name: str = "models/embedding-gecko-001"
"""Model ... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/google_palm.html |
485c173bf93b-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/edenai.html |
485c173bf93b-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()... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/edenai.html |
485c173bf93b-2 | Returns:
List of embeddings, one for each text.
"""
return self._generate_embeddings(texts)
[docs] def embed_query(self, text: str) -> List[float]:
"""Embed a query using EdenAI.
Args:
text: The text to embed.
Returns:
Embeddings for the tex... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/edenai.html |
2abfe1193918-0 | Source code for langchain.embeddings.vertexai
from typing import Dict, List
from langchain.llms.vertexai import _VertexAICommon
from langchain.pydantic_v1 import root_validator
from langchain.schema.embeddings import Embeddings
from langchain.utilities.vertexai import raise_vertex_import_error
[docs]class VertexAIEmbed... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/vertexai.html |
2abfe1193918-1 | """Embed a text.
Args:
text: The text to embed.
Returns:
Embedding for the text.
"""
embeddings = self.client.get_embeddings([text])
return embeddings[0].values | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/vertexai.html |
018dcd7f564d-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/baidu_qianfan_endpoint.html |
018dcd7f564d-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/baidu_qianfan_endpoint.html |
018dcd7f564d-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:
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/baidu_qianfan_endpoint.html |
bbf1d75fc706-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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html |
bbf1d75fc706-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/localai.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.