session manager call marge
# ask-ai
p
session manager call marge
t
Thanks for reaching out, arpan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thank you for reaching out! Could you please help me understand a bit more about what you mean by "session manager call merge"? Are you talking about merging sessions, managing calls, or something else? The more details you can share, the better I can assist you. I'm here to help!
p
i have facing problem when marge the call @observe() async def entrypoint(ctx: JobContext): """Main entrypoint for the LiveKit agent""" try: inactivity_task: asyncio.Task | None = None room_id = str(uuid.uuid4()) print(room_id) # Set up Langfuse trace_provider = setup_langfuse( metadata={ "langfuse.session.id": ctx.room.name, "langfuse.session": ctx.room.metadata, } ) async def flush_trace(): trace_provider.force_flush() ctx.add_shutdown_callback(flush_trace) # # Set up recording # req = api.RoomCompositeEgressRequest( # room_name=ctx.room.name, # audio_only=True, # file_outputs=[ # api.EncodedFileOutput( # file_type=api.EncodedFileType.MP4, # filepath=f"recordings/{datetime.now().strftime('%Y-%m-%d %H-%M-%S')}", # s3=api.S3Upload( # access_key=os.getenv("AWS_ACCESS_KEY_ID"), # secret=os.getenv("AWS_SECRET_ACCESS_KEY"), # region=os.getenv("AWS_REGION"), # bucket="holionix-voice-agent", # ), # ), # ], # ) # lkapi = api.LiveKitAPI() # await lkapi.egress.start_room_composite_egress(req) print("🚀 Starting LiveKit agent...") await ctx.connect() save_txt("Room Created\n","Artifacts/liveEvents.txt") print("✅ Agent created with tools") print("✅ Connecting to room") # Create the information tool # Wait for participant print("⏳ Waiting for participant...") participant = await ctx.wait_for_participant() # Initialize transcription logger transcription_logger = TranscriptionLogger( mongo_uri=os.getenv("MONOGO_DB_URI"), db_name=os.getenv("MONGODB_DB_NAME_TRANSCRIPTION") ) # Intilaize call info logger caller_info= CallLogger( mongo_uri=os.getenv("MONOGO_DB_URI"), db_name="caller_info" ) # Create session with error handling for each component print("🔧 Creating session components...") try: vad = silero.VAD.load( force_cpu=True ) print("✅ VAD loaded") models = model_config.get_models() stt = models.get('stt') print("✅ STT configured") llm = models.get('llm') print("✅ LLM configured") tts = models.get('tts') except Exception as e: print(f"❌ TTS error: {e}") raise CustomException(e,sys) print("✅ Session created") session = AgentSession( preemptive_generation=True, ) print("✅ Transcription logging set up") # Set up transcription logging # Check if this is a SIP call and initialize logging is_sip_call = ( hasattr(participant, 'kind') and participant.kind == rtc.ParticipantKind.PARTICIPANT_KIND_SIP ) current_call_id = caller_info.start_call(participant) # Start transcription logging for both SIP and web calls if current_call_id: call_type = "SIP" if is_sip_call else "WEB" print(f"📞 {call_type} Call detected - Call ID: {current_call_id}") if is_sip_call: print(f"📱 Caller: {participant.attributes.get('sip.phoneNumber', 'Unknown')}") transcription_logger.start_transcription(session_id=current_call_id, room_id=room_id, session=session, mode=call_type) logging.info(f"Call logging started for call ID: {current_call_id}") else: print("⚠️ Failed to start call logging") agent = HolionixAgent( stt=stt, llm=llm, tools=[info_tool], vad=vad, tts=tts, ) async def user_presence_task(): # try to ping the user 3 times, if we get no answer, close the session for _ in range(3): await session.generate_reply( instructions=( "The user has been inactive. Politely check if the user is still present." ) ) await asyncio.sleep(5) await asyncio.shield(session.aclose()) ctx.delete_room() save_txt("USER STOP REESPONSE","Artifacts/liveevents.txt") time.sleep(2) os.remove("Artifacts/liveEvents.txt") @session.on("user_state_changed") def _user_state_changed(ev: UserStateChangedEvent): nonlocal inactivity_task if ev.new_state == "away": inactivity_task = asyncio.create_task(user_presence_task()) return # ev.new_state: listening, speaking, .. if inactivity_task is not None: inactivity_task.cancel() @session.on("metrics_collected") def _on_metrics_collected(ev: MetricsCollectedEvent): metrics.log_metrics(ev.metrics) # Start the session await session.start(agent=agent, room=ctx.room,room_input_options=RoomInputOptions(close_on_disconnect=False,audio_enabled=True),) print("✅ Session started") print("✅ Initial greeting sent") save_txt("Room Connected\n","Artifacts/liveEvents.txt") SUPERVISOR_PHONE_NUMBER = "+916290438432" session_manager = SessionManager( ctx=ctx, customer_room=ctx.room, customer_session=session, supervisor_contact=SUPERVISOR_PHONE_NUMBER, lkapi=ctx.api, ) agent.session_manager = session_manager await session_manager.start() print("🎙️ Agent is now active and listening...") logging.info("Agent is now active and listening...") # Set up comprehensive transcription event handlers @session.on("user_speech_committed") def on_user_speech(event): """Handle user speech transcription""" if transcription_logger and hasattr(event, 'user_transcript') and event.user_transcript: transcription_logger.log_user_speech(event.user_transcript) lang = detect(event.user_transcript) @session.on("agent_speech_committed") def on_agent_speech(event): """Handle agent speech transcription""" if transcription_logger and hasattr(event, 'agent_transcript') and event.agent_transcript: transcription_logger.log_agent_response(event.agent_transcript) # Additional event handlers for comprehensive logging @session.on("conversation_item_added") def on_conversation_item(event): """Handle conversation items (covers both user and agent messages)""" if transcription_logger and hasattr(event, 'item'): item = event.item if hasattr(item, 'content') and item.content: # Determine speaker based on item type or role speaker = "USER" if hasattr(item, 'role') and item.role == 'user' else "AGENT" transcription_logger.log_transcription(item.content, is_final=True, speaker=speaker) # Handle session end and participant disconnect @ctx.room.on("participant_disconnected") def on_participant_disconnected(participant): """Handle participant disconnect - save transcription to MongoDB""" if current_call_id and transcription_logger: print(f"📞 Participant disconnected - saving transcription for call {current_call_id}") _, transcription = transcription_logger.close_transcription() caller_info.end_call(current_call_id,transcription) save_txt("User Left\n","Artifacts/liveEvents.txt") print(f"✅ Call {current_call_id} ended and transcription saved to MongoDB") # Handle room disconnect @ctx.room.on("disconnected") def on_room_disconnected(): """Handle room disconnect - ensure transcription is saved""" if current_call_id and transcription_logger: print(f"🏠 Room disconnected - saving transcription for call {current_call_id}") _, transcriptions = transcription_logger.close_transcription() caller_info.end_call(current_call_id,transcriptions) transcription_logger.remove_txt() print(f"✅ Call {current_call_id} ended and transcription saved to MongoDB") ctx.delete_room() save_txt("Room Deleted\n","Artifacts/liveEvents.txt") os.remove("Artifacts/liveEvents.txt") print(f"✅ Room {ctx.room.name} Deleted") # await lkapi.aclose() except Exception as e: error_msg = f"Voice agent error: {e}" print(f"❌ {error_msg}") logging.error(error_msg) raise CustomException(e, sys)
t
Let's work together to troubleshoot the issues you're experiencing with merging calls using the provided code. Here are some important areas to focus on: • Verify Supervisor Call Status: Make sure the supervisor's call is answered and the status is set correctly to "summarizing." If the call goes to voicemail, you can handle it using the
voicemail_detected()
method. • Validate Room and Participant Details: It's important to confirm that the room names and participant identities exactly match when you call the
move_participant
API. • Enable Detailed Logging: Try setting the logging level to DEBUG so you can capture detailed error messages and stack traces for the
merge_calls()
method. This can give you more insight into what's happening. • Check API Permissions: Please ensure that your API key has the necessary permissions (like
room:admin
or
room:write
) and that your LiveKit server version supports the
move_participant
endpoint. • Test Media Compatibility: Verify that the supervisor and customer can connect and interact in the same room, especially if the supervisor is connecting via SIP. • Isolate the Issue: It might help to test the
move_participant
API separately using a standalone script to make sure it works independently of the agent logic. If you continue to face challenges, consider reviewing the server logs or enabling webhook notifications for real-time event tracking. Please feel free to reach out if you'd like any help walking through these steps—I’m here to support you! Sources: livekit-plugins/livekit-plugins-ultravox/livekit/plugins/ultravox/realtime/... | README.md | SIP troubleshooting guide | LiveKit Docs | Getting Help & Troubleshooting | livekit/livekit_composite | DeepWiki
p
ok fine tell me or provide me any code with memory of conversation like when user taking with agent agent sholuld have knowledge of previous conversation also
t
I'm happy to guide you through implementing conversation memory for agents in LiveKit! Here are some helpful steps to get you started: • Preserve Context: You can use the
chat_ctx
parameter to smoothly transfer conversation history between agents, which helps keep the conversation flowing naturally during handoffs. • Truncate History: It’s a good idea to trim the chat history to just the most recent messages. This way, you save on token usage while still keeping the important context. • Persist History: To maintain memory across sessions, you might want to store
session.history
externally in a database like PostgreSQL or Redis. • Enhance Memory: For even richer memory features—like semantic recall or personalized interactions—consider integrating external tools such as Letta or LlamaIndex. • Load History: Plugins like the OpenAI Realtime API can be really helpful to preload past conversation history into your session prompt. If you’d like, I can provide a code example for any of these steps—whether it’s setting up database integration or handling context transfer between agents. Just let me know what would be most useful for you! Sources: examples/voice_agents/restaurant_agent.py | complex-agents/medical_office_triage/triage.py | Workflows | LiveKit Docs | Sending text | LiveKit Docs | External data and RAG | LiveKit Docs
p
example i have to pass diffrent agent class
t
I'm happy to guide you through passing conversation context between different agent classes in LiveKit! Here's a simple approach you can follow: • Use a Shared UserData Class: Start by creating a
UserData
class to keep shared state, like previous agent context and any custom session data you want to hold onto. • Implement a BaseAgent Class: This base class can manage the context transfer logic. It copies and truncates the previous agent’s
chat_ctx
so you keep the important parts of the conversation history. • Truncate Context: It’s helpful to have a method that trims the context to just the most recent messages. This way, you save on token usage but don’t lose the key information. • Enable Agent Transfers: Using
function_tool
decorators allows smooth control transfers between agents while keeping the context intact. Here’s a friendly example showing how you might transfer context:
Copy code
class BaseAgent(Agent):
    async def on_enter(self):
        userdata = self.session.userdata
        chat_ctx = self.chat_ctx.copy()

        if userdata.prev_agent:
            truncated_chat_ctx = userdata.prev_agent.chat_ctx.copy(
                exclude_instructions=True, 
                exclude_function_call=False
            ).truncate(max_items=6)

            existing_ids = {item.id for item in chat_ctx.items}
            items_copy = [item for item in truncated_chat_ctx.items if item.id not in existing_ids]
            chat_ctx.items.extend(items_copy)

        await self.update_chat_ctx(chat_ctx)
