AI

Apps can stream text, extract structured JSON from images or PDFs, search the web with citations, and let a model call the app's own functions without storing API keys in the app or writing provider glue.

Enable AI in openbelt.json

Add "ai": true to openbelt.json, or { "webSearch": true } if the app also needs live web search:

{
  "description": "Receipt scanner and research helper",
  "ai": { "webSearch": true },
  "functions": {
    "listTasks": {
      "description": "Lists open tasks",
      "kind": "query"
    },
    "createTask": {
      "description": "Creates a task",
      "input": {
        "type": "object",
        "properties": { "title": { "type": "string" } },
        "required": ["title"]
      }
    }
  }
}

Browser SDK: ai.stream, ai.run, ai.status

Import ai from /sdk.js. It exposes three functions:

Request options and Message shapes

Both ai.stream(req) and ai.run(req) accept:

ev.messages on done and error contains only the newly committed messages produced during this call (excluding your input prompt/messages), so multi-turn chats append them directly: history.push(userMsg, ...ev.messages). If aborted while paused in onToolCall, the uncommitted tool call is omitted so history never holds an unpaired tool call.

import { ai } from "/sdk.js"

const controller = new AbortController()
const userMsg = { role: "user", content: "What are the latest Bun release highlights?" }
let text = ""
const sources = []

for await (const ev of ai.stream({
  messages: [...history, userMsg],
  system: "Answer concisely with citations.",
  webSearch: true,
  tier: "fast",
  signal: controller.signal,
})) {
  if (ev.type === "status") setStatus(ev.detail ?? ev.stage)
  if (ev.type === "delta") {
    text += ev.text
    render(text)
  }
  if (ev.type === "source") {
    sources.push(ev)
    renderSources(sources)
  }
  if (ev.type === "done") history.push(userMsg, ...ev.messages)
  if (ev.type === "error") showError(ev.code, ev.message, ev.url)
}

Events emitted by ai.stream(req):

Structured JSON and files (vision / PDF)

Pass schema (OpenBelt JSON Schema) to validate structured output, and files with either uploaded files.put() refs (file or file.id) or ephemeral browser File/Blob objects:

import { ai, files } from "/sdk.js"

const uploaded = await files.put(input.files[0])
const { data } = await ai.run({
  prompt: "Extract merchant, date, and total in integer cents.",
  files: [uploaded],
  schema: {
    type: "object",
    properties: {
      merchant: { type: "string" },
      date: { type: "string" },
      totalCents: { type: "integer" },
    },
    required: ["merchant", "totalCents"],
  },
})

App functions as tools and human approval

Pass an explicit allowlist of your app's callable function names in functions: [...]. OpenBelt generates strict tool schemas from openbelt.json, runs each approved call via db.fn, and continues the multi-step loop automatically.

Use onToolCall(call, { signal }) to gate writes or let the user edit arguments before execution (call is { id, name, input, readOnly }):

for await (const ev of ai.stream({
  messages,
  functions: ["listTasks", "createTask"],
  onToolCall: async (call, { signal }) => {
    if (call.readOnly) return "run"
    return await askUserToApprove(call, signal) // "run" | { run: editedInput } | "deny" | { deny: "reason" }
  },
})) {
  // handle delta, tool_call, tool_result, done, error
}

Server functions: ctx.ai

Inside functions/<name>.js, use ctx.ai.run(req) and ctx.ai.status():

// functions/extractReceipt.js
export default async ({ fileId }, { db, ai }) => {
  const { data } = await ai.run({
    prompt: "Extract merchant and totalCents from this receipt.",
    files: [fileId],
    schema: {
      type: "object",
      properties: {
        merchant: { type: "string" },
        totalCents: { type: "integer" },
      },
      required: ["merchant", "totalCents"],
    },
  })
  return await db.collection("receipts").add({ fileId, ...data })
}

Credentials and errors

OpenBelt resolves credentials per viewer in this order:

  1. OPENBELT_AI_STUB=on: deterministic offline stub for check_app and tests.
  2. The viewer's own Sign in with ChatGPT connection (/_ai/connect, also linked from /settings), kept private per person.
  3. Operator-configured OPENBELT_AI_API_KEY (with optional OPENBELT_AI_BASE_URL and OPENBELT_AI_MODEL_FAST / OPENBELT_AI_MODEL_BALANCED / OPENBELT_AI_MODEL_DEEP).

Signed-out visitors never fall back to OPENBELT_AI_API_KEY: ai.status() returns { ready: false, code: "signed_out" }, and ai.stream / ai.run return needs_token.

When a signed-in viewer has no credentials yet, ai.stream / ai.run automatically pops OpenBelt's connect sheet (pass connectPrompt: false to render your own link using ev.url or status.url).

Hosted prod vs tailnet and local

Credentials never cross instances: connecting ChatGPT on a local or tailnet OpenBelt instance stays sealed in that instance's SQLite data and does not apply to hosted openbelt.com (or vice versa).

DeploymentHow AI credentials work
Local (bun run dev)Sign in with ChatGPT at /_ai/connect redirects back to 127.0.0.1 automatically, or set OPENBELT_AI_API_KEY.
Tailnet / self-hostedEach tailnet member connects their own ChatGPT subscription at /_ai/connect (via /settings): ChatGPT redirects to 127.0.0.1, and pasting that callback URL into /_ai/connect finishes sign-in. Optional OPENBELT_AI_API_KEY works as a member fallback.
Hosted prod (openbelt.com)Uses operator-configured OPENBELT_AI_API_KEY for signed-in workspace members, or Sign in with ChatGPT once the deployment's public callback URL is registered as an OpenAI partner client (until then, /_ai/connect uses the paste-callback flow). Public anonymous visitors never consume operator keys.

Error codes: needs_token, needs_consent, not_allowed, unsupported_feature, quota_exceeded, rate_limited, context_too_long, refused, invalid_output, aborted, stream_interrupted, provider_error, check_readonly.

Source: docs/ai.md on GitHub