in the on_user_turn_completed node, when it receiv...
# ask-ai
s
in the on_user_turn_completed node, when it receives turn_ctx and the full ChatContext, does that include only the user's responses, or does it also include what the LLM said?
t
Thanks for reaching out, Jason. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! Just a quick heads-up about the
on_user_turn_completed
node—it gets a
turn_ctx
parameter that holds the entire
ChatContext
up until, but not including, the user's latest message. So, it includes all the back-and-forth from previous turns, both what the user said and the LLM's replies. Now, the user's newest message comes in separately as the
new_message
parameter. Once the hook runs, this
new_message
gets added to the chat context so the LLM can work its magic. Just so you know, neither
turn_ctx
nor
new_message
includes the LLM’s response to the current user turn yet—that’s still on its way. Sources: Pipeline nodes and hooks | LiveKit Docs
s
I have another question. the way I'd like to set it up is that when one of my users clicks on the "start interview" link (which launches the agent), there is a project id that I want to pass to the agent so that It then knows what questions to ask. what is the simplest way to pass that project id to the agent?
t
Hey there! Could you help me understand how you’re launching the agent? Like, are you using a custom API, embedding it in a web app, or maybe using a specific LiveKit feature? Knowing this will make it easier for me to guide you on the simplest way to pass the project ID.
s
embedding it in a web app I think. I'm not using LiveKit cloud. I'm using my own token server
t
Hey there! If you want to pass a project ID to the agent when embedding it in a web app and using your own token server, you can do this easily by using the
metadata
field in the
RoomAgentDispatch
configuration while generating the participant access token. This lets you include custom data, like your project ID, in a neat, structured format such as JSON. Here’s how you can do it step-by-step: 1. Set Up the Token Server: On your token generation server, you’ll want to configure the
roomConfig
property of the
AccessToken
to include an agent dispatch with your custom metadata. For example, in TypeScript:
Copy code
import { AccessToken } from 'livekit-server-sdk';
import { RoomConfiguration, RoomAgentDispatch } from '@livekit/protocol';

const createTokenWithCustomData = (): Promise<string> => {
  const at = new AccessToken();
  at.identity = 'my-participant';
  at.addGrant({ roomJoin: true, room: 'my-room' });

  // Here’s where you pass your custom data via metadata
  at.roomConfig = new RoomConfiguration({
    agents: [
      new RoomAgentDispatch({
        agentName: 'test-agent',
        metadata: JSON.stringify({
          project_id: 'your-project-id',
          user_id: '12345',
          custom_field: 'custom-value',
        }),
      }),
    ],
  });

  return at.toJwt();
};
2. Access Data in the Agent: Then, in your agent’s
entrypoint
function, you can grab the metadata through the
JobContext
. Here’s a quick example in Python:
Copy code
from livekit.agents import JobContext

async def entrypoint(ctx: JobContext):
    # Let’s parse the job metadata
    metadata = json.loads(ctx.metadata) if ctx.metadata else {}
    project_id = metadata.get("project_id")
    print(f"Project ID: {project_id}")
