> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pipecat.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Client Methods

> PipecatClient methods for starting bots, managing sessions, sending messages, and controlling devices in the JavaScript SDK.

The Pipecat JavaScript client provides a comprehensive set of methods for managing bot interactions and media handling. These core methods are documented below.

## Session Connectivity

### startBot()

`async startBot(startBotParams: APIRequest): Promise<unknown>`

This method hits your server endpoint to start the bot and optionally obtain the connection parameters needed for `connect()` to connect the `Transport`. It returns a Promise that resolves with the response from the server.

**startBotParams** `APIRequest` *required*

The `APIRequest` object should have the following shape:

**APIRequest**

**endpoint** `string | URL | Request` *required*

The endpoint to call. A URL string or `URL`, or a `Request` object when
you need full control over the request. When it is a `Request`,
`headers` and `requestData` are ignored.

**headers** `Headers`

Optional headers to include in the request to the endpoint. This can be used to pass authentication tokens or other necessary headers.

**requestData** `object`

Optional request data to include in the request to the endpoint. This can be used to pass additional data to your server-side endpoint. Oftentimes, this is used to pass the initial prompt or other configuration data to initialize the bot.

**timeout** `number`

Optional timeout in milliseconds for the request to the endpoint.

During the `startBot()` process, the transport state will transition through the states: "authenticating" and "authenticated".

```javascript theme={null}
try {
  await pcClient.startBot({
    endpoint: "/api/start", // Your server endpoint to start the bot
    requestData: {
      initial_prompt: "You are a pirate captain",
      llm_provider: "openai",
    },
  });
} catch (error) {
  console.error("Error starting the bot:", error);
}
```

### connect()

`async connect(connectParams?: TransportConnectionParams | ConnectionEndpoint): Promise<BotReadyData>`

This method initiates the connection process, optionally passing parameters that your transport class requires to establish a connection or an endpoint to your server for obtaining those parameters.

**connectParams** `TransportConnectionParams`

An object containing the `TransportConnectionParams` your Transport expects.

Check your transport class documentation for the expected shape of `TransportConnectionParams`. For example, the DailyTransport expects a `url` and `token`.

*Deprecated since 1.2.0:* passing a `ConnectionEndpoint` (an `APIRequest`) to `connect()`. Use `startBotAndConnect()` instead, or `startBot()` and pass its response to `connect()`.

This method can be try / catched to handle errors at startup:

```typescript theme={null}
try {
  await pcClient.connect({
    webrtcRequestParams: { endpoint: "http://my-server/api/offer" },
  });
} catch (error) {
  console.error("Error connecting to the bot:", error);
}
```

During the connection process, the transport state will transition through the following states: "connecting", "connected", "ready".

> [!NOTE]
>
> Calling `connect()` asynchronously will resolve when the bot and client signal
> that they are ready. If you want to call `connect()` without `await`, you can
> use the `onBotReady` callback or `BotReady` event to know when you can
> interact with the bot.

