Really hoping i can get some help with this I jus...
# ask-ai
c
Really hoping i can get some help with this I just cloned the agent-starter-node repo to play around with LiveKit. I've deployed the quickstart example to LiveKit Cloud and connected it to a Twilio number to make calls to it. I can successfully call the agent and speak with it but shortly into the conversation I'm seeing the following in the logs
{"level":50,"time":1760222331494,"pid":247,"hostname":"deployment-p-3sw5kp9trhd-ca-d8xokwhwfmhe-6bd447d786-s6ffp","msg":"Error in SynthesizeStream"}
After this, the agent stops speaking but I still see the LLM generating a response to what I'm saying in the logs. It looks like the TTS is breaking for some reason and wont generate any audio. I'm not sure if i may be hitting some rate limit? I dont think I am because I'm only making a single call to my agent (no concurrent calls are taking place) and I am having a casual conversation (no constant interrupts etc.) I've tested with ElevenLabs TTS and Cartesia TTS but still get the same issue. I've tried searching the documentation and online am getting nowhere, for context I'm on a Macbook running an M3 Pro chip, no idea if this has anything to do with it (don't think it should considering I've deployed it to LiveKit so its not even running off my machine but I thought i'd mention it incase) I also received a Usage Warning from LiveKit saying that 80% of concurrent TTS connections on LiveKit have been used but I'm the only person calling this voice agent. I then checked my dashboard and saw the peak TTS usage for my project was 6/5 TTS concurrent connections (i have no idea how since again, im the only person calling it on a single line) I feel like this issue may have something to do with that. Not sure where to go from here. I also checked if theres any active sessions but there are none right now. If anyone could please provide some direction. Thanks. Thread in Slack Conversation
t
Thanks for reaching out, Jatin. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — I’ve reviewed your details about the
Error in SynthesizeStream
, the LLM continuing to generate text while no audio is produced, and the dashboard showing 6/5 TTS concurrent connections. I’ll focus on helping you diagnose and fix this. Quick summary of likely causes I'm addressing: • Your project’s TTS concurrency limit (Build plan = 5) can be hit even with a single call because multiple TTS streams may be opened from one session (preemptive speech, tool responses, retries). • A temporary spike, delayed cleanup, or reporting artifact can make the dashboard show 6/5. • When TTS streams exceed the limit, new syntheses fail (LLM still produces text, but audio stops). • Fallback TTS isn’t automatically applied in Node unless you implement it. To help narrow it down, please answer these quick checks and run a couple tests: 1) Agent config and behavior • Do you have preemptive speech enabled or any background tasks that might generate speech before the LLM completes? • Does your agent call any tools (weather, lookup, etc.) that themselves trigger spoken responses? 2) Repro / logs • Can you paste the log lines immediately before and after the
Error in SynthesizeStream
message (timestamp + a few lines)? Look for ttsNode/llmNode or retry messages. • Does the error happen at consistent times (e.g., after N seconds or after N replies)? 3) Quick simplified test (one-off) Please try this to confirm whether concurrency load is the cause: • Deploy a stripped-down agent that returns a single short static reply (no tools, no preemptive speech). Make one call and speak to it. Does TTS still fail mid-call? 4) Dashboard timing check • When you see the peak 6/5, note the timestamp and compare with logs to see what operations were running then (preemptive generations, tool calls, or multiple synth requests). Immediate mitigations you can try now • Temporarily disable preemptive generation and any tool-triggered speech to reduce concurrent TTS streams. • If feasible for testing, implement a simple fallback flow in your code to retry synthesis on a different provider or catch the error and retry after a short backoff. If you share: • the surrounding log snippet for the error, and • whether preemptive speech or tool calls are enabled, I’ll analyze those and suggest the exact code changes or next steps to reduce TTS concurrency or add retries/fallbacks. Would you like a minimal Node example for a fallback/retry flow next? Sources: Quotas and limits | LiveKit docs | Agent speech and audio | LiveKit docs | Events and error handling | LiveKit docs | LiveKit Pricing
c
• Do you have preemptive speech enabled or any background tasks that might generate speech before the LLM completes?
How do i check this? Yes we do tool calls but they don’t generate responses internally.
t
You're right to check preemptive speech — it can open extra TTS streams. Below are concise steps to find and disable it in the Node agent starter, and a minimal test to confirm whether preemptive generation is the cause. How to check/disable preemptive speech in the Node agent starter 1. Open your agent code (look for files like
agent.js
,
index.js
,
app.js
, or any file that constructs the agent). 2. Search for settings or calls containing the word "preempt" or "preemptive", e.g.,
preemptive
,
preempt
,
preemptiveGeneration
, or
generate_speech
. 3. Common places: ◦ Agent initialization/options object passed to
Agent
or similar class. ◦ Any code that starts speech synthesis before the LLM reply completes (look for TTS calls triggered while an LLM response is still streaming). 1. If you find a flag such as
preemptive: true
or
preemptiveGeneration: true
, set it to
false
or remove it. If you don’t find an explicit flag: • Look for logic that calls TTS immediately when partial text arrives from the LLM (e.g., streaming handlers that call synth per chunk). Temporarily disable that handler so TTS only runs after the LLM finishes. Minimal test to isolate the issue 1. Create a stripped-down reply handler that always returns a single short string and does not call tools or preemptive TTS. For example: ◦ Handler returns "Hello, this is a test." and then triggers a single TTS call after the full text is ready. 1. Deploy that version and make one call. If TTS no longer fails, preemptive or multiple TTS streams were likely the cause. Notes on your tools comment • Since your tools don’t generate internal spoken responses, they likely aren’t causing extra TTS streams — but verify the agent isn’t configured to read tool outputs aloud automatically. If you’d like, paste the portion of your agent code that handles LLM streaming, TTS calls, or agent initialization (3–15 lines around the relevant config) and I’ll point out exactly where to change it.
c
no there is no preemptive flag in the code similar to this.
t
Thanks — since there’s no explicit preemptive flag, let’s check for implicit preemptive TTS in the streaming/handler code and isolate the problem. What to look for (search these patterns) • Any handler for partial LLM output or streaming events, e.g.,
on('data')
,
on('chunk')
,
onPartial
,
onStream
, or
onDelta
. • Code that calls TTS or
synthesize
inside those handlers (e.g., calls to
synthesize
,
tts.speak()
,
startSynthesis()
). • Any place that starts TTS before you see the final LLM reply or before the LLM stream ends (look for
if (!finished) { ... }
or similar). • Calls that split text into chunks then call TTS per chunk. Quick edits to disable implicit preemptive TTS 1. Locate the LLM streaming handler. Wrap TTS calls so they only run after the LLM signals completion. Example pattern: ◦ Buffer partial text in a variable during streaming. ◦ On
end
/
close
/
finished
event, call
synthesize(bufferedText)
once. 1. If the code currently calls TTS inside a streaming callback, move that call to the LLM finished handler. Minimal non‑streaming TTS test (one-shot synthesis) 1. Replace your reply flow temporarily with: ◦ Build a full reply string (no streaming). ◦ Call a single
synthesize(fullReply)
once. 1. Deploy and call the agent. If TTS no longer fails mid-call, streaming-triggered synths were the cause. If you can paste 10–20 lines around: • where the agent subscribes to LLM stream events, or • where you call
synthesize
/ TTS, I’ll mark exactly where to change it and provide the minimal code snippet you can drop in. Would you like me to do that?
c
• Does the error happen at consistent times (e.g., after N seconds or after N replies)?
After 4-5 mins mark of the call
t
Thanks — helpful that it fails around 4–5 minutes. Let’s focus on logs and a quick isolation test to confirm whether TTS concurrency or a resource leak is causing the break. Please provide two small things next: 1) Log excerpt • Paste the log lines from ~10–20 seconds before the
Error in SynthesizeStream
and ~10–20 seconds after. Include timestamps and any lines mentioning
tts
,
synthesize
,
llm
,
retry
,
close
, or
stream
. This will help spot retries, stream opens/closes, or cleanup delays. 2) Dashboard timestamp check • When the error occurs, note that call’s timestamp and check the LiveKit Cloud dashboard peak TTS concurrency around that same timestamp. Tell me the peak value and exact time shown. While you gather that, run this quick isolation test (should take <10 minutes): • Deploy a temporary version of your agent that: ◦ Returns one short static reply (e.g., "Test reply.") with NO tool calls. ◦ Buffers any streaming LLM output and only calls TTS once after the LLM finishes (one-shot synthesis). • Make a single call and talk for 5+ minutes to see if the TTS still cuts out around 4–5 minutes. If TTS still fails in that stripped-down test, include those logs too — it indicates a project-wide TTS concurrency or metering/cleanup issue. If it does not fail, paste the original logs and the part of your agent that handles streaming and TTS calls (10–20 lines) and I’ll point to the exact change to prevent implicit preemptive synths or leaks.
c
This is the agent definition:
Copy code
export default defineAgent({
  prewarm: async (proc: JobProcess) => {
    proc.userData.vad = await silero.VAD.load({ forceCPU: true });
  },
  entry: async (ctx: JobContext) => {
    const logger = log();

    logger.info('Starting agent session', { roomName: ctx.room.name });

    // Set up a voice AI pipeline using OpenAI, Cartesia, AssemblyAI, and the LiveKit turn detector
    const session = new voice.AgentSession({
      voiceOptions: {
        maxToolSteps: 150,
        userAwayTimeout: 12.5,
      },
      // Speech-to-text (STT) is your agent's ears, turning the user's speech into text that the LLM can understand
      // See all available models at https://docs.livekit.io/agents/models/stt/
      stt: new inference.STT({
        model: 'assemblyai/universal-streaming',
        language: 'en',
      }),

      // A Large Language Model (LLM) is your agent's brain, processing user input and generating a response
      // See all providers at https://docs.livekit.io/agents/models/llm/
      llm: new inference.LLM({
        model: 'openai/gpt-4.1-nano',
      }),

      // Text-to-speech (TTS) is your agent's voice, turning the LLM's text into speech that the user can hear
      // See all available models as well as voice selections at https://docs.livekit.io/agents/models/tts/
      tts: new inference.TTS({
        language: 'en',
        voice: 'cgSgspJ2msm6clMCkdW9',
        model: 'elevenlabs/eleven_turbo_v2_5',
      }),

      // VAD and turn detection are used to determine when the user is speaking and when the agent should respond
      // See more at https://docs.livekit.io/agents/build/turns
      // turnDetection: new livekit.turnDetector.EnglishModel(),

      turnDetection: 'stt',
      vad: ctx.proc.userData.vad! as silero.VAD,
    });

    session.on(voice.AgentSessionEventTypes.UserStateChanged, (ev) => {
      if (ev.newState === 'speaking') {
        logger.info('User started speaking');
      } else if (ev.newState === 'listening') {
        logger.info('User stopped speaking');
      }
    });

    session.on(voice.AgentSessionEventTypes.AgentStateChanged, (ev) => {
      if (ev.newState === 'initializing') {
        logger.info('Agent is starting up');
      } else if (ev.newState === 'idle') {
        logger.info('Agent is ready but not processing');
      } else if (ev.newState === 'listening') {
        logger.info('Agent is listening for user input');
      } else if (ev.newState === 'thinking') {
        logger.info('Agent is processing user input and generating a response');
      } else if (ev.newState === 'speaking') {
        logger.info('Agent started speaking');
      }
    });

    // Metrics collection, to measure pipeline performance
    // For more information, see https://docs.livekit.io/agents/build/metrics/
    const usageCollector = new metrics.UsageCollector();
    session.on(voice.AgentSessionEventTypes.MetricsCollected, (ev) => {
      metrics.logMetrics(ev.metrics);
      usageCollector.collect(ev.metrics);
    });

    const logUsage = async () => {
      const summary = usageCollector.getSummary();
      console.log(`Usage: ${JSON.stringify(summary)}`);
    };

    ctx.addShutdownCallback(logUsage);

    // Create SessionManager for handling call transfers
    const sessionManager = new SessionManager(ctx, ctx.room, session);

    // Add cleanup callback for SessionManager
    ctx.addShutdownCallback(async () => {
      await sessionManager.cleanup();
    });

    // Start the session, which initializes the voice pipeline and warms up the models
    await session.start({
      agent: new Assistant(sessionManager),
      room: ctx.room,
      record: true,
      inputOptions: {
        // LiveKit Cloud enhanced noise cancellation
        // - If self-hosting, omit this parameter
        // - For telephony applications, use `BackgroundVoiceCancellationTelephony` for best results
        noiseCancellation: TelephonyBackgroundVoiceCancellation(),
      },
    });
    // Background audio player for ambient office sounds
    const backgroundAudio = new BackgroundAudioPlayer({
      ambientSound: {
        source: path.join(__dirname, '..', 'office-environment.mp3'),
        volume: 0.2,
      },
    });

    await backgroundAudio.start({ room: ctx.room, agentSession: session });

    // Join the room and connect to the user
    await ctx.connect();
  },
});

