The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
docs: generate embeddings using transformers.js
Greg Richardson2535d62d1acf
diff --git a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.tsindex a151d6639cf..74350eefe17 100644--- a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts+++ b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts@@ -916,6 +916,10 @@ export const ai: NavMenuConstant = {items: [{ name: 'Developing locally with Vecs', url: '/guides/ai/vecs-python-client' },{ name: 'Creating and managing collections', url: '/guides/ai/quickstarts/hello-world' },+ {+ name: 'Generate Embeddings',+ url: '/guides/ai/quickstarts/generate-text-embeddings',+ },{ name: 'Text Deduplication', url: '/guides/ai/quickstarts/text-deduplication' },{ name: 'Face similarity search', url: '/guides/ai/quickstarts/face-similarity' },],diff --git a/apps/docs/components/StepHikeCompact/index.tsx b/apps/docs/components/StepHikeCompact/index.tsxindex 1daa76568d1..3b6614351e5 100644--- a/apps/docs/components/StepHikeCompact/index.tsx+++ b/apps/docs/components/StepHikeCompact/index.tsx@@ -1,5 +1,6 @@//import { Step } from 'next-seo/lib/types'-import React, { FC } from 'react'+import { FC } from 'react'+import { cn } from 'ui'interface IStep {title: string@@ -13,7 +14,9 @@ interface IStepHikeCompactSubcomponents {}interface IDetails {title?: string+ fullWidth?: boolean}+interface ICode {}interface IStepHikeCompact {@@ -74,9 +77,9 @@ const Step: FC<IStep> = ({ children, title, step }) => {)}-const Details: FC<IDetails> = ({ children, title }) => {+const Details: FC<IDetails> = ({ children, title, fullWidth = false }) => {return (- <div className="col-span-5 ml-12 lg:ml-0">+ <div className={cn(fullWidth ? 'col-span-12' : 'col-span-5', 'ml-12', 'lg:ml-0')}><h3 className="mt-0 text-scale-1200 text-base">{title}</h3>{children}</div>diff --git a/apps/docs/pages/guides/ai/quickstarts/generate-text-embeddings.mdx b/apps/docs/pages/guides/ai/quickstarts/generate-text-embeddings.mdxnew file mode 100644index 00000000000..0a8553a1e15--- /dev/null+++ b/apps/docs/pages/guides/ai/quickstarts/generate-text-embeddings.mdx@@ -0,0 +1,210 @@+import Layout from '~/layouts/DefaultGuideLayout'++export const meta = {+ id: 'ai-generating-embeddings',+ title: 'Generate Embeddings',+ subtitle: 'Generate text embeddings using Edge Functions + Transformer.js.',+ breadcrumb: 'AI Quickstarts',+}++This guide will walk you through how to generate high quality text embeddings directly in [Edge Functions](/docs/guides/functions) using Transformers.js. Inference is performed directly in Edge Functions using open source Hugging Face models, so no external API is required.++## What is Transformers.js?++[Transformers.js](https://huggingface.co/docs/transformers.js/index) is a library that allows you to perform inference using the JavaScript runtime. You can run Hugging Face embedding models through Transformers.js directly in Supabase [Edge Functions](/docs/guides/functions).++## Build Edge Function++Let's build our Edge Function. Edge Functions are server-side TypeScript functions that run on-demand closest to your users.++<StepHikeCompact>++ <StepHikeCompact.Step step={1}>++ <StepHikeCompact.Details title="Set up Supabase locally">++ Make sure you have the latest version of the [Supabase CLI installed](/docs/guides/cli/getting-started).++ Initialize Supabase in the root directory of your app and start your local stack.++ </StepHikeCompact.Details>++ <StepHikeCompact.Code>++ ```shell+ supabase init+ supabase start+ ```++ </StepHikeCompact.Code>++ </StepHikeCompact.Step>++ <StepHikeCompact.Step step={2}>++ <StepHikeCompact.Details title="Create Edge Function">++ Create an Edge Function that we will use to generate embeddings. We'll call this `embed` (you can name this anything you like).++ This will create a new TypeScript file called `index.ts` under `./supabase/functions/embed`.++ </StepHikeCompact.Details>++ <StepHikeCompact.Code>++ ```shell+ supabase functions new embed+ ```++ </StepHikeCompact.Code>++ </StepHikeCompact.Step>++ <StepHikeCompact.Step step={3}>++ <StepHikeCompact.Details title="Import & configure Transformer.js" fullWidth>++ Let's modify the Edge Function to import the Transformers.js client and configure it for the Deno runtime.++ ```ts ./supabase/functions/embed/index.ts+ import { serve } from 'https://deno.land/[email protected]/http/server.ts'+ import { env, pipeline } from 'https://cdn.jsdelivr.net/npm/@xenova/[email protected]'++ // Configuration for Deno runtime+ env.useBrowserCache = false;+ env.allowLocalModels = false;+ ```++ </StepHikeCompact.Details>++ </StepHikeCompact.Step>++ <StepHikeCompact.Step step={4}>++ <StepHikeCompact.Details title="Construct embedding pipeline">++ Next let's construct the `pipe()` function we'll use to generate the embeddings. We use the Transformer.js `pipeline()` function to create this.++ </StepHikeCompact.Details>++ <StepHikeCompact.Code>++ ```ts ./supabase/functions/embed/index.ts+ const pipe = await pipeline(+ 'feature-extraction',+ 'Supabase/gte-small',+ );+ ```++ </StepHikeCompact.Code>++ <StepHikeCompact.Details fullWidth>++ Note the two arguments we pass to `pipeline()`:++ 1. The first argument specifies the type of [inference task](https://huggingface.co/docs/transformers.js/index#tasks) to perform. `feature-extraction` is used for embedding generation.+ 2. The second argument specificies which Hugging Face model to use for the embedding generation. Supabase officially supports models available on the [Supabase org](https://huggingface.co/Supabase).++ <Admonition>++ We intentially construct the pipeline before the `serve()` function. This allows us to reuse the pre-loaded model in future warm-start requests, significantly speeding up future queries. Note that you'll only notice this speedup after deploying your function to Supabase - requests in local developement will always be a cold-start.++ </Admonition>++ </StepHikeCompact.Details>++ </StepHikeCompact.Step>++ <StepHikeCompact.Step step={5}>++ <StepHikeCompact.Details title="Implement request handler">++ Modify our `serve()` request handler to accept an `input` string from the POST request JSON body.++ Finally let's generate the embedding by:++ 1. Calling `pipe()` to perform the embedding generation+ 2. Extracting the embedding from the output as a number array+ 3. Returning it as a JSON response++ </StepHikeCompact.Details>++ <StepHikeCompact.Code>++ ```ts ./supabase/functions/embed/index.ts+ serve(async (req) => {+ // Extract input string from JSON body+ const { input } = await req.json();++ // Generate the embedding from the user input+ const output = await pipe(input, {+ pooling: 'mean',+ normalize: true,+ });++ // Get the embedding output+ const embedding = Array.from(output.data);++ // Return the embedding+ return new Response(+ JSON.stringify({ embedding }),+ { headers: { 'Content-Type': 'application/json' } }+ );+ });+ ```++ </StepHikeCompact.Code>++ <StepHikeCompact.Details fullWidth>++ Note the two options we pass to `pipe()`:++ - `pooling`: The first option sets `pooling` to `mean`. Pooling referes to how token-level embedding representations are compressed into a single sentence embedding that reflects the meaning of the entire sentence. Average pooling is the most common type of pooling for sentence embeddings and is the method supported by Transformers.js.+ - `normalize`: The second option tells Transformers.js to normalize the embedding vector so that it can be used with distance measures like dot product. A normalized vector means its length (magnitude) is 1 - also referred to as a unit vector. A vector is normalized by dividing each element by the vector's length (magnitude), which maintains its direction but changes its length to 1.++ </StepHikeCompact.Details>++ </StepHikeCompact.Step>++ <StepHikeCompact.Step step={6}>++ <StepHikeCompact.Details title="Test it!">++ To test the Edge Function, first start a local functions server.++ </StepHikeCompact.Details>++ <StepHikeCompact.Code>++ ```shell+ supabase functions serve+ ```++ </StepHikeCompact.Code>++ <StepHikeCompact.Details fullWidth>++ Then in a new shell, create an HTTP request using cURL and pass in your input in the JSON body.++ ```shell+ curl --request POST 'http://localhost:54321/functions/v1/embed' \+ --header 'Authorization: Bearer ANON_KEY' \+ --header 'Content-Type: application/json' \+ --data '{ "input": "hello world" }'+ ```++ Be sure to replace `ANON_KEY` with your project's anonymous key. You can get this key by running `supabase status`.++ </StepHikeCompact.Details>++ </StepHikeCompact.Step>++</StepHikeCompact>++## Next steps++TBD++export const Page = ({ children }) => <Layout meta={meta} children={children} />++export default Page