Skip to content

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

CapabilityWhat it means
Frontier LLM modelsAccess to frontier LLM models from several model providers through one API and one key.
Chat completionsGenerate a model response for a conversation, with system, developer, user, assistant and tool messages, structured output through response_format, and tool calling.
Image generationCreate an image from a text prompt.
One prepaid balanceEvery call spends from your mAI Tokens balance, per token. usage.total_tokens on each response tells you what it drew.
Per-project controlModels 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
Hosthttps://api.mspace.lkhttps://maitokens.mspace.lk/api
CredentialapplicationId + password in the JSON bodyone API key in the Authorization header
Credential sourcethe mSpace application recordthe mAI Tokens portal, a *different* key
Failure signallingHTTP 200 always; branch on statusCodereal HTTP status codes; branch on the status, then error.code
Success markerstatusCode: "S1000"HTTP 2xx. There is no statusCode field
Subjecta subscriber, addressed tel:94…no subscriber, no MSISDN
Inboundcallbacks you must hostnone. mAI Tokens never calls you
Network control*Allowed Host Address* (source-IP whitelist)none: the key alone authorises the call
Cost modelper SMS / per chargeper token, from a prepaid balance
Latency budgetsub-secondseconds 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
EndpointMethodWhat it doesEnvironment variable
/v1/chat/completionsPOSTGenerate a model response for a conversationMAI_TOKENS_CHAT_COMPLETIONS_URL
/v1/images/generationsPOSTCreate an image from a text promptMAI_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.

ParameterWhy it matters
max_completion_tokensSet it on every call. It is the only hard ceiling on what one request can cost.
temperature0–2, default 1. Lower for extraction, classification and anything you parse.
response_formatAsk for structured output here rather than asking for JSON in the prompt.
nEvery choice is generated and billed. Leave it at 1 unless you use the alternatives.
stopUp to 4 stop sequences. Cheaper than generating text you then throw away.
storeDefaults to false. Leave it false for anything carrying subscriber data.
toolsLets the model ask for a tool. Validate tool arguments as untrusted input before acting.
Request
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
Response
{
  "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.

Request
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
Response
{
  "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" }
  }
}
StatusMeaningWhat to do
400Invalid or malformed requestRead error.param. Not retryable.
401Key missing, invalid or expiredSend the key verbatim, no Bearer.
402Insufficient token balanceTop up, and alert.
403Insufficient permissions, or the model is restricted for your projectCheck the project is ACTIVE and the model is enabled.
404No project matches the API keyVerify the full keyId.keyValue pair.
429Rate limit or token quota exceededCheck error.code first, then honour Retry-After.
500Unexpected server errorRetry with backoff, cap attempts.
502Failed to forward to the upstream model providerRetry with backoff, or fail over to another model.
503Temporarily unavailableRetry with backoff.
error.codeHTTPMeaning
PROJECT_NOT_FOUND404The API key doesn't match any project
PROJECT_INACTIVE403The project exists but its status is not ACTIVE
INVALID_LLM_CONFIG400The model is not configured or allowed for your project
RATE_LIMIT_EXCEEDED429Too many requests this minute. It clears on its own
TOKEN_QUOTA_EXCEEDED429The project's allocated token quota is used up. Retrying will not clear this
INSUFFICIENT_BALANCE402Balance too low to process the request
FORWARDING_FAILED502The 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.

  1. Never call a model inside a callback response path. mSpace expects S1000 immediately 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.
  2. 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.
  3. 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_KEY comes from the environment and appears in no source file, client bundle, log line or commit.
  • The header is Authorization: app_<keyId>.<keyValue>, verbatim, no Bearer.
  • The mAI Tokens client is separate from the telco client and branches on the HTTP status, then error.code.
  • max_completion_tokens is set on every chat call, and finish_reason is 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_tokens is recorded per call, and the balance is monitored so 402 is caught before a subscriber is.