how to mitigate latency in livekit sip calls espec...
# ask-ai
p
how to mitigate latency in livekit sip calls especially when prompt size increases? i want a generic solution that could work for any use case.
t
Thanks for reaching out, Vaneeza. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks for reaching out! To better assist you, could you please clarify if your use case involves SIP integration with AI agents, like voice bots using speech-to-text (STT) or text-to-speech (TTS)? Also, is the increased prompt size connected to text input within an AI processing pipeline during a SIP call? I’m here to help you through this! Sources: Live Conversations with AI using ChatGPT and WebRTC | Operational Guidance & Best Practices | livekit/livekit_composite | DeepWik... | SIP Integration & Telephony | livekit/livekit_composite | DeepWiki
p
yes its the sip call integration with livekit ai agents and telnyx for sip trunking. like this, but have a lot of latency when agent instructions size increases.
Copy code
# =============================================================================
# Agent Class
# =============================================================================

class GenericBookingBot(Agent):
    """Generic booking agent with configuration baked into code"""
    def __init__(self) -> None:
        super().__init__(
            instructions=AGENT_INSTRUCTIONS
        )

    async def on_enter(self):
        """Greet the customer when they call"""
        await self.session.say(AGENT_GREETING)
# =============================================================================
# LiveKit Entrypoint
# =============================================================================

async def entrypoint(ctx: agents.JobContext):
   
    vad_provider = silero.VAD.load()
    
    await ctx.connect(auto_subscribe=agents.AutoSubscribe.AUDIO_ONLY)
    room = ctx.room  # Get room reference BEFORE session creation
    
    stt_provider = deepgram.STT(
        model="nova-2",
        language="en",
        interim_results=True,
        punctuate=True,
        smart_format=True,
        sample_rate=16000,
        no_delay=True,
        endpointing_ms=150,
        filler_words=False,
        profanity_filter=False,
        numerals=True
    )
    
    llm_provider = create_llm_provider()
    tts_provider = create_tts_provider()
    
    room_options = RoomInputOptions(
        noise_cancellation=noise_cancellation.BVC()
    )
    
    agent_instance = GenericBookingBot()
    
    session = AgentSession(
        stt=stt_provider,
        llm=llm_provider,
        tts=tts_provider,
        vad=vad_provider,
        allow_interruptions=True,  # Enable barge-in support
        false_interruption_timeout=1.0  # 1 second to filter false triggers
    )
        
    try:
        await session.start(
            room=room,  # Already initialized
            agent=agent_instance,  # Already initialized
            room_input_options=room_options,  # Already initialized
        )
and then in main:
Copy code
# Run the LiveKit agent (this blocks)
    agents.cli.run_app(
        agents.WorkerOptions(
            entrypoint_fnc=entrypoint, 
            agent_name=AGENT_NAME
        )
    )
