Hugging Face 推断 API
Hugging Face 是一个用于 AI/ML 模型和工具的开源平台。Hugging Face 提供超过 100,000 个机器学习模型,是将特定 AI 和 ML 任务集成到你的应用中的一个很棒的方式。
在你的应用中使用 Hugging Face 模型有三种方法:
🌐 There are 3 ways to use Hugging Face models in your application:
- 在 Python 后端使用 Transformers Python 库进行推断。
- 直接在 Edge Functions 中使用 Transformers.js 生成嵌入。
- 使用 Hugging Face 托管的 Inference API 在 Hugging Face 服务器上远程执行 AI 任务。这个指南会带你了解这种方法。
人工智能任务 #
🌐 AI tasks
下面是你可以用 Hugging Face 执行的一些任务类型:
🌐 Below are some of the types of tasks you can perform with Hugging Face:
自然语言 #
🌐 Natural language
计算机视觉 #
🌐 Computer vision
音频 #
🌐 Audio
查看完整任务列表。
🌐 See a full list of tasks.
访问令牌 #
🌐 Access token
先为你的应用生成一个 Hugging Face 访问令牌:
🌐 First generate a Hugging Face access token for your app:
https://huggingface.co/settings/tokens
根据应用及其使用环境来命名你的令牌。例如,如果你正在构建一个图片生成应用,你可能会创建两个令牌:
🌐 Name your token based on the app its being used for and the environment. For example, if you are building an image generation app you might create 2 tokens:
- 图片生成器(开发中)
- 图片生成器(正式版)
既然我们会用这个令牌来调用推断 API,就选择 read 角色吧。
🌐 Since we will be using this token for the inference API, choose the read role.
虽然现在可以在没有访问令牌的情况下使用 Hugging Face 推断 API,你可能会受到速率限制。
🌐 Though it is possible to use the Hugging Face inference API today without an access token, you may be rate limited.
为了确保你不会遇到意外的停机或错误,我们建议你创建一个访问令牌。
🌐 To ensure you don't experience any unexpected downtime or errors, we recommend creating an access token.
边缘函数 #
🌐 Edge Functions
Edge Functions 是在服务器端按需运行的 TypeScript 函数。由于 Edge Functions 运行在服务器上,你可以安全地让它们访问你的 Hugging Face 访问令牌。
🌐 Edge Functions are server-side TypeScript functions that run on-demand. Since Edge Functions run on a server, you can safely give them access to your Hugging Face access token.
要创建一个新的 Edge Function,先到你的本地项目里,如果还没初始化 Supabase,就先初始化它:
🌐 To create a new Edge Function, navigate to your local project and initialize Supabase if you haven't already:
1supabase init然后创建一个 Edge 函数:
🌐 Then create an Edge Function:
1supabase functions new text-to-image创建一个名为 .env.local 的文件来存储你的 Hugging Face 访问令牌:
🌐 Create a file called .env.local to store your Hugging Face access token:
1HUGGING_FACE_ACCESS_TOKEN=<your-token-here>修改 Edge 函数以导入 Hugging Face 的推断客户端并执行 text-to-image 请求:
🌐 Modify the Edge Function to import Hugging Face's inference client and perform a text-to-image request:
1import { HfInference } from 'https://esm.sh/@huggingface/inference@2.3.2'23const hf = new HfInference(Deno.env.get('HUGGING_FACE_ACCESS_TOKEN'))45Deno.serve(async (req) => {6 const { prompt } = await req.json()78 const image = await hf.textToImage(9 {10 inputs: prompt,11 model: 'stabilityai/stable-diffusion-2',12 },13 {14 use_cache: false,15 }16 )1718 return new Response(image)19})- 这个函数使用
HUGGING_FACE_ACCESS_TOKEN环境变量创建一个新的HfInference实例。 - 它期望一个包含 JSON 请求体的 POST 请求。JSON 请求体中应该包括一个名为
prompt的参数,表示我们将传给 Hugging Face 推断 API 的文本到图片提示。 - 接下来我们调用
textToImage(),传入用户的提示以及我们想用来生成图片的模型。今天 Hugging Face 推荐stabilityai/stable-diffusion-2,但你可以换成任何其他文本生成图片的模型。你可以通过访问他们的 模型页面 并按任务筛选,查看每个任务支持的模型列表。 - 我们把
use_cache设置为false,这样使用相同提示的重复查询就会生成新的图片。如果你使用的任务和模型是确定性的(基于相同输入总会产生相同结果),可以考虑把use_cache设置为true来加快响应速度。 - 从 API 返回的
image结果将会是一个Blob。我们可以直接将Blob传入new Response(),它会自动根据image设置响应的内容类型和主体。
最后,在本地运行 Edge Function 来测试它:
🌐 Finally, serve the Edge Function locally to test it:
1supabase functions serve --env-file .env.local --no-verify-jwt记得通过 --env-file 参数传入 .env.local 文件,这样 Edge Function 才能访问 HUGGING_FACE_ACCESS_TOKEN。
🌐 Remember to pass in the .env.local file using the --env-file parameter so that the Edge Function can access the HUGGING_FACE_ACCESS_TOKEN.
为了演示目的,我们将 --no-verify-jwt 设置为方便测试 Edge Function,而无需传入 JWT token。在实际应用中,你需要将 JWT 作为 Bearer token 传入 Authorization 头中。
🌐 For demo purposes we set --no-verify-jwt to make it easy to test the Edge Function without passing in a JWT token. In a real application you will need to pass the JWT as a Bearer token in the Authorization header.
此时,你可以使用你喜欢的前端框架(Next.js、React、Expo 等)向你的 Edge Function 发起 API 请求。我们也可以在终端使用 curl 进行测试:
🌐 At this point, you can make an API request to your Edge Function using your preferred frontend framework (Next.js, React, Expo, etc). We can also test from the terminal using curl:
1curl --output result.jpg --location --request POST 'http://localhost:54321/functions/v1/text-to-image' \2 --header 'Content-Type: application/json' \3 --data '{"prompt":"Llama wearing sunglasses"}'在这个例子中,你生成的图片会保存到 result.jpg:
🌐 In this example, your generated image will save to result.jpg:

下一步 #
🌐 Next steps
你现在可以创建一个 Edge 功能,使用你选择的模型调用 Hugging Face 任务。
🌐 You can now create an Edge Function that invokes a Hugging Face task using your model of choice.
试着运行一些其他的 AI 任务。
🌐 Try running some other AI tasks.
资源 #
🌐 Resources
- 官方 Hugging Face 网站。
- 官方 Hugging Face JS 文档。
- 使用 Hugging Face 生成图片说明。