If you'd like, I can also provide a full example with multiple agent classes or dive deeper into any particular step. Just let me know—I'm here to help! Sources: pipeline-tts/tts_comparison/README.md | examples/voice_agents/restaurant_agent.py | Workflows | LiveKit Docs | Building Multi-Agent Architectures with LiveKit Agents
p
i want to print user and agent speech word by word real time help me on tat
t
To help you print user and agent speech word by word in real-time, here’s a simple guide you can follow: • Enable Synchronized Transcription: Make sure to set
sync_transcription=True
in
RoomOutputOptions
. This ensures words are forwarded exactly as they’re spoken, which is key for real-time display. • Stream Transcriptions: On the frontend, subscribe to the
lk.transcription
topic. This way, you’ll receive each word incrementally and can show them right away. • Use TTS-Aligned Transcription: If you’re working with Cartesia or ElevenLabs, enable
use_tts_aligned_transcript=True
to get precise word-level timing, making your transcription even more accurate. • Access Timing Data: In your agent class, implement the
transcription_node()
method. This allows you to print each word along with its start and end times, giving you detailed insight. Here’s a quick example to illustrate real-time word-by-word transcription:
Copy code
async def transcription_node(self, text: str, start_time: float, end_time: float):
    print(f"Word: '{text}', starts at {start_time:.2f}s, ends at {end_time:.2f}s")
If you’d like, I’m happy to provide a complete example tailored to your setup—whether that’s frontend integration or a Python backend implementation. Just let me know! Sources: Text and transcriptions | LiveKit Docs | pipeline-stt/transcriber/README.md | livekit-agents/livekit/agents/voice/agent_activity.py
p
other way sto save word by word transcription showing in frontend
t
To help you save and display word-by-word transcription for both user and agent speech on the frontend, here’s a simple step-by-step guide you can follow: • Enable Real-Time Transcriptions: Make sure to set
sync_transcription=True
in
RoomOutputOptions
. This lets you forward words as they’re being spoken, so nothing gets missed. • Stream Transcriptions: On your frontend, you can use
useTrackTranscription
or listen for the
RoomEvent.TranscriptionReceived
event. This way, you’ll receive transcription segments in real time and keep things flowing smoothly. • Save Transcriptions: To keep a record, listen for the
user_input_transcribed
event on your backend or save the
session.history
once the session ends. This ensures you have the full transcript saved safely. • Frontend Display: For showing the transcriptions nicely, components like
TranscriptionTile
can help merge and render both user and agent speech in a friendly chat-like interface. If you’d like, I’d be happy to provide a detailed code example to guide you through saving transcriptions or integrating them into your frontend. Just let me know! Sources: docs/index.yaml | Session recording and transcripts | LiveKit Docs | src/transcriptions/TranscriptionTile.tsx | Text and transcriptions | LiveKit Docs | web/src/hooks/use-agent.tsx
p
llm=openai.LLMStream(llm=openai.LLM(api_key=os.getenv("OPENAI_API_KEY"),model="gpt-3.5-turbo")),
t
I'm glad you're interested in using OpenAI LLMStream with LiveKit for real-time transcription and word-by-word display! Here's a friendly step-by-step guide to help you get started: • Enable Real-Time Transcription: To achieve low-latency transcription, you’ll want to configure the OpenAI STT model with
use_realtime=True
. Here’s a simple example:
Copy code
stt = openai.STT(
    model="gpt-4o-mini-transcribe",
    use_realtime=True,
    turn_detection={
        "type": "server_vad",
        "threshold": 0.5,
        "prefix_padding_ms": 600,
        "silence_duration_ms": 350,
    }
)
• Enable TTS-Aligned Transcription: For more precise word-level timing, you can use
use_tts_aligned_transcript=True
with compatible TTS providers like Cartesia or ElevenLabs. • Implement Transcription Node: Define a
transcription_node
method to handle the word-by-word transcriptions along with their timing. Here’s how you might do it:
Copy code
async def transcription_node(self, text_stream: AsyncIterable[str | TimedString]):
    async for text in text_stream:
        if isinstance(text, TimedString):
            print(f"Word: {text.text}, Start: {text.start_time}s, End: {text.end_time}s")
        else:
            print(f"Text chunk: {text}")
• Frontend Integration: To receive and display transcriptions in real time, subscribe to the
lk.transcription
topic. If you’re using React, the
useTranscriptions
hook is a great choice, or you can register a text stream handler like this:
Copy code
room!.registerTextStreamHandler("lk.transcription", (stream) => {
  stream.messages.forEach((msg) => {
    console.log(`Transcription: ${msg.message}, Final: ${msg.attributes['lk.transcription_final']}`);
  });
});
If you’d like, I’m here to help you with any part of the backend setup or frontend integration. Just let me know how I can assist! Sources: livekit-plugins/livekit-plugins-fireworksai/livekit/plugins/fireworksai/stt... | Real-time AI Models & Streaming | livekit/livekit_composite | DeepWiki | Text and transcriptions | LiveKit Docs
p
where i get this TimedString
t
TimedString in LiveKit is a wonderful data structure that helps represent text segments along with their timing information, including
start_time
and
end_time
in seconds relative to the start of the agent's current turn. This is super helpful for synchronized transcription forwarding, allowing you to align at the word or sentence level depending on your TTS provider. Here’s how you can access TimedString: 1. Enable TTS-Aligned Transcription: Simply set
use_tts_aligned_transcript=True
in your
AgentSession
configuration. For example:
Copy code
session = AgentSession(
    stt=deepgram.STT(),
    llm=openai.LLM(),
    tts=cartesia.TTS(),
    use_tts_aligned_transcript=True,
)
1. Implement the
transcription_node
Method:
You’ll want to override this method in your agent class to handle
TimedString
objects. Here’s a simple example:
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):
            print(f"TimedString: '{chunk.text}' ({chunk.start_time} - {chunk.end_time})")
        yield chunk
