Repository: langchain
Issue: I Can't use HuggingFaceEmbeddings and HuggingFaceBgeEmbeddings
Labels: stale

### Checked other resources

- [X] I added a very descriptive title to this issue.
- [X] I searched the LangChain documentation with the integrated search.
- [X] I used the GitHub search to find a similar question and didn't find it.
- [X] I am sure that this is a bug in LangChain rather than my code.
- [X] The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package).

### Example Code

```
from langchain_huggingface import HuggingFaceEmbeddings
embeddings=HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
```

### Error Message and Stack Trace (if applicable)

```
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
File /opt/conda/lib/python3.10/site-packages/transformers/utils/import_utils.py:1764, in _LazyModule._get_module(self, module_name)
   1763 try:
-> 1764     return importlib.import_module("." + module_name, self.__name__)
   1765 except Exception as e:

File /opt/conda/lib/python3.10/importlib/__init__.py:126, in import_module(name, package)
    125         level += 1
--> 126 return _bootstrap._gcd_import(name[level:], package, level)

File <frozen importlib._bootstrap>:1050, in _gcd_import(name, package, level)

File <frozen importlib._bootstrap>:1027, in _find_and_load(name, import_)

File <frozen importlib._bootstrap>:1006, in _find_and_load_unlocked(name, import_)

File <frozen importlib._bootstrap>:688, in _load_unlocked(spec)

File <frozen importlib._bootstrap_external>:883, in exec_module(self, module)

File <frozen importlib._bootstrap>:241, in _call_with_frames_removed(f, *args, **kwds)

File /opt/conda/lib/python3.10/site-packages/transformers/generation/utils.py:112
    111 if is_accelerate_available():
--> 112     from accelerate.hooks import AlignDevicesHook, add_hook_to_module
    115 @dataclass
    116 class GenerateDecoderOnlyOutput(ModelOutput):

File /opt/conda/lib/python3.10/site-packages/accelerate/__init__.py:16
     14 __version__ = "0.34.2"
---> 16 from .accelerator import Accelerator
     17 from .big_modeling import (
     18     cpu_offload,
     19     cpu_offload_with_hook,
   (...)
     24     load_checkpoint_and_dispatch,
     25 )

File /opt/conda/lib/python3.10/site-packages/accelerate/accelerator.py:36
     34 from huggingface_hub import split_torch_state_dict_into_shards
---> 36 from .checkpointing import load_accelerator_state, load_custom_state, save_accelerator_state, save_custom_state
     37 from .data_loader import DataLoaderDispatcher, prepare_data_loader, skip_first_batches

File /opt/conda/lib/python3.10/site-packages/accelerate/checkpointing.py:24
     22 from torch.cuda.amp import GradScaler
---> 24 from .utils import (
     25     MODEL_NAME,
     26     OPTIMIZER_NAME,
     27     RNG_STATE_NAME,
     28     SAFE_MODEL_NAME,
     29     SAFE_WEIGHTS_NAME,
     30     SAMPLER_NAME,
     31     SCALER_NAME,
     32     SCHEDULER_NAME,
     33     WEIGHTS_NAME,
     34     get_pretty_name,
     35     is_mlu_available,
     36     is_torch_xla_available,
     37     is_xpu_available,
     38     save,
     39 )
     42 if is_torch_xla_available():

File /opt/conda/lib/python3.10/site-packages/accelerate/utils/__init__.py:193
    184     from .deepspeed import (
    185         DeepSpeedEngineWrapper,
    186         DeepSpeedOptimizerWrapper,
   (...)
    190         HfDeepSpeedConfig,
    191     )
--> 193 from .bnb import has_4bit_bnb_layers, load_and_quantize_model
    194 from .fsdp_utils import (
    195     disable_fsdp_ram_efficient_loading,
    196     enable_fsdp_ram_efficient_loading,
   (...)
    201     save_fsdp_optimizer,
    202 )

File /opt/conda/lib/python3.10/site-packages/accelerate/utils/bnb.py:29
     24 from accelerate.utils.imports import (
     25     is_4bit_bnb_available,
     26     is_8bit_bnb_available,
     27 )
---> 29 from ..big_modeling import dispatch_model, init_empty_weights
     30 from .dataclasses import BnbQuantizationConfig

File /opt/conda/lib/python3.10/site-packages/accelerate/big_modeling.py:24
     22 import torch.nn as nn
---> 24 from .hooks import (
     25     AlignDevicesHook,
     26     CpuOffload,
     27     UserCpuOffloadHook,
     28     add_hook_to_module,
     29     attach_align_device_hook,
     30     attach_align_device_hook_on_blocks,
     31 )
     32 from .utils import (
     33     OffloadedWeightsLoader,
     34     check_cuda_p2p_ib_support,
   (...)
     48     retie_parameters,
     49 )

File /opt/conda/lib/python3.10/site-packages/accelerate/hooks.py:31
     30 from .utils.modeling import get_non_persistent_buffers
---> 31 from .utils.other import recursive_getattr
     34 _accelerate_added_attributes = ["to", "cuda", "npu", "xpu", "mlu", "musa"]

File /opt/conda/lib/python3.10/site-packages/accelerate/utils/other.py:29
     27 from safetensors.torch import save_file as safe_save_file
---> 29 from ..commands.config.default import write_basic_config  # noqa: F401
     30 from ..logging import get_logger

File /opt/conda/lib/python3.10/site-packages/accelerate/commands/config/__init__.py:19
     17 import argparse
---> 19 from .config import config_command_parser
     20 from .config_args import default_config_file, load_config_from_file  # noqa: F401

File /opt/conda/lib/python3.10/site-packages/accelerate/commands/config/config.py:25
     24 from .config_utils import _ask_field, _ask_options, _convert_compute_environment  # noqa: F401
---> 25 from .sagemaker import get_sagemaker_input
     28 description = "Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine"

File /opt/conda/lib/python3.10/site-packages/accelerate/commands/config/sagemaker.py:35
     34 if is_boto3_available():
---> 35     import boto3  # noqa: F401
     38 def _create_iam_role_for_sagemaker(role_name):

File /opt/conda/lib/python3.10/site-packages/boto3/__init__.py:17
     16 from boto3.compat import _warn_deprecated_python
---> 17 from boto3.session import Session
     19 __author__ = 'Amazon Web Services'

File /opt/conda/lib/python3.10/site-packages/boto3/session.py:17
     15 import os
---> 17 import botocore.session
     18 from botocore.client import Config

File /opt/conda/lib/python3.10/site-packages/botocore/session.py:26
     24 import warnings
---> 26 import botocore.client
     27 import botocore.configloader

File /opt/conda/lib/python3.10/site-packages/botocore/client.py:15
     13 import logging
---> 15 from botocore import waiter, xform_name
     16 from botocore.args import ClientArgsCreator

File /opt/conda/lib/python3.10/site-packages/botocore/waiter.py:18
     16 import jmespath
---> 18 from botocore.docs.docstring import WaiterDocstring
     19 from botocore.utils import get_service_module_name

File /opt/conda/lib/python3.10/site-packages/botocore/docs/__init__.py:15
     13 import os
---> 15 from botocore.docs.service import ServiceDocumenter
     17 DEPRECATED_SERVICE_NAMES = {'sms-voice'}

File /opt/conda/lib/python3.10/site-packages/botocore/docs/service.py:14
     13 from botocore.docs.bcdoc.restdoc import DocumentStructure
---> 14 from botocore.docs.client import (
     15     ClientContextParamsDocumenter,
     16     ClientDocumenter,
     17     ClientExceptionsDocumenter,
     18 )
     19 from botocore.docs.paginator import PaginatorDocumenter

File /opt/conda/lib/python3.10/site-packages/botocore/docs/client.py:18
     17 from botocore.docs.bcdoc.restdoc import DocumentStructure
---> 18 from botocore.docs.example import ResponseExampleDocumenter
     19 from botocore.docs.method import (
     20     document_custom_method,
     21     document_model_driven_method,
     22     get_instance_public_methods,
     23 )

File /opt/conda/lib/python3.10/site-packages/botocore/docs/example.py:13
      1 # Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
      2 #
      3 # Licensed under the Apache License, Version 2.0 (the "License"). You
   (...)
     11 # ANY KIND, either express or implied. See the License for the specific
     12 # language governing permissions and limitations under the License.
---> 13 from botocore.docs.shape import ShapeDocumenter
     14 from botocore.docs.utils import py_default

File /opt/conda/lib/python3.10/site-packages/botocore/docs/shape.py:19
      1 # Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
      2 #
      3 # Licensed under the Apache License, Version 2.0 (the "License"). You
   (...)
     17 # inherited from a Documenter class with the appropriate methods
     18 # and attributes.
---> 19 from botocore.utils import is_json_value_header
     22 class ShapeDocumenter:

File /opt/conda/lib/python3.10/site-packages/botocore/utils.py:39
     38 import botocore.awsrequest
---> 39 import botocore.httpsession
     41 # IP Regexes retained for backwards compatibility

File /opt/conda/lib/python3.10/site-packages/botocore/httpsession.py:45
     44         # Always import the original SSLContext, even if it has been patched
---> 45         from urllib3.contrib.pyopenssl import (
     46             orig_util_SSLContext as SSLContext,
     47         )
     48 except ImportError:

File /opt/conda/lib/python3.10/site-packages/urllib3/contrib/pyopenssl.py:43
     41 from __future__ import annotations
---> 43 import OpenSSL.SSL  # type: ignore[import-untyped]
     44 from cryptography import x509

File /opt/conda/lib/python3.10/site-packages/OpenSSL/__init__.py:8
      4 """
      5 pyOpenSSL - A simple wrapper around the OpenSSL library
      6 """
----> 8 from OpenSSL import SSL, crypto
      9 from OpenSSL.version import (
     10     __author__,
     11     __copyright__,
   (...)
     17     __version__,
     18 )

File /opt/conda/lib/python3.10/site-packages/OpenSSL/SSL.py:35
     32 from OpenSSL._util import (
     33     text_to_bytes_and_warn as _text_to_bytes_and_warn,
     34 )
---> 35 from OpenSSL.crypto import (
     36     FILETYPE_PEM,
     37     X509,
     38     PKey,
     39     X509Name,
     40     X509Store,
     41     _EllipticCurve,
     42     _PassphraseHelper,
     43 )
     45 __all__ = [
     46     "OPENSSL_VERSION_NUMBER",
     47     "SSLEAY_VERSION",
   (...)
    143     "X509VerificationCodes",
    144 ]

File /opt/conda/lib/python3.10/site-packages/OpenSSL/crypto.py:22
      8 from typing import (
      9     Any,
     10     Callable,
   (...)
     19     Union,
     20 )
---> 22 from cryptography import utils, x509
     23 from cryptography.hazmat.primitives.asymmetric import (
     24     dsa,
     25     ec,
   (...)
     28     rsa,
     29 )

File /opt/conda/lib/python3.10/site-packages/cryptography/x509/__init__.py:7
      5 from __future__ import annotations
----> 7 from cryptography.x509 import certificate_transparency, verification
      8 from cryptography.x509.base import (
      9     Attribute,
     10     AttributeNotFound,
   (...)
     29     random_serial_number,
     30 )

File /opt/conda/lib/python3.10/site-packages/cryptography/x509/verification.py:24
     23 Subject = typing.Union[DNSName, IPAddress]
---> 24 VerifiedClient = rust_x509.VerifiedClient
     25 ClientVerifier = rust_x509.ClientVerifier

AttributeError: module 'x509' has no attribute 'VerifiedClient'

The above exception was the direct cause of the following exception:

RuntimeError                              Traceback (most recent call last)
File /opt/conda/lib/python3.10/site-packages/transformers/utils/import_utils.py:1764, in _LazyModule._get_module(self, module_name)
   1763 try:
-> 1764     return importlib.import_module("." + module_name, self.__name__)
   1765 except Exception as e:

File /opt/conda/lib/python3.10/importlib/__init__.py:126, in import_module(name, package)
    125         level += 1
--> 126 return _bootstrap._gcd_import(name[level:], package, level)

File <frozen importlib._bootstrap>:1050, in _gcd_import(name, package, level)

File <frozen importlib._bootstrap>:1027, in _find_and_load(name, import_)

File <frozen importlib._bootstrap>:1006, in _find_and_load_unlocked(name, import_)

File <frozen importlib._bootstrap>:688, in _load_unlocked(spec)

File <frozen importlib._bootstrap_external>:883, in exec_module(self, module)

File <frozen importlib._bootstrap>:241, in _call_with_frames_removed(f, *args, **kwds)

File /opt/conda/lib/python3.10/site-packages/transformers/models/auto/modeling_auto.py:21
     20 from ...utils import logging
---> 21 from .auto_factory import (
     22     _BaseAutoBackboneClass,
     23     _BaseAutoModelClass,
     24     _LazyAutoMapping,
     25     auto_class_update,
     26 )
     27 from .configuration_auto import CONFIG_MAPPING_NAMES

File /opt/conda/lib/python3.10/site-packages/transformers/models/auto/auto_factory.py:40
     39 if is_torch_available():
---> 40     from ...generation import GenerationMixin
     43 logger = logging.get_logger(__name__)

File <frozen importlib._bootstrap>:1075, in _handle_fromlist(module, fromlist, import_, recursive)

File /opt/conda/lib/python3.10/site-packages/transformers/utils/import_utils.py:1754, in _LazyModule.__getattr__(self, name)
   1753 elif name in self._class_to_module.keys():
-> 1754     module = self._get_module(self._class_to_module[name])
   1755     value = getattr(module, name)

File /opt/conda/lib/python3.10/site-packages/transformers/utils/import_utils.py:1766, in _LazyModule._get_module(self, module_name)
   1765 except Exception as e:
-> 1766     raise RuntimeError(
   1767         f"Failed to import {self.__name__}.{module_name} because of the following error (look up to see its"
   1768         f" traceback):\n{e}"
   1769     ) from e

RuntimeError: Failed to import transformers.generation.utils because of the following error (look up to see its traceback):
module 'x509' has no attribute 'VerifiedClient'

The above exception was the direct cause of the following exception:

RuntimeError                              Traceback (most recent call last)
Cell In[22], line 3
      1 from langchain_huggingface import HuggingFaceEmbeddings
----> 3 embeddings=HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")

File /opt/conda/lib/python3.10/site-packages/langchain_huggingface/embeddings/huggingface.py:53, in HuggingFaceEmbeddings.__init__(self, **kwargs)
     51 super().__init__(**kwargs)
     52 try:
---> 53     import sentence_transformers  # type: ignore[import]
     54 except ImportError as exc:
     55     raise ImportError(
     56         "Could not import sentence_transformers python package. "
     57         "Please install it with `pip install sentence-transformers`."
     58     ) from exc

File /opt/conda/lib/python3.10/site-packages/sentence_transformers/__init__.py:10
      7 import os
      9 from sentence_transformers.backend import export_dynamic_quantized_onnx_model, export_optimized_onnx_model
---> 10 from sentence_transformers.cross_encoder.CrossEncoder import CrossEncoder
     11 from sentence_transformers.datasets import ParallelSentencesDataset, SentencesDataset
     12 from sentence_transformers.LoggingHandler import LoggingHandler

File /opt/conda/lib/python3.10/site-packages/sentence_transformers/cross_encoder/__init__.py:3
      1 from __future__ import annotations
----> 3 from .CrossEncoder import CrossEncoder
      5 __all__ = ["CrossEncoder"]

File /opt/conda/lib/python3.10/site-packages/sentence_transformers/cross_encoder/CrossEncoder.py:14
     12 from torch.utils.data import DataLoader
     13 from tqdm.autonotebook import tqdm, trange
---> 14 from transformers import AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, is_torch_npu_available
     15 from transformers.tokenization_utils_base import BatchEncoding
     16 from transformers.utils import PushToHubMixin

File <frozen importlib._bootstrap>:1075, in _handle_fromlist(module, fromlist, import_, recursive)

File /opt/conda/lib/python3.10/site-packages/transformers/utils/import_utils.py:1755, in _LazyModule.__getattr__(self, name)
   1753 elif name in self._class_to_module.keys():
   1754     module = self._get_module(self._class_to_module[name])
-> 1755     value = getattr(module, name)
   1756 else:
   1757     raise AttributeError(f"module {self.__name__} has no attribute {name}")

File /opt/conda/lib/python3.10/site-packages/transformers/utils/import_utils.py:1754, in _LazyModule.__getattr__(self, name)
   1752     value = Placeholder
   1753 elif name in self._class_to_module.keys():
-> 1754     module = self._get_module(self._class_to_module[name])
   1755     value = getattr(module, name)
   1756 else:

File /opt/conda/lib/python3.10/site-packages/transformers/utils/import_utils.py:1766, in _LazyModule._get_module(self, module_name)
   1764     return importlib.import_module("." + module_name, self.__name__)
   1765 except Exception as e:
-> 1766     raise RuntimeError(
   1767         f"Failed to import {self.__name__}.{module_name} because of the following error (look up to see its"
   1768         f" traceback):\n{e}"
   1769     ) from e

RuntimeError: Failed to import transformers.models.auto.modeling_auto because of the following error (look up to see its traceback):
Failed to import transformers.generation.utils because of the following error (look up to see its traceback):
module 'x509' has no attribute 'VerifiedClient'
```

