m
hi
t
Thanks for reaching out, Rahib. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hi there! How can I help you today? I'm here to make sure you get the support you need.
m
QUESTION 1: AgentTask Session Access In AgentTask, how do I access the session to call generate_reply()? Example needed for on_enter(): async def on_enter(self): # How to generate initial prompt? # Is it self.session.generate_reply()? # Or does the task automatically prompt based on instructions? QUESTION 2: Speech Handle Tracking For hallucination prevention: 1. Is ctx.speech_handle the correct way to track speech? 2. Does speech_handle change between tool calls? 3. Should I compare speech_handle identity (==) or use another method? Example: if ctx.speech_handle == self._last_update_speech_handle: raise ToolError("Wait for user confirmation") QUESTION 3: Task Completion When calling self.complete(result): 1. Does this automatically end the task and return control to agent? 2. Should I await it? (await self.complete() vs self.complete()) 3. Can I call generate_reply after complete() for confirmation message? Example: self.complete(CollectedClientInfo(...)) # Does execution stop here? # Or should I return immediately after? QUESTION 4: Task Exception Handling If a tool raises ToolError inside the task: 1. Does the task stay active and retry? 2. Does it bubble up to the agent? 3. Should I catch exceptions in on_enter()? QUESTION 5: Chat Context Preservation When passing chat_ctx to task: CollectClientInfoTask(chat_ctx=turn_ctx) 1. What is turn_ctx exactly? (is it llm.ChatContext?) 2. Does the task see full conversation history? 3. Can the task add to conversation context?
where should i set userdata in the entrypoint or in the on_enter of Agent?
t
Set userdata in the entrypoint function. When working with LiveKit, it's best to initialize userdata right in the entrypoint function. This is because userdata needs to be passed when creating the
AgentSession
. The entrypoint sets up the session, so having userdata ready at this stage ensures it’s available throughout the agent’s lifecycle. On the other hand, the
on_enter
method runs after the session has started and is mainly for kicking off agent behaviors, like greeting users. By then, userdata should already be set up and easy to access through
self.session.userdata
. If you’d like, I’m happy to share an example or explain anything further—just let me know! Sources: livekit-agents/livekit/agents/voice/agent_session.py | Workflows | LiveKit Docs | Job lifecycle | LiveKit Docs | complex-agents/drive-thru/session_setup.py
It looks like the error happens because OpenTelemetry attributes need to be primitive types (like strings, numbers, booleans) or sequences of those. Dataclasses such as
ReceptionistState
aren’t directly serializable, which is why the issue pops up when you try to log them as attributes. Here’s a friendly way to fix this: 1. Pull out just the serializable fields from your dataclass. For example:
Copy code
from opentelemetry import trace
import json

span = trace.get_current_span()

# Serialize only the necessary fields
safe_data = {
    "current_phase": userdata.current_phase,
    "phase_history": userdata.phase_history,
    "caller_id": userdata.caller_id,
    "call_started_at": userdata.call_started_at.isoformat(),
}

span.set_attribute("lk.userdata", json.dumps(safe_data))
1. Make sure all fields in your dataclass can be converted to JSON. For instance, leave out complex objects like tasks or contexts, or add a method in your dataclass that returns a clean dictionary:
Copy code
@dataclass
class ReceptionistState:
    ...
    def to_telemetry_dict(self):
        return {
            "current_phase": self.current_phase,
            "phase_history": self.phase_history,
            "caller_id": self.caller_id,
            "call_started_at": self.call_started_at.isoformat(),
        }
1. Then use this method to log the cleaned-up data:
Copy code
span.set_attribute("lk.userdata", json.dumps(userdata.to_telemetry_dict()))
If you’d like, I’m here to help with more examples or any other questions you might have! Sources: Docs::Agents | livekit-agents/livekit/agents/types.py
m
is this correct?
Copy code
def _create_elevenlabs_tts(self, **config):
        """Create ElevenLabs TTS with natural speech configuration."""
        # Voice settings need to be in a separate VoiceSettings object
        voice_settings = elevenlabs.VoiceSettings(
            stability=0.35,  # Lower for more expressiveness
            similarity_boost=0.65,  # Enhance voice characteristics
            style=0.20,  # Add subtle emotional variation
            use_speaker_boost=True,  # Enhance speaker characteristics
        )

        defaults = {
            "voice_id": "UgBBYS2sOqTuMpoF3BR0",
            "model": "eleven_multilingual_v2",  # Better for natural speech
            "language": "en",
            "voice_settings": voice_settings,
            "streaming_latency": 2,  # Reduce from default 3 for responsiveness
            "enable_ssml_parsing": True,  # Enable SSML tags for natural speech
            "api_key": os.getenv("ELEVEN_API_KEY"),
        }
        defaults.update(config)
        return elevenlabs.TTS(**defaults)