Just a quick note: This feature is currently available only in the Python SDK and works with TTS providers like Cartesia and ElevenLabs. If you have any questions or need a hand with the implementation, please don’t hesitate to ask—I’m here to help! Sources: Text and transcriptions | LiveKit Docs | livekit-agents/livekit/agents/voice/agent.py
p
async def tts_node( self, text: AsyncIterable[str], model_settings: ModelSettings ) -> AsyncIterable[rtc.AudioFrame]: # Insert custom text processing here print(end="\n") print(f"Agent Speech : {text}") async for frame in Agent.default.tts_node(self, text, model_settings): # Insert custom audio processing here yield frame
t
I'd love to help you customize the
tts_node
method in LiveKit to better process agent speech text and audio frames. You can tailor both the text before synthesis and the audio frames after synthesis. Here's a friendly guide to get you started: • Pre-Process Text: You can modify the incoming text stream before it reaches the TTS engine. For instance, you might want to replace certain phrases or add SSML tags to enhance the speech:
Copy code
`async def tts_node(self, text: AsyncIterable[str], model_settings: ModelSettings):
    async def process_text():
        async for chunk in text:
            modified = chunk.replace("lol", "").replace("OMG", "Oh my god!")
            yield modified

    return Agent.default.tts_node(self, process_text(), model_settings)async def tts_node(self, text: AsyncIterable[str], model_settings: ModelSettings):
    return self._process_audio_stream(Agent.default.tts_node(self, text, model_settings))

async def _process_audio_stream(self, audio_stream: AsyncIterable[rtc.AudioFrame]):
    async for frame in audio_stream:
        # Example: Adjust volume or apply effects
        yield frame`If you'd like, I can provide a more detailed example tailored to your specific needs, whether that's adding cool effects or integrating external TTS APIs. Just let me know!
Sources: Pipeline nodes and hooks | LiveKit Docs | Agents v0.x migration guide - Python | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py | docs/index.yaml | plugins/resemble/src/tts.ts
p
how show transcription with frontend
t
I'd love to help you display real-time transcription on the frontend using LiveKit! Here’s a simple way to get started: • Use Text Streams: Transcriptions come through the
lk.transcription
topic. By listening to this stream, you can receive both interim and final transcription segments as they happen. • React Integration: If you’re working with React, the
useTranscriptions
hook from
@livekit/components-react
is a great tool to manage your transcription data smoothly. • Manual Event Handling: Another option is to listen for the
RoomEvent.TranscriptionReceived
event via the
livekit-client
SDK. This event provides transcription segments along with timestamps and speaker identity, giving you rich context. • Display Logic: To keep everything in order, sort transcriptions by
firstReceivedTime
. Also, make sure to replace interim text with the finalized versions to avoid any duplicates. If you’d like, I can share a detailed code example for React or any other frontend framework you’re using. Just let me know! Sources: complex-agents/turn-taking/README.md | web/src/components/transcript.tsx | Text and transcriptions | LiveKit Docs | client/web/src/components/captions.tsx | components/typewriter.tsx
p
telephony transcription to frontend
t
Hi there! To help you display telephony transcription on the frontend in LiveKit, here’s a friendly step-by-step guide you can follow: • Listen for Transcription Events: Keep an ear out for the
RoomEvent.TranscriptionReceived
event. This will bring in transcription segments that include the text, timestamps, and some handy metadata. • Manage Transcription State: It’s a good idea to maintain a state object where you store these transcription segments. When you see
segment.isFinal === true
, replace any interim results with the final version to keep things accurate. • Render Transcriptions: To make everything look neat, sort the segments by
firstReceivedTime
and then display them in your UI. If you want to add a little flair, consider animations like a typewriter effect—it really enhances the user experience! • Use React Hooks: If you’re working with React, the
useTranscriber
hook is your friend. It simplifies event handling and managing state. Here’s a quick example:
Copy code
const { state, transcriptions } = useTranscriber();
const text = Object.values(transcriptions)
  .sort((a, b) => a.firstReceivedTime - b.firstReceivedTime)
  .map(t => t.text.trim())
  .join("\n");
• Optional: If you’d like to receive transcriptions as soon as they’re available without synchronization delays, you can set
sync_transcription: false
in
RoomOutputOptions
. If you’d like, I’d be more than happy to provide a detailed code example tailored to your specific frontend framework or any particular feature you’re interested in. Just let me know! Sources: Text and transcriptions | LiveKit Docs | hooks/use-transcriber.ts | complex-agents/note-taking-assistant/note-taker-frontend/components/medical...
p
how to get sip room token and pass to frontend
t
I'd be happy to guide you through generating a SIP room token in LiveKit and passing it to the frontend. Here’s a simple step-by-step approach to help you out: 1. Generate the Token on the Backend: You can use the
BuildSIPToken
function to create a token with SIP-specific permissions. Here’s an example in Python:
Copy code
from livekit.protocol.sip import BuildSIPToken

def generate_token(room_name, identity):
    token = BuildSIPToken(
        api_key="your-api-key",
        api_secret="your-api-secret",
        room_name=room_name,
        participant_identity=identity
    )
    return token
1. Create a Backend Endpoint: Next, set up an API endpoint (for example,
/api/generate-token
) that generates and returns the token. Here’s how you might do it using Flask:
Copy code
@app.route('/api/generate-token', methods=['POST'])
def generate_token_endpoint():
    data = request.json
    room_name = data.get("room_name")
    identity = data.get("identity")
    token = generate_token(room_name, identity)
    return jsonify({"token": token})
1. Pass the Token to the Frontend: Finally, from your frontend, make an HTTP POST request to get the token and then use it to connect to the LiveKit room. Here’s a JavaScript example:
Copy code
async function connectToRoom() {
    const response = await fetch('/api/generate-token', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            room_name: 'my-room',
            identity: 'user-123'
        })
    });

    const { token } = await response.json();

    const room = new Room();
    await room.connect('wss://your-livekit-instance', token);
}
If you’d like, I’m here to help you further with setting up the backend or integrating the frontend. Just let me know how I can assist you! Sources: rpc/sip.pb.go | ivr-nagivator/flask_livekit/extension.py | Core Platform Architecture & Authentication | livekit/livekit_composite | D... | SIP Integration & Telephony | livekit/livekit_composite | DeepWiki
p
i got the room name then sing room name i can show transcript to frontend
t
To display transcription on the frontend using a room name in LiveKit, let's walk through the steps together: 1. Connect to the Room: You'll want to use the room name to generate a token and connect to the specific LiveKit room. Here's a simple example to get you started:
Copy code
const room = new Room();
await room.connect('wss://your-livekit-instance', token);
1. Listen for Transcription Events: After connecting, listen for the
RoomEvent.TranscriptionReceived
event to catch those transcription segments as they come in. Here's how you can do that:
Copy code
room.on(RoomEvent.TranscriptionReceived, (segments) => {
  // Handle transcription segments
});
1. Render Transcriptions: Once you have the transcription segments, you can display the text in your UI. If you're using React, the
useTranscriber
hook is a great tool for this:
Copy code
const { state, transcriptions } = useTranscriber();
const text = Object.values(transcriptions)
  .sort((a, b) => a.firstReceivedTime - b.firstReceivedTime)
  .map(t => t.text.trim())
  .join("\n");
If you'd like, I can provide a detailed example to help you integrate this smoothly into your frontend application. Just let me know! Sources: app/page.tsx | hooks/use-transcriber.ts | complex-agents/note-taking-assistant/agent.py | client/web/src/components/captions.tsx | Text and transcriptions | LiveKit Docs
p
can we save the transription before user stop speaking
t
To help you save transcription in LiveKit before the user stops speaking, you can capture interim (partial) transcription events in real time. Here’s a friendly guide on how to do that: 1. Use the
on_interim_transcript
Event:
This event triggers whenever the STT engine provides partial results. Here’s an example:
Copy code
def on_interim_transcript(self, ev: stt.SpeechEvent, *, speaking: bool | None):
    transcript = ev.alternatives[0].text
    if transcript:
        with open("transcript_interim.txt", "a") as f:
            f.write(f"[Interim] {transcript}\n")
1. Listen to
user_input_transcribed
Events:
You can capture partial input by checking
is_final=False
. Here’s how:
Copy code
@session.event
async def on_user_input_transcribed(event: UserInputTranscribedEvent):
    if not event.is_final:
        with open("live_transcription.txt", "a") as f:
            f.write(f"Partial: {event.transcript}\n")
