# Artificial intelligence

Use text, image, video and voice models through the API with the OpenAI SDK, pay with credits and test free in Sandbox.

Updated on 24 November 2026

## What it is

The AI API gives you access, with the same MozOut API key, to hundreds of artificial intelligence models from many companies: text models to chat, summarise, translate or write code, and models that generate images, videos and voice.

- Chat is compatible with the OpenAI API: a program that already uses the OpenAI SDK moves to our models by changing only the address and the key.
- Everything is paid with AI credits. Each model has its own price in credits, which you can check before you use it.
- With a `sandbox_` key you can try everything without spending anything.

## What you need

- A key with the `ai:write` permission to chat and generate, and `ai:read` to see the models, the generations and the balance. See [Permissions](https://docs.mozout.co.mz/en/permissions.md).
- AI credits on the account, for the `prod_` key. Buy them in [All in One AI](https://www.meu.mozout.co.mz/all-in-one-ai.php?language=english&currency=2) in Meu MozOut, on the "Buy credits" tab, where you can also see the history and the keys. They are separate from the account credit in MZN. Check them with [`GET /v1/ai/balance`](https://docs.mozout.co.mz/en/ai.md).

## The base URL

All AI operations live at the same address as the rest of the API:

```text
https://api.mozout.co.mz/v1
```

The key goes in the `Authorization: Bearer` header, as in the other operations. See [Authentication](https://docs.mozout.co.mz/en/authentication.md).

## With the OpenAI SDK

Install the official OpenAI SDK (`pip install openai` in Python, `npm install openai` in Node.js) and point it at our address with `base_url`. The key is your `prod_` key (or `sandbox_`, to test), kept in the `MOZOUT_API_KEY` environment variable:

**Python**

```python
import os
from openai import OpenAI

client = OpenAI(base_url="https://api.mozout.co.mz/v1", api_key=os.environ["MOZOUT_API_KEY"])

completion = client.chat.completions.create(
    model="deepseek-ai/deepseek-v4-flash",
    messages=[{"role": "user", "content": "Write a two-sentence welcome message for our website."}],
    max_tokens=200,
)
print(completion.choices[0].message.content)
```

**JavaScript**

```javascript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.mozout.co.mz/v1", apiKey: process.env.MOZOUT_API_KEY });

const completion = await client.chat.completions.create({
  model: "deepseek-ai/deepseek-v4-flash",
  messages: [{ role: "user", content: "Write a two-sentence welcome message for our website." }],
  max_tokens: 200,
});
console.log(completion.choices[0].message.content);
```

**curl**

```bash
curl "https://api.mozout.co.mz/v1/chat/completions" \
  -H "Authorization: Bearer $MOZOUT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "deepseek-ai/deepseek-v4-flash", "messages": [{"role": "user", "content": "Write a two-sentence welcome message for our website."}], "max_tokens": 200}'
```


Other libraries and tools that are compatible with OpenAI work the same way: just set the base URL and the key.

## Claude Code, Codex and other tools

Besides the OpenAI Chat Completions format, the API accepts the Anthropic Messages format ([`POST /v1/messages`](https://docs.mozout.co.mz/en/ai.md)) and the OpenAI Responses format ([`POST /v1/responses`](https://docs.mozout.co.mz/en/ai.md)). This way Claude Code, Codex CLI, Cursor and other coding tools use our models with your key. The setup of each one is in [Coding tools](https://docs.mozout.co.mz/en/coding-tools.md).

## MCP server

Connect Claude Code, Codex, Cursor and other agents to our MCP server, at `https://api.mozout.co.mz/mcp`, and ask for images, videos, voice or answers from other models right in the chat, with the same credits. The setup of each tool and the skill for Claude Code are in [MCP](https://docs.mozout.co.mz/en/mcp.md).

## aio command (CLI)

To use AI in the terminal without writing code, install the `aio` command in one line: chat with the models, generate images, videos and voice and check the balance, with the same key. See [CLI](https://docs.mozout.co.mz/en/cli.md).

## Models and prices

[`GET /v1/models`](https://docs.mozout.co.mz/en/ai.md) returns every model on sale, in the OpenAI format. Filter by type with `type` (`text`, `image`, `video`, `audio` or `agent`) and search with `q`:

```curl
curl "https://api.mozout.co.mz/v1/models?type=image&q=gpt-image" \
  -H "Authorization: Bearer $MOZOUT_API_KEY"
```

Each model includes the `id` to send in `model`, its type and its price in credits in `pricing`. The `id` always has a slash, such as `deepseek-ai/deepseek-v4-flash`. Some examples from the catalog:

| Model | Type | Price in credits |
|---|---|---|
| `deepseek-ai/deepseek-v4-flash` | text | 56 per 1M input tokens and 112 per 1M output tokens |
| `moonshotai/kimi-k2.6` | text | 380 per 1M input tokens and 1600 per 1M output tokens |
| `openai/gpt-image-2/text-to-image` | image | 2 per image |
| `bytedance/seedance-2.0-mini/text-to-video` | video | 18 per second of video |
| `elevenlabs/v3/text-to-speech` | voice | 40 per generation |

The values in this table are examples: the current price of each model is always in `GET /v1/models`.

- For text models, `pricing` has `input`, `output` and `cached_input` (input read from the cache, which is cheaper), in credits per 1 million tokens. A request with 1000 input tokens and 500 output tokens on `deepseek-ai/deepseek-v4-flash` costs 0.056 + 0.056 = 0.112 credits, rounded up to 0.12. The minimum per request is 0.01.
- For image, video and voice models, `pricing` has `unit` (`image`, `second` or `generation`) and `credits` per unit.

To see the fields an image, video or voice model accepts, use [`GET /v1/models/{id}`](https://docs.mozout.co.mz/en/ai.md): the response includes `input`, with the name, the type, the accepted values and the default of each field.

## The chat

[`POST /v1/chat/completions`](https://docs.mozout.co.mz/en/ai.md) takes the same body as the OpenAI chat API: `model`, `messages` and, if you want, `max_tokens`, `temperature`, `tools` and the other OpenAI fields. The `model` must be a model of type `text` or one of your [agents](https://docs.mozout.co.mz/en/ai.md).

### Without streaming

Without `stream`, the response comes all at once, when the model finishes, as in the example in the previous section. The text is in `choices[0].message.content` and the token count in `usage`.

### With streaming

With `stream: true`, the response comes in pieces, as the model writes, as `text/event-stream` events that end with `data: [DONE]`. It is the best way to show the text appearing in a chat:

**Python**

```python
stream = client.chat.completions.create(
    model="moonshotai/kimi-k2.6",
    messages=[{"role": "user", "content": "Explain DNS in three short paragraphs."}],
    max_tokens=600,
    stream=True,
    stream_options={"include_usage": True},
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
```

**JavaScript**

```javascript
const stream = await client.chat.completions.create({
  model: "moonshotai/kimi-k2.6",
  messages: [{ role: "user", content: "Explain DNS in three short paragraphs." }],
  max_tokens: 600,
  stream: true,
  stream_options: { include_usage: true },
});
for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}
```

**curl**

```bash
curl -N "https://api.mozout.co.mz/v1/chat/completions" \
  -H "Authorization: Bearer $MOZOUT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "moonshotai/kimi-k2.6", "messages": [{"role": "user", "content": "Explain DNS in three short paragraphs."}], "max_tokens": 600, "stream": true, "stream_options": {"include_usage": true}}'
```


### How chat is charged

- Before calling the model, we reserve credits for the input (about one token per 3 characters) and for `max_tokens` of output. Without `max_tokens`, the reservation counts 4096 output tokens.
- If the balance does not cover the reservation, the response is `402` with `insufficient_credits` and nothing is charged.
- At the end, we charge for the real tokens in `usage` and give the rest of the reservation back to the balance.
- In streaming, the count comes in the last event. If the model does not send it, the reservation stays charged: so always ask for `stream_options` with `include_usage`.

## Agents

An agent is an assistant you set up once and use whenever you want: you choose a text model, write the instructions (what it does, the tone it answers in, what it must not do), add your own texts as knowledge and turn on the tools it needs. Every request to the agent already carries all of this, and your program only sends the user's messages.

### Create an agent

Agents are created in [All in One AI](https://www.meu.mozout.co.mz/all-in-one-ai.php?language=english&currency=2) in Meu MozOut, on the "Agents" tab:

1. Give it a name and choose the model, from the text models.
2. Write the instructions, up to 20,000 characters. If you want, adjust the temperature and `max_tokens`.
3. Turn on the tools the agent may use and add the knowledge.
4. Test it with the "Try it" button: a chat that spends credits and shows the cost of each answer.
5. Copy the agent id from "Use through the API", where there are also ready-made examples.

On the same tab you can pause or delete an agent. A paused agent answers `409` with `agent_paused` until you turn it back on. Each account can have up to 50 agents.

### Use it through the API

An agent is used in the chat you already know, [`POST /v1/chat/completions`](https://docs.mozout.co.mz/en/ai.md), with the same key and the `ai:write` permission. In `model`, send `agent/` followed by the agent id. Do not send the instructions or the knowledge: the agent adds them on its own, before your messages.

**Python**

```python
import os
from openai import OpenAI

client = OpenAI(base_url="https://api.mozout.co.mz/v1", api_key=os.environ["MOZOUT_API_KEY"])

completion = client.chat.completions.create(
    model="agent/7c1e9a42-b35d8f06-a2c4e719-5d0b3f8e",
    messages=[{"role": "user", "content": "What are your opening hours on Saturday?"}],
    max_tokens=400,
)
print(completion.choices[0].message.content)
```

**JavaScript**

```javascript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.mozout.co.mz/v1", apiKey: process.env.MOZOUT_API_KEY });

const completion = await client.chat.completions.create({
  model: "agent/7c1e9a42-b35d8f06-a2c4e719-5d0b3f8e",
  messages: [{ role: "user", content: "What are your opening hours on Saturday?" }],
  max_tokens: 400,
});
console.log(completion.choices[0].message.content);
```

**curl**

```bash
curl "https://api.mozout.co.mz/v1/chat/completions" \
  -H "Authorization: Bearer $MOZOUT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "agent/7c1e9a42-b35d8f06-a2c4e719-5d0b3f8e", "messages": [{"role": "user", "content": "What are your opening hours on Saturday?"}], "max_tokens": 400}'
```


The response has the chat format: the text is in `choices[0].message.content` and the token count in `usage`.

### The agent in the list of models

[`GET /v1/models`](https://docs.mozout.co.mz/en/ai.md) also shows your agents, before the models, with the `id` `agent/<id>` and the `type` `agent`. Each agent also brings the model it uses in `base_model`, the price of that model in `pricing`, the tools in `tools` and its state in `status`. To see only the agents, filter with `type=agent`:

```curl
curl "https://api.mozout.co.mz/v1/models?type=agent" \
  -H "Authorization: Bearer $MOZOUT_API_KEY"
```

Each account only sees its own agents. The agent of another account does not appear in the list and, in chat, gives `404` with `model_not_found`.

### Tools

Tools let the agent fetch information while it prepares the answer. There are three, and each one is turned on in All in One AI:

- `web_fetch`: reads a public web page (`http` or `https`) and returns its text, without HTML, up to 20,000 characters. It waits at most 10 seconds, reads up to 1 MB and refuses private and internal addresses.
- `web_search`: searches the web and returns the top results, with the title, the link and a summary. Each search costs 0.5 credits, on top of the tokens, and the agent makes at most 3 per answer. In Sandbox, the results are examples and cost nothing.
- `current_datetime`: gives the current date and time, so the agent knows, for example, what day it is today.

The agent decides on its own when to use each tool. If the chosen model does not accept tools, the agent answers without them.

### Knowledge

Knowledge is your own texts that the agent reads to answer: prices, opening hours, frequent questions or company rules. Add them on the "Agents" tab, typed there or in a `txt`, `md`, `pdf` or `docx` file, from which the text is taken. Each agent holds up to 200 KB of knowledge in total.

The instructions and the knowledge go in every request as a system message, so they count as input tokens: the shorter they are, the cheaper each request is.

### Limits

- In each request, the agent makes at most 5 tool rounds.
- The model is always the agent's one. The request's `max_tokens` and `temperature` can lower the agent's, but never go above them: a higher value stays at the agent's.
- With `stream: true`, only the final answer comes in pieces. The tool rounds do not appear, so the first piece may take longer.

### What it costs

The agent has no price of its own: you pay for the model it uses, at the price in `GET /v1/models`. Each round to the model spends credits like a chat request, with the reservation and settlement of [How chat is charged](https://docs.mozout.co.mz/en/ai.md). An answer that uses two tools makes three calls to the model, and each call also carries the text of the earlier ones, so it costs more than an answer without tools.

### Sandbox

With a `sandbox_` key, the agent answers in the same format, but calls neither the model nor the tools and charges nothing, like the rest of the AI API (see [Sandbox](https://docs.mozout.co.mz/en/ai.md)). Use it to write your program; to see the agent's real answers, use the agent's "Try it" button in All in One AI or a `prod_` key.

## Image, video and voice

An image, a video or a voice takes from a few seconds to a few minutes to make. So the work has two steps: the request, which answers at once, and the status check, which you repeat until the generation is done. The OpenAI SDK does not have these operations: use plain HTTP requests.

### The request

Send the `model` to [`POST /v1/media/generations`](https://docs.mozout.co.mz/en/ai.md) and, in `input`, the fields of that model (see them in `GET /v1/models/{id}`). Files, such as the starting image of a video, go as public URLs:

**curl**

```bash
curl -X POST "https://api.mozout.co.mz/v1/media/generations" \
  -H "Authorization: Bearer $MOZOUT_API_KEY" \
  -H "Accept-Language: en" \
  -H "Idempotency-Key: 9f1c2d3e-example" \
  -H "Content-Type: application/json" \
  -d '{"model": "openai/gpt-image-2/text-to-image", "input": {"prompt": "A bright, modern office with plants and soft morning light", "size": "1024x1024", "quality": "medium"}}'
```

**PHP**

```php
<?php
$ch = curl_init('https://api.mozout.co.mz/v1/media/generations');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => '{"model": "openai/gpt-image-2/text-to-image", "input": {"prompt": "A bright, modern office with plants and soft morning light", "size": "1024x1024", "quality": "medium"}}',
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('MOZOUT_API_KEY'),
        'Accept-Language: en',
        'Idempotency-Key: 9f1c2d3e-example',
        'Content-Type: application/json',
    ],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo $status, PHP_EOL, $body, PHP_EOL;
```

**Python**

```python
import os
import requests

headers = {
    "Authorization": "Bearer " + os.environ["MOZOUT_API_KEY"],
    "Accept-Language": "en",
    "Idempotency-Key": "9f1c2d3e-example",
}
payload = {"model": "openai/gpt-image-2/text-to-image", "input": {"prompt": "A bright, modern office with plants and soft morning light", "size": "1024x1024", "quality": "medium"}}
r = requests.post("https://api.mozout.co.mz/v1/media/generations", headers=headers, json=payload, timeout=30)
print(r.status_code)
print(r.text)
```

**JavaScript**

```javascript
const response = await fetch("https://api.mozout.co.mz/v1/media/generations", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.MOZOUT_API_KEY}`,
    "Accept-Language": "en",
    "Idempotency-Key": "9f1c2d3e-example",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({"model": "openai/gpt-image-2/text-to-image", "input": {"prompt": "A bright, modern office with plants and soft morning light", "size": "1024x1024", "quality": "medium"}}),
});
console.log(response.status);
console.log(await response.text());
```


The response is `202`, with the `id` of the generation, the `status` `processing` and the credits reserved in `credits_reserved`.

### Follow it to the end

Call [`GET /v1/media/generations/{id}`](https://docs.mozout.co.mz/en/ai.md) every 5 to 10 seconds, until the `status` is no longer `processing`:

- `completed`: the files are in `outputs` and the real cost in `credits_charged`. If the reservation was larger, the rest goes back to the balance.
- `failed`: the reason is in `error`, nothing is charged and the reservation goes back to the balance.

A complete example in Python, from the request to the link of the file:

```python
import os, time, requests

API = "https://api.mozout.co.mz/v1"
H = {"Authorization": "Bearer " + os.environ["MOZOUT_API_KEY"]}

job = requests.post(API + "/media/generations", headers=H, timeout=30, json={
    "model": "openai/gpt-image-2/text-to-image",
    "input": {"prompt": "A bright, modern office with plants and soft morning light", "size": "1024x1024"},
}).json()["data"]

while job["status"] == "processing":
    time.sleep(5)
    job = requests.get(API + "/media/generations/" + job["id"], headers=H, timeout=30).json()["data"]

print(job["status"], job["outputs"], job["credits_charged"])
```

The links in `outputs` are not permanent: download the files and keep a copy of your own.

### A video and a voice

The request is the same for every type: only the `model` and the fields of `input` change. A 5-second video in 720p:

```json
{"model": "bytedance/seedance-2.0-mini/text-to-video", "input": {"prompt": "A drone shot over a coastal city at sunset", "duration": 5, "resolution": "720p", "ratio": "16:9"}}
```

A voice from a text:

```json
{"model": "elevenlabs/v3/text-to-speech", "input": {"text": "Hello! Thank you for calling. How can we help you today?"}}
```

## The credit balance

[`GET /v1/ai/balance`](https://docs.mozout.co.mz/en/ai.md) returns the AI credits of the account in `credits`, with two decimal places. It is the same balance with `sandbox_` and `prod_` keys. Chat and generations take credits from here, and reservations that are not spent come back here. With a Coding Plan, `subscription` also shows the points left this week and this month.

## Top up credits and subscribe to a plan

[`GET /v1/ai/credits/prices`](https://docs.mozout.co.mz/en/ai.md) shows the price of each credit by quantity and [`POST /v1/ai/credits/purchase`](https://docs.mozout.co.mz/en/ai.md) buys `quantity` credits with the account credit, at the same price as in [Meu MozOut](https://www.meu.mozout.co.mz/clientarea.php?language=english&currency=2). It needs `billing:purchase`, `ai:write` and the `Idempotency-Key` header. The credits enter the balance with the payment.

**curl**

```bash
curl -X POST "https://api.mozout.co.mz/v1/ai/credits/purchase" \
  -H "Authorization: Bearer $MOZOUT_API_KEY" \
  -H "Accept-Language: en" \
  -H "Idempotency-Key: 9f1c2d3e-example" \
  -H "Content-Type: application/json" \
  -d '{"quantity": 1000}'
```

**PHP**

```php
<?php
$ch = curl_init('https://api.mozout.co.mz/v1/ai/credits/purchase');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => '{"quantity": 1000}',
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('MOZOUT_API_KEY'),
        'Accept-Language: en',
        'Idempotency-Key: 9f1c2d3e-example',
        'Content-Type: application/json',
    ],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo $status, PHP_EOL, $body, PHP_EOL;
```

**Python**

```python
import os
import requests

headers = {
    "Authorization": "Bearer " + os.environ["MOZOUT_API_KEY"],
    "Accept-Language": "en",
    "Idempotency-Key": "9f1c2d3e-example",
}
payload = {"quantity": 1000}
r = requests.post("https://api.mozout.co.mz/v1/ai/credits/purchase", headers=headers, json=payload, timeout=30)
print(r.status_code)
print(r.text)
```

**JavaScript**

```javascript
const response = await fetch("https://api.mozout.co.mz/v1/ai/credits/purchase", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.MOZOUT_API_KEY}`,
    "Accept-Language": "en",
    "Idempotency-Key": "9f1c2d3e-example",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({"quantity": 1000}),
});
console.log(response.status);
console.log(await response.text());
```


A Coding Plan is bought like the other plans, with [`POST /v1/services/purchase`](https://docs.mozout.co.mz/en/hosting.md) and `ai:write` (see [Hosting](https://docs.mozout.co.mz/en/hosting.md)); one per account. To move to a bigger plan, use [`POST /v1/services/{id}/upgrade`](https://docs.mozout.co.mz/en/billing.md), also with `ai:write`.

## Sandbox

With a `sandbox_` key, the AI API answers in the same format, but calls no model and charges nothing:

- Chat always answers `Resposta de teste (sandbox).`, with `usage` at zero, also in streaming.
- A generation is `completed` at once, with an example link in `outputs` and `0` credits.
- The list of models, the prices and the balance are the real ones.

So you can write and test your whole program without spending credits, and then just swap the key for the `prod_` one. See [Sandbox and Production](https://docs.mozout.co.mz/en/api-rules.md).

## Errors

Errors use the same format as the rest of the API, with `code`, `message`, `correlation_id` and `details` inside `error`. The OpenAI SDKs read the message from `error.message` and raise an exception with the HTTP status (in Python, `openai.APIStatusError`, with `status_code`).

| Status | Code | When it happens | What to do |
|---|---|---|---|
| `402` | `insufficient_credits` | The credits do not cover the reservation. `details.required` says how much is needed and `details.balance` how much you have. | Buy credits in All in One AI or lower `max_tokens`. |
| `403` | `insufficient_scope` | The key does not have `ai:read` or `ai:write`. | Create a key with the right permission. |
| `404` | `model_not_found` | The model does not exist, is not of the right type (for example, an image model in chat) or is an agent of another account. | Check the `id` in `GET /v1/models`. |
| `404` | `not_found` | The generation does not exist or belongs to another account. | Check the `id` returned by the request. |
| `409` | `agent_paused` | The agent is paused. | Turn it back on in the "Agents" tab of All in One AI. |
| `422` | `validation_failed` | A field is missing or a value is not one of the options. | See `details` and the fields in `GET /v1/models/{id}`. |
| `429` | `rate_limited` | You went over the limit of requests per minute. | Wait the number of seconds given in `Retry-After`. |
| `429` | `plan_limit_reached` | The Coding Plan points ran out and the request cannot be paid with credits. | Wait for `details.resets_at` or see [Plans and credits](https://docs.mozout.co.mz/en/coding-tools.md). |
| `502` | `upstream_error` | The AI service did not respond as expected. | Try again in a little while. |

The full list of codes is in [Errors](https://docs.mozout.co.mz/en/api-rules.md).

## Good practices

- Use the key only on your server, in an environment variable. Never put it in code that runs in the browser or in a mobile app.
- Create a key with only `ai:read` and `ai:write` for each program that uses AI, and develop with a `sandbox_` key.
- Always set `max_tokens`: it limits the size of the response and lowers the reservation, which avoids `402` when the balance is low.
- For generations, send the `Idempotency-Key` header: if you repeat the request after a network failure, you do not pay for two generations. See [Idempotency](https://docs.mozout.co.mz/en/api-rules.md).
- Check generations every 5 seconds or more. Each key has a limit of 90 requests per minute.
- Before a large batch, check the balance with `GET /v1/ai/balance` and the price of the models with `GET /v1/models`.


## Operations

12 operations in this area. Click an operation to see its parameters, examples and responses, or to try it in the Playground, without leaving the page.

### List the AI models

`GET https://api.mozout.co.mz/v1/models`

Needs `ai:read`. Every model on sale, in the OpenAI format (`{"object": "list", "data": [...]}`), so `client.models.list()` of the OpenAI SDKs works. Each model comes with its type and its price in credits. Your own agents come first, with `type` `agent` and the id `agent/<id>`. Filter with `type` and `q`. The list is the same with a `sandbox_` key and a `prod_` key.

#### Authentication

Needs a valid key in the `Authorization: Bearer` header. Required permission: `ai:read`.

#### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `type` | query | string: text, image, video, audio, agent | no | Only models of this type. `agent` lists only your agents. |
| `q` | query | string | no | Search in the id, the name and the description. |
| `X-API-Mode` | header | string: sandbox, production | no | Optional. If it does not match the mode of the key, the request is refused with `invalid_request` and reason `mode_mismatch`. Use it to make sure a program never runs with the wrong key. |

#### Examples

**curl**

```bash
curl "https://api.mozout.co.mz/v1/models" \
  -H "Authorization: Bearer $MOZOUT_API_KEY" \
  -H "Accept-Language: en"
```

**PHP**

```php
<?php
$ch = curl_init('https://api.mozout.co.mz/v1/models');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('MOZOUT_API_KEY'),
        'Accept-Language: en',
    ],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo $status, PHP_EOL, $body, PHP_EOL;
```

**Python**

```python
import os
import requests

headers = {
    "Authorization": "Bearer " + os.environ["MOZOUT_API_KEY"],
    "Accept-Language": "en",
}
r = requests.get("https://api.mozout.co.mz/v1/models", headers=headers, timeout=30)
print(r.status_code)
print(r.text)
```

**JavaScript**

```javascript
const response = await fetch("https://api.mozout.co.mz/v1/models", {
  headers: {
    Authorization: `Bearer ${process.env.MOZOUT_API_KEY}`,
    "Accept-Language": "en",
  },
});
console.log(response.status);
console.log(await response.text());
```


#### Responses

##### `200`

List the AI models.

```json
{
  "object": "list",
  "data": [
    {
      "id": "agent/7c1e9a42-b35d8f06-a2c4e719-5d0b3f8e",
      "object": "model",
      "owned_by": "user",
      "type": "agent",
      "category": "agent",
      "name": "Support assistant",
      "description": "Answers customer questions about our plans.",
      "base_model": "deepseek-ai/deepseek-v4-flash",
      "status": "active",
      "tools": [
        "web_fetch",
        "current_datetime"
      ],
      "pricing": {
        "unit": "1M tokens",
        "input": 56.0,
        "output": 112.0,
        "cached_input": 11.2
      }
    },
    {
      "id": "deepseek-ai/deepseek-v4-flash",
      "object": "model",
      "owned_by": "deepseek-ai",
      "type": "text",
      "category": "LLM",
      "name": "DeepSeek V4 Flash",
      "description": "Fast language model with strong reasoning and long context.",
      "context_length": 1048576,
      "max_output_tokens": 393216,
      "pricing": {
        "unit": "1M tokens",
        "input": 56.0,
        "output": 112.0,
        "cached_input": 11.2
      }
    },
    {
      "id": "moonshotai/kimi-k2.6",
      "object": "model",
      "owned_by": "moonshotai",
      "type": "text",
      "category": "LLM",
      "name": "Kimi K2.6",
      "description": "Enhanced model for reasoning, coding, and productivity.",
      "context_length": 262144,
      "max_output_tokens": 262144,
      "pricing": {
        "unit": "1M tokens",
        "input": 380.0,
        "output": 1600.0,
        "cached_input": 64.0
      }
    },
    {
      "id": "openai/gpt-image-2/text-to-image",
      "object": "model",
      "owned_by": "openai",
      "type": "image",
      "category": "text-to-image",
      "name": "GPT Image 2 Text-to-Image",
      "description": "Fast, cost-efficient text-to-image generator.",
      "pricing": {
        "unit": "image",
        "credits": 2
      }
    },
    {
      "id": "bytedance/seedance-2.0-mini/text-to-video",
      "object": "model",
      "owned_by": "bytedance",
      "type": "video",
      "category": "text-to-video",
      "name": "Seedance 2.0 Mini Text-to-Video",
      "description": "Lightweight, economical video generation from text prompts with native audio.",
      "pricing": {
        "unit": "second",
        "credits": 18
      }
    },
    {
      "id": "elevenlabs/v3/text-to-speech",
      "object": "model",
      "owned_by": "elevenlabs",
      "type": "audio",
      "category": "text-to-speech",
      "name": "ElevenLabs v3 Text-to-Speech",
      "description": "High-quality speech generation from text.",
      "pricing": {
        "unit": "generation",
        "credits": 40
      }
    }
  ]
}
```

| Field | Type | Description |
|---|---|---|
| `object` | string | Always `list`. |

| Header | Description |
|---|---|
| `X-Correlation-ID` | Identifier of this request. Give it to support when you report a problem. |
| `X-RateLimit-Limit` | Requests allowed per minute. |
| `X-RateLimit-Remaining` | Requests left in the current minute. |
| `X-RateLimit-Reset` | When the minute ends, as a Unix timestamp in seconds. |
| `X-API-Mode` | The mode of the key that made the request: `sandbox` or `production`. |

##### `401`

The key is missing, invalid, revoked or expired, or the user who created it no longer has access to the account.

```json
{
  "error": {
    "code": "unauthorized",
    "message": "Missing or invalid API key.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `403`

The account cannot use the API (`forbidden`), the key lacks the permission (`insufficient_scope`), or the IP address is not on the list of the key (`ip_not_allowed`).

```json
{
  "error": {
    "code": "insufficient_scope",
    "message": "This key does not have the required permission.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "required": "dns:read"
    }
  }
}
```

##### `422`

Some of the data is not valid.

```json
{
  "error": {
    "code": "validation_failed",
    "message": "Some of the data is not valid.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `429`

Too many requests. Wait for the time in Retry-After.

```json
{
  "error": {
    "code": "rate_limited",
    "message": "Too many requests. Please try again shortly.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "retry_after": 42
    }
  }
}
```

| Header | Description |
|---|---|
| `Retry-After` | Seconds to wait before trying again. |

##### `500`

An internal error occurred. Give the correlation_id to support.

```json
{
  "error": {
    "code": "internal_error",
    "message": "An internal error occurred. Please give the correlation_id to support.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `502`

The service behind the API did not respond as expected.

```json
{
  "error": {
    "code": "upstream_error",
    "message": "The service did not respond as expected. Please try again later.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `503`

The API is turned off.

```json
{
  "error": {
    "code": "disabled",
    "message": "The API is currently turned off.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```


#### Errors

| Status | Code | Meaning |
|---|---|---|
| 401 | `unauthorized` | The key is missing, invalid, revoked or expired, or the user who created it no longer has access to the account. |
| 403 | `forbidden`, `insufficient_scope`, `ip_not_allowed` | The account cannot use the API (`forbidden`), the key lacks the permission (`insufficient_scope`), or the IP address is not on the list of the key (`ip_not_allowed`). |
| 422 | `validation_failed` | Some of the data is not valid. |
| 429 | `rate_limited` | Too many requests. Wait for the time in Retry-After. |
| 500 | `internal_error` | An internal error occurred. Give the correlation_id to support. |
| 502 | `upstream_error` | The service behind the API did not respond as expected. |
| 503 | `disabled` | The API is turned off. |

The error format is explained in [Errors](https://docs.mozout.co.mz/en/api-rules.md).


### Get an AI model

`GET https://api.mozout.co.mz/v1/models/{id}`

Needs `ai:read`. One model, in the same format as the list. Image, video and voice models also bring `input`: the fields to send inside `input` in POST /v1/media/generations, with the accepted values and the defaults.

#### Authentication

Needs a valid key in the `Authorization: Bearer` header. Required permission: `ai:read`.

#### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | path | string | yes | The model id, slash included, such as `deepseek-ai/deepseek-v4-flash` or `openai/gpt-image-2/text-to-image`, or `agent/<id>` for one of your agents. Send it as it is. |
| `X-API-Mode` | header | string: sandbox, production | no | Optional. If it does not match the mode of the key, the request is refused with `invalid_request` and reason `mode_mismatch`. Use it to make sure a program never runs with the wrong key. |

#### Examples

**curl**

```bash
curl "https://api.mozout.co.mz/v1/models/deepseek-ai/deepseek-v4-flash" \
  -H "Authorization: Bearer $MOZOUT_API_KEY" \
  -H "Accept-Language: en"
```

**PHP**

```php
<?php
$ch = curl_init('https://api.mozout.co.mz/v1/models/deepseek-ai/deepseek-v4-flash');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('MOZOUT_API_KEY'),
        'Accept-Language: en',
    ],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo $status, PHP_EOL, $body, PHP_EOL;
```

**Python**

```python
import os
import requests

headers = {
    "Authorization": "Bearer " + os.environ["MOZOUT_API_KEY"],
    "Accept-Language": "en",
}
r = requests.get("https://api.mozout.co.mz/v1/models/deepseek-ai/deepseek-v4-flash", headers=headers, timeout=30)
print(r.status_code)
print(r.text)
```

**JavaScript**

```javascript
const response = await fetch("https://api.mozout.co.mz/v1/models/deepseek-ai/deepseek-v4-flash", {
  headers: {
    Authorization: `Bearer ${process.env.MOZOUT_API_KEY}`,
    "Accept-Language": "en",
  },
});
console.log(response.status);
console.log(await response.text());
```


#### Responses

##### `200`

Get an AI model.

```json
{
  "id": "openai/gpt-image-2/text-to-image",
  "object": "model",
  "owned_by": "openai",
  "type": "image",
  "category": "text-to-image",
  "name": "GPT Image 2 Text-to-Image",
  "description": "Fast, cost-efficient text-to-image generator.",
  "pricing": {
    "unit": "image",
    "credits": 2
  },
  "input": [
    {
      "name": "prompt",
      "type": "string",
      "required": true,
      "options": null,
      "default": null,
      "min": null,
      "max": null,
      "description": "What the image should show."
    },
    {
      "name": "size",
      "type": "string",
      "required": false,
      "options": [
        "1024x1024",
        "1024x1536",
        "1536x1024",
        "2048x2048"
      ],
      "default": "1024x1024",
      "min": null,
      "max": null,
      "description": "The size of the image, in pixels."
    },
    {
      "name": "quality",
      "type": "string",
      "required": false,
      "options": [
        "low",
        "medium",
        "high"
      ],
      "default": "medium",
      "min": null,
      "max": null,
      "description": "The quality of the image."
    },
    {
      "name": "output_format",
      "type": "string",
      "required": false,
      "options": [
        "jpeg",
        "png"
      ],
      "default": "jpeg",
      "min": null,
      "max": null,
      "description": "The file format."
    }
  ]
}
```

| Field | Type | Description |
|---|---|---|
| `id` | string | The model id, to send in `model`. It has a slash, such as `deepseek-ai/deepseek-v4-flash`. |
| `object` | string | Always `model`. |
| `owned_by` | string | Who made the model: the part of the id before the first slash. |
| `type` | string: text, image, video, audio, agent | What the model produces. Only `text` models and your agents (`agent`, id `agent/<id>`) work in POST /v1/chat/completions; the others work in POST /v1/media/generations. |
| `category` | string | A more detailed category, such as `LLM`, `text-to-image`, `image-to-video` or `text-to-speech`. |
| `name` | string | The name to show to people. |
| `description` | string, null | What the model is good at. In Portuguese when there is a translation and the request asks for `pt`. |
| `pricing` | object | The price in credits. Text models: `unit` is `1M tokens`, with `input`, `output` and `cached_input` (input read from the cache). Image, video and voice models: `unit` is `image`, `second` or `generation`, with `credits`. |
| `pricing.unit` | string: 1M tokens, image, second, generation | What the price is counted by. |
| `pricing.input` | number | Text only: credits per 1 million input tokens. |
| `pricing.output` | number | Text only: credits per 1 million output tokens. |
| `pricing.cached_input` | number | Text only: credits per 1 million input tokens read from the cache. |
| `pricing.credits` | number | Image, video and voice only: credits per `unit`. |
| `context_length` | integer | Text models and agents: the most tokens the model reads in one request (input and output together). Use it in the context window setting of coding tools. |
| `max_output_tokens` | integer | Text models and agents: the most tokens the model writes in one answer. |
| `base_model` | string | Agents only: the text model the agent uses. `pricing` is the price of this model. |
| `status` | string: active, paused | Agents only: a `paused` agent answers `409` with `agent_paused`. |
| `tools` | array<string> | Agents only: the tools turned on, `web_fetch` and `current_datetime`. |
| `input` | array<object> | Image, video and voice models only: the fields that go inside `input` in POST /v1/media/generations. |

| Header | Description |
|---|---|
| `X-Correlation-ID` | Identifier of this request. Give it to support when you report a problem. |
| `X-RateLimit-Limit` | Requests allowed per minute. |
| `X-RateLimit-Remaining` | Requests left in the current minute. |
| `X-RateLimit-Reset` | When the minute ends, as a Unix timestamp in seconds. |
| `X-API-Mode` | The mode of the key that made the request: `sandbox` or `production`. |

##### `401`

The key is missing, invalid, revoked or expired, or the user who created it no longer has access to the account.

```json
{
  "error": {
    "code": "unauthorized",
    "message": "Missing or invalid API key.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `403`

The account cannot use the API (`forbidden`), the key lacks the permission (`insufficient_scope`), or the IP address is not on the list of the key (`ip_not_allowed`).

```json
{
  "error": {
    "code": "insufficient_scope",
    "message": "This key does not have the required permission.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "required": "dns:read"
    }
  }
}
```

##### `404`

The model does not exist in the catalog, or it is not of the right type for this operation (`model_not_found`). See GET /v1/models.

```json
{
  "error": {
    "code": "model_not_found",
    "message": "This model does not exist.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "model": "example/unknown-model"
    }
  }
}
```

##### `429`

Too many requests. Wait for the time in Retry-After.

```json
{
  "error": {
    "code": "rate_limited",
    "message": "Too many requests. Please try again shortly.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "retry_after": 42
    }
  }
}
```

| Header | Description |
|---|---|
| `Retry-After` | Seconds to wait before trying again. |

##### `500`

An internal error occurred. Give the correlation_id to support.

```json
{
  "error": {
    "code": "internal_error",
    "message": "An internal error occurred. Please give the correlation_id to support.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `502`

The service behind the API did not respond as expected.

```json
{
  "error": {
    "code": "upstream_error",
    "message": "The service did not respond as expected. Please try again later.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `503`

The API is turned off.

```json
{
  "error": {
    "code": "disabled",
    "message": "The API is currently turned off.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```


#### Errors

| Status | Code | Meaning |
|---|---|---|
| 401 | `unauthorized` | The key is missing, invalid, revoked or expired, or the user who created it no longer has access to the account. |
| 403 | `forbidden`, `insufficient_scope`, `ip_not_allowed` | The account cannot use the API (`forbidden`), the key lacks the permission (`insufficient_scope`), or the IP address is not on the list of the key (`ip_not_allowed`). |
| 404 | `model_not_found` | The model does not exist in the catalog, or it is not of the right type for this operation (`model_not_found`). See GET /v1/models. |
| 429 | `rate_limited` | Too many requests. Wait for the time in Retry-After. |
| 500 | `internal_error` | An internal error occurred. Give the correlation_id to support. |
| 502 | `upstream_error` | The service behind the API did not respond as expected. |
| 503 | `disabled` | The API is turned off. |

The error format is explained in [Errors](https://docs.mozout.co.mz/en/api-rules.md).


### Chat with a text model

`POST https://api.mozout.co.mz/v1/chat/completions`

Needs `ai:write`. Compatible with the OpenAI chat API: point the OpenAI SDK at this API (`base_url`) and use your key. Before calling the model we reserve credits for the input (about one token per 3 characters) and for `max_tokens` of output; if the balance is not enough, the answer is `402` and nothing is charged. At the end we charge by the real `usage` and give back the difference. With `stream: true` the answer comes as `text/event-stream`. With a `sandbox_` key the model is not called and nothing is charged: the answer is always `Resposta de teste (sandbox).`, with `usage` at zero, also in streaming. With `"model": "agent/<id>"` the request goes to one of your agents: it adds its instructions and knowledge, uses its model, runs its tools (at most 5 rounds, each one charged as a chat request) and never goes above its `max_tokens` and `temperature`; with `stream: true` only the final answer is streamed.

#### Authentication

Needs a valid key in the `Authorization: Bearer` header. Required permission: `ai:write`.

#### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `Idempotency-Key` | header | string | no | Any unique value, up to 255 visible characters. Valid for 24 hours per key. Repeating the same request returns the saved answer; a different body, or a first request still in progress, returns 409. |
| `X-API-Mode` | header | string: sandbox, production | no | Optional. If it does not match the mode of the key, the request is refused with `invalid_request` and reason `mode_mismatch`. Use it to make sure a program never runs with the wrong key. |

#### Request body

| Field | Type | Required | Description |
|---|---|---|---|
| `model` | string | yes | A `text` model id from GET /v1/models, or `agent/<id>` to use one of your agents. |
| `messages` | array<object> | yes | The conversation, oldest first. |
| `stream` | boolean | no | `true` to receive the answer in pieces, as server-sent events (`text/event-stream`), ending with `data: [DONE]`. |
| `max_tokens` | integer | no | The most tokens the answer may have. Without it we reserve 4096. A lower value reserves fewer credits. |
| `temperature` | number | no | From 0 to 2: lower is more predictable. |
| `tools` | array<object> | no | Functions the model may call, in the OpenAI format. |
| `stream_options` | object | no | With `stream`, send `{"include_usage": true}` to get the token count in the last event. |

#### Examples

**curl**

```bash
curl -X POST "https://api.mozout.co.mz/v1/chat/completions" \
  -H "Authorization: Bearer $MOZOUT_API_KEY" \
  -H "Accept-Language: en" \
  -H "Idempotency-Key: 9f1c2d3e-example" \
  -H "Content-Type: application/json" \
  -d '{"model": "deepseek-ai/deepseek-v4-flash", "messages": [{"role": "system", "content": "You are a helpful assistant for a web hosting company."}, {"role": "user", "content": "Write a two-sentence welcome message for our website."}], "max_tokens": 200}'
```

**PHP**

```php
<?php
$ch = curl_init('https://api.mozout.co.mz/v1/chat/completions');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => '{"model": "deepseek-ai/deepseek-v4-flash", "messages": [{"role": "system", "content": "You are a helpful assistant for a web hosting company."}, {"role": "user", "content": "Write a two-sentence welcome message for our website."}], "max_tokens": 200}',
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('MOZOUT_API_KEY'),
        'Accept-Language: en',
        'Idempotency-Key: 9f1c2d3e-example',
        'Content-Type: application/json',
    ],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo $status, PHP_EOL, $body, PHP_EOL;
```

**Python**

```python
import os
import requests

headers = {
    "Authorization": "Bearer " + os.environ["MOZOUT_API_KEY"],
    "Accept-Language": "en",
    "Idempotency-Key": "9f1c2d3e-example",
}
payload = {"model": "deepseek-ai/deepseek-v4-flash", "messages": [{"role": "system", "content": "You are a helpful assistant for a web hosting company."}, {"role": "user", "content": "Write a two-sentence welcome message for our website."}], "max_tokens": 200}
r = requests.post("https://api.mozout.co.mz/v1/chat/completions", headers=headers, json=payload, timeout=30)
print(r.status_code)
print(r.text)
```

**JavaScript**

```javascript
const response = await fetch("https://api.mozout.co.mz/v1/chat/completions", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.MOZOUT_API_KEY}`,
    "Accept-Language": "en",
    "Idempotency-Key": "9f1c2d3e-example",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({"model": "deepseek-ai/deepseek-v4-flash", "messages": [{"role": "system", "content": "You are a helpful assistant for a web hosting company."}, {"role": "user", "content": "Write a two-sentence welcome message for our website."}], "max_tokens": 200}),
});
console.log(response.status);
console.log(await response.text());
```


#### Responses

##### `200`

Chat with a text model.

```json
{
  "id": "chatcmpl-8f2c1a7e5b9d4c3a",
  "object": "chat.completion",
  "created": 1795420800,
  "model": "deepseek-ai/deepseek-v4-flash",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Welcome! We keep your website fast, safe and online, so you can focus on your business."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 31,
    "completion_tokens": 22,
    "total_tokens": 53,
    "prompt_tokens_details": {
      "cached_tokens": 0
    }
  }
}
```

| Field | Type | Description |
|---|---|---|
| `object` | string | `chat.completion`. |
| `created` | integer | Unix time. |
| `usage` | object | The tokens counted. We charge by these numbers and give back the rest of the reservation. |
| `usage.prompt_tokens_details.cached_tokens` | integer | Input tokens read from the cache, charged at `cached_input`. |

| Header | Description |
|---|---|
| `X-Correlation-ID` | Identifier of this request. Give it to support when you report a problem. |
| `X-RateLimit-Limit` | Requests allowed per minute. |
| `X-RateLimit-Remaining` | Requests left in the current minute. |
| `X-RateLimit-Reset` | When the minute ends, as a Unix timestamp in seconds. |
| `X-API-Mode` | The mode of the key that made the request: `sandbox` or `production`. |

##### `401`

The key is missing, invalid, revoked or expired, or the user who created it no longer has access to the account.

```json
{
  "error": {
    "code": "unauthorized",
    "message": "Missing or invalid API key.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `402`

Not enough AI credits for this request (`insufficient_credits`). Nothing was charged. `details.required` is what the request needs and `details.balance` is what the account has.

```json
{
  "error": {
    "code": "insufficient_credits",
    "message": "Not enough credits for this request. Nothing was charged.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "required": 46.12,
      "balance": 12.5
    }
  }
}
```

##### `403`

The account cannot use the API (`forbidden`), the key lacks the permission (`insufficient_scope`), or the IP address is not on the list of the key (`ip_not_allowed`).

```json
{
  "error": {
    "code": "insufficient_scope",
    "message": "This key does not have the required permission.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "required": "dns:read"
    }
  }
}
```

##### `404`

The model does not exist in the catalog, or it is not of the right type for this operation (`model_not_found`). See GET /v1/models.

```json
{
  "error": {
    "code": "model_not_found",
    "message": "This model does not exist.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "model": "example/unknown-model"
    }
  }
}
```

##### `409`

The agent in `model` is paused (`agent_paused`). Nothing was charged. Turn it back on in All in One AI.

```json
{
  "error": {
    "code": "agent_paused",
    "message": "This agent is paused.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "model": "agent/7c1e9a42-b35d8f06-a2c4e719-5d0b3f8e"
    }
  }
}
```

##### `422`

Some of the data is not valid.

```json
{
  "error": {
    "code": "validation_failed",
    "message": "Some of the data is not valid.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `429`

Too many requests per minute for this key (`rate_limited`, wait the seconds in `Retry-After`), or the points of your Coding Plan ran out for the week or the month (`plan_limit_reached`). With `plan_limit_reached`, `details` has `limit` (`weekly` or `monthly`), `used`, `remaining`, `resets_at`, `fallback_to_credits` and `credits`. It only happens when "Use credits when the plan runs out" is off, or when the account has no credits left.

```json
{
  "error": {
    "code": "plan_limit_reached",
    "message": "Your plan's weekly limit has been reached.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "limit": "weekly",
      "used": 16500000,
      "remaining": 0,
      "resets_at": "2026-11-23T00:00:00+00:00",
      "fallback_to_credits": false,
      "credits": 0
    }
  }
}
```

| Header | Description |
|---|---|
| `Retry-After` | Seconds to wait before trying again. |

##### `500`

An internal error occurred. Give the correlation_id to support.

```json
{
  "error": {
    "code": "internal_error",
    "message": "An internal error occurred. Please give the correlation_id to support.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `502`

The service behind the API did not respond as expected.

```json
{
  "error": {
    "code": "upstream_error",
    "message": "The service did not respond as expected. Please try again later.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `503`

The API is turned off.

```json
{
  "error": {
    "code": "disabled",
    "message": "The API is currently turned off.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```


#### Errors

| Status | Code | Meaning |
|---|---|---|
| 401 | `unauthorized` | The key is missing, invalid, revoked or expired, or the user who created it no longer has access to the account. |
| 402 | `insufficient_credits` | Not enough AI credits for this request (`insufficient_credits`). Nothing was charged. `details.required` is what the request needs and `details.balance` is what the account has. |
| 403 | `forbidden`, `insufficient_scope`, `ip_not_allowed` | The account cannot use the API (`forbidden`), the key lacks the permission (`insufficient_scope`), or the IP address is not on the list of the key (`ip_not_allowed`). |
| 404 | `model_not_found` | The model does not exist in the catalog, or it is not of the right type for this operation (`model_not_found`). See GET /v1/models. |
| 409 | `agent_paused` | The agent in `model` is paused (`agent_paused`). Nothing was charged. Turn it back on in All in One AI. |
| 422 | `validation_failed` | Some of the data is not valid. |
| 429 | `rate_limited`, `plan_limit_reached`, `plan_limit_reached` | Too many requests per minute for this key (`rate_limited`, wait the seconds in `Retry-After`), or the points of your Coding Plan ran out for the week or the month (`plan_limit_reached`). With `plan_limit_reached`, `details` has `limit` (`weekly` or `monthly`), `used`, `remaining`, `resets_at`, `fallback_to_credits` and `credits`. It only happens when "Use credits when the plan runs out" is off, or when the account has no credits left. |
| 500 | `internal_error` | An internal error occurred. Give the correlation_id to support. |
| 502 | `upstream_error` | The service behind the API did not respond as expected. |
| 503 | `disabled` | The API is turned off. |

The error format is explained in [Errors](https://docs.mozout.co.mz/en/api-rules.md).


### Start an image, video or voice generation

`POST https://api.mozout.co.mz/v1/media/generations`

Needs `ai:write`. Images, videos and voice take from a few seconds to a few minutes, so the answer is `202` right away, with the `id` of the generation and the credits reserved. Then call GET /v1/media/generations/{id} until `status` is `completed` or `failed`. If the balance is not enough for the reservation, the answer is `402` and nothing is charged. With a `sandbox_` key nothing is made and nothing is charged: the generation is `completed` at once, with an example link and `0` credits.

#### Authentication

Needs a valid key in the `Authorization: Bearer` header. Required permission: `ai:write`.

#### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `Idempotency-Key` | header | string | no | Any unique value, up to 255 visible characters. Valid for 24 hours per key. Repeating the same request returns the saved answer; a different body, or a first request still in progress, returns 409. |
| `X-API-Mode` | header | string: sandbox, production | no | Optional. If it does not match the mode of the key, the request is refused with `invalid_request` and reason `mode_mismatch`. Use it to make sure a program never runs with the wrong key. |

#### Request body

| Field | Type | Required | Description |
|---|---|---|---|
| `model` | string | yes | An `image`, `video` or `audio` model id from GET /v1/models. |
| `input` | object | yes | The fields of the model, as listed in `input` of GET /v1/models/{id}. Files (images, videos, audio) go as public URLs. |

#### Examples

**curl**

```bash
curl -X POST "https://api.mozout.co.mz/v1/media/generations" \
  -H "Authorization: Bearer $MOZOUT_API_KEY" \
  -H "Accept-Language: en" \
  -H "Idempotency-Key: 9f1c2d3e-example" \
  -H "Content-Type: application/json" \
  -d '{"model": "openai/gpt-image-2/text-to-image", "input": {"prompt": "A bright, modern office with plants and soft morning light", "size": "1024x1024", "quality": "medium"}}'
```

**PHP**

```php
<?php
$ch = curl_init('https://api.mozout.co.mz/v1/media/generations');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => '{"model": "openai/gpt-image-2/text-to-image", "input": {"prompt": "A bright, modern office with plants and soft morning light", "size": "1024x1024", "quality": "medium"}}',
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('MOZOUT_API_KEY'),
        'Accept-Language: en',
        'Idempotency-Key: 9f1c2d3e-example',
        'Content-Type: application/json',
    ],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo $status, PHP_EOL, $body, PHP_EOL;
```

**Python**

```python
import os
import requests

headers = {
    "Authorization": "Bearer " + os.environ["MOZOUT_API_KEY"],
    "Accept-Language": "en",
    "Idempotency-Key": "9f1c2d3e-example",
}
payload = {"model": "openai/gpt-image-2/text-to-image", "input": {"prompt": "A bright, modern office with plants and soft morning light", "size": "1024x1024", "quality": "medium"}}
r = requests.post("https://api.mozout.co.mz/v1/media/generations", headers=headers, json=payload, timeout=30)
print(r.status_code)
print(r.text)
```

**JavaScript**

```javascript
const response = await fetch("https://api.mozout.co.mz/v1/media/generations", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.MOZOUT_API_KEY}`,
    "Accept-Language": "en",
    "Idempotency-Key": "9f1c2d3e-example",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({"model": "openai/gpt-image-2/text-to-image", "input": {"prompt": "A bright, modern office with plants and soft morning light", "size": "1024x1024", "quality": "medium"}}),
});
console.log(response.status);
console.log(await response.text());
```


#### Responses

##### `202`

Start an image, video or voice generation.

```json
{
  "data": {
    "id": "9b2f6c1e-4a7d-4f0e-9c1b-2d3e4f5a6b7c",
    "status": "processing",
    "model": "openai/gpt-image-2/text-to-image",
    "credits_reserved": 2
  }
}
```

| Field | Type | Description |
|---|---|---|
| `data.id` | string | The id of the generation, to follow it with GET /v1/media/generations/{id}. |
| `data.status` | string: processing, completed, failed | `processing` while it is being made, then `completed` or `failed`. |
| `data.credits_reserved` | number | Credits held for this generation. At the end we charge the real cost and give back the rest. |

| Header | Description |
|---|---|
| `X-Correlation-ID` | Identifier of this request. Give it to support when you report a problem. |
| `X-RateLimit-Limit` | Requests allowed per minute. |
| `X-RateLimit-Remaining` | Requests left in the current minute. |
| `X-RateLimit-Reset` | When the minute ends, as a Unix timestamp in seconds. |
| `X-API-Mode` | The mode of the key that made the request: `sandbox` or `production`. |

##### `401`

The key is missing, invalid, revoked or expired, or the user who created it no longer has access to the account.

```json
{
  "error": {
    "code": "unauthorized",
    "message": "Missing or invalid API key.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `402`

Not enough AI credits for this request (`insufficient_credits`). Nothing was charged. `details.required` is what the request needs and `details.balance` is what the account has.

```json
{
  "error": {
    "code": "insufficient_credits",
    "message": "Not enough credits for this request. Nothing was charged.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "required": 46.12,
      "balance": 12.5
    }
  }
}
```

##### `403`

The account cannot use the API (`forbidden`), the key lacks the permission (`insufficient_scope`), or the IP address is not on the list of the key (`ip_not_allowed`).

```json
{
  "error": {
    "code": "insufficient_scope",
    "message": "This key does not have the required permission.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "required": "dns:read"
    }
  }
}
```

##### `404`

The model does not exist in the catalog, or it is not of the right type for this operation (`model_not_found`). See GET /v1/models.

```json
{
  "error": {
    "code": "model_not_found",
    "message": "This model does not exist.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "model": "example/unknown-model"
    }
  }
}
```

##### `422`

Some of the data is not valid.

```json
{
  "error": {
    "code": "validation_failed",
    "message": "Some of the data is not valid.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `429`

Too many requests. Wait for the time in Retry-After.

```json
{
  "error": {
    "code": "rate_limited",
    "message": "Too many requests. Please try again shortly.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "retry_after": 42
    }
  }
}
```

| Header | Description |
|---|---|
| `Retry-After` | Seconds to wait before trying again. |

##### `500`

An internal error occurred. Give the correlation_id to support.

```json
{
  "error": {
    "code": "internal_error",
    "message": "An internal error occurred. Please give the correlation_id to support.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `502`

The service behind the API did not respond as expected.

```json
{
  "error": {
    "code": "upstream_error",
    "message": "The service did not respond as expected. Please try again later.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `503`

The API is turned off.

```json
{
  "error": {
    "code": "disabled",
    "message": "The API is currently turned off.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```


#### Errors

| Status | Code | Meaning |
|---|---|---|
| 401 | `unauthorized` | The key is missing, invalid, revoked or expired, or the user who created it no longer has access to the account. |
| 402 | `insufficient_credits` | Not enough AI credits for this request (`insufficient_credits`). Nothing was charged. `details.required` is what the request needs and `details.balance` is what the account has. |
| 403 | `forbidden`, `insufficient_scope`, `ip_not_allowed` | The account cannot use the API (`forbidden`), the key lacks the permission (`insufficient_scope`), or the IP address is not on the list of the key (`ip_not_allowed`). |
| 404 | `model_not_found` | The model does not exist in the catalog, or it is not of the right type for this operation (`model_not_found`). See GET /v1/models. |
| 422 | `validation_failed` | Some of the data is not valid. |
| 429 | `rate_limited` | Too many requests. Wait for the time in Retry-After. |
| 500 | `internal_error` | An internal error occurred. Give the correlation_id to support. |
| 502 | `upstream_error` | The service behind the API did not respond as expected. |
| 503 | `disabled` | The API is turned off. |

The error format is explained in [Errors](https://docs.mozout.co.mz/en/api-rules.md).


### Check a generation

`GET https://api.mozout.co.mz/v1/media/generations/{id}`

Needs `ai:read`. The state of a generation. Each call also moves it forward, so call it every 5 to 10 seconds until `status` is `completed` (the links are in `outputs`) or `failed` (the reason is in `error` and the reservation comes back). Only the account that asked for it can see it.

#### Authentication

Needs a valid key in the `Authorization: Bearer` header. Required permission: `ai:read`.

#### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | path | string | yes | The `id` returned by POST /v1/media/generations. |
| `X-API-Mode` | header | string: sandbox, production | no | Optional. If it does not match the mode of the key, the request is refused with `invalid_request` and reason `mode_mismatch`. Use it to make sure a program never runs with the wrong key. |

#### Examples

**curl**

```bash
curl "https://api.mozout.co.mz/v1/media/generations/9b2f6c1e-4a7d-4f0e-9c1b-2d3e4f5a6b7c" \
  -H "Authorization: Bearer $MOZOUT_API_KEY" \
  -H "Accept-Language: en"
```

**PHP**

```php
<?php
$ch = curl_init('https://api.mozout.co.mz/v1/media/generations/9b2f6c1e-4a7d-4f0e-9c1b-2d3e4f5a6b7c');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('MOZOUT_API_KEY'),
        'Accept-Language: en',
    ],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo $status, PHP_EOL, $body, PHP_EOL;
```

**Python**

```python
import os
import requests

headers = {
    "Authorization": "Bearer " + os.environ["MOZOUT_API_KEY"],
    "Accept-Language": "en",
}
r = requests.get("https://api.mozout.co.mz/v1/media/generations/9b2f6c1e-4a7d-4f0e-9c1b-2d3e4f5a6b7c", headers=headers, timeout=30)
print(r.status_code)
print(r.text)
```

**JavaScript**

```javascript
const response = await fetch("https://api.mozout.co.mz/v1/media/generations/9b2f6c1e-4a7d-4f0e-9c1b-2d3e4f5a6b7c", {
  headers: {
    Authorization: `Bearer ${process.env.MOZOUT_API_KEY}`,
    "Accept-Language": "en",
  },
});
console.log(response.status);
console.log(await response.text());
```


#### Responses

##### `200`

Check a generation.

```json
{
  "data": {
    "id": "9b2f6c1e-4a7d-4f0e-9c1b-2d3e4f5a6b7c",
    "status": "completed",
    "model": "openai/gpt-image-2/text-to-image",
    "outputs": [
      "https://ai.example.com/media/9b2f6c1e/1.jpeg"
    ],
    "credits_charged": 2,
    "error": null
  }
}
```

| Field | Type | Description |
|---|---|---|
| `data.id` | string | The id of the generation, to follow it with GET /v1/media/generations/{id}. |
| `data.status` | string: processing, completed, failed | `processing` while it is being made, then `completed` or `failed`. |
| `data.outputs` | array<string> | With `completed`: the links to the files made (image, video or audio). Download them and keep a copy: the links are not permanent. |
| `data.credits_charged` | number | Credits charged so far: `0` while `processing`, the real cost with `completed`, and `0` with `failed` (the reservation comes back). |
| `data.error` | string, null | With `failed`: the reason, in plain language. |

| Header | Description |
|---|---|
| `X-Correlation-ID` | Identifier of this request. Give it to support when you report a problem. |
| `X-RateLimit-Limit` | Requests allowed per minute. |
| `X-RateLimit-Remaining` | Requests left in the current minute. |
| `X-RateLimit-Reset` | When the minute ends, as a Unix timestamp in seconds. |
| `X-API-Mode` | The mode of the key that made the request: `sandbox` or `production`. |

##### `401`

The key is missing, invalid, revoked or expired, or the user who created it no longer has access to the account.

```json
{
  "error": {
    "code": "unauthorized",
    "message": "Missing or invalid API key.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `403`

The account cannot use the API (`forbidden`), the key lacks the permission (`insufficient_scope`), or the IP address is not on the list of the key (`ip_not_allowed`).

```json
{
  "error": {
    "code": "insufficient_scope",
    "message": "This key does not have the required permission.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "required": "dns:read"
    }
  }
}
```

##### `404`

Not found.

```json
{
  "error": {
    "code": "not_found",
    "message": "Not found.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `429`

Too many requests. Wait for the time in Retry-After.

```json
{
  "error": {
    "code": "rate_limited",
    "message": "Too many requests. Please try again shortly.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "retry_after": 42
    }
  }
}
```

| Header | Description |
|---|---|
| `Retry-After` | Seconds to wait before trying again. |

##### `500`

An internal error occurred. Give the correlation_id to support.

```json
{
  "error": {
    "code": "internal_error",
    "message": "An internal error occurred. Please give the correlation_id to support.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `502`

The service behind the API did not respond as expected.

```json
{
  "error": {
    "code": "upstream_error",
    "message": "The service did not respond as expected. Please try again later.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `503`

The API is turned off.

```json
{
  "error": {
    "code": "disabled",
    "message": "The API is currently turned off.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```


#### Errors

| Status | Code | Meaning |
|---|---|---|
| 401 | `unauthorized` | The key is missing, invalid, revoked or expired, or the user who created it no longer has access to the account. |
| 403 | `forbidden`, `insufficient_scope`, `ip_not_allowed` | The account cannot use the API (`forbidden`), the key lacks the permission (`insufficient_scope`), or the IP address is not on the list of the key (`ip_not_allowed`). |
| 404 | `not_found` | Not found. |
| 429 | `rate_limited` | Too many requests. Wait for the time in Retry-After. |
| 500 | `internal_error` | An internal error occurred. Give the correlation_id to support. |
| 502 | `upstream_error` | The service behind the API did not respond as expected. |
| 503 | `disabled` | The API is turned off. |

The error format is explained in [Errors](https://docs.mozout.co.mz/en/api-rules.md).


### See the AI credit balance

`GET https://api.mozout.co.mz/v1/ai/balance`

Needs `ai:read`. The credits the account has for AI. Chat and generations take credits from this balance; a reservation that is not used comes back to it. It is the same balance with a `sandbox_` key and a `prod_` key. With a Coding Plan, `subscription` also shows the points left this week and this month and when they come back.

#### Authentication

Needs a valid key in the `Authorization: Bearer` header. Required permission: `ai:read`.

#### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `X-API-Mode` | header | string: sandbox, production | no | Optional. If it does not match the mode of the key, the request is refused with `invalid_request` and reason `mode_mismatch`. Use it to make sure a program never runs with the wrong key. |

#### Examples

**curl**

```bash
curl "https://api.mozout.co.mz/v1/ai/balance" \
  -H "Authorization: Bearer $MOZOUT_API_KEY" \
  -H "Accept-Language: en"
```

**PHP**

```php
<?php
$ch = curl_init('https://api.mozout.co.mz/v1/ai/balance');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('MOZOUT_API_KEY'),
        'Accept-Language: en',
    ],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo $status, PHP_EOL, $body, PHP_EOL;
```

**Python**

```python
import os
import requests

headers = {
    "Authorization": "Bearer " + os.environ["MOZOUT_API_KEY"],
    "Accept-Language": "en",
}
r = requests.get("https://api.mozout.co.mz/v1/ai/balance", headers=headers, timeout=30)
print(r.status_code)
print(r.text)
```

**JavaScript**

```javascript
const response = await fetch("https://api.mozout.co.mz/v1/ai/balance", {
  headers: {
    Authorization: `Bearer ${process.env.MOZOUT_API_KEY}`,
    "Accept-Language": "en",
  },
});
console.log(response.status);
console.log(await response.text());
```


#### Responses

##### `200`

See the AI credit balance.

```json
{
  "data": {
    "credits": 1250.5,
    "currency": "MZN",
    "subscription": {
      "plan": "plus",
      "plan_name": "Plus",
      "status": "active",
      "weekly_remaining": 61250000,
      "monthly_remaining": 143750000,
      "weekly_resets_at": "2026-11-23T00:00:00+00:00",
      "monthly_resets_at": "2026-12-10T00:00:00+00:00",
      "fallback_to_credits": true
    }
  }
}
```

| Field | Type | Description |
|---|---|---|
| `data.credits` | number | The AI credits of the account, with two decimal places. |
| `data.currency` | string | Always `credits`. |
| `data.subscription` | object | Only with a Coding Plan: the plan and the points left. Without a plan this field does not come. |
| `data.subscription.plan` | string | The plan code: `starter`, `lite`, `plus`, `max`, `ultra` or `enterprise`. |
| `data.subscription.plan_name` | string | The plan name. |
| `data.subscription.status` | string: active, suspended, terminated, cancelled | Only an `active` plan spends points. |
| `data.subscription.weekly_remaining` | number | Points left this week. |
| `data.subscription.monthly_remaining` | number | Points left in this monthly cycle. |
| `data.subscription.weekly_resets_at` | string | When the weekly points come back: every Monday at 00:00 UTC (ISO 8601). |
| `data.subscription.monthly_resets_at` | string | When the monthly cycle starts again, counted from the start of the subscription period (ISO 8601). |
| `data.subscription.fallback_to_credits` | boolean | `true` (the default): when the points run out, requests go on and are paid with credits. Turn it off in the Plan tab of All in One AI. |

| Header | Description |
|---|---|
| `X-Correlation-ID` | Identifier of this request. Give it to support when you report a problem. |
| `X-RateLimit-Limit` | Requests allowed per minute. |
| `X-RateLimit-Remaining` | Requests left in the current minute. |
| `X-RateLimit-Reset` | When the minute ends, as a Unix timestamp in seconds. |
| `X-API-Mode` | The mode of the key that made the request: `sandbox` or `production`. |

##### `401`

The key is missing, invalid, revoked or expired, or the user who created it no longer has access to the account.

```json
{
  "error": {
    "code": "unauthorized",
    "message": "Missing or invalid API key.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `403`

The account cannot use the API (`forbidden`), the key lacks the permission (`insufficient_scope`), or the IP address is not on the list of the key (`ip_not_allowed`).

```json
{
  "error": {
    "code": "insufficient_scope",
    "message": "This key does not have the required permission.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "required": "dns:read"
    }
  }
}
```

##### `429`

Too many requests. Wait for the time in Retry-After.

```json
{
  "error": {
    "code": "rate_limited",
    "message": "Too many requests. Please try again shortly.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "retry_after": 42
    }
  }
}
```

| Header | Description |
|---|---|
| `Retry-After` | Seconds to wait before trying again. |

##### `500`

An internal error occurred. Give the correlation_id to support.

```json
{
  "error": {
    "code": "internal_error",
    "message": "An internal error occurred. Please give the correlation_id to support.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `502`

The service behind the API did not respond as expected.

```json
{
  "error": {
    "code": "upstream_error",
    "message": "The service did not respond as expected. Please try again later.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `503`

The API is turned off.

```json
{
  "error": {
    "code": "disabled",
    "message": "The API is currently turned off.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```


#### Errors

| Status | Code | Meaning |
|---|---|---|
| 401 | `unauthorized` | The key is missing, invalid, revoked or expired, or the user who created it no longer has access to the account. |
| 403 | `forbidden`, `insufficient_scope`, `ip_not_allowed` | The account cannot use the API (`forbidden`), the key lacks the permission (`insufficient_scope`), or the IP address is not on the list of the key (`ip_not_allowed`). |
| 429 | `rate_limited` | Too many requests. Wait for the time in Retry-After. |
| 500 | `internal_error` | An internal error occurred. Give the correlation_id to support. |
| 502 | `upstream_error` | The service behind the API did not respond as expected. |
| 503 | `disabled` | The API is turned off. |

The error format is explained in [Errors](https://docs.mozout.co.mz/en/api-rules.md).


### Send a message in the Anthropic format

`POST https://api.mozout.co.mz/v1/messages`

Needs `ai:write`. Compatible with the Anthropic Messages API, for Claude Code and the Anthropic SDKs: set the base URL to this API without `/v1` (the tool adds `/v1/messages`). It works like POST /v1/chat/completions: the same models and agents, the same reservation and charge (or Coding Plan points), the same account rules and the same sandbox, where the answer is always `Resposta de teste (sandbox).` with `usage` at zero. Tool calls come as `tool_use` blocks and you answer with `tool_result` blocks. With `stream: true` the answer comes as Anthropic events. Errors in this operation use the Anthropic format. The body may have up to 8 MB. The key may come in `Authorization: Bearer` or in `x-api-key`.

#### Authentication

Needs a valid key in the `Authorization: Bearer` header. Required permission: `ai:write`.

#### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `anthropic-version` | header | string | no | Sent by the Anthropic SDKs and Claude Code. It goes through as it is; you do not need to send it. |
| `anthropic-beta` | header | string | no | Sent by Claude Code. It goes through as it is. |
| `Idempotency-Key` | header | string | no | Any unique value, up to 255 visible characters. Valid for 24 hours per key. Repeating the same request returns the saved answer; a different body, or a first request still in progress, returns 409. |
| `x-api-key` | header | string | no | The key can come in this header instead of `Authorization: Bearer` (Claude Code sends it here when you use `ANTHROPIC_API_KEY`). It works in every operation of the API. |
| `X-API-Mode` | header | string: sandbox, production | no | Optional. If it does not match the mode of the key, the request is refused with `invalid_request` and reason `mode_mismatch`. Use it to make sure a program never runs with the wrong key. |

#### Request body

| Field | Type | Required | Description |
|---|---|---|---|
| `model` | string | yes | A `text` model id from GET /v1/models, or `agent/<id>`. A name that is not in the catalog (such as `claude-sonnet-...`) uses our default coding model. The answer brings back the name you sent. |
| `messages` | array<object> | yes | The conversation, oldest first. |
| `system` | any | no | The instructions, as text or as a list of `text` blocks. |
| `tools` | array<object> | no | Tools the model may call, in the Anthropic format. |
| `tool_choice` | object | no | `{"type": "auto"}`, `{"type": "any"}`, `{"type": "tool", "name": "..."}` or `{"type": "none"}`. |
| `max_tokens` | integer | yes | The most tokens the answer may have. Required. We reserve credits for this number of output tokens, so a lower value needs a smaller balance. |
| `temperature` | number | no | From 0 to 1: lower is more predictable. |
| `stop_sequences` | array<string> | no | Texts that end the answer when the model writes them. |
| `stream` | boolean | no | `true` to receive the answer as Anthropic server-sent events (`message_start`, `content_block_start`, `content_block_delta`, `content_block_stop`, `message_delta`, `message_stop` and `ping`). |

#### Examples

**curl**

```bash
curl -X POST "https://api.mozout.co.mz/v1/messages" \
  -H "Authorization: Bearer $MOZOUT_API_KEY" \
  -H "Accept-Language: en" \
  -H "Idempotency-Key: 9f1c2d3e-example" \
  -H "Content-Type: application/json" \
  -d '{"model": "moonshotai/kimi-k2.7-code", "max_tokens": 1024, "system": "You are a careful senior developer.", "messages": [{"role": "user", "content": "Write a Python function that checks if a string is a palindrome."}]}'
```

**PHP**

```php
<?php
$ch = curl_init('https://api.mozout.co.mz/v1/messages');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => '{"model": "moonshotai/kimi-k2.7-code", "max_tokens": 1024, "system": "You are a careful senior developer.", "messages": [{"role": "user", "content": "Write a Python function that checks if a string is a palindrome."}]}',
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('MOZOUT_API_KEY'),
        'Accept-Language: en',
        'Idempotency-Key: 9f1c2d3e-example',
        'Content-Type: application/json',
    ],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo $status, PHP_EOL, $body, PHP_EOL;
```

**Python**

```python
import os
import requests

headers = {
    "Authorization": "Bearer " + os.environ["MOZOUT_API_KEY"],
    "Accept-Language": "en",
    "Idempotency-Key": "9f1c2d3e-example",
}
payload = {"model": "moonshotai/kimi-k2.7-code", "max_tokens": 1024, "system": "You are a careful senior developer.", "messages": [{"role": "user", "content": "Write a Python function that checks if a string is a palindrome."}]}
r = requests.post("https://api.mozout.co.mz/v1/messages", headers=headers, json=payload, timeout=30)
print(r.status_code)
print(r.text)
```

**JavaScript**

```javascript
const response = await fetch("https://api.mozout.co.mz/v1/messages", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.MOZOUT_API_KEY}`,
    "Accept-Language": "en",
    "Idempotency-Key": "9f1c2d3e-example",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({"model": "moonshotai/kimi-k2.7-code", "max_tokens": 1024, "system": "You are a careful senior developer.", "messages": [{"role": "user", "content": "Write a Python function that checks if a string is a palindrome."}]}),
});
console.log(response.status);
console.log(await response.text());
```


#### Responses

##### `200`

Send a message in the Anthropic format.

```json
{
  "id": "msg_4f8a1c2e9b7d3a6f5e0c1b2a",
  "type": "message",
  "role": "assistant",
  "model": "moonshotai/kimi-k2.7-code",
  "content": [
    {
      "type": "text",
      "text": "def is_palindrome(s: str) -> bool:\n    t = \"\".join(c.lower() for c in s if c.isalnum())\n    return t == t[::-1]"
    }
  ],
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 38,
    "output_tokens": 41,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 0
  }
}
```

| Field | Type | Description |
|---|---|---|
| `id` | string | The message id, starting with `msg_`. |
| `type` | string | Always `message`. |
| `role` | string | Always `assistant`. |
| `model` | string | The `model` you sent. |
| `content` | array<object> | The answer, as a list of `text` and `tool_use` blocks. |
| `stop_reason` | string, null | `end_turn`, `max_tokens` (it hit `max_tokens`), `stop_sequence` or `tool_use` (the model wants to call a tool). |
| `usage` | object | The tokens counted. We charge by these numbers and give back the rest of the reservation. |
| `usage.cache_creation_input_tokens` | integer | Input tokens written to the cache. |
| `usage.cache_read_input_tokens` | integer | Input tokens read from the cache, charged at `cached_input`. |

| Header | Description |
|---|---|
| `X-Correlation-ID` | Identifier of this request. Give it to support when you report a problem. |
| `X-RateLimit-Limit` | Requests allowed per minute. |
| `X-RateLimit-Remaining` | Requests left in the current minute. |
| `X-RateLimit-Reset` | When the minute ends, as a Unix timestamp in seconds. |
| `X-API-Mode` | The mode of the key that made the request: `sandbox` or `production`. |

##### `400`

The request is not valid (`invalid_request`), for example the body is not JSON, or `model`, `max_tokens` or `messages` are missing.

```json
{
  "type": "error",
  "error": {
    "type": "invalid_request_error",
    "message": "The request is not valid."
  },
  "request_id": "0f8fad5b-d9cb-469f-a165-70867728950e"
}
```

##### `401`

The key is missing, wrong, revoked or expired (`unauthorized`).

```json
{
  "type": "error",
  "error": {
    "type": "authentication_error",
    "message": "Missing or invalid API key."
  },
  "request_id": "0f8fad5b-d9cb-469f-a165-70867728950e"
}
```

##### `402`

Not enough AI credits for the reservation (`insufficient_credits`). Nothing was charged.

```json
{
  "type": "error",
  "error": {
    "type": "billing_error",
    "message": "Not enough credits for this request. Nothing was charged."
  },
  "request_id": "0f8fad5b-d9cb-469f-a165-70867728950e"
}
```

##### `403`

The key does not have `ai:write` (`insufficient_scope`), or the All in One AI account is not active.

```json
{
  "type": "error",
  "error": {
    "type": "permission_error",
    "message": "This key does not have the required permission."
  },
  "request_id": "0f8fad5b-d9cb-469f-a165-70867728950e"
}
```

##### `404`

The agent in `model` does not exist or belongs to another account (`model_not_found`). A model name that is not in the catalog, such as `claude-sonnet-...`, does not give this error: it uses our default coding model.

```json
{
  "type": "error",
  "error": {
    "type": "not_found_error",
    "message": "This model does not exist."
  },
  "request_id": "0f8fad5b-d9cb-469f-a165-70867728950e"
}
```

##### `429`

Too many requests per minute for this key (`rate_limited`), or the points of the Coding Plan ran out and the request cannot be paid with credits (`plan_limit_reached`). See `Retry-After`.

```json
{
  "type": "error",
  "error": {
    "type": "rate_limit_error",
    "message": "Too many requests. Please try again shortly."
  },
  "request_id": "0f8fad5b-d9cb-469f-a165-70867728950e"
}
```

##### `500`

Internal error (`internal_error`). Give the `request_id` to support.

```json
{
  "type": "error",
  "error": {
    "type": "api_error",
    "message": "An internal error occurred. Please give the correlation_id to support."
  },
  "request_id": "0f8fad5b-d9cb-469f-a165-70867728950e"
}
```

##### `502`

The AI service did not respond as expected (`upstream_error`). Try again shortly.

```json
{
  "type": "error",
  "error": {
    "type": "api_error",
    "message": "The service did not respond as expected. Please try again later."
  },
  "request_id": "0f8fad5b-d9cb-469f-a165-70867728950e"
}
```

##### `503`

The API is turned off (`disabled`).

```json
{
  "type": "error",
  "error": {
    "type": "overloaded_error",
    "message": "The API is currently turned off."
  },
  "request_id": "0f8fad5b-d9cb-469f-a165-70867728950e"
}
```


#### Errors

| Status | Code | Meaning |
|---|---|---|
| 400 | `invalid_request` | The request is not valid (`invalid_request`), for example the body is not JSON, or `model`, `max_tokens` or `messages` are missing. |
| 401 | `unauthorized` | The key is missing, wrong, revoked or expired (`unauthorized`). |
| 402 | `insufficient_credits` | Not enough AI credits for the reservation (`insufficient_credits`). Nothing was charged. |
| 403 | `insufficient_scope` | The key does not have `ai:write` (`insufficient_scope`), or the All in One AI account is not active. |
| 404 | `model_not_found` | The agent in `model` does not exist or belongs to another account (`model_not_found`). A model name that is not in the catalog, such as `claude-sonnet-...`, does not give this error: it uses our default coding model. |
| 429 | `rate_limited`, `plan_limit_reached` | Too many requests per minute for this key (`rate_limited`), or the points of the Coding Plan ran out and the request cannot be paid with credits (`plan_limit_reached`). See `Retry-After`. |
| 500 | `internal_error` | Internal error (`internal_error`). Give the `request_id` to support. |
| 502 | `upstream_error` | The AI service did not respond as expected (`upstream_error`). Try again shortly. |
| 503 | `disabled` | The API is turned off (`disabled`). |

The error format is explained in [Errors](https://docs.mozout.co.mz/en/api-rules.md).


### Count the tokens of a message

`POST https://api.mozout.co.mz/v1/messages/count_tokens`

Needs `ai:write`. An estimate of the input tokens of a POST /v1/messages request, which Claude Code uses to manage the context. It does not call the model, costs nothing and does not spend points. Errors use the Anthropic format. The key may come in `Authorization: Bearer` or in `x-api-key`.

#### Authentication

Needs a valid key in the `Authorization: Bearer` header. Required permission: `ai:write`.

#### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `anthropic-version` | header | string | no | Sent by the Anthropic SDKs and Claude Code. It goes through as it is; you do not need to send it. |
| `anthropic-beta` | header | string | no | Sent by Claude Code. It goes through as it is. |
| `x-api-key` | header | string | no | The key can come in this header instead of `Authorization: Bearer` (Claude Code sends it here when you use `ANTHROPIC_API_KEY`). It works in every operation of the API. |
| `X-API-Mode` | header | string: sandbox, production | no | Optional. If it does not match the mode of the key, the request is refused with `invalid_request` and reason `mode_mismatch`. Use it to make sure a program never runs with the wrong key. |
| `Idempotency-Key` | header | string | no | A unique identifier for this request, so it can be repeated without duplicating it. |

#### Request body

| Field | Type | Required | Description |
|---|---|---|---|
| `model` | string | yes | A `text` model id from GET /v1/models, or `agent/<id>`. A name that is not in the catalog (such as `claude-sonnet-...`) uses our default coding model. The answer brings back the name you sent. |
| `messages` | array<object> | yes | The conversation, oldest first. |
| `system` | any | no | The instructions, as text or as a list of `text` blocks. |
| `tools` | array<object> | no | Tools the model may call, in the Anthropic format. |
| `tool_choice` | object | no | `{"type": "auto"}`, `{"type": "any"}`, `{"type": "tool", "name": "..."}` or `{"type": "none"}`. |

#### Examples

**curl**

```bash
curl -X POST "https://api.mozout.co.mz/v1/messages/count_tokens" \
  -H "Authorization: Bearer $MOZOUT_API_KEY" \
  -H "Accept-Language: en" \
  -H "Idempotency-Key: 9f1c2d3e-example" \
  -H "Content-Type: application/json" \
  -d '{"model": "moonshotai/kimi-k2.7-code", "system": "You are a careful senior developer.", "messages": [{"role": "user", "content": "Write a Python function that checks if a string is a palindrome."}]}'
```

**PHP**

```php
<?php
$ch = curl_init('https://api.mozout.co.mz/v1/messages/count_tokens');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => '{"model": "moonshotai/kimi-k2.7-code", "system": "You are a careful senior developer.", "messages": [{"role": "user", "content": "Write a Python function that checks if a string is a palindrome."}]}',
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('MOZOUT_API_KEY'),
        'Accept-Language: en',
        'Idempotency-Key: 9f1c2d3e-example',
        'Content-Type: application/json',
    ],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo $status, PHP_EOL, $body, PHP_EOL;
```

**Python**

```python
import os
import requests

headers = {
    "Authorization": "Bearer " + os.environ["MOZOUT_API_KEY"],
    "Accept-Language": "en",
    "Idempotency-Key": "9f1c2d3e-example",
}
payload = {"model": "moonshotai/kimi-k2.7-code", "system": "You are a careful senior developer.", "messages": [{"role": "user", "content": "Write a Python function that checks if a string is a palindrome."}]}
r = requests.post("https://api.mozout.co.mz/v1/messages/count_tokens", headers=headers, json=payload, timeout=30)
print(r.status_code)
print(r.text)
```

**JavaScript**

```javascript
const response = await fetch("https://api.mozout.co.mz/v1/messages/count_tokens", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.MOZOUT_API_KEY}`,
    "Accept-Language": "en",
    "Idempotency-Key": "9f1c2d3e-example",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({"model": "moonshotai/kimi-k2.7-code", "system": "You are a careful senior developer.", "messages": [{"role": "user", "content": "Write a Python function that checks if a string is a palindrome."}]}),
});
console.log(response.status);
console.log(await response.text());
```


#### Responses

##### `200`

Count the tokens of a message.

```json
{
  "input_tokens": 38
}
```

| Field | Type | Description |
|---|---|---|
| `input_tokens` | integer | An estimate of the input tokens of the request. |

| Header | Description |
|---|---|
| `X-Correlation-ID` | Identifier of this request. Give it to support when you report a problem. |
| `X-RateLimit-Limit` | Requests allowed per minute. |
| `X-RateLimit-Remaining` | Requests left in the current minute. |
| `X-RateLimit-Reset` | When the minute ends, as a Unix timestamp in seconds. |
| `X-API-Mode` | The mode of the key that made the request: `sandbox` or `production`. |

##### `400`

The request is not valid (`invalid_request`), for example the body is not JSON, or `model`, `max_tokens` or `messages` are missing.

```json
{
  "type": "error",
  "error": {
    "type": "invalid_request_error",
    "message": "The request is not valid."
  },
  "request_id": "0f8fad5b-d9cb-469f-a165-70867728950e"
}
```

##### `401`

The key is missing, wrong, revoked or expired (`unauthorized`).

```json
{
  "type": "error",
  "error": {
    "type": "authentication_error",
    "message": "Missing or invalid API key."
  },
  "request_id": "0f8fad5b-d9cb-469f-a165-70867728950e"
}
```

##### `403`

The key does not have `ai:write` (`insufficient_scope`), or the All in One AI account is not active.

```json
{
  "type": "error",
  "error": {
    "type": "permission_error",
    "message": "This key does not have the required permission."
  },
  "request_id": "0f8fad5b-d9cb-469f-a165-70867728950e"
}
```

##### `404`

The agent in `model` does not exist or belongs to another account (`model_not_found`). A model name that is not in the catalog, such as `claude-sonnet-...`, does not give this error: it uses our default coding model.

```json
{
  "type": "error",
  "error": {
    "type": "not_found_error",
    "message": "This model does not exist."
  },
  "request_id": "0f8fad5b-d9cb-469f-a165-70867728950e"
}
```

##### `429`

Too many requests per minute for this key (`rate_limited`). See `Retry-After`.

```json
{
  "type": "error",
  "error": {
    "type": "rate_limit_error",
    "message": "Too many requests. Please try again shortly."
  },
  "request_id": "0f8fad5b-d9cb-469f-a165-70867728950e"
}
```

##### `500`

Internal error (`internal_error`). Give the `request_id` to support.

```json
{
  "type": "error",
  "error": {
    "type": "api_error",
    "message": "An internal error occurred. Please give the correlation_id to support."
  },
  "request_id": "0f8fad5b-d9cb-469f-a165-70867728950e"
}
```

##### `502`

The AI service did not respond as expected (`upstream_error`). Try again shortly.

```json
{
  "type": "error",
  "error": {
    "type": "api_error",
    "message": "The service did not respond as expected. Please try again later."
  },
  "request_id": "0f8fad5b-d9cb-469f-a165-70867728950e"
}
```

##### `503`

The API is turned off (`disabled`).

```json
{
  "type": "error",
  "error": {
    "type": "overloaded_error",
    "message": "The API is currently turned off."
  },
  "request_id": "0f8fad5b-d9cb-469f-a165-70867728950e"
}
```


#### Errors

| Status | Code | Meaning |
|---|---|---|
| 400 | `invalid_request` | The request is not valid (`invalid_request`), for example the body is not JSON, or `model`, `max_tokens` or `messages` are missing. |
| 401 | `unauthorized` | The key is missing, wrong, revoked or expired (`unauthorized`). |
| 403 | `insufficient_scope` | The key does not have `ai:write` (`insufficient_scope`), or the All in One AI account is not active. |
| 404 | `model_not_found` | The agent in `model` does not exist or belongs to another account (`model_not_found`). A model name that is not in the catalog, such as `claude-sonnet-...`, does not give this error: it uses our default coding model. |
| 429 | `rate_limited` | Too many requests per minute for this key (`rate_limited`). See `Retry-After`. |
| 500 | `internal_error` | Internal error (`internal_error`). Give the `request_id` to support. |
| 502 | `upstream_error` | The AI service did not respond as expected (`upstream_error`). Try again shortly. |
| 503 | `disabled` | The API is turned off (`disabled`). |

The error format is explained in [Errors](https://docs.mozout.co.mz/en/api-rules.md).


### Create a response in the OpenAI Responses format

`POST https://api.mozout.co.mz/v1/responses`

Needs `ai:write`. Compatible with the OpenAI Responses API, for Codex CLI (`wire_api = "responses"`) and the OpenAI SDKs (`client.responses.create`), with the base URL ending in `/v1`. It works like POST /v1/chat/completions: the same models and agents, the same reservation and charge (or Coding Plan points), the same account rules and the same sandbox. Function calls come as `function_call` items and you answer with `function_call_output` items. The response is kept for 30 days, so you can go on with `previous_response_id`. Errors of the model and of the account come in the OpenAI format (`{"error": {"message", "type", "param", "code"}}`), with the same `code`. The body may have up to 8 MB. The key may come in `Authorization: Bearer` or in `x-api-key`.

#### Authentication

Needs a valid key in the `Authorization: Bearer` header. Required permission: `ai:write`.

#### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `x-api-key` | header | string | no | The key can come in this header instead of `Authorization: Bearer` (Claude Code sends it here when you use `ANTHROPIC_API_KEY`). It works in every operation of the API. |
| `Idempotency-Key` | header | string | no | Any unique value, up to 255 visible characters. Valid for 24 hours per key. Repeating the same request returns the saved answer; a different body, or a first request still in progress, returns 409. |
| `X-API-Mode` | header | string: sandbox, production | no | Optional. If it does not match the mode of the key, the request is refused with `invalid_request` and reason `mode_mismatch`. Use it to make sure a program never runs with the wrong key. |

#### Request body

| Field | Type | Required | Description |
|---|---|---|---|
| `model` | string | yes | A `text` model id from GET /v1/models, or `agent/<id>`. |
| `input` | any | yes | The text of the request, or a list of input items. |
| `instructions` | string | no | The instructions (the system message). |
| `previous_response_id` | string | no | The `id` of an earlier response of the same account, to go on with that conversation without sending it again. Responses are kept for 30 days. |
| `tools` | array<object> | no | Functions the model may call: `{"type": "function", "name", "description", "parameters"}`. |
| `tool_choice` | string | no | `auto`, `none`, `required` or a function. |
| `max_output_tokens` | integer | no | The most tokens the answer may have. Without it we reserve 4096. |
| `temperature` | number | no | From 0 to 2: lower is more predictable. |
| `stream` | boolean | no | `true` to receive the answer as Responses events (`response.created`, `response.output_item.added`, `response.output_text.delta`, `response.function_call_arguments.delta`, `response.output_item.done` and `response.completed`). |

#### Examples

**curl**

```bash
curl -X POST "https://api.mozout.co.mz/v1/responses" \
  -H "Authorization: Bearer $MOZOUT_API_KEY" \
  -H "Accept-Language: en" \
  -H "Idempotency-Key: 9f1c2d3e-example" \
  -H "Content-Type: application/json" \
  -d '{"model": "moonshotai/kimi-k2.7-code", "instructions": "You are a careful senior developer.", "input": "Write a Python function that checks if a string is a palindrome.", "max_output_tokens": 1024}'
```

**PHP**

```php
<?php
$ch = curl_init('https://api.mozout.co.mz/v1/responses');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => '{"model": "moonshotai/kimi-k2.7-code", "instructions": "You are a careful senior developer.", "input": "Write a Python function that checks if a string is a palindrome.", "max_output_tokens": 1024}',
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('MOZOUT_API_KEY'),
        'Accept-Language: en',
        'Idempotency-Key: 9f1c2d3e-example',
        'Content-Type: application/json',
    ],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo $status, PHP_EOL, $body, PHP_EOL;
```

**Python**

```python
import os
import requests

headers = {
    "Authorization": "Bearer " + os.environ["MOZOUT_API_KEY"],
    "Accept-Language": "en",
    "Idempotency-Key": "9f1c2d3e-example",
}
payload = {"model": "moonshotai/kimi-k2.7-code", "instructions": "You are a careful senior developer.", "input": "Write a Python function that checks if a string is a palindrome.", "max_output_tokens": 1024}
r = requests.post("https://api.mozout.co.mz/v1/responses", headers=headers, json=payload, timeout=30)
print(r.status_code)
print(r.text)
```

**JavaScript**

```javascript
const response = await fetch("https://api.mozout.co.mz/v1/responses", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.MOZOUT_API_KEY}`,
    "Accept-Language": "en",
    "Idempotency-Key": "9f1c2d3e-example",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({"model": "moonshotai/kimi-k2.7-code", "instructions": "You are a careful senior developer.", "input": "Write a Python function that checks if a string is a palindrome.", "max_output_tokens": 1024}),
});
console.log(response.status);
console.log(await response.text());
```


#### Responses

##### `200`

Create a response in the OpenAI Responses format.

```json
{
  "id": "resp_7d2c9e4b1a6f3c8e5b0d2a19",
  "object": "response",
  "created_at": 1795420800,
  "status": "completed",
  "model": "moonshotai/kimi-k2.7-code",
  "output": [
    {
      "id": "msg_3b8e1d6c4a9f2e7b0c5d1a83",
      "type": "message",
      "status": "completed",
      "role": "assistant",
      "content": [
        {
          "type": "output_text",
          "text": "def is_palindrome(s: str) -> bool:\n    t = \"\".join(c.lower() for c in s if c.isalnum())\n    return t == t[::-1]",
          "annotations": []
        }
      ]
    }
  ],
  "previous_response_id": null,
  "usage": {
    "input_tokens": 38,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 41,
    "output_tokens_details": {
      "reasoning_tokens": 0
    },
    "total_tokens": 79
  }
}
```

| Field | Type | Description |
|---|---|---|
| `id` | string | The response id, starting with `resp_`. Use it in `previous_response_id` or in GET /v1/responses/{id}. |
| `object` | string | Always `response`. |
| `created_at` | integer | Unix time. |
| `status` | string: completed, incomplete, failed | `completed`, or `incomplete` when it hit `max_output_tokens` (see `incomplete_details`). |
| `output` | array<object> | What the model produced. |
| `usage` | object | The tokens counted. We charge by these numbers. |
| `usage.input_tokens_details.cached_tokens` | integer | Input tokens read from the cache. |

| Header | Description |
|---|---|
| `X-Correlation-ID` | Identifier of this request. Give it to support when you report a problem. |
| `X-RateLimit-Limit` | Requests allowed per minute. |
| `X-RateLimit-Remaining` | Requests left in the current minute. |
| `X-RateLimit-Reset` | When the minute ends, as a Unix timestamp in seconds. |
| `X-API-Mode` | The mode of the key that made the request: `sandbox` or `production`. |

##### `401`

The key is missing, invalid, revoked or expired, or the user who created it no longer has access to the account.

```json
{
  "error": {
    "code": "unauthorized",
    "message": "Missing or invalid API key.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `402`

Not enough AI credits for this request (`insufficient_credits`). Nothing was charged. `details.required` is what the request needs and `details.balance` is what the account has.

```json
{
  "error": {
    "code": "insufficient_credits",
    "message": "Not enough credits for this request. Nothing was charged.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "required": 46.12,
      "balance": 12.5
    }
  }
}
```

##### `403`

The account cannot use the API (`forbidden`), the key lacks the permission (`insufficient_scope`), or the IP address is not on the list of the key (`ip_not_allowed`).

```json
{
  "error": {
    "code": "insufficient_scope",
    "message": "This key does not have the required permission.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "required": "dns:read"
    }
  }
}
```

##### `404`

The model does not exist in the catalog, or it is not of the right type for this operation (`model_not_found`). See GET /v1/models.

```json
{
  "error": {
    "code": "model_not_found",
    "message": "This model does not exist.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "model": "example/unknown-model"
    }
  }
}
```

##### `409`

The agent in `model` is paused (`agent_paused`). Nothing was charged. Turn it back on in All in One AI.

```json
{
  "error": {
    "code": "agent_paused",
    "message": "This agent is paused.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "model": "agent/7c1e9a42-b35d8f06-a2c4e719-5d0b3f8e"
    }
  }
}
```

##### `422`

Some of the data is not valid.

```json
{
  "error": {
    "code": "validation_failed",
    "message": "Some of the data is not valid.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `429`

Too many requests per minute for this key (`rate_limited`, wait the seconds in `Retry-After`), or the points of your Coding Plan ran out for the week or the month (`plan_limit_reached`). With `plan_limit_reached`, `details` has `limit` (`weekly` or `monthly`), `used`, `remaining`, `resets_at`, `fallback_to_credits` and `credits`. It only happens when "Use credits when the plan runs out" is off, or when the account has no credits left.

```json
{
  "error": {
    "code": "plan_limit_reached",
    "message": "Your plan's weekly limit has been reached.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "limit": "weekly",
      "used": 16500000,
      "remaining": 0,
      "resets_at": "2026-11-23T00:00:00+00:00",
      "fallback_to_credits": false,
      "credits": 0
    }
  }
}
```

| Header | Description |
|---|---|
| `Retry-After` | Seconds to wait before trying again. |

##### `500`

An internal error occurred. Give the correlation_id to support.

```json
{
  "error": {
    "code": "internal_error",
    "message": "An internal error occurred. Please give the correlation_id to support.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `502`

The service behind the API did not respond as expected.

```json
{
  "error": {
    "code": "upstream_error",
    "message": "The service did not respond as expected. Please try again later.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `503`

The API is turned off.

```json
{
  "error": {
    "code": "disabled",
    "message": "The API is currently turned off.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```


#### Errors

| Status | Code | Meaning |
|---|---|---|
| 401 | `unauthorized` | The key is missing, invalid, revoked or expired, or the user who created it no longer has access to the account. |
| 402 | `insufficient_credits` | Not enough AI credits for this request (`insufficient_credits`). Nothing was charged. `details.required` is what the request needs and `details.balance` is what the account has. |
| 403 | `forbidden`, `insufficient_scope`, `ip_not_allowed` | The account cannot use the API (`forbidden`), the key lacks the permission (`insufficient_scope`), or the IP address is not on the list of the key (`ip_not_allowed`). |
| 404 | `model_not_found` | The model does not exist in the catalog, or it is not of the right type for this operation (`model_not_found`). See GET /v1/models. |
| 409 | `agent_paused` | The agent in `model` is paused (`agent_paused`). Nothing was charged. Turn it back on in All in One AI. |
| 422 | `validation_failed` | Some of the data is not valid. |
| 429 | `rate_limited`, `plan_limit_reached`, `plan_limit_reached` | Too many requests per minute for this key (`rate_limited`, wait the seconds in `Retry-After`), or the points of your Coding Plan ran out for the week or the month (`plan_limit_reached`). With `plan_limit_reached`, `details` has `limit` (`weekly` or `monthly`), `used`, `remaining`, `resets_at`, `fallback_to_credits` and `credits`. It only happens when "Use credits when the plan runs out" is off, or when the account has no credits left. |
| 500 | `internal_error` | An internal error occurred. Give the correlation_id to support. |
| 502 | `upstream_error` | The service behind the API did not respond as expected. |
| 503 | `disabled` | The API is turned off. |

The error format is explained in [Errors](https://docs.mozout.co.mz/en/api-rules.md).


### Get a saved response

`GET https://api.mozout.co.mz/v1/responses/{id}`

Needs `ai:read`. A response made by POST /v1/responses in the last 30 days, the same as it was returned. Only the account that made it can see it; after 30 days the answer is `404`. The key may come in `Authorization: Bearer` or in `x-api-key`.

#### Authentication

Needs a valid key in the `Authorization: Bearer` header. Required permission: `ai:read`.

#### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `id` | path | string | yes | The `id` returned by POST /v1/responses. |
| `x-api-key` | header | string | no | The key can come in this header instead of `Authorization: Bearer` (Claude Code sends it here when you use `ANTHROPIC_API_KEY`). It works in every operation of the API. |
| `X-API-Mode` | header | string: sandbox, production | no | Optional. If it does not match the mode of the key, the request is refused with `invalid_request` and reason `mode_mismatch`. Use it to make sure a program never runs with the wrong key. |

#### Examples

**curl**

```bash
curl "https://api.mozout.co.mz/v1/responses/resp_7d2c9e4b1a6f3c8e5b0d2a19" \
  -H "Authorization: Bearer $MOZOUT_API_KEY" \
  -H "Accept-Language: en"
```

**PHP**

```php
<?php
$ch = curl_init('https://api.mozout.co.mz/v1/responses/resp_7d2c9e4b1a6f3c8e5b0d2a19');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('MOZOUT_API_KEY'),
        'Accept-Language: en',
    ],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo $status, PHP_EOL, $body, PHP_EOL;
```

**Python**

```python
import os
import requests

headers = {
    "Authorization": "Bearer " + os.environ["MOZOUT_API_KEY"],
    "Accept-Language": "en",
}
r = requests.get("https://api.mozout.co.mz/v1/responses/resp_7d2c9e4b1a6f3c8e5b0d2a19", headers=headers, timeout=30)
print(r.status_code)
print(r.text)
```

**JavaScript**

```javascript
const response = await fetch("https://api.mozout.co.mz/v1/responses/resp_7d2c9e4b1a6f3c8e5b0d2a19", {
  headers: {
    Authorization: `Bearer ${process.env.MOZOUT_API_KEY}`,
    "Accept-Language": "en",
  },
});
console.log(response.status);
console.log(await response.text());
```


#### Responses

##### `200`

Get a saved response.

```json
{
  "id": "resp_7d2c9e4b1a6f3c8e5b0d2a19",
  "object": "response",
  "created_at": 1795420800,
  "status": "completed",
  "model": "moonshotai/kimi-k2.7-code",
  "output": [
    {
      "id": "msg_3b8e1d6c4a9f2e7b0c5d1a83",
      "type": "message",
      "status": "completed",
      "role": "assistant",
      "content": [
        {
          "type": "output_text",
          "text": "def is_palindrome(s: str) -> bool:\n    t = \"\".join(c.lower() for c in s if c.isalnum())\n    return t == t[::-1]",
          "annotations": []
        }
      ]
    }
  ],
  "previous_response_id": null,
  "usage": {
    "input_tokens": 38,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 41,
    "output_tokens_details": {
      "reasoning_tokens": 0
    },
    "total_tokens": 79
  }
}
```

| Field | Type | Description |
|---|---|---|
| `id` | string | The response id, starting with `resp_`. Use it in `previous_response_id` or in GET /v1/responses/{id}. |
| `object` | string | Always `response`. |
| `created_at` | integer | Unix time. |
| `status` | string: completed, incomplete, failed | `completed`, or `incomplete` when it hit `max_output_tokens` (see `incomplete_details`). |
| `output` | array<object> | What the model produced. |
| `usage` | object | The tokens counted. We charge by these numbers. |
| `usage.input_tokens_details.cached_tokens` | integer | Input tokens read from the cache. |

| Header | Description |
|---|---|
| `X-Correlation-ID` | Identifier of this request. Give it to support when you report a problem. |
| `X-RateLimit-Limit` | Requests allowed per minute. |
| `X-RateLimit-Remaining` | Requests left in the current minute. |
| `X-RateLimit-Reset` | When the minute ends, as a Unix timestamp in seconds. |
| `X-API-Mode` | The mode of the key that made the request: `sandbox` or `production`. |

##### `401`

The key is missing, invalid, revoked or expired, or the user who created it no longer has access to the account.

```json
{
  "error": {
    "code": "unauthorized",
    "message": "Missing or invalid API key.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `403`

The account cannot use the API (`forbidden`), the key lacks the permission (`insufficient_scope`), or the IP address is not on the list of the key (`ip_not_allowed`).

```json
{
  "error": {
    "code": "insufficient_scope",
    "message": "This key does not have the required permission.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "required": "dns:read"
    }
  }
}
```

##### `404`

Not found.

```json
{
  "error": {
    "code": "not_found",
    "message": "Not found.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `429`

Too many requests. Wait for the time in Retry-After.

```json
{
  "error": {
    "code": "rate_limited",
    "message": "Too many requests. Please try again shortly.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "retry_after": 42
    }
  }
}
```

| Header | Description |
|---|---|
| `Retry-After` | Seconds to wait before trying again. |

##### `500`

An internal error occurred. Give the correlation_id to support.

```json
{
  "error": {
    "code": "internal_error",
    "message": "An internal error occurred. Please give the correlation_id to support.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `502`

The service behind the API did not respond as expected.

```json
{
  "error": {
    "code": "upstream_error",
    "message": "The service did not respond as expected. Please try again later.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `503`

The API is turned off.

```json
{
  "error": {
    "code": "disabled",
    "message": "The API is currently turned off.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```


#### Errors

| Status | Code | Meaning |
|---|---|---|
| 401 | `unauthorized` | The key is missing, invalid, revoked or expired, or the user who created it no longer has access to the account. |
| 403 | `forbidden`, `insufficient_scope`, `ip_not_allowed` | The account cannot use the API (`forbidden`), the key lacks the permission (`insufficient_scope`), or the IP address is not on the list of the key (`ip_not_allowed`). |
| 404 | `not_found` | Not found. |
| 429 | `rate_limited` | Too many requests. Wait for the time in Retry-After. |
| 500 | `internal_error` | An internal error occurred. Give the correlation_id to support. |
| 502 | `upstream_error` | The service behind the API did not respond as expected. |
| 503 | `disabled` | The API is turned off. |

The error format is explained in [Errors](https://docs.mozout.co.mz/en/api-rules.md).


### AI credit prices

`GET https://api.mozout.co.mz/v1/ai/credits/prices`

Needs `ai:read`. The price of each AI credit by quantity, in the currency of the account. Tax is added on the invoice (`tax_added`).

#### Authentication

Needs a valid key in the `Authorization: Bearer` header. Required permission: `ai:read`.

#### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `X-API-Mode` | header | string: sandbox, production | no | Optional. If it does not match the mode of the key, the request is refused with `invalid_request` and reason `mode_mismatch`. Use it to make sure a program never runs with the wrong key. |

#### Examples

**curl**

```bash
curl "https://api.mozout.co.mz/v1/ai/credits/prices" \
  -H "Authorization: Bearer $MOZOUT_API_KEY" \
  -H "Accept-Language: en"
```

**PHP**

```php
<?php
$ch = curl_init('https://api.mozout.co.mz/v1/ai/credits/prices');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('MOZOUT_API_KEY'),
        'Accept-Language: en',
    ],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo $status, PHP_EOL, $body, PHP_EOL;
```

**Python**

```python
import os
import requests

headers = {
    "Authorization": "Bearer " + os.environ["MOZOUT_API_KEY"],
    "Accept-Language": "en",
}
r = requests.get("https://api.mozout.co.mz/v1/ai/credits/prices", headers=headers, timeout=30)
print(r.status_code)
print(r.text)
```

**JavaScript**

```javascript
const response = await fetch("https://api.mozout.co.mz/v1/ai/credits/prices", {
  headers: {
    Authorization: `Bearer ${process.env.MOZOUT_API_KEY}`,
    "Accept-Language": "en",
  },
});
console.log(response.status);
console.log(await response.text());
```


#### Responses

##### `200`

AI credit prices.

```json
{
  "data": {
    "currency": "MZN",
    "minimum": 1000,
    "maximum": 10000000,
    "tax_added": true,
    "tiers": [
      {
        "from": 1000,
        "unit_price": 0.6
      },
      {
        "from": 10001,
        "unit_price": 0.54
      },
      {
        "from": 100001,
        "unit_price": 0.45
      }
    ]
  },
  "meta": {}
}
```

| Header | Description |
|---|---|
| `X-Correlation-ID` | Identifier of this request. Give it to support when you report a problem. |
| `X-RateLimit-Limit` | Requests allowed per minute. |
| `X-RateLimit-Remaining` | Requests left in the current minute. |
| `X-RateLimit-Reset` | When the minute ends, as a Unix timestamp in seconds. |
| `X-API-Mode` | The mode of the key that made the request: `sandbox` or `production`. |

##### `401`

The key is missing, invalid, revoked or expired, or the user who created it no longer has access to the account.

```json
{
  "error": {
    "code": "unauthorized",
    "message": "Missing or invalid API key.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `403`

The account cannot use the API (`forbidden`), the key lacks the permission (`insufficient_scope`), or the IP address is not on the list of the key (`ip_not_allowed`).

```json
{
  "error": {
    "code": "insufficient_scope",
    "message": "This key does not have the required permission.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "required": "dns:read"
    }
  }
}
```

##### `429`

Too many requests. Wait for the time in Retry-After.

```json
{
  "error": {
    "code": "rate_limited",
    "message": "Too many requests. Please try again shortly.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "retry_after": 42
    }
  }
}
```

| Header | Description |
|---|---|
| `Retry-After` | Seconds to wait before trying again. |

##### `500`

An internal error occurred. Give the correlation_id to support.

```json
{
  "error": {
    "code": "internal_error",
    "message": "An internal error occurred. Please give the correlation_id to support.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `503`

The API is turned off.

```json
{
  "error": {
    "code": "disabled",
    "message": "The API is currently turned off.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```


#### Errors

| Status | Code | Meaning |
|---|---|---|
| 401 | `unauthorized` | The key is missing, invalid, revoked or expired, or the user who created it no longer has access to the account. |
| 403 | `forbidden`, `insufficient_scope`, `ip_not_allowed` | The account cannot use the API (`forbidden`), the key lacks the permission (`insufficient_scope`), or the IP address is not on the list of the key (`ip_not_allowed`). |
| 429 | `rate_limited` | Too many requests. Wait for the time in Retry-After. |
| 500 | `internal_error` | An internal error occurred. Give the correlation_id to support. |
| 503 | `disabled` | The API is turned off. |

The error format is explained in [Errors](https://docs.mozout.co.mz/en/api-rules.md).


### Buy AI credits

`POST https://api.mozout.co.mz/v1/ai/credits/purchase`

Needs `billing:purchase`. Also needs `ai:write`. Buys `quantity` AI credits at the price of GET /v1/ai/credits/prices; they enter the balance with the payment. Credits do not take `promo_code`. Paid with credit only, within the spending limit of the key; the `Idempotency-Key` header is required and purchases are limited to 5 per minute. The price is the same as in your account: if the invoice does not match it, the purchase is undone and nothing is charged. `amount` is the invoice total with tax, `subtotal` is without tax and `tax` is the tax; in Sandbox nothing is created, `amount` comes without tax and `tax` is `null`. With the account profile incomplete it answers `409` with `profile_incomplete`.

#### Authentication

Needs a valid key in the `Authorization: Bearer` header. Required permission: `billing:purchase`.

#### Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `Idempotency-Key` | header | string | no | Any unique value, up to 255 visible characters. Valid for 24 hours per key. Repeating the same request returns the saved answer; a different body, or a first request still in progress, returns 409. |
| `X-API-Mode` | header | string: sandbox, production | no | Optional. If it does not match the mode of the key, the request is refused with `invalid_request` and reason `mode_mismatch`. Use it to make sure a program never runs with the wrong key. |

#### Request body

| Field | Type | Required | Description |
|---|---|---|---|
| `quantity` | integer | yes | Number of credits. |

#### Examples

**curl**

```bash
curl -X POST "https://api.mozout.co.mz/v1/ai/credits/purchase" \
  -H "Authorization: Bearer $MOZOUT_API_KEY" \
  -H "Accept-Language: en" \
  -H "Idempotency-Key: 9f1c2d3e-example" \
  -H "Content-Type: application/json" \
  -d '{"quantity": 1000}'
```

**PHP**

```php
<?php
$ch = curl_init('https://api.mozout.co.mz/v1/ai/credits/purchase');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => '{"quantity": 1000}',
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('MOZOUT_API_KEY'),
        'Accept-Language: en',
        'Idempotency-Key: 9f1c2d3e-example',
        'Content-Type: application/json',
    ],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo $status, PHP_EOL, $body, PHP_EOL;
```

**Python**

```python
import os
import requests

headers = {
    "Authorization": "Bearer " + os.environ["MOZOUT_API_KEY"],
    "Accept-Language": "en",
    "Idempotency-Key": "9f1c2d3e-example",
}
payload = {"quantity": 1000}
r = requests.post("https://api.mozout.co.mz/v1/ai/credits/purchase", headers=headers, json=payload, timeout=30)
print(r.status_code)
print(r.text)
```

**JavaScript**

```javascript
const response = await fetch("https://api.mozout.co.mz/v1/ai/credits/purchase", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.MOZOUT_API_KEY}`,
    "Accept-Language": "en",
    "Idempotency-Key": "9f1c2d3e-example",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({"quantity": 1000}),
});
console.log(response.status);
console.log(await response.text());
```


#### Responses

##### `202`

Buy AI credits.

```json
{
  "data": {
    "action_id": "6f1d2c3a-8b4e-4f7a-9c21-1d2e3f4a5b6c",
    "status": "paid",
    "simulated": false,
    "credits": 1000,
    "unit_price": 0.6,
    "order_id": null,
    "invoice_id": 3603,
    "amount": 696.0,
    "subtotal": 600.0,
    "tax": 96.0,
    "currency": "MZN",
    "promo_code": null,
    "discount": null
  },
  "meta": {}
}
```

| Header | Description |
|---|---|
| `X-Correlation-ID` | Identifier of this request. Give it to support when you report a problem. |
| `X-RateLimit-Limit` | Requests allowed per minute. |
| `X-RateLimit-Remaining` | Requests left in the current minute. |
| `X-RateLimit-Reset` | When the minute ends, as a Unix timestamp in seconds. |
| `X-API-Mode` | The mode of the key that made the request: `sandbox` or `production`. |

##### `400`

The request is not valid, for example the body is not JSON or the connection is not HTTPS.

```json
{
  "error": {
    "code": "invalid_request",
    "message": "The request is not valid.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `401`

The key is missing, invalid, revoked or expired, or the user who created it no longer has access to the account.

```json
{
  "error": {
    "code": "unauthorized",
    "message": "Missing or invalid API key.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `402`

Not enough credit. Nothing was charged.

```json
{
  "error": {
    "code": "insufficient_credit",
    "message": "The account does not have enough credit. Nothing was charged.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "amount": 1900.0,
      "currency": "MZN"
    }
  }
}
```

##### `403`

The account cannot use the API (`forbidden`), the key lacks the permission (`insufficient_scope`), or the IP address is not on the list of the key (`ip_not_allowed`).

```json
{
  "error": {
    "code": "insufficient_scope",
    "message": "This key does not have the required permission.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "required": "dns:read"
    }
  }
}
```

##### `409`

The operation cannot be done in the current state. See `details.reason`.

```json
{
  "error": {
    "code": "conflict",
    "message": "This operation only works on an active domain.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "reason": "domain_not_active"
    }
  }
}
```

##### `422`

Some of the data is not valid.

```json
{
  "error": {
    "code": "validation_failed",
    "message": "Some of the data is not valid.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `429`

Too many requests. Wait for the time in Retry-After.

```json
{
  "error": {
    "code": "rate_limited",
    "message": "Too many requests. Please try again shortly.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {
      "retry_after": 42
    }
  }
}
```

| Header | Description |
|---|---|
| `Retry-After` | Seconds to wait before trying again. |

##### `500`

An internal error occurred. Give the correlation_id to support.

```json
{
  "error": {
    "code": "internal_error",
    "message": "An internal error occurred. Please give the correlation_id to support.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `502`

The service behind the API did not respond as expected.

```json
{
  "error": {
    "code": "upstream_error",
    "message": "The service did not respond as expected. Please try again later.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```

##### `503`

The API is turned off.

```json
{
  "error": {
    "code": "disabled",
    "message": "The API is currently turned off.",
    "correlation_id": "0f8fad5b-d9cb-469f-a165-70867728950e",
    "details": {}
  }
}
```


#### Errors

| Status | Code | Meaning |
|---|---|---|
| 400 | `invalid_request` | The request is not valid, for example the body is not JSON or the connection is not HTTPS. |
| 401 | `unauthorized` | The key is missing, invalid, revoked or expired, or the user who created it no longer has access to the account. |
| 402 | `insufficient_credit` | Not enough credit. Nothing was charged. |
| 403 | `forbidden`, `insufficient_scope`, `ip_not_allowed` | The account cannot use the API (`forbidden`), the key lacks the permission (`insufficient_scope`), or the IP address is not on the list of the key (`ip_not_allowed`). |
| 409 | `conflict` | The operation cannot be done in the current state. See `details.reason`. |
| 422 | `validation_failed` | Some of the data is not valid. |
| 429 | `rate_limited` | Too many requests. Wait for the time in Retry-After. |
| 500 | `internal_error` | An internal error occurred. Give the correlation_id to support. |
| 502 | `upstream_error` | The service behind the API did not respond as expected. |
| 503 | `disabled` | The API is turned off. |

The error format is explained in [Errors](https://docs.mozout.co.mz/en/api-rules.md).
