How to setup assemblyai for stt in AgentSession?
# ask-ai
b
How to setup assemblyai for stt in AgentSession?
t
Thanks for reaching out, Dmytro. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To help you set up AssemblyAI for Speech-to-Text (STT) in
AgentSession
, you have two friendly options to choose from: • LiveKit Inference: This is a straightforward way to get started with automatic billing and no need for an API key. • AssemblyAI Plugin: If you prefer more control, you can use your own AssemblyAI API key. Option A: Using LiveKit Inference 1. Simply set the model ID in your
AgentSession
or
Agent
configuration like this:
Copy code
stt="assemblyai/universal-streaming"
You can also specify the language if you want, for example:
stt="assemblyai/universal-streaming:en"
. Option B: Using the AssemblyAI Plugin 1. First, install the plugin with:
pip install livekit-plugins-assemblyai
2. Next, set your AssemblyAI API key as an environment variable:
ASSEMBLYAI_API_KEY=your_api_key_here
3. Then, use the plugin in your
AgentSession
like this:
Copy code
from livekit.plugins import assemblyai

stt_plugin = assemblyai.STT()

session = AgentSession(
    stt=stt_plugin,
    vad=silero.VAD.load(),  # Recommended
    turn_detection="stt"   # Optional: enable semantic turn detection
)
For both options, I highly recommend including a Voice Activity Detection (VAD) plugin like Silero to make your experience smoother and more responsive. If you have any questions or would like me to walk you through more examples, please don’t hesitate to ask—I’m here to help! Sources: AssemblyAI STT | LiveKit Docs | complex-agents/ivr-agent/agent.py | livekit-agents/livekit/agents/voice/agent_session.py | Turn detection and interruptions | LiveKit Docs | AssemblyAI plugin guide | LiveKit Docs
b
I need example for Node.js SDK and the problem is that with option A it works good but option B throws: [114655.346] ERROR (11424): Unhandled error. ({ type: 'error', error: TypeError: this.run is not a function at SpeechStream.mainTask (F:\Projects\Redflag\redflag-agent\node_modules\.pnpm\@livekit+agents@1.0.14_@livekit+rtc-node@0.13.20\node_modules\@livekit\agents\src\stt\stt.ts18627) at Timeout._onTimeout (F:\Projects\Redflag\redflag-agent\node_modules\.pnpm\@livekit+agents@1.0.14_@livekit+rtc-node@0.13.20\node_modules\@livekit\agents\src\stt\stt.ts18026) at listOnTimeout (nodeinternal/timers573:17) at process.processTimers (nodeinternal/timers514:7), source: STT { _events: [Object: null prototype] { metrics_collected: [Function (anonymous)], error: [Function (anonymous)] }, _eventsCount: 2, _maxListeners: undefined, label: 'assemblyai.STT', [Symbol(shapeMode)]: false, [Symbol(kCapture)]: false }, createdAt: 1761817615345 })
t
Hi there! The error
TypeError: this.run is not a function
happens because the AssemblyAI plugin (
@livekit/agents-plugin-assemblyai
) is designed specifically for Python and isn’t available for Node.js. But don’t worry! In Node.js, you can still use AssemblyAI for speech-to-text (STT) through LiveKit Inference. Here’s a friendly example of how to use LiveKit Inference correctly in Node.js:
Copy code
import {
  defineAgent,
  voice,
} from '@livekit/agents';
import * as silero from '@livekit/agents-plugin-silero';

export default defineAgent({
  prewarm: async (proc) => {
    proc.userData.vad = await silero.VAD.load();
  },
  entry: async (ctx) => {
    const session = new voice.AgentSession({
      stt: 'assemblyai/universal-streaming:en', // Use LiveKit Inference
      llm: 'openai/gpt-4.1-mini',
      tts: 'cartesia/sonic-2:voice-id',
      vad: ctx.proc.userData.vad! as silero.VAD,
      turnDetection: new voice.turnDetector.MultilingualModel(),
    });

    await session.start({
      agent: new voice.Agent({ instructions: 'You are a helpful assistant.' }),
      room: ctx.room,
    });
  },
});
Just a few helpful reminders: • The AssemblyAI plugin isn’t supported in Node.js, so it’s best to avoid using
assemblyai.STT
or anything similar. • Make sure to use the model string
'assemblyai/universal-streaming:en'
in the
stt
field to tap into LiveKit Inference. • Don’t forget to set your environment variables
LIVEKIT_API_KEY
and
LIVEKIT_API_SECRET
so everything authenticates smoothly. If you have any more questions or want me to walk you through additional examples, just let me know—I’m here to help! Sources: examples/src/drive-thru/drivethru_agent.ts | livekit-plugins/livekit-plugins-assemblyai/README.md | Speech-to-text (STT) models | LiveKit Docs | AssemblyAI plugin guide | LiveKit Docs | AssemblyAI STT | LiveKit Docs
b
I have another question, let's imagine livekit agent need to get some information from end user, after agent get it how can I trigger room end event?
t
To help you smoothly trigger a room end event in LiveKit after your agent has gathered information from the end user, you can use the
delete_room
API. Here’s a simple way to do it: 1. Collect User Information: Have your agent gather the necessary details from the user. 2. Provide a Final Response (Optional): It’s nice to acknowledge the user before ending the session, like this:
Copy code
await self.session.generate_reply(
    instructions="Thank you for your time. I'll be ending this call now. Goodbye!",
    allow_interruptions=False
)
1. End the Agent Session: Close the agent session gracefully:
Copy code
await self.session.aclose()
1. Delete the Room: Finally, use the
delete_room
API to terminate the room:
Copy code
from livekit.api import DeleteRoomRequest

