class Evi(Agent): def __init__(self) -> Non...
# ask-ai
f
class Evi(Agent): def __init__(self) -> None: super().__init__(instructions=instructions) self.paused: bool = False async def on_enter(self) -> None: if not self.paused: await self.session.generate_reply( instructions=self.instructions ) async def on_exit(self) -> None: return await super().on_exit() how can I pass metadata to my agent along with instructions. this metadata will be unique to every user
t
Thanks for reaching out, venu. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! If you want to pass some unique metadata to your agent along with instructions, you can use job metadata when dispatching the agent. This metadata is a flexible string field where you can include user-specific info like user ID or name, and your agent can access it easily in the code. Here’s a simple way to do it: 1. Dispatch Agent with Metadata: Just use JSON to structure your metadata and include it when you dispatch the agent. For example, in Python:
Copy code
metadata = 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:
Copy code
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 Docs
f
from entry point how do I pass it to agent as initial instructions
t
Hey there! If you want to pass metadata from the entrypoint to the agent as initial instructions, here’s a friendly way to do it: 1. Parse Metadata in the Entrypoint: Grab the metadata when the agent is dispatched. For example:
Copy code
import 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:
Copy code
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:
Copy code
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 Docs
f
how to use chat context
t
To get started with
ChatContext
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:
Copy code
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:
Copy code
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:
Copy code
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 Docs
f
I have this agent code - class Evi(Agent): def __init__(self) -> None: super().__init__(instructions=instructions) self.paused: bool = False async def on_enter(self) -> None: if not self.paused: messages = [ {"role":"system","content":self.instructions} ] await self.session.generate_reply( instructions=messages ) async def on_exit(self) -> None: return await super().on_exit() How should I pass the chat ctx and also the message which I pass in on_enter function will it come after chat context or before
t
Hey there! To pass
ChatContext
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:
Copy code
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:
Copy code
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 Docs
f
how do I pass data to on_enter function
t
Hey there! If you want to pass data to the
on_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:
Copy code
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:
Copy code
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 Docs
f
deepseek_llm=openai.LLM( _base_url_="https://api.deepinfra.com/v1/openai", model="meta-llama/Llama-3.2-3B-Instruct", _api_key_=os.getenv("OPENAI_API_KEY"), _max_completion_tokens_=512, temperature=0.7, _top_p_=0.9, ) what is the correct format to pass
t
Here’s a friendly guide on how to pass parameters like
base_url
,
model
,
api_key
,
max_completion_tokens
,
temperature
, and
top_p
to the
openai.LLM
class in LiveKit:
Copy code
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 Docs
f
TypeError: LLM.__init__() got an unexpected keyword argument 'top_p'", "level": "ERROR", "name": "livekit.agents", "pid": 81, "job_id": "AJ_nCZL5RHZkdYF", "timestamp": "2025-08-29T214341.117078+00:00"}
t
Hey there! The error
TypeError: 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:
Copy code
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.html
f
class Evi(Agent): def __init__(self, _initialUserCtx_: str) -> None: super().__init__(instructions=instructions) self._chat_ctx = ChatContext() if _initialUserCtx_: self._chat_ctx.append( {"role": "system", "content": instructions}, {"role": "user", "content": initialUserCtx} ) self.paused: bool = False async def on_enter(self) -> None: if not self.paused: await self.session.generate_reply( instructions=self._chat_ctx ) async def on_exit(self) -> None: return await super().on_exit() what is the error ?
t
Hey there! It looks like the error in your code might be coming from a few common spots: 1. ChatContext Modification: Directly using
append()
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:
Copy code
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.py
f
class Evi(Agent): def __init__(self, _initialUserCtx_: str) -> None: super().__init__(instructions=instructions) 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) self.paused: bool = False async def on_enter(self) -> None: if not self.paused: await self.session.generate_reply( instructions=self.chat_ctx ) async def on_exit(self) -> None: return await super().on_exit() please fix the errors
t
Here’s the corrected version of your code with proper handling of
ChatContext
and `generate_reply`:
Copy code
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 Docs
f
ERROR livekit.agents - Error in _traceable_on_enter Traceback (most recent call last): File "/Users/venuchoudhary/Developer/freelance/nextpeer_backend/venv/lib/python3.13/site-packages/livekit/agents/utils/log.py", line 16, in async_fn_logs return await fn(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/venuchoudhary/Developer/freelance/nextpeer_backend/venv/lib/python3.13/site-packages/livekit/agents/voice/agent_activity.py", line 387, in _traceable_on_enter await self._agent.on_enter() File "/Users/venuchoudhary/Developer/freelance/nextpeer_backend/agent.py", line 48, in on_enter await self.session.generate_reply( ~~~~~~~~~~~~~~~~~~~~~~~~~~~^ instructions=self.chat_ctx ^^^^^^^^^^^^^^^^^^^^^^^^^^ ) ^ File "/Users/venuchoudhary/Developer/freelance/nextpeer_backend/venv/lib/python3.13/site-packages/livekit/agents/voice/agent_session.py", line 742, in generate_reply handle = self._activity._generate_reply( user_message=user_message, ...<2 lines>... allow_interruptions=allow_interruptions, ) File "/Users/venuchoudhary/Developer/freelance/nextpeer_backend/venv/lib/python3.13/site-packages/livekit/agents/voice/agent_activity.py", line 759, in _generate_reply instructions = "\n".join([self._agent.instructions, instructions]) TypeError: sequence item 1: expected str instance, _ReadOnlyChatContext
t
Hey there! That
TypeError: 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:
Copy code
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:
Copy code
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 Docs
f
why is ti that sometimes I hear 2 voices
t
Sometimes, hearing overlapping or duplicate voices in LiveKit agents can be a bit confusing, but don’t worry — it usually happens for a few common reasons. Let’s walk through them together and see how you can fix it: 1. Turn Detection Configuration: If turn detection isn’t set up just right, the agent might jump in too soon or talk over the user. Try tweaking settings like
min_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.py
f
def prewarm(_proc_: JobProcess) -> None: logger.info("Preloading VAD model...") proc.userdata["vad"] = silero.VAD.load() 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=INITIAL_USER_FALLBACK_PROMPT ) async def on_exit(self) -> None: return await super().on_exit() async def start_session(_ctx_: agents.JobContext) -> None: logger.info(_f_"🚀 Starting session for context: {ctx}") default_voice= DEFAULT_VOICE # ✅ Parse job metadata try: metadata = json.loads(ctx.job.metadata or "{}") except Exception: metadata = {} voice_id = metadata.get("voice_id", default_voice) # fallback session_id = metadata.get("session_id") session_ctx = metadata.get("session_context") logger.info(_f_"Metadata received , session_id={session_id}, voice_id={voice_id}, session_ctx={session_ctx}") # ✅ Setup voice voice_info = voice_id or default_voice if session_ctx is None or session_ctx.strip() == "": session_ctx = INITIAL_USER_FALLBACK_PROMPT agent_instance = Evi(session_ctx,instructions) # ✅ Track session start time start_time = datetime.now(timezone.utc) deepseek_llm=openai.LLM( _base_url_="https://api.deepinfra.com/v1/openai", model="meta-llama/Llama-3.2-3B-Instruct", _api_key_=os.getenv("OPENAI_API_KEY"), _max_completion_tokens_=512, temperature=0.7, ) 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_=MultilingualModel(), ) # ✅ Start session await session.start( room=ctx.room, agent=agent_instance, _room_input_options_=RoomInputOptions(audio_enabled=True, video_enabled=False), ) if name == "__main__": agents.cli.run_app( agents.WorkerOptions(entrypoint_fnc=start_session, prewarm_fnc=prewarm, agent_name="Evi", ws_url=API_URL, api_key=API_KEY,api_secret=API_SECRET) ) can you update this code to take care of overalapping voice issue
t
To help fix those overlapping voice issues in your LiveKit agent session, here are some easy tweaks you can make: 1. Enable Interruptions: Let users jump in and interrupt the agent mid-speech to avoid audio overlaps. Just set
allow_interruptions=True
in your
AgentSession
like this:
Copy code
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:
Copy code
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`:
Copy code
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`:
Copy code
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.py
f
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)
t
To handle
on_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:
Copy code
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:
Copy code
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:
Copy code
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.py
f
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=INITIAL_USER_FALLBACK_PROMPT ) async def on_exit(self) -> None: return await super().on_exit() please make changes here
t
Here’s the updated version of your code with some tweaks to help fix the overlapping voice issues and make sure the TTS behaves just right:
Copy code
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:
            # 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!
f
the on_enter function plays only once right ? I mean that only when agent enters the room and not after right? or is it that whenever a speech playback starts this function is fired ? I am looking for something which can detect when agent is speaking so that it doesn't overlap
t
Hey there! The
on_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.md
f
the on_enter function plays only once right ? I mean that only when agent enters the room and not after right? or is it that whenever a speech playback starts this function is fired ? I am looking for something which can detect when agent is speaking so that it doesn't overlap
t
Hey there! Just a quick heads-up: the
on_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:
Copy code
@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:
Copy code
@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:
Copy code
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:
Copy code
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&#39;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.py
f
so when agent is speaking I dont want another audio being played from agent
t
To make sure an agent doesn’t start playing another audio while it’s already speaking, you can simply disable interruptions for the current speech. Here’s a friendly little guide on how to do that: 1. Disable Interruptions for Current Speech: When you’re generating speech, just set
allow_interruptions=False
. This way, the current audio finishes completely before any new one kicks in:
Copy code
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:
Copy code
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:
Copy code
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