# Agent API

Source: https://docs.autessa.com/docs/api/agents

> Complete API reference for executing agents, managing conversations, and handling multimodal interactions.

# Agent API

The Agent API allows you to create and manage conversations with AI agents, execute them with text or audio input, and receive real-time streaming responses.
> All Agent API requests require the `resourceId` query parameter set to your agent ID and an `Authorization` header with your API key.

---

## Base URL

```
REST API:   https://api.autessa.com/clients/agents
WebSocket:  wss://api.autessa.com/ws/clients/agents/execute
```

---

## Authentication

### HTTP REST APIs
Pass your API key in the `Authorization` header (no "Bearer" prefix):

```
Authorization: your_api_key_here
```

### WebSocket APIs
Pass your API key as a query parameter:

```
authorization=your_api_key_here
```

**REST:**

```bash
curl https://api.autessa.com/clients/agents/execute-create?resourceId=V1StGXR8Z5 \
  -H "Authorization: your_api_key" \
  -H "Content-Type: application/json"
```

**WebSocket:**

```bash
websocat "wss://api.autessa.com/ws/clients/agents/execute?authorization=your_api_key&resourceId=V1StGXR8Z5"
```

---

## REST API Endpoints

## Create Conversation **POST** `/execute-create`

Creates a new conversation for multi-turn agent interactions. A conversation maintains context across multiple agent executions. You only need to create a conversation if you want multi-turn interactions - single-shot requests don't require conversations.

**Note:** Once created, a conversation is tied to a specific agent version. Even if you publish a new version, existing conversations will continue using the original version.

### Query Parameters

- `resourceId` (string, required) — The ID of the agent (e.g. `V1StGXR8Z5`).

### Request Body

- `agentId` (string, required) — The ID of the agent to create a conversation for.
- `version` (CustomVersion) — Optional version override. If not specified, uses the PUBLISHED version.

### Response

- `conversationId` (string) — The unique ID for the created conversation. Use this in subsequent execute requests.
- `errors` — "> Array of error messages if any occurred.
  
  
  
  

**cURL:**

```bash
  curl --request POST \
    --url 'https://api.autessa.com/clients/agents/execute-create?resourceId=V1StGXR8Z5' \
    --header 'Content-Type: application/json' \
    --header 'Authorization: your_api_key' \
    --data '{
      "agentId": "V1StGXR8Z5"
    }'
```

**JavaScript:**

```javascript
const response = await fetch(
'https://api.autessa.com/clients/agents/execute-create?resourceId=V1StGXR8Z5',
{
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'your_api_key'
  },
  body: JSON.stringify({
    agentId: 'V1StGXR8Z5'
  })
}
);

const data = await response.json();
console.log(data.conversationId);
```

```json title="JSON"
{
  "conversationId": "conv_a1b2c3d4e5",
  "errors": []
}
```
  

---

## Execute Agent **POST** `/execute`

Executes an agent synchronously with multimodal input (text or audio). This endpoint returns the complete response once processing is done.

**Note:** Synchronous execution only supports TEXT output. For AUDIO output or real-time streaming, use the WebSocket endpoint.

### Query Parameters

- `resourceId` (string, required) — The ID of the agent (e.g. `V1StGXR8Z5`).

### Request Body

- `agentId` (string, required) — The ID of the agent to execute.
- `conversationId` (string) — The conversation ID from `/execute-create`. Required for multi-turn conversations.
- `input` — " required> Array of multimodal inputs. See [Multimodal Input](#multimodal-input).
  - `environmentVariables` (object) — Key-value pairs for environment variables that won't be stored on the server.
  - `promptTemplateVariables` (object) — Key-value pairs to inject into the agent's prompt template. Variables are referenced in the agent instructions using `@@{variableName}@@` syntax.
  - `version` (CustomVersion) — Version override. Ignored if using an existing conversationId.
  

  ### Response

  
  - `output` — "> Array of output responses from the agent.
    - `errors` — "> Array of error messages if any occurred.
    
  
  
  

**cURL:**

```bash
  curl --request POST \
    --url 'https://api.autessa.com/clients/agents/execute?resourceId=V1StGXR8Z5' \
    --header 'Content-Type: application/json' \
    --header 'Authorization: your_api_key' \
    --data '{
      "agentId": "V1StGXR8Z5",
      "conversationId": "conv_a1b2c3d4e5",
      "input": [
        {
          "inputType": "TEXT",
          "content": "What is the weather today?"
        }
      ],
      "environmentVariables": {
        "USER_LOCATION": "Seattle"
      },
      "promptTemplateVariables": {
        "customerName": "John Doe",
        "accountType": "Premium"
      }
    }'
```

**JavaScript:**

```javascript
const response = await fetch(
'https://api.autessa.com/clients/agents/execute?resourceId=V1StGXR8Z5',
{
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'your_api_key'
  },
  body: JSON.stringify({
    agentId: 'V1StGXR8Z5',
    conversationId: 'conv_a1b2c3d4e5',
    input: [
      {
        inputType: 'TEXT',
        content: 'What is the weather today?'
      }
    ],
    environmentVariables: {
      USER_LOCATION: 'Seattle'
    },
    promptTemplateVariables: {
      customerName: 'John Doe',
      accountType: 'Premium'
    }
  })
}
);

const data = await response.json();
```

```json title="JSON"
{
  "output": [
    {
      "outputType": "TEXT",
      "content": "The weather in Seattle today is 65°F with partly cloudy skies."
    }
  ],
  "errors": []
}
```
  

---

## Close Conversation **POST** `/execute-close`

Closes an existing conversation. This triggers logging and any configured auto-evaluation for the conversation. It's safe to call this even for expired conversations.

**Important:** Conversations automatically close after 12 hours of inactivity, but it's best practice to explicitly close them when done.

### Query Parameters

- `resourceId` (string, required) — The ID of the agent (e.g. `V1StGXR8Z5`).

### Request Body

- `agentId` (string, required) — The ID of the agent.
- `conversationId` (string, required) — The conversation ID to close.

### Response

- `errors` — "> Array of error messages if any occurred.
  
  
  
  

**cURL:**

```bash
  curl --request POST \
    --url 'https://api.autessa.com/clients/agents/execute-close?resourceId=V1StGXR8Z5' \
    --header 'Content-Type: application/json' \
    --header 'Authorization: your_api_key' \
    --data '{
      "agentId": "V1StGXR8Z5",
      "conversationId": "conv_a1b2c3d4e5"
    }'
```

**JavaScript:**

