# Synthesize speech from text prompts

> OpenGen models speech synthesis under the text-to-speech operation with typed voice, speed, audio outputFormat, and optional style systemPrompt controls. Inspect exact character limits and published character or token pricing for minimax/speech-02-hd and openai/gpt-4o-mini-tts via GET /v1/models/{provider}/{model}?operation=text-to-speech, run POST /v1/pricing/estimate to verify route eligibility, and submit once with a persisted Idempotency-Key when an executable route is configured.

## Agent Prompt

```text
Walk me through a text-to-speech synthesis request on OpenGen (https://opengen.dev):
1. Discover speech models via GET https://opengen.dev/v1/models?operation=text-to-speech (or MCP find_models with operation="text-to-speech").
2. Inspect minimax/speech-02-hd or openai/gpt-4o-mini-tts via GET https://opengen.dev/v1/models/{provider}/{model}?operation=text-to-speech (or MCP get_model) to verify prompt length limits, speed range, outputFormat ("mp3" or "wav"), voice, and optional systemPrompt support.
3. Run POST https://opengen.dev/v1/pricing/estimate (or MCP estimate_cost) to inspect workspaceEligibility and character or token pricing disclosures. Stop and report if routes are documented/comparison-only on the current gateway.
4. Only when an executable route is eligible and I confirm the spend cap, submit once with a persisted Idempotency-Key via POST https://opengen.dev/v1/generations or MCP generate, then retrieve the private audio output via job_get.
```

OpenGen `text-to-speech` uses the same canonical generation envelope (`modelId`, `operation: "text-to-speech"`, `input`) and workspace-private delivery pipeline as image and video models, returning short-lived first-party `/media/...` links for MP3 or WAV audio files.

> [!NOTE]
> Verify route executability before promising live speech synthesis. In the current catalog snapshot, `minimax-undisclosed/minimax-speech-02-hd`, `fal-undisclosed/minimax-speech-02-hd`, and `openai-undisclosed/openai-gpt-4o-mini-tts` carry `status: "documented"` with no active execution adapter (comparison-only until enabled on your target gateway). Always check `workspaceEligibility` in `POST /v1/pricing/estimate`.

## 1. Compare the catalog speech models

| Model                                                                  | Prompt limit   | Speed bounds | Extra controls                                                                            | Published tariff                                                                                   |
| ---------------------------------------------------------------------- | -------------- | ------------ | ----------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| [MiniMax Speech-02 HD](/minimax/speech-02-hd) (`minimax/speech-02-hd`) | `10,000` chars | `0.5`–`2`    | `voice`, `speed`, `outputFormat` (`mp3`/`wav`)                                            | `$0.10` per `1,000` characters (`$100.00 / 1M` characters) across MiniMax and fal.                 |
| [GPT-4o mini TTS](/openai/gpt-4o-mini-tts) (`openai/gpt-4o-mini-tts`)  | `4,096` chars  | `0.25`–`4`   | `voice`, `speed`, `systemPrompt` (tone/pacing instructions), `outputFormat` (`mp3`/`wav`) | `$0.60 / 1M` text input tokens + `$12.00 / 1M` audio output tokens (estimated `~$0.015 / minute`). |

`text-to-speech` rejects image/video fields (`references`, `firstFrame`, `lastFrame`, `sourceVideo`, `mask`, `resolution`, `aspectRatio`) and rejects non-audio `outputFormat` values (`png`, `jpeg`, `webp`, `mp4`) with `400 invalid_generation`.

```bash tab="cURL"
curl --fail-with-body \
  "https://opengen.dev/v1/models?operation=text-to-speech"

curl --fail-with-body \
  "https://opengen.dev/v1/models/minimax/speech-02-hd?operation=text-to-speech"

curl --fail-with-body \
  "https://opengen.dev/v1/models/openai/gpt-4o-mini-tts?operation=text-to-speech"
```

