from dotenv import load_dotenv from livekit impor...
# ask-ai
p
from dotenv import load_dotenv from livekit import agents from livekit.agents import AgentSession, Agent, RoomInputOptions from livekit.plugins import ( openai, noise_cancellation, ) import os from mcp_client import MCPServerSse from mcp_client.agent_tools import MCPToolsIntegration import logging import pathlib import asyncio import threading import subprocess import platform from livekit.agents.voice.events import ErrorEvent from livekit.agents.utils.audio import audio_frames_from_file logger = logging.getLogger("assistant") logger.setLevel(logging.INFO) load_dotenv(override=True) instructions = ( "You are Nuwan " ) class Assistant(Agent): def __init__(self) -> None: super().__init__(instructions=instructions) async def entrypoint(ctx: agents.JobContext): room_id = ctx.room.name # Use room name as room ID # Initialize MCP server connection mcp_server = MCPServerSse( params={"url": "http://localhost:7777/sse"}, cache_tools_list=True, name="mcp" ) # Create room context to pass to MCP tools room_context = { "room_name": ctx.room.name, "room_id": ctx.room.name, # Using room name as room ID } # Primary session with OpenAI Realtime API for best performance try: session = AgentSession( llm=openai.realtime.RealtimeModel( model="gpt-realtime", modalities=["text"], api_key=os.getenv("OPENAI_API_KEY") ), tts=openai.TTS( model="tts-1", voice="ash", ), ) logger.info("Using OpenAI Realtime API (primary)") except Exception as e: logger.warning(f"Failed to initialize Realtime API, falling back to standard LLM: {e}") # Fallback to standard OpenAI LLM with separate STT/TTS session = AgentSession( llm=openai.LLM(model="gpt-4o-mini"), stt=openai.STT(), # Use OpenAI STT instead of Deepgram to avoid dependencies tts=openai.TTS( model="tts-1", voice="echo", # Male voice ), _# turn_detection=MultilingualModel(),_ _# preemptive_generation=True,_ ) logger.info("Using fallback LLM configuration") error_audio_path = os.path.join(pathlib.Path(file).parent.absolute(), "error_message.wav") start_audio_path = os.path.join(pathlib.Path(file).parent.absolute(), "start.wav") # Track speaking state to prevent self-interruption is_speaking = False @session.on("agent_speech_started") def on_agent_speech_started(): global is_speaking is_speaking = True logger.info("Agent started speaking - microphone sensitivity reduced") @session.on("agent_speech_finished") def on_agent_speech_finished(): global is_speaking is_speaking = False logger.info("Agent finished speaking - microphone sensitivity restored") @session.on("error") def on_error(ev: ErrorEvent): if ev.error.recoverable: logger.info(f"Recoverable error occurred: {ev.error}") # For API connection errors, try to maintain the session if "APIConnectionError" in str(ev.error) or "connection" in str(ev.error).lower(): logger.info("API connection issue detected, session will retry automatically") return logger.error(f"Unrecoverable error occurred: {ev.error}") # Play custom error sound try: session.say( "Sorry, I'm experiencing a technical issue. Please try speaking again.", audio=audio_frames_from_file(error_audio_path), allow_interruptions=False, ) except Exception as e: logger.error(f"Failed to play error message: {e}") @session.on("agent_started_thinking") def on_agent_thinking(): logger.debug("Agent started processing input") @session.on("agent_stopped_thinking") def on_agent_stopped_thinking(): logger.debug("Agent finished processing input") assistant = Assistant() # Create agent with MCP tools integration agent = await MCPToolsIntegration.create_agent_with_tools( agent_class=Assistant, mcp_servers=[mcp_server], room_context=room_context ) await session.start( room=ctx.room, agent=agent, room_input_options=RoomInputOptions( # Enhanced noise cancellation and echo suppression for Raspberry Pi setup noise_cancellation=noise_cancellation.BVCTelephony(), ), ) try: await session.generate_reply( instructions="Greet the user in English only. Say hello and introduce yourself as Nuwan." ) finally: await session.stop() if name == "__main__": agents.cli.run_app(agents.WorkerOptions( entrypoint_fnc=entrypoint, port=1100, initialize_process_timeout=300 # 5 minutes )) this is my agent code and i run this using console command. so i want save user input audio before llm start to answer
t
Thanks for reaching out, Nuwan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'd love to help you save user input audio before the LLM starts responding! Here are a few approaches you might consider: • Client-Side Recording: You can have a client or bot join the room, subscribe to the user's microphone track, and save the raw audio frames to a file in real time. This way, you’ll capture the audio right before any processing happens. • Agent-Level Audio Access: Inside the agent, it’s possible to access the internal audio stream using methods like
attachAudioInput
and
tee()
. This lets you split the audio stream—saving one copy to a file while sending the other to the LLM pipeline. Keep in mind, this approach will need some extra file system access and encoding setup. • Egress + Post-Processing: Another option is recording the entire room session using egress (for example,
RoomCompositeEgressRequest
) and then extracting the user input from the recorded file afterward. This works well if you don’t need real-time saving. Please feel free to reach out if you'd like me to walk you through detailed implementation steps for any of these methods, or if you have specific needs like real-time saving or post-processing. I'm here to help! Sources: examples/receive-audio/index.ts | agents/src/voice/agent_activity.ts | Agent speech and audio | LiveKit Docs | egress/recording_agent.py
p
i want save user input mic audio. it has not client side. it only run livekit usign console command
t
I'm glad you asked about saving user microphone input audio in your LiveKit agent running via console command! You can easily do this using the built-in recording functionality in the
chat_cli.py
module. This handy feature lets you record both the user's input and the agent's responses automatically, making things simple for you. Here’s a friendly step-by-step to get you started: 1. Just run your agent script with the
--record
flag like this:
python your_agent_script.py console --record
2. The audio will be saved as a timestamped
.ogg
file (for example,
console_YYYY-MM-DD_HH-MM.ogg
) right in your current directory. 3. The recording kicks off automatically when your session begins and stops as soon as it ends. The best part? You don’t need to change any code—it works perfectly out-of-the-box with the console interface. If you have any questions or want me to walk you through anything else, just let me know. I’m here to help! Sources: livekit-plugins/livekit-plugins-tavus/livekit/plugins/tavus/avatar.py | Session recording and transcripts | LiveKit Docs
p
python your_agent_script.py console --record from this only save agent voice. it not save users voice
t
Thank you for reaching out! I understand you're looking to save only the user's microphone input, rather than the mixed audio recorded by the default
--record
flag in LiveKit's console mode. To achieve this, a custom approach is needed to capture and save the raw input audio frames before they reach the agent. Here’s a friendly outline to guide you through this: 1. Intercept Audio Frames: Adjust the agent to grab the raw audio frames directly from the user's microphone, before they’re processed by the LLM or STT pipeline. 2. Buffer Audio: Keep these audio frames stored in a buffer throughout the session. 3. Save to File: At the end of the session, write the buffered audio to a file format like WAV or OGG. If you'd like, I’d be happy to provide detailed code examples or walk you through the implementation step-by-step. Just let me know how I can assist you further! Sources: examples/voice_agents/realtime_video_agent.py | basics/echo_transcriber_agent.py
p
yes i want
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!