fierce-answer-55580
08/29/2025, 7:47 PMtall-airline-16756
08/29/2025, 7:47 PMtall-airline-16756
08/29/2025, 7:48 PMmetadata = json.dumps({
"user_id": "12345",
"user_name": "John Doe",
"instructions": "Provide technical support."
})
await lkapi.agent_dispatch.create_dispatch(
api.CreateAgentDispatchRequest(
agent_name="test-agent",
room="my-room",
metadata=metadata
)
)
1. Access Metadata in the Agent: Then, in your agent’s entrypoint function, just parse that metadata like this:
metadata = json.loads(ctx.job.metadata)
user_id = metadata["user_id"]
user_name = metadata["user_name"]
instructions = metadata["instructions"]
This way, you can tailor your agent’s behavior for each user. If you have any questions or want me to walk you through it, just let me know—I’m here to help!
Sources: Job lifecycle | LiveKit Docs | Agent dispatch | LiveKit Docs | examples/agent_dispatch.py | packages/livekit-rtc/src/proto/room_pb.ts | External data and RAG | LiveKit Docsfierce-answer-55580
08/29/2025, 7:48 PMtall-airline-16756
08/29/2025, 7:49 PMimport json
async def entrypoint(ctx: JobContext):
metadata = json.loads(ctx.job.metadata)
user_name = metadata["user_name"]
instructions = f"You are a helpful assistant. The user's name is {user_name}."
1. Pass Instructions to the Agent: Use that metadata to set up the agent with personalized instructions:
session = AgentSession()
agent = MyAgent(instructions=instructions)
await session.start(agent=agent, room=ctx.room)
Or, if you prefer, you can preload context using ChatContext like this:
from livekit.agents import ChatContext
initial_ctx = ChatContext()
initial_ctx.add_message(role="system", content=f"The user's name is {user_name}.")
session = AgentSession()
await session.start(agent=Assistant(chat_ctx=initial_ctx), room=ctx.room)
If anything’s unclear or you want a hand with this, just let me know—I’m here to help!
Sources: External data and RAG | LiveKit Docs | flows/declarative_flow.py | Job lifecycle | LiveKit Docsfierce-answer-55580
08/29/2025, 7:49 PMtall-airline-16756
08/29/2025, 7:50 PMChatContext in LiveKit, you can preload some context for your agent by setting up a ChatContext object filled with predefined messages. This way, your agent kicks off the conversation already equipped with a tailored history or important info.
Here’s a simple way to do it:
1. Create a ChatContext: Add messages with roles like system, user, or assistant. For example:
from livekit.agents.llm import ChatContext, ChatMessage
initial_ctx = ChatContext(
messages=[
ChatMessage(
role="system",
content="You are a helpful assistant. Be concise and friendly."
)
]
)
1. Pass the ChatContext to the Agent: Just use the chat_ctx parameter when you create your agent:
agent = VoicePipelineAgent(
stt=stt_instance,
llm=llm_instance,
tts=tts_instance,
vad=vad_instance,
chat_ctx=initial_ctx # Preloaded context
)
1. Update Context on the Fly: You can also add new messages while things are running:
chat_ctx.add_message(role="user", content="What’s the weather today?")
await agent.update_chat_ctx(chat_ctx)
This way, your agent always has the right context to be as helpful and relevant as possible. If you want me to walk you through any part or share more examples, just let me know—I’m happy to help!
Sources: External data and RAG | LiveKit Docs | agent/main.py | Testing and evaluation | LiveKit Docs | livekit-agents/livekit/agents/llm/chat_context.py | Vision | LiveKit Docsfierce-answer-55580
08/29/2025, 7:53 PMtall-airline-16756
08/29/2025, 7:54 PMChatContext to your agent and get how it works with the messages in on_enter, here’s a simple guide for you:
1. Passing ChatContext: Just use the chat_ctx parameter when you set up your agent. Like this:
from livekit.agents.llm import ChatContext
chat_ctx = ChatContext.empty()
chat_ctx.add_message(role="user", content="Tell me a story")
chat_ctx.add_message(role="assistant", content="Once upon a time...")
agent = Evi(chat_ctx=chat_ctx)
1. How it interacts with `on_enter`: The messages you provide in on_enter will be handled right after the ChatContext. If you want to tweak or add to the context on the fly, you can do that inside on_enter like this:
async def on_enter(self):
if not self.paused:
chat_ctx = self.chat_ctx.copy()
chat_ctx.add_message(role="system", content=self.instructions)
await self.update_chat_ctx(chat_ctx)
messages = chat_ctx.messages # This includes all the earlier context
await self.session.generate_reply(instructions=messages)
Just a couple of quick tips:
• The messages in on_enter come after the preloaded ChatContext, unless you change it explicitly.
• Don’t forget to call self.update_chat_ctx to save any changes you make to the context inside on_enter.
If you want me to walk you through anything else or need more examples, just let me know—I’m happy to help!
Sources: tests/test_agent_session.py | Workflows | LiveKit Docs | complex-agents/role-playing/agents/base_agent.py | Pipeline nodes and hooks | LiveKit Docs | Vision | LiveKit Docsfierce-answer-55580
08/29/2025, 8:41 PMtall-airline-16756
08/29/2025, 8:42 PMon_enter function in LiveKit agents, here are a couple of friendly ways to do it:
1. Using `session.userdata`: You can pass your custom data through the userdata attribute of AgentSession. Then, you can easily access it in on_enter via self.session.userdata. Here's a quick example:
from dataclasses import dataclass
@dataclass
class MySessionInfo:
user_name: str
age: int
city: str
class ContextAgent(Agent):
async def on_enter(self):
userdata = self.session.userdata
await self.session.generate_reply(
instructions=f\"Hello {userdata.user_name}, you are {userdata.age} and live in {userdata.city}.\"
)
async def entrypoint(ctx: JobContext):
session = AgentSession[MySessionInfo](
userdata=MySessionInfo(user_name=\"Alice\", age=30, city=\"Paris\"),
)
await session.start(agent=ContextAgent(), room=ctx.room)
1. Using Agent Initialization: Another way is to pass parameters when you create the agent and save them as instance variables. Then, you can use these inside on_enter. Check this out:
class StoryAgent(Agent):
def __init__(self, name: str, location: str):
self.greeting = f\"Welcome, {name} from {location}.\"
super().__init__(instructions=self.greeting)
async def on_enter(self):
await self.session.generate_reply(instructions=self.greeting)
await session.start(agent=StoryAgent(name=\"Alice\", location=\"Paris\"), room=ctx.room)
Just a couple of quick notes:
• session.userdata is your best bet if you want to pass persistent data to on_enter.
• If you pass data during agent initialization, remember it won’t be shared across tools or sessions unless you handle that explicitly.
Feel free to ask if you want me to walk you through more examples or clarify anything!
Sources: tests/test_agent_session.py | tool_calling/update_tools.py | Pipeline nodes and hooks | LiveKit Docs | Workflows | LiveKit Docsfierce-answer-55580
08/29/2025, 9:46 PMtall-airline-16756
08/29/2025, 9:47 PMbase_url, model, api_key, max_completion_tokens, temperature, and top_p to the openai.LLM class in LiveKit:
from livekit.plugins import openai
llm_instance = openai.LLM(
model=\"meta-llama/Llama-3.2-3B-Instruct\", # Choose your model
api_key=os.getenv(\"OPENAI_API_KEY\"), # Your API key (using environment variable works great)
base_url=os.getenv(\"BASE_API_URL\"), # If you have a custom API URL, set it here
temperature=0.7, # Controls how creative the output is
top_p=0.9, # Nucleus sampling parameter
max_completion_tokens=512 # Max tokens in the response
)
Here’s a quick rundown of each parameter:
• model: The specific model you want to use (like \"meta-llama/Llama-3.2-3B-Instruct\").
• api_key: Your OpenAI API key. If you don’t pass it directly, it’ll look for the OPENAI_API_KEY environment variable.
• base_url: If you’re using a custom API endpoint or proxy, this lets you override the default. Setting it via an environment variable like BASE_API_URL is super handy.
• temperature: This adjusts how random or creative the responses are. Lower means more predictable.
• top_p: This is for nucleus sampling, which helps shape the randomness too. It takes a float like 0.9.
• max_completion_tokens: Limits how long the response can be, in tokens.
If anything’s unclear or you want a hand setting this up, just let me know—I’m here to help!
Sources: livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real... | OpenAI integration guide | LiveKit Docs | plugins/openai/src/realtime/realtime_model.ts | Ollama integration guide | LiveKit Docs | Together AI LLM integration guide | LiveKit Docsfierce-answer-55580
08/29/2025, 9:47 PMtall-airline-16756
08/29/2025, 9:48 PMTypeError: LLM.__init__() got an unexpected keyword argument 'top_p' usually means that the top_p parameter isn’t recognized in your current setup of openai.LLM. Just so you know, the top_p parameter is actually supported in LiveKit's openai.LLM class to help control nucleus sampling.
Here are a few friendly steps to help you sort this out:
1. Check Your LiveKit Version: Make sure you’re running the latest version of the LiveKit SDK because older versions might not support top_p.
2. Double-Check Your Code: Take another look at how you’re using the parameter. Here’s the right way to do it:
llm_instance = openai.LLM(
model="meta-llama/Llama-3.2-3B-Instruct",
api_key=os.getenv("OPENAI_API_KEY"),
base_url=os.getenv("BASE_API_URL"),
temperature=0.7,
top_p=0.9,
max_completion_tokens=512
)
1. Try Alternatives: If you’re still running into trouble, you can try leaving out top_p and just using temperature to control randomness.
If you hit any more bumps or want me to walk you through it, just give me a shout—I’m here to help!
Sources: OpenAI LLM integration guide | LiveKit Docs | livekit-plugins/livekit-plugins-groq/livekit/plugins/groq/services.py | tools/server/public_legacy/index-new.htmlfierce-answer-55580
08/29/2025, 10:01 PMtall-airline-16756
08/29/2025, 10:02 PMappend() on ChatContext might not save the changes properly. A better way is to use self.update_chat_ctx() to make sure everything updates as it should. Here’s a quick example:
chat_ctx = self._chat_ctx.copy()
chat_ctx.add_message(role="system", content=instructions)
chat_ctx.add_message(role="user", content=initialUserCtx)
await self.update_chat_ctx(chat_ctx)
1. LLM Configuration: Double-check that your agent has an LLM set up. If self.llm isn’t configured, generate_reply() won’t work.
2. Timing Issues: Make sure you’re calling generate_reply() only after the session is fully ready, like inside on_enter().
If any of this feels unclear or you want a hand troubleshooting, just let me know—I’m here to help!
Sources: Agents 0.x migration guide | LiveKit Docs | Agents v0.x migration guide - Node.js | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py | agent.pyfierce-answer-55580
08/29/2025, 10:07 PMtall-airline-16756
08/29/2025, 10:08 PMChatContext and `generate_reply`:
from livekit.agents.llm import ChatContext
class Evi(Agent):
def __init__(self, initialUserCtx: str, instructions: str) -> None:
super().__init__(instructions=instructions)
# Initialize ChatContext
self._chat_ctx = ChatContext.empty()
# Add initial messages to ChatContext
if initialUserCtx:
chat_ctx = self._chat_ctx.copy()
chat_ctx.add_message(role="system", content=instructions)
chat_ctx.add_message(role="user", content=initialUserCtx)
self.update_chat_ctx(chat_ctx) # Persist changes
self.paused: bool = False
async def on_enter(self) -> None:
if not self.paused:
# Use the updated ChatContext for generating a reply
await self.session.generate_reply(
instructions=self.chat_ctx
)
async def on_exit(self) -> None:
return await super().on_exit()
Key Fixes:
• Used ChatContext.empty() to initialize an empty context.
• Added messages to a copied context and persisted changes with self.update_chat_ctx().
• Ensured generate_reply() uses the updated ChatContext.
If you run into any other issues or want me to explain anything further, just let me know — I’m happy to help!
Sources: livekit-agents/livekit/agents/voice/generation.py | Vision Agent Quickstart | LiveKit Docs | agent.py | Testing and evaluation | LiveKit Docs | External data and RAG | LiveKit Docsfierce-answer-55580
08/29/2025, 10:12 PMtall-airline-16756
08/29/2025, 10:12 PMTypeError: sequence item 1: expected str instance, _ReadOnlyChatContext pops up because the generate_reply function is expecting the instructions parameter to be a string, but it got a _ReadOnlyChatContext object instead.
Here’s how you can fix it:
1. Make Sure Instructions Are Strings: The instructions parameter in generate_reply needs to be a string. If you want to use the chat context, just pull out the relevant messages as a string. Like this:
instructions = "\n".join([item.content for item in self.chat_ctx.items])
await self.session.generate_reply(instructions=instructions)
1. Handle ChatContext Properly: If you want to update the chat context, create a mutable copy with self.chat_ctx.copy() and then update it using self.update_chat_ctx().
2. Pass Text Instructions Directly: If you only need to give specific instructions, just pass them as a string like this:
await self.session.generate_reply(instructions="Greet the user warmly.")
If anything’s unclear or you want a hand with these changes, just let me know—I’m here to help!
Sources: complex-agents/personal_shopper/personal_shopper.py | livekit-agents/livekit/agents/voice/generation.py | Agent speech and audio | LiveKit Docsfierce-answer-55580
08/29/2025, 10:56 PMtall-airline-16756
08/29/2025, 10:56 PMmin_endpointing_delay and max_endpointing_delay to help the system better recognize when someone’s finished speaking.
2. Voice Activity Detection (VAD): Sometimes VAD can be too sensitive or not sensitive enough, causing early starts or delayed replies. Adjusting the VAD threshold can help find that sweet spot.
3. Network or Timing Delays: If there’s high latency or jitter, audio streams might get out of sync. Keeping an eye on RTP packet flow can reveal if packets are duplicated or arriving out of order.
4. Agent Interruption Logic: If interruption settings like allow_interruptions aren’t configured properly, you might get overlapping or outdated responses. Double-check that interruptions and audio buffering are handled smoothly.
5. Preemptive Generation: When preemptive_generation is on, the agent might start responding before the user finishes talking. Turning this off by setting preemptive_generation=False can help.
Here are a few tips to keep things running smoothly:
• Try using "vad" or "realtime_llm" turn detection for more accurate real-time signaling.
• Turn on debug logging with setLogLevel('debug') to get detailed insights into audio and event flow.
• Keep an eye on RTP stats to spot any packet duplication or network hiccups.
If you want, I’m here to help you dive deeper or guide you through setting these up — just let me know!
Sources: Speech & Audio Processing | livekit/livekit_composite | DeepWiki | pkg/sfu/rtpstats/rtpstats_receiver.go | .github/ISSUE_TEMPLATE/bug_report.yaml | .github/ISSUE_TEMPLATE/bug.yaml | livekit-agents/livekit/agents/voice/agent_session.pyfierce-answer-55580
08/30/2025, 2:52 PMtall-airline-16756
08/30/2025, 2:53 PMallow_interruptions=True in your AgentSession like this:
session = AgentSession(
stt=deepgram.STT(model="nova-3", language="multi"),
llm=deepseek_llm,
tts=cartesia.TTS(model="sonic-2", voice=voice_info, language="en"),
vad=ctx.proc.userdata["vad"],
turn_detection="vad",
allow_interruptions=True,
)
1. Adjust Endpointing Delays: Tweak min_endpointing_delay and max_endpointing_delay so the agent waits just the right amount before responding:
session.update_options(
min_endpointing_delay=0.8,
max_endpointing_delay=8.0
)
1. Set Minimum Speech Delay: Make sure the agent doesn’t jump in too quickly after speaking by setting `min_consecutive_speech_delay`:
session.update_options(min_consecutive_speech_delay=1.0)
1. Discard Audio When Uninterruptible: To avoid confusion, discard any user audio captured while the agent is speaking by enabling `discard_audio_if_uninterruptible=True`:
session.update_options(discard_audio_if_uninterruptible=True)
These small changes should really help smooth out the conversation and cut down on overlapping voices. If you want a hand setting these up or have any questions, just let me know—I’m here to help!
Sources: livekit-agents/livekit/agents/voice/agent.pyfierce-answer-55580
08/30/2025, 3:13 PMtall-airline-16756
08/30/2025, 3:14 PMon_user_turn_completed in LiveKit and keep voices from overlapping while making sure TTS works just right, here’s a friendly step-by-step guide for you:
1. Stop Ongoing TTS: If the agent is already speaking, it’s best to stop the current TTS before starting a new reply. Here’s how you can do that:
async def on_user_turn_completed(self, turn_ctx, new_message):
if self.session.tts and getattr(self.session.tts, "is_playing", False):
await self.session.tts.stop()
await self.session.generate_reply(instructions=INITIAL_USER_FALLBACK_PROMPT)
1. Ignore Empty User Turns: To avoid the agent responding when there’s no real input, just check if the user’s message is empty and skip it:
async def on_user_turn_completed(self, turn_ctx, new_message):
if not new_message.text_content:
raise StopResponse()
1. Enable Interruptions: Let your users jump in and interrupt the agent mid-speech by setting allow_interruptions=True in the AgentSession config. This makes the conversation feel more natural.
2. Use Retrieval-Augmented Generation (RAG): You can add helpful context on the fly before generating a reply, making responses smarter and more relevant:
async def on_user_turn_completed(self, turn_ctx, new_message):
rag_content = await my_rag_lookup(new_message.text_content())
turn_ctx.add_message(role="assistant", content=rag_content)
await self.update_chat_ctx(turn_ctx)
Following these steps will help keep the conversation flowing smoothly without voices stepping on each other. If you have any questions or want to dive deeper, just let me know—I’m here to help!
Sources: Pipeline nodes and hooks | LiveKit Docs | agents/src/voice/audio_recognition.ts | livekit-agents/livekit/agents/voice/audio_recognition.py | home_assistant/homeautomation.pyfierce-answer-55580
08/30/2025, 3:19 PMtall-airline-16756
08/30/2025, 3:19 PMfrom livekit.agents.llm import ChatContext
class Evi(Agent):
def __init__(self, initialUserCtx: str, instructions: str) -> None:
super().__init__(instructions=instructions)
# Initialize ChatContext
self._chat_ctx = ChatContext.empty()
# Add initial messages to ChatContext
if initialUserCtx:
chat_ctx = self._chat_ctx.copy()
chat_ctx.add_message(role="system", content=instructions)
chat_ctx.add_message(role="user", content=initialUserCtx)
self.update_chat_ctx(chat_ctx) # Persist changes
self.paused: bool = False
async def on_enter(self) -> None:
if not self.paused:
# Stop ongoing TTS to avoid overlapping voices
if self.session.tts and getattr(self.session.tts, "is_playing", False):
await self.session.tts.stop()
# Use the updated ChatContext for generating a reply
await self.session.generate_reply(
instructions=INITIAL_USER_FALLBACK_PROMPT
)
async def on_exit(self) -> None:
return await super().on_exit()
Key Changes:
• Added a check in on_enter to stop any ongoing TTS with self.session.tts.stop() before starting a new reply.
• This helps avoid overlapping voices by making sure any active TTS playback is stopped first.
If you want me to tweak anything else or if you have more questions, just let me know—I’m here to help!fierce-answer-55580
08/30/2025, 3:23 PMtall-airline-16756
08/30/2025, 3:24 PMon_enter function in LiveKit agents is set up to run just once when the agent becomes the active one in a session. It kicks in during the agent's activation lifecycle, usually right at the start of a session or when there's a handoff and the agent first gets initialized.
If that same agent gets reactivated later on in the same session (like after a handoff), how on_enter behaves can depend on the session's specifics. But generally, it’s treated as a one-time initialization step.
Feel free to ask if you want me to explain anything more or if you have any other questions—I’m here to help!
Sources: Pipeline nodes and hooks | LiveKit Docs | pipeline-llm/transcription_node.py | README.mdfierce-answer-55580
08/30/2025, 3:33 PMtall-airline-16756
08/30/2025, 3:34 PMon_enter function in LiveKit agents runs only once when the agent becomes active in a session. It doesn’t get triggered every time the agent plays speech. To help you spot when the agent is actually speaking and avoid any overlapping speech, here are some friendly tips you can try out:
1. Keep an Eye on Agent State: You can watch the agent's state changes using the agent_state_changed event. Here’s a simple example:
@agent.on("agent_state_changed")
def on_agent_state_changed(old_state, new_state):
if new_state == "speaking":
print("Agent started speaking")
elif new_state == "listening":
print("Agent stopped speaking")
1. Use Speaking Events: Another easy way is to tap into the agent_started_speaking and agent_stopped_speaking events to know exactly when speaking starts and stops:
@agent.on("agent_started_speaking")
def agent_started():
print("Agent is now speaking")
@agent.on("agent_stopped_speaking")
def agent_stopped():
print("Agent stopped speaking")
1. Stop Overlapping Speech: You can also set up your session to prevent interruptions and toss out any overlapping audio like this:
session = AgentSession(
allow_interruptions=False,
discard_audio_if_uninterruptible=True,
)
1. Tweak Endpointing: If you want more control over when the agent jumps in after a user stops talking, try adjusting min_endpointing_delay and max_endpointing_delay like so:
session.update_options(
min_endpointing_delay=0.8,
max_endpointing_delay=6.0
)
Using these tips will help you keep track of the agent’s speaking moments and cut down on any talking over each other. If you want me to walk you through any of these steps or have more questions, just let me know—I’m here to help!
Sources: Improving voice AI's turn detection with transformers | OpenAI Realtime API integration guide | LiveKit Docs | Events and error handling | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py | agent/main.pyfierce-answer-55580
08/30/2025, 3:36 PMtall-airline-16756
08/30/2025, 3:36 PMallow_interruptions=False. This way, the current audio finishes completely before any new one kicks in:
speech_handle = await session.say("This message will not be interrupted.", allow_interruptions=False)
1. Global Session-Level Control: You can also set up the session to ignore new audio requests while the agent is still talking:
session = AgentSession(
allow_interruptions=False,
discard_audio_if_uninterruptible=True,
)
1. Handle Interruptions in Tools: If you’re working with tools, you can turn off interruptions during certain actions like this:
def my_tool(ctx: RunContext):
ctx.disallow_interruptions() # Stops interruptions during this and any following speech
These simple settings help make sure your agent finishes what it’s saying before moving on to the next audio. If you want to chat more about this or need a hand with anything else, just let me know!
Sources: livekit-agents/livekit/agents/voice/agent_activity.py | Agent speech and audio | LiveKit Docs