> [!WARNING]
>
> Calling `connect()`, `startBot()`, or `startBotAndConnect()` while the
> transport is 'authenticating', 'connecting', 'connected', or 'ready' throws a
> `BotAlreadyStartedError`. [Disconnect](#disconnect) from the session before
> connecting again.

### startBotAndConnect()

`async startBotAndConnect(startBotParams: APIRequest): Promise<BotReadyData>`

This method combines the functionality of `startBot()` and `connect()`. It first starts the bot by hitting your server endpoint and then connects the transport passing the response from the endpoint to the transport as connection parameters.

```javascript theme={null}
try {
  await pcClient.startBotAndConnect({
    endpoint: "/api/start", // Your server endpoint to start the bot
    requestData: {
      initial_prompt: "You are a pirate captain",
      llm_provider: "openai",
    },
  });
} catch (error) {
  console.error("Error starting up:", error);
}
```

It's equivalent to: `pcClient.startBot(...).then((resp) => pcClient.connect(resp))`.

### disconnect()

`async disconnect(): Promise<void>`

Disconnects from the active session. The transport state will transition to "disconnecting" and then "disconnected".

It is common practice for bots to exit and cleanup when the client disconnects.

```typescript theme={null}
await pcClient.disconnect();
```

### disconnectBot()

`disconnectBot(): void`

Triggers the bot to disconnect from the session, leaving the client connected.

```typescript theme={null}
pcClient.disconnectBot();
```

## Messages

Custom messaging between the client and the bot. This is useful for sending data to the bot, triggering specific actions, reacting to server events, or querying the server.

For more, see the [Custom Messaging](https://docs.pipecat.ai/client/guides/custom-messaging.md) guide.

### sendClientMessage()

`sendClientMessage(msgType: string, data?: unknown): void`

Sends a custom message to the bot and does not expect a response. This is useful for sending data to the bot or triggering specific actions.

**msgType** `string` *required*

A string identifying the message.

**data** `unknown`

Optional data to send with the message. This can be any JSON-serializable
object.

### sendClientRequest()

`async sendClientRequest(msgType: string, data: unknown, timeout?: number): Promise<unknown>`

Sends a custom request to the bot and expects a response. This is useful for querying the server or triggering specific actions that require a response. The method returns a Promise that resolves with the data from response. If the client disconnects before a response arrives, the Promise rejects with an RTVIMessage of type `'error-response'`.

**msgType** `string` *required*

A string identifying the message.

**data** `unknown` *required*

Data to send with the message. This can be any JSON-serializable value; pass
`undefined` when there is none.

**timeout** `number` (default: 10000)

Optional timeout in milliseconds for the request. If the request does not
receive a response within this time, it will reject with an RTVIMessage of
type `'error-response'`.

## Devices

### initDevices()

`async initDevices(): Promise<void>`

Initializes the media device selection machinery, based on `enableCam`/`enableMic` selections and defaults (i.e. turns on the local cam/mic). This method can be called before `connect()` to test and switch between camera and microphone sources.

```typescript theme={null}
await pcClient.initDevices();
```

It drives [`mediaState`](#mediastate): both devices move to `initializing` on entry, then to `granted` for each device the transport reports as acquired. A device that isn't acquired falls back to `uninitialized`. On failure the underlying error classifies the affected devices and is re-thrown, so callers still see it.

> [!NOTE]
>
> Calling `initDevices()` again after a failure is the recovery path: a second
> call re-enters `initializing` and reclassifies. There is no separate retry
> method.

### getAllMics()

`async getAllMics(): Promise<MediaDeviceInfo[]>`

Returns a list of available microphones in the form of [`MediaDeviceInfo[]`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo).

```typescript theme={null}
const mics = await pcClient.getAllMics();
```

### getAllCams()

`async getAllCams(): Promise<MediaDeviceInfo[]>`

Returns a list of available cameras in the form of [`MediaDeviceInfo[]`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo).

```typescript theme={null}
const cams = await pcClient.getAllCams();
```

### getAllSpeakers()

`async getAllSpeakers(): Promise<MediaDeviceInfo[]>`

Returns a list of available speakers in the form of [`MediaDeviceInfo[]`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo).

```typescript theme={null}
const speakers = await pcClient.getAllSpeakers();
```

### selectedMic

`selectedMic: MediaDeviceInfo | Record<string, never>`

The currently selected microphone, represented as a `MediaDeviceInfo` object. If no microphone is selected, it returns an empty object.

```typescript theme={null}
const currentMic = pcClient.selectedMic;
```

### selectedCam

`selectedCam: MediaDeviceInfo | Record<string, never>`

The currently selected camera, represented as a `MediaDeviceInfo` object. If no camera is selected, it returns an empty object.

```typescript theme={null}
const currentCam = pcClient.selectedCam;
```

### selectedSpeaker

`selectedSpeaker: MediaDeviceInfo | Record<string, never>`

The currently selected speaker, represented as a `MediaDeviceInfo` object. If no speaker is selected, it returns an empty object.

```typescript theme={null}
const currentSpeaker = pcClient.selectedSpeaker;
```

### updateMic()

`updateMic(micId: string): void`

Switches to the microphone identified by the provided `micId`, which should match a `deviceId` in the list returned from [`getAllMics()`](#getallmics).

**micId** `string`

deviceId

```typescript theme={null}
pcClient.updateMic(deviceId);
```

### updateCam()

`updateCam(camId: string): void`

Switches to the camera identified by the provided `camId`, which should match a `deviceId` in the list returned from [`getAllCams()`](#getallcams).

**camId** `string`

deviceId

```typescript theme={null}
pcClient.updateCam(deviceId);
```

### updateSpeaker()

`updateSpeaker(speakerId: string): void`

Switches to the speaker identified by the provided `speakerId`, which should match a `deviceId` in the list returned from [`getAllSpeakers()`](#getallspeakers).

**speakerId** `string`

deviceId

```typescript theme={null}
pcClient.updateSpeaker(deviceId);
```

### enableMic(enable: boolean)

`enableMic(enable: boolean): void`

Turn on or off (unmute or mute) the client mic input.

**enable** `boolean` *required*

A boolean indicating whether to enable (`true`) or disable (`false`) the
microphone.

```typescript theme={null}
pcClient.enableMic(true);
```

### enableCam(enable: boolean)

`enableCam(enable: boolean): void`

Turn on or off the client cam input.

**enable** `boolean` *required*

A boolean indicating whether to enable (`true`) or disable (`false`) the
camera.

```typescript theme={null}
pcClient.enableCam(true);
```

### enableScreenShare(enable: boolean)

`enableScreenShare(enable: boolean): void`

Start a screen share from the client's device.

**enable** `boolean` *required*

A boolean indicating whether to enable (`true`) or disable (`false`) screen
sharing.

```typescript theme={null}
pcClient.enableScreenShare(true);
```

### isMicEnabled

`isMicEnabled: boolean`

An accessor to determine if the client's microphone is enabled.

```typescript theme={null}
const micEnabled = pcClient.isMicEnabled;
```

### isCamEnabled

`isCamEnabled: boolean`

An accessor to determine if the client's camera is enabled.

```typescript theme={null}
const camEnabled = pcClient.isCamEnabled;
```

### isSharingScreen

`isSharingScreen: boolean`

An accessor to determine if the client is sharing their screen.

```typescript theme={null}
const sharingScreen = pcClient.isSharingScreen;
```

### mediaState

`get mediaState(): MediaState`

Per-device state for the mic and cam, independent of the transport's connection state. Use it to render permission UI: whether to show a "grant access" prompt, an error, or the device picker.

```typescript theme={null}
const { mic, cam } = pcClient.mediaState;

if (mic.state === "error" && mic.reason === "blocked") {
  // the user denied microphone permission
}
```

Returns a snapshot. To track changes, subscribe to `RTVIEvent.MediaStateUpdated` or pass an [`onMediaStateChanged`](https://docs.pipecat.ai/api-reference/client/js/callbacks) callback to the constructor. In React, use [`useMediaState`](https://docs.pipecat.ai/api-reference/client/react/hooks#usemediastate).

**MediaState**

**mic** `DeviceStatus`

Status of the microphone.

**cam** `DeviceStatus`

Status of the camera.

A `DeviceStatus` is `{ state }`, plus `reason` and optional `details` when `state` is `"error"`:

| `state` | Meaning |
| - | - |
| `uninitialized` | `initDevices()` hasn't run for this device |
| `initializing` | Enumeration or a permission request is in flight |
| `granted` | Enumerated and ready to use |
| `error` | Could not be acquired; see `reason` |

| `reason` | Meaning |
| - | - |
| `blocked` | The user denied permission |
| `already-in-use` | The hardware is busy in another application |
| `not-found` | No matching hardware |
| `invalid-constraints` | The requested constraints couldn't be satisfied |
| `not-supported` | Browser API unavailable: a legacy browser, or an insecure context |
| `unknown` | Couldn't be classified |

> [!NOTE]
>
> Speakers aren't tracked here. Output devices have no permission or in-use
> failure mode, only enumeration, so `getAllSpeakers()` and `updateSpeaker()`
> are the whole story for them.

### mediaSupport

`get mediaSupport(): MediaSupport`

Whether each kind of media can flow in this session, combining what the transport supports with the bot's capabilities. Before `bot-ready` it reflects only the transport. Use it to hide controls for media that can't be used.

```typescript theme={null}
const { cam, screenShare } = pcClient.mediaSupport;

if (cam === false) {
  // hide the camera toggle
}
```

Returns a snapshot. To track changes, subscribe to `RTVIEvent.MediaSupportUpdated` or pass an [`onMediaSupportChanged`](https://docs.pipecat.ai/api-reference/client/js/callbacks) callback to the constructor. In React, use [`useMediaSupport`](https://docs.pipecat.ai/api-reference/client/react/hooks#usemediasupport).

**MediaSupport**

**mic** `boolean`

The user's microphone audio to the bot.

**cam** `boolean`

The user's camera video to the bot.

**screenShare** `boolean`

The user's screen share to the bot.

**botAudio** `boolean`

The bot's audio to the user.

**botVideo** `boolean`

The bot's video to the user.

`false` means the transport or the bot rules that media out. `true` means both support it. `undefined` means it isn't ruled out, so show the matching UI.

### botCapabilities

`get botCapabilities(): BotCapabilities | undefined`

What the bot does in this session, from its `bot-ready` message. It is `undefined` before `bot-ready`, after disconnecting, and for bots that don't send capabilities (RTVI protocol older than 2.2.0). In React, use [`useBotCapabilities`](https://docs.pipecat.ai/api-reference/client/react/hooks#usebotcapabilities).

**BotCapabilities**

**audio\_in** `boolean`

Whether the bot receives the user's audio.

**audio\_out** `boolean`

Whether the bot sends audio to the user.

**video\_in** `boolean`

Whether the bot receives the user's video.

**screen\_in** `boolean`

Whether the bot receives the user's screen share. Left out when the bot
captures its video sources itself.

**video\_out** `boolean`

Whether the bot sends video to the user.

**metrics** `boolean`

Whether the bot reports metrics.

A missing field means the bot can't tell, and `false` means the bot doesn't do it.

### needsInit()

`needsInit(): boolean`

Whether `initDevices()` still has work to do: `true` while any device you opted into with `enableMic` / `enableCam` is still `uninitialized`. Devices you opted out of stay `uninitialized` by design and don't count.

`connect()` and `startBot()` use this internally to decide whether to run an implicit `initDevices()`; it's public so your own code can branch on the same rule.

## Tracks (Audio and Video)

### tracks()

`tracks(): Tracks`

Returns a `Tracks` object with available `MediaStreamTrack` objects for both the client and the bot.

```typescript theme={null}
const tracks = pcClient.tracks();
```

**Tracks Type**

```typescript theme={null}
{
  local: {
    audio?: MediaStreamTrack;
    video?: MediaStreamTrack;
    screenAudio?: MediaStreamTrack;
    screenVideo?: MediaStreamTrack;
  },
  bot?: {
    audio?: MediaStreamTrack;
    video?: MediaStreamTrack;
  }
}
```

## Advanced LLM Interactions

### sendText()

`async sendText(content: string, options?: SendTextOptions = {}): Promise<string>`

A method to append text to the user's context. This is useful for providing text input as an alternative to audio input for the user.

Returns the ID of the send-text message. A bot on RTVI 2.2.0 or later with user input turned on acknowledges the text with a `user-input` message of type `chat` that carries this ID as `msg_id` (see [`onUserInput`](https://docs.pipecat.ai/api-reference/client/js/callbacks#transcription)).

**content** `string` *required*

The text content to send to the bot.

**options** `SendTextOptions`

An optional set of options for how the bot should handle the text input.

**SendTextOptions**

**run\_immediately** `boolean` (default: true)

Whether to immediately run the bot with the updated context. If `false`,
the context will be updated but the bot will not be run until the next
message or action that triggers the bot to run (like the user speaking).

**audio\_response** `boolean` (default: true)

Whether the bot should respond with audio. If `true`, the bot's response
will be processed by TTS and be spoken. If `false`, the bot will bypass
the TTS and respond with text only.

### sendFile()

`async sendFile(file: RTVIFile | File, content: string, options?: SendFileOptions = {}): Promise<void>`

Sends a file to the bot along with accompanying text, and appends both to the user's context. Files too large to send inline are uploaded to the endpoint advertised in the `startBot()` response, or to the [`fileUploadEndpoint`](https://docs.pipecat.ai/api-reference/client/js/client-constructor#file-uploads) client option, and sent by URL.

**file** `RTVIFile | File` *required*

The file to send. Pass a browser `File`, or an `RTVIFile` object.

**RTVIFile**

**name** `string`

The file name.

**format** `string` *required*

The file's MIME type, or a shorthand such as `"png"`, `"pdf"`, or `"mp3"`
that is mapped to its MIME type.

**source** `FileBytes | FileUrl` *required*

Either `{ type: "bytes", bytes: string }` with base64-encoded data, or `{
            type: "url", url: string | URL }`.

**content** `string` *required*

The text to send with the file.

**options** `SendFileOptions`

**SendFileOptions**

**run\_immediately** `boolean`

Whether to immediately run the bot with the updated context.

**audio\_response** `boolean`

Whether the bot should respond with audio.

**custom\_options** `Record\<string | number, Serializable\>`

Provider-specific options passed through with the file.

```typescript theme={null}
await pcClient.sendFile(fileInput.files[0], "What is in this image?");
```

> [!NOTE]
>
> `sendFile()` requires a bot on RTVI protocol 2.2.0 or later; calling it
> against an older bot raises an `UnsupportedFeatureError`.

### sendDTMF()

`sendDTMF(dtmf: DTMFButton | string): void`

Sends DTMF keypresses to the bot: the digits a caller would press on a phone keypad, for navigating an IVR or entering an account number.

**dtmf** `DTMFButton | string` *required*

A single key or a sequence of them, e.g. `"5"` or `"123#"`. Only `0`–`9`, `*`
and `#` are valid; anything else raises an `RTVIError` before a message is
sent.

```typescript theme={null}
pcClient.sendDTMF("1"); // one key
pcClient.sendDTMF("4085551234#"); // a sequence, in order
```

> [!NOTE]
>
> DTMF requires a bot on RTVI protocol 2.0.0 or later; calling it against an
> older bot raises an `UnsupportedFeatureError`. A sequence reaches a 2.1.0+ bot
> as a single message, and a 2.0.x bot as one message per key; the client
> handles the difference.

### registerFunctionCallHandler()

`registerFunctionCallHandler(functionName: string, callback: FunctionCallCallback): void`

Registers a function call handler that will be called when the bot requests a function call. This is useful for when the server-side function handler needs information from the client to execute the function call or when the client needs to perform some action based on the running of function call.

**functionName** `string` *required*

The name of the function to handle. This should match the function name in the bot's context.

**callback** `FunctionCallCallback` *required*

`type FunctionCallCallback = (fn: FunctionCallParams) => Promise<LLMFunctionCallResult | void>`

The callback function to call when the bot sends a function call request. This function should accept the following parameters:

**FunctionCallParams**

**functionName** `string` *required*

The name of the function being called. It should always match the name you
registered the handler under.

**arguments** `Record\<string, unknown\>` *required*

The arguments passed to the function call. This is a key-value object where
the keys are the argument names and the values are the argument values.

The callback should return a Promise that resolves with the result of the function call or void if no result is needed. If returning a result, it should be a `string` or `Record<string, unknown>`.

### unregisterFunctionCallHandler()

`unregisterFunctionCallHandler(functionName: string): void`

Removes the handler registered for `functionName`.

**functionName** `string` *required*

The name the handler was registered under.

### unregisterAllFunctionCallHandlers()

`unregisterAllFunctionCallHandlers(): void`

Removes every registered function call handler.

## Other

### transport

`transport: Transport`

A safe accessor for the transport instance used by the client. This is useful for accessing transport-specific methods or properties that are not exposed directly on the client. Calling `initDevices()`, `connect()`, or `disconnect()` through it throws an `Error`; use the client's methods instead.

```typescript theme={null}
const transport = pcClient.transport as DailyTransport;
transport.getSessionInfo();
```

### connected

`connected: boolean`

`true` while the transport state is `connected` or `ready`.

### state

`state: TransportState`

The current [transport state](https://docs.pipecat.ai/api-reference/client/js/transports/transport.md#transport-states).

### version

`version: string`

The version of the `@pipecat-ai/client-js` package.

### setLogLevel()

`setLogLevel(level: LogLevel): void`

Sets the log level for the client. This is useful for debugging and controlling the verbosity of logs. The log levels are defined in the `LogLevel` enum:

```typescript theme={null}
export enum LogLevel {
  NONE = 0,
  ERROR = 1,
  WARN = 2,
  INFO = 3,
  DEBUG = 4,
}
```

By default, the log level is set to `LogLevel.DEBUG`.

```typescript theme={null}
pcClient.setLogLevel(LogLevel.INFO);
```

## User Interface

These methods voice-enable a UI: the client streams the screen to a server-side [`UIWorker`](https://docs.pipecat.ai/api-reference/server/workers/ui-worker) and forwards UI events, while the bot drives the page with commands (handled via the [`UICommand` event](https://docs.pipecat.ai/api-reference/client/js/callbacks#user-interface-events)). See [the RTVI standard](https://docs.pipecat.ai/api-reference/standards/rtvi-standard.md#user-interface) for the wire payloads and [Controlling the UI](https://docs.pipecat.ai/pipecat/learn/ui-worker.md) for the patterns.

### startUISnapshotStream()

`startUISnapshotStream(options?: A11ySnapshotStreamerOptions): void`

Streams accessibility snapshots of the page to the bot as `ui-snapshot` messages. Emits an initial snapshot, then re-emits on DOM, form-control, focus, scroll, resize, and visibility changes, coalesced by `debounceMs`. Calling it again replaces the existing stream.

**options** `A11ySnapshotStreamerOptions`

**A11ySnapshotStreamerOptions**

**debounceMs** `number` (default: 300)

Coalesce window before emitting a snapshot.

**trackViewport** `boolean` (default: true)

Tag off-screen nodes `offscreen` so the bot scrolls before acting on them.

**logSnapshots** `boolean` (default: false)

Log each emitted snapshot to the console.

### stopUISnapshotStream()

`stopUISnapshotStream(): void`

Stops the managed snapshot stream and tears down its observers. Idempotent.

### A11ySnapshotStreamer

`new A11ySnapshotStreamer(emitSnapshot: A11ySnapshotEmitter, options?: A11ySnapshotStreamerOptions)`

The class behind `startUISnapshotStream()`, for streaming snapshots somewhere other than the bot. It calls `emitSnapshot(snapshot: A11ySnapshot)` on the same triggers and takes the same options. `start()` begins streaming and `stop()` detaches its observers; both are safe to call more than once.

### sendUIEvent()

`sendUIEvent(event: string, payload?: unknown): void`

Sends an app-defined UI event to the bot (routed to the worker's `@ui_event` handlers).

**event** `string` *required*

App-defined event name (e.g. `"note_click"`).

**payload** `unknown`

Optional schemaless payload.

### cancelUIJobGroup()

`cancelUIJobGroup(jobId: string, reason?: string): void`

Asks the bot to cancel an in-flight job group (only honored for groups the server marked `cancellable`). The `jobId` comes from the `group_started` envelope on the [`UIJobGroup` event](https://docs.pipecat.ai/api-reference/client/js/callbacks#user-interface-events).

**jobId** `string` *required*

The job group id.

**reason** `string`

Optional human-readable reason.

> [!NOTE]
>
> To act on the bot's commands, resolve its snapshot refs against the live DOM
> with the exported helpers `findElementByRef(ref)`, `findRefForElement(el)`,
> `snapshotDocument(root?, options?)`, and `serializeSelection()`.

## Transport Compatibility


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.