t
I understand that dealing with latency in LiveKit SIP calls with AI agents can be quite challenging, especially as prompt sizes grow. Let’s explore some helpful strategies together to ease this: • Optimize Network Proximity: It really helps to deploy your agents closer to your LLM, STT, and TTS service providers. This way, you can reduce network latency and make things smoother. • Use LiveKit Inference: This is a great option because it keeps your AI services co-located, avoiding public internet congestion and cutting down on queuing delays. • Monitor Key Metrics: Keeping an eye on metrics like Time To First Token (TTFT) for LLM responses and Time To First Byte (TTFB) for TTS generation can really help you spot where delays might be happening. • Manage Prompt Size: Try optimizing the context by trimming chat history to just the essentials—the system prompt, the last user-agent interaction, and the current user request. Also, limiting max tokens to 1024 can prevent large responses from slowing things down. • Implement Advanced Techniques: Techniques like TTS text pacing to batch text efficiently and a fast pre-response strategy to quickly acknowledge user input while the main response is being generated can make a big difference. Also, it’s important to make sure you’re using the most efficient models for your particular needs. LiveKit Inference offers unified access to top-performing models from various providers, which can simplify your testing and optimization process. If you’re comfortable sharing more about your current network setup, metrics like TTFT and TTFB, and which providers you’re working with, I’d be happy to offer more personalized advice to help you out. Sources: Introducing LiveKit Inference: A unified model interface for voice AI | Troubleshooting & Common Issues | livekit/livekit_composite | DeepWiki | How can I reduce latency in voice agents using STT, TTS and LLM? | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real...
p
im using deepgram nova, groq llm, and deepgram tts. main issue is prompt size.
t
To help you get the best latency performance for your LiveKit SIP calls using Deepgram Nova STT, Groq LLM, and Deepgram TTS—especially when working with large prompts—here are some friendly strategies you can try: • Network Proximity: It really helps to deploy your agent in a cloud region that’s close to Deepgram and Groq services. This way, you can reduce network latency and speed things up. • STT Optimization: For real-time transcription, using Deepgram Nova-3 with settings like
noDelay: true
,
endpointing: 25ms
, and
interimResults: true
can make a big difference. • LLM Optimization: Try using Groq’s low-latency models that support streaming responses and prompt compression. Also, placing your agent near Groq Cloud can help speed up processing. • TTS Optimization: Configuring Deepgram TTS with fast response settings and considering streaming TTS can really reduce the perceived latency for your users. • Prompt Management: It’s a good idea to trim unnecessary context from your prompts and focus on the most important information. Caching repetitive prompt parts can also save time. • Monitor Metrics: Keep an eye on Time To First Token (TTFT) for LLM responses and Time To First Byte (TTFB) for TTS generation by using LiveKit’s metrics API—this helps you spot where improvements can be made. For the smoothest experience, make sure all components (STT, LLM, TTS) are set up to use streaming, which really helps cut down delays. If you’d like, I’m here to help with any specific configurations or questions you have—just let me know! Sources: How can I reduce latency in voice agents using STT, TTS and LLM? | complex-agents/drive-thru/agent_config.py | plugins/deepgram/src/stt.ts | README.md | livekit-plugins/livekit-plugins-groq/README.md
p
arent they setup to use streaming by default?
t
Hi there! Just to share a little insight, Deepgram Nova STT and Deepgram TTS come set up for streaming right out of the box when used with LiveKit integrations. However, when it comes to Groq LLM, it seems that streaming might not be enabled automatically. You might need to adjust the settings to get those streaming features up and running. If you're noticing any latency issues, it could be really helpful to double-check the streaming configuration for Groq LLM in your setup. Please feel free to reach out if you'd like a hand with how to find or enable these settings—I’m here to help! Sources: Groq and LiveKit | LiveKit Docs | livekit-plugins/livekit-plugins-deepgram/README.md | Deepgram STT plugin guide | LiveKit Docs
p
these are the metrics what seems to be the bottleneck?
Copy code
{"message": "TTS metrics", "level": "INFO", "name": "livekit.agents", "model_name": "aura-2-thalia-en", "model_provider": "Deepgram", "ttfb": 0.23983744599996726, "audio_duration": 2.52, "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:12.334305+00:00"}
2025-10-23T23:05:12.352 app[d8d9221c304668] iad [info] {"message": ":bar_chart: TTS Metrics - TTFB: 0.240s, Duration: 1.359s, Audio: 2.520s", "level": "INFO", "name": "__mp_main__", "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:12.334462+00:00"}
2025-10-23T23:05:12.581 app[d8d9221c304668] iad [info] {"message": "STT metrics", "level": "INFO", "name": "livekit.agents", "model_name": "nova-2", "model_provider": "Deepgram", "audio_duration": 4.85, "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:12.580190+00:00"}
2025-10-23T23:05:12.581 app[d8d9221c304668] iad [info] {"message": ":bar_chart: STT Metrics - Audio duration: 4.850s, Processing: 0.000s, Streamed: True", "level": "INFO", "name": "__mp_main__", "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:12.580369+00:00"}
2025-10-23T23:05:17.583 app[d8d9221c304668] iad [info] {"message": "STT metrics", "level": "INFO", "name": "livekit.agents", "model_name": "nova-2", "model_provider": "Deepgram", "audio_duration": 5.0, "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:17.582467+00:00"}
2025-10-23T23:05:17.583 app[d8d9221c304668] iad [info] {"message": ":bar_chart: STT Metrics - Audio duration: 5.000s, Processing: 0.000s, Streamed: True", "level": "INFO", "name": "__mp_main__", "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:17.582622+00:00"}
2025-10-23T23:05:21.392 app[d8d9221c304668] iad [info] {"message": "EOU metrics", "level": "INFO", "name": "livekit.agents", "end_of_utterance_delay": 1.09, "transcription_delay": 1.09, "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:21.339705+00:00"}
2025-10-23T23:05:21.392 app[d8d9221c304668] iad [info] {"message": ":bar_chart: EOU Metrics - End of utterance delay: 1.094s, Transcription delay: 1.094s", "level": "INFO", "name": "__mp_main__", "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:21.339849+00:00"}
2025-10-23T23:05:22.304 app[d8d9221c304668] iad [info] {"message": "LLM metrics", "level": "INFO", "name": "livekit.agents", "model_name": "llama-3.1-8b-instant", "model_provider": "api.groq.com", "ttft": 0.91, "prompt_tokens": 331, "prompt_cached_tokens": 0, "completion_tokens": 16, "tokens_per_second": 17.26, "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:22.302882+00:00"}
2025-10-23T23:05:22.304 app[d8d9221c304668] iad [info] {"message": ":bar_chart: LLM Metrics - TTFT: 0.914s, Duration: 0.927s, Tokens: 16, Speed: 17.3 tok/s", "level": "INFO", "name": "__mp_main__", "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:22.303040+00:00"}
2025-10-23T23:05:22.631 app[d8d9221c304668] iad [info] {"message": "STT metrics", "level": "INFO", "name": "livekit.agents", "model_name": "nova-2", "model_provider": "Deepgram", "audio_duration": 5.05, "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:22.630870+00:00"}
2025-10-23T23:05:22.632 app[d8d9221c304668] iad [info] {"message": ":bar_chart: STT Metrics - Audio duration: 5.050s, Processing: 0.000s, Streamed: True", "level": "INFO", "name": "__mp_main__", "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:22.631097+00:00"}
2025-10-23T23:05:24.240 app[d8d9221c304668] iad [info] {"message": "TTS metrics", "level": "INFO", "name": "livekit.agents", "model_name": "aura-2-thalia-en", "model_provider": "Deepgram", "ttfb": 0.2523112349999792, "audio_duration": 3.96, "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:24.239362+00:00"}
2025-10-23T23:05:24.241 app[d8d9221c304668] iad [info] {"message": ":bar_chart: TTS Metrics - TTFB: 0.252s, Duration: 1.948s, Audio: 3.960s", "level": "INFO", "name": "__mp_main__", "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:24.239530+00:00"}
2025-10-23T23:05:24.242 app[d8d9221c304668] iad [info] {"message": ":zap: TOTAL CONVERSATION LATENCY: 2.261s", "level": "INFO", "name": "__mp_main__", "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:24.239604+00:00"}
2025-10-23T23:05:24.243 app[d8d9221c304668] iad [info] {"message": " └─ EOU delay: 1.094s + LLM TTFT: 0.914s + TTS TTFB: 0.252s", "level": "INFO", "name": "__mp_main__", "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:24.239659+00:00"}
2025-10-23T23:05:27.682 app[d8d9221c304668] iad [info] {"message": "STT metrics", "level": "INFO", "name": "livekit.agents", "model_name": "nova-2", "model_provider": "Deepgram", "audio_duration": 5.05, "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:27.681067+00:00"}
2025-10-23T23:05:27.682 app[d8d9221c304668] iad [info] {"message": ":bar_chart: STT Metrics - Audio duration: 5.050s, Processing: 0.000s, Streamed: True", "level": "INFO", "name": "__mp_main__", "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:27.681251+00:00"}
2025-10-23T23:05:32.733 app[d8d9221c304668] iad [info] {"message": "STT metrics", "level": "INFO", "name": "livekit.agents", "model_name": "nova-2", "model_provider": "Deepgram", "audio_duration": 5.05, "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:32.732210+00:00"}
2025-10-23T23:05:32.733 app[d8d9221c304668] iad [info] {"message": ":bar_chart: STT Metrics - Audio duration: 5.050s, Processing: 0.000s, Streamed: True", "level": "INFO", "name": "__mp_main__", "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:32.732385+00:00"}
2025-10-23T23:05:37.783 app[d8d9221c304668] iad [info] {"message": "STT metrics", "level": "INFO", "name": "livekit.agents", "model_name": "nova-2", "model_provider": "Deepgram", "audio_duration": 5.05, "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:37.781884+00:00"}
2025-10-23T23:05:37.783 app[d8d9221c304668] iad [info] {"message": ":bar_chart: STT Metrics - Audio duration: 5.050s, Processing: 0.000s, Streamed: True", "level": "INFO", "name": "__mp_main__", "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:37.781998+00:00"}
2025-10-23T23:05:37.840 app[d8d9221c304668] iad [info] {"message": "EOU metrics", "level": "INFO", "name": "livekit.agents", "end_of_utterance_delay": 0.58, "transcription_delay": 0.52, "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:37.832686+00:00"}
2025-10-23T23:05:37.841 app[d8d9221c304668] iad [info] {"message": ":bar_chart: EOU Metrics - End of utterance delay: 0.576s, Transcription delay: 0.524s", "level": "INFO", "name": "__mp_main__", "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:37.832845+00:00"}
2025-10-23T23:05:38.034 app[d8d9221c304668] iad [info] {"message": "LLM metrics", "level": "INFO", "name": "livekit.agents", "model_name": "llama-3.1-8b-instant", "model_provider": "api.groq.com", "ttft": 0.14, "prompt_tokens": 369, "prompt_cached_tokens": 0, "completion_tokens": 38, "tokens_per_second": 191.13, "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:38.033043+00:00"}
2025-10-23T23:05:38.034 app[d8d9221c304668] iad [info] {"message": ":bar_chart: LLM Metrics - TTFT: 0.136s, Duration: 0.199s, Tokens: 38, Speed: 191.1 tok/s", "level": "INFO", "name": "__mp_main__", "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:38.033126+00:00"}
2025-10-23T23:05:42.575 app[d8d9221c304668] iad [info] {"message": "TTS metrics", "level": "INFO", "name": "livekit.agents", "model_name": "aura-2-thalia-en", "model_provider": "Deepgram", "ttfb": 0.24641100499997037, "audio_duration": 9.76, "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:42.573248+00:00"}
2025-10-23T23:05:42.578 app[d8d9221c304668] iad [info] {"message": ":bar_chart: TTS Metrics - TTFB: 0.246s, Duration: 4.592s, Audio: 9.760s", "level": "INFO", "name": "__mp_main__", "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:42.573423+00:00"}
2025-10-23T23:05:42.578 app[d8d9221c304668] iad [info] {"message": ":zap: TOTAL CONVERSATION LATENCY: 0.959s", "level": "INFO", "name": "__mp_main__", "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:42.573503+00:00"}
2025-10-23T23:05:42.578 app[d8d9221c304668] iad [info] {"message": " └─ EOU delay: 0.576s + LLM TTFT: 0.136s + TTS TTFB: 0.246s", "level": "INFO", "name": "__mp_main__", "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:42.573545+00:00"}
2025-10-23T23:05:42.831 app[d8d9221c304668] iad [info] {"message": "STT metrics", "level": "INFO", "name": "livekit.agents", "model_name": "nova-2", "model_provider": "Deepgram", "audio_duration": 5.05, "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:42.830529+00:00"}
2025-10-23T23:05:42.831 app[d8d9221c304668] iad [info] {"message": ":bar_chart: STT Metrics - Audio duration: 5.050s, Processing: 0.000s, Streamed: True", "level": "INFO", "name": "__mp_main__", "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:42.830709+00:00"}
2025-10-23T23:05:47.833 app[d8d9221c304668] iad [info] {"message": "STT metrics", "level": "INFO", "name": "livekit.agents", "model_name": "nova-2", "model_provider": "Deepgram", "audio_duration": 5.0, "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:47.831492+00:00"}
2025-10-23T23:05:47.833 app[d8d9221c304668] iad [info] {"message": ":bar_chart: STT Metrics - Audio duration: 5.000s, Processing: 0.000s, Streamed: True", "level": "INFO", "name": "__mp_main__", "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:47.831701+00:00"}
2025-10-23T23:05:51.929 app[d8d9221c304668] iad [info] {"message": "closing agent session due to participant disconnect (disable via `RoomInputOptions.close_on_disconnect=False`)", "level": "INFO", "name": "livekit.agents", "participant": "sip_+923135364365", "reason": "CLIENT_INITIATED", "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:05:51.928094+00:00"}
2025-10-23T23:06:15.495 app[d8d9221c304668] iad [info] {"message": "process exiting", "level": "INFO", "name": "livekit.agents", "reason": "", "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:06:15.495178+00:00"}
2025-10-23T23:06:15.506 app[d8d9221c304668] iad [info] {"message": ":chart_with_upwards_trend: Session Usage Summary: UsageSummary(llm_prompt_tokens=700, llm_prompt_cached_tokens=0, llm_input_audio_tokens=0, llm_completion_tokens=54, llm_output_audio_tokens=0, tts_characters_count=253, tts_audio_duration=16.240125, stt_audio_duration=40.09999999999992)", "level": "INFO", "name": "__mp_main__", "pid": 712, "job_id": "AJ_Az3hiBmXw2bo", "timestamp": "2025-10-23T23:06:15.505148+00:00"}
t
Thank you for sharing the metrics! From what I see, the main contributors to latency seem to be: • End of Utterance (EOU) Delay: This is sometimes over 1 second, which suggests there might be some delay in detecting when the user finishes speaking. Tweaking the silence detection or endpointing settings in your STT configuration could really help improve this. • LLM Time To First Token (TTFT): Although usually under 1 second, it can still slow things down, especially with larger prompts. You might find it helpful to optimize your prompts by trimming unnecessary context or caching commonly used prompt parts. • TTS Time To First Byte (TTFB): This is quite low (around 0.25 seconds), but the overall TTS duration (like 4.59 seconds for 9.76 seconds of audio) could be sped up by trying faster TTS models or enabling streaming TTS output. Here are some suggestions to help address these: • For EOU delay, try lowering the
endpointing
parameter in your STT settings to something like 25ms and make sure
noDelay
is turned on. • For LLM TTFT, focus on reducing the prompt size by including only the most relevant context, and if possible, co-locate your agent with Groq services to cut down on network latency. • For TTS, double-check that streaming is enabled and consider exploring faster TTS models if you have access to them. Please feel free to reach out if you'd like specific configuration examples or any further help—I’m here to support you!
p
how to improve EOU as that is the bottleneck for latency. in livekit?
t
To help you improve End-of-Utterance (EOU) detection latency in LiveKit, here are some friendly tips you can try: • Endpointing Delays: You might want to lower the
min_endpointing_delay
(default: 0.5s) and
max_endpointing_delay
(default: 6.0s) to speed things up a bit. For example:
Copy code
session = AgentSession(  
    min_endpointing_delay=0.2,  # Faster detection  
    max_endpointing_delay=3.0   
)
• VAD Configuration: Tweaking Voice Activity Detection (VAD) parameters can also help: • `min_silence_duration`: Try reducing it from 0.3s to 0.2s to catch silence quicker. •
activation_threshold
and `deactivation_threshold`: Adjust these based on your specific environment for better results. • Turn Detection Mode: Using the
"vad"
mode offers a nice balance between speed and reliability. Alternatively, a custom turn detection model can provide even higher accuracy. • Confidence-Based Optimization: It's great to have high-confidence predictions use
min_endpointing_delay
and let low-confidence ones use
max_endpointing_delay
. • Regional Deployment: Deploying agents closer to your AI service providers can really help reduce network latency. If you’d like, I’m here to help you implement these changes or answer any questions you might have. Just let me know!
p
{"message": "Error in _traceable_on_enter\nTraceback (most recent call last):\n File \"/home/appuser/.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 \"/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/voice/agent_activity.py\", line 434, in _traceable_on_enter\n await self._agent.on_enter()\n File \"/home/appuser/main.py\", line 147, in on_enter\n self.session.chat_context.add_assistant_message(instruction_segment)\n ^^^^^^^^^^^^^^^^^^^^^^^^^\nAttributeError: 'AgentSession' object has no attribute 'chat_context'", "level": "ERROR", "name": "livekit.agents", "pid": 713, "job_id": "AJ_UZ3N8BmJy7nz", "timestamp": "2025-10-23T233916.844402+00:00"} why this error: async def on_enter(self): """ Greet the user and then add the rest of the instructions to the chat history. This gives the LLM the full context without a long initial system prompt. """ # 1. Add follow-up instructions to the chat history as assistant messages for instruction_segment in self._follow_up_instructions: self.session.chat_context.add_assistant_message(instruction_segment) # 2. Greet the user await self.session.say(self._greeting)
t
It looks like the error is happening because the
AgentSession
class doesn’t have a
chat_context
attribute. The good news is that managing the chat context is actually handled by the
Agent
class, which gives you access to the conversation history through the
chat_ctx
property. Here’s how you can fix this: • Make sure to access the chat context via the
Agent
instance, not the
AgentSession
. • Use
Agent.update_chat_ctx()
whenever you want to update the chat context during runtime. • Also, double-check that your agent is initialized with a proper
ChatContext
object. For example:
Copy code
# Initialize chat context
chat_ctx = llm.ChatContext.empty()
chat_ctx.add_message(role="assistant", content="Hello!")

