> ## 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

[Supabase](https://supabase.com/) は、認証・ストレージ・サーバーレスの [Edge Functions](https://supabase.com/docs/guides/functions) を備えたホステッド Postgres プラットフォームです。Edge Function は Deno 上で動作する小さな TypeScript 関数で、API キーをブラウザに公開することなく、サーバーサイドのコードから SambaCloud モデルを呼び出せます。本ガイドでは、SambaCloud モデルでプロンプトに回答する Edge Function を、応答をストリーミングするオプション付きで作成し、Supabase CLI を使って手元のマシンで実行します。

> [!NOTE]
>
> Supabase 組み込みの `Supabase.ai.Session` には、セルフマネージドサーバー向けの `openaicompatible` モードがありますが、SambaCloud では動作しません。このモードは `Authorization` ヘッダーを送信しないため SambaCloud が `401 Unauthorized` を返し、ヘッダーを追加するオプションもありません。代わりに、以下に示すように OpenAI SDK を使用してください。

## 前提条件

* [SambaCloud](https://cloud.sambanova.ai/?utm_source=supabase\&utm_medium=external\&utm_campaign=cloud_signup) のアカウントと [API キー](https://cloud.sambanova.ai/apis?utm_source=supabase\&utm_medium=external\&utm_campaign=cloud_signup)
* [Docker](https://docs.docker.com/get-docker/)（起動済みであること）。Supabase CLI はローカル環境 (local stack) をコンテナで起動します。
* [Supabase CLI](https://supabase.com/docs/guides/local-development/cli/getting-started)。本ガイドはバージョン 2.121.0 と 3.2.0 で動作確認済みです。

すべてローカルで動作するため、本ガイドを進めるうえで Supabase のアカウントは不要です。

## インストールとセットアップ

**1. Supabase プロジェクトの作成とローカル環境の起動**

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

初回の `supabase start` はコンテナイメージをダウンロードするため、数分かかります。`supabase functions serve` はローカル環境が起動していることを前提としており、起動していない場合は `supabase start is not running` で失敗します。

**2. Edge Function の作成**

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

これにより `supabase/functions/sambacloud-chat/index.ts` が作成されます。

**3. SambaCloud API キーの保存**

`supabase/functions/.env` を作成し、キーを追加します。関数はこれを `SAMBANOVA_API_KEY` として読み取ります。

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

このファイルはコミットしないでください。

## 関数からの SambaCloud 呼び出し

`supabase/functions/sambacloud-chat/index.ts` の内容を置き換えます。この関数は SambaCloud のベース URL を指定した OpenAI SDK を使用し、呼び出し側がストリーミングでの応答を求めた場合は `stream: true` をモデルに送信します。

```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 })
  }
})
```

関数をサービングして呼び出します。

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

別のターミナルから、プロンプトを送信します。

```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..."}
```

応答をストリーミングするには、`"stream": true` を追加し、`curl` に `-N` を渡して各チャンクを到着順に表示します。

```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` は、サインイン済みユーザーかどうかの Supabase の検証をスキップするため、素の `curl` で関数を呼び出せます。`supabase functions new` は `supabase/config.toml` でこの関数の `verify_jwt = false` をあらかじめ設定するため、このフラグなしでも関数は動作します。`true` に変更した場合は、リクエストに Supabase の JWT を含めるか `--no-verify-jwt` 付きでサービングしない限り、関数は `401 Missing authorization header` を返します。`MiniMax-M3.1-Flash` は Reasoning モデルのため、ストリーミングの最初のテキストが届くまでに数秒かかることがあります。32 回のテスト実行では、最初のテキストは 1.1〜5.2 秒で届き、応答は 3.1〜8.0 秒で完了しました。

Supabase のデータベースには pgvector 拡張機能が含まれています。この関数と組み合わせてベクトルを保存・検索するには、[pgvector ガイド](https://docs.sambanova.ai/docs/ja/integrations/pgvector.md)をご参照ください。

## トラブルシューティング

> [accordion] supabase start is not running
>
> `supabase functions serve` にはローカル環境が必要です。Docker が起動していることを確認し、プロジェクトフォルダで `supabase start` を実行してください。

> [accordion] WORKER\_ERROR: Function exited due to an error (please check logs)
>
> 関数が応答を返す前に失敗しています。`supabase functions serve` を実行しているターミナルを確認してください。`Missing credentials. Please pass an apiKey` は `SAMBANOVA_API_KEY` が未設定であることを意味するため、`supabase/functions/.env` が存在し、キーが含まれていることを確認してください。

> [accordion] 401 Missing authorization header
>
> `supabase/config.toml` でこの関数の `verify_jwt` が `true` の場合、関数は Supabase の JWT を要求します。`supabase functions new` は `false` に設定するため、変更していないか確認してください。ローカルでのテストでは、上記のように `--no-verify-jwt` 付きで関数をサービングするか、`verify_jwt = false` を設定してください。

> [accordion] 401 Incorrect API key provided
>
> `supabase/functions/.env` のキーが有効ではありません。[SambaCloud の API キーページ](https://cloud.sambanova.ai/apis)からキーをコピーしてください。ファイルを変更したら `supabase functions serve` を再起動してください。

> [accordion] 404 The model does not exist or you do not have access to it
>
> `model` の値が SambaCloud のモデル ID ではありません。現在のモデル一覧は [SambaCloud モデル](https://docs.sambanova.ai/docs/ja/models/sambacloud-models.md)をご参照ください。

> [accordion] 404 404 page not found
>
> `baseURL` に `/v1` がありません。`https://api.sambanova.ai/v1` を設定してください。

> [accordion] Failed to fetch inference API host. Status 401: Unauthorized
>
> `Supabase.ai.Session` を `mode: 'openaicompatible'` で使用しています。このモードでは SambaCloud のキーを送信できないため、本ガイドで示したとおり OpenAI SDK を使用してください。

## 参考情報

* [Supabase Edge Functions](https://supabase.com/docs/guides/functions)
* [Supabase CLI](https://supabase.com/docs/guides/local-development/cli/getting-started)
* [pgvector ガイド](https://docs.sambanova.ai/docs/ja/integrations/pgvector.md)
* [SambaCloud 対応モデル](https://docs.sambanova.ai/docs/ja/models/sambacloud-models.md)
