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

# AI resource recipes

> Worked examples for the jobs people used to do with PostgREST on ai.*: searching several knowledge bases, agent usage summaries, bulk-tagging sources, and per-KB source reports, all through the typed /api/* endpoints.

The `ai` schema is backend-only (see [The ai schema](https://docs.powabase.ai/concepts/ai-schema-postgrest.md)). It isn't exposed through PostgREST, so `/rest/v1/*` requests with `Accept-Profile: ai` or `Content-Profile: ai` are rejected whichever key you use. Earlier versions of this page queried `ai.*` that way; those examples no longer work.

These recipes do the same jobs through the typed `/api/*` endpoints. Where the typed surface has no equivalent, the recipe says so.

All examples assume the Service Role (Secret) Key from the Connect modal and these headers:

```python theme={null}
headers = {
    "apikey": API_KEY,
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json",
}
```

> [!NOTE]
>
> **Call these from a trusted backend with the Service Role key.** They touch project-wide data, and the routes they use (knowledge bases, sources, agents) answer a signed-in user's JWT with `403`. If you expose any of this to end users, put it behind your own API. See [Which key for which route](https://docs.powabase.ai/guides/auth-connection.md#which-key-for-which-route).

## Recipe 1: Search across several knowledge bases

`POST /api/knowledge-bases/{id}/search` searches one knowledge base. To search several, call it once per KB and merge the results. Each call can narrow its results with `filter_metadata` (fields from the KB's [enrichment config](https://docs.powabase.ai/api-reference/knowledge-bases.md#metadata-enrichment)) and `source_ids`.

```python Python theme={null}
import requests

KB_IDS = ["kb-uuid-1", "kb-uuid-2"]

results = []
for kb_id in KB_IDS:
    response = requests.post(
        f"{BASE_URL}/api/knowledge-bases/{kb_id}/search",
        headers=headers,
        json={
            "query": "refund policy for annual plans",
            "top_k": 10,
            "retrieval_method": "hybrid",
            "filter_metadata": {"topic": "billing"},
        },
    )
    response.raise_for_status()
    for hit in response.json()["results"]:
        results.append({**hit, "knowledge_base_id": kb_id})

results.sort(key=lambda r: r["score"], reverse=True)
for row in results[:20]:
    print(f"[KB {row['knowledge_base_id'][:8]}] score={row['score']:.3f}")
    print(row["text"][:200])
```

```typescript TypeScript theme={null}
const kbIds = ["kb-uuid-1", "kb-uuid-2"];

const perKb = await Promise.all(
  kbIds.map(async (kbId) => {
    const res = await fetch(`${BASE_URL}/api/knowledge-bases/${kbId}/search`, {
      method: "POST",
      headers,
      body: JSON.stringify({
        query: "refund policy for annual plans",
        top_k: 10,
        retrieval_method: "hybrid",
        filter_metadata: { topic: "billing" },
      }),
    });
    const { results } = await res.json();
    return results.map((hit: any) => ({ ...hit, knowledge_base_id: kbId }));
  }),
);

const merged = perKb.flat().sort((a, b) => b.score - a.score).slice(0, 20);
for (const row of merged) {
  console.log(`[KB ${row.knowledge_base_id.slice(0, 8)}] score=${row.score.toFixed(3)}`);
  console.log(row.text.slice(0, 200));
}
```

```bash cURL theme={null}
# One call per knowledge base; merge the results in your code.
curl -X POST '{BASE_URL}/api/knowledge-bases/kb-uuid-1/search' \
  -H "apikey: {API_KEY}" \
  -H "Authorization: Bearer {API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{"query": "refund policy for annual plans", "top_k": 10, "retrieval_method": "hybrid", "filter_metadata": {"topic": "billing"}}'
```

Each result has `chunk_id`, `text`, `score`, `source_id` and `meta`. Scores are only comparable across knowledge bases when every call uses the same `retrieval_method`, so set it explicitly rather than relying on each KB's default. To search inside specific documents, pass their source ids in `source_ids`.

## Recipe 2: Agent usage summary

`GET /api/agents` returns, for each agent, `total_runs`, `session_count` and `last_run_at`. It pages at up to 100 agents per request, and you can sort by `last_run_at`.

```python Python theme={null}
agents, offset = [], 0
while True:
    page = requests.get(
        f"{BASE_URL}/api/agents",
        headers=headers,
        params={"sort": "last_run_at", "order": "desc", "limit": 100, "offset": offset},
    ).json()
    agents.extend(page["agents"])
    offset += len(page["agents"])
    if not page["agents"] or offset >= page["total"]:
        break

for a in agents:
    print(f"{a['name']:30s} runs={a['total_runs']:5d} sessions={a['session_count']:4d} last={a['last_run_at']}")
```

```typescript TypeScript theme={null}
const agents: any[] = [];
let offset = 0;
while (true) {
  const params = new URLSearchParams({ sort: "last_run_at", order: "desc", limit: "100", offset: String(offset) });
  const page = await (await fetch(`${BASE_URL}/api/agents?${params}`, { headers })).json();
  agents.push(...page.agents);
  offset += page.agents.length;
  if (page.agents.length === 0 || offset >= page.total) break;
}

for (const a of agents) {
  console.log(`${a.name.padEnd(30)} runs=${a.total_runs} sessions=${a.session_count} last=${a.last_run_at}`);
}
```

```bash cURL theme={null}
curl '{BASE_URL}/api/agents?sort=last_run_at&order=desc&limit=100' \
  -H "apikey: {API_KEY}" \
  -H "Authorization: Bearer {API_KEY}"
```

These counts cover all time. The documented `/api/*` surface has no endpoint that aggregates runs or token usage over a time window; for that, use the Studio's Observability page (see [Observability](https://docs.powabase.ai/concepts/observability.md)). Defining your own SQL function in `ai` and calling it through `/rest/v1/rpc/*` doesn't work either, because PostgREST doesn't expose that schema.

## Recipe 3: Bulk-tag sources

There's no bulk update endpoint for sources. Call `PATCH /api/sources/{id}` once per source.

`metadata` in the PATCH body **replaces** the source's whole metadata object; it doesn't merge. To add one key without losing the others, read the current metadata with `GET /api/sources/{id}` first. The reserved keys `extraction_model`, `source_type` and `source_url` are dropped from the body, because the platform keeps those in `auto_metadata`.

```python Python theme={null}
SOURCE_IDS = ["uuid-1", "uuid-2", "..."]

updated = 0
for source_id in SOURCE_IDS:
    current = requests.get(f"{BASE_URL}/api/sources/{source_id}", headers=headers).json()
    merged = {**(current.get("metadata") or {}), "tag": "q3-2025"}
    response = requests.patch(
        f"{BASE_URL}/api/sources/{source_id}",
        headers=headers,
        json={"metadata": merged},
    )
    if response.ok:
        updated += 1
print(f"Updated {updated} of {len(SOURCE_IDS)} sources")
```

```typescript TypeScript theme={null}
const sourceIds = ["uuid-1", "uuid-2" /* ... */];