1. Override `transcription_node`: This lets you access the transcription stream directly for real-time processing:
Copy code
async def transcription_node(self, text_stream: AsyncIterable[str]):
    async for text in text_stream:
        with open("transcript_log.txt", "a") as f:
            f.write(f"{text}\n")
These approaches make it easy to save transcription data bit by bit as the user speaks. If you have any questions or need a hand with the implementation, please don’t hesitate to ask—I’m here to help! Sources: How to capture real-time agent transcriptions during conversations | Session recording and transcripts | LiveKit Docs | livekit-plugins/livekit-plugins-assemblyai/livekit/plugins/assemblyai/stt.p... | Pipeline nodes and hooks | LiveKit Docs | Text and transcriptions | LiveKit Docs
p
so i have sip room i have that room name particepent iddenty can estblish connection with fronend using room name and idennty so i fetch transcription from that room
t
Let's walk through how you can connect to a SIP room using the room name and participant identity in LiveKit, and also fetch transcriptions on the frontend. Here’s a simple step-by-step guide: 1. Generate a Token: First, you'll want to generate a token on your backend using the room name and participant identity. Here's an example in Python to help you get started:
Copy code
def generate_token(room_name, identity):
    token = api.AccessToken() \
        .with_identity(identity) \
        .with_grants(api.VideoGrants(room_join=True, room=room_name)) \
        .to_jwt()
    return token
1. Connect to the Room: Next, on the frontend, you can use this token to connect to the room like so:
Copy code
const room = new Room();
await room.connect('wss://your-livekit-instance', token);
1. Fetch Transcriptions: To receive transcription segments, listen for the
RoomEvent.TranscriptionReceived
event. Here’s how you might do that:
Copy code
room.on(RoomEvent.TranscriptionReceived, (segments) => {
  segments.forEach(segment => {
    console.log(`Transcription: ${segment.text}`);
  });
});
1. Display Transcriptions: Finally, you can display these transcriptions in real time using a React component like
TranscriptionView
, or feel free to build a custom UI that fits your needs. If you’d like, I’m happy to provide a more detailed example for either backend token generation or frontend transcription display—just let me know what would be most helpful for you! Sources: main.py | livekit-rtc/livekit/rtc/room.py | SIP APIs | LiveKit Docs | Voice Assistant Applications | livekit/livekit_composite | DeepWiki | complex-agents/ivr-agent/flask_livekit/extension.py
p
can you provide any example code
t
Here’s a friendly example to help you connect to a SIP room using the room name and participant identity, and also fetch transcriptions right on the frontend: Backend: Token Generation
Copy code
from flask import Flask, request, jsonify
from livekit import AccessToken, VideoGrant

app = Flask(__name__)

@app.route('/api/generate-token', methods=['POST'])
def generate_token():
    data = request.json
    room_name = data.get("room_name")
    identity = data.get("identity")

    if not room_name or not identity:
        return jsonify({"error": "Missing room_name or identity"}), 400

    token = AccessToken("your-api-key", "your-api-secret")
    token.identity = identity
    token.add_grant(VideoGrant(room=room_name))

    return jsonify({"token": token.to_jwt()})
Frontend: Connect to Room and Fetch Transcriptions
Copy code
import { Room, RoomEvent } from 'livekit-client';

async function connectToRoom(roomName, identity) {
    // First, we fetch the token from your backend
    const response = await fetch('/api/generate-token', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ room_name: roomName, identity: identity })
    });

    const { token } = await response.json();

    // Now, connect to the LiveKit room
    const room = new Room();
    await room.connect('wss://your-livekit-instance', token);

    // Listen for transcription events and handle them here
    room.on(RoomEvent.TranscriptionReceived, (segments) => {
        segments.forEach(segment => {
            console.log(`Transcription: ${segment.text}`);
        });
    });

    console.log('Connected to room:', roomName);
}
Usage
Copy code
// Just call this function with your room name and participant identity
connectToRoom('sip-room-name', 'sip-participant-identity');
This example walks you through generating a token on the backend, connecting to a SIP room on the frontend, and fetching transcriptions in real time. If you have any questions or need a hand with anything else, feel free to ask—I’m here to help!
p
can we get streming transcription here @session.on("conversation_item_added") def on_conversation_item(event): """Handle conversation items (covers both user and agent messages)""" if transcription_logger and hasattr(event, 'item'): item = event.item if hasattr(item, 'content') and item.content: # Determine speaker based on item type or role speaker = "USER" if hasattr(item, 'role') and item.role == 'user' else "AGENT" transcription_logger.log_transcription(item.content, is_final=True, speaker=speaker)
t
Absolutely, you can access transcription using the
conversation_item_added
event! Just a little heads-up though, this event gives you the finalized content only, not the real-time streaming updates. It gets triggered whenever a conversation item (like a message from the user or agent) is saved to the chat history. Here’s a quick example to illustrate:
Copy code
@session.on("conversation_item_added")
def on_conversation_item(event):
    if hasattr(event, 'item') and event.item.content:
        speaker = "USER" if getattr(event.item, 'role', '') == 'user' else "AGENT"
        print(f"{speaker}: {event.item.content}")
If you’re looking for real-time streaming transcription, you might want to explore the
user_input_transcribed
event or try overriding the
transcription_node
method. These options give you those interim transcription updates as the user is speaking. I’m happy to share some examples for these if you’d like—just let me know! Sources: Events and error handling | LiveKit Docs | Text and transcriptions | LiveKit Docs | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real... | Session recording and transcripts | LiveKit Docs | How to capture real-time agent transcriptions during conversations
p
give other examples
t
Here are some helpful examples of alternatives for accessing real-time streaming transcription in LiveKit that you might find useful: 1. Using the
user_input_transcribed
Event
This event gives you real-time transcription updates, including those interim results. Here's a simple example:
Copy code
@session.on("user_input_transcribed")
def on_user_input_transcribed(event):
    if not event.is_final:
        print(f"Interim transcription: {event.transcript}")
    else:
        print(f"Final transcription: {event.transcript}")
2. Overriding the
transcription_node
Method
This method lets you handle transcription streams directly. Take a look at this example:
Copy code
async def transcription_node(self, text_stream: AsyncIterable[str]):
    async for text in text_stream:
        print(f"Streaming transcription: {text}")
3. Using the
llm_node
for Real-Time Text
If you’re working with an LLM pipeline, you can get real-time text output through the
llm_node
. Here’s how:
Copy code
async def llm_node(self, text_stream: AsyncIterable[str]):
    async for text in text_stream:
        print(f"LLM output: {text}")
These approaches are great for getting immediate transcription updates, perfect for applications that need quick feedback. If you have any questions or want me to walk you through more examples, just let me know—I’m here to help!
p
how add redis here suggest me
t
I'm happy to guide you through integrating Redis with LiveKit for storing transcription or session data. Let's take it step by step: 1. Configure Redis for LiveKit
Copy code
redis:
  address: localhost:6379
  username: redis_username
  password: redis_password
  db: 0
This setup helps LiveKit use Redis for managing distributed state smoothly. 2. Store Transcriptions in Redis You can use Redis to save transcription data in real time. Here's a simple example:
Copy code
import redis
import json

redis_client = redis.StrictRedis(host='localhost', port=6379, db=0)

def store_transcription(room_name, participant_id, transcript):
    key = f"transcriptions:{room_name}"
    redis_client.hset(key, participant_id, json.dumps(transcript))
3. Capture Transcription Events To keep everything up to date, listen for transcription events and save them to Redis like this:
Copy code
@session.on("user_input_transcribed")
def on_transcription(event):
    store_transcription(event.room_name, event.participant_id, event.transcript)
4. Persist Session Data For session data, including transcriptions, you can store them with an expiry time to manage storage efficiently:
Copy code
def store_session_data(session_id, data):
    redis_client.setex(f"session:{session_id}", 3600, json.dumps(data))
If you'd like, I’m here to help you further with setting up Redis or tailoring this to your specific needs. Just let me know! Sources: Distributed Setup | LiveKit Docs | README.md | Core Platform Architecture & Authentication | livekit/livekit_composite | D... | Session recording and transcripts | LiveKit Docs | Agents v0.x migration guide - Python | LiveKit Docs
p
can you full redis doc that can i use my livekit agent]
t
Here’s a comprehensive guide to integrating Redis with LiveKit agents for transcription and session data storage: 1. Configure Redis for LiveKit
Copy code
redis:
  address: localhost:6379
  username: redis_username
  password: redis_password
  db: 0
