# OpenAI

> Text-to-speech with OpenAITTSService, streaming 24 kHz PCM from OpenAI's speech API.

Source: https://polvallverdu.github.io/pipedog/docs/services/tts/openai/



## Overview [#overview]

* **`OpenAITTSService`**: sends each sentence to OpenAI's speech API (`audio.speech`) and streams
  the reply back as raw 24 kHz PCM. Supports the `gpt-4o-mini-tts` instructions and speed
  controls.

<Cards>
  <Card title="Upstream page" href="https://docs.pipecat.ai/api-reference/server/services/tts/openai">
    Pipecat's documentation for the same service.
  </Card>

  <Card title="Source" href="https://github.com/polvallverdu/pipedog/tree/main/packages/openai/src">
    `packages/openai/src/tts.ts`.
  </Card>

  <Card title="OpenAI docs" href="https://platform.openai.com/docs/guides/text-to-speech">
    Models, voices and instructions.
  </Card>
</Cards>

## Installation [#installation]

```bash
bun add @pipedog/openai
```

```ts
import { OpenAITTSService } from "@pipedog/openai/tts";
```

## Prerequisites [#prerequisites]

* An OpenAI account and an API key from the [OpenAI dashboard](https://platform.openai.com/api-keys).
* Pass the key as `apiKey`. If you leave it out, the OpenAI SDK reads `OPENAI_API_KEY`. The
  examples read it from `OPENAI_API_KEY`.

## OpenAITTSService [#openaittsservice]

### Configuration [#configuration]

| Option | Type | Required | Description |
|---|---|---|---|
| `apiKey` | `string \| null \| undefined` | no | OpenAI API key for authentication. If null, uses environment variable. |
| `baseUrl` | `string \| null \| undefined` | no | Custom base URL for OpenAI API. If null, uses default. |
| `httpClient` | `{ (input: RequestInfo \| URL, init?: RequestInit): Promise<Response>; (input: string \| URL \| Request, init?: RequestInit): Promise<Response>; } \| null \| undefined` | no | Custom `fetch` for API requests, e.g. one with a longer request timeout. Defaults to null, which lets the SDK use its own. DIVERGENCE: upstream takes an httpx client here. |
| `settings` | `OpenAITTSSettings \| null \| undefined` | no | Runtime-updatable settings. |
| `name` | `string \| null \| undefined` | no | Custom name; defaults to `ClassName#count`. |
| `taskManager` | `BaseTaskManager \| null \| undefined` | no | Task manager for handling tasks. |
| `enableDirectMode` | `boolean \| undefined` | no | Process frames immediately instead of using internal queues. |
| `metrics` | `FrameProcessorMetrics \| null \| undefined` | no | Optional metrics collector for this processor. |
| `textAggregationMode` | `TextAggregationMode \| null \| undefined` | no | How to aggregate incoming text before synthesis. `TextAggregationMode.SENTENCE` (default) buffers until sentence boundaries, `TextAggregationMode.TOKEN` streams tokens directly for lower latency. |
| `pushTextFrames` | `boolean \| undefined` | no | Whether to push TextFrames and LLMFullResponseEndFrames. |
| `pushStopFrames` | `boolean \| undefined` | no | Whether to automatically push TTSStoppedFrames. |
| `pushStartFrame` | `boolean \| undefined` | no | Whether to automatically create audio contexts and push TTSStartedFrames. When true, the base class handles `createAudioContext` and yields `TTSStartedFrame` before each synthesis call, so `runTts` implementations do not need to. |
| `stopFrameTimeoutS` | `number \| undefined` | no | Idle time before pushing TTSStoppedFrame when pushStopFrames is true. |
| `pushSilenceAfterStop` | `boolean \| undefined` | no | Whether to push silence audio after TTSStoppedFrame. |
| `silenceTimeS` | `number \| undefined` | no | Duration of silence to push when pushSilenceAfterStop is true. |
| `pauseFrameProcessing` | `boolean \| undefined` | no | Whether to hold incoming frames after a turn until its audio contexts end. Needed by services whose audio doesn't carry its request's context ID. |
| `maxConsecutiveZeroAudioContexts` | `number \| undefined` | no | How many consecutive TTS contexts may complete without producing any audio before the service is reported unable to do its job. Catches a provider that accepts requests and stays silent — an unknown voice ID, say — which no error ever surfaces. Every silent context reports an error the service can carry on from, whatever the limit is; on reaching the limit the service reports a permanent error instead, stops being given work, and the pipeline worker applies its `ProcessorUnusablePolicy`. Set to 0 to report silent contexts without ever writing the service off. |
| `appendTrailingSpace` | `boolean \| undefined` | no | Whether to append a trailing space to text before sending to TTS. This helps prevent some TTS services from vocalizing trailing punctuation (e.g., "dot"). Only applied in sentence aggregation mode; when streaming tokens, the incoming text's own whitespace is preserved. |
| `sampleRate` | `number \| null \| undefined` | no | Output sample rate for generated audio. |
| `skipTextTypes` | `string[] \| null \| undefined` | no | List of text types that should not be spoken. |
| `textTransforms` | `[string, TextTransform][] \| null \| undefined` | no | A list of TextTransforms to transform text just before sending it to TTS. Each TextTransform takes the aggregated text and its type, and returns the transformed text. To register, provide a list of tuples of `[textType \| "*", transformFunction]`. |
| `transportDestination` | `string \| null \| undefined` | no | Destination for generated audio frames. |
| `reuseContextIdWithinTurn` | `boolean \| undefined` | no | Whether the service should reuse context IDs within the same turn. |
| `audioCache` | `TTSAudioCacheStore \| null \| undefined` | no | Where to keep synthesized audio for reuse (e.g. a shared `TTSAudioCache`). Text whose audio is in the cache is served from it, with no request to the provider. Lines get there through `warmAudioCache()`, and also from live synthesis when `cacheSynthesizedAudio` allows it. Only services that yield their audio from `runTts` (HTTP and streaming-RPC services, see `supportsAudioCache`) use it, and only in sentence aggregation mode. Defaults to null (no cache). pipedog only. |
| `cacheSynthesizedAudio` | `boolean \| ((text: string) => boolean) \| undefined` | no | Whether audio synthesized live is stored in `audioCache`, or a function that decides per text. Defaults to false: only warmed lines are stored, since a generated reply can repeat what the user said. pipedog only. |
| `audioCacheNamespace` | `string \| undefined` | no | Extra part of the cache key, for constructor options that change the audio but are not in `settings`. pipedog only. |

### Settings [#settings]

Runtime-updatable settings, passed as `settings: new OpenAITTSService.Settings({...})`
(`OpenAITTSSettings`). Any setting you leave out keeps the default below.

| Setting        | Type             | Default             | Description                                                                                                              |
| -------------- | ---------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `model`        | `string`         | `"gpt-4o-mini-tts"` | Speech model.                                                                                                            |
| `voice`        | `string`         | `"alloy"`           | One of `alloy`, `ash`, `ballad`, `cedar`, `coral`, `echo`, `fable`, `marin`, `nova`, `onyx`, `sage`, `shimmer`, `verse`. |
| `language`     | `null`           | `null`              | Not used by this service.                                                                                                |
| `instructions` | `string \| null` | `null`              | How the voice should speak (tone, pace, accent).                                                                         |
| `speed`        | `number \| null` | `null`              | Speed, 0.25 to 4.0. `null` leaves OpenAI's default (1.0).                                                                |

### Usage [#usage]

```ts title="tts.ts"
import { TTSUpdateSettingsFrame } from "@pipedog/core/frames/frames";
import { OpenAITTSService } from "@pipedog/openai/tts";

const tts = new OpenAITTSService({
  apiKey: process.env.OPENAI_API_KEY ?? "",
  sampleRate: 24000,
  settings: new OpenAITTSService.Settings({
    model: "gpt-4o-mini-tts",
    voice: "marin",
    instructions: "Speak in a calm, friendly tone.",
  }),
});
```

Change the voice or speed mid-call with a `TTSUpdateSettingsFrame`:

```ts
const update = new TTSUpdateSettingsFrame({
  delta: new OpenAITTSService.Settings({ voice: "cedar", speed: 1.2 }),
});
```

### Event handlers [#event-handlers]

| Event            | Description                              |
| ---------------- | ---------------------------------------- |
| `on_tts_request` | A synthesis request is about to be made. |

This comes from the `TTSService` base class.

### Notes [#notes]

* Requests `response_format: "pcm"` and emits `TTSAudioRawFrame`s (mono, `chunkSize` bytes each)
  between `TTSStartedFrame` and `TTSStoppedFrame`.
* OpenAI only returns 24 kHz audio. Set `sampleRate: 24000` (or a 24 kHz pipeline output rate);
  any other rate logs a warning, and the frames are still labelled with that rate.
* An unknown voice, or a request OpenAI rejects, produces an `ErrorFrame` instead of audio.
* `httpClient` replaces the SDK's `fetch`, for example to set a longer request timeout.

## Runtime notes [#runtime-notes]

| Runtime            | Works | What it needs |
| ------------------ | ----- | ------------- |
| Bun                | ✅ yes | Nothing.      |
| Node.js            | ✅ yes | Nothing.      |
| Deno               | ✅ yes | Nothing.      |
| Cloudflare Workers | ✅ yes | Nothing.      |

Generated from `pipecat.runtimes` and `pipecat.compat` in `packages/openai/package.json`: ✅ means the compat smoke test passes on that runtime.

* The client is the `openai` JS SDK over `fetch`. The audio is read from the response body
  stream, so it works on Bun, Node, Deno and Cloudflare Workers.
* `httpClient` takes a `fetch` function where upstream takes an httpx client.
* The deprecated `OpenAITTSService.InputParams` and the `voice`, `model`, `instructions`,
  `speed` and `params` constructor options are not ported. Use `settings`.