```javascript
await fetch(
'https://api.autessa.com/clients/agents/execute-close?resourceId=V1StGXR8Z5',
{
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'your_api_key'
  },
  body: JSON.stringify({
    agentId: 'V1StGXR8Z5',
    conversationId: 'conv_a1b2c3d4e5'
  })
}
);
```

```json title="JSON"
{
  "errors": []
}
```
  

---

## Get Conversation **POST** `/conversation`

Retrieves the complete conversation history including all messages and evaluation context.

### Query Parameters

- `resourceId` (string, required) — The ID of the agent (e.g. `V1StGXR8Z5`).

### Request Body

- `agentId` (string, required) — The ID of the agent.
- `conversationId` (string, required) — The conversation ID to retrieve.

### Response

- `conversation` (AgentConversationDto) — The complete conversation data including logs and evaluation context.
- `errors` — "> Array of error messages if any occurred.
  
  
  
```bash title="cURL"
curl --request POST \
  --url 'https://api.autessa.com/clients/agents/conversation?resourceId=V1StGXR8Z5' \
  --header 'Content-Type: application/json' \
  --header 'Authorization: your_api_key' \
  --data '{
    "agentId": "V1StGXR8Z5",
    "conversationId": "conv_a1b2c3d4e5"
  }'
```

```json title="JSON"
{
  "conversation": {
    "resourceId": "V1StGXR8Z5",
    "version": "1",
    "conversationId": "conv_a1b2c3d4e5",
    "apiKeyId": "key_xyz",
    "closeDate": null,
    "logs": [
      {
        "logType": "USER",
        "userMultimodalInputs": [
          {
            "inputType": "TEXT",
            "content": "What is the weather in Seattle?"
          }
        ]
      },
      {
        "logType": "TOOL_REQUEST",
        "executeToolRequest": {
          "toolCallId": "call_abc123",
          "name": "GetWeather",
          "variables": {
            "location": "Seattle"
          }
        }
      },
      {
        "logType": "TOOL_RESPONSE",
        "executeToolResponse": {
          "toolCallId": "call_abc123",
          "toolName": "GetWeather",
          "result": {
            "temperature": 65,
            "condition": "Partly Cloudy"
          }
        }
      },
      {
        "logType": "MESSAGE_TO_USER",
        "multimodalOutput": {
          "outputType": "TEXT",
          "content": "The weather in Seattle is currently 65°F with partly cloudy skies."
        }
      }
    ]
  },
  "errors": []
}
```
  

---

## Conversation Log Structure

Conversation logs returned by the `/conversation` endpoint contain detailed information about all interactions in a conversation. Each log entry has a `logType` field that determines which other fields are present.

### Log Types

- `USER` — User input to the agent. Contains `userMultimodalInputs` array with text or audio inputs.
- `MESSAGE_TO_USER` — Agent's response to the user. Contains `multimodalOutput` with text or audio output.
- `TOOL_REQUEST` — Request to execute a tool. Contains `executeToolRequest` with tool name and variables.
- `TOOL_RESPONSE` — Result from tool execution. Contains `executeToolResponse` with the tool's result.
- `RESPONSE_CHECK` — The results of the agent's [response checks](/docs/guide/agentic/response-checks.md) on one reply. Contains `responseCheckResult`. Builder-only: never returned by the client conversation endpoints. See [Response check log](#response-check-log).
- `CRITIC_REJECTED_MESSAGE` — A draft that a retired Critic agent rejected. Appears only in older conversations, and is no longer returned by the client conversation endpoints.
- `LISTEN` — Voice-mode marker indicating the agent chose to keep listening instead of responding.

### AgentLog Structure

Each log entry has one of these structures based on its `logType`:

**USER Log:**

- `logType` (string) — `"USER"`
- `userMultimodalInputs` — "> Array of user inputs (text or audio). See [Multimodal Input](#multimodal-input).
  

  **MESSAGE_TO_USER Log:**
  
  - `logType` (string) — `"MESSAGE_TO_USER"`
  - `multimodalOutput` (MultimodalOutput) — The agent's response (text or audio).
  

  **TOOL_REQUEST Log:**
  
  - `logType` (string) — `"TOOL_REQUEST"`
  - `executeToolRequest` (object) — Tool execution request details.
  - `executeToolRequest.toolCallId` (string) — Unique identifier for this tool call.
  - `executeToolRequest.name` (string) — Name of the tool being invoked.
  - `executeToolRequest.variables` (object) — Key-value pairs of arguments passed to the tool.
  

  **TOOL_RESPONSE Log:**
  
  - `logType` (string) — `"TOOL_RESPONSE"`
  - `executeToolResponse` (object) — Tool execution result.
  - `executeToolResponse.toolCallId` (string) — Matches the toolCallId from the corresponding TOOL_REQUEST.
  - `executeToolResponse.toolName` (string) — Name of the tool that was executed.
  - `executeToolResponse.result` (any) — The result returned by the tool.
  
  
  
  

**USER (Text):**

```json
  {
    "logType": "USER",
    "userMultimodalInputs": [
      {
        "inputType": "TEXT",
        "content": "What is the weather?"
      }
    ]
  }
```

**USER (Audio):**

```json
{
"logType": "USER",
"userMultimodalInputs": [
  {
    "inputType": "AUDIO",
    "s3Uri": "temp/audio/1024/8f3a2b7c.wav",
    "audioFormat": {
      "sampleRate": 16000,
      "sampleSizeInBits": 16,
      "channels": 1,
      "signed": true,
      "bigEndian": false
    },
    "transcription": "What is the weather?"
  }
]
}
```

**MESSAGE_TO_USER (Text):**

```json
{
"logType": "MESSAGE_TO_USER",
"multimodalOutput": {
  "outputType": "TEXT",
  "content": "It's 65°F and sunny."
}
}
```

**MESSAGE_TO_USER (Audio):**

```json
{
"logType": "MESSAGE_TO_USER",
"multimodalOutput": {
  "outputType": "AUDIO",
  "sampleRate": 16000,
  "base64Audio": "UklGRiQAAABXQVZF...",
  "transcription": "It's 65 degrees and sunny.",
  "isFinalChunk": true
}
}
```

**TOOL_REQUEST:**

```json
{
"logType": "TOOL_REQUEST",
"executeToolRequest": {
  "toolCallId": "call_123",
  "name": "GetWeather",
  "variables": {
    "location": "Seattle",
    "units": "fahrenheit"
  }
}
}
```

**TOOL_RESPONSE:**

```json
{
"logType": "TOOL_RESPONSE",
"executeToolResponse": {
  "toolCallId": "call_123",
  "toolName": "GetWeather",
  "result": {
    "temperature": 65,
    "condition": "Sunny"
  }
}
}
```

  

### Response check log