```ts tab="TypeScript"
const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev';
const detail = await fetch(
  `${origin}/v1/models/minimax/speech-02-hd?operation=text-to-speech`,
).then((r) => r.json());
console.log(detail.model.generationProfiles[0], detail.pricing);
```

```python tab="Python"
import os
import httpx

origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev")
with httpx.Client(timeout=30.0) as client:
    detail = client.get(
        f"{origin}/v1/models/minimax/speech-02-hd",
        params={"operation": "text-to-speech"},
    ).raise_for_status().json()
    print(detail["model"]["generationProfiles"][0], detail["pricing"])
```

```json tab="MCP"
{
  "tool": "get_model",
  "arguments": {
    "id": "minimax/speech-02-hd",
    "operation": "text-to-speech"
  }
}
```

```bash tab="CLI"
opengen catalog search --operation text-to-speech
opengen catalog get minimax/speech-02-hd
opengen pricing --model minimax/speech-02-hd --operation text-to-speech
```

## 2. Estimate cost and route eligibility with MiniMax Speech-02 HD

Use `POST /v1/pricing/estimate` first to check route eligibility and character-based pricing (`$0.10 / 1,000` characters).

```bash tab="cURL"
set -eu
umask 077
if [ -e tts-submission.key ]; then
  echo "Existing tts-submission.key found; recover read-only via GET /v1/generations/lookup before replacing tts-request.json." >&2
  exit 1
fi
rm -f tts-request.json
cat <<'JSON' > tts-request.json
{
  "modelId": "minimax/speech-02-hd",
  "operation": "text-to-speech",
  "input": {
    "prompt": "Welcome to OpenGen. Your private media generation job has finished and is ready to download.",
    "voice": "English_CalmWoman",
    "speed": 1,
    "outputFormat": "mp3"
  },
  "routeId": "minimax-undisclosed/minimax-speech-02-hd",
  "billing": "managed",
  "maxCostMicros": 150000
}
JSON
chmod 600 tts-request.json

# Dry-run estimate only (review selectedRouteId, recommendedMaxCostMicros, and workspaceEligibility)
curl --fail-with-body \
  -X POST "https://opengen.dev/v1/pricing/estimate" \
  -H "Authorization: Bearer $OPENGEN_API_KEY" \
  -H "Content-Type: application/json" \
  --data @tts-request.json
```

```json tab="MCP"
{
  "tool": "estimate_cost",
  "arguments": {
    "modelId": "minimax/speech-02-hd",
    "operation": "text-to-speech",
    "input": {
      "prompt": "Welcome to OpenGen. Your private media generation job has finished and is ready to download.",
      "voice": "English_CalmWoman",
      "speed": 1,
      "outputFormat": "mp3"
    },
    "routeId": "minimax-undisclosed/minimax-speech-02-hd",
    "billing": "managed",
    "maxCostMicros": 150000
  }
}
```

```bash tab="CLI"
opengen pricing estimate --input tts-request.json
```

### Submit once after reviewing the estimate

Run this step only after reviewing the estimate output above and confirming an executable route is eligible (`selectedRouteId != null`, `executableCandidateCount > 0`, `blockers: []`) and confirming `maxCostMicros`.

```bash tab="cURL"
set -eu
umask 077
if [ -e tts-submission.key ]; then
  echo "Existing tts-submission.key found; recover read-only via GET /v1/generations/lookup before creating a new submission." >&2
  exit 1
fi
RAW_UUID="$(uuidgen)"
[ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; }
IDEMPOTENCY_KEY="tts-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')"
(set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > tts-submission.key)

curl --fail-with-body \
  -X POST "https://opengen.dev/v1/generations" \
  -H "Authorization: Bearer $OPENGEN_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $IDEMPOTENCY_KEY" \
  -H "Prefer: wait=20" \
  --data @tts-request.json > tts-receipt.json
```

```ts tab="TypeScript"
import { randomUUID } from 'node:crypto';
import { writeFile } from 'node:fs/promises';

const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev';
const headers = {
  Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`,
  'Content-Type': 'application/json',
};

