Skip to main content
Open In ColabOpen on GitHub

Huggingface 端点

Hugging Face Hub 是一个拥有超过 12 万个模型、2 万个数据集和 5 万个演示应用(Spaces)的平台,所有这些都是开源的,并且可以在线公开访问,人们可以在其中轻松协作并共同构建 ML 应用。

Hugging Face Hub 还提供各种用于构建机器学习应用的端点。 本示例展示了如何连接到不同类型的端点。

特别是,文本生成推理由 Text Generation Inference 提供支持:这是一个专为极速文本生成推理构建的定制化 Rust、Python 和 gRPC 服务器。

from langchain_huggingface import HuggingFaceEndpoint
API Reference:HuggingFaceEndpoint

安装与设置

要使用,您应该安装 huggingface_hub 的 python

%pip install --upgrade --quiet huggingface_hub
# get a token: https://huggingface.co/docs/api-inference/quicktour#get-your-api-token

from getpass import getpass

HUGGINGFACEHUB_API_TOKEN = getpass()
import os

os.environ["HUGGINGFACEHUB_API_TOKEN"] = HUGGINGFACEHUB_API_TOKEN

准备示例

from langchain_huggingface import HuggingFaceEndpoint
API Reference:HuggingFaceEndpoint
from langchain.chains import LLMChain
from langchain_core.prompts import PromptTemplate
API Reference:LLMChain | PromptTemplate
question = "Who won the FIFA World Cup in the year 1994? "

template = """Question: {question}

Answer: Let's think step by step."""

prompt = PromptTemplate.from_template(template)

示例

以下是如何访问 推理提供商 API 的无服务器 HuggingFaceEndpoint 集成的示例。

repo_id = "deepseek-ai/DeepSeek-R1-0528"

llm = HuggingFaceEndpoint(
repo_id=repo_id,
max_length=128,
temperature=0.5,
huggingfacehub_api_token=HUGGINGFACEHUB_API_TOKEN,
provider="auto", # set your provider here hf.co/settings/inference-providers
# provider="hyperbolic",
# provider="nebius",
# provider="together",
)
llm_chain = prompt | llm
print(llm_chain.invoke({"question": question}))

专用端点

免费的无服务器 API 让您可以快速实现解决方案并进行迭代,但对于重度使用场景可能会受到速率限制,因为其负载与其他请求共享。

对于企业级工作负载,最佳选择是使用 Inference Endpoints - Dedicated。 这可以访问完全托管的基础设施,提供更大的灵活性和速度。这些资源附带持续支持和正常运行时间保证,以及自动扩展等选项。

# Set the url to your Inference Endpoint below
your_endpoint_url = "https://fayjubiy2xqn36z0.us-east-1.aws.endpoints.huggingface.cloud"
llm = HuggingFaceEndpoint(
endpoint_url=f"{your_endpoint_url}",
max_new_tokens=512,
top_k=10,
top_p=0.95,
typical_p=0.95,
temperature=0.01,
repetition_penalty=1.03,
)
llm("What did foo say about bar?")

流式传输

from langchain_core.callbacks import StreamingStdOutCallbackHandler
from langchain_huggingface import HuggingFaceEndpoint

llm = HuggingFaceEndpoint(
endpoint_url=f"{your_endpoint_url}",
max_new_tokens=512,
top_k=10,
top_p=0.95,
typical_p=0.95,
temperature=0.01,
repetition_penalty=1.03,
streaming=True,
)
llm("What did foo say about bar?", callbacks=[StreamingStdOutCallbackHandler()])

这个 HuggingFaceEndpoint 类也可以与托管 LLM 的本地 HuggingFace TGI 实例 一起使用。查阅 TGI 仓库 以了解各种硬件(GPU、TPU、Gaudi 等)支持的详细信息。