i am constantly getting these types of errors (usi...
# ask-ai
e
i am constantly getting these types of errors (using livekit cloud and cartesia). what can i do to fix them? {"message": "Error in _tts_inference_task\nTraceback (most recent call last):\n File \"/usr/local/lib/python3.11/site-packages/livekit/plugins/cartesia/tts.py\", line 387, in _run\n await asyncio.gather(*tasks)\n File \"/usr/local/lib/python3.11/site-packages/livekit/plugins/cartesia/tts.py\", line 353, in _recv_task\n raise APIError(f\"Cartesia returned error: {data}\")\nlivekit.agents._exceptions.APIError: Cartesia returned error: {'type': 'error', 'context_id': '8043f4ffa8e0', 'status_code': 400, 'done': True, 'error': 'transcript empty or contains only punctuation: first transcript for WS is empty or contains only punctuation'} (body=None, retryable=True)\n\nThe above exception was the direct cause of the following exception:\n\nTraceback (most recent call last):\n File \"/usr/local/lib/python3.11/site-packages/livekit/agents/utils/log.py\", line 16, in async_fn_logs\n return await fn(*args, **kwargs)\n ^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/usr/local/lib/python3.11/site-packages/opentelemetry/util/_decorator.py\", line 71, in async_wrapper\n return await func(*args, **kwargs) # type: ignore\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/usr/local/lib/python3.11/site-packages/livekit/agents/voice/generation.py\", line 212, in _tts_inference_task\n async for audio_frame in tts_node:\n File \"/usr/local/lib/python3.11/site-packages/livekit/agents/voice/agent.py\", line 408, in tts_node\n async for ev in stream:\n File \"/usr/local/lib/python3.11/site-packages/livekit/agents/tts/tts.py\", line 532, in __anext__\n raise exc # noqa: B904\n ^^^^^^^^^\n File \"/usr/local/lib/python3.11/site-packages/opentelemetry/util/_decorator.py\", line 71, in async_wrapper\n return await func(*args, **kwargs) # type: ignore\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/usr/local/lib/python3.11/site-packages/livekit/agents/tts/tts.py\", line 357, in _main_task\n await self._run(output_emitter)\n File \"/usr/local/lib/python3.11/site-packages/livekit/plugins/cartesia/tts.py\", line 398, in _run\n raise APIConnectionError() from e\nlivekit.agents._exceptions.APIConnectionError: Connection error. (body=None, retryable=True)", "level": "ERROR", "name": "livekit.agents", "pid": 57, "job_id": "AJ_CLxvjJAZB9Xs", "timestamp": "2025-10-13T003117.995674+00:00"} livekit-agent October 12, 2025, 17:31 {"message": "failed to synthesize speech, retrying in 2.0s\nTraceback (most recent call last):\n File \"/usr/local/lib/python3.11/site-packages/livekit/plugins/cartesia/tts.py\", line 387, in _run\n await asyncio.gather(*tasks)\n File \"/usr/local/lib/python3.11/site-packages/livekit/plugins/cartesia/tts.py\", line 353, in _recv_task\n raise APIError(f\"Cartesia returned error: {data}\")\nlivekit.agents._exceptions.APIError: Cartesia returned error: {'type': 'error', 'context_id': 'a7e680f9767f', 'status_code': 400, 'done': True, 'error': 'transcript empty or contains only punctuation: first transcript for WS is empty or contains only punctuation'} (body=None, retryable=True)\n\nThe above exception was the direct cause of the following exception:\n\nTraceback (most recent call last):\n File \"/usr/local/lib/python3.11/site-packages/livekit/agents/tts/tts.py\", line 357, in _main_task\n await self._run(output_emitter)\n File \"/usr/local/lib/python3.11/site-packages/livekit/plugins/cartesia/tts.py\", line 398, in _run\n raise APIConnectionError() from e\nlivekit.agents._exceptions.APIConnectionError: Connection error. (body=None, retryable=True)", "level": "WARNING", "name": "livekit.agents", "tts": "livekit.plugins.cartesia.tts.TTS", "attempt": 3, "streamed": true, "pid": 57, "job_id": "AJ_CLxvjJAZB9Xs", "timestamp": "2025-10-13T003115.695745+00:00"}
t
Thanks for reaching out, Jason. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm here to help you with the errors you're encountering with Cartesia TTS in LiveKit Cloud. Let's walk through some steps together to get things running smoothly: 1. Resolving 'transcript empty or contains only punctuation' Error: • First, please make sure the input text actually contains meaningful words and isn't empty or just punctuation. • Take a look at your text processing pipeline to confirm that sentence tokenization and text generation are working properly. • Try enabling or configuring text pacing to better handle edge cases:
Copy code
tts = cartesia.TTS(
    text_pacing=True,  # Enable default pacer
    # or use custom pacer
    text_pacing=tts.SentenceStreamPacer()
)
2. Resolving 'APIConnectionError': • Double-check that your Cartesia API key is correctly set, either in your environment variables or passed directly like this:
Copy code
# Set in environment
CARTESIA_API_KEY=your_api_key_here

# Or pass directly
tts = cartesia.TTS(api_key="your_api_key_here")
• If your connection is slow, try increasing the timeout settings:
Copy code
from livekit.agents import APIConnectOptions

conn_options = APIConnectOptions(timeout=30.0)  # Increase timeout
stream = tts.synthesize("text", conn_options=conn_options)
• Prewarming the connection pool can also help prevent session issues:
Copy code
tts.prewarm()  # Prewarm the connection pool
• Lastly, make sure the base URL is accessible and correctly configured:
Copy code
tts = cartesia.TTS(
    base_url="https://api.cartesia.ai"  # Default, but can be customized
)
Additional Steps: • Turning on detailed logging can give us more insight if problems persist:
Copy code
import logging
logging.getLogger("livekit.plugins.cartesia").setLevel(logging.DEBUG)
• Also, it’s a good idea to check your Cartesia API dashboard to review your quota limits, service status, and permissions. If you try these suggestions and still face issues, please don’t hesitate to reach out. I’m here to support you and we can explore other solutions together! Sources: livekit-plugins/livekit-plugins-sarvam/livekit/plugins/sarvam/tts.py | Cartesia TTS plugin guide | LiveKit Docs
e
is there a way to see what the LLM is sending to cartesia?
t
I'd be happy to help you see what the LLM is sending to Cartesia by enabling logging of the input text in the TTS pipeline. Here are some friendly methods you can try: 1. Enable TTS-Aligned Transcriptions: You can set
use_tts_aligned_transcript=True
in the
AgentSession
configuration. This will help you log the text chunks being sent to the TTS engine along with timing metadata:
Copy code
async def transcription_node(
    self, text: AsyncIterable[str | TimedString], model_settings: ModelSettings
) -> AsyncGenerator[str | TimedString, None]:
    async for chunk in text:
        if isinstance(chunk, TimedString):
            logger.info(f"TimedString: '{chunk}' ({chunk.start_time} - {chunk.end_time})")
        else:
            logger.info(f"Text chunk: '{chunk}'")
        yield chunk
2. Monitor Transcription Output: Agents publish transcriptions to the
lk.transcription
text stream topic. You can register handlers to receive and log these streams using the LiveKit SDKs, which is quite handy. 3. Client-Side Text Stream Logging: If you’re working on a frontend application, you can set up text stream logging to capture and log text streams published by the agent. For example, in a React app, you might do:
Copy code
room.registerTextStreamHandler('lk.transcription', handler);
Please feel free to reach out if you'd like any help implementing these methods or if you have any questions along the way. I'm here to support you! Sources: avatars/hedra/education_avatar/education-frontend/hooks/useTextStreamLogger... | Sending text | LiveKit Docs | Text and transcriptions | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py
e
i added logging and see this:
t
Could you please share the specific logs or details you’re seeing after enabling logging? That way, I can better understand what’s happening and help identify any issues or confirm the input being sent to Cartesia. I’m here to help!
e
it's in the snippet
t
I'd be happy to help! Could you please let me know which snippet you're referring to? If you can, sharing the specific part of the logs that seems relevant or is causing concern would be really helpful.
e
here's what cursor said: Looking at the logs you shared, here's the key excerpt that shows the issue: ## 🔍 The Problem: Empty TTS Streams
Copy code
bash
:arrows_counterclockwise: TTS NODE START: Processing text stream
:arrows_counterclockwise: TTS NODE FINAL TEXT: ''
:mag: TEXT PIPELINE [TTS_NODE_FINAL]: ''
:mag: TEXT ANALYSIS [TTS_NODE_FINAL]:
  - Length: 0
  - Stripped length: 0
  - Has alphanumeric: False
  - Is only punctuation: False
  - Raw bytes: b''
  - Character codes: []
This pattern appears multiple times in your logs, showing that the TTS node is receiving completely empty text streams initially. ## 🎯 The Issue Explained 1. Empty Stream Detection: The
TTS_NODE_FINAL
text is empty (
Length: 0
) 2. No Content:
Has alphanumeric: False
and
Is only punctuation: False
3. Empty Bytes:
Raw bytes: b''
shows completely empty content 4. No Characters:
Character codes: []
shows no characters at all ## 🔄 What Happens Next After the empty stream, the chunks start coming through properly:
Copy code
bash
:arrows_counterclockwise: TTS CHUNK: 'Hi' (length: 2)
:arrows_counterclockwise: TTS CHUNK: ' -' (length: 2)
:arrows_counterclockwise: TTS CHUNK: ' I' (length: 2)
# ... more chunks follow
## 🚨 Why This Causes Cartesia Errors Cartesia receives the empty stream first before the actual text chunks arrive. This triggers the "transcript empty or contains only punctuation" error because: 1. Cartesia gets an empty text stream initially 2. It tries to process the empty content 3. It fails with the error you're seeing 4. Then the actual text chunks arrive (too late) ## 💡 The Fix Needed The issue is that the TTS node is processing an empty stream before the actual text is ready. This is a timing/streaming issue where Cartesia gets called with empty content before the real text arrives. This explains why you get the Cartesia errors intermittently - it depends on the timing of when the empty stream vs. the actual text chunks arrive at the TTS system.
t
I'm sorry to hear you're running into this issue. It seems that empty text streams are being sent to Cartesia before the actual text chunks are ready, which is likely a timing or streaming hiccup. Don’t worry, I’m here to help you through it! Here are some friendly steps to get things running smoothly: 1. Validate Text Chunks: • Make sure each text chunk you send to the TTS pipeline actually has meaningful content. Try to avoid sending empty strings or chunks that only have whitespace. • Here’s a simple validation function you can use to filter out those empty or invalid chunks:
Copy code
def validate_text_chunk(chunk: str) -> bool:
    if not chunk or not chunk.strip():
        return False
    if len(chunk.strip().split()) < 2:  # Less than 2 words
        return False
    return True
2. Configure Tokenizer Settings: • Using a properly set-up tokenizer can really help with breaking down your text chunks effectively:
Copy code
from livekit.agents import tokenize

tokenizer = tokenize.blingfire.SentenceTokenizer()
3. Handle Streaming Properly: • It's best to buffer your text and send it in meaningful chunks rather than character-by-character or tiny fragments. Here’s an example:
Copy code
# Example of chunking text
words = text.split()
for i in range(0, len(words), 2):
    chunk = " ".join(words[i : i + 2])
    if chunk:
        stream.push_text(chunk + " ")
4. Use StreamAdapter for Consistency: • If you find timing issues are still popping up, wrapping your TTS instance with a StreamAdapter can help manage streaming more predictably:
Copy code
from livekit.agents.tts import StreamAdapter

tts_wrapped = StreamAdapter(tts=tts, sentence_tokenizer=tokenizer)
stream = tts_wrapped.stream()
5. Monitor and Debug: • Turning on detailed logging can give you a clearer picture of what’s being sent to Cartesia:
Copy code
import logging
logging.getLogger("cartesia").setLevel(logging.DEBUG)
• Keep an eye out for any warnings about empty or invalid chunks in the logs. By following these steps, you should be able to make sure Cartesia receives meaningful text streams and avoid the "transcript empty or contains only punctuation" error. If you hit any snags or want to chat more about this, just let me know—I’m here to help! Sources: plugins/cartesia/src/tts.ts | livekit-agents/livekit/agents/inference/tts.py