This configuration helps LiveKit use Redis for distributed state management smoothly. 2. Store Transcriptions in Redis
Copy code
import redis
import json

redis_client = redis.StrictRedis(host='localhost', port=6379, db=0)

def store_transcription(room_name, participant_id, transcript):
    key = f"transcriptions:{room_name}"
    redis_client.hset(key, participant_id, json.dumps(transcript))
3. Capture Transcription Events To keep everything in sync, listen for transcription events and save them to Redis like this:
Copy code
@session.on("user_input_transcribed")
def on_transcription(event):
    store_transcription(event.room_name, event.participant_id, event.transcript)
4. Persist Session Data You can store session data, including transcriptions, with an expiry to manage storage efficiently:
Copy code
def store_session_data(session_id, data):
    redis_client.setex(f"session:{session_id}", 3600, json.dumps(data))
5. Use Redis for Agent Dispatch and Jobs LiveKit leverages Redis for agent dispatch and job storage. Here's a handy example:
Copy code
def store_agent_job(room_name, job_id, job_data):
    key = f"agent_jobs:{room_name}"
    redis_client.hset(key, job_id, json.dumps(job_data))
6. Access Session History To retrieve the full conversation history and save it to Redis, use
session.history
like this:
Copy code
def save_session_history(session_id, history):
    redis_client.set(f"session_history:{session_id}", json.dumps(history))
If you'd like, I’m here to help with any specific Redis patterns or LiveKit agent configurations you want to explore further. Just let me know! Sources: Self-hosting the Ingress Service | LiveKit Docs | Distributed Setup | LiveKit Docs | pkg/service/redisstore_test.go | examples/other/transcription/README.md | Session recording and transcripts | LiveKit Docs
p
prompt chace
t
I'm happy to help you understand how prompt caching works in LiveKit for agents and workflows! Here’s a friendly guide to get you started: 1. For LiveKit Agents with Anthropic: You can enable caching by setting
caching="ephemeral"
in your LLM configuration. This helps optimize resource usage by caching the system prompt, tools, and chat history. Here’s a simple example:
Copy code
llm = AnthropicLLM(api_key="your-api-key", caching="ephemeral")
2. For LiveKit with llama.cpp: Great news—prompt caching is enabled by default using the
cache_prompt
parameter. It works by reusing previously computed tokens when prompts share common prefixes. Here’s how you can set it up:
Copy code
llm = LlamaCppLLM(cache_prompt=True)
3. Advanced Caching Features: • Cache Reuse: This matches common prefixes to reuse tokens efficiently. • Slot-based Cache Management: Allows you to save and restore cache states across sessions. • Chunk Reuse: Helps efficiently reuse attention states for handling larger prompts. 4. For Transcription Workflows: Although there isn’t detailed caching specifically for transcription, you can use initial prompts with STT models like Azure OpenAI to help guide the transcription process. I’d recommend checking your STT provider’s documentation to see if they support caching. If you’d like, I’m here to help you with implementing prompt caching tailored to your specific use case—just let me know! Sources: livekit-plugins/livekit-plugins-anthropic/livekit/plugins/anthropic/llm.py | tools/server/public_simplechat/readme.md
p
what do you thing om langdetect import detect from speechbrain.pretrained import EncoderClassifier async def detect_language_from_audio(frames): classifier = EncoderClassifier.from_hparams(source="speechbrain/lang-id-commonlanguage_ecapa") wav = concatenate_audio_frames(frames) prediction = classifier.classify_file(wav) return prediction[0] Integrating with LiveKit Agent: self.detected_language = "en" async def stt_node(self, audio, model_settings): # buffer first frames for language detection buffered_frames = [] async for frame in audio: buffered_frames.append(frame) if len(buffered_frames) >= 50 and not self.detected_language: self.detected_language = await detect_language_from_audio(buffered_frames) print(f"Detected Language: {self.detected_language}") yield frame Then pass it to downstream: async with llm.chat(chat_ctx=chat_ctx.set_language(self.detected_language)) as stream: ... async for audio in self.tts_node(response_stream, model_settings.with_language(self.detected_language)):
t
I'm glad you're exploring how to integrate language detection with LiveKit agents! Here are some friendly recommendations to help you pass the detected language smoothly to your downstream processes: 1. Use Deepgram for Automatic Language Detection Deepgram is fantastic because it supports multilingual transcription with automatic language detection. Here's a simple example to get you started:
Copy code
stt = deepgram.STT(
    model="nova-2",
    language="multi"  # Enables automatic language detection
)
By setting
language="multi"
, Deepgram will detect the spoken language and include that context in the transcriptions, which is super helpful! 2. Pass Detected Language to Downstream Processes Once you have the detected language, you can easily update your TTS and STT components dynamically like this:
Copy code
# Update both STT and TTS with the detected language
tts.update_options(language="es")  # Update TTS to Spanish
stt.update_options(language="es")  # Update STT to Spanish
3. Implement a Custom SpeechBrain STT Plugin Even though LiveKit doesn’t directly support SpeechBrain out of the box, you can create a custom STT plugin by: • Inheriting from
stt.STT
• Implementing the
_recognize_impl
method to handle language detection • Providing a
stream()
method for real-time transcription This approach offers great flexibility if you want to tailor things to your needs. 4. Use Multilingual Turn Detection LiveKit also supports multilingual turn detection, which is perfect for conversations with mixed languages. Here's a quick setup example:
Copy code
from livekit.plugins.turn_detector.multilingual import MultilingualModel

session = AgentSession(
    stt=deepgram.STT(model="nova-3", language="multi"),
    turn_detection=MultilingualModel(),
)
If you'd like, I’m here to help you dive deeper into implementing a custom STT plugin or configuring Deepgram for language detection. Just let me know how I can support you further! Sources: LiveKit turn detector plugin | LiveKit Docs | pipeline-tts/changing_language/README.md | Building the all-in-one platform for voice AI agents | Building the all-in-one platform for voice AI agents | Building the all-in-one platform for voice AI agents
p
how to update stt or tts during conversation
t
To help you smoothly update STT or TTS settings during a LiveKit agent conversation, you can use the
update_options()
method provided by the plugins. Let me walk you through it: 1. Update STT Settings You can easily change STT parameters like language or model on the fly. Here’s an example:
Copy code
stt.update_options(languages=["ja", "en"], translation_enabled=True, translation_target_languages=["fr"])
2. Update TTS Settings Similarly, you can adjust TTS settings such as voice, language, speed, or volume dynamically. For instance:
Copy code
tts.update_options(voice="Spanish_Narrator", language="es", speed=1.2, vol=1.0)
3. Real-Time Language Switching If you want to synchronize STT and TTS for multilingual conversations, just update both like this:
Copy code
# Update both TTS and STT when switching languages
tts.update_options(language="es")
stt.update_options(language="es")
4. Use Cases • Voice Switching: Easily change TTS voice on the go. • Language Adaptation: Switch STT and TTS languages based on what the user needs. • Context-Aware Adjustments: Tweak speed or pitch for better clarity. These updates happen seamlessly during your sessions without interrupting the conversation. If you’d like, I’m here to help you with any part of the implementation—just let me know! Sources: livekit-plugins/livekit-plugins-minimax/livekit/plugins/minimax/tts.py | Gladia STT plugin guide | LiveKit Docs | pipeline-tts/tts_comparison/README.md | Models | LiveKit Docs | Introducing LiveKit Inference: A unified model interface for voice AI
p
how can we use without plugin models
t
I'm glad you're interested in using custom STT or TTS models in LiveKit without relying on the built-in plugins! You can absolutely create your own model nodes by extending the base classes (
stt.STT
or
tts.TTS
). Let me walk you through how to do this: 1. Custom STT Implementation Start by creating a class that inherits from
stt.STT
and implement the necessary methods:
Copy code
from livekit.agents import stt

class CustomSTT(stt.STT):
    def __init__(self, api_key: str, model_url: str):
        super().__init__(capabilities=stt.STTCapabilities(streaming=True, interim_results=True))
        self._api_key = api_key
        self._model_url = model_url

    def stream(self, *, language: str = None, conn_options=None):
        return CustomSpeechStream(stt=self, opts={}, conn_options=conn_options)
You'll want to define a
CustomSpeechStream
class that manages real-time audio processing and emits transcription events. This helps keep everything running smoothly. 2. Custom TTS Implementation Next, create a class that inherits from
tts.TTS
and implement the
synth
method like this:
Copy code
from livekit.agents import tts

