AI Gateway Module
Call Base44's managed AI models from your own backend code via base44.asServiceRole.aiGateway.
Note: Backend functions only. It uses your app's models, billing, and credit quota — there is no API key to manage.
Overview
connection() returns a baseURL, bearer token, and headers to hand to a client
library. Two providers sit behind it:
| Provider | Endpoints | Client |
|---|---|---|
openai (default) |
Chat Completions, /images/generations, /images/edits, /videos, /audio/speech |
Any OpenAI-compatible client (the openai SDK, Vercel AI SDK, TanStack AI, …) |
typesafe |
Structured evaluations with the jev model |
@ai-sdk/typesafe-ai + ai's experimental_evaluate |
Every call is metered against your app's credit quota, the same quota
integrations.Core.* uses.
When to use it
| Use | When |
|---|---|
integrations.Core.InvokeLLM |
A single call, no tools. Don't chain it to simulate an agent loop. See integrations.md. |
In-app agents (base44.agents) |
Managed and conversational — app users talk to it and the platform runs the agent loop for you. See base44-agents.md. |
| Code agents (gateway chat) | Programmable, not a conversation — a backend function where your code owns the loop, tools, model, and result; triggered by an entity event / schedule / webhook, not a chat. |
integrations.Core.GenerateImage |
One image from a prompt (optionally with reference images), default settings. See integrations.md. |
| Gateway images | Several images per request, a specific model, aspect ratio or resolution, reference images, or editing an existing image. |
integrations.Core.GenerateVideo |
Straightforward text-to-video: { prompt, duration?: 4 | 6 | 8, aspect_ratio?: "16:9" | "9:16", generate_audio? } → { url }. Waits for the result (30–60 s). |
| Gateway videos | Model choice, image/video/audio references, first/last frames, or anything outside the GenerateVideo schema. It is an asynchronous job: create, then retrieve later. |
integrations.Core.GenerateSpeech |
Straightforward stored MP3: { text, voice?: "river" | "honey" | "sunny" | "storm" | "spark", language_code?: "en" | … } → { url }. Default voice river; up to 5,000 characters, 1 credit per 50 characters. |
| Gateway speech | Model-specific text-to-speech controls. See Generate speech for browser/Core/gateway selection and existing speech code. |
AI decisions (gateway typesafe) |
Classify, score, or route a record against named criteria and get probabilities back — instead of InvokeLLM with a JSON schema. |
Apps that restrict Core integrations (the default for new apps) also block frontend calls to
GenerateImage, GenerateVideo, and GenerateSpeech; call them from a backend function as
base44.asServiceRole.integrations.Core.*.
Methods
| Method | Signature | Description |
|---|---|---|
connection(options?) |
({ provider?: "openai" | "typesafe" }) => AiGatewayConnection |
Returns { baseURL, token, headers } for the selected provider. Defaults to openai. |
base44.asServiceRole.aiGateway— the app's service-role token. Use it server-side; the gateway rejects other calls with 403ai_gateway_requires_service_role. Works with no signed-in user (e.g. scheduled automations).base44.aiGateway— the signed-in app user's token. Accepted only on apps shared privately or with the workspace.
Rules for every gateway call
- Backend function only (
createClientFromRequest(req)). All other backend-function rules (deployment, secrets, error handling) apply — see functions.md. Never send the gatewaytokento the browser. - Guard user-triggered functions with
await base44.auth.me()before the service-role call — every call spends the app owner's credits. Scheduled or entity-triggered runs have no caller to check. - Decide cost-driving parameters in code (model, image count, video duration, resolution). Don't pass a browser-supplied request straight to the gateway, or any signed-in user can pick the most expensive options.
- Always pass
headersto the client (defaultHeadersfor theopenaiSDK and TanStack AI,headersfor Vercel AI SDK providers). On a client fromcreateClientFromRequest()it carries the signedBase44-Statethat a workspace IP allowlist requires; without it those workspaces reject the call. - Set
maxRetries: 0on image, video, speech, and evaluation calls. Client retries replay billed requests.
Build a code agent
- Get the connection with
base44.asServiceRole.aiGateway.connection()→{ baseURL, token, headers }. - Point an agent SDK's OpenAI-compatible provider at it (
baseURL,apiKey: token,headers). - Give the agent tools that read/act on your app via
base44.*, and let it finish by recording its result through a tool.
Rules:
- Tools run in the caller's scope by default. The gateway connection is service-role,
but the agent's tools should use
base44.entities.*so they act with the calling user's permissions (RLS applies) and can't exceed them. Usebase44.asServiceRole.entities.*in a tool only for genuine cross-user/system work — and then scope it to trusted context, not agent-chosen inputs (e.g. fixcustomer_emailfrom the request, not an agent parameter), since service role has full access. - Stateless between invocations. Persistent memory means storing and replaying state (e.g. in an entity).
- Use model
automaticunless the task needs a specific model — non-default models use more credits: only when needed, and tell the user. - Don't chain
InvokeLLMto fake a tool loop — use a real agent loop. - Always bound the loop.
stopWhenis an OR-list — the first condition to fire wins (mix a step cap likestepCountIs, a finish tool likehasToolCall, or a custom check). Give it room to finish but stop a runaway: every step is another metered model call.
Example with the Vercel AI SDK — a background reviewer the app runs on a return request:
import { createClientFromRequest } from "npm:@base44/sdk@0.8.52";
import { ToolLoopAgent, tool, stepCountIs, hasToolCall } from "npm:ai@7.0.16";
import { createOpenAICompatible } from "npm:@ai-sdk/openai-compatible@3.0.5";
import { z } from "npm:zod@4.4.3";
export default async function (req) {
const base44 = createClientFromRequest(req);
const user = await base44.auth.me();
if (!user) return Response.json({ error: "Unauthorized" }, { status: 401 });
const { return_id } = await req.json();
const request = await base44.entities.ReturnRequest.get(return_id);
const { baseURL, token, headers } = base44.asServiceRole.aiGateway.connection();
const base44Models = createOpenAICompatible({ name: "base44", baseURL, apiKey: token, headers });
const agent = new ToolLoopAgent({
model: base44Models("automatic"),
instructions:
"Decide whether this return looks fine or needs the owner's attention. " +
"Check the customer's past orders as many times as you need, then submit your verdict.",
tools: {
searchOrders: tool({
description: "This customer's past orders, optionally filtered by status",
inputSchema: z.object({ status: z.string().optional() }),
execute: ({ status }) => {
const query = { customer_email: request.customer_email };
if (status) query.status = status;
return base44.entities.Order.filter(query, "-created_date", 50);
},
}),
submitVerdict: tool({
description: "Record the final verdict. Call this once, when you've decided.",
inputSchema: z.object({ decision: z.enum(["approved", "flagged"]), reason: z.string() }),
execute: ({ decision, reason }) =>
base44.entities.ReturnRequest.update(return_id, { status: decision, review_note: reason }),
}),
},
// stops at the first to trigger — submitVerdict was called, or 8 steps elapsed;
// mix whatever conditions fit the task (a step cap, a finish tool, a custom condition)
stopWhen: [stepCountIs(8), hasToolCall("submitVerdict")],
});
await agent.generate({ prompt: `Review this return request: ${JSON.stringify(request)}` });
return Response.json({ ok: true });
}Images as input: when the agent needs to see an image, pass it as an image part in messages:
const { text } = await agent.generate({ messages: [{ role: "user", content: [
{ type: "text", text: `Review this receipt: ${JSON.stringify(receipt)}` },
{ type: "image", image: receipt.image_url },
]}]});Any OpenAI-compatible agent SDK works the same way — construct its provider/client with
the gateway's baseURL, token, and headers. Streaming (stream: true, streamText) is
supported.
Generate and edit images
POST /images/generations and POST /images/edits through the openai SDK:
import OpenAI from "npm:openai@6.45.0";
const { baseURL, token, headers } = base44.asServiceRole.aiGateway.connection();
const client = new OpenAI({ baseURL, apiKey: token, defaultHeaders: headers, maxRetries: 0 });
const { data, usage } = await client.images.generate({
model: "automatic",
prompt: `${description}. Studio lighting.`,
n: 1, // up to 4 per request; some models allow fewer
response_format: "url", // "url" or "b64_json"; default "b64_json"
// Base44 extensions beyond the OpenAI spec:
aspect_ratio: "16:9",
resolution: "1K", // higher resolutions are model-specific
reference_image_urls: [url], // image inputs by URL
});
// data[0].url is the stored image URL; usage.base44_credits is the charged amount.- Editing:
client.images.edit({ model, prompt, image })needs at least one input image — uploaded bytes inimage, orreference_image_urls. Generations acceptreference_image_urlstoo. - Other options:
quality,output_format,background(transparent/opaque) — support is model-specific. Withautomatic, setting any of them (evenquality: "auto") skips the Gemini models and routes to a GPT Image model, which changes the output and the cost — omit them unless you need them. - Models: prefer
"automatic", which picks a model that supports the requested options. Pin one (e.g.gemini_3_1_flash_image,gpt_image_2) only when needed. Unsupported option/model combinations return 400. Full model list and limits: Generate images with the AI Gateway. - Cost preview: add
dry_run: trueto the same request to get{ dry_run: true, model, usage: { base44_credits } }without generating or charging.
With the Vercel AI SDK, use models.imageModel("automatic") with generateImage and pass
the Base44 extensions under providerOptions: { base44: { ... } } (the key is the name
you gave createOpenAICompatible).
Generate videos
Video generation is an asynchronous job through the openai SDK's videos client.
videos.create() returns a job id right away; the video is ready later.
import { createClientFromRequest } from "npm:@base44/sdk@0.8.52";
import OpenAI from "npm:openai@6.45.0";
export default async function (req) {
const base44 = createClientFromRequest(req);
const user = await base44.auth.me();
if (!user) return Response.json({ error: "Unauthorized" }, { status: 401 });
const { action, prompt, videoId } = await req.json();
const { baseURL, token, headers } = base44.asServiceRole.aiGateway.connection();
const { videos } = new OpenAI({ baseURL, apiKey: token, defaultHeaders: headers });
if (action === "create") {
// The function picks the model and duration; the browser only sends the prompt.
const job = await videos.create(
{ model: "veo_3_1_lite", prompt, seconds: 4, generate_audio: false },
{ maxRetries: 0 },
);
return Response.json(job, { status: 202 });
}
if (action === "retrieve") {
return Response.json(await videos.retrieve(videoId));
}
return Response.json({ error: "Invalid action" }, { status: 400 });
}Poll from the frontend (or a later scheduled run), not inside one function invocation — a backend function is a bounded HTTP call:
const isProcessing = (status) => status === "queued" || status === "in_progress";
let { data: video } = await base44.functions.invoke("video-gateway", { action: "create", prompt });
for (let attempt = 0; isProcessing(video.status) && attempt < 40; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 15_000));
({ data: video } = await base44.functions.invoke("video-gateway", {
action: "retrieve",
videoId: video.id,
}));
}
if (video.status === "failed") throw new Error(video.error?.message || "Video generation failed");
// video.url is the stored video once status is "completed"- Statuses:
queued,in_progress,completed,failed. Treatqueued/in_progressor hitting your polling limit as unfinished, not failed. For background flows, persistvideo.id(e.g. in an entity) and retrieve it in a later run. - Cost differs a lot by model. A 4-second clip without audio ranged from 48 credits
(
veo_3_1_lite) to over 350 (kling_3) when this was written. Preview withdry_runbefore choosing a model, and default toveo_3_1_liteunless the app needs another. - Models: there is no
automatic— pass a specific model:veo_3_1_lite,veo_3_1_fast,seedance_2,seedance_2_5,seedance_2_fast,seedance_2_mini,kling_3,minimax_h3,minimax_h3_max,grok_imagine_video,grok_imagine_video_1_5,flux_3_video,wan_3. Supportedseconds,resolution,aspect_ratio, and references differ per model, and some models rejectgenerate_audio; unsupported values return 400, and an unknown model (includingautomatic) returns 404. - Request fields:
model,prompt,seconds,aspect_ratio,resolution,generate_audio,seed,dry_run, and eitherframe_images(up to 2, each{ type: "image_url", image_url: { url }, frame_type: "first_frame" | "last_frame" }) orinput_references(image/video/audio URLs, each{ type: "image_url", image_url: { url } }and likewise forvideo_url/audio_url) — don't combine the two. Reference limits per model:seedance_2_530 images, 10 videos, 10 audio; other Seedance models 9 images, 3 videos, 3 audio;minimax_h33 of each type;wan_35 videos and 50 references in total; Grok models 7 images. On Seedance andminimax_h3, audio needs an image or video reference too. Reference URLs must be public HTTPS URLs or private files the app owns. - Cost preview:
videos.create({ ...request, dry_run: true })returns HTTP 200 withusage.base44_creditsand no job id — don't poll it, and don't return it as a 202.
Generate speech
- Browser-only read-aloud, without stored audio or voice/style requirements: use the browser's TTS API. This option does not apply to native apps.
- Straightforward stored MP3 with a Core voice (
riverdefault,honey,sunny,storm,spark), optional ISO-639-1language_code, up to 5,000 characters: useintegrations.Core.GenerateSpeech({ text, voice?, language_code? })→{ url }. - Model choice, delivery instructions, speed, other formats, or voices outside Core: use the gateway. Follow this section when editing existing gateway speech code too.
POST /audio/speech returns completed audio bytes. It does not store a file or return
a URL or job ID; there is no polling step.
Call it from a backend function, following the
shared rules and functions.md.
text is the supplied spoken text; base44 is the function's request client:
import OpenAI from "npm:openai";
const { baseURL, token, headers } = base44.asServiceRole.aiGateway.connection();
const client = new OpenAI({ baseURL, apiKey: token, defaultHeaders: headers, maxRetries: 0 });
const speechRequest = {
model: "gpt_4o_mini_tts",
input: text,
voice: "nova",
};
const audio = await client.audio.speech.create(speechRequest);
const credits = Number(audio.headers.get("x-base44-credits"));
const file = new File([await audio.arrayBuffer()], "speech.mp3", { type: "audio/mpeg" });
const { file_uri } = await base44.asServiceRole.integrations.Core.UploadPrivateFile({ file });
return Response.json({ file_uri, credits });This example stores private MP3 audio. To store public audio instead,
base44.asServiceRole.integrations.Core.UploadFile({ file }) returns file_url
(see UploadFile).
For private file_uri, call base44.integrations.Core.CreateFileSignedUrl({ file_uri })
and use signed_url for playback (see the signed-URL flow).
Match the filename and content type when choosing another encoding. Prefer MP3 or WAV
for playback; raw PCM requires decoding and cannot be played directly as an audio URL.
- Web: render
<audio controls src={signed_url}>; do not assume autoplay is allowed. - Native: use an installed React Native-compatible player or
Linking.openURL(signed_url)to open saved audio externally. The native template has no audio-player package. Do not use HTML<audio>,new Audio, orspeechSynthesis.
Cost preview: run this instead of the generation/upload block. dry_run: true
returns JSON, without generating or charging; the estimate can differ from the final
charge and contains no audio or file to play:
const estimate = await client.post("/audio/speech", {
body: { ...speechRequest, dry_run: true },
});
const estimatedCredits = estimate.usage.base44_credits;Request fields:
| Field | Meaning |
|---|---|
input |
Required spoken text; not text or prompt. |
model |
Optional alias or vendor ID. Omitted or "automatic" selects a fixed default, not a model chosen to satisfy requested controls. |
voice |
Model-specific, case-sensitive name; omitted uses the model's default. |
response_format |
Audio encoding, not "url" or "b64_json"; omitted uses the model's default. |
speed |
Model-specific range; omit or use 1 for normal speed. |
instructions |
Delivery/style guidance, only on supporting models; keep it out of the spoken input. |
language |
Model-specific ISO-639 control, not Core's language_code; omit for automatic language handling. |
stream_format |
Omit or use "audio"; SSE is unsupported and the endpoint returns completed audio. |
dry_run |
Optional boolean; true returns the JSON credit estimate. |
Models and controls: omitted model or "automatic" resolves to gpt_4o_mini_tts.
| Model | Voice set (default) | Formats (default) | Instructions | Speed | Language control |
|---|---|---|---|---|---|
gpt_4o_mini_tts |
OpenAI extended (nova) |
aac, flac, mp3, opus, pcm, wav (mp3) |
Supported | 0.25–4.0 | ISO-639 code |
tts_1, tts_1_hd |
OpenAI legacy (nova) |
aac, flac, mp3, opus, pcm, wav (mp3) |
Unsupported | 0.25–4.0 | Unsupported |
eleven_flash_v2_5 |
ElevenLabs (river) |
mp3, opus, pcm, wav (mp3) |
Unsupported | 0.7–1.2 | Codes below |
eleven_multilingual_v2 |
ElevenLabs (river) |
mp3, opus, pcm, wav (mp3) |
Unsupported | 0.7–1.2 | Unsupported |
gemini_2_5_flash_tts |
Gemini (Kore) |
pcm, wav (wav) |
Unsupported | Omit or 1 |
Unsupported |
- OpenAI legacy voices:
alloy,ash,coral,echo,fable,onyx,nova,sage,shimmer. OpenAI extended addsballad,verse,marin,cedar. - ElevenLabs voices:
honey,river,spark,storm,sunny. - Gemini voices:
Kore,Puck,Zephyr,Charon,Leda,Fenrir(case-sensitive). - OpenAI input limit: 4,096 characters for all three models.
eleven_flash_v2_5language codes:ar,bg,cs,da,de,el,en,es,fi,fil,fr,hi,hr,id,it,ja,ko,ms,nl,pl,pt,ro,ru,sk,sv,ta,tr,uk,zh.
Model discovery: GET /audio/speech/models returns { items, next_cursor };
GET /audio/speech/models/{model} returns one entry with its capabilities. Use these
gateway catalogs for voices, formats and their defaults, speed ranges, instruction and
language support, and input-length limits. The automatic entry's resolves_to identifies
the fixed default. Do not assume upstream provider features are exposed by the gateway.
AI decisions (Jev)
Structured evaluations: give the jev model some state and a set of questions, and get
each answer back with probabilities. Use it to classify, score, or route; then apply your
own thresholds and actions in deterministic code.
- Needs
ai7.0.105+ — older versions (including the7.0.16code-agent pin above) don't exportexperimental_evaluate. - The model id is exactly
"jev". The package README's"jev-latest"is rejected by the gateway.
import { createClientFromRequest } from "npm:@base44/sdk@0.8.52";
import { experimental_evaluate as evaluate } from "npm:ai@7.0.105";
import { createTypeSafeAi } from "npm:@ai-sdk/typesafe-ai@3.0.4";
export default async function (req) {
const base44 = createClientFromRequest(req);
const user = await base44.auth.me();
if (!user) return Response.json({ error: "Unauthorized" }, { status: 401 });
const { message } = await req.json();
const { baseURL, token, headers } = base44.asServiceRole.aiGateway.connection({ provider: "typesafe" });
const typesafe = createTypeSafeAi({ baseURL, apiKey: token, headers });
const result = await evaluate({
model: typesafe.evaluationModel("jev"),
maxRetries: 0, // avoid automatic replays of billed requests
state: { message },
questions: {
department: { type: "choice", instructions: "Which team should handle this?",
criteria: { billing: "Payments and refunds", support: "Other requests" } },
urgency: { type: "score", instructions: "How urgent is this?",
criteria: ["No deadline", "Requested today", "Immediate emergency"] },
refund: { type: "boolean", instructions: "Is a refund explicitly requested?" },
},
});
return Response.json({ answers: result.answers });
}Request:
state— string, JSON object, or array (an array is one state).questions— non-empty; questions can't depend on other answers in the same call.choice:criteriarequired, an object of 1–255 named options (descriptions may benull).score:criteriarequired, an array of 2–10 ordered rubric levels.boolean:criteriaoptional, an object with onlytrue/falsekeys (descriptions may benull).instructionsand criteria descriptions may be a string, JSON object, or JSON array.
Response (answer keys match question ids):
{
answers: {
department: { type: "choice", choice: "billing", probabilities: { billing: 0.97, support: 0.03 } },
urgency: { type: "score", score: 1.2, probabilities: { 0: 0.1, 1: 0.6, 2: 0.3 } }, // 0..criteria.length-1, may be fractional
refund: { type: "boolean", probability: 0.99 }, // P(true)
},
providerMetadata: {
typesafe: { confidence: { department: 0.9, urgency: 0.7 } }, // choice/score only; entries may be absent
},
}Models
- Chat: any model available through
InvokeLLM;automaticby default (see the code-agent rules above). - Images:
automaticor a pinned image model — see Generate and edit images. - Videos: always a specific model — see Generate videos.
- Speech:
automaticis a fixed default; use the speech catalog for model-specific controls — see Generate speech. - Evaluations:
jev.
Notes
- Token: the service-role token for
base44.asServiceRole.aiGateway; the caller's token forbase44.aiGateway. The gateway expects the service-role token; otherwise 403ai_gateway_requires_service_role. - Billing: metered per call against your app's credit quota (same as InvokeLLM). If the app is out of credits, calls are rejected before the model runs.
Type Definitions
/** Connection details for the Base44 AI Gateway. */
interface AiGatewayConnection {
/** Base URL of the selected gateway provider. */
baseURL: string;
/** Bearer token for the gateway: the service-role token, or the signed-in user's token. The gateway expects the service-role token. */
token: string;
/**
* Extra headers to send with every gateway request (`defaultHeaders` for the `openai`
* SDK and TanStack AI, `headers` for Vercel AI SDK providers). On a client from
* `createClientFromRequest()` this carries the signed `Base44-State` a workspace IP
* allowlist requires; otherwise it's empty.
*/
headers: Record<string, string>;
}
/** Options for selecting an AI Gateway provider. */
interface AiGatewayConnectionOptions {
/** Gateway provider to connect to. Defaults to `openai`. */
provider?: "openai" | "typesafe";
}
interface AiGatewayModule {
connection(options?: AiGatewayConnectionOptions): AiGatewayConnection;
}