job_ctx = get_job_context()
await job_ctx.api.room.delete_room(
    DeleteRoomRequest(room=job_ctx.room.name)
)
Here are a couple of best practices to keep in mind: • Make sure the final message finishes playing by awaiting the
generate_reply
call before deleting the room. • It’s a good idea to add error handling around the
delete_room
call to gracefully manage any hiccups during room termination. If you have any questions or need more examples, please don’t hesitate to ask—I’m here to help! Sources: telephony/sip_lifecycle.py | livekit-agents/livekit/agents/voice/agent_session.py | Job lifecycle | LiveKit Docs
b
Can I somehow catch what tts is going to say to the user in pipeline? My config:
Copy code
const session = new voice.AgentSession({
  stt: 'assemblyai/universal-streaming:en',
  llm: cache.llm,
  tts: cache.tts,
  vad: cache.vad,
  turnDetection: 'realtime_llm',
});
t
I'm happy to help you with intercepting or modifying the TTS output in the LiveKit pipeline before it reaches the user. You can achieve this using one of the following friendly methods: 1. Using a Callback: If you're working with a
VoicePipelineAgent
, you can utilize the
before_tts_cb
callback to gently tweak the text before it goes to the TTS engine. Here's a simple example to guide you:
Copy code
async function beforeTtsCallback(agent, text) {
  if (typeof text === 'string') {
    return text.replace('example', 'sample');
  } else {
    const processedStream = async function* () {
      for await (const chunk of text) {
        yield chunk.replace('example', 'sample');
      }
    };
    return processedStream();
  }
}

const session = new voice.AgentSession({
  stt: 'assemblyai/universal-streaming:en',
  llm: cache.llm,
  tts: cache.tts,
  vad: cache.vad,
  turnDetection: 'realtime_llm',
  beforeTtsCb: beforeTtsCallback,
});
1. Overriding the TTS Node: For a bit more advanced and flexible control, you might consider overriding the
ttsNode
method in a custom agent class. This way, you can carefully process each piece of text before it’s passed along to the TTS engine:
Copy code
class CustomAgent extends voice.Agent {
  async ttsNode(text, modelSettings) {
    const processedStream = async function* () {
      for await (const chunk of text) {
        yield chunk.replace('example', 'sample');
      }
    };
    return super.ttsNode(processedStream(), modelSettings);
  }
}

const session = new voice.AgentSession({
  stt: 'assemblyai/universal-streaming:en',
  llm: cache.llm,
  tts: cache.tts,
  vad: cache.vad,
  turnDetection: 'realtime_llm',
  agent: new CustomAgent(),
});
Please feel free to reach out if you'd like me to explain anything further or if you'd appreciate more examples. I'm here to support you! Sources: docs/index.yaml | Pipeline nodes and hooks | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py | agents/src/voice/agent.ts | chain-of-thought-tts/README.mdoc
b
For option 2: ERROR (33192): source.getReader is not a function jobID: "AJ_67JVXNF8dNPr" err: { "type": "TypeError", "message": "source.getReader is not a function", "stack": TypeError: source.getReader is not a function
t
I'm here to help you understand why the error
TypeError: source.getReader is not a function
happens. This error occurs because the
ttsNode
method needs to return a proper
ReadableStream
that follows the Web Streams API. The LiveKit TTS pipeline expects this stream to have a
getReader()
method so it can consume the audio frames correctly. Here's a correct way to implement it:
Copy code
class CustomAgent extends voice.Agent {
  async ttsNode(
    text: ReadableStream<string>,
    modelSettings: voice.ModelSettings
  ): Promise<ReadableStream<AudioFrame> | null> {
    const baseStream = await voice.Agent.default.ttsNode(this, text, modelSettings);
    if (!baseStream) return null;

    return new ReadableStream<AudioFrame>({
      async start(controller) {
        const reader = baseStream.getReader();
        try {
          while (true) {
            const { done, value } = await reader.read();
            if (done) break;

            // Example: Process audio frame (e.g., adjust volume)
            const processedFrame = new AudioFrame({
              data: value.data.map(sample => sample * 0.5),
              sampleRate: value.sampleRate,
              numChannels: value.numChannels,
              samplesPerChannel: value.samplesPerChannel
            });

            controller.enqueue(processedFrame);
          }
          controller.close();
        } finally {
          reader.releaseLock();
        }
      },
      cancel(reason) {
        return baseStream.cancel(reason);
      }
    });
  }
}
Here are some key points to keep in mind: • Make sure
ttsNode
always returns a
ReadableStream
, not a Node.js
Readable
or any other object. • Use
voice.Agent.default.ttsNode
to obtain the base stream and then process it as needed. • Don't forget to handle errors properly and clean up resources by calling
reader.releaseLock()
. If anything is unclear or you'd like me to walk you through more examples, please don't hesitate to ask. I'm here to support you every step of the way! Sources: plugins/resemble/src/tts.ts | Pipeline nodes and hooks | LiveKit Docs | Agents v0.x migration guide - Node.js | LiveKit Docs