cli.runApp(
  new WorkerOptions({
    agent: fileURLToPath(import.meta.url),
    agentName: 'ai-claims-rep',
    jobMemoryLimitMB: 2048,
    jobMemoryWarnMB: 1024,
    maxRetry: 3,
    production: true,
  }),
);
t
Thanks — seeing your agent code makes the likely cause clear and gives us a direct path to fix it. Why this is happening (brief) • Background audio +
turnDetection: 'stt'
can cause many implicit turn events during a long call. Each event can spawn a TTS job, which accumulates across minutes and hits the 5-concurrent TTS limit, causing the
Error in SynthesizeStream
you see while the LLM keeps generating text. What to change now (apply in this order) 1) Disable preemptive generation explicitly • Add
preemptiveGeneration: false
in
voiceOptions
so the agent won't start speculative synths from interim STT:
Copy code
const session = new voice.AgentSession({
  voiceOptions: {
    maxToolSteps: 150,
    userAwayTimeout: 12.5,
    preemptiveGeneration: false,
  },
  ...
});
2) Prevent background audio from triggering turns • Start your BackgroundAudioPlayer with interruptions disabled so ambient audio doesn't flip agent state:
Copy code
await backgroundAudio.start({
  room: ctx.room,
  agentSession: session,
  audioOptions: { allowInterruptions: false },
});
3) Only generate replies after real user turns • Ensure you do not call
session.generateReply()
/
session.say()
inside
AgentStateChanged
handlers. Use the user-turn event instead:
Copy code
session.on(voice.AgentSessionEventTypes.UserTurnCompleted, async (ev) => {
  await session.generateReply();
});
4) Long-term: use the turn detector model • Replace
turnDetection: 'stt'
with the turn detector to reduce false positives:
Copy code
turnDetection: new voice.turnDetector.EnglishModel(),
// remove passing a standalone VAD when using the turn detector
Quick test after changes • Deploy with these changes and run a single 5–6 minute call. If TTS stays stable (no error after ~4–5 min), the concurrency/leak issue is resolved. If it still fails • Paste 10–20 log lines surrounding the
Error in SynthesizeStream
(timestamps + any tts/llm/retry lines) and the dashboard peak TTS timestamp you observe. I’ll analyze them and suggest the next steps (fallback TTS, reducing tool-triggered speech, or targeted retries). Would you like the minimal patched agent file with these edits applied so you can drop it in and test quickly? Sources: Live Conversations with AI using ChatGPT and WebRTC | Text and transcriptions | LiveKit docs | Quotas and limits | LiveKit docs | Events and error handling | LiveKit docs | Pipeline nodes and hooks | LiveKit docs
c
This is the error please check:
Copy code
{"level":50,"time":1764904368220,"pid":107,"hostname":"deployment-p-1fwry9d9cfn-ca-ntdtlfa9jzaw-69696d6b5f-phtcv","pid":107,"jobID":"AJ_c4JXPmjPsYeB","err":{"type":"Error","message":"Unhandled error. ({\n  type: 'error',\n  error: APIConnectionError: Error connecting to LiveKit WebSocket\n      at WebSocket.onError (file:///app/node_modules/.pnpm/@livekit+agents@1.0.24_@livekit+rtc-node@0.13.21_bufferutil@4.0.9_zod@3.25.76/node_modules/@livekit/agents/dist/inference/utils.js:29:16)\n      at Object.onceWrapper (node:events:634:26)\n      at WebSocket.emit (node:events:519:28)\n      at emitErrorAndClose (/app/node_modules/.pnpm/ws@8.18.3_bufferutil@4.0.9/node_modules/ws/lib/websocket.js:1041:13)\n      at process.processTicksAndRejections (node:internal/process/task_queues:90:21) {\n    body: null,\n    retryable: true\n  },\n  source: TTS {\n    _events: [Object: null prototype] {\n      metrics_collected: [Function (anonymous)],\n      error: [Function (anonymous)]\n    },\n    _eventsCount: 2,\n    _maxListeners: undefined,\n    opts: {\n      model: 'elevenlabs/eleven_turbo_v2_5',\n      voice: 'cgSgspJ2msm6clMCkdW9',\n      language: 'en',\n      encoding: 'pcm_s16le',\n      sampleRate: 16000,\n      baseURL: 'http://inference.livekit.svc.cluster.local/v1',\n      apiKey: 'APIXZBBbdB6jPiN',\n      apiSecret: 'EE28wUDYJe9UWtdQ1DqUVFvlg6fEnKnJAwrhqG94fcUB',\n      modelOptions: {}\n    },\n    streams: Set(30) {\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream]\n    },\n    [Symbol(shapeMode)]: false,\n    [Symbol(kCapture)]: false\n  },\n  createdAt: 1764904368220\n})","stack":"Error [ERR_UNHANDLED_ERROR]: Unhandled error. ({\n  type: 'error',\n  error: APIConnectionError: Error connecting to LiveKit WebSocket\n      at WebSocket.onError (file:///app/node_modules/.pnpm/@livekit+agents@1.0.24_@livekit+rtc-node@0.13.21_bufferutil@4.0.9_zod@3.25.76/node_modules/@livekit/agents/dist/inference/utils.js:29:16)\n      at Object.onceWrapper (node:events:634:26)\n      at WebSocket.emit (node:events:519:28)\n      at emitErrorAndClose (/app/node_modules/.pnpm/ws@8.18.3_bufferutil@4.0.9/node_modules/ws/lib/websocket.js:1041:13)\n      at process.processTicksAndRejections (node:internal/process/task_queues:90:21) {\n    body: null,\n    retryable: true\n  },\n  source: TTS {\n    _events: [Object: null prototype] {\n      metrics_collected: [Function (anonymous)],\n      error: [Function (anonymous)]\n    },\n    _eventsCount: 2,\n    _maxListeners: undefined,\n    opts: {\n      model: 'elevenlabs/eleven_turbo_v2_5',\n      voice: 'cgSgspJ2msm6clMCkdW9',\n      language: 'en',\n      encoding: 'pcm_s16le',\n      sampleRate: 16000,\n      baseURL: 'http://inference.livekit.svc.cluster.local/v1',\n      apiKey: 'APIXZBBbdB6jPiN',\n      apiSecret: 'EE28wUDYJe9UWtdQ1DqUVFvlg6fEnKnJAwrhqG94fcUB',\n      modelOptions: {}\n    },\n    streams: Set(30) {\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream]\n    },\n    [Symbol(shapeMode)]: false,\n    [Symbol(kCapture)]: false\n  },\n  createdAt: 1764904368220\n})\n    at AgentSession.emit (node:events:508:17)\n    at AgentSession.emit (file:///app/node_modules/.pnpm/@livekit+agents@1.0.24_@livekit+rtc-node@0.13.21_bufferutil@4.0.9_zod@3.25.76/node_modules/@livekit/agents/dist/voice/agent_session.js:105:18)\n    at AgentActivity.onError (file:///app/node_modules/.pnpm/@livekit+agents@1.0.24_@livekit+rtc-node@0.13.21_bufferutil@4.0.9_zod@3.25.76/node_modules/@livekit/agents/dist/voice/agent_activity.js:363:25)\n    at TTS.<anonymous> (file:///app/node_modules/.pnpm/@livekit+agents@1.0.24_@livekit+rtc-node@0.13.21_bufferutil@4.0.9_zod@3.25.76/node_modules/@livekit/agents/dist/voice/agent_activity.js:188:43)\n    at TTS.emit (node:events:519:28)\n    at SynthesizeStream.emitError (file:///app/node_modules/.pnpm/@livekit+agents@1.0.24_@livekit+rtc-node@0.13.21_bufferutil@4.0.9_zod@3.25.76/node_modules/@livekit/agents/dist/tts/tts.js:116:15)\n    at SynthesizeStream._mainTaskImpl (file:///app/node_modules/.pnpm/@livekit+agents@1.0.24_@livekit+rtc-node@0.13.21_bufferutil@4.0.9_zod@3.25.76/node_modules/@livekit/agents/dist/tts/tts.js:90:18)\n    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)\n    at async file:///app/node_modules/.pnpm/@livekit+agents@1.0.24_@livekit+rtc-node@0.13.21_bufferutil@4.0.9_zod@3.25.76/node_modules/@livekit/agents/dist/telemetry/traces.js:73:16\n    at async DynamicTracer.startActiveSpan (file:///app/node_modules/.pnpm/@livekit+agents@1.0.24_@livekit+rtc-node@0.13.21_bufferutil@4.0.9_zod@3.25.76/node_modules/@livekit/agents/dist/telemetry/traces.js:71:12)","code":"ERR_UNHANDLED_ERROR","context":{"type":"error","error":{"body":null,"retryable":true,"name":"APIConnectionError"},"source":{"_events":{},"_eventsCount":2,"opts":{"model":"elevenlabs/eleven_turbo_v2_5","voice":"cgSgspJ2msm6clMCkdW9","language":"en","encoding":"pcm_s16le","sampleRate":16000,"baseURL":"http://inference.livekit.svc.cluster.local/v1","apiKey":"APIXZBBbdB6jPiN","apiSecret":"EE28wUDYJe9UWtdQ1DqUVFvlg6fEnKnJAwrhqG94fcUB","modelOptions":{}},"streams":{}},"createdAt":1764904368220}},"msg":"Unhandled error. ({\n  type: 'error',\n  error: APIConnectionError: Error connecting to LiveKit WebSocket\n      at WebSocket.onError (file:///app/node_modules/.pnpm/@livekit+agents@1.0.24_@livekit+rtc-node@0.13.21_bufferutil@4.0.9_zod@3.25.76/node_modules/@livekit/agents/dist/inference/utils.js:29:16)\n      at Object.onceWrapper (node:events:634:26)\n      at WebSocket.emit (node:events:519:28)\n      at emitErrorAndClose (/app/node_modules/.pnpm/ws@8.18.3_bufferutil@4.0.9/node_modules/ws/lib/websocket.js:1041:13)\n      at process.processTicksAndRejections (node:internal/process/task_queues:90:21) {\n    body: null,\n    retryable: true\n  },\n  source: TTS {\n    _events: [Object: null prototype] {\n      metrics_collected: [Function (anonymous)],\n      error: [Function (anonymous)]\n    },\n    _eventsCount: 2,\n    _maxListeners: undefined,\n    opts: {\n      model: 'elevenlabs/eleven_turbo_v2_5',\n      voice: 'cgSgspJ2msm6clMCkdW9',\n      language: 'en',\n      encoding: 'pcm_s16le',\n      sampleRate: 16000,\n      baseURL: 'http://inference.livekit.svc.cluster.local/v1',\n      apiKey: 'APIXZBBbdB6jPiN',\n      apiSecret: 'EE28wUDYJe9UWtdQ1DqUVFvlg6fEnKnJAwrhqG94fcUB',\n      modelOptions: {}\n    },\n    streams: Set(30) {\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream],\n      [SynthesizeStream]\n    },\n    [Symbol(shapeMode)]: false,\n    [Symbol(kCapture)]: false\n  },\n  createdAt: 1764904368220\n})"}
{"level":40,"time":1764904368820,"pid":107,"hostname":"deployment-p-1fwry9d9cfn-ca-ntdtlfa9jzaw-69696d6b5f-phtcv","tts":"inference.TTS","attempt":3,"error":{"body":null,"retryable":true,"name":"APIConnectionError"},"msg":"failed to synthesize speech, retrying in  2000s"}
{"level":30,"time":1764904369189,"pid":107,"hostname":"deployment-p-1fwry9d9cfn-ca-ntdtlfa9jzaw-69696d6b5f-phtcv","speech_id":"speech_1a1e5db5-e4a","message":"","msg":"playout completed with interrupt"}
{"level":40,"time":1764904369189,"pid":107,"hostname":"deployment-p-1fwry9d9cfn-ca-ntdtlfa9jzaw-69696d6b5f-phtcv","msg":"SegmentSynchronizerImpl text marked as ended in capture text, rotating segment"}
{"level":50,"time":1764904370827,"pid":107,"hostname":"deployment-p-1fwry9d9cfn-ca-ntdtlfa9jzaw-69696d6b5f-phtcv","pid":107,"jobID":"AJ_c4JXPmjPsYeB","err":{"type":"Error","message":"Unhandled error. ({\n  type: 'error',\n  error: APIConnectionError: Error connecting to LiveKit WebSocket\n      at WebSocket.onError (file:///app/node_modules/.pnpm/@livekit+agents@1.0.24_@livekit+rtc-node@0.13.21_bufferutil@4.0.9_zod@3.25.76/node_modules/@livekit/agents/dist/inference/utils.js:29:16)\n      at Object.onceWrapper (node:events:634:26)\n      at WebSocket.emit (node:events:519:28)\n      at emitErrorAndClose (/app/node_modules/.pnpm/ws@8.18.3_bufferutil@4.0.9/node_modules/ws/lib/websocket.js:1041:13)\n      at process.processTicksAndRejections (node:internal/process/task_queues:90:21) {\n    body: null,\n    retryable: true\n  },\n  source: TTS {\n    _events: [Object: null prototype] {\n      metrics_collected: [Function (anonymous)],\n      error: [Function (anonymous)]\n    },\n    _eventsCount: 2,\n    _maxListeners: undefined,\n    opts: {\n      model: 'elevenlabs/eleven_turbo_v2_5',\n      voice: 'cgSgspJ2msm6clMCkdW9',\n      language: 'en',\n      encoding: 'pcm_s16le',\n      sampleRate: 16000,\n      baseURL: 'http://inference.livekit.svc.cluster.local/v1',\n      apiKey: 'APIXZBBbdB6jPiN',\n
t
Thanks — this log is very helpful. What the log shows (short) • The TTS component opened 30 active
SynthesizeStream
entries and then hit repeated
APIConnectionError: Error connecting to LiveKit WebSocket
. • The TTS code is retrying (
attempt:3 ... retryable:true
) and then an unhandled error bubbles up because many streams are active and the inference WebSocket connection fails. • This matches a concurrency/leak issue where many synth streams are opened (streams Set size 30) and the inference service or WebSocket endpoint becomes overloaded or unreachable. Immediate, practical fixes to apply now 1. Explicitly disable speculative/preemptive synths • Add
preemptiveGeneration: false
under
voiceOptions
(as previously shown). This prevents many synth jobs from being created for interim STT. 1. Prevent background audio from causing state churn • Start background audio with interruptions disabled:
Copy code
await backgroundAudio.start({
  room: ctx.room,
  agentSession: session,
  audioOptions: { allowInterruptions: false },
});
1. Only generate replies on user-turn completion • Ensure you generate replies from
UserTurnCompleted
(or equivalent user-turn event) rather than
AgentStateChanged
. 1. Add defensive limits on simultaneous synths • Throttle/synchronize TTS calls in your app so only one in-flight synth per agent is active at a time. Example pattern: ◦ Maintain an in-memory semaphore/flag
ttsInFlight
. ◦ If
ttsInFlight
is true, queue the next synthesis or drop it. ◦ On synth completion/failure clear the flag and process next queued item. 1. Increase retry/backoff and handle WebSocket errors gracefully • The logs show retries but also an unhandled exception. Wrap synthesis errors so they don't crash the job and implement exponential backoff (e.g., 500ms → 2s → 8s) and a max retry count. Ensure TTS stream errors are caught and streams are removed from the session
streams
Set. Verification steps to run after applying changes • Deploy a version with (1) + (2) + a simple single-synthesis semaphore. Start a 6-minute call and watch: ◦ Agent logs for any new
SynthesizeStream
errors. ◦ LiveKit dashboard TTS concurrency metric (confirm it stays low). ◦ The
streams
Set size in logs (should stay <=1–2). If the problem persists after those fixes • Paste the new log slice around the next
Error in SynthesizeStream
(10–20s before/after) and the dashboard peak TTS timestamp. Also include whether semaphore/queue prevented more than one active synth in your test. I can provide: • A minimal Node code snippet for a simple semaphore/throttling wrapper around
session.tts.synthesize(...)
and • A short safe error-handling wrapper to prevent unhandled exceptions if you want to paste where you call synth. Which would you prefer?
c
I can provide:
• A minimal Node code snippet for a simple semaphore/throttling wrapper around
session.tts.synthesize(...)
and
• A short safe error-handling wrapper to prevent unhandled exceptions if you want to paste where you call synth. Which would you prefer?
Give me both options
t
Below are two minimal Node.js snippets you can drop into your agent code: (A) a semaphore/throttle wrapper that ensures only one in-flight TTS synth runs at a time (with a small queue), and (B) a safe error-handling wrapper that catches TTS/WebSocket errors, applies exponential backoff retries, and prevents unhandled exceptions. A — Simple semaphore + queue around synth • Ensures at most one active synthesis. Queued requests run FIFO. • Replace
session.tts.synthesize(...)
calls with
ttsQueue.synthesize(text, opts)
.
Copy code
class TTSQueue {
  constructor(session) {
    this.session = session;
    this.inFlight = false;
    this.queue = [];
  }

  async synthesize(text, opts = {}) {
    return new Promise((resolve, reject) => {
      this.queue.push({ text, opts, resolve, reject });
      this._next();
    });
  }

  async _next() {
    if (this.inFlight) return;
    const item = this.queue.shift();
    if (!item) return;

    this.inFlight = true;
    try {
      // call real synth (may throw)
      const result = await this.session.tts.synthesize(item.text, item.opts);
      item.resolve(result);
    } catch (err) {
      item.reject(err);
    } finally {
      this.inFlight = false;
      // schedule next tick to avoid deep recursion
      setImmediate(() => this._next());
    }
  }
}

// usage
const ttsQueue = new TTSQueue(session);
// later: await ttsQueue.synthesize("Hello world");
B — Safe error-handling wrapper with retries and exponential backoff • Catches TTS errors, applies retry/backoff, logs, and never throws unhandled errors. • Use around actual synth calls (or wrap the queue's synth call if preferred).
Copy code
async function safeSynthesize(session, text, opts = {}, {
  maxRetries = 4,
  baseDelayMs = 500,
  maxDelayMs = 8000,
  onError = (err) => console.error('TTS synth error', err),
} = {}) {
  let attempt = 0;

  while (attempt <= maxRetries) {
    try {
      // If you use the queue, call its synthesize instead:
      // return await ttsQueue.synthesize(text, opts);
      return await session.tts.synthesize(text, opts);
    } catch (err) {
      attempt += 1;
      onError(err);

      // If not retryable or exceeded attempts, return a failure marker
      const retryable = err && err.retryable !== false;
      if (!retryable || attempt > maxRetries) {
        // return null or a safe fallback audio marker
        return { success: false, error: err };
      }

      // exponential backoff jittered
      const delay = Math.min(baseDelayMs * 2 ** (attempt - 1), maxDelayMs);
      const jitter = Math.floor(Math.random() * baseDelayMs);
      await new Promise((res) => setTimeout(res, delay + jitter));
      // continue retry loop
    }
  }
  // should not reach here
  return { success: false };
}

// usage
const res = await safeSynthesize(session, 'Hello', {});
if (!res || res.success === false) {
  // handle gracefully: skip playback, play fallback audio, or notify user
  console.warn('TTS failed, skipping playback');
}
Integration suggestions • Combine both: have
ttsQueue
call
safeSynthesize(session, text, opts)
inside its
_next()
try block so queued items are retried safely. • Ensure any errors returned from
safeSynthesize
are handled (do not rethrow). • Log queue size and
inFlight
state occasionally to detect leaks. • On session shutdown, flush or clear the queue to avoid dangling promises. If you want, I can provide the combined wrapper (queue + safe retries) as a single class you can drop into your agent. Which format would you prefer?