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

# JavaScript / TypeScript SDK

> Connect to Vatel voice agents from JavaScript or TypeScript. Run real-time voice sessions and access the API in Node.js or the browser.

Use **@vatel/sdk** to connect to Vatel voice agents from JavaScript or TypeScript. The SDK provides a REST client and a WebSocket session for real-time voice: send audio, receive events, and handle tool calls. It works in Node.js and the browser.

<Card title="Session token" icon="key" href="/api-reference/session/session-token">
  REST endpoint used to obtain a short-lived JWT for the WebSocket connection.
</Card>

<Card title="Connection" icon="radio" href="/api-reference/session/connection">
  WebSocket channel, message types, and request/response flow.
</Card>

## Prerequisites

* **Node.js** 18+ or a modern **browser**
* **API key** (organization API key from the Vatel dashboard)
* **Agent ID** for the agent you want to connect to
* In **Node.js** only: a WebSocket implementation (`ws` package)

## Walkthrough

<Steps>
  <Step title="Install the SDK">
    Install the package:

    ```bash theme={null}
    npm install @vatel/sdk
    ```

    In **Node.js**, also install a WebSocket implementation (browsers have one built in):

    ```bash theme={null}
    npm install ws
    ```
  </Step>

  <Step title="Get a session token">
    Create a `Client` with your API key and call `generateSessionToken` with your agent ID. The token is a short-lived JWT used to open the WebSocket session.

    ```js theme={null}
    import { Client } from "@vatel/sdk";

    const client = new Client({
      getToken: () => process.env.VATEL_API_KEY,
    });

    const { data } = await client.generateSessionToken("your-agent-id");
    if (!data?.token) throw new Error("Failed to get token");
    ```

    In the browser, call your backend to get the token (never expose the API key in client code).
  </Step>

  <Step title="Connect a session and listen for events">
    Create a `Session` with the token, register event handlers, then call `connect()`.

    ```js theme={null}
    import { Session } from "@vatel/sdk";

    const session = new Session({ token: data.token });

    session.on("session_started", () => console.log("Connected"));
    session.on("response_text", (msg) => console.log("Agent:", msg.data.text));
    session.on("response_audio", (msg) => {
      // msg.data.audio is base64-encoded PCM (24 kHz, mono, 16-bit)
      // Decode and play with your audio stack
    });
    session.on("input_audio_transcript", (msg) => console.log("You said:", msg.data.transcript));

    await session.connect();
    ```
  </Step>

  <Step title="Send audio">
    Send microphone (or other) audio as base64-encoded PCM chunks (24 kHz, mono, 16-bit):

    ```js theme={null}
    session.sendInputAudio(base64PcmChunk);
    ```

    Use your preferred audio capture and encoding; the SDK does not capture the microphone for you.
  </Step>
</Steps>

## Node.js: WebSocket setup

Node does not include a WebSocket API. Install `ws` and pass a WebSocket factory when creating the session:

```js theme={null}
import { Session } from "@vatel/sdk";
import WebSocket from "ws";

const session = new Session({
  token: data.token,
  createWebSocket: (url) => new WebSocket(url),
});
await session.connect();
```

## Session options

| Option            | Description                                                                                                    |
| ----------------- | -------------------------------------------------------------------------------------------------------------- |
| `token`           | **Required.** JWT from `client.generateSessionToken(agentId)`.                                                 |
| `baseUrl`         | API base URL. Default: `https://api.vatel.ai`. Use `https://…` or `wss://…`; the SDK picks the right protocol. |
| `createWebSocket` | **Node only.** Function that takes a URL and returns a WebSocket instance. Use with the `ws` package.          |

## REST client

The `Client` uses your organization API key as a Bearer token and exposes the REST API. See the [API reference](/api-reference) for all endpoints. Example:

```js theme={null}
import { Client } from "@vatel/sdk";

const client = new Client({
  getToken: () => process.env.VATEL_API_KEY,
});

const { data: tokenData } = await client.generateSessionToken("agent-id");
// Other endpoints available on the client
```

## Tool calls

When the agent invokes a tool, handle the `tool_call` event and send the result back with `sendToolCallOutput`:

```js theme={null}
session.on("tool_call", async (msg) => {
  const { toolCallId, toolName, arguments: args } = msg.data;
  const result = await yourToolHandler(toolName, args);
  session.sendToolCallOutput(toolCallId, JSON.stringify(result));
});
```

## TypeScript

The package includes type definitions. No extra `@types` install; import types when needed:

```ts theme={null}
import type { ResponseAudioMessage, SessionStartedMessage } from "@vatel/sdk";
```
