2023-12-11 21:53:30 +00:00
|
|
|
import json
|
|
|
|
from typing import Any, Dict, List, Optional
|
|
|
|
|
2024-06-04 16:48:25 +00:00
|
|
|
from langchain_core._api import deprecated
|
2023-12-11 21:53:30 +00:00
|
|
|
from langchain_core.embeddings import Embeddings
|
|
|
|
from langchain_core.pydantic_v1 import BaseModel, Extra, root_validator
|
community[patch]: Update root_validators embeddings: llamacpp, jina, dashscope, mosaicml, huggingface_hub, Toolkits: Connery, ChatModels: PAI_EAS, (#22828)
This PR updates root validators for:
* Embeddings: llamacpp, jina, dashscope, mosaicml, huggingface_hub
* Toolkits: Connery
* ChatModels: PAI_EAS
Following this issue:
https://github.com/langchain-ai/langchain/issues/22819
2024-06-12 17:59:05 +00:00
|
|
|
from langchain_core.utils import get_from_dict_or_env
|
2023-12-11 21:53:30 +00:00
|
|
|
|
|
|
|
DEFAULT_MODEL = "sentence-transformers/all-mpnet-base-v2"
|
|
|
|
VALID_TASKS = ("feature-extraction",)
|
|
|
|
|
|
|
|
|
2024-06-04 16:48:25 +00:00
|
|
|
@deprecated(
|
|
|
|
since="0.2.2",
|
|
|
|
removal="0.3.0",
|
2024-06-05 04:13:13 +00:00
|
|
|
alternative_import="langchain_huggingface.HuggingFaceEndpointEmbeddings",
|
2024-06-04 16:48:25 +00:00
|
|
|
)
|
2023-12-11 21:53:30 +00:00
|
|
|
class HuggingFaceHubEmbeddings(BaseModel, Embeddings):
|
|
|
|
"""HuggingFaceHub embedding models.
|
|
|
|
|
|
|
|
To use, you should have the ``huggingface_hub`` python package installed, and the
|
|
|
|
environment variable ``HUGGINGFACEHUB_API_TOKEN`` set with your API token, or pass
|
|
|
|
it as a named parameter to the constructor.
|
|
|
|
|
|
|
|
Example:
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
from langchain_community.embeddings import HuggingFaceHubEmbeddings
|
|
|
|
model = "sentence-transformers/all-mpnet-base-v2"
|
|
|
|
hf = HuggingFaceHubEmbeddings(
|
|
|
|
model=model,
|
|
|
|
task="feature-extraction",
|
|
|
|
huggingfacehub_api_token="my-api-key",
|
|
|
|
)
|
|
|
|
"""
|
|
|
|
|
|
|
|
client: Any #: :meta private:
|
2024-01-12 05:52:55 +00:00
|
|
|
async_client: Any #: :meta private:
|
2023-12-11 21:53:30 +00:00
|
|
|
model: Optional[str] = None
|
|
|
|
"""Model name to use."""
|
|
|
|
repo_id: Optional[str] = None
|
|
|
|
"""Huggingfacehub repository id, for backward compatibility."""
|
|
|
|
task: Optional[str] = "feature-extraction"
|
|
|
|
"""Task to call the model with."""
|
|
|
|
model_kwargs: Optional[dict] = None
|
|
|
|
"""Keyword arguments to pass to the model."""
|
|
|
|
|
|
|
|
huggingfacehub_api_token: Optional[str] = None
|
|
|
|
|
|
|
|
class Config:
|
|
|
|
"""Configuration for this pydantic object."""
|
|
|
|
|
|
|
|
extra = Extra.forbid
|
|
|
|
|
community[patch]: Update root_validators embeddings: llamacpp, jina, dashscope, mosaicml, huggingface_hub, Toolkits: Connery, ChatModels: PAI_EAS, (#22828)
This PR updates root validators for:
* Embeddings: llamacpp, jina, dashscope, mosaicml, huggingface_hub
* Toolkits: Connery
* ChatModels: PAI_EAS
Following this issue:
https://github.com/langchain-ai/langchain/issues/22819
2024-06-12 17:59:05 +00:00
|
|
|
@root_validator(pre=True)
|
2023-12-11 21:53:30 +00:00
|
|
|
def validate_environment(cls, values: Dict) -> Dict:
|
|
|
|
"""Validate that api key and python package exists in environment."""
|
community[patch]: Update root_validators embeddings: llamacpp, jina, dashscope, mosaicml, huggingface_hub, Toolkits: Connery, ChatModels: PAI_EAS, (#22828)
This PR updates root validators for:
* Embeddings: llamacpp, jina, dashscope, mosaicml, huggingface_hub
* Toolkits: Connery
* ChatModels: PAI_EAS
Following this issue:
https://github.com/langchain-ai/langchain/issues/22819
2024-06-12 17:59:05 +00:00
|
|
|
huggingfacehub_api_token = get_from_dict_or_env(
|
|
|
|
values, "huggingfacehub_api_token", "HUGGINGFACEHUB_API_TOKEN"
|
2023-12-11 21:53:30 +00:00
|
|
|
)
|
2023-12-13 01:21:52 +00:00
|
|
|
|
2023-12-11 21:53:30 +00:00
|
|
|
try:
|
2024-01-12 05:52:55 +00:00
|
|
|
from huggingface_hub import AsyncInferenceClient, InferenceClient
|
2023-12-11 21:53:30 +00:00
|
|
|
|
community[patch]: Update root_validators embeddings: llamacpp, jina, dashscope, mosaicml, huggingface_hub, Toolkits: Connery, ChatModels: PAI_EAS, (#22828)
This PR updates root validators for:
* Embeddings: llamacpp, jina, dashscope, mosaicml, huggingface_hub
* Toolkits: Connery
* ChatModels: PAI_EAS
Following this issue:
https://github.com/langchain-ai/langchain/issues/22819
2024-06-12 17:59:05 +00:00
|
|
|
if values.get("model"):
|
2023-12-11 21:53:30 +00:00
|
|
|
values["repo_id"] = values["model"]
|
community[patch]: Update root_validators embeddings: llamacpp, jina, dashscope, mosaicml, huggingface_hub, Toolkits: Connery, ChatModels: PAI_EAS, (#22828)
This PR updates root validators for:
* Embeddings: llamacpp, jina, dashscope, mosaicml, huggingface_hub
* Toolkits: Connery
* ChatModels: PAI_EAS
Following this issue:
https://github.com/langchain-ai/langchain/issues/22819
2024-06-12 17:59:05 +00:00
|
|
|
elif values.get("repo_id"):
|
2023-12-11 21:53:30 +00:00
|
|
|
values["model"] = values["repo_id"]
|
|
|
|
else:
|
|
|
|
values["model"] = DEFAULT_MODEL
|
|
|
|
values["repo_id"] = DEFAULT_MODEL
|
|
|
|
|
|
|
|
client = InferenceClient(
|
|
|
|
model=values["model"],
|
|
|
|
token=huggingfacehub_api_token,
|
|
|
|
)
|
2024-01-12 05:52:55 +00:00
|
|
|
|
|
|
|
async_client = AsyncInferenceClient(
|
|
|
|
model=values["model"],
|
|
|
|
token=huggingfacehub_api_token,
|
|
|
|
)
|
|
|
|
|
2023-12-11 21:53:30 +00:00
|
|
|
values["client"] = client
|
2024-01-12 05:52:55 +00:00
|
|
|
values["async_client"] = async_client
|
|
|
|
|
2023-12-11 21:53:30 +00:00
|
|
|
except ImportError:
|
|
|
|
raise ImportError(
|
|
|
|
"Could not import huggingface_hub python package. "
|
|
|
|
"Please install it with `pip install huggingface_hub`."
|
|
|
|
)
|
|
|
|
return values
|
|
|
|
|
community[patch]: Update root_validators embeddings: llamacpp, jina, dashscope, mosaicml, huggingface_hub, Toolkits: Connery, ChatModels: PAI_EAS, (#22828)
This PR updates root validators for:
* Embeddings: llamacpp, jina, dashscope, mosaicml, huggingface_hub
* Toolkits: Connery
* ChatModels: PAI_EAS
Following this issue:
https://github.com/langchain-ai/langchain/issues/22819
2024-06-12 17:59:05 +00:00
|
|
|
@root_validator(pre=False, skip_on_failure=True)
|
|
|
|
def post_init(cls, values: Dict) -> Dict:
|
|
|
|
"""Post init validation for the class."""
|
|
|
|
if values["task"] not in VALID_TASKS:
|
|
|
|
raise ValueError(
|
|
|
|
f"Got invalid task {values['task']}, "
|
|
|
|
f"currently only {VALID_TASKS} are supported"
|
|
|
|
)
|
|
|
|
return values
|
|
|
|
|
2023-12-11 21:53:30 +00:00
|
|
|
def embed_documents(self, texts: List[str]) -> List[List[float]]:
|
|
|
|
"""Call out to HuggingFaceHub's embedding endpoint for embedding search docs.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
texts: The list of texts to embed.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
List of embeddings, one for each text.
|
|
|
|
"""
|
|
|
|
# replace newlines, which can negatively affect performance.
|
|
|
|
texts = [text.replace("\n", " ") for text in texts]
|
|
|
|
_model_kwargs = self.model_kwargs or {}
|
|
|
|
responses = self.client.post(
|
2023-12-13 01:21:52 +00:00
|
|
|
json={"inputs": texts, "parameters": _model_kwargs}, task=self.task
|
2023-12-11 21:53:30 +00:00
|
|
|
)
|
|
|
|
return json.loads(responses.decode())
|
|
|
|
|
2024-01-12 05:52:55 +00:00
|
|
|
async def aembed_documents(self, texts: List[str]) -> List[List[float]]:
|
|
|
|
"""Async Call to HuggingFaceHub's embedding endpoint for embedding search docs.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
texts: The list of texts to embed.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
List of embeddings, one for each text.
|
|
|
|
"""
|
|
|
|
# replace newlines, which can negatively affect performance.
|
|
|
|
texts = [text.replace("\n", " ") for text in texts]
|
|
|
|
_model_kwargs = self.model_kwargs or {}
|
|
|
|
responses = await self.async_client.post(
|
|
|
|
json={"inputs": texts, "parameters": _model_kwargs}, task=self.task
|
|
|
|
)
|
|
|
|
return json.loads(responses.decode())
|
|
|
|
|
2023-12-11 21:53:30 +00:00
|
|
|
def embed_query(self, text: str) -> List[float]:
|
|
|
|
"""Call out to HuggingFaceHub's embedding endpoint for embedding query text.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
text: The text to embed.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
Embeddings for the text.
|
|
|
|
"""
|
|
|
|
response = self.embed_documents([text])[0]
|
|
|
|
return response
|
2024-01-12 05:52:55 +00:00
|
|
|
|
|
|
|
async def aembed_query(self, text: str) -> List[float]:
|
|
|
|
"""Async Call to HuggingFaceHub's embedding endpoint for embedding query text.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
text: The text to embed.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
Embeddings for the text.
|
|
|
|
"""
|
2024-01-15 18:34:10 +00:00
|
|
|
response = (await self.aembed_documents([text]))[0]
|
2024-01-12 05:52:55 +00:00
|
|
|
return response
|