The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
docs: convert openai embeddings examples to transformers.js
Greg Richardson85b5729f5bc8
diff --git a/apps/docs/pages/guides/ai/concepts.mdx b/apps/docs/pages/guides/ai/concepts.mdxindex c35a6e72aed..7f1bec30d61 100644--- a/apps/docs/pages/guides/ai/concepts.mdx+++ b/apps/docs/pages/guides/ai/concepts.mdx@@ -7,7 +7,7 @@ export const meta = {sidebar_label: 'Concepts',}-Embeddings are a core concept when building AI and vector applications.+Embeddings are core to many AI and vector applications. This guide will cover these concepts. If you prefer to get started right away, see our guide on [Generating Embeddings](/docs/guides/ai/quickstarts/generate-text-embeddings).## What are embeddings?@@ -48,7 +48,7 @@ In this example we only have 2 dimensions: the X and Y axis. In reality, we woul## Using embeddings-Compared to our 2-dimensional example above, most embedding models will output many more dimensions. For example OpenAI's `text-embedding-ada-002` model outputs 1536 dimensions.+Compared to our 2-dimensional example above, most embedding models will output many more dimensions. For example the open source [`gte-small`](https://huggingface.co/Supabase/gte-small) model outputs 384 dimensions.Why is this useful? Once we have generated embeddings on multiple texts, it is trivial to calculate how similar they are using vector math operations like cosine distance. A common use case for this is search. Your process might look something like this:diff --git a/apps/docs/pages/guides/ai/engineering-for-scale.mdx b/apps/docs/pages/guides/ai/engineering-for-scale.mdxindex 0621207930f..871d0a5059c 100644--- a/apps/docs/pages/guides/ai/engineering-for-scale.mdx+++ b/apps/docs/pages/guides/ai/engineering-for-scale.mdx@@ -120,7 +120,7 @@ We can now create a foreign table to access the data in our secondary project.```sqlcreate foreign table docs (id text not null,- embedding vector(1536),+ embedding vector(384),metadata jsonb,url text)diff --git a/apps/docs/pages/guides/ai/hugging-face.mdx b/apps/docs/pages/guides/ai/hugging-face.mdxindex c198e7b2349..9bf295d42d5 100644--- a/apps/docs/pages/guides/ai/hugging-face.mdx+++ b/apps/docs/pages/guides/ai/hugging-face.mdx@@ -2,14 +2,18 @@ import Layout from '~/layouts/DefaultGuideLayout'export const meta = {id: 'ai-hugging-face',- title: 'Hugging Face',+ title: 'Hugging Face Inference API',description: 'Learn how to integrate hugging face models with Supabase',sidebar_label: 'Hugging Face',}[Hugging Face](https://huggingface.co) is an open source hub for AI/ML models and tools. With over 100,000 machine learning models available, Hugging Face provides a great way to integrate specialized AI & ML tasks into your application.-Hugging Face exposes an [Inference API](https://huggingface.co/inference-api) you can use to execute AI tasks remotely on Hugging Face servers. This opens the doors to using Hugging Face with languages like TypeScript and can be deployed using [Edge Functions](/docs/guides/functions).+There are 3 ways to use Hugging Face models in your application:++1. Use the [Transformers](https://huggingface.co/docs/transformers/index) Python library to perform inference in a Python backend.+1. [Generate embeddings](/docs/guides/ai/quickstarts/generate-text-embeddings) directly in Edge Functions using Transformers.js.+1. Use Hugging Face's hosted [Inference API](https://huggingface.co/inference-api) to execute AI tasks remotely on Hugging Face servers. This guide will walk you through this approach.## AI Tasksdiff --git a/apps/docs/pages/guides/ai/quickstarts/generate-text-embeddings.mdx b/apps/docs/pages/guides/ai/quickstarts/generate-text-embeddings.mdxindex 0a8553a1e15..f755a681b66 100644--- a/apps/docs/pages/guides/ai/quickstarts/generate-text-embeddings.mdx+++ b/apps/docs/pages/guides/ai/quickstarts/generate-text-embeddings.mdx@@ -142,7 +142,7 @@ Let's build our Edge Function. Edge Functions are server-side TypeScript functionormalize: true,});- // Get the embedding output+ // Extract the embedding outputconst embedding = Array.from(output.data);// Return the embedding@@ -203,7 +203,8 @@ Let's build our Edge Function. Edge Functions are server-side TypeScript functio## Next steps-TBD+- Learn more about [embedding concepts](/docs/guides/ai/concepts)+- [Store your embeddings](/docs/guides/ai/vector-columns) in a databaseexport const Page = ({ children }) => <Layout meta={meta} children={children} />diff --git a/apps/docs/pages/guides/ai/vector-columns.mdx b/apps/docs/pages/guides/ai/vector-columns.mdxindex 7c768606e0b..c5e344b0bbb 100644--- a/apps/docs/pages/guides/ai/vector-columns.mdx+++ b/apps/docs/pages/guides/ai/vector-columns.mdx@@ -56,27 +56,31 @@ create table documents (id serial primary key,title text not null,body text not null,- embedding vector(1536)+ embedding vector(384));```-In the above SQL snippet, we create a `documents` table with a column called `embedding` (note this is just a regular Postgres column - you can name it whatever you like). We give the `embedding` column a `vector` data type with 1536 dimensions. Change this to the number of dimensions used in your vector application. For example, if you are generating embeddings using OpenAI's `text-embeddings-ada-002` model, you would set this number as 1536 since that model produces 1536 dimensions.+In the above SQL snippet, we create a `documents` table with a column called `embedding` (note this is just a regular Postgres column - you can name it whatever you like). We give the `embedding` column a `vector` data type with 384 dimensions. Change this to the number of dimensions produced by your embedding model. For example, if you are generating embeddings using the open source [`gte-small`](https://huggingface.co/Supabase/gte-small) model, you would set this number as 384 since that model produces 384 dimensions.### Storing a vector / embedding-In this example we'll generate a vector using the OpenAI API client, then store it in the database using the Supabase JavaScript client.+In this example we'll generate a vector using Transformers.js, then store it in the database using the Supabase JavaScript client.```js+import { pipeline } from 'transformers'+const generateEmbedding = await pipeline('feature-extraction', 'Supabase/gte-small')+const title = 'First post!'const body = 'Hello world!'-// Generate a vector using OpenAI-const embeddingResponse = await openai.createEmbedding({- model: 'text-embedding-ada-002',- input: body,+// Generate a vector using Transformers.js+const output = await generateEmbedding(body, {+ pooling: 'mean',+ normalize: true,})-const [{ embedding }] = embeddingResponse.data.data+// Extract the embedding output+const embedding = Array.from(output.data)// Store the vector in Postgresconst { data, error } = await supabase.from('documents').insert({@@ -90,7 +94,7 @@ This example uses the JavaScript Supabase client, but you can modify it to work### Querying a vector / embedding-Similarity search is the most common use case for vectors. `pgvector` support 3 new operators for performing similarity search:+Similarity search is the most common use case for vectors. `pgvector` support 3 new operators for computing distance:| Operator | Description || -------- | ---------------------- |@@ -98,13 +102,13 @@ Similarity search is the most common use case for vectors. `pgvector` support 3| `<#>` | negative inner product || `<=>` | cosine distance |-Choosing the right operator depends on your needs. If you are searching over OpenAI embeddings, OpenAI recommends using cosine similarity. For more information on how embeddings work and how they relate to each other, see [What are Embeddings?](/docs/guides/ai/concepts#what-are-embeddings).+Choosing the right operator depends on your needs. Dot product tends to be the fastest if your vectors are normalized. For more information on how embeddings work and how they relate to each other, see [What are Embeddings?](/docs/guides/ai/concepts#what-are-embeddings).Supabase client libraries like `supabase-js` connect to your Postgres instance via [PostgREST](docs/guides/getting-started/architecture#postgrest-api). PostgREST does not currently support `pgvector` similarity operators, so we'll need to wrap our query in a Postgres function and call it via the `rpc()` method:```sqlcreate or replace function match_documents (- query_embedding vector(1536),+ query_embedding vector(384),match_threshold float,match_count int)@@ -140,9 +144,15 @@ const { data: documents } = await supabaseClient.rpc('match_documents', {})```-In this example `embedding` would be another embedding you wish to compare against your table of pre-generated embedding documents. For example if you were building a search engine, every time the user submits their query you would first generate an embedding on the search query itself (using `openai.createEmbedding()`), then pass it into the above `rpc()` function to match.+In this example `embedding` would be another embedding you wish to compare against your table of pre-generated embedding documents. For example if you were building a search engine, every time the user submits their query you would first generate an embedding on the search query itself, then pass it into the above `rpc()` function to match.++<Admonition>++Be sure to use embeddings produced from the same embedding model when calculating distance. Comparing embeddings from two different models will produce no meaningful result.++</Admonition>-Vectors and embedding can be used for much more than search. Learn more about embeddings at [What are Embeddings?](/docs/guides/ai/concepts#what-are-embeddings).+Vectors and embeddings can be used for much more than search. Learn more about embeddings at [What are Embeddings?](/docs/guides/ai/concepts#what-are-embeddings).### Indexesdiff --git a/apps/docs/pages/guides/database/extensions/pgvector.mdx b/apps/docs/pages/guides/database/extensions/pgvector.mdxindex b142920f358..5d408e10e03 100644--- a/apps/docs/pages/guides/database/extensions/pgvector.mdx+++ b/apps/docs/pages/guides/database/extensions/pgvector.mdx@@ -19,7 +19,7 @@ Vector similarity refers to a measure of the similarity between two related item### Embeddings-This is particularly useful if you're building on top of OpenAI's [GPT-3](https://openai.com/blog/gpt-3-apps/). You can create and store [embeddings](https://platform.openai.com/docs/guides/embeddings) which match the GPT model you're using.+This is particularly useful if you're building on top of OpenAI's [GPT-3](https://openai.com/blog/gpt-3-apps/). You can create and store [embeddings](/docs/guides/ai/quickstarts/generate-text-embeddings) for retrieval augmented generation.## Usage@@ -66,25 +66,29 @@ create table posts (id serial primary key,title text not null,body text not null,- embedding vector(1536)+ embedding vector(384));```### Storing a vector / embedding-In this example we'll generate a vector using the OpenAI API client, then store it in the database using the Supabase client.+In this example we'll generate a vector using Transformer.js, then store it in the database using the Supabase client.```js+import { pipeline } from 'transformers'+const generateEmbedding = await pipeline('feature-extraction', 'Supabase/gte-small')+const title = 'First post!'const body = 'Hello world!'-// Generate a vector using OpenAI-const embeddingResponse = await openai.createEmbedding({- model: 'text-embedding-ada-002',- input: body,+// Generate a vector using Transformers.js+const output = await generateEmbedding(body, {+ pooling: 'mean',+ normalize: true,})-const [{ embedding }] = embeddingResponse.data.data+// Extract the embedding output+const embedding = Array.from(output.data)// Store the vector in Postgresconst { data, error } = await supabase.from('posts').insert({