Skip to content
Edge Functions

运行 AI 模型

Run AI models in Edge Functions using the built-in Supabase AI API.

Edge Functions 内置了一个用于运行 AI 模型的 API。你可以使用这个 API 来生成嵌入、构建对话工作流,以及在你的 Edge Functions 中执行其他 AI 相关的任务。

🌐 Edge Functions have a built-in API for running AI models. You can use this API to generate embeddings, build conversational workflows, and do other AI related tasks in your Edge Functions.

这让你可以:

🌐 This allows you to:

  • 在不依赖外部资源的情况下生成文本嵌入
  • 通过 Ollama 或 Llamafile 运行大型语言模型
  • 构建对话式 AI 工作流程

设置 #

🌐 Setup

启用这个 API 不需要安装任何外部依赖或软件包。

🌐 There are no external dependencies or packages to install to enable the API.

创建一个新的推断会话:

🌐 Create a new inference session:

const model = new Supabase.ai.Session('model-name')

运行模型推断 #

🌐 Running a model inference

一旦会话被实例化,你就可以用输入来调用它进行推断:

🌐 Once the session is instantiated, you can call it with inputs to perform inferences:

// For embeddings (gte-small model)
const embeddings = await model.run('Hello world', {
mean_pool: true,
normalize: true,
})
// For text generation (non-streaming)
const response = await model.run('Write a haiku about coding', {
stream: false,
timeout: 30,
})
// For streaming responses
const stream = await model.run('Tell me a story', {
stream: true,
mode: 'ollama',
})

生成文本嵌入 #

🌐 Generate text embeddings

使用内置 gte-small 模型生成文本嵌入:

🌐 Generate text embeddings using the built-in gte-small model:

import { withSupabase } from 'npm:@supabase/server@^1'
const model = new Supabase.ai.Session('gte-small')
export default {
fetch: withSupabase({ auth: 'publishable' }, async (req, ctx) => {
const params = new URL(req.url).searchParams
const input = params.get('input')
const output = await model.run(input, { mean_pool: true, normalize: true })
return Response.json(output)
}),
}

使用大型语言模型 (LLM) #

🌐 Using Large Language Models (LLM)

通过更大的模型进行推断可以通过 Ollama 和 Mozilla Llamafile 实现。在第一轮中,你可以使用自管理的 Ollama 或 Llamafile 服务器 来使用它。

🌐 Inference via larger models is supported via Ollama and Mozilla Llamafile. In the first iteration, you can use it with a self-managed Ollama or Llamafile server.


本地运行 #

🌐 Running locally

1
Install Ollama

安装 Ollama 并拉取 Mistral 模型

ollama pull mistral
2
Run the Ollama server
ollama serve
3
Set the function secret

Set a function secret called AI_INFERENCE_API_HOST to point to the Ollama server

echo "AI_INFERENCE_API_HOST=http://host.docker.internal:11434" >> supabase/functions/.env
4
Create a new function
supabase functions new ollama-test
import 'jsr:@supabase/functions-js/edge-runtime.d.ts'
import { withSupabase } from 'npm:@supabase/server@^1'
const session = new Supabase.ai.Session('mistral')
export default {
fetch: withSupabase({ auth: 'publishable' }, async (req, ctx) => {
const params = new URL(req.url).searchParams
const prompt = params.get('prompt') ?? ''
// Get the output as a stream
const output = await session.run(prompt, { stream: true })
const headers = new Headers({
'Content-Type': 'text/event-stream',
Connection: 'keep-alive',
})
// Create a stream
const stream = new ReadableStream({
async start(controller) {
const encoder = new TextEncoder()
try {
for await (const chunk of output) {
controller.enqueue(encoder.encode(chunk.response ?? ''))
}
} catch (err) {
console.error('Stream error:', err)
} finally {
controller.close()
}
},
})
// Return the stream to the user
return new Response(stream, {
headers,
})
}),
}
5
Serve the function
supabase functions serve --no-verify-jwt --env-file supabase/functions/.env
6
Execute the function
curl --get "http://localhost:54321/functions/v1/ollama-test" \
--data-urlencode "prompt=write a short rap song about Supabase, the Postgres Developer platform, as sung by Nicki Minaj" \
-H "apikey: $PUBLISHABLE_KEY"

部署到生产环境 #

🌐 Deploying to production

一旦这个功能在本地能正常运行,就可以部署到生产环境了。

🌐 Once the function is working locally, it's time to deploy to production.

1
Deploy an Ollama or Llamafile server

部署一个 Ollama 或 Llamafile 服务器,并设置一个名为 AI_INFERENCE_API_HOST 的函数密钥指向已部署的服务器:

supabase secrets set AI_INFERENCE_API_HOST=https://path-to-your-llm-server/
2
Deploy the function
supabase functions deploy --no-verify-jwt
3
Execute the function
curl --get "https://project-ref.supabase.co/functions/v1/ollama-test" \
--data-urlencode "prompt=write a short rap song about Supabase, the Postgres Developer platform, as sung by Nicki Minaj" \
-H "apikey: $PUBLISHABLE_KEY"