AI models for apps
Call the AI gateway from an app backend using its deployment token and read the streamed result.
Call a model from your app’s backend to get a reply, stream text or ask the model to use a tool. The workspace owner connects providers and sets the app’s budget. With Builder chooses, you pick a model in your app code. The backend uses its own deployment token for each call. A model call runs without a sandbox. If you also want an agent to run shell commands, see agent jobs.
Enable AI for an app
- Workspace owner: Open AI models, connect the provider you want to use. Cloud providers include OpenAI, Anthropic, Google Gemini and OpenRouter.
- Workspace owner: In the app’s Connections, enable AI and set a monthly budget in USD. Under Models it can use, choose Builder chooses to let the app request any available model from your connected providers. A builder or coding agent can request AI access by declaring
"ai"in the app’s source. - App administrator: Deploy the app and run
smolcloud capabilities APP_ID. In theairesource, check thatdeploymentReadyis true. Pick a provider/model ID fromchoices. For example, if you seeopenai/gpt-4o-mini, useopenaias the provider andgpt-4o-minias the model. Split at the first slash so any slash in the model ID is preserved. Check app capabilities.
Make your first call
Run this JavaScript as an ES module in the deployed Node backend. Smolcloud supplies LLM_GATEWAY_URL and LLM_GATEWAY_TOKEN there. Keep the token in server-side code. Replace the example provider and model with the pair you picked.
import { Readable } from "node:stream";
import { createInterface } from "node:readline";
const response = await fetch(process.env.LLM_GATEWAY_URL, {
method: "POST",
redirect: "error",
headers: {
authorization: `Bearer ${process.env.LLM_GATEWAY_TOKEN}`,
"content-type": "application/json",
},
body: JSON.stringify({
provider: "openai",
model: "gpt-4o-mini",
context: {
messages: [
{
role: "user",
content: "Reply with just hello.",
timestamp: Date.now(),
},
],
},
options: { maxTokens: 64 },
}),
});
if (!response.ok)
throw new Error(`AI gateway returned HTTP ${response.status}`);
const lines = createInterface({ input: Readable.fromWeb(response.body) });
let answer;
for await (const line of lines) {
const event = JSON.parse(line);
if (event.type === "result") answer = event.message;
}
if (!answer) throw new Error("The AI gateway stream ended before its result");
if (answer.stopReason !== "stop")
throw new Error(`Model stopped: ${answer.stopReason}`);
console.log(
answer.content
.filter((block) => block.type === "text")
.map((block) => block.text)
.join(""),
);
This prints the model’s reply when the stream completes. In an app route, return the text to the caller after checking their access. A named agent with Can use can call that route from the CLI.
Choose a model
Each request can name a different provider and model from the app’s choices. Approved Ollama or vLLM models can appear alongside cloud models.
Optional workspace defaults. If several apps should follow one model choice, the owner can assign a model to Everyday or Best in AI models. An app opts in by sending model: "everyday" or model: "best" and omitting provider. Changing the workspace default then changes what those requests use. An owner can also restrict an individual app’s model choices.
Request options include maxTokens, temperature and reasoning (minimal, low, medium, high, xhigh or max). Changes to the app’s allowed models and budget apply to new calls without a redeployment.
Read the reply
The gateway streams one JSON object per line. To show text as it arrives, read frame.delta on text_delta frames. A text_start frame can already contain text in frame.content.text. The final result.message contains the complete reply and usage. A stream that ends before result is incomplete.
Check stopReason even after HTTP 200. stop means the reply finished, length means it reached an output limit, and toolUse means the app has a tool call to handle. Treat error and aborted as unsuccessful.
| HTTP status | What to check |
|---|---|
| 400 or 413 | Check the request fields and total body size. |
| 401 or 403 | Check the deployment token, the app’s AI access and the allowed model. |
| 402 | Check the app budget and any workspace budget. The remaining allowance must cover the reservation for this model. |
| 409 | Check the provider and gateway configuration. |
| 429 | Wait for an in-flight call to finish before trying again. |
| 503 | The gateway or an upstream service is temporarily unavailable. |
Use tools
Describe each tool in context.tools using JSON Schema. For example:
{
"name": "lookup_order",
"description": "Find an order by id",
"parameters": {
"type": "object",
"properties": { "id": { "type": "string" } },
"required": ["id"]
}
}
When stopReason is toolUse, read each toolCall in the message’s content. Your backend checks the caller’s permissions, validates the arguments and runs the tool. For the next request, append the complete assistant message to context.messages, then append a result for each tool call:
{
"role": "toolResult",
"toolCallId": "<id from the toolCall>",
"toolName": "lookup_order",
"content": [{ "type": "text", "text": "Shipped on Monday" }],
"isError": false,
"timestamp": 1760000000000
}
Use the actual tool call ID and name. Preserve the assistant message, including any provider signatures, when continuing the conversation. To require schema-constrained arguments on a supported model, set constrainedSampling on the tool to {"type":"json_schema","strict":"require"}. Use "prefer" if ordinary tool calling is an acceptable fallback.
Send images
For a model that supports images, use an array as the user message’s content. Set data to the base64-encoded image bytes and mimeType to its format.
[
{ "type": "text", "text": "Describe this image" },
{ "type": "image", "data": "<base64>", "mimeType": "image/png" }
]
Limits
Each request accepts up to 1,000 messages and 128 tool definitions. The JSON body can be up to 24 MiB, including base64 image data. Supported image formats are JPEG, PNG, WebP and GIF. By default, up to four calls from one app can be in progress at once per gateway. A fifth simultaneous call gets HTTP 429. A slot opens when a call ends. The gateway supports conversations and tool calls. Embeddings are unavailable.
For a cloud model, Smolcloud reserves an estimated cost before contacting the provider, using the model’s context window and maximum output. This is why even a short prompt can get a 402 while some allowance remains. Check other in-flight calls and the selected model, or ask the owner to review the budget. Estimated usage in Smolcloud can differ from the provider’s invoice.
Where the key lives
In a shared workspace, the owner’s browser encrypts the cloud provider key for the gateway on the workspace’s compute. That gateway opens the key and calls the provider. Management stores a reference and the last four characters. The app receives a deployment token. Prompts and replies pass through the management router and the selected provider. Follow an AI request.