Skip to content
AI & Vectors

生成嵌入

Generate text embeddings using Edge Functions.

本指南将带你了解如何在 Edge Functions 中使用内置的 AI 推断 API 生成高质量的文本嵌入,所以不需要外部 API。

🌐 This guide will walk you through how to generate high quality text embeddings in Edge Functions using its built-in AI inference API, so no external API is required.

构建 Edge 函数 #

🌐 Build the Edge Function

构建一个 Edge 函数,它接受输入字符串并为其生成嵌入。Edge 函数是运行在服务器端的 TypeScript HTTP 端点,会按需在最靠近用户的地方运行。

🌐 Build an Edge Function that accepts an input string and generates an embedding for it. Edge Functions are server-side TypeScript HTTP endpoints that run on-demand closest to your users.

1
Set up Supabase locally

确保你已经安装了最新版本的 Supabase CLI

在你应用的根目录初始化 Supabase,然后启动你的本地环境。

1
supabase init
2
supabase start
2
Create Edge Function

创建一个 Edge Function,我们将用它来生成嵌入。我们把它叫做 embed(你可以随意命名)。

这会在 ./supabase/functions/embed 下创建一个叫做 index.ts 的新 TypeScript 文件。

1
supabase functions new embed
3
Setup Inference Session

创建一个新的推断会话,用于这个函数的整个生命周期。多个请求可以使用同一个推断会话。

目前,在 Supabase 的 Edge Runtime 中仅支持 gte-small (https://huggingface.co/Supabase/gte-small) 文本嵌入模型。

1
const session = new Supabase.ai.Session('gte-small');
4
Implement request handler

修改我们的请求处理器,以便从 POST 请求的 JSON 正文中接受一个 input 字符串。

然后通过调用 session.run(input) 来生成嵌入。

1
Deno.serve(async (req) => {
2
// Extract input string from JSON body
3
const { input } = await req.json();
4
5
// Generate the embedding from the user input
6
const embedding = await session.run(input, {
7
mean_pool: true,
8
normalize: true,
9
});
10
11
// Return the embedding
12
return new Response(
13
JSON.stringify({ embedding }),
14
{ headers: { 'Content-Type': 'application/json' } }
15
);
16
});

注意我们传给 session.run() 的两个选项:

  • mean_pool:第一个选项将 pooling 设置为 mean。池化指的是如何将单词级别的嵌入表示压缩成一个反映整个句子含义的句子嵌入。平均池化是句子嵌入中最常见的池化方式。
  • normalize:第二个选项是对嵌入向量进行归一化,这样它就可以用于点积等距离度量。归一化向量意味着它的长度(大小)为 1,也叫单位向量。向量的归一化是通过将每个元素除以向量的长度(大小)来实现的,这样可以保持方向不变,但长度变为 1。
5
Test it!

要测试 Edge 功能,先启动本地函数服务器。

1
supabase functions serve

然后在一个新的终端里,使用 cURL 创建一个 HTTP 请求,并把你的输入放在 JSON 正文里。

1
curl --request POST 'http://localhost:54321/functions/v1/embed' \
2
--header 'Content-Type: application/json' \
3
--header 'apikey: SUPABASE_PUBLISHABLE_KEY' \
4
--data '{ "input": "hello world" }'

一定要把 SUPABASE_PUBLISHABLE_KEY 替换成你项目的可发布密钥。你可以通过运行 supabase status 来获得这个密钥。

下一步 #

🌐 Next steps