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

# BaaS + AI cookbook

> Four worked patterns that pair the BaaS primitives (PostgREST, Auth, Storage, Realtime) with the AI surface (agents, KBs, workflows). The composability story Powabase is built around.

The point of Powabase is that the BaaS substrate and the AI primitives compose. You can build an app that signs users in (Auth), stores their files (Storage), indexes those files into a knowledge base (Sources + KB), runs an agent that searches the KB (Agents), and streams the answer back to the user, all on one platform, with one auth model, with RLS gating the right things.

This page is four worked patterns that string those primitives together. None of them is the only right way; treat them as starting points you'll adapt to your shape. For deeper dives on each primitive, see the per-area pages linked from the Cards at the end.

Two rules from the [authorization model](https://docs.powabase.ai/guides/auth-connection.md#which-key-for-which-route) shape these recipes. First, a signed-in user's JWT works only on the conversation routes (their own sessions, runs and approvals); knowledge bases, sources and search need the Service Role key, so those calls go through your backend. Second, an agent's data tools act as whoever started the run: the user on a run started with their JWT, the agent's own database login on a run started with the Service Role key.

## Recipe 1: User-scoped agent context

The pattern: you have an agent that needs to retrieve from a knowledge base, but each end user should see only their own sources within that KB. The naive approach (agent has unrestricted KB access; you filter results in your app) leaks data via the response.

The `ai` schema is backend-only, so you can't put RLS policies on `ai.chunks` and query it under the user's JWT. (Earlier versions of this recipe did that; since the `ai` schema lockdown, PostgREST rejects `Accept-Profile: ai`.) Instead, keep ownership in your own `public` table, where RLS does apply, and have your backend pass the user's source ids to the typed search endpoint.

**Step 1: an ownership table in `public` with RLS**:

```sql theme={null}
CREATE TABLE public.documents (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  source_id uuid NOT NULL,          -- the id returned by POST /api/sources/upload
  owner_id uuid NOT NULL DEFAULT auth.uid(),
  created_at timestamptz NOT NULL DEFAULT now()
);

ALTER TABLE public.documents ENABLE ROW LEVEL SECURITY;

CREATE POLICY own_documents ON public.documents
  FOR SELECT TO authenticated
  USING (owner_id = auth.uid());
```

**Step 2: on your backend, resolve the user's sources, then search.** Read `public.documents` via PostgREST with the user's access token, so RLS returns only their rows (and an invalid token gets a `401`). Then call the typed search endpoint with the Service Role key, restricted to those sources with `source_ids`:

```typescript theme={null}
// Runs on your backend. The browser sends its access token; it never
// chooses the source_ids itself.
async function retrieveContext(kbId: string, query: string, userToken: string) {
  const docsRes = await fetch(`${BASE_URL}/rest/v1/documents?select=source_id`, {
    headers: { apikey: ANON_KEY, Authorization: `Bearer ${userToken}` },
  });
  if (!docsRes.ok) throw new Error(`documents lookup failed: ${docsRes.status}`);
  const sourceIds = (await docsRes.json()).map((d: { source_id: string }) => d.source_id);
  if (sourceIds.length === 0) return [];

  const searchRes = await fetch(`${BASE_URL}/api/knowledge-bases/${kbId}/search`, {
    method: "POST",
    headers: {
      apikey: SERVICE_ROLE_KEY,
      Authorization: `Bearer ${SERVICE_ROLE_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ query, top_k: 10, source_ids: sourceIds }),
  });
  const { results } = await searchRes.json();
  return results; // [{ chunk_id, text, score, source_id, meta }]
}
```

The browser can't call `/api/knowledge-bases/{id}/search` itself: the route requires the Service Role key and answers a user's JWT with `403`. Keep it that way in your own API too. Never forward `source_ids` the browser chose, because the search endpoint doesn't check who owns the sources.

**Step 3: pass the retrieved chunks as agent `context_items`.** The agent run endpoint accepts a `context_items` array that replaces the agent's own retrieval:

```typescript theme={null}
async function askAgent(agentId: string, message: string, contextItems: any[]) {
  // Also on your backend, with the Service Role key. The run doesn't check
  // who owns the chunks; the filtering happened in retrieveContext().
  const res = await fetch(`${BASE_URL}/api/agents/${agentId}/run`, {
    method: "POST",
    headers: {
      apikey: SERVICE_ROLE_KEY,
      Authorization: `Bearer ${SERVICE_ROLE_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      message,
      context_items: contextItems.map((c) => ({
        text: c.text,
        meta: { ...c.meta, source_id: c.source_id },
      })),
    }),
  });
  return res.json();
}
```

The data path is: user JWT → PostgREST (RLS on `public.documents`) → the user's source ids → typed search restricted to those sources → `context_items` → agent. `/run` makes a single LLM call with no tools, so the agent never sees chunks from sources the user doesn't own. If you switch to `/run/stream` for tool use, remember this is a service-role run: the knowledge bases configured on the agent are searched without your ownership filter, and its database tools bypass RLS on their configured tables. Keep those off this agent (see Recipe 2).

**Trade-offs.** You keep the platform's hybrid scoring and reranking, because the typed search endpoint still does the retrieval. The cost is a backend in the middle holding the Service Role key. If users never share sources, one knowledge base per user (or per tenant) is simpler still: your backend picks the KB, and no `source_ids` list is needed.

## Recipe 2: Build-your-own authenticated chatbot

A chat app where each user talks to an agent and the response streams back to them. User A's chat history must not be visible to user B. There are two working shapes; pick by what the agent needs.

### Option A: the browser calls the conversation routes

Agent runs, sessions and approvals are [end-user routes](https://docs.powabase.ai/guides/auth-connection.md#end-user-routes), so the browser can stream a run with the signed-in user's own access token. No Service Role key is involved:

```typescript theme={null}
// Runs in the browser, with the user's own access token. /run/stream is an
// end-user route, so this is allowed; knowledge-base and source routes aren't.
async function sendMessage(agentId: string, message: string, sessionId?: string) {
  return fetch(`${BASE_URL}/api/agents/${agentId}/run/stream`, {
    method: "POST",
    headers: {
      apikey: ANON_KEY,
      Authorization: `Bearer ${accessToken}`,  // the signed-in user's token
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      message,
      // Omit on the first turn. Afterwards, reuse the session_id from the
      // start event; an end user can't name a new session id.
      ...(sessionId ? { session_id: sessionId } : {}),
    }),
  });
}
```

What the platform enforces for you:

* **History is per user.** The run creates a session owned by the user. `GET /api/agents/{id}/sessions` with their token lists only their sessions, and another user's `session_id` answers `404`.
* **Data tools act as the user.** The agent's `database_query` and `database_write` tools query Postgres as the `authenticated` role with the user's claims, so your RLS policies on the agent's configured tables decide what it can read and write. Its storage tools use the user's token, so your Storage policies apply.
* **The run can't choose knowledge bases.** It searches the knowledge bases configured on the agent; sending `knowledge_bases` or `runtime_knowledge_bases` answers `403`. Every user of the agent searches the same knowledge bases, so don't attach a knowledge base holding one user's private documents to a shared agent. Use Recipe 1 or Option B for per-user retrieval.

Creating the agent, attaching its tools and knowledge bases, and uploading sources stay on your backend with the Service Role key.

### Option B: your backend runs the agent

When a run needs something an end user can't send, such as knowledge bases chosen per request or `context_items` your backend filtered (Recipe 1), run it from your backend with the Service Role key. Create the session with the user's `user_id`, so the conversation still belongs to them: they can list and read it with their own token.

```typescript theme={null}
// Backend route. Express-style for illustration.
const serviceHeaders = {
  apikey: SERVICE_ROLE_KEY,
  Authorization: `Bearer ${SERVICE_ROLE_KEY}`,
  "Content-Type": "application/json",
};

app.post("/api/chat", requireUserAuth, async (req, res) => {
  const { userId } = req.user;  // from your own auth middleware
  const { message, sessionId } = req.body;
  const agentId = await getAgentForUser(userId);

  // First turn: create a session owned by this user. Only the Service Role
  // key may set user_id. On later turns, check the session is this user's
  // before using it: a service-role run can continue any session.
  const sid = sessionId && (await sessionBelongsTo(sessionId, userId))
    ? sessionId
    : (await (await fetch(`${POWABASE_URL}/api/agents/${agentId}/sessions`, {
        method: "POST",
        headers: serviceHeaders,
        body: JSON.stringify({ user_id: userId }),
      })).json()).session_id;

  const agentRes = await fetch(`${POWABASE_URL}/api/agents/${agentId}/run/stream`, {
    method: "POST",
    headers: serviceHeaders,
    body: JSON.stringify({
      message,
      session_id: sid,
      // Service-role runs may set knowledge_bases or context_items here.
      // See Recipe 1 for user-scoped context_items.
    }),
  });

  // Forward the SSE stream to the client.
  res.setHeader("Content-Type", "text/event-stream");
  res.setHeader("Cache-Control", "no-cache");
  res.setHeader("Connection", "keep-alive");
  agentRes.body.pipe(res);
});
```

The client never sees the Service Role key; only your backend does. Your backend decides who may call `/api/chat` and which session they may continue.

> [!WARNING]
>
> A run your backend starts with the Service Role key is a service-role run, even in a session owned by the user. The agent's database tools use its own database login, which bypasses RLS on its configured tables, and its storage tools see every bucket except the internal `sources` bucket. Give an Option B agent data tools only over tables and buckets every user it serves may see in full, or use Option A for agents that carry data tools. If such a run pauses for approval, only the Service Role key can approve it, so relay the user's decision through your backend.

### Adding a Custom Tool that's user-aware

On Option A runs, the builtin database tools already act as the user. For user-specific data that lives outside this project's Postgres, or for agents run from your backend (Option B), register a Custom HTTP Tool that points at your own backend:

```bash theme={null}
POST /api/tools
{
  "name": "search_user_articles",
  "description": "Searches the user's saved articles for relevant content.",
  "type": "http",
  "input_schema": {
    "type": "object",
    "properties": {
      "query": { "type": "string" },
      "session_token": { "type": "string" }
    },
    "required": ["query", "session_token"]
  },
  "config": {
    "endpoint": "https://your-app.example.com/internal/tools/search-articles",
    "method": "POST"
  }
}
```

Then in your backend's `/internal/tools/search-articles` handler:

```typescript theme={null}
app.post("/internal/tools/search-articles", async (req, res) => {
  const { query, session_token } = req.body;

  // Look up the user from your opaque session_token — NOT from any header
  // because the platform doesn't forward auth to custom tools.
  const userId = await sessionStore.lookup(session_token);
  if (!userId) return res.status(401).end();

  // Now run the query against your DB with the user's identity applied.
  const results = await db.searchArticles(userId, query);
  res.json({ results });
});
```

The pattern: pass an opaque `session_token` through the tool's arguments at call time. Your backend resolves it to the user identity and gates the query. The agent doesn't know who the user is; your backend does.

The system prompt for the agent includes "always call `search_user_articles` with `session_token = <token>`." You inject the current user's token into the system prompt at agent-run-time, server-side. From the agent's perspective, the token is opaque data it passes through.

Custom HTTP tools send only the headers configured on the tool, never the caller's token, which is why the identity travels as an argument your backend resolves.

## Recipe 3: Storage vs ai.sources

You have a multi-format app: users upload PDFs that need to be indexed for RAG, plus they upload images for display. Two distinct flows.

**For files that need to enter the RAG pipeline (PDFs, docs, anything you want chunked + embedded):**

* Upload via `POST /api/sources/upload` (the typed Sources endpoint).
* The platform creates a row in `ai.sources`, stores the file in a platform-managed Storage bucket, dispatches the extraction Celery task, and returns the source id.
* Add the source to a KB via `POST /api/knowledge-bases/{id}/sources` to trigger indexing.

**For files that are user content displayed back to the user (avatars, gallery images, attachments):**

* Upload via `POST /storage/v1/object/{bucket}/{path}` (the typed Storage endpoint).
* The file lands in `storage.objects` under your own bucket. Your application code reads/displays it.

The two flows use different buckets, different tables (`ai.sources` vs `storage.objects`), and have different RLS postures. **Don't try to share buckets between them.** The platform assumes ownership of its Sources bucket layout and will overwrite paths.

For files that need to be both (e.g., a PDF the user uploaded that they should be able to download AND that's indexed for RAG): upload twice, once through each path. They're independent: one row in `storage.objects` (for download) and one row in `ai.sources` (for indexing). Or pick one path, upload to `ai.sources`, and use the platform's pre-signed download URL for the user-facing download.

A worked end-to-end flow for an "upload a PDF, then chat with it" pattern:

```typescript theme={null}
// Runs on your backend: the Sources and knowledge-base routes require the
// Service Role key, so the browser sends the file to you, not to Powabase.
async function uploadAndChat(file: Blob, userId: string) {
  // Step 1: Upload to Sources (will be indexed).
  const sourceRes = await fetch(`${BASE_URL}/api/sources/upload`, {
    method: "POST",
    headers: {
      apikey: SERVICE_ROLE_KEY,
      Authorization: `Bearer ${SERVICE_ROLE_KEY}`,
    },
    body: (() => {
      const fd = new FormData();
      fd.append("file", file);
      return fd;
    })(),
  });
  const { id: sourceId } = await sourceRes.json();

  // Step 2: Record ownership (so RLS can scope future reads)
  await postgrest("documents", { source_id: sourceId, owner_id: userId });

  // Step 3: Poll for extraction completion (see Sources Reference for shape)
  await pollUntilExtracted(sourceId);

  // Step 4: Add to a user-specific KB
  const kbId = await getUserKb(userId);
  await fetch(`${BASE_URL}/api/knowledge-bases/${kbId}/sources`, {
    method: "POST",
    headers: { apikey: SERVICE_ROLE_KEY, Authorization: `Bearer ${SERVICE_ROLE_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({ source_id: sourceId }),
  });

  // Step 5: Chat about the PDF. The KB is chosen per user, so this is an
  // Option B run from Recipe 2: Service Role key, knowledge_bases in the run
  // body, in a session created with this user's user_id.
  return runChat(kbId, userId);
}
```

`public.documents` is your own table for "who owns which source." `ai.sources` is the platform's table; `public.documents.source_id` references it for the ownership graph.

## Recipe 4: Realtime + agent runs

For showing live progress during agent runs: the agent SSE stream is one event source, but if you want UI updates to reach other devices too (the user's phone watching while their laptop runs the chat), Realtime is the right second channel.

Two patterns:

**Pattern 4a: Mirror the SSE stream to a Realtime channel.** Your backend receives the SSE stream from `/api/agents/{id}/run/stream`, persists each event to a row in a `public.chat_messages` table, AND re-broadcasts each event to a per-user Realtime channel. Clients subscribe to the channel for live updates.

```typescript theme={null}
async function streamAndBroadcast(agentId: string, userId: string, message: string) {
  // Open the agent SSE stream
  const agentRes = await fetch(`${POWABASE_URL}/api/agents/${agentId}/run/stream`, { ... });
  const reader = agentRes.body!.getReader();

  // The Realtime topic this user is subscribed to
  const topic = `chat:${userId}`;

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    const text = decoder.decode(value);
    for (const line of text.split("\n")) {
      if (!line.startsWith("data: ")) continue;
      const event = JSON.parse(line.slice(6));

      // Persist for chat history
      if (event.event === "chunk" || event.event === "complete") {
        await db.chatMessages.insert({ user_id: userId, payload: event });
      }

      // Broadcast for live UIs
      await broadcast({
        topic,
        event: event.event,
        payload: event,
      });
    }
  }
}
```

**Pattern 4b: Use a database trigger.** Insert each agent event into `public.chat_messages`; a trigger function calls `realtime.send()` to broadcast it. The application code doesn't need to call Realtime explicitly; the database side-effect drives the broadcast.

```sql theme={null}
CREATE OR REPLACE FUNCTION broadcast_chat_message()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
  PERFORM realtime.send(
    payload  => jsonb_build_object('message_id', NEW.id, 'event', NEW.payload),
    event    => 'chat_event',
    topic    => 'chat:' || NEW.user_id::text,
    private  => true
  );
  RETURN NEW;
END;
$$;

CREATE TRIGGER chat_realtime
  AFTER INSERT ON public.chat_messages
  FOR EACH ROW EXECUTE FUNCTION broadcast_chat_message();
```

Pair this with the matching RLS on `realtime.messages` (so only the user themselves can subscribe to their channel) and you have device-syncing chat, gated by the same auth model as the rest of the app. See [Realtime model](https://docs.powabase.ai/concepts/realtime.md) for the function reference.

## Next steps

> [card] [AI resource recipes](https://docs.powabase.ai/guides/ai-schema-recipes.md)
>
> Typed /api/\* patterns for multi-KB search, usage summaries and bulk source updates.

> [card] [RLS Cookbook](https://docs.powabase.ai/guides/rls-policies.md)
>
> The lower-level RLS patterns these recipes build on.

> [card] [Billing model](https://docs.powabase.ai/concepts/billing-model.md)
>
> What every agent run and workflow execution costs in credits.

> [card] [Realtime subscriptions](https://docs.powabase.ai/guides/realtime-subscriptions.md)
>
> Detailed Realtime patterns the recipe-4 broadcast is one application of.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.