# Machine Translation

Request, stream, cache-clear and batch machine translation suggestions through the Comvi REST API.

Canonical: https://comvi.io/docs/api/machine-translation

Comvi returns translation suggestions from several providers: one key at a time, as a stream, as a batch job over many keys, or as a fill of every value a project is missing.

## Permissions

Every endpoint needs `machine_translation.use`; the configured-providers read needs `machine_translation.view`. Language restrictions apply to the source and the target locale separately.

For an API key, the scope `mt:use` grants `machine_translation.use`. Machine translation spends the organization's credits, so the scope is opt-in: no preset includes it, and a key gets it only when it is named, at creation or in the full `permissions` list of `PUT /v1/api-keys/{id}`; the dashboard cannot add it to an existing key. A key without it gets `403 FORBIDDEN` with `meta.requiredScope: "mt:use"`. No scope grants `machine_translation.view`; a key passes the configured-providers read only when its `permissions` include that permission string, set at creation or through `PUT /v1/api-keys/{id}`.

Common errors: `401 AUTHENTICATION_REQUIRED`, `403 FORBIDDEN` (missing permission for the source or target locale, or a key without `mt:use`), `403 READ_ONLY_MODE` on writes. See [Errors](/docs/api/errors).

## Providers

| Provider | ID | Type | Glossary terms in the prompt |
|----------|----|------|------------------------------|
| Google Translate | `google` | Traditional | No |
| DeepL | `deepl` | Traditional | No |
| Amazon Translate | `aws` | Traditional | No |
| Azure Translator | `azure` | Traditional | No |
| OpenAI | `openai` | AI | Yes |
| Anthropic Claude | `anthropic` | AI | Yes |

Glossary terms, no-translate terms, translation memory matches, the key's AI context and the project's AI instructions are assembled into a prompt for the AI providers only. Traditional providers receive the source text and nothing else. Availability depends on the keys the instance administrator has configured.

ICU plural and select messages, including a select wrapping a plural, go through the same suggestions endpoint as plain messages: send the whole message as `sourceText`. An AI provider translates the whole pattern and rebuilds it with the target language's plural categories, so an English `one`/`other` message can come back with the Ukrainian `one`/`few`/`many`/`other` set. A traditional provider translates each form on its own and keeps the source's categories.

### `GET /v1/projects/{projectId}/mt/configured-providers`

Which providers are available on the server. `machine_translation.view`.

| Parameter | In | Type | Required | Meaning |
|-----------|----|------|----------|---------|
| `projectId` | path | `integer` | Yes | Project ID |

```bash
curl -b cookies.txt https://api.comvi.io/v1/projects/1/mt/configured-providers
```

```json
{ "providers": { "google": true, "deepl": true, "aws": false, "azure": false, "openai": true, "anthropic": true } }
```

### `POST /v1/projects/{projectId}/mt/suggestions`

Ask each configured provider for a suggestion for one key. Rate limit: 60 requests per minute per caller per project. Suggestions are cached; editing a glossary, the translation memory or the AI instructions does not invalidate the cache, so clear it with `DELETE /v1/projects/{projectId}/mt/suggestions`.

| Parameter | In | Type | Required | Meaning |
|-----------|----|------|----------|---------|
| `projectId` | path | `integer` | Yes | Project ID |
| `key` | body | `string` | Yes | Key name, 1 to 512 characters |
| `namespace` | body | `string` | No | Default `default` |
| `sourceLocale` | body | `string` | Yes | Source language code |
| `targetLocale` | body | `string` | Yes | Target language code. Must differ from `sourceLocale` |
| `sourceText` | body | `string` | No | Text to translate; resolved from the key if omitted |
| `limit` | body | `integer` | No | Providers to ask, 1 to 10, default 5. With six providers configured, pass 10 to ask them all |

```bash
curl -X POST -b cookies.txt -H "Content-Type: application/json" \
-d '{"key": "welcome.message", "sourceLocale": "en", "targetLocale": "uk", "limit": 3}' \
https://api.comvi.io/v1/projects/1/mt/suggestions
```

```json
[
{ "providerId": "google", "providerLabel": "Google Translate", "text": "Ласкаво просимо до нашого додатку!" },
{ "providerId": "openai", "providerLabel": "OpenAI", "text": "Вітаємо у нашому застосунку!" }
]
```

