huggingface.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import importlib
  2. import logging
  3. import os
  4. from typing import Optional
  5. from langchain_community.llms.huggingface_endpoint import HuggingFaceEndpoint
  6. from langchain_community.llms.huggingface_hub import HuggingFaceHub
  7. from langchain_community.llms.huggingface_pipeline import HuggingFacePipeline
  8. from embedchain.config import BaseLlmConfig
  9. from embedchain.helpers.json_serializable import register_deserializable
  10. from embedchain.llm.base import BaseLlm
  11. logger = logging.getLogger(__name__)
  12. @register_deserializable
  13. class HuggingFaceLlm(BaseLlm):
  14. def __init__(self, config: Optional[BaseLlmConfig] = None):
  15. try:
  16. importlib.import_module("huggingface_hub")
  17. except ModuleNotFoundError:
  18. raise ModuleNotFoundError(
  19. "The required dependencies for HuggingFaceHub are not installed."
  20. 'Please install with `pip install --upgrade "embedchain[huggingface-hub]"`'
  21. ) from None
  22. super().__init__(config=config)
  23. if not self.config.api_key and "HUGGINGFACE_ACCESS_TOKEN" not in os.environ:
  24. raise ValueError("Please set the HUGGINGFACE_ACCESS_TOKEN environment variable or pass it in the config.")
  25. def get_llm_model_answer(self, prompt):
  26. if self.config.system_prompt:
  27. raise ValueError("HuggingFaceLlm does not support `system_prompt`")
  28. return HuggingFaceLlm._get_answer(prompt=prompt, config=self.config)
  29. @staticmethod
  30. def _get_answer(prompt: str, config: BaseLlmConfig) -> str:
  31. # If the user wants to run the model locally, they can do so by setting the `local` flag to True
  32. if config.model and config.local:
  33. return HuggingFaceLlm._from_pipeline(prompt=prompt, config=config)
  34. elif config.model:
  35. return HuggingFaceLlm._from_model(prompt=prompt, config=config)
  36. elif config.endpoint:
  37. return HuggingFaceLlm._from_endpoint(prompt=prompt, config=config)
  38. else:
  39. raise ValueError("Either `model` or `endpoint` must be set in config")
  40. @staticmethod
  41. def _from_model(prompt: str, config: BaseLlmConfig) -> str:
  42. model_kwargs = {
  43. "temperature": config.temperature or 0.1,
  44. "max_new_tokens": config.max_tokens,
  45. }
  46. if 0.0 < config.top_p < 1.0:
  47. model_kwargs["top_p"] = config.top_p
  48. else:
  49. raise ValueError("`top_p` must be > 0.0 and < 1.0")
  50. model = config.model
  51. api_key = config.api_key or os.getenv("HUGGINGFACE_ACCESS_TOKEN")
  52. logger.info(f"Using HuggingFaceHub with model {model}")
  53. llm = HuggingFaceHub(
  54. huggingfacehub_api_token=api_key,
  55. repo_id=model,
  56. model_kwargs=model_kwargs,
  57. )
  58. return llm.invoke(prompt)
  59. @staticmethod
  60. def _from_endpoint(prompt: str, config: BaseLlmConfig) -> str:
  61. api_key = config.api_key or os.getenv("HUGGINGFACE_ACCESS_TOKEN")
  62. llm = HuggingFaceEndpoint(
  63. huggingfacehub_api_token=api_key,
  64. endpoint_url=config.endpoint,
  65. task="text-generation",
  66. model_kwargs=config.model_kwargs,
  67. )
  68. return llm.invoke(prompt)
  69. @staticmethod
  70. def _from_pipeline(prompt: str, config: BaseLlmConfig) -> str:
  71. model_kwargs = {
  72. "temperature": config.temperature or 0.1,
  73. "max_new_tokens": config.max_tokens,
  74. }
  75. if 0.0 < config.top_p < 1.0:
  76. model_kwargs["top_p"] = config.top_p
  77. else:
  78. raise ValueError("`top_p` must be > 0.0 and < 1.0")
  79. llm = HuggingFacePipeline.from_model_id(
  80. model_id=config.model,
  81. task="text-generation",
  82. pipeline_kwargs=model_kwargs,
  83. )
  84. return llm.invoke(prompt)