# Initialize agent with chat context
agent = Agent(
    instructions="You are a helpful assistant.",
    chat_ctx=chat_ctx,
)

# Start session with the agent
session = AgentSession()
await session.start(agent=agent, room=ctx.room)
And don’t forget to update your
on_enter
method to work with the agent’s
chat_ctx
like this:
Copy code
async def on_enter(self):
    for instruction_segment in self._follow_up_instructions:
        self.chat_ctx.add_message(role="assistant", content=instruction_segment)
    await self.session.say(self._greeting)
If anything isn’t clear or you’d like me to walk you through it step-by-step, just let me know—I’m here to help! Sources: livekit-agents/livekit/agents/voice/room_io/room_io.py | Agents v0.x migration guide - Python | LiveKit Docs | livekit/agent/livekit_agent_session.pb.go
p
why i still get this error then?
Copy code
timestamp": "2025-10-23T23:46:05.667590+00:00"}
2025-10-23T23:46:05.679 app[286010dc74d998] iad [info] {"message": "Error in _traceable_on_enter\nTraceback (most recent call last):\n File \"/home/appuser/.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 \"/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/voice/agent_activity.py\", line 434, in _traceable_on_enter\n await self._agent.on_enter()\n File \"/home/appuser/main.py\", line 147, in on_enter\n self.chat_ctx.add_message(role=\"assistant\", content=instruction_segment)\n File \"/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/llm/chat_context.py\", line 211, in add_message\n self._items.append(message)\n File \"/home/appuser/.local/lib/python3.11/site-packages/livekit/agents/llm/chat_context.py\", line 519, in _raise_error\n raise RuntimeError(_ReadOnlyChatContext.error_msg)\nRuntimeError: trying to modify a read-only chat context, please use .copy() and agent.update_chat_ctx() to modify the chat context", "level": "ERROR", "name": "livekit.agents", "pid": 713, "job_id": "AJ_TE6X9Bx4m2V8", "timestamp": "2025-10-23T23:46:05.667882+00:00"}
t
It looks like the error happens because the chat context is read-only while the agent is running. No worries, though! You can fix this by creating a mutable copy of the chat context, making your changes there, and then updating the agent's context. Here's a simple way to do it: 1. Create a copy of the chat context:
Copy code
new_ctx = self.chat_ctx.copy()
1. Modify the copied context:
Copy code
new_ctx.add_message(role="assistant", content=instruction_segment)
1. Update the agent's chat context:
Copy code
await self.update_chat_ctx(new_ctx)
Here's how you can update your
on_enter
method:
Copy code
async def on_enter(self):
    new_ctx = self.chat_ctx.copy()
    for instruction_segment in self._follow_up_instructions:
        new_ctx.add_message(role="assistant", content=instruction_segment)
    await self.update_chat_ctx(new_ctx)
    await self.session.say(self._greeting)
This approach helps keep everything safe and respects the read-only rule. If you have any questions or want me to walk you through it, just let me know—I’m here to help!