const ttsPayload = {
  modelId: 'minimax/speech-02-hd',
  operation: 'text-to-speech',
  input: {
    prompt:
      'Welcome to OpenGen. Your private media generation job has finished and is ready to download.',
    voice: 'English_CalmWoman',
    speed: 1,
    outputFormat: 'mp3',
  },
  routeId: 'minimax-undisclosed/minimax-speech-02-hd',
  billing: 'managed',
  maxCostMicros: 150000,
} as const;

const estRes = await fetch(`${origin}/v1/pricing/estimate`, {
  method: 'POST',
  headers,
  body: JSON.stringify(ttsPayload),
});
if (!estRes.ok) throw new Error(`Estimate failed (${estRes.status}): ${await estRes.text()}`);
const estimate = await estRes.json();
console.log('Review estimate before submitting:', estimate);

const eligibility = estimate.workspaceEligibility;
const canSubmit = Boolean(
  estimate.selectedRouteId &&
  eligibility?.policyAllowed === true &&
  eligibility.hasActiveBillingHold === false &&
  eligibility.executableCandidateCount > 0 &&
  (eligibility.billingMode === 'byok' || eligibility.sufficientBalance === true) &&
  Array.isArray(eligibility.blockers) &&
  eligibility.blockers.length === 0,
);
if (canSubmit && process.env.CONFIRM_SUBMIT === '1') {
  const idempotencyKey = `tts-${randomUUID()}`;
  await writeFile(
    'tts-submission.json',
    JSON.stringify({ idempotencyKey, payload: ttsPayload }, null, 2),
    { mode: 0o600, flag: 'wx' },
  );
  const genRes = await fetch(`${origin}/v1/generations`, {
    method: 'POST',
    headers: { ...headers, 'Idempotency-Key': idempotencyKey, Prefer: 'wait=20' },
    body: JSON.stringify(ttsPayload),
  });
  if (!genRes.ok) throw new Error(`Generation failed (${genRes.status}): ${await genRes.text()}`);
  const job = await genRes.json();
  console.log(job.id, job.status, job.outputs);
}
```

```python tab="Python"
import json
import os
import uuid
import httpx

origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev")
auth = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"}
tts_payload = {
    "modelId": "minimax/speech-02-hd",
    "operation": "text-to-speech",
    "input": {
        "prompt": "Welcome to OpenGen. Your private media generation job has finished and is ready to download.",
        "voice": "English_CalmWoman",
        "speed": 1,
        "outputFormat": "mp3",
    },
    "routeId": "minimax-undisclosed/minimax-speech-02-hd",
    "billing": "managed",
    "maxCostMicros": 150000,
}

