You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
langchain/langchain/llms/huggingface_hub.py

116 lines
4.0 KiB
Python

"""Wrapper around HuggingFace APIs."""
import os
from typing import Any, Dict, List, Mapping, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.llms.base import LLM, CompletionOutput
from langchain.llms.utils import enforce_stop_tokens
DEFAULT_REPO_ID = "gpt2"
class HuggingFaceHub(BaseModel, LLM):
"""Wrapper around HuggingFaceHub models.
To use, you should have the ``huggingface_hub`` python package installed, and the
environment variable ``HUGGINGFACEHUB_API_TOKEN`` set with your API token.
Only supports task `text-generation` for now.
Example:
.. code-block:: python
from langchain import HuggingFace
hf = HuggingFace(model="text-davinci-002")
"""
client: Any #: :meta private:
repo_id: str = DEFAULT_REPO_ID
"""Model name to use."""
temperature: float = 0.7
"""What sampling temperature to use."""
max_new_tokens: int = 200
"""The maximum number of tokens to generate in the completion."""
top_p: int = 1
"""Total probability mass of tokens to consider at each step."""
num_return_sequences: int = 1
"""How many completions to generate for each prompt."""
class Config:
"""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."""
if "HUGGINGFACEHUB_API_TOKEN" not in os.environ:
raise ValueError(
"Did not find HuggingFace API token, please add an environment variable"
" `HUGGINGFACEHUB_API_TOKEN` which contains it."
)
try:
from huggingface_hub.inference_api import InferenceApi
repo_id = values.get("repo_id", DEFAULT_REPO_ID)
values["client"] = InferenceApi(
repo_id=repo_id,
token=os.environ["HUGGINGFACEHUB_API_TOKEN"],
task="text-generation",
)
except ImportError:
raise ValueError(
"Could not import huggingface_hub python package. "
"Please it install it with `pip install huggingface_hub`."
)
return values
@property
def _default_params(self) -> Mapping[str, Any]:
"""Get the default parameters for calling HuggingFace Hub API."""
# Convert temperature from [0, 1] to [1, 100] so 0 maps to 1 and 1 maps to 100.
temperature = self.temperature
if 0.0 <= temperature <= 1.0:
temperature = 1.0 + (temperature * 99.0)
# TODO: Add support for returning logprobs once added to the API.
return {
"temperature": temperature,
"max_new_tokens": self.max_new_tokens,
"top_p": self.top_p,
"num_return_sequences": self.num_return_sequences,
"return_full_text": False,
}
def generate(
self, prompt: str, stop: Optional[List[str]] = None
) -> List[CompletionOutput]:
"""Call out to HuggingFace Hub's inference endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
The string generated by the model.
Example:
.. code-block:: python
response = hf("Tell me a joke.")
"""
response = self.client(inputs=prompt, params=self._default_params)
if "error" in response:
raise ValueError(f"Error raised by inference API: {response['error']}")
if stop is not None:
return []
results = []
for result in response:
text = result["generated_text"]
if stop is not None:
# This is a bit hacky, but I can't figure out a better way to enforce
# stop tokens when making calls to huggingface_hub.
text = enforce_stop_tokens(text, stop)
results.append(CompletionOutput(text=text))
return results