UNPKG

@softr/sdk

Version:

The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.

64 lines (62 loc) • 2.08 kB
import { fetch } from "../fetch.js"; import { readSessionToken } from "../auth/session.js"; import { describeFailure, dsUrl, refererHeader } from "../datasource/record.js"; //#region src/core/ai.ts /** * Thrown when the model call was refused or failed. `status` is the HTTP status Softr answered * with; 402 means the workspace has no AI credits left. */ var AiError = class extends Error { status; constructor(status, message) { super(message); this.name = "AiError"; this.status = status; } }; function body(init) { return JSON.stringify({ system: init.system, messages: init.messages, prompt: init.prompt, schema: init.schema, files: init.files, maxOutputTokens: init.maxOutputTokens, reasoning: init.reasoning, temperature: init.temperature }); } async function post(action, path, init) { if (init.signal?.aborted) throw init.signal.reason ?? new DOMException("The operation was aborted.", "AbortError"); const res = await fetch(`${dsUrl(action.id)}/${path}`, { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${readSessionToken()}`, ...refererHeader() }, body: body(init), signal: init.signal }); if (!res.ok) throw new AiError(res.status, `AI call "${action.id}" failed: ${await describeFailure(res)}`); return res; } /** Runs the action once and answers when the model is done. */ async function aiGenerate(action, init) { return await (await post(action, "softr-ai/generate", init)).json(); } /** * Runs the action and answers while the model writes. The returned `Response` body is a stream of * Server-Sent Events, one JSON object per `data:` line: `{ "text": "..." }` for each piece of the * answer, then `{ "done": true, "usage": {...}, "model": "..." }`, or `{ "error": "..." }` in its * place. Hand it to the browser as a `Response` with `Content-Type: text/event-stream`. */ async function aiStream(action, init) { return post(action, "softr-ai/generate/stream", init); } const ai = { generate: aiGenerate, stream: aiStream }; //#endregion export { AiError, ai };