| Status and code | When |
|-----------------|------|
| `400 INVALID_INPUT` | `sourceLocale` and `targetLocale` are the same |
| `403 LIMIT_EXCEEDED` | The organization has used all its MT credits |
| `422 FIELD_REQUIRED` | `key`, `sourceLocale` or `targetLocale` is missing |
| `422 VALIDATION_ERROR` | `limit` is outside 1 to 10, or a field has the wrong type |
| `429 TOO_MANY_REQUESTS` | More than 60 requests in a minute |

### `DELETE /v1/projects/{projectId}/mt/suggestions`

Delete the cached suggestions for one key and locale pair, for every provider. Idempotent: an unknown key or an empty cache returns `{ "deleted": 0 }`, not `404`. Rate limit: 30 requests per minute per caller per project.

| Parameter | In | Type | Required | Meaning |
|-----------|----|------|----------|---------|
| `projectId` | path | `integer` | Yes | Project ID |
| `key` | body | `string` | Yes | Key name, 1 to 512 characters |
| `namespace` | body | `string` | No | Default `default` |
| `sourceLocale` | body | `string` | Yes | Source language code |
| `targetLocale` | body | `string` | Yes | Target language code |

```bash
curl -X DELETE -b cookies.txt -H "Content-Type: application/json" \
-d '{"key": "welcome.message", "sourceLocale": "en", "targetLocale": "uk"}' \
https://api.comvi.io/v1/projects/1/mt/suggestions
```

```json
{ "deleted": 3 }
```

| Status and code | When |
|-----------------|------|
| `400 INVALID_INPUT` | `sourceLocale` and `targetLocale` are the same |
| `422 FIELD_REQUIRED` | `key`, `sourceLocale` or `targetLocale` is missing |
| `422 FIELD_TOO_LONG` | `key` over 512 characters, or a locale code over 50 |
| `422 FIELD_TOO_SHORT` | `key` or a locale code is empty |
| `429 TOO_MANY_REQUESTS` | More than 30 requests in a minute |

### `GET /v1/projects/{projectId}/mt/suggestions/stream`

The same suggestions as Server-Sent Events, for `EventSource`. This variant waits for every provider and then writes all `suggestion` events at once, followed by `done`. Every 15 seconds the server writes an SSE comment, `: ping <milliseconds>`, which `EventSource` ignores. A failure mid-stream arrives as an `error` event carrying `{ "message": "..." }` and the stream closes; it is not an HTTP status, because the headers were already sent.

| Parameter | In | Type | Required | Meaning |
|-----------|----|------|----------|---------|
| `projectId` | path | `integer` | Yes | Project ID |
| `key` | query | `string` | Yes | Key name |
| `sourceLocale` | query | `string` | Yes | Source language code |
| `targetLocale` | query | `string` | Yes | Target language code |
| `namespace` | query | `string` | No | Namespace |
| `sourceText` | query | `string` | No | Text to translate |
| `limit` | query | `integer` | No | 1 to 10, default 5 |

```javascript
const url = new URL('https://api.comvi.io/v1/projects/1/mt/suggestions/stream');
url.searchParams.set('key', 'welcome.message');
url.searchParams.set('sourceLocale', 'en');
url.searchParams.set('targetLocale', 'uk');
const source = new EventSource(url, { withCredentials: true });
source.addEventListener('suggestion', (e) => console.log(JSON.parse(e.data).text));
source.addEventListener('error', (e) => { if (e.data) console.error(JSON.parse(e.data).message); source.close(); });
source.addEventListener('done', () => source.close());
```

### `POST /v1/projects/{projectId}/mt/suggestions/stream`

The same suggestions as newline-delimited JSON, delivered as they land. The body is the same as `POST /v1/projects/{projectId}/mt/suggestions`. Every 15 seconds the server writes a bare newline as a keep-alive, so skip blank lines before parsing.

```text
{"event":"suggestion","data":{"providerId":"google","providerLabel":"Google Translate","text":"Ласкаво просимо!"}}
{"event":"suggestion","data":{"providerId":"deepl","providerLabel":"DeepL","text":"Ласкаво просимо!"}}
{"event":"done","data":{}}
```

### `POST /v1/projects/{projectId}/mt/fill`

Queue machine translation for every key × locale pair whose target is missing (`null` or empty), and nothing else. The route is what `comvi translate` calls. Pairs that a running job already covers, from an earlier fill, from a batch, or from the automatic translation a push triggers, are reported as in flight and not queued again, so credits are spent once. Jobs are queued per target locale, each holding up to 10,000 keys, with a single attempt; calling again is the retry. Rate limit: 10 requests per minute per API key (per user for a session).