Agents with [response checks](/docs/guide/agentic/response-checks.md) record one
`RESPONSE_CHECK` entry per checked reply. It comes right after that reply's
`MESSAGE_TO_USER` entry. When a check sent the draft back for a retry, it
takes the draft's place, since nothing was sent.

`RESPONSE_CHECK` entries are for builders. They appear in the builder's
[agent history](/docs/guide/agentic/agent-history.md) and the
[poweruser conversation endpoint](/docs/api/poweruser/agents.md#get-a-conversation),
and are **never returned by the client conversation endpoints on this page**.
They can include text the customer was deliberately not sent.

**RESPONSE_CHECK Log:**

- `logType` (string) — `"RESPONSE_CHECK"`
- `responseCheckResult.mode` (string) — How the reply was released: `MONITOR` (sent right away; checks only record problems), `SENTENCE` (checked sentence by sentence before sending), or `HOLD` (held until every check passed).
- `responseCheckResult.decision` (string) — `PASSED`, `FLAGGED`, `REDACTED`, `BLOCKED`, `REGENERATED` (the draft was sent back and nothing was sent), or `SENT_AFTER_RETRIES`.
- `responseCheckResult.attempt` (integer) — Which attempt at the reply this was, starting at `1`.
- `responseCheckResult.originalDraft` (string) — The draft the agent wrote. Null when it was released unchanged.
- `responseCheckResult.releasedText` (string) — What the customer received. Null for `REGENERATED`.
- `responseCheckResult.verdicts` (array<object>) — One entry per check: `checkId`, `name`, `checkType`, `action`, `passed`, `reason` (plain-language, may be null), `matches` (each with `start`, `end`, `label`, `text`; offsets into the checked text), `latencyMs`, and `error` (set when the check couldn't run, in which case it counts as failed).

```json title="RESPONSE_CHECK"
{
  "logType": "RESPONSE_CHECK",
  "responseCheckResult": {
    "mode": "SENTENCE",
    "decision": "REDACTED",
    "attempt": 1,
    "originalDraft": "I found your account. Your SSN on file is 123-45-6789.",
    "releasedText": "I found your account. Your SSN on file is [REDACTED].",
    "verdicts": [
      {
        "checkId": "a8d27e10-4c6b-4f3e-8d2a-71b9c0e4f512",
        "name": "Sensitive data",
        "checkType": "BUILT_IN",
        "action": "REDACT",
        "passed": false,
        "reason": "Found a Social Security number.",
        "matches": [
          { "start": 42, "end": 53, "label": "SSN", "text": "123-45-6789" }
        ],
        "latencyMs": 3,
        "error": null
      }
    ]
  }
}
```

---

## Get Conversation Status **POST** `/conversation-status`

Checks the current status of a conversation (IN_PROGRESS, CLOSED, or NOT_FOUND).

### Query Parameters

- `resourceId` (string, required) — The ID of the agent (e.g. `V1StGXR8Z5`).

### Request Body

- `agentId` (string, required) — The ID of the agent.
- `conversationId` (string, required) — The conversation ID to check.

### Response

- `conversationId` (string) — The conversation ID that was checked.
- `status` (string) — One of: `IN_PROGRESS`, `CLOSED`, `NOT_FOUND`
- `errors` — "> Array of error messages if any occurred.
  
  
  
```bash title="cURL"
curl --request POST \
  --url 'https://api.autessa.com/clients/agents/conversation-status?resourceId=V1StGXR8Z5' \
  --header 'Content-Type: application/json' \
  --header 'Authorization: your_api_key' \
  --data '{
    "agentId": "V1StGXR8Z5",
    "conversationId": "conv_a1b2c3d4e5"
  }'
```

```json title="JSON"
{
  "conversationId": "conv_a1b2c3d4e5",
  "status": "IN_PROGRESS",
  "errors": []
}
```
  

---

## Revive Conversation **POST** `/revive-conversation`

Revives a closed conversation, allowing you to continue the interaction where it left off.

### Query Parameters

- `resourceId` (string, required) — The ID of the agent (e.g. `V1StGXR8Z5`).

### Request Body

- `agentId` (string, required) — The ID of the agent.
- `conversationId` (string, required) — The conversation ID to revive.

### Response

- `conversationId` (string) — The revived conversation ID.
- `status` (string) — Status message about the revival operation.
- `errors` — "> Array of error messages if any occurred.
  
  
  
```bash title="cURL"
curl --request POST \
  --url 'https://api.autessa.com/clients/agents/revive-conversation?resourceId=V1StGXR8Z5' \
  --header 'Content-Type: application/json' \
  --header 'Authorization: your_api_key' \
  --data '{
    "agentId": "V1StGXR8Z5",
    "conversationId": "conv_a1b2c3d4e5"
  }'
```

```json title="JSON"
{
  "conversationId": "conv_a1b2c3d4e5",
  "status": "REVIVED",
  "errors": []
}
```
  

---

## Generate Audio Upload Link **POST** `/generate-audio-upload-link`

Generates a pre-signed S3 upload URL for audio files. Use this when you want to upload audio files separately rather than sending them as base64 in the request.

**Note:** Currently supports WAV format only.

### Query Parameters

- `resourceId` (string, required) — The ID of the agent (e.g. `V1StGXR8Z5`).

### Request Body

Currently empty (WAV format is hardcoded).

### Response

- `uploadUrl` (string) — Pre-signed URL for uploading the audio file via PUT request.
- `s3Uri` (string) — Key of the uploaded file. Pass it as `s3Uri` in an AudioInput.
- `expiresInSeconds` (integer) — Time in seconds until the upload URL expires.
- `errors` — "> Array of error messages if any occurred.
  
  
  
```bash title="cURL"
curl --request POST \
  --url 'https://api.autessa.com/clients/agents/generate-audio-upload-link?resourceId=V1StGXR8Z5' \
  --header 'Content-Type: application/json' \
  --header 'Authorization: your_api_key' \
  --data '{}'
```

```json title="JSON"
{
  "uploadUrl": "https://s3.amazonaws.com/autessa-audio/...",
  "s3Uri": "temp/audio/1024/8f3a2b7c.wav",
  "expiresInSeconds": 3600,
  "errors": []
}
```

```bash title="Upload the file"
# Step 1: Get upload link
# Step 2: Upload audio file
curl --request PUT \
  --url 'https://s3.amazonaws.com/autessa-audio/...' \
  --header 'Content-Type: audio/wav' \
  --data-binary '@audio.wav'

# Step 3: Use s3Uri in AudioInput
# {
#   "inputType": "AUDIO",
#   "s3Uri": "temp/audio/1024/8f3a2b7c.wav"
# }
```
  

---

## Generate Image Upload Link **POST** `/generate-image-upload-link`

Generates a pre-signed S3 upload URL for image files. Upload the image via PUT, then reference the returned `s3Uri` in an [Image Input](#image-input).

### Query Parameters

- `resourceId` (string, required) — The ID of the agent (e.g. `V1StGXR8Z5`).

### Request Body

- `fileExtension` (string) — Image file extension: `png`, `jpg`, or `jpeg`. Defaults to `png` if not provided.

### Response

- `uploadUrl` (string) — Pre-signed URL for uploading the image file via PUT request.
- `s3Uri` (string) — Key of the uploaded file. Pass it as `s3Uri` in an ImageInput.
- `mimeType` (string) — MIME type of the image (e.g. `image/png`). Use it as the `Content-Type` header when uploading, and in the ImageInput.
- `expiresInSeconds` (integer) — Time in seconds until the upload URL expires.
- `errors` — "> Array of error messages if any occurred.
  
  
  
```bash title="cURL"
curl --request POST \
  --url 'https://api.autessa.com/clients/agents/generate-image-upload-link?resourceId=V1StGXR8Z5' \
  --header 'Content-Type: application/json' \
  --header 'Authorization: your_api_key' \
  --data '{
    "fileExtension": "png"
  }'
```

```json title="JSON"
{
  "uploadUrl": "https://s3.amazonaws.com/autessa-images/...",
  "s3Uri": "temp/images/1024/2b7c9d1e.png",
  "mimeType": "image/png",
  "expiresInSeconds": 3600,
  "errors": []
}
```

```bash title="Upload the file"
# Step 1: Get upload link
# Step 2: Upload image file
curl --request PUT \
  --url 'https://s3.amazonaws.com/autessa-images/...' \
  --header 'Content-Type: image/png' \
  --data-binary '@image.png'

# Step 3: Use s3Uri in ImageInput
# {
#   "inputType": "IMAGE",
#   "s3Uri": "temp/images/1024/2b7c9d1e.png",
#   "mimeType": "image/png"
# }
```
  

---

## Generate File Upload Link **POST** `/generate-file-upload-link`

Generates a pre-signed S3 upload URL for document files (PDFs, text documents, etc.). Upload the file via PUT, then reference the returned `s3Uri` in a [File Input](#file-input).

### Query Parameters

- `resourceId` (string, required) — The ID of the agent (e.g. `V1StGXR8Z5`).

### Request Body

- `fileExtension` (string) — File extension of the document to upload (e.g. `pdf`, `docx`, `txt`).

### Response

- `uploadUrl` (string) — Pre-signed URL for uploading the file via PUT request.
- `s3Uri` (string) — Key of the uploaded file. Pass it as `s3Uri` in a FileInput.
- `mimeType` (string) — MIME type of the file (e.g. `application/pdf`). Use it as the `Content-Type` header when uploading, and in the FileInput.
- `expiresInSeconds` (integer) — Time in seconds until the upload URL expires.
- `errors` — "> Array of error messages if any occurred.
  
  
  
```bash title="cURL"
curl --request POST \
  --url 'https://api.autessa.com/clients/agents/generate-file-upload-link?resourceId=V1StGXR8Z5' \
  --header 'Content-Type: application/json' \
  --header 'Authorization: your_api_key' \
  --data '{
    "fileExtension": "pdf"
  }'
```

```json title="JSON"
{
  "uploadUrl": "https://s3.amazonaws.com/autessa-files/...",
  "s3Uri": "temp/files/1024/9d1e4a6f.pdf",
  "mimeType": "application/pdf",
  "expiresInSeconds": 3600,
  "errors": []
}
```

```bash title="Upload the file"
# Step 1: Get upload link
# Step 2: Upload document file
curl --request PUT \
  --url 'https://s3.amazonaws.com/autessa-files/...' \
  --header 'Content-Type: application/pdf' \
  --data-binary '@document.pdf'

# Step 3: Use s3Uri in FileInput
# {
#   "inputType": "FILE",
#   "s3Uri": "temp/files/1024/9d1e4a6f.pdf",
#   "mimeType": "application/pdf"
# }
```
  

---

## WebSocket API

## Multimodal Agent Execution **WSS** `/ws/clients/agents/execute`

Real-time agent execution with streaming responses. Supports both text and audio input/output with streaming capabilities.

### Connection URL

```
wss://api.autessa.com/ws/clients/agents/execute?authorization={key}&resourceId={agentId}
```

### Query Parameters

- `authorization` (string, required) — Your API key.
- `resourceId` (string, required) — The ID of the agent.
- `conversationId` (string) — Optional conversation ID to revive and continue.
- `voiceModeEnabled` (boolean) — Set to "true" for voice mode with continuous audio streaming.
- `versionState` (string) — Optional version state override: `PUBLISHED` (default), `DRAFT`, or `ARCHIVED`.
- `versionNumber` (integer) — Optional specific version number to use.

### Connection Lifecycle

1. **Connect** - WebSocket connection established
2. **Status Message** - Server sends conversation status
3. **Send Messages** - Client sends MULTIMODAL or VOICE messages
4. **Receive Streams** - Server streams responses in real-time
5. **Disconnect** - Connection closes, conversation auto-closes

**websocat:**

```bash
websocat "wss://api.autessa.com/ws/clients/agents/execute?authorization=your_api_key&resourceId=V1StGXR8Z5"
```

**JavaScript:**

```javascript
const ws = new WebSocket(
  'wss://api.autessa.com/ws/clients/agents/execute?authorization=your_api_key&resourceId=V1StGXR8Z5'
);

ws.onopen = () => {
  console.log('Connected to agent');
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Received:', data);
};
```

**Python:**

```python
import websocket
import json

ws = websocket.WebSocket()
ws.connect(
  "wss://api.autessa.com/ws/clients/agents/execute?authorization=your_api_key&resourceId=V1StGXR8Z5"
)

# Receive status
status = json.loads(ws.recv())
print(status)
```

### Server-to-Client Messages

When you connect, the server immediately sends a status message:

**New Conversation:**

```json
{
  "conversationId": "conv_abc123",
  "status": "CREATED",
  "errors": []
}
```

**Revived Conversation:**

```json
{
  "conversationId": "conv_abc123",
  "status": "REVIVED",
  "errors": []
}
```

**Error:**

```json
{
  "conversationId": null,
  "status": "ERROR",
  "errors": ["Invalid API key"]
}
```

### Client-to-Server Messages

#### MULTIMODAL Message

Send a JSON message to execute the agent with multimodal input:

- `messageType` (string, required) — Must be `"MULTIMODAL"`
- `agentId` (string, required) — The agent ID
- `input` — " required> Array of multimodal inputs (text or audio)
  - `executionOutputMode` (string) — `"TEXT"` or `"AUDIO"` - desired output format. Defaults to `"TEXT"`.
  - `environmentVariables` (object) — Key-value pairs for environment variables that won't be stored on the server.
  - `promptTemplateVariables` (object) — Key-value pairs to inject into the agent's prompt template. Variables are referenced in the agent instructions using `@@{variableName}@@` syntax.
  
  
  
```json title="JSON"
{
  "messageType": "MULTIMODAL",
  "agentId": "V1StGXR8Z5",
  "executionOutputMode": "TEXT",
  "input": [
    {
      "inputType": "TEXT",
      "content": "What's the weather in Seattle?"
    }
  ],
  "environmentVariables": {
    "USER_LOCATION": "Seattle"
  },
  "promptTemplateVariables": {
    "customerName": "John Doe",
    "accountType": "Premium"
  }
}
```
  

#### VOICE Message

Establish voice mode for continuous audio streaming:

- `messageType` (string, required) — Must be `"VOICE"`
- `agentId` (string, required) — The agent ID
- `audioFormat` (AudioFormat, required) — Audio format specification for the audio bytes you'll send
- `outputType` (string) — `"TEXT"` or `"AUDIO"` - desired output format
- `environmentVariables` (object) — Environment variables

```json title="JSON"
{
  "messageType": "VOICE",
  "agentId": "V1StGXR8Z5",
  "audioFormat": {
    "sampleRate": 16000,
    "sampleSizeInBits": 16,
    "channels": 1,
    "signed": true,
    "bigEndian": false
  },
  "outputType": "AUDIO",
  "environmentVariables": {}
}
```

After establishing voice mode, send raw audio bytes as binary WebSocket messages.

### Streaming Response Messages

The server streams responses in real-time. There are three types of messages:

#### 1. Text Stream Messages

```json title="JSON"
{
  "streamedOutput": {
    "outputType": "TEXT",
    "content": " Seattle"
  }
}
```

Text is streamed token-by-token. Concatenate the `content` fields to build the full response.

#### 2. Tool Stream Messages

**Tool Start:**

```json
{
  "streamedToolMessages": {
    "responseType": "EXECUTE_TOOL",
    "toolName": "GetWeather",
    "invocationId": "inv_123",
    "publicVars": {
      "city": "Seattle",
      "state": "WA"
    },
    "streamMessage": "EXECUTION START: GetWeather"
  }
}
```

**Tool Variables:**

```json
{
  "streamedToolMessages": {
    "responseType": "EXECUTE_TOOL",
    "toolName": "GetWeather",
    "invocationId": "inv_123",
    "streamMessage": "EXECUTION VARIABLES: {\"city\":\"Seattle\",\"state\":\"WA\"}"
  }
}
```

**Tool End:**

```json
{
  "streamedToolMessages": {
    "responseType": "EXECUTE_TOOL",
    "toolName": "GetWeather",
    "invocationId": "inv_123",
    "streamMessage": "EXECUTION END: GetWeather"
  }
}
```

**Tool Result:**

```json
{
  "streamedToolMessages": {
    "responseType": "EXECUTE_TOOL",
    "toolName": "GetWeather",
    "invocationId": "inv_123",
    "streamMessage": "EXECUTION RESULT: \"It is 65°F and partly cloudy\""
  }
}
```

#### 3. Audio Stream Messages

When `executionOutputMode: "AUDIO"` is requested:

```json title="JSON"
{
  "streamedOutput": {
    "outputType": "AUDIO",
    "sampleRate": 16000,
    "base64Audio": "//8AAAMAAAD...",
    "transcription": "The weather in Seattle is 65 degrees",
    "isFinalChunk": false
  }
}
```

Audio is streamed in chunks. Decode the `base64Audio` and play it sequentially.

#### 4. Final Response

After streaming completes, the server sends a final message with the complete output:

```json title="JSON"
{
  "conversationId": "conv_abc123",
  "output": [
    {
      "outputType": "TEXT",
      "content": "The weather in Seattle is currently 65°F with partly cloudy skies."
    }
  ],
  "errors": []
}
```

---

## Multimodal Input

Autessa supports multimodal input - you can send text, audio, images, files, or any combination. Each input is distinguished by its `inputType` field: `"TEXT"`, `"AUDIO"`, `"IMAGE"`, `"FILE"`, `"IMAGE_URL"`, or `"FILE_URL"`.

### Text Input

- `inputType` (string, required) — Must be `"TEXT"`
- `content` (string, required) — The text message from the user

```json title="JSON"
{
  "inputType": "TEXT",
  "content": "What's the weather today?"
}
```

### Audio Input

Audio can be provided in two ways: base64 encoded data or the key of an uploaded file.

- `inputType` (string, required) — Must be `"AUDIO"`
- `base64EncodedData` (string) — Base64 encoded audio data (option 1)
- `s3Uri` (string) — The `s3Uri` key returned by `/generate-audio-upload-link` (option 2). The older `s3://` form is still accepted.
- `audioFormat` (AudioFormat, required) — Audio format metadata
- `transcription` (string) — Optional pre-transcribed text

**Base64:**

```json
{
  "inputType": "AUDIO",
  "base64EncodedData": "UklGRiQAAABXQVZFZm10...",
  "audioFormat": {
    "sampleRate": 16000,
    "sampleSizeInBits": 16,
    "channels": 1,
    "signed": true,
    "bigEndian": false
  }
}
```

**Uploaded file:**

```json
{
  "inputType": "AUDIO",
  "s3Uri": "temp/audio/1024/8f3a2b7c.wav",
  "audioFormat": {
"sampleRate": 16000,
"sampleSizeInBits": 16,
"channels": 1,
"signed": true,
"bigEndian": false
  }
}
```

### Image Input

Send an image the agent can see. Upload the image first with [/generate-image-upload-link](#generate-image-upload-link-), or point at an external URL with `directUrl`.

- `inputType` (string, required) — Must be `"IMAGE"`
- `s3Uri` (string) — The `s3Uri` key returned by `/generate-image-upload-link`. The older `s3://` form is still accepted.
- `directUrl` (string) — Direct HTTPS URL to an externally hosted image. If set, it is used instead of `s3Uri`.
- `mimeType` (string) — Image MIME type, e.g. `image/png`, `image/jpeg`

**Uploaded file:**

```json
{
  "inputType": "IMAGE",
  "s3Uri": "temp/images/1024/2b7c9d1e.png",
  "mimeType": "image/png"
}
```

**Direct URL:**

```json
{
  "inputType": "IMAGE",
  "directUrl": "https://example.com/product-photo.jpg",
  "mimeType": "image/jpeg"
}
```

### File Input

Send a document (PDF, text, etc.) the agent can read. Upload the file first with [/generate-file-upload-link](#generate-file-upload-link-), or point at an external URL with `directUrl`.

- `inputType` (string, required) — Must be `"FILE"`
- `s3Uri` (string) — The `s3Uri` key returned by `/generate-file-upload-link`. The older `s3://` form is still accepted.
- `directUrl` (string) — Direct HTTPS URL to an externally hosted file. If set, it is used instead of `s3Uri`.
- `mimeType` (string) — File MIME type, e.g. `application/pdf`, `text/plain`

```json title="JSON"
{
  "inputType": "FILE",
  "s3Uri": "temp/files/1024/9d1e4a6f.pdf",
  "mimeType": "application/pdf"
}
```

### URL Inputs

`IMAGE_URL` and `FILE_URL` inputs reference content by URL directly:

- `inputType` (string, required) — `"IMAGE_URL"` or `"FILE_URL"`
- `url` (string, required) — Direct URL (`https://...`) or S3 URI (`s3://...`)
- `mimeType` (string) — MIME type. Can be inferred from the URL if omitted.
- `isS3Uri` (boolean) — Set to `true` if `url` is an `s3://` URI that needs pre-signed URL conversion.

```json title="JSON"
{
  "inputType": "IMAGE_URL",
  "url": "https://example.com/diagram.png",
  "mimeType": "image/png",
  "isS3Uri": false
}
```

### AudioFormat

- `sampleRate` (integer, required) — Samples per second in Hz. Common values: 16000 (telephony), 44100 (CD quality), 48000 (professional).
- `sampleSizeInBits` (integer, required) — Bits per sample. Typical values: 8, 16, 24, 32.
- `channels` (integer, required) — Number of audio channels. 1 = mono, 2 = stereo.
- `signed` (boolean, required) — Whether samples are signed (true) or unsigned (false).
- `bigEndian` (boolean, required) — Byte order: true = big-endian, false = little-endian.

---

## Multimodal Output

Agent responses can be in text or audio format. The output type is distinguished by the `outputType` field, which can be either `"TEXT"` or `"AUDIO"`.

### Text Output

- `outputType` (string, required) — Must be `"TEXT"`
- `content` (string, required) — The text response from the agent

```json title="JSON"
{
  "outputType": "TEXT",
  "content": "The weather in Seattle is 65°F with partly cloudy skies."
}
```

### Audio Output

Audio output is used when you request `executionOutputMode: "AUDIO"` via WebSocket.

- `outputType` (string, required) — Must be `"AUDIO"`
- `sampleRate` (integer, required) — Samples per second in Hz (e.g., 16000)
- `base64Audio` (string, required) — Base64 encoded audio data
- `transcription` (string, required) — Text transcription of the audio
- `isFinalChunk` (boolean, required) — Whether this is the final chunk of audio in the stream

```json title="JSON"
{
  "outputType": "AUDIO",
  "sampleRate": 16000,
  "base64Audio": "UklGRiQAAABXQVZFZm10...",
  "transcription": "The weather in Seattle is 65 degrees with partly cloudy skies.",
  "isFinalChunk": true
}
```

---

## Custom Version

Override the default PUBLISHED version of an agent:

- `versionState` (string) — Version state: `"PUBLISHED"`, `"DRAFT"`, or `"ARCHIVED"`. Defaults to `"PUBLISHED"`.
- `versionNumber` (integer) — Specific version number to use (optional).

**REST API:**

```json
{
  "agentId": "V1StGXR8Z5",
  "version": {
    "versionState": "DRAFT"
  },
  "input": [...]
}
```

**WebSocket:**

```bash
wss://api.autessa.com/ws/clients/agents/execute?authorization=key&resourceId=V1StGXR8Z5&versionState=DRAFT
```

---

## Enumerations

### EConversationStatus

- `IN_PROGRESS` - Conversation is active
- `CLOSED` - Conversation has been closed
- `NOT_FOUND` - Conversation doesn't exist

### ExecutionOutputMode

- `TEXT` - Text output (default)
- `AUDIO` - Audio output (base64 encoded)

### EInputType

- `TEXT` - Text input
- `AUDIO` - Audio input
- `IMAGE` - Image input (uploaded file key or direct URL)
- `FILE` - File/document input (uploaded file key or direct URL)
- `IMAGE_URL` - Image referenced by URL
- `FILE_URL` - File referenced by URL

### EOutputType

- `TEXT` - Text output
- `AUDIO` - Audio output

### EVersionState

- `PUBLISHED` - Published version (default)
- `DRAFT` - Draft/sandbox version
- `ARCHIVED` - Archived version

---

## Rate Limiting

Agent execution endpoints are rate limited. Rate limit information is included in response headers:

- `X-RateLimit-Limit-Minute` - Requests allowed per minute
- `X-RateLimit-Remaining-Minute` - Remaining requests this minute
- `X-RateLimit-Limit-Day` - Requests allowed per day
- `X-RateLimit-Remaining-Day` - Remaining requests today

When rate limited, you'll receive a 429 status code with a `Retry-After` header.

---

## Complete Examples

### Single-Turn Conversation

**JavaScript:**

```javascript
// Simple one-shot agent execution
const response = await fetch(
  'https://api.autessa.com/clients/agents/execute?resourceId=V1StGXR8Z5',
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'your_api_key'
    },
    body: JSON.stringify({
      agentId: 'V1StGXR8Z5',
      input: [
        {
          inputType: 'TEXT',
          content: 'Tell me a joke'
        }
      ]
    })
  }
);

const data = await response.json();
console.log(data.output[0].content);
```

**Python:**

```python
import requests

response = requests.post(
    'https://api.autessa.com/clients/agents/execute?resourceId=V1StGXR8Z5',
    headers={
        'Content-Type': 'application/json',
        'Authorization': 'your_api_key'
    },
    json={
        'agentId': 'V1StGXR8Z5',
        'input': [
            {
                'inputType': 'TEXT',
                'content': 'Tell me a joke'
            }
        ]
    }
)

data = response.json()
print(data['output'][0]['content'])
```

### Multi-Turn Conversation

```javascript title="JavaScript"
// Create conversation
const createResp = await fetch(
  'https://api.autessa.com/clients/agents/execute-create?resourceId=V1StGXR8Z5',
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'your_api_key'
    },
    body: JSON.stringify({ agentId: 'V1StGXR8Z5' })
  }
);

const { conversationId } = await createResp.json();

// First message
const resp1 = await fetch(
  'https://api.autessa.com/clients/agents/execute?resourceId=V1StGXR8Z5',
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'your_api_key'
    },
    body: JSON.stringify({
      agentId: 'V1StGXR8Z5',
      conversationId,
      input: [{ inputType: 'TEXT', content: 'Hi, I need help booking a flight' }]
    })
  }
);

// Second message (continues conversation)
const resp2 = await fetch(
  'https://api.autessa.com/clients/agents/execute?resourceId=V1StGXR8Z5',
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'your_api_key'
    },
    body: JSON.stringify({
      agentId: 'V1StGXR8Z5',
      conversationId,
      input: [{ inputType: 'TEXT', content: 'From Seattle to San Francisco' }]
    })
  }
);

// Close conversation
await fetch(
  'https://api.autessa.com/clients/agents/execute-close?resourceId=V1StGXR8Z5',
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'your_api_key'
    },
    body: JSON.stringify({
      agentId: 'V1StGXR8Z5',
      conversationId
    })
  }
);
```

### Mixed Text and Audio Input

```javascript title="JavaScript"
// Example showing both text and audio inputs in one request
const response = await fetch(
  'https://api.autessa.com/clients/agents/execute?resourceId=V1StGXR8Z5',
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'your_api_key'
    },
    body: JSON.stringify({
      agentId: 'V1StGXR8Z5',
      conversationId: 'conv_a1b2c3d4e5',
      input: [
        // Text input
        {
          inputType: 'TEXT',
          content: 'Here is my question:'
        },
        // Audio input
        {
          inputType: 'AUDIO',
          s3Uri: 'temp/audio/1024/5c1d9e3a.wav',
          audioFormat: {
            sampleRate: 16000,
            sampleSizeInBits: 16,
            channels: 1,
            signed: true,
            bigEndian: false
          }
        }
      ]
    })
  }
);

const data = await response.json();
// Response has outputType field to distinguish format
console.log('Output type:', data.output[0].outputType); // "TEXT" or "AUDIO"
```

### WebSocket Streaming

```javascript title="JavaScript"
const ws = new WebSocket(
  'wss://api.autessa.com/ws/clients/agents/execute?authorization=your_api_key&resourceId=V1StGXR8Z5'
);

let conversationId;
let fullResponse = '';

ws.onopen = () => {
  console.log('Connected');
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);

  // Connection status
  if (data.status) {
    conversationId = data.conversationId;
    console.log('Conversation created:', conversationId);

    // Send first message
    ws.send(JSON.stringify({
      messageType: 'MULTIMODAL',
      agentId: 'V1StGXR8Z5',
      executionOutputMode: 'TEXT',
      input: [
        {
          inputType: 'TEXT',
          content: 'What is the weather?'
        }
      ]
    }));
    return;
  }

  // Streaming text
  if (data.streamedOutput) {
    fullResponse += data.streamedOutput.content;
    console.log('Stream:', data.streamedOutput.content);
  }

  // Tool messages
  if (data.streamedToolMessages) {
    console.log('Tool:', data.streamedToolMessages.streamMessage);
  }

  // Final output
  if (data.output) {
    console.log('Final response:', data.output[0].content);
    console.log('Full streamed response:', fullResponse);
  }
};

ws.onerror = (error) => {
  console.error('WebSocket error:', error);
};

ws.onclose = () => {
  console.log('Disconnected');
};
```

### Real-time Voice Mode
For conversational AI with continuous audio streaming, use the `voiceModeEnabled=true` parameter. This enables bidirectional audio streaming for natural voice conversations.

**JavaScript:**

```javascript
const agentId = 'V1StGXR8Z5'
const apiKey = 'your_api_key'

// Connect with voice mode enabled
const ws = new WebSocket(
  `wss://api.autessa.com/ws/clients/agents/execute?authorization=${apiKey}&resourceId=${agentId}&voiceModeEnabled=true`
)

let conversationId

ws.onopen = () => {
  console.log('Connected in voice mode')
}

ws.onmessage = async (event) => {
  // Handle connection status
  if (typeof event.data === 'string') {
    const data = JSON.parse(event.data)

    if (data.status) {
      conversationId = data.conversationId
      console.log('Conversation created:', conversationId)

      // Send voice establishment message
      ws.send(JSON.stringify({
        messageType: 'VOICE',
        agentId: agentId,
        audioFormat: {
          sampleRate: 16000,
          sampleSizeInBits: 32,
          channels: 1,
          signed: true,
          bigEndian: false
        },
        outputType: 'AUDIO',
        environmentVariables: {},
        promptTemplateVariables: {}
      }))

      console.log('Voice mode established')
      return
    }

    // Handle audio output chunks
    if (data.streamedOutput?.outputType === 'AUDIO') {
      const { base64Audio, sampleRate, transcription, isFinalChunk } = data.streamedOutput

      console.log('Agent:', transcription)

      // Process audio chunk for playback
      // See: https://docs.autessa.com/api/audio-playback
      await audioProcessor.processAudioChunk(base64Audio, sampleRate, transcription)

      // Auto-start playback
      const status = audioProcessor.getStatus()
      if (status.totalItems === 1 && !status.isPlaying) {
        audioProcessor.play()
      }

      if (isFinalChunk) {
        console.log('Agent finished speaking')
      }
    }
  }
}

// Start recording and stream audio
// See complete implementation at: https://docs.autessa.com/api/audio-record
const recorder = new AudioRecorder(16000)

recorder.onSpeechStart = () => {
  console.log('User started speaking')
  audioProcessor.setInterrupted(true)
}

recorder.onSpeechEnd = () => {
  console.log('User stopped speaking')
  audioProcessor.setInterrupted(false)
}

// Start continuous recording with WebSocket
await recorder.startContinuousRecording(
  `wss://api.autessa.com/ws/clients/agents/execute?authorization=${apiKey}&resourceId=${agentId}&voiceModeEnabled=true`,
  {
    outputType: 'AUDIO',
    agentId: agentId,
    environmentVariables: {},
    promptTemplateVariables: {}
  }
)

// Later: cleanup
recorder.stopRecording()
audioProcessor.clear()
ws.close()
```

**Python:**

```python
import websocket
import json
import asyncio

agent_id = 'V1StGXR8Z5'
api_key = 'your_api_key'

# Connect with voice mode
ws_url = f"wss://api.autessa.com/ws/clients/agents/execute?authorization={api_key}&resourceId={agent_id}&voiceModeEnabled=true"
ws = websocket.create_connection(ws_url)

# Receive connection status
status = json.loads(ws.recv())
conversation_id = status['conversationId']
print(f"Connected: {conversation_id}")

# Send voice establishment message
ws.send(json.dumps({
    "messageType": "VOICE",
    "agentId": agent_id,
    "audioFormat": {
        "sampleRate": 16000,
        "sampleSizeInBits": 32,
        "channels": 1,
        "signed": True,
        "bigEndian": False
    },
    "outputType": "AUDIO",
    "environmentVariables": {},
    "promptTemplateVariables": {}
}))

print("Voice mode established")

# Now stream audio bytes
# See Python audio recording implementation in docs
while True:
    # Receive audio or text responses
    response = json.loads(ws.recv())

    if 'streamedOutput' in response:
        output = response['streamedOutput']
        if output['outputType'] == 'AUDIO':
            print(f"Agent: {output['transcription']}")
            # Process audio chunk
            # See: https://docs.autessa.com/api/audio-playback

ws.close()
```

> **Voice Mode Protocol:**
> 1. Connect with `voiceModeEnabled=true`
> 2. Wait for connection status message
> 3. Send VOICE establishment message with audio format
> 4. Stream raw audio bytes as binary WebSocket messages
> 5. Receive streamed audio chunks in real-time
> 
> For complete implementation with Voice Activity Detection and audio utilities, see the [Audio Recording](/docs/api/audio-record.md#real-time-voice-mode-websocket) and [Audio Playback](/docs/api/audio-playback.md#real-time-voice-mode-playback) guides.

#### Voice Establishment Message

After connecting, send this message to establish voice mode:

```json title="VOICE Message"
{
  "messageType": "VOICE",
  "agentId": "V1StGXR8Z5",
  "audioFormat": {
    "sampleRate": 16000,
    "sampleSizeInBits": 32,
    "channels": 1,
    "signed": true,
    "bigEndian": false
  },
  "outputType": "AUDIO",
  "environmentVariables": {},
  "promptTemplateVariables": {}
}
```

**After sending the establishment message:**

- Send raw audio bytes as **binary** WebSocket messages (ArrayBuffer/bytes)
- Receive JSON messages with audio chunks and transcriptions
- Audio format: Float32Array converted to ArrayBuffer (32-bit float, mono, 16kHz)

#### Audio Streaming Format

**Input Audio (Client → Server):**

- Send raw ArrayBuffer from Float32Array
- 16kHz sample rate, 32-bit float, mono
- Continuous streaming (detected via Voice Activity Detection)

**Output Audio (Server → Client):**
```json
{
  "streamedOutput": {
    "outputType": "AUDIO",
    "sampleRate": 16000,
    "base64Audio": "UklGRiQAAABXQVZF...",
    "transcription": "Hello! How can I help you today?",
    "isFinalChunk": false
  }
}
```

#### Complete Voice Mode Example

This example combines everything for a working voice conversation:

```typescript title="Complete TypeScript Example"
import { AudioRecorder } from './audio-recorder'
import { AudioProcessor } from './audio-processor'

class VoiceConversation {
  private agentId: string
  private apiKey: string
  private ws: WebSocket | null = null
  private recorder: AudioRecorder
  private audioProcessor: AudioProcessor
  private conversationId: string | null = null

  constructor(agentId: string, apiKey: string) {
    this.agentId = agentId
    this.apiKey = apiKey
    this.recorder = new AudioRecorder(16000)
    this.audioProcessor = new AudioProcessor()
    this.setupCallbacks()
  }

  private setupCallbacks() {
    // Handle user speech detection
    this.recorder.onSpeechStart = () => {
      console.log('👤 User speaking...')
      this.audioProcessor.setInterrupted(true)
    }

    this.recorder.onSpeechEnd = () => {
      console.log('👤 User stopped')
      this.audioProcessor.setInterrupted(false)
    }
  }

  async start() {
    const wsUrl = `wss://api.autessa.com/ws/clients/agents/execute?authorization=${this.apiKey}&resourceId=${this.agentId}&voiceModeEnabled=true`

    this.ws = new WebSocket(wsUrl)

    this.ws.onopen = () => {
      console.log('✅ Connected')
    }

    this.ws.onmessage = async (event) => {
      const data = JSON.parse(event.data)

      // Connection status
      if (data.status) {
        this.conversationId = data.conversationId
        console.log('💬 Conversation:', this.conversationId)

        // Establish voice mode
        await this.recorder.startContinuousRecording(wsUrl, {
          outputType: 'AUDIO',
          agentId: this.agentId,
          environmentVariables: {},
          promptTemplateVariables: {}
        })

        console.log('🎤 Voice mode active')
        return
      }

      // Audio responses
      if (data.streamedOutput?.outputType === 'AUDIO') {
        const { base64Audio, sampleRate, transcription, isFinalChunk } = data.streamedOutput

        console.log('🤖 Agent:', transcription)

        // Play audio
        await this.audioProcessor.processAudioChunk(base64Audio, sampleRate, transcription)

        const status = this.audioProcessor.getStatus()
        if (status.totalItems === 1 && !status.isPlaying) {
          this.audioProcessor.play()
        }

        if (isFinalChunk) {
          console.log('🤖 Agent finished')
        }
      }
    }

    this.ws.onerror = (error) => {
      console.error('❌ Error:', error)
    }

    this.ws.onclose = () => {
      console.log('👋 Disconnected')
      this.cleanup()
    }
  }

  cleanup() {
    this.recorder.stopRecording()
    this.audioProcessor.clear()
    if (this.ws) {
      this.ws.close()
      this.ws = null
    }
  }
}

// Usage
const conversation = new VoiceConversation('V1StGXR8Z5', 'your_api_key')
await conversation.start()

// Later: cleanup
conversation.cleanup()
```

> **Production Considerations:**
> 
> 1. **Interruption Handling**: The example above handles user interruptions by pausing agent audio when the user starts speaking
> 2. **Voice Activity Detection**: The AudioRecorder includes VAD to detect speech vs silence
> 3. **Memory Management**: Always call cleanup methods to free blob URLs and close connections
> 4. **Error Handling**: Implement reconnection logic for production use
> 5. **Audio Format**: Use 16kHz, mono, Float32 for recording; receive Int16 PCM for playback
> 
> For complete utility class implementations, see:
> 
> - [Audio Recording Guide](/docs/api/audio-record.md)
> - [Audio Playback Guide](/docs/api/audio-playback.md)

---

## Related

- [Agents guide](/docs/guide/agentic/agents.md)
- [Manager API](/docs/api/managers.md)
- [Tool Execution API](/docs/api/tools.md)
- [Audio Recording](/docs/api/audio-record.md) and [Audio Playback](/docs/api/audio-playback.md)
- [API keys](/docs/guide/api-management/api-keys.md) and [Authentication](/docs/guide/authentication.md)

