MACLLM AI API

Build intelligent applications with MACLLM Brain — our self-built AI engine.

https://api.macllm.ai

Introduction

MACLLM AI API provides programmatic access to our Brain engine. All requests and responses use JSON format. Authenticate via Bearer token (JWT) or API key.

Base URL: https://api.macllm.ai
Content-Type: All requests must include Content-Type: application/json
Auth: Include Authorization: Bearer <token> or X-API-Key: <key> header

Response Envelope

All endpoints return a consistent JSON envelope with success, data, and error fields:

{
  "success": true,
  "data": { ... },
  "error": null
}

Rate Limits Overview

TierRequests/minBrain Queries/moAPI Calls/mo
Free101001,000
Basic6050050,000
Pro1201,500500,000
Scale300Unlimited5,000,000
Enterprise1,000UnlimitedUnlimited

Authentication

Register an account to receive JWT tokens and an API key. Use JWT Bearer tokens for user-facing apps and API keys for server-to-server integration. Supports email/password and Google OAuth sign-in.

POST /v3/auth/register

Create a new account. Returns JWT tokens, user profile, and a unique API key.

FieldTypeRequiredDescription
emailstringYesValid email address
passwordstringYesMinimum 8 characters, max 128
namestringYesDisplay name (2-100 characters)
import requests resp = requests.post("https://api.macllm.ai/v3/auth/register", json={ "email": "[email protected]", "password": "your_secure_password", "name": "Your Name" }) data = resp.json() print(data["data"]["tokens"]["access_token"]) print(data["data"]["api_key"])
const resp = await fetch("https://api.macllm.ai/v3/auth/register", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email: "[email protected]", password: "your_secure_password", name: "Your Name" }) }); const data = await resp.json(); console.log(data.data.tokens.access_token); console.log(data.data.api_key);
curl -X POST https://api.macllm.ai/v3/auth/register \ -H "Content-Type: application/json" \ -d '{"email":"[email protected]","password":"your_secure_password","name":"Your Name"}'
Response
{
  "success": true,
  "data": {
    "user": {
      "id": "a1b2c3d4e5f6...",
      "email": "[email protected]",
      "name": "Your Name",
      "tier": "free",
      "is_active": true,
      "is_verified": false,
      "created_at": "2026-03-18T12:00:00"
    },
    "tokens": {
      "access_token": "eyJhbGciOiJIUzI1NiIs...",
      "refresh_token": "eyJhbGciOiJIUzI1NiIs...",
      "token_type": "bearer",
      "expires_in": 86400
    },
    "api_key": "mk_live_a1b2c3d4e5f6..."
  },
  "error": null
}
Important: Save your api_key immediately. It is only returned at registration and login. Use it as X-API-Key header for server-to-server calls.
POST /v3/auth/login

Authenticate with email and password. Returns JWT tokens, user profile, and API key.

