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:
ai.status(): non-throwing status probe before the user acts. Resolves to:{ ready: boolean, provider: "chatgpt" | "api_key" | "stub" | null, email?: string | null, code?: string, message?: string, fix?: string, url?: string, manageUrl?: string, capabilities: { vision, pdf, webSearch, webSearchWithTools, jsonSchema, tools }, tiers: { fast, balanced, deep }, contextWindow: number, }ai.stream(req): returns an async iterable of events and never throws: both pre-flight failures and mid-stream disconnects or aborts yield a terminalerrorevent.ai.run(req): awaitsai.stream(req)to completion and returns{ text, data?, sources, calls, messages, usage }, throwing anErrorwithcode,fix,url,retryable,partialText,sources, andmessageson failure.
Request options and Message shapes
Both ai.stream(req) and ai.run(req) accept:
prompt(string) ormessages(array of conversation messages):- User message:
{ role: "user", content: string, files?: [...] } - Assistant message:
{ role: "assistant", content: string, calls?: [{ id, name, input }] } - Tool result message:
{ role: "tool", callId: string, name: string, result: json, isError?: boolean }
- User message:
system: optional system prompt string.files: array offiles.put()refs (fileorfile.id) or browserFile/Blobobjects (when usingprompt).schema: OpenBelt JSON Schema for strict structured JSON output (returned asdata).functions: explicit allowlist of this app's callable function names.toolChoice:"auto" | "required" | "<functionName>"(applies to step 0, then resets to"auto").maxSteps: maximum reasoning/tool steps (default5, max20).webSearch: boolean (requires"ai": { "webSearch": true }inopenbelt.json).tier:"fast" | "balanced" | "deep", ormodel(explicit model string).signal:AbortSignalto cancel streaming or an in-flightonToolCallprompt.onToolCall: async approval hook(call, { signal }) => "run" | { run: editedInput } | "deny" | { deny: string }.connectPrompt: setfalseto suppress OpenBelt's automatic connect sheet onneeds_token.
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.
Streaming text and web search
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):
{ type: "step", index }: start of each reasoning or tool step.{ type: "status", stage, detail? }:"thinking" | "searching" | "calling_tool".{ type: "delta", text }: streamed text chunk.{ type: "source", title, url }: deduplicated web citation.{ type: "tool_call", id, name, input, readOnly }: model requested an app function.{ type: "tool_result", id, name, result, isError }: function result, or{ denied: true, reason }withisError: truewhen denied.{ type: "done", text, data?, sources, calls, messages, usage }: terminal success.{ type: "error", code, message, fix?, url?, retryable, partialText, sources, messages, usage? }: terminal failure or abort.
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
}
toolChoice("auto" | "required" | "<functionName>") applies to step 0 and automatically resets to"auto"on later steps so forced tool calls cannot infinite-loop.- Combine
schemawithfunctionsorwebSearchfreely: OpenBelt routes the final structured answer transparently and validates it against yourschema.
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 })
}
ctx.ai.runresolves the app's uploaded file IDs directly on the server and records an external effect so a DB conflict never silently re-runs a spent AI call.- Queries (
"kind": "query") cannot callctx.ai.run. Read-only checks (check_appwithreadonly: trueon a live app) block both browserai.stream/ai.run(POST /_ai/step) andctx.ai.rununlessOPENBELT_AI_STUB=on; test AI flows in a preview environment. - If the viewer has not connected an AI provider yet,
ctx.ai.runfails withcode: "needs_token"and a connecturl, anddb.fn(...)automatically opens the connect sheet on the page.
Credentials and errors
OpenBelt resolves credentials per viewer in this order:
OPENBELT_AI_STUB=on: deterministic offline stub forcheck_appand tests.- The viewer's own Sign in with ChatGPT connection (
/_ai/connect, also linked from/settings), kept private per person. - Operator-configured
OPENBELT_AI_API_KEY(with optionalOPENBELT_AI_BASE_URLandOPENBELT_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).
| Deployment | How 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-hosted | Each 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