Hello! After migrating Node.js agent code to v1 (R...
# agents
a
Hello! After migrating Node.js agent code to v1 (Realtime with SIP), I am stuck with this error after I make a phone call to the agent.
Copy code
[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):
Copy code
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_5qapiq24o9b
r
To debug the error "realtime session is not available" in your Node.js agent after migrating to version 1.0, you can follow these steps: 1. Check Session Initialization: Ensure that the
session.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.
Copy code
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:
Copy code
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:
Copy code
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:
Copy code
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:
Copy code
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.
a
@refined-appointment-81829 thank you for the response, these steps did not help much but I managed to find a clue by running agent in
--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:
Copy code
[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).
Copy code
[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.updated
r
@aloof-notebook-98064 You have any advise?
h
I’m getting the same error, with a different prior error after migrating from 0.9 -> 1.0 agents-js, this code…
Copy code
const 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:
Copy code
[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.
a
I’ll take a look
🙏🏼 1
🙏 1
h
I can also make the second error go away by inserting a
await 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.
a
@high-tailor-35255 can you send me your file for the agent?
the
Invalid 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
generateReply
🙌 2
@aloof-notebook-98064 Thanks! I’ve patched my local project with a build which contains your
ReadableStream 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…
➕ 1
a
@aloof-notebook-98064 Thank you! However, as the commenter above mentioned in last paragraph, that problem is relevant for me as well. Is it by design or will there be a future fix that will allow to get participant info before starting the session? I also need to get metadata from the participant to get agent context.
h
There is a way of getting the participant info before you connect as a workaround, but it is pretty long winded. You have to get the Room name from the Job info in the context (can’t get it from the room object as that isn’t populated until you connect). Then use the RoomService API from the livekit node sdk to list the participants for that room. Your remote participant will always be participant[0]. To make it even more fun, the ParticipantInfo field names in the node sdk are slightly different to the participant object you get in the room context (camel case rather than dotted).
🙏 1
a
What plugins are you all using for the realtime model?
h
@livekit/agents-plugin-openai
➕ 1
a
Are you still having the issue of the audio not being forwarded?
h
Don’t know, I refactored so that I call ctx.connect() after servce.start() and that resolved it for me. Has there beed a related fix?
a
No but I agree that remembering to call ctx.connect() after session.start() is annoying. Going to see if I can make so that we can handle this all in session.start()
Thanks for calling this out
h
I think it is mainly an issue because old sample code had ctx.connect() as the very first line of the job entrypoint, so anyone porting from 0.9 will come across this. My refactor is a bit complex because I want to get access to the room name and participant info before starting the agent so have to do things like calling roomService.listParticipants() to grab that rather than just ctx.connect() and waitForParticipant() at the top of the worker. Having gone to the trouble of doing this, I’m going to stick with it for my use case as it delays the answer until the agent is in the room which is an improvement.
h
I can confirm this issue as well, it would be really helpful if I can call ctx.connect at the beginning, I have similar implementation as Rob
h
@happy-night-10979 just had a look at the commits @aloof-notebook-98064 just made and it looks like what they do is make the call to
ctx.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.
h
@high-tailor-35255 Yes it is possible to do it like that, thank you. I just wanted to send message (ctx.room.localParticipant.publishData) before I call session.start() which doesn't work for me right now.