FieldTypeRequiredDescription
emailstringYesRegistered email address
passwordstringYesAccount password
import requests resp = requests.post("https://api.macllm.ai/v3/auth/login", json={ "email": "[email protected]", "password": "your_secure_password" }) data = resp.json() print(data["data"]["tokens"]["access_token"])
const resp = await fetch("https://api.macllm.ai/v3/auth/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email: "[email protected]", password: "your_secure_password" }) }); const { data } = await resp.json(); console.log(data.tokens.access_token);
curl -X POST https://api.macllm.ai/v3/auth/login \ -H "Content-Type: application/json" \ -d '{"email":"[email protected]","password":"your_secure_password"}'
Response
{
  "success": true,
  "data": {
    "user": {
      "id": "a1b2c3d4e5f6...",
      "email": "[email protected]",
      "name": "Your Name",
      "tier": "basic",
      "role": "user",
      "is_active": true,
      "is_verified": true,
      "created_at": "2026-03-15T08:30:00"
    },
    "tokens": {
      "access_token": "eyJhbGciOiJIUzI1NiIs...",
      "refresh_token": "eyJhbGciOiJIUzI1NiIs...",
      "token_type": "bearer",
      "expires_in": 86400
    },
    "api_key": "mk_live_a1b2c3d4e5f6..."
  },
  "error": null
}
POST /v3/auth/google

Sign in with Google OAuth. Verifies the Google ID token server-side and creates a new account if the email is not yet registered. Google-authenticated accounts are auto-verified.

FieldTypeRequiredDescription
google_tokenstringYesGoogle ID token obtained from frontend Sign-In
Request
{
  "google_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6..."
}
Response
{
  "success": true,
  "data": {
    "user": {
      "id": "a1b2c3d4e5f6...",
      "email": "[email protected]",
      "name": "Google User",
      "tier": "free",
      "is_verified": true,
      "avatar_url": "https://lh3.googleusercontent.com/..."
    },
    "tokens": {
      "access_token": "eyJhbGciOiJIUzI1NiIs...",
      "refresh_token": "eyJhbGciOiJIUzI1NiIs...",
      "token_type": "bearer",
      "expires_in": 86400
    },
    "api_key": "mk_live_a1b2c3d4e5f6...",
    "is_new_user": true
  },
  "error": null
}
GET /v3/auth/me

Get the current user's profile, usage statistics, tier limits, and API key. Requires JWT Bearer authentication.

Headers
Authorization: Bearer <access_token>
import requests resp = requests.get("https://api.macllm.ai/v3/auth/me", headers={"Authorization": f"Bearer {TOKEN}"}) data = resp.json() print(data["data"]["user"]["tier"]) print(data["data"]["usage"])
const resp = await fetch("https://api.macllm.ai/v3/auth/me", { headers: { "Authorization": `Bearer ${TOKEN}` } }); const { data } = await resp.json(); console.log(data.user.tier); console.log(data.usage);
curl https://api.macllm.ai/v3/auth/me \ -H "Authorization: Bearer YOUR_TOKEN"
Response
{
  "success": true,
  "data": {
    "user": {
      "id": "a1b2c3d4e5f6...",
      "email": "[email protected]",
      "name": "Your Name",
      "tier": "pro",
      "tier_name": "Pro",
      "role": "user",
      "is_active": true,
      "is_verified": true,
      "avatar_url": null,
      "oauth_provider": null,
      "created_at": "2026-03-15T08:30:00"
    },
    "usage": {
      "brain_queries_used": 42,
      "api_calls_used": 1234
    },
    "api_key": "mk_live_a1b2c3d4e5f6...",
    "tier_limits": {
      "price_monthly": 15,
      "brain_queries": 1500,
      "api_calls_monthly": 500000,
      "rate_per_minute": 120
    }
  },
  "error": null
}
POST /v3/auth/refresh

Obtain a new access token using your refresh token. Use this when your access token expires instead of re-authenticating.

FieldTypeRequiredDescription
refresh_tokenstringYesJWT refresh token from login or register
Request
{
  "refresh_token": "eyJhbGciOiJIUzI1NiIs..."
}
Response
{
  "success": true,
  "data": {
    "access_token": "eyJhbGciOiJIUzI1NiIs...",
    "refresh_token": "eyJhbGciOiJIUzI1NiIs...",
    "token_type": "bearer",
    "expires_in": 86400
  },
  "error": null
}
Token Rotation: Each refresh call returns a new refresh token. The old refresh token becomes invalid. Always store the latest refresh token.
POST /v3/auth/api-key/regenerate

Regenerate your API key. The old key is invalidated immediately. Requires JWT Bearer authentication.

Headers
Authorization: Bearer <access_token>
Response
{
  "success": true,
  "data": {
    "api_key": "mk_live_newkey789abc...",
    "api_key_prefix": "mk_live_newk...",
    "message": "Save your new API key now. It will NOT be shown again."
  },
  "error": null
}
Warning: The new API key is only shown once. Store it securely. All requests using the old key will fail immediately after regeneration.
GET /v3/auth/tiers

List all available API tiers with their rate limits and quotas. Public endpoint -- no authentication required.

Response
{
  "success": true,
  "data": {
    "tiers": [
      {
        "id": "free",
        "name": "Free",
        "price_monthly": 0,
        "brain_queries": 100,
        "api_calls_monthly": 1000,
        "rate_per_minute": 10
      },
      {
        "id": "basic",
        "name": "Basic",
        "price_monthly": 5,
        "brain_queries": 500,
        "api_calls_monthly": 50000,
        "rate_per_minute": 60
      }
      // ... more tiers
    ]
  },
  "error": null
}
GET /v3/auth/providers

List available authentication providers and their status. Useful for frontends to dynamically show/hide login options. Public endpoint.

Response
{
  "success": true,
  "data": {
    "providers": [
      {
        "id": "email",
        "name": "Email & Password",
        "enabled": true
      },
      {
        "id": "google",
        "name": "Google",
        "enabled": true,
        "client_id": "123456789.apps.googleusercontent.com"
      }
    ]
  },
  "error": null
}

Chat API

The main endpoint for interacting with MACLLM Brain. Send a message, get an intelligent response powered by our self-built AI engine.

POST /v3/chat/send

Send a message to MACLLM Brain and receive a response.

Headers
Authorization: Bearer <token>
Content-Type: application/json
Request
{
  "message": "สวัสดี ช่วยอธิบาย Python ให้หน่อย",
  "session_id": "optional_session_id"
}
Response
{
  "success": true,
  "session_id": "a1b2c3d4...",
  "message_id": "m_abc123...",
  "response": "Python เป็นภาษาโปรแกรมที่ออกแบบมาให้อ่านง่าย...",
  "agent": "orchestrator",
  "domain": "general",
  "timestamp": "2026-03-19T12:00:00"
}
FieldTypeDescription
messagestringYour message or question (required, 1-10000 chars)
session_idstringOptional session ID for multi-turn conversations
responsestringThe AI-generated response
agentstringThe agent that handled the query
domainstringThe detected domain of the query
message_idstringUnique ID for this message
timestampstringISO 8601 timestamp

API Keys

Manage API keys for server-to-server integration. Use API keys instead of JWT tokens for programmatic access.

POST /v3/api-keys

Create a new API key. The full key is only shown once — save it immediately.

Headers
Authorization: Bearer <token>
Request
{
  "name": "Production Key",
  "allowed_ips": []
}
Response
{
  "key_id": "key_9f3a1b...",
  "api_key": "mclm_abc123def456...",
  "message": "Save your key now. It will not be shown again."
}
Important: The full API key is only returned once at creation time. Store it securely. You will only see the prefix in subsequent API calls.
GET /v3/api-keys

List all API keys for your account. Only the key prefix is shown.

Response
[
  {
    "key_id": "key_9f3a1b...",
    "name": "Production Key",
    "prefix": "mclm_abc123...",
    "rate_limit": 100,
    "enabled": true
  }
]
PATCH /v3/api-keys/{key_id}

Update an API key's name or enable/disable it.

Request
{
  "name": "New Key Name",
  "enabled": false
}
Response
{
  "key_id": "key_9f3a1b...",
  "name": "New Key Name",
  "enabled": false,
  "updated_at": "2026-03-18T12:00:00Z"
}
POST /v3/api-keys/{key_id}/rotate

Rotate (regenerate) an API key. The old key becomes invalid immediately.

Response
{
  "api_key": "mclm_newkey789xyz...",
  "message": "Save your new key. The previous key has been revoked."
}
DELETE /v3/api-keys/{key_id}

Permanently delete an API key. This action cannot be undone.

Response
{
  "message": "API key deleted successfully."
}

Billing

Manage subscriptions, view usage quotas, and access payment history. MACLLM uses monthly billing with Omise payment gateway. Plans are billed in Thai Baht (THB).

GET /v3/billing/plans

List all subscription plans with pricing, quotas, and features. Public endpoint -- no authentication required.

import requests resp = requests.get("https://api.macllm.ai/v3/billing/plans") plans = resp.json()["data"]["plans"] for p in plans: print(f"{p['name']}: {p['price_thb']} THB/mo")
const resp = await fetch("https://api.macllm.ai/v3/billing/plans"); const { data } = await resp.json(); data.plans.forEach(p => console.log(`${p.name}: ${p.price_thb} THB/mo`) );
curl https://api.macllm.ai/v3/billing/plans
Response
{
  "success": true,
  "data": {
    "plans": [
      {
        "id": "free",
        "name": "Free",
        "name_th": "ฟรี",
        "price_thb": 0,
        "brain_queries": 100,
        "api_calls": 1000,
        "rate_per_minute": 10,
        "features": ["100 Brain queries/month", "1,000 API calls/month", ...],
        "popular": false
      },
      {
        "id": "basic",
        "name": "Basic",
        "name_th": "เบสิค",
        "price_thb": 179,
        "brain_queries": 500,
        "api_calls": 50000,
        "rate_per_minute": 60,
        "features": [...],
        "popular": false
      },
      {
        "id": "pro",
        "name": "Pro",
        "price_thb": 539,
        "popular": true
      }
      // ... scale, enterprise
    ],
    "currency": "THB",
    "billing_cycle": "monthly"
  },
  "error": null
}
PlanPrice (THB/mo)Brain QueriesAPI CallsRate/min
Free01001,00010
Basic17950050,00060
Pro5391,500500,000120
Scale3,559Unlimited5,000,000300
EnterpriseCustomUnlimitedUnlimited1,000
GET /v3/billing/usage

Get your current month's usage statistics and remaining quota. Requires JWT Bearer authentication.

Headers
Authorization: Bearer <access_token>
import requests resp = requests.get("https://api.macllm.ai/v3/billing/usage", headers={"Authorization": f"Bearer {TOKEN}"}) usage = resp.json()["data"] print(f"Brain queries: {usage['brain_queries_used']}/{usage['brain_queries_limit']}") print(f"API calls: {usage['api_calls_used']}/{usage['api_calls_limit']}")
const resp = await fetch("https://api.macllm.ai/v3/billing/usage", { headers: { "Authorization": `Bearer ${TOKEN}` } }); const { data } = await resp.json(); console.log(`Brain: ${data.brain_queries_used}/${data.brain_queries_limit}`);
curl https://api.macllm.ai/v3/billing/usage \ -H "Authorization: Bearer YOUR_TOKEN"
Response
{
  "success": true,
  "data": {
    "user_id": "a1b2c3d4e5f6...",
    "tier": "pro",
    "period": "2026-03",
    "brain_queries_used": 42,
    "brain_queries_limit": 1500,
    "brain_queries_remaining": 1458,
    "api_calls_used": 12345,
    "api_calls_limit": 500000,
    "api_calls_remaining": 487655,
    "rate_per_minute": 120,
    "tokens_used": 56789,
    "reset_at": "2026-04-01T00:00:00"
  },
  "error": null
}
FieldTypeDescription
periodstringCurrent billing period (YYYY-MM)
brain_queries_usedintegerBrain queries consumed this month
brain_queries_limitintegerMonthly brain query limit (-1 = unlimited)
brain_queries_remainingintegerBrain queries remaining (-1 = unlimited)
api_calls_usedintegerTotal API calls this month
api_calls_limitintegerMonthly API call limit (-1 = unlimited)
tokens_usedintegerTotal tokens consumed this month
reset_atstringISO timestamp when usage resets (1st of next month)
POST /v3/billing/subscribe

Subscribe to a billing plan. Charges via Omise payment gateway and upgrades your account tier upon successful payment. Requires JWT Bearer authentication.

Headers
Authorization: Bearer <access_token>
Content-Type: application/json
FieldTypeRequiredDescription
plan_idstringYesPlan ID: basic, pro, or scale
omise_tokenstringYesCard token obtained from Omise.js frontend SDK
Request
{
  "plan_id": "pro",
  "omise_token": "tokn_test_abc123..."
}
Response (successful)
{
  "success": true,
  "data": {
    "success": true,
    "charge_id": "chrg_test_abc123...",
    "plan_id": "pro",
    "amount_thb": 539,
    "status": "successful",
    "message": "Subscribed to Pro plan successfully!"
  },
  "error": null
}
Response (3D Secure required)
{
  "success": true,
  "data": {
    "charge_id": "chrg_test_abc123...",
    "plan_id": "pro",
    "amount_thb": 539,
    "status": "pending",
    "authorize_uri": "https://api.omise.co/payments/...",
    "message": "Payment requires additional authorization (3D Secure)"
  },
  "error": null
}
3D Secure: If the response status is pending, redirect the user to authorize_uri for card verification. The subscription activates automatically via webhook after the user completes authorization.
GET /v3/billing/invoices

Get payment history and invoices, most recent first. Requires JWT Bearer authentication.

Headers
Authorization: Bearer <access_token>
ParamTypeDefaultDescription
limitinteger20Max number of invoices to return (query param)
Response
{
  "success": true,
  "data": {
    "invoices": [
      {
        "invoice_id": "inv_a1b2c3d4e5f6...",
        "plan_id": "pro",
        "plan_name": "Pro",
        "amount_thb": 539,
        "currency": "THB",
        "status": "successful",
        "payment_method": "card",
        "charge_id": "chrg_test_abc123...",
        "created_at": "2026-03-18T12:00:00",
        "period_start": "2026-03-18T12:00:00",
        "period_end": "2026-04-17T12:00:00"
      }
    ],
    "count": 1
  },
  "error": null
}
StatusDescription
successfulPayment received, subscription active
pendingAwaiting payment confirmation (e.g. 3D Secure)
failedPayment was declined or processing error
refundedPayment was refunded
POST /v3/billing/cancel

Cancel your current subscription. The plan remains active until the end of the billing period, then downgrades to Free. No refund is issued. Requires JWT Bearer authentication.

Headers
Authorization: Bearer <access_token>
import requests resp = requests.post("https://api.macllm.ai/v3/billing/cancel", headers={"Authorization": f"Bearer {TOKEN}"}) data = resp.json() print(data["data"]["message"])
const resp = await fetch("https://api.macllm.ai/v3/billing/cancel", { method: "POST", headers: { "Authorization": `Bearer ${TOKEN}` } }); const { data } = await resp.json(); console.log(data.message);
curl -X POST https://api.macllm.ai/v3/billing/cancel \ -H "Authorization: Bearer YOUR_TOKEN"
Response
{
  "success": true,
  "data": {
    "success": true,
    "current_plan": "pro",
    "effective_until": "2026-04-17T12:00:00",
    "message": "Pro plan will remain active until 2026-04-17. You will be downgraded to the Free plan after that."
  },
  "error": null
}

Credit Payments

Purchase credits to use the MACLLM API. Supports PromptPay QR payments.

GET /v3/payment/packages

List available credit packages and pricing.

Response
[
  {
    "type": "CREDITS_100",
    "credits": 100,
    "bonus": 0,
    "price_thb": 99
  },
  {
    "type": "CREDITS_300",
    "credits": 300,
    "bonus": 30,
    "price_thb": 249
  },
  {
    "type": "CREDITS_1000",
    "credits": 1000,
    "bonus": 150,
    "price_thb": 749
  }
]
POST /v3/payment/create

Create a payment and receive a QR code for PromptPay.

Headers
Authorization: Bearer <token>
Request
{
  "package_type": "CREDITS_300",
  "method": "promptpay"
}
Response
{
  "payment_id": "pay_x7k2m9...",
  "qr_code_url": "https://api.macllm.ai/qr/pay_x7k2m9.png",
  "amount_thb": 249,
  "expires_at": "2026-03-18T13:00:00Z"
}
GET /v3/payment/status/{payment_id}

Check the status of a payment.

Response
{
  "payment_id": "pay_x7k2m9...",
  "status": "completed",
  "credits_added": 330,
  "completed_at": "2026-03-18T12:05:32Z"
}
StatusDescription
pendingWaiting for payment
completedPayment received, credits added
expiredQR code expired, no payment received
failedPayment processing error

Code Examples

Quick start examples to integrate MACLLM AI into your application.

import requests # Configuration API = "https://api.macllm.ai" TOKEN = "your_access_token" # Send a message to MACLLM Brain resp = requests.post( f"{API}/v3/chat/send", headers={"Authorization": f"Bearer {TOKEN}"}, json={"message": "อธิบาย Machine Learning"} ) data = resp.json() print(data["response"]) print(f"Agent: {data['agent']}") print(f"Domain: {data['domain']}")
// Send a message to MACLLM Brain const resp = await fetch("https://api.macllm.ai/v3/chat/send", { method: "POST", headers: { "Authorization": "Bearer YOUR_TOKEN", "Content-Type": "application/json" }, body: JSON.stringify({ message: "อธิบาย Machine Learning" }) }); const data = await resp.json(); console.log(data.response); console.log(`Agent: ${data.agent}`); console.log(`Domain: ${data.domain}`);
curl -X POST https://api.macllm.ai/v3/chat/send \ -H "Authorization: Bearer YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{"message": "อธิบาย Machine Learning"}'

Using API Key Instead of JWT

# Use X-API-Key header instead of Authorization
curl -X POST https://api.macllm.ai/v3/chat/send \
  -H "X-API-Key: mk_live_abc123def456..." \
  -H "Content-Type: application/json" \
  -d '{"message": "สวัสดี"}'

Multi-turn Conversation

import requests

API = "https://api.macllm.ai"
HEADERS = {"Authorization": "Bearer YOUR_TOKEN"}

# First message — start a session
r1 = requests.post(f"{API}/v3/chat/send", headers=HEADERS,
    json={"message": "Python คืออะไร?"})
session_id = r1.json().get("session_id")

# Follow-up message — same session
r2 = requests.post(f"{API}/v3/chat/send", headers=HEADERS,
    json={"message": "แล้วเริ่มเรียนยังไงดี?", "session_id": session_id})
print(r2.json()["response"])

Full Auth Flow Example

import requests

API = "https://api.macllm.ai"

# 1. Register
auth = requests.post(f"{API}/v3/auth/register", json={
    "email": "[email protected]",
    "password": "secure_password_123",
    "name": "Developer"
}).json()

TOKEN = auth["data"]["tokens"]["access_token"]
API_KEY = auth["data"]["api_key"]

# 2. Check usage
usage = requests.get(f"{API}/v3/billing/usage",
    headers={"Authorization": f"Bearer {TOKEN}"}).json()
print(f"Brain queries remaining: {usage['data']['brain_queries_remaining']}")

# 3. Chat using API key
reply = requests.post(f"{API}/v3/chat/send",
    headers={"X-API-Key": API_KEY},
    json={"message": "สอน Python เบื้องต้น"}).json()
print(reply["response"])

Error Codes

All errors return a JSON body with a message field explaining the issue.

Error Response Format
{
  "success": false,
  "data": null,
  "error": "Descriptive error message"
}
CodeMeaningDescription
400Bad RequestInvalid request body or missing required fields
401UnauthorizedInvalid or missing authentication token/API key
402Insufficient CreditsNo credits remaining — purchase more to continue
403ForbiddenIP not in API key whitelist or action not permitted
404Not FoundResource or endpoint does not exist
429Rate Limit ExceededToo many requests — retry after the Retry-After header value
500Server ErrorInternal error — contact support if persistent
502Bad GatewayPayment gateway unreachable (billing endpoints)
503Service UnavailablePayment gateway not configured — contact support
Retry-After: When you receive a 429 response, check the Retry-After header for the number of seconds to wait before retrying.

Rate Limits

Rate limits vary by account tier. Exceeding limits returns HTTP 429. Limits reset per minute and per day. Auth endpoints have separate rate limits to prevent abuse.

TierRequests/minBrain Queries/moAPI Calls/moPrice (THB)
Free101001,000Free
Basic6050050,000179/mo
Pro1201,500500,000539/mo
Scale300Unlimited5,000,0003,559/mo
Enterprise1,000UnlimitedUnlimitedContact us

Auth Rate Limits

ActionLimitWindow
Login / Refresh / OAuth10 attempts60 seconds per IP
Registration3 attempts60 seconds per IP

Rate Limit Headers

Every API response includes rate limit information in the headers:

X-RateLimit-Limit: 30          # Max requests per minute
X-RateLimit-Remaining: 27      # Requests remaining
X-RateLimit-Reset: 1710763200  # Unix timestamp when limit resets
X-Daily-Limit: 1000            # Max requests per day
X-Daily-Remaining: 984         # Daily requests remaining
Tip: Use the X-RateLimit-Remaining header to implement client-side throttling and avoid hitting the rate limit.

MACLLM AI API — Built by MACLLM

Questions? Contact [email protected]