t
It looks like your implementation of ElevenLabs TTS creation is spot on and follows the best practices for LiveKit. Using
VoiceSettings
to set parameters like
stability
,
similarity_boost
,
style
, and
use_speaker_boost
is definitely the right way to go. Also, passing these settings to the
TTS
constructor is exactly what we recommend. If you have any questions or want to chat more about this, please don’t hesitate to reach out—I’m here to help! Sources: ElevenLabs TTS plugin guide | LiveKit Docs | plugins/elevenlabs/src/tts.ts | Text-to-speech (TTS) models | LiveKit Docs | livekit-plugins/livekit-plugins-elevenlabs/livekit/plugins/elevenlabs/__ini... | complex-agents/drive-thru/agent_config.py
m
then why am i getting this error ?
Copy code
2025-10-03 17:48:48,091 - WARNING livekit.agents - failed to synthesize speech, retrying in 2.0s {"room_name": "mock_room", "tts": "livekit.plugins.elevenlabs.tts.TTS", "attempt": 3, "streamed": true}
Traceback (most recent call last):
  File "/Users/reverse/PycharmProjects/cmetric/cmetric-voicekit/.venv/lib/python3.13/site-packages/livekit/agents/tts/tts.py", line 357, in _main_task
    await self._run(output_emitter)
  File "/Users/reverse/PycharmProjects/cmetric/cmetric-voicekit/.venv/lib/python3.13/site-packages/livekit/plugins/elevenlabs/tts.py", line 429, in _run
    raise e
  File "/Users/reverse/PycharmProjects/cmetric/cmetric-voicekit/.venv/lib/python3.13/site-packages/livekit/plugins/elevenlabs/tts.py", line 424, in _run
    await waiter
livekit.agents._exceptions.APIStatusError: connection closed (status_code=-1, request_id=None, body=None, retryable=True)
t
I'm sorry you're encountering the
APIStatusError: connection closed
error. This usually happens because of some hiccups with the ElevenLabs TTS WebSocket connection. Let’s walk through some steps together to help you troubleshoot and hopefully resolve it: 1. Verify API Key: Please double-check that your
ELEVEN_API_KEY
environment variable is set correctly and is valid. 2. Check Network Connectivity: Make sure your agent can access
wss://api.elevenlabs.io
without any blocks. Sometimes firewalls or network policies can get in the way of WebSocket connections. 3. Adjust Inactivity Timeout: If the connection stays idle for too long, it might close. Try increasing the
inactivity_timeout
parameter when you initialize the TTS object. 4. Ensure Proper Text Formatting: It’s important that your input text is properly formatted, including complete SSML tags and a trailing space if you’re using streaming mode. 5. Avoid Premature Stream Closure: Make sure the TTS stream isn’t closed before all the audio is synthesized — avoid calling
stream.aclose()
too early. 6. Retry Logic: Since the Python plugin doesn’t have built-in retries, adding retry logic can help with temporary network glitches. 7. Use Correct Initialization: Double-check that the
voice_id
and
model
parameters you’re passing to the TTS constructor are correct, as invalid values can cause connection errors. If you’re still having trouble after trying these steps, enabling debug logs in your LiveKit agent can give you more detailed info about the WebSocket events and error messages. Please feel free to reach out if you need any more help — I’m here for you! Sources: ElevenLabs TTS | LiveKit Docs | plugins/elevenlabs/src/tts.ts | Example Applications | livekit/livekit_composite | DeepWiki | Diagnosing Connection Errors with Connection Test Utility | livekit-plugins/livekit-plugins-inworld/livekit/plugins/inworld/tts.py