| Parameter | In | Type | Required | Meaning |
|-----------|----|------|----------|---------|
| `projectId` | path | `integer` | Yes | Project ID |
| `targetLocaleCodes` | body | `string[]` | No | Target locales, in any spelling of the code, 1 to 1,000 entries of 1 to 50 characters. Default: every target locale the caller may use machine translation on; the ones they may not are listed in `skippedLocales`. A locale named here that the caller may not use is `403 FORBIDDEN` |
| `namespaces` | body | `string[]` | No | Limit the fill to these namespaces, 1 to 1,000 names of 1 to 255 characters |
| `keyIds` | body | `integer[]` | No | Limit the fill to these keys, 1 to 10,000 unique IDs |
| `maxPairs` | body | `integer` | No | Upper bound on `pairs.toTranslate`. `0` or omitted: no limit |
| `dryRun` | body | `boolean` | No | Count and estimate, queue nothing. Default `false` |

```bash
curl -X POST -H "Authorization: Bearer $COMVI_API_KEY" -H "Content-Type: application/json" \
-d '{"targetLocaleCodes": ["de"], "namespaces": ["common"], "maxPairs": 1000}' \
https://api.comvi.io/v1/projects/1/mt/fill
```

Returns `202 Accepted` when jobs were queued, `200 OK` for a dry run or when there is no new work. Both carry the same body.

```json
{
"jobs": [{ "jobId": "fill-1-de-5b0c3c1e-8d7a-4c9b-9f61-2f4b8a1d6e30", "targetLocaleCode": "de", "keyCount": 2, "owned": true }],
"pairs": { "toTranslate": 2, "alreadyInFlight": 0, "alreadyTranslated": 1, "noSource": 0 },
"skippedLocales": [],
"failedLocales": [],
"estimate": { "credits": 2, "approximate": false },
"credits": { "exhausted": false }
}
```

| Field | Meaning |
|-------|---------|
| `jobs[]` | Every job covering the fill, to poll with the status endpoint. `owned: false` is a job that already existed; its pairs were not queued again |
| `pairs.toTranslate` | New work: queued now, or what a dry run would queue |
| `pairs.alreadyInFlight` | Missing pairs an existing job covers |
| `pairs.alreadyTranslated` | Pairs that have a target value |
| `pairs.noSource` | Pairs with no source value to translate from |
| `skippedLocales[]` | Target locales left out of the default set because the caller may not use machine translation on them; empty when `targetLocaleCodes` was given |
| `failedLocales[]` | Locales whose job could not be queued (`reason: "enqueue_failed"`). The other jobs went in; call again to finish these |
| `estimate` | Credits the new pairs take, per pair with the provider's minimum per request. `approximate: true` for an AI provider, which bills by tokens |
| `credits.exhausted` | The organization's credits are at their limit. With no new work the response is still `200` and carries the jobs in flight |

| Status and code | When |
|-----------------|------|
| `403 FORBIDDEN` | The caller may not use machine translation on the source locale or on a locale named in `targetLocaleCodes`; `meta.locales` names them. Or an API key without `mt:use` |
| `403 LIMIT_EXCEEDED` | Credits are at their limit and there is new work. Nothing was queued; `meta.jobs` lists the jobs already in flight so a client can still wait for them |
| `409 MT_FILL_BUSY` | Another fill held the project for about 5 seconds. Nothing was queued; retry |
| `422 MT_FILL_LIMIT` | `pairs.toTranslate` is over `maxPairs`. Nothing was queued; `meta` carries `maxPairs`, `pairs` and `estimate` |
| `422 LOCALE_NOT_FOUND` | A code in `targetLocaleCodes` is not a target locale of the project, or is the source locale; `meta.locales` names them |
| `422 NAMESPACE_NOT_FOUND` | A name in `namespaces` is not a namespace of the project; `meta.namespaces` names them |
| `429 TOO_MANY_REQUESTS` | More than 10 requests in a minute |
| `500 INTERNAL_ERROR` | No job at all could be queued; `meta.failedLocales` lists them |

### `POST /v1/projects/{projectId}/keys/batch/mt`

Translate many keys into one or more target locales. One job is queued per target locale, each attempted up to 3 times with exponential backoff starting at 10 seconds.