### Description

I was trying to use HuggingFaceEmbeddings and HuggingFaceBgeEmbeddings but I am getting the error mentioned above

### System Info

```

System Information
------------------
> OS:  Linux
> OS Version:  #1 SMP Thu Jun 27 20:43:36 UTC 2024
> Python Version:  3.10.14 | packaged by conda-forge | (main, Mar 20 2024, 12:45:18) [GCC 12.3.0]

Package Information
-------------------
> langchain_core: 0.3.13
> langchain: 0.3.4
> langchain_community: 0.3.3
> langsmith: 0.1.137
> langchain_chroma: 0.1.4
> langchain_groq: 0.2.0
> langchain_huggingface: 0.1.0
> langchain_openai: 0.2.3
> langchain_text_splitters: 0.3.0

Optional packages not installed
-------------------------------
> langgraph
> langserve

Other Dependencies
------------------
> aiohttp: 3.9.5
> async-timeout: 4.0.3
> chromadb: 0.5.15
> dataclasses-json: 0.6.7
> fastapi: 0.111.0
> groq: 0.11.0
> httpx: 0.27.0
> huggingface-hub: 0.25.1
> jsonpatch: 1.33
> numpy: 1.26.4
> openai: 1.52.2
> orjson: 3.10.4
> packaging: 24.1
> pydantic: 2.9.2
> pydantic-settings: 2.6.0
> PyYAML: 6.0.2
> requests: 2.32.3
> requests-toolbelt: 1.0.0
> sentence-transformers: 3.2.1
> SQLAlchemy: 2.0.30
> tenacity: 8.3.0
> tiktoken: 0.8.0
> tokenizers: 0.20.0
> transformers: 4.45.1
> typing-extensions: 4.12.2
```