I get this error - ```(.venv) root@livekit:~# pyth...
# ask-ai
d
I get this error -
Copy code
(.venv) root@livekit:~# python3 new_.py  connect --room my-first-room
2025-09-01 07:17:19,677 - DEBUG asyncio - Using selector: EpollSelector 
2025-09-01 07:17:19,680 - DEV  livekit.agents - Watching /root 
2025-09-01 07:17:21,455 - DEBUG asyncio - Using selector: EpollSelector 
2025-09-01 07:17:21,460 - INFO livekit.agents - starting worker {"version": "1.2.6", "rtc-version": "1.0.12"}
2025-09-01 07:17:21,461 - INFO livekit.agents - preloading plugins {"packages": ["livekit.plugins.cartesia", "livekit.plugins.deepgram", "livekit.plugins.openai", "livekit.plugins.silero", "livekit.plugins.sarvam", "livekit.plugins.turn_detector", "av"]}
2025-09-01 07:17:21,463 - INFO livekit.agents - starting inference executor 
2025-09-01 07:17:23,102 - INFO livekit.agents - initializing process {"pid": 10310, "inference": true}
2025-09-01 07:17:23,498 - DEBUG livekit.agents - initializing inference runner {"runner": "lk_end_of_utterance_multilingual", "pid": 10310, "inference": true}
2025-09-01 07:17:30,219 - ERROR livekit.agents - worker failed 
Traceback (most recent call last):
  File "/root/.venv/lib/python3.13/site-packages/livekit/agents/utils/aio/duplex_unix.py", line 35, in recv_bytes
    len_bytes = await self._reader.readexactly(4)
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.13/asyncio/streams.py", line 767, in readexactly
    raise exceptions.IncompleteReadError(incomplete, n)
asyncio.exceptions.IncompleteReadError: 0 bytes read on a total of 4 expected bytes

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/root/.venv/lib/python3.13/site-packages/livekit/agents/cli/_run.py", line 79, in _worker_run
    await worker.run()
  File "/root/.venv/lib/python3.13/site-packages/livekit/agents/worker.py", line 403, in run
    await self._inference_executor.initialize()
  File "/root/.venv/lib/python3.13/site-packages/livekit/agents/ipc/supervised_proc.py", line 169, in initialize
    init_res = await asyncio.wait_for(
               ^^^^^^^^^^^^^^^^^^^^^^^
    ...<2 lines>...
    )
    ^
  File "/usr/lib/python3.13/asyncio/tasks.py", line 507, in wait_for
    return await fut
           ^^^^^^^^^
  File "/root/.venv/lib/python3.13/site-packages/livekit/agents/ipc/channel.py", line 47, in arecv_message
    return _read_message(await dplx.recv_bytes(), messages)
                         ^^^^^^^^^^^^^^^^^^^^^^^
  File "/root/.venv/lib/python3.13/site-packages/livekit/agents/utils/aio/duplex_unix.py", line 43, in recv_bytes
    raise DuplexClosed() from e
livekit.agents.utils.aio.duplex_unix.DuplexClosed
2025-09-01 07:17:30,253 - WARNING livekit.agents - Failed to get memory info for process {"pid": 10310, "inference": true}
Traceback (most recent call last):
  File "/root/.venv/lib/python3.13/site-packages/livekit/agents/ipc/supervised_proc.py", line 361, in _memory_monitor_task
    process = psutil.Process(self._pid)
  File "/root/.venv/lib/python3.13/site-packages/psutil/__init__.py", line 317, in __init__
    self._init(pid)
    ~~~~~~~~~~^^^^^
  File "/root/.venv/lib/python3.13/site-packages/psutil/__init__.py", line 363, in _init
    raise NoSuchProcess(pid, msg=msg) from None
psutil.NoSuchProcess: process PID not found (pid=10310)
How do i fix this? Here is my code -
Copy code
class Assistant(Agent):
    def __init__(self) -> None:
        super().__init__(
            instructions="""You are a helpful voice AI assistant.
You automatically adapt to the language the user speaks in, supporting all major Indian languages such as Hindi, Kannada, Tamil, Telugu, Bengali, Marathi, Malayalam, Gujarati, Punjabi, and English.
You eagerly assist users with their questions by providing information from your extensive knowledge.
Your responses are always clear, concise, and to the point, without using any complex formatting or special characters.
You are curious, friendly, and have a natural sense of humor while keeping the conversation respectful and culturally appropriate to the language being spoken.""",
        )

    @function_tool
    async def lookup_weather(self, context: RunContext, location: str):
        logger.info(f"Looking up weather for {location}")
        return "sunny with a temperature of 70 degrees."


def prewarm(proc: JobProcess):
    proc.userdata["vad"] = silero.VAD.load()


async def entrypoint(ctx: JobContext):
    ctx.log_context_fields = {
        "room": ctx.room.name,
    }

    session = AgentSession(
        llm=openai.LLM(model="gpt-4o-mini"),
        stt=sarvam.STT(language="kn-IN", model="saarika:v2.5", api_key=SARVAM_API_KEY),
        tts=sarvam.TTS(target_language_code="kn-IN", speaker="anushka", api_key=SARVAM_API_KEY),
        turn_detection=MultilingualModel(),
        vad=ctx.proc.userdata["vad"],
        preemptive_generation=True,
    )

    @session.on("agent_false_interruption")
    def _on_agent_false_interruption(ev: AgentFalseInterruptionEvent):
        logger.info("false positive interruption, resuming")
        session.generate_reply(instructions=ev.extra_instructions or NOT_GIVEN)

    usage_collector = metrics.UsageCollector()

    @session.on("metrics_collected")
    def _on_metrics_collected(ev: MetricsCollectedEvent):
        metrics.log_metrics(ev.metrics)
        usage_collector.collect(ev.metrics)

    async def log_usage():
        summary = usage_collector.get_summary()
        logger.info("---- Session Summary ----")
        logger.info(f"Total prompt tokens: {summary.llm_prompt_tokens}")
        logger.info(f"Total completion tokens: {summary.llm_completion_tokens}")
        logger.info(f"Total LLM tokens: {summary.llm_total_tokens}")
        logger.info(f"Usage: {summary}")

    ctx.add_shutdown_callback(log_usage)

    # Graceful shutdown callback
    async def cleanup():
        logger.info("Performing cleanup before shutdown")
    ctx.add_shutdown_callback(cleanup)

    # Start the session
    await session.start(
        agent=Assistant(),
        room=ctx.room,
        room_input_options=RoomInputOptions(
            noise_cancellation=noise_cancellation.BVC(),
        ),
    )

    # Connect to the room
    await ctx.connect()

if __name__ == "__main__":
    cli.run_app(WorkerOptions(
        entrypoint_fnc=entrypoint,
        prewarm_fnc=prewarm,
        shutdown_process_timeout=60,  # Ensures proper cleanup
        job_memory_limit_mb=1024,  # Set memory limit to 1GB
        drain_timeout=15,  # Increased ping timeout
    ))
t
Thanks for reaching out, Harsha. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! That error
asyncio.exceptions.IncompleteReadError: 0 bytes read on a total of 4 expected bytes
usually pops up when the connection to the LiveKit server gets cut off unexpectedly. No worries though—here are some friendly steps to help you fix it: 1. Check Your Access Token: Make sure your token is still valid, has the right permissions, and hasn’t expired. Using the
livekit-api
package to generate tokens is a safe bet. 2. Look at Your Network: Double-check that your internet connection is steady and not dropping out. 3. Confirm Room and Server Settings: Verify that the room actually exists and that your
LIVEKIT_URL
is pointing to a proper LiveKit server. 4. Add Some Error Handling: It’s a good idea to wrap your connection code in a try-except block so you can catch issues smoothly. Here’s a quick example:
Copy code
try:
    await room.connect(url, token, options=rtc.RoomOptions(auto_subscribe=True))
except rtc.ConnectError as e:
    logging.error(f"Connection failed: {e}")
except Exception as e:
    logging.error(f"Unexpected error during connection: {e}")
5. Set Up Reconnection Attempts: Sometimes connections just hiccup! Adding retry logic can help. Here’s how you might do it:
Copy code
async def connect_with_retry(room, url, token, max_retries=3):
    for attempt in range(max_retries):
        try:
            await room.connect(url, token)
            logging.info("Connected successfully")
            return
        except Exception as e:
            logging.warning(f"Connection attempt {attempt + 1} failed: {e}")
            if attempt < max_retries - 1:
                await asyncio.sleep(2 ** attempt)  # Exponential backoff
    raise Exception("Failed to connect after retry attempts")
6. Keep an Eye on Disconnect Events: Subscribing to the
"disconnected"
event can give you clues about why the server disconnected you: 7. Update Your SDK: Make sure you’re running the latest versions of the
livekit
and
livekit-api
packages to benefit from all the newest fixes and features. If you’re still stuck after trying these, it might be something on the server side or infrastructure-related. Feel free to reach out if you want to chat more or need a hand—I’m here to help! Sources: livekit-agents/livekit/agents/voice/avatar/_datastream_io.py | examples/e2ee.py
d
is it because the previous one is running, how do i fix that
t
Hey there! If an earlier LiveKit process is still running, it might be causing some hiccups. Here's a quick way to sort it out: 1. Check for Running Processes: Run this command to see all the Python processes currently active:
ps aux | grep python
2. Stop the Previous Process: Find the process ID (PID) for the LiveKit process that's still running, then stop it with:
kill -9 <PID>
3. Double-Check: Run
ps aux
again to make sure no other conflicting processes are hanging around. 4. Restart Your Script: Once everything’s clear, go ahead and restart your script safely. If you hit any snags or want a hand with anything else, just give me a shout!
d
how do i start this process before running the code - raise NoSuchProcess(pid, msg=msg) from None psutil.NoSuchProcess: process PID not found (pid=11184)
t
Hey there! The error
psutil.NoSuchProcess
pops up when you try to access a process that’s already gone. Usually, the LiveKit framework takes care of this for you, so you probably don’t need to do anything. But if you’re manually starting a process, here’s a friendly little checklist to help you out: 1. Make Sure the Process is Actually Running: Double-check that your process is up and running before you try to grab its PID. Something like this works:
process = psutil.Process(pid)\nif process.is_running():\n    memory_mb = process.memory_info().rss / (1024 * 1024)
2. Catch Those Exceptions Smoothly: It’s a good idea to wrap your code in a try-except block so you can handle
NoSuchProcess
errors without a fuss:
try:\n    process = psutil.Process(pid)\n    if process.is_running():\n        memory_mb = process.memory_info().rss / (1024 * 1024)\nexcept (psutil.NoSuchProcess, psutil.AccessDenied):\n    logger.warning("Process no longer accessible")
3. Lean on LiveKit’s Built-in Helpers: If you’re using LiveKit’s supervised process classes like
ProcJobExecutor
, you’re in luck—these errors are already managed for you behind the scenes. 4. Keep an Eye on the Process Lifecycle: Make sure the process isn’t ending too soon or stepping on the toes of another instance. If anything’s unclear or you want to chat more about this, just let me know—I’m here to help! Sources: livekit-agents/livekit/agents/worker.py