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

# JavaScript

## 설치

프로젝트에 패키지를 설치하세요.

```shell theme={null}
npm install @vox-ai/client
# or
yarn add @vox-ai/client
# or
pnpm add @vox-ai/client
```

## 사용법

바닐라 JavaScript 프로젝트에서 바로 쓸 수 있고, 프레임워크별 라이브러리의 기반으로도 쓸 수 있습니다.
React를 쓴다면 [React](/docs/sdk/react)를, React Native를 쓴다면 [React Native](/docs/sdk/react-native)를 확인해 보세요.

### 세션 초기화

`Conversation.startSession(options)`으로 세션을 시작합니다.

```js theme={null}
import { Conversation } from "@vox-ai/client";

const conversation = await Conversation.startSession(options);
```

이 호출로 WebRTC 연결이 시작되고, 마이크를 통해 에이전트와 통화가 열립니다.
세션 시작 전에 UI에서 마이크 접근 권한을 안내하고 요청해 주세요.

```js theme={null}
// 마이크 권한이 필요한 이유를 UI에서 안내한 후 호출
await navigator.mediaDevices.getUserMedia({ audio: true });
```

#### 세션 설정

`startSession`에 전달하는 옵션으로 세션 방식을 설정합니다. Agent ID는 [vox.ai 대시보드](https://www.tryvox.co/dashboard/)에서 확인하세요.

```js theme={null}
const conversation = await Conversation.startSession({
  agentId: "<your-agent-id>",
  apiKey: "<your-api-key>",
});
```

| 옵션                 | 타입                                            | 필수 | 설명                                                               |
| ------------------ | --------------------------------------------- | -- | ---------------------------------------------------------------- |
| `agentId`          | `string`                                      | O  | Agent ID                                                         |
| `apiKey`           | `string`                                      | O  | API Key                                                          |
| `agentVersion`     | `string`                                      |    | 에이전트 버전 (`"current"`, `"production"`, `"v1"` 등). 기본값 `"current"` |
| `textOnly`         | `boolean`                                     |    | `true`면 마이크/오디오 없이 텍스트 전용으로 연결. 기본값 `false`                      |
| `dynamicVariables` | `Record<string, string \| number \| boolean>` |    | 에이전트 프롬프트에 주입할 [동적 변수](/docs/build/variables/dynamic-variables)  |
| `metadata`         | `Record<string, unknown>`                     |    | 콜 메타데이터 (웹훅, 통화 기록에 포함)                                          |

#### 콜백

`startSession` 옵션으로 콜백을 등록할 수 있습니다.

* **onConnect** — 세션이 연결되면 불립니다.
* **onDisconnect** — 연결이 끊기면 불립니다.
* **onMessage** — 메시지가 들어올 때 불립니다. 사용자 음성의 텍스트 변환이나 에이전트 응답이 여기로 옵니다.
* **onError** — 에러 발생 시 불립니다.
* **onStatusChange** — 연결 상태가 바뀔 때 불립니다. `"disconnected"`, `"connecting"`, `"connected"` 중 하나가 넘어옵니다.
* **onAgentStateChange** — 에이전트 상태가 `"initializing"`, `"idle"`, `"listening"`, `"thinking"`, `"speaking"` 중 하나로 바뀔 때 불립니다.

```js theme={null}
const conversation = await Conversation.startSession({
  agentId: "<your-agent-id>",
  apiKey: "<your-api-key>",
  onConnect: () => console.log("Connected"),
  onDisconnect: () => console.log("Disconnected"),
  onMessage: (message) => console.log(`${message.source}: ${message.text}`),
  onError: (error) => console.error("Error:", error),
  onStatusChange: (status) => console.log("Status:", status),
  onAgentStateChange: (agentState) => console.log("Agent state:", agentState),
});
```

#### 반환값

`startSession`은 세션을 제어할 수 있는 `Conversation` 인스턴스를 돌려줍니다. 마이크 권한이 거부되거나 연결이 실패하면 에러를 throw합니다.

### 메서드

#### endSession

세션을 종료합니다. 연결을 끊고 리소스를 정리합니다.
`Promise<void>`를 반환합니다.

```js theme={null}
await conversation.endSession();
```

#### getId

현재 세션 ID를 돌려줍니다. 세션 ID가 없으면 `undefined`를 반환합니다.

```js theme={null}
const id = conversation.getId();
```

#### getMessages

세션에서 주고받은 메시지를 timestamp 순으로 돌려줍니다.

```js theme={null}
const messages = conversation.getMessages();

messages.forEach((msg) => {
  console.log(msg.source, msg.text, msg.isFinal);
});
```

#### sendUserMessage

에이전트에게 텍스트 메시지를 보냅니다. 마이크 대신 텍스트로 입력할 때 쓰세요.
`Promise<void>`를 반환합니다.

```js theme={null}
sendButton.addEventListener("click", async () => {
  await conversation.sendUserMessage(textInput.value);
  textInput.value = "";
});
```

#### setVolume

에이전트 음성의 출력 볼륨을 조절합니다. 0\~1 사이 값을 넣으세요.

```js theme={null}
conversation.setVolume({ volume: 0.5 });
```

#### setMicMuted

마이크를 음소거하거나 해제합니다. `Promise<void>`를 반환합니다.

```js theme={null}
// 음소거
await conversation.setMicMuted(true);

// 해제
await conversation.setMicMuted(false);
```

#### getInputVolume / getOutputVolume

현재 입출력 볼륨을 0\~1 스케일로 돌려줍니다.

```js theme={null}
const inputVolume = conversation.getInputVolume();
const outputVolume = conversation.getOutputVolume();
```

#### getInputByteFrequencyData / getOutputByteFrequencyData

입출력 주파수 데이터를 `Uint8Array`로 돌려줍니다. 오디오 시각화에 쓸 수 있습니다.

```js theme={null}
const inputFrequency = conversation.getInputByteFrequencyData();
const outputFrequency = conversation.getOutputByteFrequencyData();
```

<Note>
  오디오 모니터링 메서드는 음성 세션에서만 동작합니다.
</Note>

#### changeInputDevice

세션 중에 오디오 입력 디바이스를 바꿉니다.
전환 성공 여부를 담은 `Promise<boolean>`을 반환합니다.

```js theme={null}
const changed = await conversation.changeInputDevice({
  inputDeviceId: "your-device-id",
});
```

#### changeOutputDevice

세션 중에 오디오 출력 디바이스를 바꿉니다.
전환 성공 여부를 담은 `Promise<boolean>`을 반환합니다.

```js theme={null}
const changed = await conversation.changeOutputDevice({
  outputDeviceId: "your-device-id",
});
```

<Note>
  디바이스 전환은 음성 세션에서만 동작합니다. `deviceId`를 지정하지 않으면 브라우저 기본 디바이스가 쓰입니다.
  사용 가능한 디바이스 목록은 [MediaDevices.enumerateDevices()](https://developer.mozilla.org/docs/Web/API/MediaDevices/enumerateDevices) API로 조회하세요.
</Note>

### 상태 조회

```js theme={null}
const status = conversation.getStatus(); // "disconnected" | "connecting" | "connected"
const agentState = conversation.getAgentState();
// "initializing" | "idle" | "listening" | "thinking" | "speaking" | undefined
const muted = conversation.getMicMuted(); // boolean
```

`agentState`는 `"initializing"`, `"idle"`, `"listening"`, `"thinking"`, `"speaking"` 중 하나이거나 아직 수신 전에는 `undefined`입니다. `isSpeaking` 같은 화면 상태가 필요하면 `agentState === "speaking"`으로 계산하세요.

### Text Only 모드

마이크 없이 텍스트만으로 에이전트와 대화할 수 있습니다.

```js theme={null}
const conversation = await Conversation.startSession({
  agentId: "<your-agent-id>",
  apiKey: "<your-api-key>",
  textOnly: true,
  onMessage: (msg) => console.log(`${msg.source}: ${msg.text}`),
});

await conversation.sendUserMessage("안녕하세요");
```

* Text Only 세션은 마이크 권한을 요청하지 않습니다.
* 오디오 관련 API(`getInputVolume` 등)는 zero-value를 돌려줍니다.

### Dynamic Variables와 Metadata

```js theme={null}
const conversation = await Conversation.startSession({
  agentId: "<your-agent-id>",
  apiKey: "<your-api-key>",
  dynamicVariables: {
    userName: "홍길동",
    userType: "premium",
    accountBalance: 50000,
  },
  metadata: {
    sessionId: "sess_abc123",
    source: "web-app",
  },
});
```

* `dynamicVariables` — 에이전트 프롬프트에서 `{{userName}}` 형식으로 참조됩니다. [동적 변수](/docs/build/variables/dynamic-variables)에서 자세히 알아보세요.
* `metadata` — 웹훅과 통화 기록에 포함됩니다.

***

<Accordion title="연관 검색어">
  JavaScript SDK, JS SDK, @vox-ai/client, 웹 연동, web integration, startSession, 바닐라 자바스크립트
</Accordion>