| Parameter | In | Type | Required | Meaning |
|-----------|----|------|----------|---------|
| `projectId` | path | `integer` | Yes | Project ID |
| `keyIds` | body | `integer[]` | Yes | 1–10,000 unique key IDs |
| `sourceLocaleCode` | body | `string` | Yes | Source language code |
| `targetLocaleCodes` | body | `string[]` | Yes | 1–1,000 codes of 1–50 characters. No duplicates, none equal to the source |
| `overwriteExisting` | body | `boolean` | No | Default `false` |

```bash
curl -X POST -b cookies.txt -H "Content-Type: application/json" \
-d '{"keyIds": [42, 43, 44, 45], "sourceLocaleCode": "en", "targetLocaleCodes": ["uk", "de"]}' \
https://api.comvi.io/v1/projects/1/keys/batch/mt
```

Returns `202 Accepted`. There is no top-level `jobId`; poll each entry of `jobs[]`. `totalKeys` counts the keys sent, not keys times locales.

```json
{
"jobs": [{ "jobId": "1042", "targetLocaleCode": "uk" }, { "jobId": "1043", "targetLocaleCode": "de" }],
"status": "queued", "totalKeys": 4,
"message": "2 batch MT job(s) queued. Subscribe to SSE events for project 1 to receive progress updates."
}
```

| Status and code | When |
|-----------------|------|
| `400 INVALID_INPUT` | `targetLocaleCodes` has duplicates, or one equals `sourceLocaleCode` |
| `403 LIMIT_EXCEEDED` | The organization has used all its MT credits |
| `422 FIELD_REQUIRED` | `keyIds`, `sourceLocaleCode` or `targetLocaleCodes` is missing |
| `422 VALIDATION_ERROR` | `keyIds` or `targetLocaleCodes` is empty |

### `GET /v1/projects/{projectId}/keys/batch/mt/{jobId}/status`

Poll one batch or fill job. `result` is present only when `status` is `completed`; a failed job carries `error` instead.

| Parameter | In | Type | Required | Meaning |
|-----------|----|------|----------|---------|
| `projectId` | path | `integer` | Yes | Project ID |
| `jobId` | path | `string` | Yes | A `jobId` from `jobs[]` |

```bash
curl -b cookies.txt https://api.comvi.io/v1/projects/1/keys/batch/mt/1042/status
```

```json
{
"jobId": "1042", "status": "completed", "progress": 100,
"result": {
    "processed": 3, "failed": 1, "duration": 3200.5, "alreadyTranslated": 0, "skippedFilledMeanwhile": 1,
    "errors": [{ "keyId": 45, "key": "checkout.total", "message": "MT service returned no translation", "type": "no_translation" }]
}
}
```

| `status` | Meaning |
|----------|---------|
| `waiting` | In the queue |
| `active` | Being processed |
| `completed` | Finished |
| `failed` | Failed |

| `result` field | Meaning |
|----------------|---------|
| `processed` | Values written |
| `failed` | Keys that got no value; one entry each in `errors[]` |
| `alreadyTranslated` | Keys skipped because the target already had a value when the job read it. Absent on jobs that finished before the counter existed |
| `skippedFilledMeanwhile` | Keys skipped because a value arrived, from a person or another job, between the read and the write. The job never overwrites it. Absent on older jobs |
| `errors[].type` | `insufficient_credits` (the organization's credits ran out during the job), `provider_error`, `no_source`, `no_translation` (the provider returned nothing), `unknown` |

| Status and body | When |
|-----------------|------|
| `404 { "error": "Job not found" }` | Unknown job, a finished job the queue has already evicted, one from another project, or one whose source or target locale the caller may not use machine translation on. A job started by someone else in the project is visible as long as its locales are. Not the standard envelope |

### `POST /v1/projects/{projectId}/keys/batch/mt/{jobId}/cancel`

Cancel a queued job. A job that has started cannot be stopped: the response is `200` with `success: false` and a message saying it is active, completed or failed. Check `success`, not the status code.

```bash
curl -X POST -b cookies.txt https://api.comvi.io/v1/projects/1/keys/batch/mt/1042/cancel
```

```json
{ "success": true, "message": "Job cancelled successfully" }
```

| Status and body | When |
|-----------------|------|
| `404 { "error": "Job not found" }` | Unknown job, or one the caller may not see, as for the status endpoint |

## Next steps

- [comvi translate](/docs/cli/translate) to run a fill from a terminal or CI and write the results into local files
- [Translations](/docs/api/translations) to apply suggestions and follow `batch_mt.*` events
- [Projects](/docs/api/projects) to configure providers per project
- [Glossaries](/docs/api/glossaries) for terminology in the prompt
