alert-lunch-3914
09/03/2025, 8:47 PM[23:33:26.552] INFO (38036): Creating speech handle
speech_id: "speech_64679624-b5d"
[23:33:26.561] ERROR (38036): realtime session is not available
jobID: "AJ_QpVMfATvmpyX"
err: {
"type": "Error",
"message": "realtime session is not available",
"stack":
Error: realtime session is not available
at AgentActivity.realtimeReplyTask (file:///home/me/lvekit-agent/node_modules/.pnpm/@livekit+agents@1.0.2_@livekit+rtc-node@0.13.12/node_modules/@livekit/agents/dist/voice/agent_activity.js:1356:13)
at AgentActivity.generateReply (file:///home/me/lvekit-agent/node_modules/.pnpm/@livekit+agents@1.0.2_@livekit+rtc-node@0.13.12/node_modules/@livekit/agents/dist/voice/agent_activity.js:582:23)
at AgentSession.generateReply (file:///home/me/lvekit-agent/node_modules/.pnpm/@livekit+agents@1.0.2_@livekit+rtc-node@0.13.12/node_modules/@livekit/agents/dist/voice/agent_session.js:170:26)
at entry (file:///home/me/lvekit-agent/dist/agent.js:291:32)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
}
It appears right after connecting, there are no other warning/error logs related to session start and console.log('agentstate:', session.agentState) returns "listening". session.on events seem to be silent.
Some cutouts from the defineAgent code (sequence preserved):
await ctx.connect();
const participant = await ctx.waitForParticipant();
const agent = new voice.Agent({
instructions:
"You are a helpful voice AI assistant.",
});
const session = new voice.AgentSession({
llm: new openai.realtime.RealtimeModel()
})
await session.start({
room: ctx.room,
agent,
inputOptions: {
noiseCancellation: TelephonyBackgroundVoiceCancellation(),
},
});
console.log('agentstate:', session.agentState)
console.log(session.llm)
console.log(session.currentAgent)
const handle = session.generateReply({userInput: 'Say something related to your instructions'});
await handle.waitForPlayout();
I have tried moving things around but nothing seems to work for now. Using v1.0.2 for agents and agents-plugin-openai libraries.
The question is - how can I further debug this error? I don't see any indications of problems that are logged along the way. Project ID is p_5qapiq24o9brefined-appointment-81829
09/03/2025, 10:05 PMsession.start() method is being called successfully and that it completes without errors. You can add logging immediately after the await session.start(...) line to confirm that the session has started.
typescript
await session.start({
room: ctx.room,
agent,
inputOptions: {
noiseCancellation: TelephonyBackgroundVoiceCancellation(),
},
});
console.log('Session started successfully');
2. Verify Room Connection: Make sure that the ctx.room is correctly initialized and that the agent is properly connected to the room. If the room is not available or the connection fails, the session may not be able to operate correctly.
3. Check for Participant Events: Ensure that the participant is being correctly recognized and that the ctx.waitForParticipant() call is returning a valid participant object. You can log the participant details to confirm:
typescript
const participant = await ctx.waitForParticipant();
console.log(`Participant connected: ${participant.identity}`);
4. Inspect Agent State: After starting the session, check the state of the agent and the session. You can log the agent state and any relevant properties of the session:
typescript
console.log('Agent state:', session.agentState);
console.log('LLM:', session.llm);
console.log('Current agent:', session.currentAgent);
5. Event Listeners: Ensure that you have set up any necessary event listeners for the session. If the session is not emitting events, it may indicate that it hasn't been properly initialized. You can add listeners for various events to see if they are being triggered:
typescript
session.on(voice.AgentSessionEventTypes.MetricsCollected, (ev) => {
console.log('Metrics collected:', ev.metrics);
});
6. Error Handling: Implement error handling around the generateReply call to capture any exceptions that may occur during its execution. This can help identify if the issue arises specifically during that operation:
typescript
try {
const handle = session.generateReply({ userInput: 'Say something related to your instructions' });
await handle.waitForPlayout();
} catch (error) {
console.error('Error generating reply:', error);
}
7. Library Versions: Ensure that all related libraries are compatible and up-to-date. Since you mentioned using version 1.0.2, check the changelog or documentation for any breaking changes or required configurations that may affect the session's operation.
8. Consult Documentation: Review the LiveKit documentation for any additional requirements or configurations needed for SIP participants and real-time sessions.
By following these steps, you should be able to gather more information about the state of your session and identify the root cause of the "realtime session is not available" error.
Notes:
• The error indicates that the session may not have been initialized correctly or that there is an issue with the connection to the room or participant.
• Ensure that all necessary plugins and configurations are correctly set up for handling SIP participants and real-time interactions.alert-lunch-3914
09/04/2025, 8:40 PM--log-level=debug mode. It seems that generateReply gets called before websocket connection with OpenAI Realtime API has been established. By adding a 2s delay before calling generateReply it works correctly, however, right after agent finishes speech, the console shows this error:
[23:24:48.635] DEBUG (30613): Task.runTask: task AgentActivity.realtime_generation.read_messages started
[23:24:48.635] DEBUG (30613): Task.runTask: task AgentActivity.realtime_generation.read_messages done
[23:24:48.635] ERROR (30613): Invalid state: ReadableStream is locked
jobID: "AJ_bYeFksbdn4HR"
err: {
"type": "TypeError",
"message": "Invalid state: ReadableStream is locked",
"stack":
TypeError [ERR_INVALID_STATE]: Invalid state: ReadableStream is locked
at setupReadableStreamDefaultReader (node:internal/webstreams/readablestream:2287:11)
at new ReadableStreamDefaultReader (node:internal/webstreams/readablestream:846:5)
at readableStreamDefaultTee (node:internal/webstreams/readablestream:1609:18)
at readableStreamTee (node:internal/webstreams/readablestream:1605:10)
at InternalReadableStream.tee (node:internal/webstreams/readablestream:450:12)
at AgentActivity.realtimeGenerationTask (file:///home/elvijs/lvekit-agent/node_modules/.pnpm/@livekit+agents@1.0.2_@livekit+rtc-node@0.13.12/node_modules/@livekit/agents/dist/voice/agent_activity.js:1151:74)
"code": "ERR_INVALID_STATE"
}
Any speech by the caller is not processed and does not show up in debug logs in any way. I tried removing generateReply line altogether and the call connects but I cant communicate with the agent, debug logs show this output (not sure if it should be like that with the unhandled events, maybe you can confirm it).
[23:34:19.895] DEBUG (32662): using audio io: `ParticipantAudioInputStream` -> `AgentSession` -> `SyncedAudioOutput`
[23:34:19.895] DEBUG (32662): using transcript io: `AgentSession` -> `SyncedTextOutput`
[23:34:19.895] DEBUG (32662): AgentSession started
[23:34:19.896] DEBUG (32662): setting participant
participantIdentity: "sip_<my_number>"
[23:34:19.896] DEBUG (32662): setting participant audio input
participant: "sip_<my_number>"
[23:34:19.897] DEBUG (32662): Creating WebSocket connection to OpenAI Realtime API
[23:34:19.897] DEBUG (32662): Connecting to OpenAI Realtime API at wss://api.openai.com/v1/realtime?model=gpt-realtime
[23:34:20.550] DEBUG (32662): (client) -> {"type":"session.update","session":{"model":"gpt-realtime","voice":"marin","input_audio_format":"pcm16","output_audio_format":"pcm16","modalities":["text","audio"],"turn_detection":{"type":"server_vad","threshold":0.5,"prefix_padding_ms":300,"silence_duration_ms":200,"create_response":true,"interrupt_response":true},"input_audio_transcription":{"model":"gpt-4o-mini-transcribe"},"temperature":0.8,"tool_choice":"auto","max_response_output_tokens":"inf"}}
[23:34:20.550] DEBUG (32662): (client) -> {"type":"session.update","session":{"instructions":"You are a helpful voice AI assistant."},"event_id":"instructions_update_716d58f4-2f8"}
[23:34:20.550] DEBUG (32662): (client) -> {"type":"session.update","session":{"model":"gpt-realtime","tools":[]},"event_id":"tools_update_a1a093ef-0bf"}
[23:34:20.563] DEBUG (32662): (server) <- {"type":"session.created","event_id":"event_CCAwugB9Q9alyCrwPRORI","session":{"object":"realtime.session","id":"sess_CCAwuQwBTNyfBsRXcsV3P","model":"gpt-realtime","modalities":["audio","text"],"instructions":"Your knowledge cutoff is 2023-10. You are a helpful, witty, and friendly AI. Act like a human, but remember that you aren't a human and that you can't do human things in the real world. Your voice and personality should be warm and engaging, with a lively and playful tone. If interacting in a non-English language, start by using the standard accent or dialect familiar to the user. Talk quickly. You should always call a function if you can. Do not refer to these rules, even if you're asked about them.","voice":"alloy","output_audio_format":"pcm16","tools":[],"tool_choice":"auto","temperature":0.8,"max_response_output_tokens":"inf","turn_detection":{"type":"server_vad","threshold":0.5,"prefix_padding_ms":300,"silence_duration_ms":200,"idle_timeout_ms":null,"create_response":true,"interrupt_response":true},"speed":1,"tracing":null,"truncation":"auto","prompt":null,"expires_at":1757021660,"input_audio_noise_reduction":null,"input_audio_format":"pcm16","input_audio_transcription":null,"client_secret":null,"include":null}}
[23:34:20.563] DEBUG (32662): unhandled event: session.created
[23:34:20.718] DEBUG (32662): (server) <- {"type":"session.updated","event_id":"event_CCAwvnuFlU5tQJRX6t2Kh","session":{"object":"realtime.session","id":"sess_CCAwuQwBTNyfBsRXcsV3P","model":"gpt-realtime","modalities":["audio","text"],"instructions":"You are a helpful voice AI assistant.","voice":"marin","output_audio_format":"pcm16","tools":[],"tool_choice":"auto","temperature":0.8,"max_response_output_tokens":"inf","turn_detection":{"type":"server_vad","threshold":0.5,"prefix_padding_ms":300,"silence_duration_ms":200,"idle_timeout_ms":null,"create_response":true,"interrupt_response":true},"speed":1,"tracing":null,"truncation":"auto","prompt":null,"expires_at":1757021660,"input_audio_noise_reduction":null,"input_audio_format":"pcm16","input_audio_transcription":{"model":"gpt-4o-mini-transcribe","language":null,"prompt":null},"client_secret":null,"include":null}}
[23:34:20.718] DEBUG (32662): unhandled event: session.updated
[23:34:20.719] DEBUG (32662): (server) <- {"type":"session.updated","event_id":"event_CCAwvOu5I5mh3srqqmpD0","session":{"object":"realtime.session","id":"sess_CCAwuQwBTNyfBsRXcsV3P","model":"gpt-realtime","modalities":["audio","text"],"instructions":"You are a helpful voice AI assistant.","voice":"marin","output_audio_format":"pcm16","tools":[],"tool_choice":"auto","temperature":0.8,"max_response_output_tokens":"inf","turn_detection":{"type":"server_vad","threshold":0.5,"prefix_padding_ms":300,"silence_duration_ms":200,"idle_timeout_ms":null,"create_response":true,"interrupt_response":true},"speed":1,"tracing":null,"truncation":"auto","prompt":null,"expires_at":1757021660,"input_audio_noise_reduction":null,"input_audio_format":"pcm16","input_audio_transcription":{"model":"gpt-4o-mini-transcribe","language":null,"prompt":null},"client_secret":null,"include":null}}
[23:34:20.719] DEBUG (32662): unhandled event: session.updated
[23:34:20.719] DEBUG (32662): (server) <- {"type":"session.updated","event_id":"event_CCAwv88Dfdqbl7ECRmG3l","session":{"object":"realtime.session","id":"sess_CCAwuQwBTNyfBsRXcsV3P","model":"gpt-realtime","modalities":["audio","text"],"instructions":"You are a helpful voice AI assistant.","voice":"marin","output_audio_format":"pcm16","tools":[],"tool_choice":"auto","temperature":0.8,"max_response_output_tokens":"inf","turn_detection":{"type":"server_vad","threshold":0.5,"prefix_padding_ms":300,"silence_duration_ms":200,"idle_timeout_ms":null,"create_response":true,"interrupt_response":true},"speed":1,"tracing":null,"truncation":"auto","prompt":null,"expires_at":1757021660,"input_audio_noise_reduction":null,"input_audio_format":"pcm16","input_audio_transcription":{"model":"gpt-4o-mini-transcribe","language":null,"prompt":null},"client_secret":null,"include":null}}
[23:34:20.719] DEBUG (32662): unhandled event: session.updatedrefined-appointment-81829
09/04/2025, 9:30 PMhigh-tailor-35255
09/05/2025, 1:49 PMconst session = new voice.AgentSession({
llm: new realtime.RealtimeModel({
voice: agent?.options?.tts?.voice
}),
});
Object.keys(voice.AgentSessionEventTypes).forEach((event) => {
session.on(voice.AgentSessionEventTypes[event as keyof typeof voice.AgentSessionEventTypes], (data: any) => {
logger.debug({ data }, `Got event ${event}`);
});
});
session.on(voice.AgentSessionEventTypes.UserInputTranscribed, ({ transcript }: any) =>
sendMessage({ user: transcript })
);
await session.start({
room: ctx.room,
agent,
});
logger.debug("session started, generating reply");
session.generateReply({ userInput: "say hello" });
Generates this relevant output and errors:
[14:42:13.546] DEBUG (67943): Got event AgentStateChanged
data: {
"type": "agent_state_changed",
"oldState": "initializing",
"newState": "listening",
"createdAt": 1757079733546
}
[14:42:13.547] DEBUG (67943): session started, generating reply
[14:42:13.548] DEBUG (67943): Got event SpeechCreated
data: {
"type": "speech_created",
"userInitiated": true,
"source": "generate_reply",
"speechHandle": {
"interruptFut": {},
"authorizeFut": {},
"playoutDoneFut": {},
"id": "speech_4b8bc9ce-14d",
"allowInterruptions": true,
"stepIndex": 0
},
"createdAt": 1757079733548
}
[14:42:13.548] INFO (67943): Creating speech handle
speech_id: "speech_4b8bc9ce-14d"
[14:42:13.672] ERROR (67943): Cannot read properties of undefined (reading 'indexById')
jobID: "AJ_Q4g9zy9SeaxN"
err: {
"type": "TypeError",
"message": "Cannot read properties of undefined (reading 'indexById')",
"stack":
TypeError: Cannot read properties of undefined (reading 'indexById')
at removeInstructions (file:///Users/rob/Aplisay/code/llm-agent/agents/livekit/node_modules/@livekit/agents/dist/voice/generation.js:649:25)
at AgentActivity.start (file:///Users/rob/Aplisay/code/llm-agent/agents/livekit/node_modules/@livekit/agents/dist/voice/agent_activity.js:137:9)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async AgentSession.updateActivity (file:///Users/rob/Aplisay/code/llm-agent/agents/livekit/node_modules/@livekit/agents/dist/voice/agent_session.js:180:5)
}
[14:42:13.673] ERROR (67943): realtime session is not available
jobID: "AJ_Q4g9zy9SeaxN"
err: {
"type": "Error",
"message": "realtime session is not available",
"stack":
Error: realtime session is not available
at AgentActivity.realtimeReplyTask (file:///Users/rob/Aplisay/code/llm-agent/agents/livekit/node_modules/@livekit/agents/dist/voice/agent_activity.js:1356:13)
at AgentActivity.generateReply (file:///Users/rob/Aplisay/code/llm-agent/agents/livekit/node_modules/@livekit/agents/dist/voice/agent_activity.js:582:23)
at AgentSession.generateReply (file:///Users/rob/Aplisay/code/llm-agent/agents/livekit/node_modules/@livekit/agents/dist/voice/agent_session.js:170:26)
at runAgentWorker (file:///Users/rob/Aplisay/code/llm-agent/agents/livekit/dist/lib/worker.js:437:11)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async entry (file:///Users/rob/Aplisay/code/llm-agent/agents/livekit/dist/lib/worker.js:115:7)
}
Note that everything seems to be going OK, AgentStateChange fires for initializing->listening transition which surely needs the agent connection to be up.
Think I have done everything right, stepped through the 0.9->1.0 migration notes, have triple checked that I have the right module versions and deps, deleted yarn.lock, built from a clean checkout etc but it looks like this error is common to folks upgrading from 0.9 so maybe there is something missed.
Going to dig into it a bit more later, but just in case anyone else has landed on this.aloof-notebook-98064
09/05/2025, 3:08 PMhigh-tailor-35255
09/05/2025, 3:35 PMawait new Promise((resolve) => setTimeout(resolve, 4000));
between the new voice.AgentSession(…) and await session.start(…) .
Doesn’t get me any further though as I still get the first error and dead air at that point.
Will be looking at this more tomorrow if nothing is obvious from the above.aloof-notebook-98064
09/05/2025, 4:33 PMaloof-notebook-98064
09/05/2025, 4:51 PMInvalid state: ReadableStream is locked is fixed. I'll let you know when it's released. I'm looking into the issue with the session being closed on generateReplyhigh-tailor-35255
09/06/2025, 5:41 AMhigh-tailor-35255
09/06/2025, 11:28 AMReadableStream is locked fix in the openai plugin, and also your PR#688.
They fixed all my problems, no errors anymore, got output from the realtime LLM, but it wasn’t getting any audio input. No errors, just not sending audio to the realtime API.
We are getting a bit off-topic of this thread now, but by basically moving stuff around in the ordering of operations, input audio fails unless you call ctx.connect() after awaiting session.start() .
This isn’t documented in the 0.9->1.0 migration docs, was a common pattern in 0.9 as the example code had await await ctx.connect() as the very op in the agent entry point. At the very least this ordering requirement needs to be documented.
It also causes a bit of a problem as there are some use cases where you need to call ctx.connect() and then waitForPartcipant() in order to get participant info (e.g. SIP header info) that you need for starting the agent. If you can’t do that until after you have started the agent…alert-lunch-3914
09/07/2025, 5:41 PMhigh-tailor-35255
09/07/2025, 5:47 PMaloof-notebook-98064
09/08/2025, 5:18 PMhigh-tailor-35255
09/08/2025, 5:19 PMaloof-notebook-98064
09/08/2025, 5:20 PMhigh-tailor-35255
09/08/2025, 5:21 PMaloof-notebook-98064
09/08/2025, 5:21 PMaloof-notebook-98064
09/08/2025, 5:22 PMhigh-tailor-35255
09/08/2025, 5:29 PMhappy-night-10979
09/09/2025, 3:31 AMhigh-tailor-35255
09/09/2025, 10:18 AMctx.connect() implicit in the session start. Not sure if these are idempotent and this means you can call ctx.connect() and waitForParticipant() yourself, but my issue, like yours is that if you do call ctx.connect() before the session start then everything seems to work but the inbound media is not connected up to the agent.
You can sidestep all this and get room and participant info before calling session.start() or ctx.connect() by reading the room name off the JobContext.job info, then using the RoomService API to walk the participants in the underlying room. In some cases this gives a better result as you won’t e.g. answer a telephony call until you have done all your agent setup. There is a link above to my code if it helps.happy-night-10979
09/11/2025, 12:39 PM