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

# AssemblyAI integration guide

> Point an AssemblyAI voice agent at a SambaCloud model with the llm field and measure the time to first audio.

[AssemblyAI](https://www.assemblyai.com/) offers a Voice Agent API that runs speech-to-text, an LLM, and text-to-speech behind one WebSocket. By default the agent uses AssemblyAI's managed model, but the `llm` field accepts any OpenAI-compatible chat completions endpoint. Pointing it at SambaCloud lets an AssemblyAI voice agent answer with SambaNova models. Because voice depends on how fast the first sound arrives, this guide also measures that for each model.

## Prerequisites

* A [SambaCloud](https://cloud.sambanova.ai/?utm_source=assemblyai\&utm_medium=external\&utm_campaign=cloud_signup) account and [API key](https://cloud.sambanova.ai/apis?utm_source=assemblyai\&utm_medium=external\&utm_campaign=cloud_signup).
* An [AssemblyAI](https://www.assemblyai.com/dashboard/signup) account and API key. Copy the key from the [API keys page](https://www.assemblyai.com/dashboard/api-keys) of the dashboard.
* Python 3.10 or higher.

> [!NOTE]
>
> macOS ships with Python 3.9 and exposes it as `python3` rather than `python`. Check your version with `python3 --version`. If it is below 3.10, install a supported version with [pyenv](https://github.com/pyenv/pyenv), [uv](https://docs.astral.sh/uv/), or `brew install python@3.12` before continuing.

## Installation and setup

**1. Create a virtual environment**

```bash macOS / Linux theme={}
python3 -m venv .venv
source .venv/bin/activate
```

```powershell Windows theme={}
python -m venv .venv
.venv\Scripts\Activate.ps1
```

**2. Install the dependencies**

```bash theme={}
pip install requests websockets
```

This guide was tested with `requests` 2.34.2 and `websockets` 17.4 on Python 3.12.

**3. Set your API keys**

```bash macOS / Linux theme={}
export SAMBANOVA_API_KEY="your-sambanova-api-key"
export ASSEMBLYAI_API_KEY="your-assemblyai-api-key"
```

```powershell Windows theme={}
$env:SAMBANOVA_API_KEY="your-sambanova-api-key"
$env:ASSEMBLYAI_API_KEY="your-assemblyai-api-key"
```

## Connect a voice agent to SambaCloud

You create the agent with an HTTP request and connect to it over a WebSocket. The part that changes for SambaNova is the `llm` field:

```json theme={}
"llm": [
  {
    "base_url": "https://api.sambanova.ai/v1",
    "model": "MiniMax-M3.1-Flash",
    "api_key": "your-sambanova-api-key"
  }
]
```

* `base_url` is the SambaCloud base URL. AssemblyAI calls `{base_url}/chat/completions`, so keep the `/v1`.
* `model` is a SambaCloud model ID.
* `api_key` is your SambaCloud key. AssemblyAI encrypts it and never returns it in a response.
* The list takes one entry. The model must support streamed chat completions, which SambaCloud models do.

> [!NOTE]
>
> This guide works with SambaCloud only. AssemblyAI requires the `base_url` to use `https` and a public host, so it cannot reach a private SambaStack instance.

The script below creates an agent with this `llm` entry, connects to it, and types a question to the agent with a `conversation.message` event instead of speaking it, so you can test without a microphone. It prints the reply and the time from the request to the first sound, and saves the spoken reply as `reply.wav`. The agent is deleted at the end, because it holds your SambaCloud key.

```python voice_agent.py theme={}
import asyncio
import base64
import json
import os
import time
import wave

import requests
import websockets

API = "https://agents.assemblyai.com/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['ASSEMBLYAI_API_KEY']}"}
MODEL = "MiniMax-M3.1-Flash"
QUESTION = "What can you do?"

# Create an agent whose LLM is a SambaCloud model.
agent = requests.post(
    f"{API}/agents",
    headers=HEADERS,
    json={
        "name": "SambaCloud assistant",
        "system_prompt": "You are a helpful voice assistant. Keep answers under two sentences.",
        "voice": {"voice_id": "alba"},
        "llm": [
            {
                "base_url": "https://api.sambanova.ai/v1",
                "model": MODEL,
                "api_key": os.environ["SAMBANOVA_API_KEY"],
            }
        ],
    },
)
agent.raise_for_status()
agent_id = agent.json()["id"]


async def main():
    # A short-lived token lets the WebSocket connect without exposing your API key.
    token = requests.post(
        "https://token.assemblyai.com/v1/token",
        headers=HEADERS,
        json={"product": "speech_to_speech", "expires_in_seconds": 60},
    ).json()["token"]
    audio = bytearray()
    first_audio = None
    async with websockets.connect(f"wss://agents.assemblyai.com/v1/ws?token={token}") as ws:
        await ws.send(json.dumps({"type": "session.update", "session": {"agent_id": agent_id}}))
        async for message in ws:
            event = json.loads(message)
            kind = event["type"]
            if kind == "session.ready":
                # Type the question instead of speaking it, then ask for a reply.
                await ws.send(json.dumps({"type": "conversation.message", "role": "user", "content": QUESTION}))
                start = time.perf_counter()
                await ws.send(json.dumps({"type": "reply.create"}))
            elif kind == "reply.audio":
                if first_audio is None:
                    first_audio = time.perf_counter() - start
                audio.extend(base64.b64decode(event["data"]))
            elif kind == "transcript.agent":
                print(f"agent: {event['text']}")
            elif kind == "reply.error":
                print(f"reply.error: {event['code']}: {event['message']}")
            elif kind == "reply.done" or kind == "session.error":
                if kind == "session.error":
                    print(f"session.error: {event['code']}: {event['message']}")
                break

    if first_audio is not None:
        print(f"Time to first audio: {first_audio:.2f} s")
    with wave.open("reply.wav", "wb") as wav:
        wav.setnchannels(1)
        wav.setsampwidth(2)
        wav.setframerate(24000)
        wav.writeframes(bytes(audio))
    print(f"Saved reply.wav ({len(audio)} bytes of audio)")


try:
    asyncio.run(main())
finally:
    # Remove the test agent. Its SambaCloud key is stored on AssemblyAI's side.
    requests.delete(f"{API}/agents/{agent_id}", headers=HEADERS)
```

```bash theme={}
python voice_agent.py
```

```text Output theme={}
agent: I can answer questions, help you write or edit text, summarize information, brainstorm ideas, and plan tasks. I can also work through problems step by step and adjust my tone and detail to fit your needs.
Time to first audio: 1.53 s
Saved reply.wav (558240 bytes of audio)
```

> [!NOTE]
>
> Time to first audio is measured on the client, from the moment the script asks for a reply to the first audio chunk. It includes the model's first token and AssemblyAI's text-to-speech. Because this test sends text, it does not include speech-to-text time. Your numbers depend on the model, the prompt, and your network.

## Choose a model for voice

The script uses `MiniMax-M3.1-Flash`. Voice is where first-sound latency matters most, so it is worth comparing models. Each row is the time to first audio over 5 runs of the script above, changing only `MODEL`, measured on 6 November 2026:

| Model | Time to first audio |
| :- | :- |
| `MiniMax-M3.1-Flash` | 1.5 to 1.8 s in 5 of 5 runs |
| `gpt-oss-120b` | 0.42 to 0.44 s in 4 of 5 runs, 3.0 s in one run |
| `gemma-4-31B-it` | 1.4 to 7.2 s, with 4 of 5 runs over 3.5 s |

> [!WARNING]
>
> `MiniMax-M3.1-Flash` is a reasoning model. It thinks before it answers, and that time counts toward the first sound, so the reply starts later than with a non-reasoning model. For a voice agent where the pause matters most, set `MODEL` to `gpt-oss-120b`, the fastest model in the table.

> [!NOTE]
>
> `Meta-Llama-3.3-70B-Instruct` is not in the table because SambaCloud deprecated it on 17 November 2026. A request for it returns HTTP 503, and the script ends with `reply.error: llm_provider_error`. See [Deprecations](https://docs.sambanova.ai/docs/en/models/deprecations.md) for the replacement, and confirm that `GET https://api.sambanova.ai/v1/models` lists any model before you choose it.

> [!NOTE]
>
> First-audio times vary between runs and between days. Every model except `MiniMax-M3.1-Flash` had at least one run about 2 seconds or more slower than its usual time, and `gemma-4-31B-it` was slower and less steady than the others. Measure over several runs before you quote a latency number.

## Troubleshooting

> [accordion] KeyError: 'ASSEMBLYAI\_API\_KEY' or 'SAMBANOVA\_API\_KEY'
>
> An environment variable is not set in the shell you run Python from. Set it as shown in [Installation and setup](#installation-and-setup), then run the script again from the same shell.

> [accordion] 401 Client Error: Unauthorized for url: [https://agents.assemblyai.com/v1/agents](https://agents.assemblyai.com/v1/agents)
>
> AssemblyAI rejected `ASSEMBLYAI_API_KEY`. Copy a key from the [API keys page](https://www.assemblyai.com/dashboard/api-keys) and export it again.

> [accordion] 422 Client Error: Unprocessable Content for url: [https://agents.assemblyai.com/v1/agents](https://agents.assemblyai.com/v1/agents)
>
> AssemblyAI validated the agent and refused it. Print `agent.text` to read the reason. For example, `llm[0].base_url ... must use https://` means the `base_url` starts with `http://`. Use `https://api.sambanova.ai/v1`.

> [accordion] reply.error: llm\_request\_rejected: Incorrect API key provided
>
> The agent was created, but AssemblyAI's request to SambaCloud failed because the `api_key` in the `llm` entry is not valid. Copy a key from the [SambaCloud API keys page](https://cloud.sambanova.ai/apis) and run the script again.

> [accordion] reply.error: llm\_request\_rejected: The model ... does not exist or you do not have access to it
>
> The `model` value is not a SambaCloud model ID. See [SambaCloud models](https://docs.sambanova.ai/docs/en/models/sambacloud-models.md) for the current list.

> [accordion] reply.error: llm\_request\_rejected: The model provider rejected the request
>
> This generic message was what AssemblyAI returned when the `base_url` was `https://api.sambanova.ai` without `/v1`. Set it to `https://api.sambanova.ai/v1`.

> [accordion] reply.error: llm\_provider\_error: The model provider returned an error
>
> SambaCloud returned an error for the request. This is what a deprecated model produces: `Meta-Llama-3.3-70B-Instruct` was deprecated on 17 November 2026, and a direct SambaCloud request for it returns HTTP 503 "currently not available". Call `GET https://api.sambanova.ai/v1/models` with your key and set `model` to one of the IDs it lists.

> [accordion] reply.error: llm\_timeout: The model provider did not respond in time
>
> SambaCloud did not answer in time. This appeared once in 5 runs with `gemma-4-31B-it`, the model with the slowest and least steady first-audio times in the table. Run the script again, or set `MODEL` to a steadier model such as `gpt-oss-120b`.

> [accordion] The script finishes with a 0-byte reply.wav and no reply text
>
> A failed model request does not stop the session. AssemblyAI sends a `reply.error` event and then a normal `reply.done`, so the script ends quietly. Read the `reply.error` line the script prints for the cause. The `reply.error` event is not listed in AssemblyAI's events reference, but the API sends it.

> [accordion] A test agent is left in your account
>
> The script deletes its agent when it finishes, even after an error in the session. If the process is killed before then, delete the agent with `DELETE https://agents.assemblyai.com/v1/agents/<agent-id>`, because it stores your SambaCloud key.

## Additional resources

* [AssemblyAI Voice Agent API](https://assemblyai.com/docs/voice-agents/voice-agent-api/quickstart)
* [Connect your own LLM](https://assemblyai.com/docs/voice-agents/voice-agent-api/connect-your-own-llm)
* [Voice Agent events reference](https://assemblyai.com/docs/voice-agents/voice-agent-api/events-reference)
* [Supported SambaCloud models](https://docs.sambanova.ai/docs/en/models/sambacloud-models.md)