This way, your project ID gets passed along dynamically to the agent, making it super easy to customize its behavior based on that info. If you have any questions or want to chat more about it, just let me know! Sources: Web Embed Example | livekit/livekit_composite | DeepWiki | Agent dispatch | LiveKit Docs | Job lifecycle | LiveKit Docs | examples/agent-dispatch/index.ts | src/pages/api/token.ts
s
thanks. one other question. I'm going to run an interview where upon each on_user_turn_completed node, it will run a task. the task is always the same, but the task uses the latest chat context from turn_ctx. meaning it uses the latest updated information about the conversation. cursor is asking me this: Option 1: Create Task Each Time (What I wrote) • Every time on_user_turn_completed is triggered, we create a new InterviewPlanningTask instance • Task does its evaluation, returns the next question, then completes • Next turn = create another new task instance Option 2: Create Task Once, Reuse • Create one InterviewPlanningTask at the beginning of the interview • Keep the same task instance throughout the interview • Each turn calls methods on the existing task Looking at the LiveKit documentation, tasks seem to be designed to "complete a specific task and return a specific result" - suggesting they're meant to be created for each discrete operation. But I'm not certain which approach is correct for our use case. Which way do you think we should do it? • Create a new task instance for each turn's evaluation? • Or create one task instance that persists throughout the interview? The documentation examples show tasks being created and awaited for completion, which suggests the "create each time" approach. what should I do?
t
In LiveKit, tasks are built to be reusable pieces that help you achieve specific goals and give back clear results. For your interview setup, a great way to go about it is to create one
InterviewPlanningTask
right at the start and keep using it throughout the session. This fits well with how LiveKit is designed and helps keep things consistent and easy to manage. By sticking with the same task, you make sure it keeps track of the context and makes updates simpler, while still being able to handle the latest chat info from
turn_ctx
each time. If you made a new task every turn, you'd end up repeating yourself and it would get harder to maintain—definitely not the best for smooth, repeatable interactions. Feel free to reach out if you'd like me to explain anything more or help you set this up! Sources: Workflows | LiveKit Docs
s
I need to verify the exact import statement for AgentTask. The plan shows using AgentTask but I want to confirm if it's imported as from livekit.agents import AgentTask or if it's in a different module like from livekit.agents.tasks import AgentTask or something else.
t
Hey! Just a quick heads-up—the right way to import
AgentTask
in LiveKit is:
Copy code
from livekit.agents import AgentTask
If you have any questions or need a hand with anything else, feel free to ask. I'm here to help! Sources: livekit-agents/livekit/agents/py.typed | Workflows | LiveKit Docs
s
Question: In the plan's LLM node override example, it shows chat_ctx.add_message(role="system", content=self.system_prompt). Is this the correct LiveKit API for adding messages to ChatContext, or should it be a different method like chat_ctx.messages.append() or something else?
t
Hey! Could you let me know which exact LiveKit version or implementation you're working with? That way, I can make sure to give you the right API method for adding messages to
ChatContext
. Thanks!
s
what do you mean by which LiveKit version or implementation I'm working with ?
t
Hey there! The best way to add messages to
ChatContext
in LiveKit is by using
chat_ctx.add_message
. This method is made just for this purpose, letting you add messages with details like role, content, and even some optional metadata, so everything stays organized and works smoothly. It’s usually not a great idea to mess with
messages
directly (like using
chat_ctx.messages.append
) because the
ChatContext
class doesn’t actually give direct access to a
messages
attribute in Python. If you want, I’m happy to share more examples or explain further—just let me know! Sources: tests/test_llm.py | Large language model (LLM) integrations | LiveKit Docs | agents/src/llm/chat_context.ts
s
hi - here's another question: Question: In the on_user_turn_completed(self, turn_ctx, new_message) method, what is the correct way to get the text content from new_message? The plan shows new_message.text_content() but I want to verify this is the correct LiveKit API before proceeding. Also, should I be using new_message directly as a string, or is it an object that needs a method call to get the text?
t
Hey there! To get the text content from
new_message
inside the
on_user_turn_completed
method, you’ll want to use the
text_content
property—not as a method. Like this:
Copy code
text = new_message.text_content
Just a couple of things to keep in mind: •
text_content
is a property, so no parentheses! Calling
new_message.text_content()
will cause an error. • This property pulls together all the text bits from
new_message.content
, skipping anything that’s not text, like images. If you want me to walk you through it more or need some examples, just let me know—I’m here to help! Sources: livekit-agents/livekit/agents/voice/agent_activity.py | complex-agents/vision/agent.py | Pipeline nodes and hooks | LiveKit Docs
s
I have a LiveKit agent that's registered and running (I can see registered worker in the logs), but when I generate a token with agent dispatch using roomConfig.agents, the agent never receives a job request. My token includes: "roomConfig": { "agents": [{ "agentName": "total-agent", "metadata": "{\"project_id\": 2}" }] } My agent is running with python total_agent.py dev and I see it register successfully, but when a user joins the room with this token, I never see a "received job request" log line. Do I need to configure anything in livekit.yaml for agent dispatch to work? Or is there another step I'm missing to make the LiveKit server actually dispatch agents when roomConfig.agents is specified in the token?"
t
Hey there! To make sure your agent gets job requests when you're using
roomConfig.agents
in the token, here are a few things to double-check: 1. Set
agent_name
in WorkerOptions:
Your agent needs to be registered with a clear
agent_name
in its
WorkerOptions
. This name should exactly match the
agentName
you’ve put in the token's
roomConfig.agents
. 2. Configure
roomConfig.agents
in the Access Token:
Make sure your token has a
RoomConfiguration
object that includes an
agents
array. Each item should have: ◦ `agentName`: The name of the agent you want to dispatch. ◦
metadata
(optional): Any extra context you want to send to the agent. 1. Grant Room Join Permissions: Don’t forget to include a video grant in the token with
roomJoin: true
and specify the
room
they’re joining. Once you’ve got all that set up, LiveKit should take care of dispatching the agent automatically when someone joins the room. If you hit any snags or want to chat more about this, just let me know—I’m here to help! Sources: examples/agent-dispatch/index.ts | Authentication | LiveKit Docs | Dispatching agents | LiveKit Docs | Agent dispatch | LiveKit Docs
s
what nodes can I modify when using the open ai realtime model?
t
Hey there! When you're working with the OpenAI realtime model in LiveKit, the main pipeline node you can tweak is the
realtime_audio_output_node
. This is where you get to customize the audio output before it reaches the user. Just a heads up, other nodes like
stt_node
,
llm_node
, and
tts_node
aren’t available for the realtime model—they’re part of the STT-LLM-TTS pipeline instead. On top of that, you’ve got some handy parameters to shape how the model behaves, such as: • Voice: Choose the voice for audio responses (think "alloy" or "shimmer"). • Temperature: This controls how random or creative the model’s output feels. • Turn Detection: Helps the model figure out when you’ve finished speaking. • Modalities: Decide if the model uses text, audio, or both for input and output. • Instructions: Set the system prompt or guide how the model behaves. You can set these up when you initialize the model or change them on the fly using the
update_options
method. If you want me to walk you through any of this or share some examples, just let me know—I’m here to help! Sources: Pipeline nodes and hooks | LiveKit Docs | OpenAI Realtime API integration guide | LiveKit Docs | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/stt.py
s
wait a minute. can I use the regular open ai (not the realtime model), along with VAD and turn detection from the Multilingual modal, and still use tasks and modify the llm_node?
t
Absolutely! You can definitely use the regular OpenAI model (like
gpt-4o-mini
) alongside VAD and turn detection from the Multilingual model. Plus, you can still take advantage of tasks and tweak the
llm_node
. This setup is fully supported and actually pretty common for building responsive, context-aware voice agents. Here’s a quick configuration example:
Copy code
from livekit.agents import AgentSession
from livekit.plugins import openai, deepgram, silero
from livekit.plugins.turn_detector.multilingual import MultilingualModel

