Skip to content
AI & Vectors

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:

  1. 在 Python 后端使用 Transformers Python 库进行推断。
  2. 直接在 Edge Functions 中使用 Transformers.js 生成嵌入
  3. 使用 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.

边缘函数 #

🌐 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:

1
supabase init

然后创建一个 Edge 函数:

🌐 Then create an Edge Function:

1
supabase functions new text-to-image

创建一个名为 .env.local 的文件来存储你的 Hugging Face 访问令牌:

🌐 Create a file called .env.local to store your Hugging Face access token:

1
HUGGING_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:

1
import { HfInference } from 'https://esm.sh/@huggingface/inference@2.3.2'
2
3
const hf = new HfInference(Deno.env.get('HUGGING_FACE_ACCESS_TOKEN'))
4
5
Deno.serve(async (req) => {
6
const { prompt } = await req.json()
7
8
const image = await hf.textToImage(
9
{
10
inputs: prompt,
11
model: 'stabilityai/stable-diffusion-2',
12
},
13
{
14
use_cache: false,
15
}
16
)
17
18
return new Response(image)
19
})
  1. 这个函数使用 HUGGING_FACE_ACCESS_TOKEN 环境变量创建一个新的 HfInference 实例。
  2. 它期望一个包含 JSON 请求体的 POST 请求。JSON 请求体中应该包括一个名为 prompt 的参数,表示我们将传给 Hugging Face 推断 API 的文本到图片提示。
  3. 接下来我们调用 textToImage(),传入用户的提示以及我们想用来生成图片的模型。今天 Hugging Face 推荐 stabilityai/stable-diffusion-2,但你可以换成任何其他文本生成图片的模型。你可以通过访问他们的 模型页面 并按任务筛选,查看每个任务支持的模型列表。
  4. 我们把 use_cache 设置为 false,这样使用相同提示的重复查询就会生成新的图片。如果你使用的任务和模型是确定性的(基于相同输入总会产生相同结果),可以考虑把 use_cache 设置为 true 来加快响应速度。
  5. 从 API 返回的 image 结果将会是一个 Blob。我们可以直接将 Blob 传入 new Response(),它会自动根据 image 设置响应的内容类型和主体。

最后,在本地运行 Edge Function 来测试它:

🌐 Finally, serve the Edge Function locally to test it:

1
supabase 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.

此时,你可以使用你喜欢的前端框架(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:

1
curl --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:

Llama wearing sunglasses example

下一步 #

🌐 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