let updated = 0;
for (const sourceId of sourceIds) {
  const current = await (await fetch(`${BASE_URL}/api/sources/${sourceId}`, { headers })).json();
  const merged = { ...(current.metadata ?? {}), tag: "q3-2025" };
  const res = await fetch(`${BASE_URL}/api/sources/${sourceId}`, {
    method: "PATCH",
    headers,
    body: JSON.stringify({ metadata: merged }),
  });
  if (res.ok) updated++;
}
console.log(`Updated ${updated} of ${sourceIds.length} sources`);
```

```bash cURL theme={null}
# Per source. This replaces the whole metadata object.
curl -X PATCH '{BASE_URL}/api/sources/uuid-1' \
  -H "apikey: {API_KEY}" \
  -H "Authorization: Bearer {API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{"metadata": {"author": "alice", "tag": "q3-2025"}}'
```

For a few hundred sources, run the calls with modest concurrency (5 to 10 at a time) rather than strictly one after another.

## Recipe 4: Per-KB source report

For a "what's in this knowledge base and is it healthy" report, `GET /api/knowledge-bases/{id}/sources` joins each indexed source with its source row. Each item carries `index_status`, `indexed_at`, `error_message`, `source_name` and `file_type`. It pages at up to 200 rows and filters by `status` and name substring (`q`).

```python Python theme={null}
from collections import Counter

KB_ID = "kb-uuid"

items, offset = [], 0
while True:
    page = requests.get(
        f"{BASE_URL}/api/knowledge-bases/{KB_ID}/sources",
        headers=headers,
        params={"sort": "name", "order": "asc", "limit": 200, "offset": offset},
    ).json()
    items.extend(page["items"])
    offset += len(page["items"])
    if not page["items"] or offset >= page["total"]:
        break

print(Counter(i["index_status"] for i in items))
print(Counter(i["file_type"] for i in items))
for i in items:
    if i["index_status"] == "failed":
        print(f"{i['source_name']}: {i['error_message']}")
```

```typescript TypeScript theme={null}
const kbId = "kb-uuid";

const items: any[] = [];
let offset = 0;
while (true) {
  const params = new URLSearchParams({ sort: "name", order: "asc", limit: "200", offset: String(offset) });
  const page = await (await fetch(`${BASE_URL}/api/knowledge-bases/${kbId}/sources?${params}`, { headers })).json();
  items.push(...page.items);
  offset += page.items.length;
  if (page.items.length === 0 || offset >= page.total) break;
}

const byStatus: Record<string, number> = {};
for (const i of items) byStatus[i.index_status] = (byStatus[i.index_status] ?? 0) + 1;
console.log(byStatus);
for (const i of items.filter((i) => i.index_status === "failed")) {
  console.log(`${i.source_name}: ${i.error_message}`);
}
```

```bash cURL theme={null}
curl '{BASE_URL}/api/knowledge-bases/kb-uuid/sources?sort=name&order=asc&limit=200' \
  -H "apikey: {API_KEY}" \
  -H "Authorization: Bearer {API_KEY}"
```

The documented endpoints don't return per-source chunk counts, so the old "rank sources by chunk count" query has no `/api/*` equivalent.

## Next steps

> [card] [The ai schema](https://docs.powabase.ai/concepts/ai-schema-postgrest.md)
>
> Why ai.\* is backend-only, and what the typed surface enforces.

> [card] [Knowledge Bases Reference](https://docs.powabase.ai/api-reference/knowledge-bases.md)
>
> Search, source listing, enrichment and metadata filters.

> [card] [Sources Reference](https://docs.powabase.ai/api-reference/sources.md)
>
> Upload, update and re-extract sources.

> [card] [Agents Reference](https://docs.powabase.ai/api-reference/agents.md)
>
> Agents, runs and sessions.


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