session = AgentSession(
    stt=deepgram.STT(model="nova-3", language="multi"),
    llm=openai.LLM(model="gpt-4o-mini"),
    tts=openai.TTS(voice="ash"),
    vad=silero.VAD.load(),
    turn_detection=MultilingualModel(),  # Context-aware turn detection
)
Some key things to keep in mind: • Tasks: You can easily set up tasks (like function calling) using the
@function_tool
decorator, and the OpenAI LLM will handle them smoothly. • Turn Detection: The Multilingual model offers semantic turn detection based on the transcribed text, while Silero VAD takes care of real-time voice activity detection. • Node Customization: Feel free to modify the
llm_node
or
tts_node
to customize how things behave—for example, filtering output before it goes to TTS. If you want, I’m here to help with more details or guide you through the implementation! Sources: LiveKit turn detector plugin | LiveKit Docs | examples/voice_agents/basic_agent.py | Gemini Live API integration guide | LiveKit Docs | Building voice agents | LiveKit Docs | complex-agents/turn-taking/README.md
s
does this configuration look ok? session = AgentSession( userdata=userdata, # Use LiveKit's turn detection for natural conversation flow _turn_detection_=MultilingualModel(), # Allow interruptions for more natural flow _allow_interruptions_=True, vad=ctx.proc.userdata["vad"], # From prewarm stt=deepgram.STT(model="nova-3", language="multi"), _# Use regular OpenAI LLM for Tasks and llm_node override support_ llm=openai.LLM(model="gpt-4o"), tts=openai.TTS(voice="alloy"), # Separate TTS component # Force metrics collection for all turns _min_endpointing_delay_=0.5, _max_endpointing_delay_=6.0, # Enable comprehensive metrics collection _discard_audio_if_uninterruptible_=False
t
Your configuration looks spot on and really follows LiveKit's best practices for building responsive, context-aware voice agents. Let me walk you through the key parts: • Turn Detection: Using
MultilingualModel()
is a great choice and supports smooth, natural turn detection for conversations. • STT: Setting up Deepgram STT with
model="nova-3"
and
language="multi"
works well for handling multiple languages in transcription. • LLM: The OpenAI LLM with
model="gpt-4o"
is fully compatible and integrates nicely with tasks and
llm_node
overrides. • TTS: OpenAI TTS using
voice="alloy"
is a solid pick for generating clear audio responses. • VAD: Using
ctx.proc.userdata["vad"]
(probably preloaded with
silero.VAD.load()
) fits perfectly with LiveKit’s recommendations. • Endpointing Delays: Setting
min_endpointing_delay=0.5
and
max_endpointing_delay=6.0
helps keep turn-taking feeling natural and responsive. Just a couple more things to keep in mind: • Make sure you’ve downloaded the necessary model weights for
MultilingualModel
by running
python agent.py download-files
. • Double-check that your environment variables like
DEEPGRAM_API_KEY
and
OPENAI_API_KEY
are set up correctly. • For production use, it’s best to run on compute-optimized instances to avoid any CPU slowdowns. If you have any more questions or need a hand with anything else, just let me know—I’m here to help! Sources: LiveKit turn detector plugin | LiveKit Docs | complex-agents/drive-thru/agent_config.py | examples/frontdesk/frontdesk_agent.py | agent.py | Voice AI quickstart | LiveKit Docs
s
I have built a couple of agents. I built the first one, and downloaded the model weights. Then I built another agent, with a different name, in the same directory as the first agent. Do I need to download the model weights again?
t
Hey! Just wondering, does the second agent use the same models or settings as the first one? Knowing this will help us figure out if we need to download the model weights again.
s
The only difference would be that the first agent uses open ai realtime, and the second agent uses the regular open ai
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
s
would anything bad happen if I tried to download the model weights again?
hi -- I just tested the agent. It spoke the introduction, I then answered, and then it asked the right first interview question. it detected my answer correctly, but then nothing happened. here's what cursor is telling me, and I want you to tell me what you think the problem is: Looking at the agent logs you provided, I can see exactly what happened: 1. ✅ Introduction worked perfectly - the agent spoke the introduction and you responded "Sure." 2. ✅ First question worked perfectly - the agent asked the correct first question from the interview plan 3. ✅ Speech detection worked - the agent detected your response "Nim's okay. I'd give it, like, a one out of ten." 4. ❌ Agent crashed during LLM processing - Here's the exact error: text Apply to total_agent.... RuntimeError: no activity context found, the agent is not running The specific problem: In the InterviewPlanningTask.llm_node method, this line is failing: python Apply to total_agent.... return Agent.default.llm_node(self, chat_ctx, tools, model_settings) This line is trying to call the parent class's llm_node method, but it's doing so incorrectly. The Agent.default.llm_node call doesn't have the proper activity context that LiveKit requires. Why this happens: The llm_node override in a task needs to use the session's LLM directly, not try to call back to the agent's default LLM node method. The minimal fix needed: Replace that one problematic line with: python Apply to total_agent.... return await self.session.agent.llm.generate(chat_ctx) This is a very small change - just replacing one line that's causing the crash. Would you like me to make just this single line change?
can you please answer that last question ? thanks