with httpx.Client(timeout=45.0) as client:
    estimate = client.post(f"{origin}/v1/pricing/estimate", headers=auth, json=tts_payload).raise_for_status().json()
    print("Review estimate before submitting:", estimate)
    eligibility = estimate.get("workspaceEligibility") or {}
    can_submit = (
        bool(estimate.get("selectedRouteId"))
        and eligibility.get("policyAllowed") is True
        and eligibility.get("hasActiveBillingHold") is False
        and eligibility.get("executableCandidateCount", 0) > 0
        and (eligibility.get("billingMode") == "byok" or eligibility.get("sufficientBalance") is True)
        and eligibility.get("blockers") == []
    )
    if can_submit and os.environ.get("CONFIRM_SUBMIT") == "1":
        idempotency_key = f"tts-{uuid.uuid4()}"
        fd = os.open("tts-submission.json", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
        with os.fdopen(fd, "w", encoding="utf-8") as handle:
            json.dump({"idempotencyKey": idempotency_key, "payload": tts_payload}, handle, indent=2)
        job = client.post(
            f"{origin}/v1/generations",
            headers={**auth, "Idempotency-Key": idempotency_key, "Prefer": "wait=20"},
            json=tts_payload,
        ).raise_for_status().json()
        print(job["id"], job["status"], job.get("outputs"))
```

```json tab="MCP"
{
  "tool": "generate",
  "arguments": {
    "idempotencyKey": "tts-example-001",
    "modelId": "minimax/speech-02-hd",
    "operation": "text-to-speech",
    "input": {
      "prompt": "Welcome to OpenGen. Your private media generation job has finished and is ready to download.",
      "voice": "English_CalmWoman",
      "speed": 1,
      "outputFormat": "mp3"
    },
    "routeId": "minimax-undisclosed/minimax-speech-02-hd",
    "billing": "managed",
    "maxCostMicros": 150000,
    "waitMs": 20000
  }
}
```

```bash tab="CLI"
set -eu
umask 077
if [ -e tts-submission.key ]; then
  echo "Existing tts-submission.key found; run 'opengen job recover --idempotency-key \"\$(cat tts-submission.key)\"' before creating a new submission." >&2
  exit 1
fi
RAW_UUID="$(uuidgen)"
[ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; }
IDEMPOTENCY_KEY="tts-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')"
(set -C; printf '%s\n' "$IDEMPOTENCY_KEY" > tts-submission.key)
opengen generate --input tts-request.json --idempotency-key "$IDEMPOTENCY_KEY" --wait 20 > tts-receipt.json
```

## 3. Steerable delivery instructions with GPT-4o mini TTS

[GPT-4o mini TTS](/openai/gpt-4o-mini-tts) (`openai/gpt-4o-mini-tts`) adds `input.systemPrompt` to steer speaking tone, pacing, and emphasis (up to `4,096` prompt characters and `speed` `0.25`–`4`). Because audio-token output length varies dynamically, managed quotes are currently comparison-only (`selectedRouteId: null`); once an execution adapter is enabled, use `"billing": "byok"` (omitting `maxCostMicros`):

```json
{
  "modelId": "openai/gpt-4o-mini-tts",
  "operation": "text-to-speech",
  "input": {
    "prompt": "Your build pipeline succeeded with zero warnings.",
    "voice": "coral",
    "speed": 1,
    "systemPrompt": "Speak in a calm, clear technical narration style with brief pauses between clauses.",
    "outputFormat": "mp3"
  },
  "routeId": "openai-undisclosed/openai-gpt-4o-mini-tts",
  "billing": "byok"
}
```

## 4. Download audio privately or feed it into video

Delivered MP3 (`audio/mpeg`) and WAV (`audio/wav`) outputs download over short-lived first-party `/media/...` URLs and can also be promoted into private workspace inputs with `POST /v1/assets` (`{ "source": "job_output", "sourceJobId": "<audio-job-uuid>", "outputIndex": 0 }`) for audio-conditioned [Reference to Video](/docs/guides/reference-to-video) workflows.

## Next steps

- Pair generated narration with synchronized visual clips in [Reference to Video](/docs/guides/reference-to-video).
- Compare per-unit pricing disclosures across all modalities in [Pricing and Analytics](/docs/pricing-and-analytics).

## Supported Models

Live catalog variants supporting `text-to-speech` (single-source tariffs from `@media-router/catalog`; unknown prices stay `Unknown`, never `$0`).

| Model | Exact ID | Creator | Routes | Lowest published rate | Weights | Inspect schema |
| --- | --- | --- | --- | --- | --- | --- |
| [MiniMax Speech-02 HD](https://opengen.dev/minimax/speech-02-hd#variant-minimax-speech-02-hd) | `minimax/speech-02-hd` | MiniMax | 2 | $0.10 / 1k chars | Closed | `GET /v1/models/minimax/speech-02-hd?operation=text-to-speech` |
| [GPT-4o mini TTS](https://opengen.dev/openai/gpt-4o-mini-tts#variant-openai-gpt-4o-mini-tts) | `openai/gpt-4o-mini-tts` | OpenAI | 1 | ≈$0.00025 / sec | Closed | `GET /v1/models/openai/gpt-4o-mini-tts?operation=text-to-speech` |
