> For the complete documentation index, see [llms.txt](https://docs.maiagent.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.maiagent.ai/api/en/api-reference/ai-gateway.md). Agents can also search and read this documentation through its [MCP server](https://docs.maiagent.ai/~gitbook/mcp).

# AI Gateway

AI Gateway provides OpenAI-compatible endpoints, allowing existing OpenAI SDKs or tools to call models through MaiAgent by changing only the URL and API key. These endpoints are available only under `/api/v1/`, and their paths do not end with `/`. Authentication uses `Authorization: Bearer <API Key>` (the key is your MaiAgent API Key, but Gateway endpoints accept only the `Bearer` prefix; using the `Api-Key` prefix returns `401`). MaiAgent must enable AI Gateway for your organization. Administrators configure which models each key can call in API Key management. For full details, see the technical manual: [AI Gateway: OpenAI-compatible API integration](https://docs.maiagent.ai/tech/api-integration/ai-gateway-openai-compatible).

### List available models <a href="#models-retrieve" id="models-retrieve"></a>

GET `/api/v1/models`

{% hint style="info" %}
Returns the identifiers and pricing of models accessible with this key. For identifier conventions, see [Model identifiers](https://docs.maiagent.ai/tech/api-integration/ai-gateway-openai-compatible#model-ids) in the technical guide.
{% endhint %}

#### Code examples

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API call example (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/models" \
  -H "Authorization: Bearer YOUR_API_KEY"

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// Set request headers
const config = {
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/models", config)
  .then(response => {
    console.log('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request error:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/models"
headers = {
    "Authorization": "Bearer YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request error:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/models", [
        'headers' => [
            'Authorization' => 'Bearer YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response body

**Status code: 200**

**Example response structure**

```typescript
{
  "object"?: string (enum: list) // Optional
  "data"?: [ // Optional
    {
      "id"?: string // Model ID to use in the model field when making a request (Optional)
      "object"?: string (enum: model) // Optional
      "created"?: integer // Unix seconds (Optional)
      "owned_by"?: string // Optional
      "name"?: string // Optional
      "icon"?: string // Optional
      "type"?: string (enum: language) // Optional
      "tags"?: [ // Optional
        string (enum: tool-use, multimodal, reasoning, prompt-caching, streaming)
      ]
      "pricing"?: { // Platform models use input/output/unit=credits_per_1k_tokens/currency; organization-owned models use traffic_fee_percent/unit=percent_of_total_tokens/currency (Optional)
      {
        "input"?: string // Optional
        "output"?: string // Optional
        "traffic_fee_percent"?: string // Optional
        "unit"?: string // Optional
        "currency"?: string // Optional
      }
      }
      "providers"?: [ // Optional
        {
          "slug"?: string // Optional
          "name"?: string // Optional
          "icon_url"?: string // Optional
          "color"?: string // Optional
        }
      ]
      "context_window"?: integer // Only present when configured for the model (Optional)
      "max_tokens"?: integer // Only present when configured for the model (Optional)
    }
  ]
}
```

**Example response values**

```json
{
  "object": "list",
  "data": [
    {
      "id": "Response string",
      "object": "model",
      "created": 456,
      "owned_by": "Response string",
      "name": "Response string",
      "icon": "Response string",
      "type": "language",
      "tags": [
        "tool-use"
      ],
      "pricing": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "Example response name",
        "description": "Example response description"
      },
      "providers": [
        {
          "slug": "Response string",
          "name": "Response string",
          "icon_url": "Response string",
          "color": "Response string"
        }
      ],
      "context_window": 456,
      "max_tokens": 456
    }
  ]
}
```

**Status code: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### Chat completions (with streaming and tool calling) <a href="#chat-completions-create" id="chat-completions-create"></a>

POST `/api/v1/chat/completions`

{% hint style="info" %}
The request and response formats match OpenAI `chat/completions` (`model`, `messages`, `stream`, `tools`, etc.); the platform schema does not list these fields. For parameters and examples, see [Chat completion parameters](https://docs.maiagent.ai/tech/api-integration/ai-gateway-openai-compatible#chat-completions-params) and [Minimal examples](https://docs.maiagent.ai/tech/api-integration/ai-gateway-openai-compatible#minimal-examples) in the technical guide.
{% endhint %}

#### Request body

**Request parameters**

| Field                          | Type                                                        | Required | Description                                                                                            |
| ------------------------------ | ----------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------ |
| model                          | string                                                      | Yes      | Model ID from GET /v1/models                                                                           |
| messages                       | array\[object]                                              | Yes      |                                                                                                        |
| stream                         | boolean                                                     | No       | Returns text/event-stream when true                                                                    |
| stream\_options                | object                                                      | No       |                                                                                                        |
| stream\_options.include\_usage | boolean                                                     | No       |                                                                                                        |
| temperature                    | number                                                      | No       |                                                                                                        |
| max\_tokens                    | integer                                                     | No       |                                                                                                        |
| top\_p                         | number                                                      | No       |                                                                                                        |
| stop                           | object                                                      | No       |                                                                                                        |
| n                              | integer                                                     | No       |                                                                                                        |
| provider                       | object                                                      | No       |                                                                                                        |
| provider.order                 | array\[string]                                              | No       | Specifies backend providers; currently only the first is used                                          |
| tools                          | array\[object]                                              | No       |                                                                                                        |
| tool\_choice                   | object                                                      | No       |                                                                                                        |
| parallel\_tool\_calls          | boolean                                                     | No       |                                                                                                        |
| response\_format               | object                                                      | No       | type is text, json\_object, or json\_schema; a json\_schema object is required when using json\_schema |
| reasoning\_effort              | string (enum: none, minimal, low, medium, high, xhigh, max) | No       |                                                                                                        |

**Example request structure**

```typescript
{
  "model": string // Model ID from GET /v1/models
  "messages": [
    {
      "role": string (enum: system, user, assistant, tool)
      "content": object // Text or an array of OpenAI multimodal content parts
      "tool_calls"?: [ // Optional
        {
          "id"?: string // Optional
          "type"?: string (enum: function) // Optional
          "function"?: { // Optional
          {
            "name"?: string // Optional
            "arguments"?: string // JSON string (Optional)
          }
          }
        }
      ]
      "tool_call_id"?: string // Optional
      "name"?: string // Optional
    }
  ]
  "stream"?: boolean // Returns text/event-stream when true (Optional)
  "stream_options"?: { // Optional
  {
    "include_usage"?: boolean // Optional
  }
  }
  "temperature"?: number // Optional
  "max_tokens"?: integer // Optional
  "top_p"?: number // Optional
  "stop"?: // May have different types (Optional)
  string // Optional
  "n"?: integer // Optional
  "provider"?: { // Optional
  {
    "order"?: [ // Specifies backend providers; currently only the first is used (Optional)
      string
    ]
  }
  }
  "tools"?: [ // Optional
    {
      "type": string (enum: function)
      "function": {
      {
        "name": string
        "description"?: string // Optional
        "parameters"?: object // JSON Schema (Optional)
        "strict"?: boolean // Optional
      }
      }
    }
  ]
  "tool_choice"?: // May have different types (Optional)
  string (enum: auto, none, required) // Optional
  "parallel_tool_calls"?: boolean // Optional
  "response_format"?: object // type is text, json_object, or json_schema; a json_schema object is required when using json_schema (Optional)
  "reasoning_effort"?: string (enum: none, minimal, low, medium, high, xhigh, max) // Optional
}
```

**Example request values**

```json
{
  "model": "openai/gpt-5.4-mini",
  "messages": [
    {
      "role": "user",
      "content": "Hello, please introduce yourself in one sentence."
    }
  ]
}
```

#### Code examples

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API call example (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/chat/completions" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-5.4-mini",
    "messages": [
      {
        "role": "user",
        "content": "Hello, please introduce yourself in one sentence."
      }
    ]
  }'

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// Set request headers
const config = {
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// Request body (payload)
const data = {
    "model": "openai/gpt-5.4-mini",
    "messages": [
      {
        "role": "user",
        "content": "Hello, please introduce yourself in one sentence."
      }
    ]
  };

axios.post("https://api.maiagent.ai/api/v1/chat/completions", data, config)
  .then(response => {
    console.log('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request error:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/chat/completions"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json"
}

# Request body (payload)
data = {
    "model": "openai/gpt-5.4-mini",
    "messages": [
        {
            "role": "user",
            "content": "Hello, please introduce yourself in one sentence."
        }
    ]
}

response = requests.post(url, json=data, headers=headers)
try:
    print("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request error:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/chat/completions", [
        'headers' => [
            'Authorization' => 'Bearer YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'model' => 'openai/gpt-5.4-mini',
            'messages' => [
                [
                    'role' => 'user',
                    'content' => 'Hello, please introduce yourself in one sentence.'
                ]
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response body

**Status code: 200 - Returns a chat.completion object when stream=false; returns SSE when stream=true**

**Example response structure**

```typescript
{
  "id"?: string // Optional
  "object"?: string (enum: chat.completion) // Optional
  "created"?: integer // Unix seconds (Optional)
  "model"?: string // Optional
  "choices"?: [ // Optional
    {
      "index"?: integer // Optional
      "message"?: { // Optional
      {
        "role"?: string (enum: assistant) // Optional
        "content"?: string // Optional
        "tool_calls"?: [ // Optional
          {
            "id"?: string // Optional
            "type"?: string (enum: function) // Optional
            "function"?: { // Optional
            {
              "name"?: string // Optional
              "arguments"?: string // JSON string (Optional)
            }
            }
          }
        ]
      }
      }
      "finish_reason"?: string // Optional
    }
  ]
  "usage"?: { // total_tokens equals the total number of tokens used for billing (input + output + prompt cache writes + reads) (optional)
  {
    "prompt_tokens"?: integer // Total input tokens, including prompt cache reads (cached_tokens) and writes (cache_write_tokens) (optional)
    "completion_tokens"?: integer // Optional
    "total_tokens"?: integer // prompt_tokens + completion_tokens (optional)
    "prompt_tokens_details"?: { // Optional
    {
      "cached_tokens"?: integer // Portion of prompt_tokens billed at the prompt cache read price; 0 for models whose cache reads are billed as regular input (such as Vertex Gemini) (optional)
      "cache_write_tokens"?: integer // Portion of prompt_tokens written to the prompt cache (optional)
    }
    }
  }
  }
}
```

**Example response values**

```json
{
  "id": "Response string",
  "object": "chat.completion",
  "created": 456,
  "model": "Response string",
  "choices": [
    {
      "index": 456,
      "message": {
        "id": "msg_550e8400e29b41d4a716446655440000",
        "content": "This is the response message content",
        "timestamp": "2025-01-01T00:00:00.000Z"
      },
      "finish_reason": "Response string"
    }
  ],
  "usage": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  }
}
```

**Status code: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### Generate text embeddings <a href="#embeddings-create" id="embeddings-create"></a>

POST `/api/v1/embeddings`

{% hint style="info" %}
The request and response formats match OpenAI `embeddings` (`model`, `input`). For examples, see [Embeddings](https://docs.maiagent.ai/tech/api-integration/ai-gateway-openai-compatible#embeddings) in the technical guide.
{% endhint %}

#### Request body

**Request parameters**

| Field            | Type                         | Required | Description                                         |
| ---------------- | ---------------------------- | -------- | --------------------------------------------------- |
| model            | string                       | Yes      |                                                     |
| input            | object                       | Yes      | A non-empty string or an array of non-empty strings |
| encoding\_format | string (enum: float, base64) | No       |                                                     |
| dimensions       | integer                      | No       |                                                     |
| user             | string                       | No       |                                                     |

**Example request structure**

```typescript
{
  "model": string
  "input": // May have different types
  string // A non-empty string or an array of non-empty strings
  "encoding_format"?: string (enum: float, base64) // Optional
  "dimensions"?: integer // Optional
  "user"?: string // Optional
}
```

**Example request values**

```json
{
  "model": "text-embedding-3-large",
  "input": "The weather is nice today"
}
```

#### Code examples

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# API call example (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/embeddings" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "text-embedding-3-large",
    "input": "The weather is nice today"
  }'

# Replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');

// Set request headers
const config = {
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// Request body (payload)
const data = {
    "model": "text-embedding-3-large",
    "input": "The weather is nice today"
  };

axios.post("https://api.maiagent.ai/api/v1/embeddings", data, config)
  .then(response => {
    console.log('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request error:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/embeddings"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json"
}

# Request body (payload)
data = {
    "model": "text-embedding-3-large",
    "input": "The weather is nice today"
}

response = requests.post(url, json=data, headers=headers)
try:
    print("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request error:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/embeddings", [
        'headers' => [
            'Authorization' => 'Bearer YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'model' => 'text-embedding-3-large',
            'input' => 'The weather is nice today'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request error: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response body

**Status code: 200**

**Example response structure**

```typescript
{
  "object"?: string (enum: list) // Optional
  "data"?: [ // Optional
    {
      "object"?: string (enum: embedding) // Optional
      "index"?: integer // Optional
      "embedding"?: // May have different types (Optional)
      array[number] // With encoding_format=float, an array of numbers; with base64, a base64 string of little-endian float32 values (Optional)
    }
  ]
  "model"?: string // Optional
  "usage"?: { // Optional
  {
    "prompt_tokens"?: integer // Optional
    "total_tokens"?: integer // Optional
  }
  }
}
```

**Example response values**

```json
{
  "object": "list",
  "data": [
    {
      "object": "embedding",
      "index": 456,
      "embedding": [
        456
      ]
    }
  ],
  "model": "Response string",
  "usage": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Example response name",
    "description": "Example response description"
  }
}
```

**Status code: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### Speech to Text <a href="#audio-transcriptions-create" id="audio-transcriptions-create"></a>

POST `/api/v1/audio/transcriptions`

{% hint style="info" %}
Upload a complete audio file to get a transcript (synchronous call; streaming is not supported). The request body is `multipart/form-data`: `file` is required. It is the audio file, up to 25 MB, with the format determined by the file extension; `mp3`, `mp4`, `mpeg`, `mpga`, `m4a`, `wav`, and `webm` are accepted. `model` is required; use a model whose `type` is `transcription` (for example `openai/gpt-transcribe` or `azure/speech-to-text`). `language` is optional, for example `zh`; if omitted, the model detects it automatically. `response_format` is optional: `json` (default) or `text`. With `text`, the response is a `text/plain` transcript instead of JSON. For the rules of `language` and for fields that only some models support or that accept a single value only (`prompt`, `temperature`, `stream`), see [Speech to Text](https://docs.maiagent.ai/tech/api-integration/ai-gateway-openai-compatible#audio-transcriptions) in the technical manual. Billing is per second based on the audio duration reported by the provider, rounded up to the next whole second with a minimum of 1 second; see [Usage and Credits billing](https://docs.maiagent.ai/tech/api-integration/ai-gateway-openai-compatible#billing). An API Key with a model allowlist cannot use speech models (returns `404 model_not_found`), and organizations on a per-character billing plan cannot use them (returns `403`); see [Available speech models](https://docs.maiagent.ai/tech/api-integration/ai-gateway-openai-compatible#audio-models). For timeouts, errors, and cases where no credits are deducted, see [Common behavior of speech endpoints](https://docs.maiagent.ai/tech/api-integration/ai-gateway-openai-compatible#audio-behavior).
{% endhint %}

#### Code Examples

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# Example API call (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/audio/transcriptions" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "file=@example_file.mp3" \
  -F "model=openai/gpt-transcribe" \
  -F "language=zh" \
  -F "response_format=json"

# Make sure to replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');
const FormData = require('form-data');

// Create a FormData object
const formData = new FormData();
// Replace with the actual file
formData.append('file', /* actual file object */, 'example_file.mp3');
formData.append('model', 'openai/gpt-transcribe');
formData.append('language', 'zh');
formData.append('response_format', 'json');

// Set request headers
const config = {
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    ...formData.getHeaders()
  }
};

axios.post("https://api.maiagent.ai/api/v1/audio/transcriptions", formData, config)
  .then(response => {
    console.log('Response received successfully:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('Request failed:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/audio/transcriptions"
headers = {
    "Authorization": "Bearer YOUR_API_KEY"
}

# Build the file and form data
files = {
    'file': ('example_file.mp3', open('example_file.mp3', 'rb'), 'audio/mpeg'),
    'model': (None, 'openai/gpt-transcribe'),
    'language': (None, 'zh'),
    'response_format': (None, 'json')
}

response = requests.post(url, files=files, headers=headers)
try:
    print("Response received successfully:")
    print(response.json())
except Exception as e:
    print("Request failed:", e)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/audio/transcriptions", [
        'headers' => [
            'Authorization' => 'Bearer YOUR_API_KEY'
        ],
        'multipart' => [
            [
                'name' => 'file',
                'contents' => fopen('example_file.mp3', 'r'),
                'filename' => 'example_file.mp3'
            ],
            [
                'name' => 'model',
                'contents' => 'openai/gpt-transcribe'
            ],
            [
                'name' => 'language',
                'contents' => 'zh'
            ],
            [
                'name' => 'response_format',
                'contents' => 'json'
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "Response received successfully:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response

**Status code: 200 - Success. When response\_format is json (default), JSON is returned and usage.seconds is the number of seconds billed for this call; when it is text, text/plain; charset=utf-8 is returned and the body is the transcript**

**Response Schema Example**

```typescript
{
  "text"?: string // Transcript (optional)
  "usage"?: { // optional
  {
    "type"?: string (enum: duration) // optional
    "seconds"?: integer // Billed seconds, rounded up to the next whole second, minimum 1 second (optional)
  }
  }
}
```

**Response Example**

```json
{
  "text": "Transcript content",
  "usage": {
    "type": "duration",
    "seconds": 6
  }
}
```

**Status code: 4XX - Error response; X-Error-Code carries its code (see "Error codes").**

***

### Text to Speech <a href="#audio-speech-create" id="audio-speech-create"></a>

POST `/api/v1/audio/speech`

{% hint style="info" %}
Send text to get a complete audio file (synchronous call; streaming is not supported). The request body is JSON: `model` is required; use a model whose `type` is `speech` (for example `openai/gpt-4o-mini-tts`). `input` is required, must not be empty, and is limited to 4,096 characters. `voice` is required and must be one of the `voices` the model lists in `GET /api/v1/models` (for example `alloy`). `response_format` is optional, `mp3` or `wav`; if omitted, the model's first format is used. `speed` is optional; for current OpenAI models it ranges from `0.25` to `4.0`. For `instructions`, which only some models support, and `stream_format`, which only accepts `audio`, see [Text to Speech](https://docs.maiagent.ai/tech/api-integration/ai-gateway-openai-compatible#audio-speech) in the technical manual. The response body is the audio file itself (`audio/mpeg` or `audio/wav`), not JSON; the sample code saves it to a file. Billing is per 1,000 characters of `input`; see [Usage and Credits billing](https://docs.maiagent.ai/tech/api-integration/ai-gateway-openai-compatible#billing). The API Key allowlist and per-character billing plan restrictions are the same as for speech to text; see [Available speech models](https://docs.maiagent.ai/tech/api-integration/ai-gateway-openai-compatible#audio-models). For timeouts and errors, see [Common behavior of speech endpoints](https://docs.maiagent.ai/tech/api-integration/ai-gateway-openai-compatible#audio-behavior); for call limits, see [Limits](https://docs.maiagent.ai/tech/api-integration/ai-gateway-openai-compatible#limits).
{% endhint %}

#### Request Body

**Request Parameters**

| Field            | Type                    | Required | Description                                                                                       |
| ---------------- | ----------------------- | -------- | ------------------------------------------------------------------------------------------------- |
| model            | string                  | Yes      | Identifier of a model whose type is speech                                                        |
| input            | string                  | Yes      | Text to synthesize; must not be empty, up to 4,096 characters                                     |
| voice            | string                  | Yes      | Must be a voice from the model's voices                                                           |
| response\_format | string (enum: mp3, wav) | No       | Must be a format from the model's response\_formats; if omitted, the model's first format is used |
| speed            | number                  | No       | Speech speed; for current OpenAI models, 0.25 to 4.0                                              |

**Request Schema Example**

```typescript
{
  "model": string // Identifier of a model whose type is speech
  "input": string // Text to synthesize; must not be empty, up to 4,096 characters
  "voice": string // Must be a voice from the model's voices
  "response_format"?: string (enum: mp3, wav) // Must be a format from the model's response_formats; if omitted, the model's first format is used (optional)
  "speed"?: number // Speech speed; for current OpenAI models, 0.25 to 4.0 (optional)
}
```

**Request Example**

```json
{
  "model": "openai/gpt-4o-mini-tts",
  "input": "Welcome to MaiAgent.",
  "voice": "alloy",
  "response_format": "mp3"
}
```

#### Code Examples

{% tabs %}
{% tab title="Shell/Bash" %}

```bash
# Example API call (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/audio/speech" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4o-mini-tts",
    "input": "Welcome to MaiAgent.",
    "voice": "alloy",
    "response_format": "mp3"
  }' \
  -o speech.mp3

# Make sure to replace YOUR_API_KEY and verify the request data before running.
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require('axios');
const fs = require('fs');

// Set request headers
const config = {
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  responseType: 'arraybuffer' // The response body is an audio file; receive it as binary
};

// Request payload
const data = {
    "model": "openai/gpt-4o-mini-tts",
    "input": "Welcome to MaiAgent.",
    "voice": "alloy",
    "response_format": "mp3"
  };

axios.post("https://api.maiagent.ai/api/v1/audio/speech", data, config)
  .then(response => {
    fs.writeFileSync('speech.mp3', response.data);
    console.log('Saved as speech.mp3');
  })
  .catch(error => {
    console.error('Request failed:');
    console.error(error.response ? Buffer.from(error.response.data).toString('utf8') : error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/audio/speech"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json"
}

# Request payload
data = {
    "model": "openai/gpt-4o-mini-tts",
    "input": "Welcome to MaiAgent.",
    "voice": "alloy",
    "response_format": "mp3"
}

response = requests.post(url, json=data, headers=headers)
try:
    response.raise_for_status()
    # The response body is an audio file; write it directly to a file
    with open('speech.mp3', 'wb') as f:
        f.write(response.content)
    print("Saved as speech.mp3")
except requests.HTTPError as e:
    print("Request failed:", e, response.text)
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/audio/speech", [
        'headers' => [
            'Authorization' => 'Bearer YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'model' => 'openai/gpt-4o-mini-tts',
            'input' => 'Welcome to MaiAgent.',
            'voice' => 'alloy',
            'response_format' => 'mp3'
        ]
    ]);
    
    // The response body is an audio file; write it directly to a file
    file_put_contents('speech.mp3', $response->getBody());
    echo "Saved as speech.mp3\n";
} catch (Exception $e) {
    echo 'Request failed: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### Response

| Status Code | Description                                                                                                             |
| ----------- | ----------------------------------------------------------------------------------------------------------------------- |
| 200         | Success. The response body is the complete audio file (not JSON), with Content-Type audio/mpeg (mp3) or audio/wav (wav) |
| 4XX         | Error response; X-Error-Code carries its code (see "Error codes").                                                      |

***


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.maiagent.ai/api/en/api-reference/ai-gateway.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