class CustomTTS(tts.TTS):
    def __init__(self, voice_id: str, api_endpoint: str, api_key: str):
        super().__init__(capabilities=tts.TTSCapabilities(sampling_rate=24000, channels=1))
        self._voice_id = voice_id
        self._endpoint = api_endpoint
        self._api_key = api_key

    async def synth(self, text: str):
        audio_data = await self._call_tts_api(text)
        yield SynthesizedAudio(text=text, data=audio_data)
3. Integrate with AgentSession Once your custom STT and TTS classes are ready, you can easily pass their instances into the
AgentSession
like this:
Copy code
session = AgentSession(
    stt=CustomSTT(api_key="your-key", model_url="https://your-stt-api"),
    tts=CustomTTS(voice_id="custom-voice", api_endpoint="https://your-tts-api"),
    llm=OpenAI(),
)
4. Key Notes • By using custom implementations, you get full control and bypass all built-in plugins, which is great for tailoring the experience exactly how you want. • Make sure your custom STT and TTS handle real-time audio and text processing properly, and emit the necessary events like
SpeechEvent
or
SynthesizedAudio
so everything integrates seamlessly. If you'd like, I’m here to help you with implementing a specific custom model or integrating a particular API. Just let me know how I can support you! Sources: livekit-plugins/livekit-plugins-speechmatics/livekit/plugins/speechmatics/s... | Text-to-speech (TTS) models | LiveKit Docs
p
if you have anu example
t
I'd love to walk you through an example of how to implement a custom STT model in LiveKit without relying on built-in plugins. Let’s dive in together: Custom STT Implementation
Copy code
from livekit.agents import stt
from livekit.agents.utils import AudioBuffer

class CustomSTT(stt.STT):
    def __init__(self, api_key: str, model_url: str):
        super().__init__(capabilities=stt.STTCapabilities(streaming=True, interim_results=True))
        self._api_key = api_key
        self._model_url = model_url

    def stream(self, *, language: str = None, conn_options=None):
        return CustomSpeechStream(self._api_key, self._model_url, language)

class CustomSpeechStream(stt.SpeechStream):
    def __init__(self, api_key, model_url, language):
        self.api_key = api_key
        self.model_url = model_url
        self.language = language
        self.audio_buffer = AudioBuffer()

    async def push_audio(self, frame):
        self.audio_buffer.add_frame(frame)
        # Here, you’d send audio to your custom STT API and get the transcription
        transcription = await self._call_stt_api()
        if transcription:
            yield stt.SpeechEvent(transcript=transcription, is_final=False)

    async def _call_stt_api(self):
        # Just an example of calling your custom STT API
        audio_data = self.audio_buffer.get_audio()
        response = await some_http_library.post(self.model_url, data=audio_data, headers={"Authorization": f"Bearer {self.api_key}"})
        return response.json().get("transcription")
Custom TTS Implementation
Copy code
from livekit.agents import tts

class CustomTTS(tts.TTS):
    def __init__(self, voice_id: str, api_endpoint: str, api_key: str):
        super().__init__(capabilities=tts.TTSCapabilities(sampling_rate=24000, channels=1))
        self._voice_id = voice_id
        self._endpoint = api_endpoint
        self._api_key = api_key

    async def synth(self, text: str):
        # This is where you call your custom TTS API
        response = await some_http_library.post(self._endpoint, json={"text": text, "voice": self._voice_id}, headers={"Authorization": f"Bearer {self._api_key}"})
        audio_data = response.content
        yield tts.SynthesizedAudio(text=text, data=audio_data)
Integrate with AgentSession
Copy code
session = AgentSession(
    stt=CustomSTT(api_key="your-stt-api-key", model_url="https://your-stt-api"),
    tts=CustomTTS(voice_id="custom-voice", api_endpoint="https://your-tts-api", api_key="your-tts-api-key"),
    llm=OpenAI(),
)
This example aims to show you how to create your own STT and TTS implementations and seamlessly integrate them into a LiveKit agent session. If you have any questions or would like me to clarify anything or provide more examples, please don’t hesitate to ask—I’m here to help!
p
async def stt_node( self, audio: AsyncIterable[rtc.AudioFrame], model_settings: ModelSettings ) -> Optional[AsyncIterable[stt.SpeechEvent]]: async def filtered_audio(): async for frame in audio: yield frame async for event in Agent.default.stt_node(self, filtered_audio(), model_settings): # insert custom text postprocessing here if event.alternatives[0].text is None: print(f"✨STT Node{event.alternatives[0]}") yield event
t
I'd love to help you customize the
stt_node
method in LiveKit for postprocessing transcription events! You can do this by overriding the method in a custom
Agent
subclass. Here’s a friendly example to get you started: Example: Keyword Detection in Transcription Events
Copy code
from livekit.agents import Agent
from livekit.plugins import deepgram, openai, silero
import logging

logger = logging.getLogger("keyword-detection")

class KeywordDetectionAgent(Agent):
    def __init__(self):
        super().__init__(
            instructions="You are a helpful assistant.",
            stt=deepgram.STT(),
            llm=openai.LLM(),
            tts=openai.TTS(),
            vad=silero.VAD.load(),
        )

    async def stt_node(self, audio, model_settings):
        # Get the parent transcription stream
        stream = super().stt_node(audio, model_settings)

        async def process_stream():
            async for event in stream:
                if event.type == SpeechEventType.FINAL_TRANSCRIPT and event.alternatives:
                    transcript = event.alternatives[0].text.lower()
                    keywords = ["hello", "thanks", "bye"]
                    for keyword in keywords:
                        if keyword in transcript:
                            logger.info(f"Keyword detected: '{keyword}'")
                yield event

        return process_stream()
Example: Diarization with Speaker Labeling
Copy code
class DiarizationAgent(Agent):
    async def stt_node(self, audio, model_settings):
        stream = super().stt_node(audio, model_settings)
        self.speaker_names = getattr(self, "speaker_names", {})

        async def process_stream():
            async for event in stream:
                if event.type == SpeechEventType.FINAL_TRANSCRIPT and event.alternatives:
                    alternative = event.alternatives[0]
                    speaker_id = getattr(alternative, "speaker_id", None)
                    if speaker_id:
                        name = self.speaker_names.get(speaker_id, speaker_id)
                        alternative.text = f"{name}: {alternative.text}"
                yield event

        return process_stream()
These examples show you how to add your own special touch, like keyword detection or speaker labeling, all while keeping the original transcription stream intact. If you have any questions or want to explore this further, please don’t hesitate to ask—I’m here to help! Sources: Pipeline nodes and hooks | LiveKit docs | pipeline-stt/keyword-detection/README.md | Text and transcriptions | LiveKit docs
p
how add privious context of currently running conversation
t
I'd love to help you include previous context in a currently running conversation with LiveKit agents! You can use the
chat_ctx
parameter to transfer or merge conversation history smoothly. Here’s a friendly guide to get you started: 1. Basic Context Transfer When you create a new agent, simply pass the previous agent’s
chat_ctx
to keep the conversation history intact:
Copy code
return TechnicalSupportAgent(chat_ctx=self.session.chat_ctx)
2. Advanced Context Copying and Truncation To avoid going over token limits, you can copy and truncate the previous context like this:
Copy code
truncated_chat_ctx = userdata.prev_agent.chat_ctx.copy(
    exclude_instructions=True, 
    exclude_function_call=False
).truncate(max_items=6)
3. Merging Contexts When merging contexts, it’s helpful to avoid duplicate messages by checking existing IDs:
Copy code
existing_ids = {item.id for item in chat_ctx.items}
items_copy = [item for item in truncated_chat_ctx.items if item.id not in existing_ids]
chat_ctx.items.extend(items_copy)
4. Use a BaseAgent Pattern You might find it easier to create a base class that automatically handles context preservation for you:
Copy code
class BaseAgent(Agent):
    async def on_enter(self):
        userdata = self.session.userdata
        chat_ctx = self.chat_ctx.copy()

        if userdata.prev_agent:
            truncated_chat_ctx = userdata.prev_agent.chat_ctx.copy(
                exclude_instructions=True, 
                exclude_function_call=False
            ).truncate(max_items=6)
            existing_ids = {item.id for item in chat_ctx.items}
            items_copy = [item for item in truncated_chat_ctx.items if item.id not in existing_ids]
            chat_ctx.items.extend(items_copy)

        await self.update_chat_ctx(chat_ctx)
