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.

96 lines (94 loc) • 3.23 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, 429 means a rate limit was hit. * `retryAfter` is the seconds Softr asks to wait, set when the answer carries a `Retry-After` header. */ var AiError = class extends Error { status; retryAfter; constructor(status, message, retryAfter) { super(message); this.name = "AiError"; this.status = status; this.retryAfter = retryAfter; } }; const MAX_RETRIES = 2; const MAX_RETRY_WAIT_SECONDS = 10; function parseRetryAfter(res) { const header = res.headers.get("Retry-After"); return header !== null && /^\d+$/.test(header) ? Number(header) : void 0; } function abortReason(signal) { return signal?.reason ?? new DOMException("The operation was aborted.", "AbortError"); } 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 abortReason(init.signal); for (let retries = 0;; retries++) { 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) return res; const retryAfter = parseRetryAfter(res); if (!(res.status === 429 && retryAfter !== void 0 && retryAfter <= MAX_RETRY_WAIT_SECONDS && retries < MAX_RETRIES)) throw new AiError(res.status, `AI call "${action.id}" failed: ${await describeFailure(res)}`, retryAfter); await res.body?.cancel(); const signal = init.signal; await new Promise((resolve, reject) => { if (signal?.aborted) { reject(abortReason(signal)); return; } const onAbort = () => { clearTimeout(timer); reject(abortReason(signal)); }; const timer = setTimeout(() => { signal?.removeEventListener("abort", onAbort); resolve(); }, retryAfter * 1e3); signal?.addEventListener("abort", onAbort, { once: true }); }); } } /** 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 };