AI gateway
mAI Tokens
mAI Tokens is the mSpace AI gateway: one API in front of frontier LLM models, with chat completions and image generation. You authenticate once, against mAI Tokens, and spend from an mAI Tokens balance instead of holding a separate commercial account with each model provider.
What you get
| Capability | What it means |
|---|---|
| Frontier LLM models | Access to frontier LLM models from several model providers through one API and one key. |
| Chat completions | Generate a model response for a conversation, with system, developer, user, assistant and tool messages, structured output through response_format, and tool calling. |
| Image generation | Create an image from a text prompt. |
| One prepaid balance | Every call spends from your mAI Tokens balance, per token. usage.total_tokens on each response tells you what it drew. |
| Per-project control | Models are enabled per project in the portal. Each model has different capabilities, performance characteristics and price points, so choose per task, not per project. |
mAI Tokens is not the telco platform
It shares the mSpace brand with the Inzpire APIs, but not the host, the credential or the way failures are signalled. Keep two separate clients: a single shared HTTP helper will apply one of these conventions and be wrong for half your calls.
| Telco APIs (SMS, USSD, Subscription, OTP, CaaS, LBS) | mAI Tokens | |
|---|---|---|
| Host | https://api.mspace.lk | https://maitokens.mspace.lk/api |
| Credential | applicationId + password in the JSON body | one API key in the Authorization header |
| Credential source | the mSpace application record | the mAI Tokens portal, a *different* key |
| Failure signalling | HTTP 200 always; branch on statusCode | real HTTP status codes; branch on the status, then error.code |
| Success marker | statusCode: "S1000" | HTTP 2xx. There is no statusCode field |
| Subject | a subscriber, addressed tel:94… | no subscriber, no MSISDN |
| Inbound | callbacks you must host | none. mAI Tokens never calls you |
| Network control | *Allowed Host Address* (source-IP whitelist) | none: the key alone authorises the call |
| Cost model | per SMS / per charge | per token, from a prepaid balance |
| Latency budget | sub-second | seconds to tens of seconds |
Authentication
Authorization: app_<keyId>.<keyValue>
Generate the key in the mAI Tokens portal and send the whole value in the header verbatim, including the app_ prefix. It is not an OAuth bearer token: do not write Bearer app_… and do not base64-encode it. It is not your mSpace application password, and your application password will not work here.
export MAI_TOKENS_API_KEY='app_<keyId>.<keyValue>'
Base URL and endpoints
https://maitokens.mspace.lk/api
| Endpoint | Method | What it does | Environment variable |
|---|---|---|---|
/v1/chat/completions | POST | Generate a model response for a conversation | MAI_TOKENS_CHAT_COMPLETIONS_URL |
/v1/images/generations | POST | Create an image from a text prompt | MAI_TOKENS_IMAGE_GENERATIONS_URL |
Chat completions
POST https://maitokens.mspace.lk/api/v1/chat/completions
Required: model and messages. messages is the conversation so far, oldest first; each entry has a role and content.
| Parameter | Why it matters |
|---|---|
max_completion_tokens | Set it on every call. It is the only hard ceiling on what one request can cost. |
temperature | 0–2, default 1. Lower for extraction, classification and anything you parse. |
response_format | Ask for structured output here rather than asking for JSON in the prompt. |
n | Every choice is generated and billed. Leave it at 1 unless you use the alternatives. |
stop | Up to 4 stop sequences. Cheaper than generating text you then throw away. |
store | Defaults to false. Leave it false for anything carrying subscriber data. |
tools | Lets the model ask for a tool. Validate tool arguments as untrusted input before acting. |
curl -sS -X POST "$MAI_TOKENS_CHAT_COMPLETIONS_URL" \
-H 'Content-Type: application/json' \
-H "Authorization: $MAI_TOKENS_API_KEY" \
--max-time 120 \
-d @- <<'REQUEST'
{
"model": "<model id enabled for your project>",
"messages": [
{ "role": "system", "content": "You are a concise assistant for a Sri Lankan mobile service. Answer in one short paragraph." },
{ "role": "user", "content": "Explain megapixels in a picture" }
],
"response_format": { "type": "text" },
"max_completion_tokens": 300
}
REQUEST{
"id": "chatcmpl-B9MBs8CjcvOU2jLn4n570S5qMJKcT",
"object": "chat.completion",
"created": 1741569952,
"model": "<the model that answered>",
"choices": [
{
"index": 0,
"message": { "role": "assistant", "content": "Megapixels count the millions of pixels…", "refusal": null, "annotations": [] },
"logprobs": null,
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 19,
"completion_tokens": 10,
"total_tokens": 29
},
"service_tier": "default"
}Check choices[0].finish_reason before you use the content: stop is a complete answer, length means the answer was cut off at max_completion_tokens, and tool_calls means the model wants a tool run first. Append choices[0].message to your history verbatim before the next turn, and record usage.total_tokens per call.
Image generation
POST https://maitokens.mspace.lk/api/v1/images/generations
prompt is the only required parameter. Send model explicitly so a change of default never changes your output or your cost.
curl -sS -X POST "$MAI_TOKENS_IMAGE_GENERATIONS_URL" \
-H 'Content-Type: application/json' \
-H "Authorization: $MAI_TOKENS_API_KEY" \
--max-time 120 \
-d @- <<'REQUEST'
{
"model": "<image model id enabled for your project>",
"prompt": "a red apple on a plain background",
"n": 1,
"size": "1024x1024",
"quality": "low"
}
REQUEST{
"created": 1767763326,
"background": "opaque",
"data": [{ "b64_json": "<base64-encoded image bytes>" }],
"output_format": "png",
"quality": "low",
"size": "1024x1024",
"usage": { "input_tokens": 9, "output_tokens": 272, "total_tokens": 281 }
}The image comes back as base64 in the body, never as a URL. Decode it once, write the bytes to object storage, and hand around a URL of your own. Cost and latency levers, in order of impact: quality, n (each image is billed), then size. Image generation is slow, so run it in a background job.
Errors
Failures arrive as real HTTP status codes with this body. Branch on error.code, the machine-readable one.
{
"error": {
"message": "Human-readable error message",
"type": "Error type or code",
"param": "Parameter name that caused the error (if applicable)",
"code": "Error code",
"additional_data": { "key": "value" }
}
}| Status | Meaning | What to do |
|---|---|---|
400 | Invalid or malformed request | Read error.param. Not retryable. |
401 | Key missing, invalid or expired | Send the key verbatim, no Bearer. |
402 | Insufficient token balance | Top up, and alert. |
403 | Insufficient permissions, or the model is restricted for your project | Check the project is ACTIVE and the model is enabled. |
404 | No project matches the API key | Verify the full keyId.keyValue pair. |
429 | Rate limit or token quota exceeded | Check error.code first, then honour Retry-After. |
500 | Unexpected server error | Retry with backoff, cap attempts. |
502 | Failed to forward to the upstream model provider | Retry with backoff, or fail over to another model. |
503 | Temporarily unavailable | Retry with backoff. |
| error.code | HTTP | Meaning |
|---|---|---|
PROJECT_NOT_FOUND | 404 | The API key doesn't match any project |
PROJECT_INACTIVE | 403 | The project exists but its status is not ACTIVE |
INVALID_LLM_CONFIG | 400 | The model is not configured or allowed for your project |
RATE_LIMIT_EXCEEDED | 429 | Too many requests this minute. It clears on its own |
TOKEN_QUOTA_EXCEEDED | 429 | The project's allocated token quota is used up. Retrying will not clear this |
INSUFFICIENT_BALANCE | 402 | Balance too low to process the request |
FORWARDING_FAILED | 502 | The call to the upstream provider failed |
Using mAI Tokens with the telco APIs
An AI-answering SMS shortcode, a USSD assistant or generated campaign copy puts a slow, spendy call inside a fast, cheap flow. Three rules make that work.
- Never call a model inside a callback response path. mSpace expects
S1000immediately and USSD sessions time out in seconds. Acknowledge the callback first, generate out of band, then deliver the answer by MT SMS or on the next USSD screen. - Redact before the prompt. No MSISDN, no
subscriberId, no OTP, no mSpace password. Substitute an opaque placeholder and re-insert the real value after the response comes back. - Treat model output as untrusted input. Check its length and content before sending it to a subscriber: an SMS built from a model response still costs money per part.
Checklist before you ship
MAI_TOKENS_API_KEYcomes from the environment and appears in no source file, client bundle, log line or commit.- The header is
Authorization: app_<keyId>.<keyValue>, verbatim, noBearer. - The mAI Tokens client is separate from the telco client and branches on the HTTP status, then
error.code. max_completion_tokensis set on every chat call, andfinish_reasonis checked before the content is used.- Client timeout is 60–120 seconds; retries are transient only, capped, and honour
Retry-After. - No MSISDN,
subscriberId, OTP or credential can reach a prompt. usage.total_tokensis recorded per call, and the balance is monitored so402is caught before a subscriber is.