> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sambanova.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Supabase integration guide

[Supabase](https://supabase.com/) is a hosted Postgres platform with built-in auth, storage, and serverless [Edge Functions](https://supabase.com/docs/guides/functions). An Edge Function is a small TypeScript function that runs on Deno, so you can call a SambaCloud model from server-side code without exposing your API key to the browser. This guide builds one that answers a prompt with a SambaCloud model, with an option to stream the reply, and runs it on your machine with the Supabase CLI.

> [!NOTE]
>
> Supabase's built-in `Supabase.ai.Session` has an `openaicompatible` mode for self-managed servers, but it does not work with SambaCloud. The mode sends no `Authorization` header, so SambaCloud answers `401 Unauthorized`, and there is no option to add one. Use the OpenAI SDK as shown below instead.

## Prerequisites

* A [SambaCloud](https://cloud.sambanova.ai/?utm_source=supabase\&utm_medium=external\&utm_campaign=cloud_signup) account and [API key](https://cloud.sambanova.ai/apis?utm_source=supabase\&utm_medium=external\&utm_campaign=cloud_signup)
* [Docker](https://docs.docker.com/get-docker/), running. The Supabase CLI starts its local stack in containers.
* The [Supabase CLI](https://supabase.com/docs/guides/local-development/cli/getting-started). This guide was tested with versions 2.121.0 and 3.2.0.

You do not need a Supabase account to follow this guide, because everything runs locally.

## Installation and setup

**1. Create a Supabase project and start the local stack**

```bash theme={}
supabase init
supabase start
```

The first `supabase start` downloads the container images, which takes a few minutes. `supabase functions serve` needs the stack to be running, and fails with `supabase start is not running` otherwise.

**2. Create the Edge Function**

```bash theme={}
supabase functions new sambacloud-chat
```

This creates `supabase/functions/sambacloud-chat/index.ts`.

**3. Store your SambaCloud API key**

Create `supabase/functions/.env` and add your key. The function reads it as `SAMBANOVA_API_KEY`:

```text supabase/functions/.env theme={}
SAMBANOVA_API_KEY=your-sambanova-api-key
```

Do not commit this file.

## Call SambaCloud from the function

Replace the contents of `supabase/functions/sambacloud-chat/index.ts`. The function uses the OpenAI SDK with the SambaCloud base URL, and sends `stream: true` to the model when the caller asks for a streamed reply:

```ts supabase/functions/sambacloud-chat/index.ts theme={}
import 'jsr:@supabase/functions-js/edge-runtime.d.ts'
import OpenAI from 'npm:openai@^6'

const client = new OpenAI({
  apiKey: Deno.env.get('SAMBANOVA_API_KEY'),
  baseURL: 'https://api.sambanova.ai/v1',
})

Deno.serve(async (req) => {
  const { prompt, stream = false } = await req.json()

  try {
    const params = { model: 'MiniMax-M3.1-Flash', messages: [{ role: 'user' as const, content: prompt }] }

    if (!stream) {
      const completion = await client.chat.completions.create({ ...params, stream: false })
      return Response.json({ reply: completion.choices[0].message.content })
    }

    // A separate call with a literal `stream: true` gives TypeScript the streaming return type.
    const completion = await client.chat.completions.create({ ...params, stream: true })

    // Forward each token to the caller as it arrives.
    const encoder = new TextEncoder()
    const body = new ReadableStream({
      async start(controller) {
        for await (const chunk of completion) {
          const text = chunk.choices[0]?.delta?.content ?? ''
          if (text) controller.enqueue(encoder.encode(text))
        }
        controller.close()
      },
    })
    return new Response(body, { headers: { 'Content-Type': 'text/plain; charset=utf-8' } })
  } catch (error) {
    const status = error instanceof OpenAI.APIError ? (error.status ?? 500) : 500
    return Response.json({ error: String(error) }, { status })
  }
})
```

Serve it and call it:

```bash theme={}
supabase functions serve --no-verify-jwt --env-file supabase/functions/.env
```

In a second terminal, send a prompt:

```bash macOS / Linux theme={}
curl -s -X POST http://127.0.0.1:54321/functions/v1/sambacloud-chat \
  -H "Content-Type: application/json" \
  -d '{"prompt": "What can you do?"}'
```

```powershell Windows theme={}
curl.exe -s -X POST http://127.0.0.1:54321/functions/v1/sambacloud-chat `
  -H "Content-Type: application/json" `
  -d '{\"prompt\": \"What can you do?\"}'
```

```json Output (abridged) theme={}
{"reply": "I can help you think, write, learn, and solve problems. For example:\n\n- **Answer questions** and explain complex topics in simple terms\n- **Write and edit** emails, essays, stories, résumés, and reports\n..."}
```

To stream the reply, add `"stream": true` and pass `-N` to `curl` so it prints each chunk as it arrives:

```bash theme={}
curl -sN -X POST http://127.0.0.1:54321/functions/v1/sambacloud-chat \
  -H "Content-Type: application/json" \
  -d '{"prompt": "What can you do?", "stream": true}'
```

> [!NOTE]
>
> `--no-verify-jwt` skips Supabase's check for a signed-in user, so you can call the function with a plain `curl`. `supabase functions new` already sets `verify_jwt = false` for this function in `supabase/config.toml`, so the function also works without the flag. If you change it to `true`, the function answers `401 Missing authorization header` unless the request carries a Supabase JWT or you serve it with `--no-verify-jwt`. `MiniMax-M3.1-Flash` is a reasoning model, so the first streamed text can take a couple of seconds. In 32 test runs it arrived after 1.1 to 5.2 s and the reply finished after 3.1 to 8.0 s.

Supabase's database includes the pgvector extension. To store and search vectors alongside this function, see the [pgvector guide](https://docs.sambanova.ai/docs/en/integrations/pgvector.md).

## Troubleshooting

> [accordion] supabase start is not running
>
> `supabase functions serve` needs the local stack. Make sure Docker is running, then run `supabase start` from the project folder.

> [accordion] WORKER\_ERROR: Function exited due to an error (please check logs)
>
> The function failed before it could answer. Look at the `supabase functions serve` terminal. `Missing credentials. Please pass an apiKey` means `SAMBANOVA_API_KEY` is not set, so check that `supabase/functions/.env` exists and contains the key.

> [accordion] 401 Missing authorization header
>
> The function requires a Supabase JWT when `verify_jwt` is `true` for it in `supabase/config.toml`. `supabase functions new` sets it to `false`, so check whether you changed it. For local testing, serve the function with `--no-verify-jwt`, as shown above, or set `verify_jwt = false`.

> [accordion] 401 Incorrect API key provided
>
> The key in `supabase/functions/.env` is not valid. Copy a key from the [SambaCloud API keys page](https://cloud.sambanova.ai/apis). Restart `supabase functions serve` after you change the file.

> [accordion] 404 The model does not exist or you do not have access to it
>
> The `model` value is not a SambaCloud model ID. See [SambaCloud models](https://docs.sambanova.ai/docs/en/models/sambacloud-models.md) for the current list.

> [accordion] 404 404 page not found
>
> The `baseURL` is missing `/v1`. Set it to `https://api.sambanova.ai/v1`.

> [accordion] Failed to fetch inference API host. Status 401: Unauthorized
>
> You used `Supabase.ai.Session` with `mode: 'openaicompatible'`. That mode cannot send a SambaCloud key, so use the OpenAI SDK as shown in this guide.

## Additional resources

* [Supabase Edge Functions](https://supabase.com/docs/guides/functions)
* [Supabase CLI](https://supabase.com/docs/guides/local-development/cli/getting-started)
* [pgvector guide](https://docs.sambanova.ai/docs/en/integrations/pgvector.md)
* [Supported SambaCloud models](https://docs.sambanova.ai/docs/en/models/sambacloud-models.md)
