#### TypeScript SDK

# Voice

The `client.voice` namespace covers text to speech, speech to text, custom voices, and ephemeral client secrets for realtime browser sessions. Examples use the `client` created in the [quickstart](/developers/sdk/typescript#quickstart).

## Text to speech

Synthesize speech with `client.voice.speak()`. It returns a `BinaryResponse` encoded as MP3 unless `output_format` specifies another codec. See the [Text to Speech guide](/developers/model-capabilities/audio/text-to-speech) for supported codecs, languages, and voices.

```typescript
import { writeFile } from 'node:fs/promises';

const speech = await client.voice.speak({
  text: 'Welcome to SpaceXSI. [pause] How can I help you today?',
  language: 'en',
  voice_id: 'eve',
});

await writeFile('welcome.mp3', await speech.bytes());
```

Control delivery using [speech tags](/developers/model-capabilities/audio/text-to-speech#speech-tags): inline tags such as `[pause]`, `[long-pause]`, and `[laugh]`, and wrapping tags such as `<whisper>It's a secret.</whisper>`. Because the API does not report malformed tags, TypeScript checks string literals at compile time: it flags typos like `[laff]` with a suggestion and catches unclosed, unopened, or misnested wrapping tags. Ordinary bracketed text (such as `[they]`) is not flagged unless it matches, hyphenates, or closely resembles a known tag.

To pass a newly released tag before updating the SDK, cast the string to `UnsafeSpeechText`:

```typescript
import { type UnsafeSpeechText } from '@grok/sdk';

await client.voice.speak({
  text: 'Hello [new-tag] there.' as UnsafeSpeechText,
  language: 'en',
});
```

Compile-time tag checking applies only to string literals, not arbitrary `string` values such as model-generated scripts or user input. Supply the valid tags in your prompt using `INLINE_SPEECH_TAGS` and `WRAPPING_SPEECH_TAGS`, validate with `checkSpeechText()`, and clean unknown tags or markup with `stripInvalidSpeechTags()` before synthesis:

```typescript
import {
  INLINE_SPEECH_TAGS,
  checkSpeechText,
  stripInvalidSpeechTags,
} from '@grok/sdk';

const tags = INLINE_SPEECH_TAGS.map(tag => `[${tag}]`).join(', ');
const response = await client.responses.create({
  model: 'grok-4.7',
  input: `Write the opening line of a podcast about volcanoes. You can use these speech tags: ${tags}.`,
});
const line = response.toText();

const problems = checkSpeechText(line); // e.g., ["Unknown speech tag [laff], did you mean [laugh]?"]
if (problems.length > 0) console.warn(problems);

await client.voice.speak({ text: stripInvalidSpeechTags(line), language: 'en' });
```

`voice_id` autocompletes built-in voices and accepts any custom voice ID. List built-in voices with `client.voice.list()`, or inspect one with `client.voice.get(voiceId)`. To begin playback before synthesis finishes, stream `speech.body`. Set `with_timestamps: true` to receive JSON containing base64 `audio` and per-character `audio_timestamps` instead of raw audio bytes.

## Speech to text

Transcribe audio with `client.voice.transcribe()`. Pass a `Blob` or `File`, or provide a `url` for the API to fetch. See the [Speech to Text guide](/developers/model-capabilities/audio/speech-to-text) for supported audio formats and options.

```typescript
import { openAsBlob } from 'node:fs';

const transcript = await client.voice.transcribe({
  file: await openAsBlob('./meeting.mp3'),
  language: 'en',
  format: true,
});

console.log(transcript.text);
```

`format: true` formats spoken numbers, currencies, and units into written form and requires `language`. Word-level timestamps appear in `transcript.words`.

With `diarize: true`, each word includes a `speaker` index. A `File` sends its own filename; for a `Blob`, the SDK derives a filename from its MIME type or detects MP3, AAC, WAV, FLAC, Ogg, Opus, M4A, MP4, Matroska, WebM, AVI, or MOV from the leading bytes. For other formats, set `type` when creating the `Blob`.

To replace sensitive values with placeholder tags such as `[NAME_1]`, pass `redact` with one or more groups (`'pii'`, `'pci'`, `'phi'`) or specific types such as `'ssn'`. Set `show_redacted_text: true` to return the original words on each redacted word as `redacted_text`:

```typescript
const redacted = await client.voice.transcribe({
  file: await openAsBlob('./call.mp3'),
  language: 'en',
  redact: ['pii', 'pci'],
  show_redacted_text: true,
});

console.log(redacted.text); // "My card number is [CREDIT_CARD_1]."
```

`'pii'` does not cover card or bank details, so include `'pci'`, `'bank_account'`, and `'routing_number'` when redacting payment details. If redaction cannot run, the API fails with HTTP 503 rather than returning an unredacted transcript. Redaction is billed per hour of audio on top of transcription.

## Custom voices

Clone a voice from a reference clip of up to 120 seconds with `client.voice.custom.create()`. Creating [custom voices](/developers/model-capabilities/audio/custom-voices) via the API requires an Enterprise plan:

```typescript
import { openAsBlob } from 'node:fs';

const voice = await client.voice.custom.create({
  file: await openAsBlob('./reference.wav'),
  name: 'Friendly Narrator',
  language: 'en',
});

console.log(voice.voice_id);
```

Pass the returned `voice_id` to `client.voice.speak()` or a realtime voice session. `client.voice.custom` also exposes `list()`, `get()`, `update()`, `delete()`, and `getAudio()` (which downloads the reference clip).

## Realtime client secrets

Authenticate browser-based realtime voice sessions with a short-lived [ephemeral client secret](/developers/model-capabilities/audio/ephemeral-tokens) minted on your server instead of exposing your API key:

```typescript
const secret = await client.voice.clientSecrets.create({
  expires_after: { seconds: 300 },
});
```

Send `secret.value` to the browser and pass `xai-client-secret.<value>` as the WebSocket subprotocol when connecting to `wss://api.x.ai/v1/realtime`. Secrets expire after 10 minutes by default (`expires_after.seconds` maxes out at 3,600). You can also pass `session` to preconfigure `model`, `instructions`, `turn_detection`, and `reasoning` for the session.
