initialization timed out, killing process. this heppens very often and sometimes I can start the agent without any issue.
Sometimes it runs successfully, but most of the time I get this error.
.venv/bin/python3.10 agent.py dev
2025-02-06 05:02:51,425 - DEBUG asyncio - Using selector: EpollSelector
2025-02-06 05:02:51,429 - DEV livekit.agents - Watching /home/ai-agent/agent
2025-02-06 05:03:02,101 - DEBUG asyncio - Using selector: EpollSelector
2025-02-06 05:03:02,298 - INFO livekit.agents - starting worker {"version": "0.12.10", "rtc-version": "0.19.1"}
2025-02-06 05:03:02,298 - INFO livekit.agents - starting inference executor
2025-02-06 05:03:12,065 - INFO livekit.agents - initializing inference process {"pid": 13864, "inference": true}
2025-02-06 05:03:12,065 - DEBUG livekit.agents - initializing inference runner {"runner": "lk_end_of_utterance", "pid": 13864, "inference": true}
2025-02-06 05:03:32,340 - ERROR livekit.agents - initialization timed out, killing process {"pid": 13864, "inference": true}
2025-02-06 05:03:32,340 - INFO livekit.agents - killing process {"pid": 13864, "inference": true}
2025-02-06 05:03:32,340 - ERROR livekit.agents - worker failed
Traceback (most recent call last):
File "/home/ai-agent/agent/.venv/lib/python3.10/site-packages/livekit/agents/ipc/channel.py", line 47, in arecv_message
return _read_message(await dplx.recv_bytes(), messages)
File "/home/ai-agent/agent/.venv/lib/python3.10/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.10/asyncio/streams.py", line 708, in readexactly
await self._wait_for_data('readexactly')
File "/usr/lib/python3.10/asyncio/streams.py", line 501, in _wait_for_data
await self._waiter
asyncio.exceptions.CancelledError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.10/asyncio/tasks.py", line 456, in wait_for
return fut.result()
asyncio.exceptions.CancelledError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/ai-agent/agent/.venv/lib/python3.10/site-packages/livekit/agents/cli/cli.py", line 266, in _worker_run
await worker.run()
File "/home/ai-agent/agent/.venv/lib/python3.10/site-packages/livekit/agents/worker.py", line 330, in run
await self._inference_executor.initialize()
File "/home/ai-agent/agent/.venv/lib/python3.10/site-packages/livekit/agents/ipc/supervised_proc.py", line 164, in initialize
init_res = await asyncio.wait_for(
File "/usr/lib/python3.10/asyncio/tasks.py", line 458, in wait_for
raise exceptions.TimeoutError() from exc
asyncio.exceptions.TimeoutError
agent.py
import logging
from dotenv import load_dotenv
from livekit.agents import (
AutoSubscribe,
JobContext,
JobProcess,
WorkerOptions,
cli,
)
from livekit.plugins import turn_detector, silero
from livekit.agents.pipeline import VoicePipelineAgent
from whisperSTT import WhisperSTT
from miraLLM import MiraLLM
from xTTS import XTTS
load_dotenv(dotenv_path=".env")
logger = logging.getLogger("voice-agent")
def prewarm(proc: JobProcess):
proc.userdata["vad"] = silero.VAD.load()
async def entrypoint(ctx: JobContext):
stt = WhisperSTT()
tts = XTTS()
mira_llm = MiraLLM()
logger.info(f"connecting to room {ctx.room.name}")
await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)
# Wait for the first participant to connect
participant = await ctx.wait_for_participant(identity='agent-connector')
logger.info(f"starting voice assistant for participant {participant.identity}")
agent = VoicePipelineAgent(
turn_detector=turn_detector.EOUModel(),
vad=ctx.proc.userdata["vad"],
stt=stt,
tts=tts,
llm=mira_llm,
)
logger.info('agent started')
agent.start(ctx.room, participant)
def on_participant_disconnected(participant):
logger.info(participant)
if participant.identity == "agent-connector":
ctx.shutdown(reason="Conversation concluded")
ctx.room.on('participant_disconnected', on_participant_disconnected)
# The agent should be polite and greet the user when it joins :)
await agent.say("Hey, how can I help you today?", allow_interruptions=True)
if __name__ == "__main__":
cli.run_app(
WorkerOptions(
entrypoint_fnc=entrypoint,
prewarm_fnc=prewarm,
job_memory_warn_mb=15000,
initialize_process_timeout=2000,
agent_name="taiga-ai-voice-agent",
),
)
what are these libraries?
from whisperSTT import WhisperSTT
from miraLLM import MiraLLM
from xTTS import XTTS
if they are performing heavy operations when modules are getting loaded.. this is expected to timeout
@davidzhao Ahh, do I have any option to increase the timeout limit? cause when it succeed in running it takes around a minute to start. And, those libraries are my custom implantation for Whisper STT, XTTs, and LLM. I can provide you the files if needed. here is a log for successful run. ran the command at 09:44:01
.venv/bin/python agent.py dev
2025-02-06 09:44:12,935 - DEBUG asyncio - Using selector: EpollSelector
2025-02-06 09:44:12,938 - DEV livekit.agents - Watching /home/ai-agent/agent
2025-02-06 09:44:24,532 - DEBUG asyncio - Using selector: EpollSelector
2025-02-06 09:44:24,753 - INFO livekit.agents - starting worker {"version": "0.12.10", "rtc-version": "0.19.1"}
2025-02-06 09:44:24,753 - INFO livekit.agents - starting inference executor
2025-02-06 09:44:35,595 - INFO livekit.agents - initializing inference process {"pid": 15310, "inference": true}
2025-02-06 09:44:35,596 - DEBUG livekit.agents - initializing inference runner {"runner": "lk_end_of_utterance", "pid": 15310, "inference": true}
2025-02-06 09:44:50,141 - INFO livekit.agents - inference process initialized {"pid": 15310, "inference": true}
2025-02-06 09:44:50,141 - DEBUG asyncio - Using selector: EpollSelector {"pid": 15310, "inference": true}
2025-02-06 09:44:50,269 - INFO livekit.agents - registered worker {"id": "AW_jDAn4UfG9bsX", "region": "Germany", "protocol": 15, "node_id": "NC_OFRANKFURT1A_b4NWncU9BbCW"}
Not initial in here. Slowly.
stt = WhisperSTT()
tts = XTTS()
mira_llm = MiraLLM()
did you find any solution? because I am also stuck in this problem
try to load your llm, stt, tts in prewarm function then use them in entrypoint, maybe your issue get resolved after this. Can you provide your implementation of opensource stt, tts, llm please.
@Harras3 Ok, I tried doing what you suggested I have moved my stt, tts, and llm to the prewarm function. But, the issue still persists.
Since then I also moved to an open AI compatible tts, and stt server. here is my tts file, as for the stt I am using the openai stt plugin.
from __future__ import annotations
import logging
from dataclasses import dataclass
import httpx
from livekit.agents import (
DEFAULT_API_CONNECT_OPTIONS,
APIConnectionError,
APIConnectOptions,
APIStatusError,
APITimeoutError,
tts,
utils,
)
import openai
from livekit.plugins.openai.models import TTSModels, TTSVoices
from livekit.plugins.openai.utils import AsyncAzureADTokenProvider
# from langdetect import detect_langs
from lingua import Language, LanguageDetectorBuilder
logger = logging.getLogger("voice-agent")
OPENAI_TTS_SAMPLE_RATE = 24000
OPENAI_TTS_CHANNELS = 1
languages = [
Language.ENGLISH, Language.FRENCH, Language.SPANISH,
Language.ITALIAN, Language.PORTUGUESE, Language.HINDI,
Language.JAPANESE, Language.CHINESE
]
voice_mapper = {
"ENGLISH": "af_heart", # English
"FRENCH": "ff_siwis", # French
"SPANISH": "ef_dora", # Spanish
"ITALIAN": "if_sara", # Italian
"PORTUGUESE": "pf_dora", # Portuguese
"HINDI": "hf_alpha", # Hindi
"JAPANESE": "jf_alpha", # Japanese
"CHINESE": "zf_xiaobei", # Chinese
}
# Create a language detector
detector = LanguageDetectorBuilder.from_languages(*languages).build()
@dataclass
class _TTSOptions:
model: TTSModels | str
voice: TTSVoices | str
speed: float
class TTS(tts.TTS):
def __init__(
self,
*,
model: TTSModels | str = "tts-1",
voice: TTSVoices | str = "alloy",
speed: float = 1.0,
base_url: str | None = None,
api_key: str | None = None,
client: openai.AsyncClient | None = None,
) -> None:
"""
Create a new instance of OpenAI TTS.
``api_key`` must be set to your OpenAI API key, either using the argument or by setting the
``OPENAI_API_KEY`` environmental variable.
"""
super().__init__(
capabilities=tts.TTSCapabilities(
streaming=False,
),
sample_rate=OPENAI_TTS_SAMPLE_RATE,
num_channels=OPENAI_TTS_CHANNELS,
)
self._opts = _TTSOptions(
model=model,
voice=voice,
speed=speed,
)
self._client = client or openai.AsyncClient(
max_retries=0,
api_key=api_key,
base_url=base_url,
http_client=httpx.AsyncClient(
timeout=httpx.Timeout(connect=15.0, read=5.0, write=5.0, pool=5.0),
follow_redirects=True,
limits=httpx.Limits(
max_connections=50,
max_keepalive_connections=50,
keepalive_expiry=120,
),
),
)
def update_options(
self, *, model: TTSModels | None, voice: TTSVoices | None, speed: float | None
) -> None:
self._opts.model = model or self._opts.model
self._opts.voice = voice or self._opts.voice
self._opts.speed = speed or self._opts.speed
@staticmethod
def create_azure_client(
*,
model: TTSModels = "tts-1",
voice: TTSVoices = "alloy",
speed: float = 1.0,
azure_endpoint: str | None = None,
azure_deployment: str | None = None,
api_version: str | None = None,
api_key: str | None = None,
azure_ad_token: str | None = None,
azure_ad_token_provider: AsyncAzureADTokenProvider | None = None,
organization: str | None = None,
project: str | None = None,
base_url: str | None = None,
) -> TTS:
"""
This automatically infers the following arguments from their corresponding environment variables if they are not provided:
- `api_key` from `AZURE_OPENAI_API_KEY`
- `organization` from `OPENAI_ORG_ID`
- `project` from `OPENAI_PROJECT_ID`
- `azure_ad_token` from `AZURE_OPENAI_AD_TOKEN`
- `api_version` from `OPENAI_API_VERSION`
- `azure_endpoint` from `AZURE_OPENAI_ENDPOINT`
"""
azure_client = openai.AsyncAzureOpenAI(
max_retries=0,
azure_endpoint=azure_endpoint,
azure_deployment=azure_deployment,
api_version=api_version,
api_key=api_key,
azure_ad_token=azure_ad_token,
azure_ad_token_provider=azure_ad_token_provider,
organization=organization,
project=project,
base_url=base_url,
) # type: ignore
return TTS(model=model, voice=voice, speed=speed, client=azure_client)
def synthesize(
self,
text: str,
*,
conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
) -> "ChunkedStream":
return ChunkedStream(
tts=self,
input_text=text,
conn_options=conn_options,
opts=self._opts,
client=self._client,
)
class ChunkedStream(tts.ChunkedStream):
def __init__(
self,
*,
tts: TTS,
input_text: str,
conn_options: APIConnectOptions,
opts: _TTSOptions,
client: openai.AsyncClient,
) -> None:
super().__init__(tts=tts, input_text=input_text, conn_options=conn_options)
self._client = client
self._opts = opts
def get_voice(self, text: str):
voice = "af_heart"
if text.strip():
detected_lang = detector.detect_multiple_languages_of(text)
for lang in detected_lang:
if lang.language.name in voice_mapper:
return voice_mapper[lang.language.name] # Prioritize leftmost detected language
return voice
async def _run(self):
voice = self.get_voice(text=self.input_text)
oai_stream = self._client.audio.speech.with_streaming_response.create(
input=self.input_text,
model=self._opts.model,
voice=voice, # type: ignore
response_format="pcm",
speed=self._opts.speed,
timeout=httpx.Timeout(30, connect=self._conn_options.timeout),
)
request_id = utils.shortuuid()
audio_bstream = utils.audio.AudioByteStream(
sample_rate=OPENAI_TTS_SAMPLE_RATE,
num_channels=OPENAI_TTS_CHANNELS,
)
try:
async with oai_stream as stream:
async for data in stream.iter_bytes():
for frame in audio_bstream.write(data):
self._event_ch.send_nowait(
tts.SynthesizedAudio(
frame=frame,
request_id=request_id,
)
)
for frame in audio_bstream.flush():
self._event_ch.send_nowait(
tts.SynthesizedAudio(
frame=frame,
request_id=request_id,
)
)
except openai.APITimeoutError:
raise APITimeoutError()
except openai.APIStatusError as e:
raise APIStatusError(
e.message,
status_code=e.status_code,
request_id=e.request_id,
body=e.body,
)
except Exception as e:
raise APIConnectionError() from e
Ok, Identified the issue. It is related to my lower read speed of storage and not related to livekit-agent. closing the issue.
Ok, Identified the issue. It is related to my lower read speed of storage and not related to livekit-agent. closing the issue.
I am still facing the issue, so how did you solve this issue.
Have you solved this issue?
There is a initialize_process_timeout option in WorkerOptions. You can try to move the slow module loading to prewarm and increase the timeout like
cli.run_app(
WorkerOptions(
entrypoint_fnc=entrypoint,
initialize_process_timeout=60,
prewarm_fnc=...
)
)