5. External Context Management If you’re looking for even more advanced memory retention, integrating external tools like Letta or LlamaIndex can be a great option to maintain context across sessions. If you’d like, I’m here to help you further with implementing context transfer or exploring those external tools. Just let me know! Sources: Agent-assisted warm transfer | LiveKit docs | External data and RAG | LiveKit Docs | Workflows | LiveKit docs | examples/voice_agents/README.md | agents/src/llm/chat_context.ts
p
how to deploy livekit telephonic app in docker
t
I'd be happy to guide you through deploying a LiveKit telephony application in Docker. Here’s a step-by-step approach to make it as smooth as possible: 1. Use Docker Compose Start by creating a
docker-compose.yaml
file to define your services like this:
Copy code
services:
  redis:
    image: redis
    volumes:
      - redis_data:/data
    ports:
      - 6379:6379

  livekit:
    image: livekit/livekit-server
    command: --dev --redis-host localhost:6379
    network_mode: host
    depends_on:
      redis:
        condition: service_started

  sip:
    image: livekit/sip
    network_mode: host
    environment:
      SIP_CONFIG_BODY: |
        api_key: 'devkey'
        api_secret: 'secret'
        ws_url: 'ws://localhost:7880'
        redis:
          address: 'localhost:6379'
        sip_port: 5060
        rtp_port: 10000-20000
        use_external_ip: true
        logging:
          level: debug

volumes:
  redis_data:
2. Configuration Details • The SIP service connects to the LiveKit server via WebSocket (
ws_url
), ensuring smooth communication. • Both services share the same Redis instance to keep everything in sync seamlessly. • We use host network mode (
network_mode: host
) for SIP (port 5060) and RTP (ports 10000–20000) so the networking works correctly. 3. Run with Docker Compose
Copy code
docker-compose up
4. Alternative: Run with
docker run
Copy code
docker run --rm \
    -e SIP_CONFIG_BODY="`cat config.yaml`" \
    --network host \
    livekit/sip
5. Post-Deployment Setup • Don’t forget to configure your SIP Trunks and Dispatch Rules using the LiveKit CLI or SDKs to tailor everything to your needs. • Also, make sure UDP traffic is allowed on ports 5060 (SIP) and 10000–20000 (RTP) for smooth operation. If you'd like, I’m here to help you further with SIP trunk configuration or explore more advanced deployment options. Just let me know! Sources: README.md | aws-ecs/README.md
p
i am doing docker deploy # syntax=docker/dockerfile:1 # Use the official UV Python base image with Python 3.13 on Debian Bookworm # UV is a fast Python package manager that provides better performance than pip # We use the slim variant to keep the image size smaller while still having essential tools ARG PYTHON_VERSION=3.12 FROM ghcr.io/astral-sh/uv:python${PYTHON_VERSION}-bookworm-slim AS base # Keeps Python from buffering stdout and stderr to avoid situations where # the application crashes without emitting any logs due to buffering. ENV PYTHONUNBUFFERED=1 # Create a non-privileged user that the app will run under. # See https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#user ARG UID=10001 RUN adduser \ --disabled-password \ --gecos "" \ --home "/app" \ --shell "/sbin/nologin" \ --uid "${UID}" \ appuser # Install build dependencies required for Python packages with native extensions # gcc: C compiler needed for building Python packages with C extensions # python3-dev: Python development headers needed for compilation # We clean up the apt cache after installation to keep the image size down RUN apt-get update && apt-get install -y \ gcc \ g++ \ python3-dev \ && rm -rf /var/lib/apt/lists/* # Create a new directory for our application code # And set it as the working directory WORKDIR /app # Copy just the dependency files first, for more efficient layer caching COPY pyproject.toml uv.lock ./ RUN mkdir -p src # Install Python dependencies using UV's lock file # --locked ensures we use exact versions from uv.lock for reproducible builds # This creates a virtual environment and installs all dependencies # Ensure your uv.lock file is checked in for consistency across environments RUN uv sync --locked # Copy all remaining application files into the container # This includes source code, configuration files, and dependency specifications # (Excludes files specified in .dockerignore) COPY . . # Change ownership of all app files to the non-privileged user # This ensures the application can read/write files as needed RUN chown -R appuser:appuser /app # Switch to the non-privileged user for all subsequent operations # This improves security by not running as root USER appuser # Pre-download any ML models or files the agent needs # This ensures the container is ready to run immediately without downloading # dependencies at runtime, which improves startup time and reliability RUN uv run main.py download-files # Run the application using UV # UV will activate the virtual environment and run the agent. # The "start" command tells the worker to connect to LiveKit and begin waiting for jobs. CMD ["uv", "run", "main.py", "start"]
t
Hi there! To get your LiveKit application up and running using a custom Dockerfile with Python and the UV package manager, I’ve put together some friendly steps to guide you through the process: 1. Use the Correct Base Image Start by choosing a glibc-based base image like
ghcr.io/astral-sh/uv:python${PYTHON_VERSION}-bookworm-slim
. Just swap out
${PYTHON_VERSION}
for the Python version you want to use (for example, 3.13). 2. Set Environment Variables and Non-Root User It’s a good idea to set
PYTHONUNBUFFERED=1
to keep your logs flowing smoothly without buffering. Also, for security, create a non-privileged user like this:
Copy code
ARG UID=10001
RUN adduser \
    --disabled-password \
    --gecos "" \
    --home "/app" \
    --shell "/sbin/nologin" \
    --uid "${UID}" \
    appuser
