thankful-twilight-49934
10/01/2025, 9:11 AMtall-airline-16756
10/01/2025, 9:11 AMtall-airline-16756
10/01/2025, 9:12 AMlk agent delete (or destroy): Use this to permanently stop and remove the agent when you’re ready.
Now, if you’re looking to temporarily pause certain behaviors of an agent—like stopping the audio input—you can do that within the agent’s code using the LiveKit Agents SDK. For example:
• Call session.input.set_audio_enabled(False) to pause the agent from listening to audio input.
• Call session.input.set_audio_enabled(True) when you want it to start listening again.
Just a heads-up: this kind of control needs to be built into the agent’s runtime code since it’s not handled through the CLI. If you need any help with that, feel free to ask—I’m here to help!
Sources: cmd/lk/main.go | Agent deployment CLI reference | LiveKit Docs | Text and transcriptions | LiveKit Docs | Text and transcriptions | LiveKit Docsthankful-twilight-49934
10/01/2025, 9:38 AMtall-airline-16756
10/01/2025, 9:39 AMlibc++abi: terminating due to uncaught exception of type std::__1::system_error: mutex lock failed: Invalid argument in long-running agents is often related to native threading or synchronization challenges, such as mutex state corruption. This can happen if resources aren’t cleaned up properly, if there are signal interruptions, or if threads are reused unexpectedly.
To help you address this, here are some steps you can try:
• Make sure to always call await job_ctx.shutdown() in your agent’s entrypoint to properly clean up resources.
• Try to avoid using os._exit(1) for shutdowns; instead, using await worker.aclose() allows for a more graceful termination.
• Enable ggml backtraces by setting `GGML_NO_BACKTRACE=0`—this can be really helpful for debugging mutex-related issues.
• Be sure not to reuse ggml-based models across jobs without fully unloading and reinitializing them each time.
• Consider restarting your agents periodically to prevent resource accumulation over long runs.
If you want to dig deeper, enabling detailed logging and monitoring thread IDs can help correlate crashes with specific operations. Please feel free to reach out if you’d like help implementing these suggestions or if you need any further assistance with debugging—I’m here to support you!
Sources: livekit-agents/livekit/agents/voice/agent_activity.py | Docs::Agents | common/arg.cppthankful-twilight-49934
10/01/2025, 9:48 AMRoomInputOptions.closeOnDisconnect=False)
participant: “01JNJNHJ78WYWHAWJXXKS16NB6"
reason: “CLIENT_INITIATED”
[164716.683] INFO (38966): mainTask: draining and no more speech tasks
[164716.683] INFO (38966): AgentActivity mainTask: exiting
libc++abi: terminating due to uncaught exception of type std: 1system error mutex lock failed: Invalid argumenttall-airline-16756
10/01/2025, 9:49 AMRoomInputOptions.closeOnDisconnect parameter, which controls whether the agent session closes when a participant disconnects. Setting it to False will prevent automatic closure, which is great to know! However, the error mutex lock failed: Invalid argument seems to be unrelated to this setting and might be coming from some lower-level threading or synchronization challenges.
To help you move forward, here are a few things to check:
• Make sure your LiveKit client and agent SDK versions are compatible and up to date.
• Double-check that your runtime environment (like your Python or Node.js version, and operating system) supports the threading models used by the SDK.
• Look out for any unusual disconnection patterns or resource contention that might be happening in your application.
If you’re still facing this issue after these steps, it might be helpful to dig deeper with runtime logs, environment details, and possibly some insights into the SDK internals. Please feel free to reach out if you’d like guidance on any of these steps or need more support—I’m here to help!
Sources: livekit-agents/livekit/agents/voice/agent_session.py | src/room/Room.tsthankful-twilight-49934
10/01/2025, 9:49 AMimport { cli, defineAgent, type JobContext, type JobProcess, metrics, voice, WorkerOptions } from '@livekit/agents';
import * as deepgram from '@livekit/agents-plugin-deepgram';
import * as silero from '@livekit/agents-plugin-silero';
import dotenv from 'dotenv';
import { fileURLToPath } from 'node:url';
import { RoomEvent } from 'livekit-client';
dotenv.config({ path: '.env.local' });
class Assistant extends voice.Agent {
constructor() {
super({
instructions: '',
});
}
}
export default defineAgent({
prewarm: async (proc: JobProcess) => {
proc.userData.vad = await silero.VAD.load();
},
entry: async (ctx: JobContext) => {
const session = new voice.AgentSession({
stt: new deepgram.STT({ model: 'nova-3' }),
});
const userId = JSON.parse(ctx.job.metadata)?.userId
const usageCollector = new metrics.UsageCollector();
session.on(voice.AgentSessionEventTypes.MetricsCollected, (ev) => {
metrics.logMetrics(ev.metrics);
usageCollector.collect(ev.metrics);
});
session.on(voice.AgentSessionEventTypes.UserInputTranscribed, (event) => {
console.log(`User input transcribed: ${event.transcript}`);
});
const logUsage = async () => {
const summary = usageCollector.getSummary();
console.log(`Usage: ${JSON.stringify(summary)}`);
};
ctx.addShutdownCallback(logUsage);
// Start the session, which initializes the voice pipeline and warms up the models
await session.start({
agent: new Assistant(),
room: ctx.room,
inputOptions: {
participantIdentity: userId,
},
outputOptions: {
transcriptionEnabled: true,
syncTranscription: false
}
});
ctx.room.on(RoomEvent.ParticipantDisconnected, async (participant) => {
if (participant.identity === userId) {
ctx.shutdown()
}
})
console.log(ctx.room.remoteParticipants, 'remote participants');
console.log(userId, 'user id');
// Join the room and connect to the user
await ctx.connect(undefined);
},
});
cli.runApp(new WorkerOptions({ agent: fileURLToPath(import.meta.url), agentName: 'transcript-agent-alpha' }));tall-airline-16756
10/01/2025, 9:50 AMmutex lock failed: Invalid argument usually points to some tricky threading or synchronization hiccups, like how mutexes are used or cleaned up.
To help you move forward, here are a few friendly tips:
• Make sure every change to shared state is safely wrapped with proper locking methods, like Lock() and Unlock().
• Using defer Unlock() right after locking is a great way to guarantee the lock gets released, even if something unexpected happens.
• Try to avoid copying structs that include mutexes; passing them by reference keeps things safer.
• Keep your locks active only during the essential parts of your code to prevent unnecessary waiting.
• If your code reads shared data more often than it writes, sync.RWMutex can be a helpful tool to improve performance.
If you'd like, I’m here to walk you through debugging or help implement these suggestions in your code. Just let me know!
Sources: room.go | pkg/rtc/room.go | agents/src/voice/room_io/room_io.ts | pkg/loadtester/agentloadtester.gothankful-twilight-49934
10/02/2025, 2:36 AMtall-airline-16756
10/02/2025, 2:36 AMthankful-twilight-49934
10/02/2025, 2:50 AMtall-airline-16756
10/02/2025, 2:51 AMthankful-twilight-49934
10/03/2025, 4:02 AMtall-airline-16756
10/03/2025, 4:03 AMps, top, or systemctl to find the running process.
• Stop the process: This depends on how your agent is managed:
◦ If it’s running directly: try kill <pid> or kill -SIGTERM <pid>.
◦ If it’s managed via systemd: just run sudo systemctl stop <agent-service-name>.
◦ If it’s running in Docker: use docker stop <container-id>.
• Ensure cleanup: The agent should disconnect from the room automatically and trigger any shutdown hooks you have set up in your code.
If you have any questions or need a hand with any of these steps, please don’t hesitate to ask—I’m here to help!
Sources: LiveKit Pricing | Job lifecycle | LiveKit Docs | cmd/lk/agent.go | Agents Overview | LiveKit Docs | Voice AI quickstart | LiveKit Docsthankful-twilight-49934
10/03/2025, 4:10 AMtall-airline-16756
10/03/2025, 4:10 AMshutdown() in the agent’s code.
Just a quick note: LiveKit Cloud management commands like lk agent delete only work with cloud-hosted agents and won’t affect your self-hosted ones. If you’re having trouble finding the self-hosted agent, it might help to review your deployment environment or check your logs to pinpoint where it’s running. Please feel free to reach out if you need any more help—I’m here to support you!
Sources: LiveKit Docs | cmd/lk/agent.go | LiveKit Pricing | Job lifecycle | LiveKit Docs | livekit-agents/livekit/agents/voice/room_io/room_io.pythankful-twilight-49934
10/03/2025, 4:14 AMtall-airline-16756
10/03/2025, 4:14 AMlk room delete [OPTIONS] ROOM_NAME_OR_ID
For example:
lk room delete my-room-name
This will disconnect everyone in the room and remove it from the server. Just make sure your CLI is set up with the right authentication and connection to the LiveKit server. If you have any questions or need a hand with this, feel free to ask—I’m here to help!
Sources: Inside a session | LiveKit Docs | README.md | Connecting to LiveKit | LiveKit Docsthankful-twilight-49934
10/03/2025, 4:23 AM{
"build": "tsc",
"clean": "rm -rf dist",
"typecheck": "tsc --noEmit",
"lint": "eslint \"**/*.{ts,js}\"",
"lint:fix": "eslint --fix \"**/*.{ts,js}\"",
"format": "prettier --write \"**/*.{ts,js,json,md}\"",
"format:check": "prettier --check \"**/*.{ts,js,json,md}\"",
"test": "node --test --import tsx",
"test:watch": "node --test --watch --import tsx",
"dev": "tsx src/agent.ts dev",
"download-files": "pnpm run build && node dist/agent.js download-files",
"start": "node dist/agent.js start"
}
i run strart, it does create new agent, but when it exit, it does not close from livekittall-airline-16756
10/03/2025, 4:24 AMctx.shutdown() in your code to end the agent's session. For example:
await ctx.shutdown(reason="Session ended")
• Close the agent session: If you're working with AgentSession, simply call session.aclose() to gracefully wrap things up.
• Automatically close on participant disconnect: Make sure RoomInputOptions.close_on_disconnect is set to True (which is the default) so the agent disconnects as soon as the user leaves.
• Terminate the room: You can also use ctx.delete_room() to end the session for everyone, including the agent.
Following these steps will help your agent disconnect properly from LiveKit. If you have any questions or need a hand with anything else, just let me know—I’m here to help!
Sources: Docs::Agents | docs/index.yaml | livekit-agents/livekit/agents/voice/room_io/room_io.pythankful-twilight-49934
10/03/2025, 4:26 AMimport {
AutoSubscribe,
type JobContext,
type JobProcess,
WorkerOptions,
cli,
defineAgent,
metrics,
voice,
} from '@livekit/agents';
import * as livekit from '@livekit/agents-plugin-livekit';
import * as silero from '@livekit/agents-plugin-silero';
import dotenv from 'dotenv';
import { RoomEvent } from 'livekit-client';
import { fileURLToPath } from 'node:url';
dotenv.config({ path: '.env.local' });
class Assistant extends voice.Agent {
constructor() {
super({
instructions: '',
});
}
}
export default defineAgent({
prewarm: async (proc: JobProcess) => {
proc.userData.vad = await silero.VAD.load();
},
entry: async (ctx: JobContext) => {
const session = new voice.AgentSession({
stt: 'deepgram/nova-3:en',
// stt: new deepgram.STT({ model: 'nova-3' }),
turnDetection: new livekit.turnDetector.MultilingualModel(),
vad: ctx.proc.userData.vad! as silero.VAD,
});
const userId = ctx.job.metadata ? JSON.parse(ctx.job.metadata)?.userId : undefined;
console.log(userId, 'userId');
const usageCollector = new metrics.UsageCollector();
session.on(voice.AgentSessionEventTypes.MetricsCollected, (ev) => {
metrics.logMetrics(ev.metrics);
usageCollector.collect(ev.metrics);
});
session.on(voice.AgentSessionEventTypes.UserInputTranscribed, (event) => {
console.log(`User input transcribed: ${event.transcript}`);
});
const logUsage = async () => {
const summary = usageCollector.getSummary();
console.log(`Usage: ${JSON.stringify(summary)}`);
};
ctx.addShutdownCallback(async () => {
await logUsage();
await session.close();
});
// Start the session, which initializes the voice pipeline and warms up the models
await session.start({
agent: new Assistant(),
room: ctx.room,
inputOptions: {
audioEnabled: true,
videoEnabled: false,
textEnabled: false,
participantIdentity: userId,
closeOnDisconnect: true,
},
outputOptions: {
transcriptionEnabled: true,
},
});
console.log('Connected to room:' + ctx.agent?.identity);
ctx.room.on(RoomEvent.ParticipantDisconnected, async (participant) => {
if (participant.identity === userId) {
ctx.shutdown();
}
});
// Join the room and connect to the user
await ctx.connect(undefined, AutoSubscribe.AUDIO_ONLY);
},
});
cli.runApp(
new WorkerOptions({
agent: fileURLToPath(import.meta.url),
workerType: 1,
agentName: 'test',
}),
);tall-airline-16756
10/03/2025, 4:27 AMctx.addShutdownCallback is already set up to log usage and close the session, like this:
ctx.addShutdownCallback(async () => {
await logUsage();
await session.close();
});
Also, the closeOnDisconnect option within inputOptions is set to true, which is great because it ensures the agent disconnects when the participant leaves the room:
inputOptions: {
audioEnabled: true,
videoEnabled: false,
textEnabled: false,
participantIdentity: userId,
closeOnDisconnect: true,
}
If you notice the agent isn’t disconnecting as expected, it might be helpful to double-check a couple of things:
• That the ctx.shutdown() call inside the RoomEvent.ParticipantDisconnected handler is actually being triggered.
• That the session.close() method completes smoothly without any errors during shutdown.
Please feel free to reach out if you'd like me to walk through this with you or help debug further — I’m here to support you!thankful-twilight-49934
10/03/2025, 4:40 AMtall-airline-16756
10/03/2025, 4:40 AMlk agent destroy command for them. But don’t worry, here’s how you can handle it:
• Stop the agent process: You can use your system commands like kill, or tools like Docker or Kubernetes, to stop the agent running on your own infrastructure.
• Disconnect the agent from a room: If the agent is currently active in a room, you can gracefully disconnect it by calling the shutdown function in the agent’s code.
If you have any questions or want to dive deeper into managing self-hosted agents, just let me know—I’m here to help!
Sources: livekit/livekit_cloud_agent.twirp.go | autocomplete/fish_autocomplete | Job lifecycle | LiveKit Docs | LiveKit Pricingthankful-twilight-49934
10/03/2025, 5:45 AMtall-airline-16756
10/03/2025, 5:46 AMSIGTERM or SIGINT signal, which helps the process shut down gracefully. For example:
kill <process_id>
This approach allows the process to clean up and deregister from LiveKit smoothly. If you ever find yourself needing to forcefully stop the process, you can use:
kill -9 <process_id>
That said, I usually don’t recommend this because it skips the graceful shutdown steps.
If you notice the process running without a worker connection, it might mean something unusual is going on. Please feel free to reach out if you'd like some help figuring it out or managing the process—I’m here to support you!
Sources: Worker options | LiveKit Docs | LiveKit Docs | agents/src/worker.tsthankful-twilight-49934
10/03/2025, 5:49 AMtall-airline-16756
10/03/2025, 5:50 AMthankful-twilight-49934
10/03/2025, 6:21 PMtall-airline-16756
10/03/2025, 6:21 PMthankful-twilight-49934
10/03/2025, 6:28 PMtall-airline-16756
10/03/2025, 6:28 PMthankful-twilight-49934
10/07/2025, 11:32 AMthankful-twilight-49934
10/08/2025, 4:57 AM