@softr/sdk
ai
>-
Boundary. ai lives on @softr/sdk/server and runs only inside a createServerFn handler — importing it into a component fails the build. defineAiAction and every type come from @softr/sdk and can be imported anywhere.
AI
An app asks a model through an AI action. Softr runs the call on its own provider keys and bills the workspace's AI credits, so there is no key to ask the user for and nothing to connect. This is the default for every AI feature of the app's own — a summary of a record, fields extracted from a document, a classification, a draft, a chat. The other path is the user's own provider account, through a connected integration: the integrations sub-skill. An app can hold both: each feature carries its own choice in its code.
Decide who runs it first
Never choose silently between Softr AI and the user's own account. Decide for each AI feature, before you write its code, in this order:
- The user said who runs it: follow it. "My OpenAI key" or "our Anthropic account", with exactly one integration of that type in integration_list: use that one, without asking. A new key of a provider they named — they asked for a new one, or the workspace holds none of that type — is one requestinput of type integration for that type: its card connects one. A connected key runs the feature; a skipped request means Softr AI, and you say so. Several keys of that type, or "my own key" with no provider: ask (step 4). A provider or a model named without "my" or "our" ("use Claude", "summarise with GPT") is a model preference on Softr AI, not a reason to ask.
- The app already has AI features: follow the choice they made, and say so in one line.
- integration_list shows no OPEN_AI, ANTHROPIC_AI or GEMINI_AI integration: use Softr AI, and say so in one line. Call the tool; do not assume the answer.
- Otherwise ask with one requestinput of type aiProvider. Its card lists every key the workspace holds and every provider to connect, unfiltered. The answer is Softr AI, or the integration with its id and type: follow it, even when it is another provider than the one the user named. A declined request means Softr AI: use it, and say so in one line.
Never ask who runs a feature, or which key, with the question tool: its free-text answer invites the user to type a key into the chat.
Ask at most once per turn. A turn that builds several AI features sends one request, and its feature names every one of them in the user's words: "Deal summary and lead tagging". It holds the names only, never the provider, the key or how the feature runs, because the card asks exactly that: "Product chat", not "Product chat, using an OpenAI key".
An own-account answer leaves this skill: the call goes through defineIntegration, as the integrations sub-skill describes.
Choose the model
The model is chosen when the app is built and frozen in its code. Before you declare an action, read Softr's catalog with the ai_list_models tool: the most recent models of each provider. Each entry carries the id the action names, the provider, bestFor, what to pick it for, reads, what it reads beside text, and reasoning, whether it thinks before it answers. (providerModelId is for the own-account path of the integrations sub-skill, never for defineAiAction.)
- by default — a chat, an assistant, a summary, a briefing, a draft: a mid-tier model, anthropic's newest one between its cheapest and strongest. When the user named another provider, that provider's mid-tier model;
- an extraction or a classification: the cheapest model whose reads covers what it is given — an image or a PDF needs IMAGE;
- the strongest model listed only when the user asks for more quality.
Copy the id exactly from the tool's answer. An id outside the catalog is refused when the action is saved, and a model spelled from memory, or taken from an example, never is in it.
Changing it later
A model change asked in chat ("use a cheaper model", "try Gemini") edits the model of the feature's action, or, on the user's own account, the providerModelId its call sends. Read ai_list_models again and copy the new id. It never sends an aiProvider request. On the user's own account the new model is one of that account's provider: a model of another provider, or a switch to the user's own key, changes who runs it, so follow step 1 of the order above.
Say it
The plan and the closing message give one line per AI feature built or changed: who runs it, its model, what it bills — Softr AI uses the workspace's AI credits, the user's own key is billed by its provider — and that the user can ask to switch the model or to use their own OpenAI, Anthropic or Gemini key. For example: "Deal summary runs on Softr AI with
Declare the action
const summarizeDeal = defineAiAction({
id: 'summarizeDeal',
model: '<an id from ai_list_models>',
permissions: { userGroupTypes: ['LOGGED_IN_USERS'] },
})Write the object inline in defineAiAction. Passing it through a variable widens the types.
Every call spends the workspace's credits. Keep the audience to ['LOGGED_IN_USERS'], narrowed with customGroups where the feature is for some users only. Open an AI action to visitors only when a public page really needs it, and say so to the user: anyone on the internet can then bill the workspace.
Declare one action per feature — the summary and the extraction are two actions, each with its own id, its own model and its own audience.
Core pattern: an answer the server reads
ai.generate(action, init) runs the action and answers when the model is done. init takes:
- prompt — what the model is asked, with the facts it is given. Required.
- system — what the model is and the rules it answers under.
- schema — a JSON schema the answer has to match. With it the model is asked for JSON only, and the answer comes back parsed in json as well as written in text.
- files — documents and images the model reads, each as { url, mimeType? }: an https URL Softr may fetch, one of the app's own uploads as a rule.
- maxOutputTokens — a cap on the answer's length. Softr caps it further.
- messages — the earlier turns of a conversation, oldest first, each { role: 'user' | 'assistant', content }. The prompt is the newest turn. Leave out for a one-shot call.
- reasoning — 'low', 'medium' or 'high': how hard a reasoning model thinks before it answers. The catalog says which models reason; the others ignore it. Leave out for the provider's default.
- temperature — 0 to 1: how varied the answer is. 0 for an extraction or a classification, around 0.7 for a draft. Left out, the provider's default applies. A model whose provider no longer takes one, such as the Claude 5 models, ignores it.
The answer is { text, json, usage, model }: text as the model wrote it, json parsed when a schema was given and the model kept to it, null otherwise.
const summarize = createServerFn({ method: 'POST' })
.validator(z.object({ recordId: z.string() }))
.handler(async ({ data }) => {
const deal = await ds.get(dealQuery, { id: data.recordId })
if (deal === null) throw new Error('This deal no longer exists')
const facts = [`Name: ${fieldText(deal.fields.name)}`, `Stage: ${fieldText(deal.fields.stage)}`].join('\n')
const answer = await ai.generate(summarizeDeal, {
system: 'You brief a sales team. Use only the facts given; say what is missing rather than invent it.',
prompt: facts,
maxOutputTokens: 800,
})
return answer.text
})The record id comes from the browser, so it can name any deal. dealQuery takes the table's filter, like every other query of the table. Where reps see only their own deals, a query without it briefs anyone on any deal: see record-queries.
Extraction: an answer that is data
A document dropped on the app, fields pulled out of it, a record created — the model reads the file and answers in the shape the record needs. Give it the schema and the file; validate the parsed answer before writing it, since a model may stray from the shape.
const InvoiceFields = z.object({ vendor: z.string(), total: z.number(), issuedOn: z.string() })
const extractInvoice = createServerFn({ method: 'POST' })
.validator(z.object({ fileUrl: z.string().url() }))
.handler(async ({ data }) => {
const answer = await ai.generate(readInvoice, {
system: 'Read the invoice and answer with its fields. Dates as YYYY-MM-DD, amounts as numbers.',
prompt: 'Extract the vendor, the total and the issue date.',
schema: {
type: 'object',
properties: { vendor: { type: 'string' }, total: { type: 'number' }, issuedOn: { type: 'string' } },
required: ['vendor', 'total', 'issuedOn'],
},
files: [{ url: data.fileUrl, mimeType: 'application/pdf' }],
})
const parsed = InvoiceFields.safeParse(answer.json)
if (!parsed.success) throw new Error('The invoice could not be read. Try a clearer scan.')
return ds.create(createInvoice, { data: parsed.data })
})The file's URL comes from the app's own upload: load the Softr SDK file-uploads guidance for that half. readInvoice names a model whose bestFor reads PDF documents.
Streaming: an answer the user watches being written
A chat, an assistant, a long draft shown as it is typed — never buffer these: the user would watch a blank panel until the last token. A chat box the user types into is always this case, never ai.generate. ai.stream(action, init) takes the same init and answers with a Response whose body is a stream of Server-Sent Events. Hand it to the browser from the server function, unchanged:
const draftReply = createServerFn({ method: 'POST' })
.validator(z.object({ prompt: z.string() }))
.handler(async ({ data }) => {
const res = await ai.stream(draftAction, { system: 'You write replies for a support team.', prompt: data.prompt })
return new Response(res.body, { headers: { 'Content-Type': 'text/event-stream' } })
})Each event is one JSON object on a data: line:
- { "text": "..." } — the next piece of the answer; append it.
- { "done": true, "usage": { "inputTokens", "outputTokens" }, "model": "..." } — the answer is complete.
- { "error": "..." } — in place of done, when the call ended before its answer: show the message.
On the client, call the server function's URL with fetch, read response.body with a stream reader, split on blank lines, and parse the JSON after data:. A conversation sends its earlier turns in messages; the app keeps them, the model holds nothing between calls.
Failure modes
Calling from client code. ai is server-only. Importing it into a component or calling it outside a createServerFn handler fails the build or has no request context to act on.
Spelling a model id. model is copied from ai_list_models, never written from memory. An id outside the catalog fails the save of the action, so the app cannot be published with it.
No credits left. ai.generate and ai.stream throw an AiError whose status is 402 when the workspace has no AI credits. Show its message to the user; the workspace owner tops the credits up in Softr. Any other refusal carries its status and reason the same way.
Trusting json without checking it. A model may stray from the schema; json is then null, or a shape close to the one asked. Validate it with zod before writing it to a record, and keep text as the fallback the user can read.
Buffering a chat. A chat built on ai.generate shows nothing until the whole reply is done, and the user reads "replies appear all at once" in your closing message. A chat streams.
Reading a streamed body with res.json(). The body of ai.stream is an event stream, not one JSON document. Return res.body in a Response or read it with a stream reader.
Asking for the user's API key. An AI feature of the app's own needs none. Only when the user chose their own provider account for the feature does the call go through a connected integration — load the integrations sub-skill then.