3. Install Build Dependencies Next, you’ll want to install the system packages needed to build Python extensions:
Copy code
RUN apt-get update && apt-get install -y gcc g++ python3-dev \
    && rm -rf /var/lib/apt/lists/*
4. Install Dependencies with UV For a smooth build process, copy your
pyproject.toml
and
uv.lock
files first to take advantage of layer caching, then install your dependencies:
Copy code
COPY pyproject.toml uv.lock ./
RUN uv sync --locked
5. Pre-download ML Models or Assets To make sure everything’s ready to go, run a command that pre-fetches any necessary models or assets:
Copy code
RUN uv run "agent.py" download-files
6. Define Startup Command Finally, set the container’s entrypoint so your agent starts up automatically:
Copy code
CMD ["uv", "run", "agent.py", "start"]
Here’s an example Dockerfile putting it all together:
Copy code
ARG PYTHON_VERSION=3.13
FROM ghcr.io/astral-sh/uv:python${PYTHON_VERSION}-bookworm-slim AS base
ENV PYTHONUNBUFFERED=1
ARG UID=10001
RUN adduser \
    --disabled-password \
    --gecos "" \
    --home "/app" \
    --shell "/sbin/nologin" \
    --uid "${UID}" \
    appuser

RUN apt-get update && apt-get install -y gcc g++ python3-dev \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY pyproject.toml uv.lock ./
RUN uv sync --locked
COPY . .
RUN chown -R appuser:appuser /app
USER appuser
RUN uv run "agent.py" download-files
CMD ["uv", "run", "agent.py", "start"]
If you’d like, I’m here to help with any part of your Docker deployment or LiveKit configuration. Just let me know how I can support you! Sources: Builds and Dockerfiles | LiveKit Docs | pkg/agentfs/docker_test.go | complex-agents/exa-deep-researcher/uv.lock | Agent Deployment & Docker | livekit/livekit_composite | DeepWiki | Build Systems & Toolchains | livekit/livekit_composite | DeepWiki
p
diffrence between agent intraction and session instruction
t
Thanks for reaching out! Let me help clarify the difference between agent instructions and session instructions in LiveKit—they each have their own important roles and scope: Agent Instructions: • These are set at the
Agent
level as a string parameter. • They provide high-level behavioral guidelines or act as a system prompt for the agent. • For example:
instructions="You are a friendly voice assistant built by LiveKit."
Session Instructions: • Actually, there isn’t a separate concept called "session instructions." • The
AgentSession
simply uses the agent’s instructions to guide real-time execution. • It manages operational tasks like STT, TTS, and LLM interactions throughout the session. Dynamic Updates: Here’s something neat—you can update the agent’s instructions on the fly during a live session using
update_instructions()
. This means the agent’s behavior adapts instantly without needing to restart the session. If you’d like, I’d be happy to walk you through an example of how to update instructions dynamically during a session. Just let me know! Sources: Agent Session Management & Turn Detection | livekit/livekit_composite | Dee... | agent/main.py | livekit-agents/livekit/agents/voice/agent_activity.py | .cursor/rules/agent-core.mdc
p
how can we add load balancer
t
Let's walk through setting up a load balancer for your LiveKit deployments together. Here’s a simple step-by-step guide: 1. Choose a Load Balancer Type In your Helm
values.yaml
file, you’ll want to specify the load balancer type like this:
Copy code
loadBalancer:
  type: alb  # Options: alb (AWS), gke, do (Digital Ocean), etc.
2. Configure TLS and Hostnames Next, define your domain(s) and SSL certificates to keep things secure:
Copy code
loadBalancer:
  type: alb
  tls:
    - hosts:
      - livekit.myhost.com
3. Enable TURN with Load Balancer To improve connectivity, it’s a great idea to enable TURN by adding:
Copy code
turn:
  enabled: true
  domain: turn.myhost.com
  tls_port: 3478
  udp_port: 443
  secretName: livekit-tls-secret
  serviceType: LoadBalancer
4. Deploy via Helm Once your
values.yaml
is all set, you can deploy LiveKit using Helm like this:
Copy code
helm install livekit livekit/livekit-server -f values.yaml
5. Open Required Ports Make sure these ports are open so everything runs smoothly: • WebRTC UDP: 50000-60000 • WebRTC TCP: 7881 • TURN/UDP: 443 • TURN/TLS: 3478 6. Verify Load Balancer Address To find your load balancer’s address, you can use this command:
Copy code
kubectl get service <livekit-service-name> --namespace <namespace>
Don’t forget to update your DNS records to point to this address. 7. Multi-Region Routing (Optional) If you’re aiming for a global reach, consider using a geo-aware DNS service like AWS Route53 to direct users to the closest region. If you’d like, I’m here to help you with any part of the Helm configuration or DNS setup. Just let me know! Sources: Deploy to Kubernetes | LiveKit docs | examples/server-eks.yaml | Distributed Setup | LiveKit docs | docs/tutorials/aws-sd.md
p
nginx
t
I'm here to help you configure NGINX as a load balancer for your LiveKit deployments. Let's walk through the steps together: 1. Deploy NGINX Ingress Controller First, you'll want to install the NGINX Ingress Controller using Helm. Here's how you can do it:
Copy code
helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx
helm repo update
helm install nginx-ingress ingress-nginx/ingress-nginx --set controller.publishService.enabled=true
2. Configure LiveKit Load Balancer Next, in your LiveKit Helm
values.yaml
, make sure to disable the built-in load balancer when using NGINX:
Copy code
loadBalancer:
  type: disable
3. Open Required Ports To ensure everything runs smoothly, please confirm that the following ports are open: • WebRTC UDP: 50000-60000 • WebRTC TCP: 7881 • TURN/UDP: 443 • TURN/TLS: 3478 4. Configure SSL Certificates For automatic SSL certificate management, you'll want to install Cert Manager. Here’s how:
Copy code
kubectl create namespace cert-manager
helm repo add jetstack https://charts.jetstack.io
helm repo update
helm install cert-manager jetstack/cert-manager --namespace cert-manager --version v1.8.0 --set installCRDs=true
Then, create a ClusterIssuer for Let’s Encrypt with this configuration:
Copy code
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
  name: letsencrypt-prod
spec:
  acme:
    email: <your-email-address>
    server: https://acme-v02.api.letsencrypt.org/directory
    privateKeySecretRef:
      name: letsencrypt-prod-private-key
    solvers:
    - http01:
        ingress:
          class: nginx
5. Configure TURN Service To enable TURN in your LiveKit setup, update your configuration like this:
Copy code
livekit:
  turn:
    enabled: true
    domain: turn.myhost.com
    tls_port: 3478
    udp_port: 443
    secretName: livekit-tls-secret
6. Deploy LiveKit with Helm Once everything is set, you can install LiveKit using your configured values:
Copy code
helm install livekit livekit/livekit-server --namespace <namespace> --values values.yaml
7. Verify Deployment Finally, check the ingress status and DNS resolution to ensure your setup is working:
Copy code
kubectl get ingress --namespace <namespace>
If you have any questions or need a hand with the NGINX configuration or troubleshooting, please don’t hesitate to ask. I’m here to support you every step of the way! Sources: Deploy to Kubernetes | LiveKit docs | docs/tutorials/gke-nginx.md | ingress-sample.yaml
p
partially transcript
t
I'm happy to guide you through handling partial transcription in LiveKit for real-time updates. Here's a simple step-by-step approach: 1. Enable Partial Transcription in STT Plugins • If you're using OpenAI, just set
use_realtime=True
to activate streaming with interim results. • For Speechmatics, make sure
enable_partials=True
is set (it’s enabled by default) so you receive those helpful interim transcription events. 2. Backend Processing Partial transcriptions come through as
SpeechEvent
with the type
SpeechEventType.INTERIM_TRANSCRIPT
. You can easily forward these events to the frontend or use them within your agent's logic—whichever works best for you. 3. Frontend Rendering • Use
registerTextStreamHandler
to listen to the transcription streams. • Keep an eye on the
lk.transcription_final
field to tell interim and final transcriptions apart, and swap out the interim text with the final one when it arrives. 4. Example Flow 1. The user starts speaking → the agent streams audio to the STT engine. 2. The STT engine sends partial transcriptions periodically (like every 0.5 seconds). 3. The agent forwards these interim results to the frontend. 4. Once the speech ends, a final transcription is sent, replacing the interim text. If you'd like, I’m here to help you dive deeper into either backend or frontend implementation—just let me know! Sources: Text and transcriptions | LiveKit docs | lib/src/core/room.dart | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/stt.py
p
partially pass the user input so we can reduce latency
t
To help you reduce latency during transcription in LiveKit by passing partial user input, here’s a friendly step-by-step guide: 1. Enable Partial Transcriptions Start by configuring your STT plugin to emit interim (partial) transcripts. For example, with Speechmatics, you can set it up like this:
Copy code
STT(
    enable_partials=True,  # Enabled by default
    max_delay=0.7,  # Controls processing delay (lower = faster but potentially less accurate)
)
2. Use Preemptive Generation Next, enable preemptive response generation. This means the system begins processing user input before the full utterance is finished, helping to overlap response generation with speech and reduce overall latency. 3. Access Partial Input in Real Time You can use the
onInterimTranscript
hook to handle partial input right away, like this:
Copy code
const recognitionHooks: RecognitionHooks = {
  onInterimTranscript: (ev: SpeechEvent) => {
    console.log("Partial transcript:", ev.alternatives[0].text);
  },
  onFinalTranscript: (ev: SpeechEvent) => {
    console.log("Final transcript:", ev.alternatives[0].text);
  },
  onPreemptiveGeneration: (info: PreemptiveGenerationInfo) => {
    console.log("Starting preemptive response for:", info.newTranscript);
  },
};
These handy features let you respond to partial input immediately while still preparing for the final, confirmed user input. If you have any questions or want some help with the implementation, please don’t hesitate to reach out—I’m here to support you! Sources: livekit-plugins/livekit-plugins-speechmatics/livekit/plugins/speechmatics/s... | Agent speech and audio | LiveKit docs | agents/src/voice/agent_activity.ts
p
fast tts response
t
To help you get the best TTS response time in LiveKit for quicker audio generation, here are some friendly tips you can try: 1. Enable Low-Latency Mode If you’re using Rime TTS, setting
reduce_latency=True
can really help cut down delays. And if you’re working with streaming plugins like ElevenLabs or NeuPhonic, they already have low-latency streaming built in for you. 2. Use Streaming TTS Models Picking TTS plugins that support native streaming, such as ElevenLabs or NeuPhonic, lets audio come through bit by bit as it’s created, making things feel faster. 3. Optimize Audio Format Using the
audio/pcm
format can reduce encoding time, and matching the
sample_rate
to what your app needs helps keep things smooth. 4. Prewarm TTS Connections For plugins like NeuPhonic, calling
prewarm()
gets connections ready ahead of time, so you won’t have to wait for that initial setup. 5. Pre-Synthesize Predictable Responses If you have fixed phrases like greetings, using
session.say()
with pre-recorded or pre-generated audio can skip the synthesis step altogether. 6. Adjust Speech Speed Speeding up speech with parameters like
speed_alpha
(for Rime) or
speaking_rate
(for Inworld) can help reduce how long it takes to generate audio. 7. Monitor Latency Metrics Keep an eye on key numbers like
TTFT (Time to First Token) < 300ms
,
TTFB (Time to First Byte) < 200ms
, and
End-to-End Latency < 1000ms
to make sure things are running smoothly. If you’d like, I’m here to help you configure a specific TTS plugin or fine-tune your setup—just let me know! Sources: Operational Best Practices | livekit/livekit_composite | DeepWiki | Live Conversations with AI using ChatGPT and WebRTC | Agent speech and audio | LiveKit docs | Knowledge Base Content | livekit/livekit_composite | DeepWiki | Rime TTS plugin guide | LiveKit Docs