i have a question. if i’m using an LLM in the Age...
# ask-ai
e
i have a question. if i’m using an LLM in the AgentSession (in this case openai realtime), does the LLM have knowledge of the entire conversation history at all times? i am asking because i want it to conduct an interview but the questions it asks will be dependent on what the user says.
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.
Just so you know, the LLM in an
AgentSession
always has access to the full conversation history through the
session.history
property. This property holds the entire chat history as a
ChatContext
object, and it keeps updating as the session goes on. This means the LLM can easily look back at previous messages when crafting its responses, which is super handy for things like interviews where questions depend on what you’ve said before. Plus, if you’re a developer, you can access and even tweak this history programmatically—maybe to save it after the session or pass it along between agents in multi-agent setups. Pretty neat, right? Sources: examples/voice_agents/realtime_load_chat_history.py | plugins/google/src/beta/realtime/realtime_api.ts | Session recording and transcripts | LiveKit Docs | main.py | complex-agents/personal_shopper/README.md
e
that’s great. do i need to explicitly tell it to look at the session.history or can i just prompt it by saying something like “when you decide what to ask next, please consider the entire conversation history up to that point”?
t
Just a heads-up: the LLM in
AgentSession
doesn’t automatically take
session.history
into account unless you set it up that way. By default, every new agent or task starts fresh, without any previous conversation history in the LLM prompt. If you'd like the LLM to remember the whole conversation, you’ll want to explicitly include it by setting the
chat_ctx
parameter in the
Agent
or
AgentTask
constructor. This way, the LLM gets the full picture when it’s crafting its responses. Another option is to nudge the LLM with a prompt like the one you mentioned (for example, "when you decide what to ask next, please consider the entire conversation history up to that point"). Just keep in mind that this works best if the history is already part of the LLM’s input context. Sources: Workflows | LiveKit Docs | Session recording and transcripts | LiveKit Docs
e
can you give me an example of how to set it up that way ?
t
Here’s a friendly walkthrough on how to set up the LLM in
AgentSession
so it includes the full conversation history: 1. Access the Full Session History: You’ll find the conversation history stored in
session.history
, which is a
ChatContext
object holding all the previous messages. 2. Pass the History to the Agent: When you’re creating a new agent, just pass
session.history
to the
chat_ctx
parameter in the agent’s constructor. Like this: `return TechnicalSupportAgent(chat_ctx=self.session.chat_ctx)`This way, the LLM gets the full context it needs. 3. Manually Build or Modify History (Optional): If you want to tweak or filter the history, you can build a
ChatContext
yourself: `from livekit.agents import ChatContext chat_ctx = ChatContext.empty() for item in session.history.items: chat_ctx.add_message(role=item.role, content=item.content)`Then just pass this
chat_ctx
to your agent. 4. Update Context Dynamically: If your agent is already up and running, no worries—you can update the context during the session like this:
await agent.update_chat_ctx(chat_ctx)
Following these simple steps makes sure the LLM has the full conversation history, helping it give you responses that really fit the context. Sources: Workflows | LiveKit Docs | examples/voice_agents/session_close_callback.py | Testing and evaluation | LiveKit Docs | Large language model (LLM) integrations | LiveKit Docs
e
how do i set the chat_ctx parameter in the Agent constructor? can you give me some example code?
t
Here’s a friendly little example to help you set the
chat_ctx
parameter in the
Agent
constructor: Basic Example:
Copy code
from livekit.agents import ChatContext, Agent

initial_ctx = ChatContext()
initial_ctx.add_message(role="assistant", content="Hello, how can I help you today?")

agent = Agent(
    instructions="You are a helpful assistant.",
    chat_ctx=initial_ctx
)
Loading from History:
Copy code
from livekit.agents import llm

chat_history = [
    {"role": "assistant", "content": "Hello, I am a travel planner. How can I help you?"},
    {"role": "user", "content": "I want to go to Paris this summer."}
]

chat_ctx = llm.ChatContext.empty()
for item in chat_history:
    chat_ctx.add_message(role=item["role"], content=item["content"])

agent = Agent(
    instructions="You are a helpful travel planner.",
    chat_ctx=chat_ctx
)
Passing Context During Agent Handoff:
Copy code
class TechnicalSupportAgent(Agent):
    def __init__(self, chat_ctx: ChatContext):
        super().__init__(
            instructions="You are a technical support specialist.",
            chat_ctx=chat_ctx
        )

# During agent transfer
return TechnicalSupportAgent(chat_ctx=self.session.chat_ctx)
These examples are here to make it easy for you to initialize an agent with the conversation history you already have, so the LLM can fully understand the context and give the best responses possible. Sources: Workflows | LiveKit Docs | External data and RAG | LiveKit Docs
e
i don’t think you understand. i’m not trying to load a prior conversation at the beginning of the interview. at the beginning there is no chat history. but as the agent asks the user questions and the user answers those questions, a chat history is created. i want the agent to consider this chat history as it decides the next question to ask.
t
Thanks for clearing that up! Just to make sure I’m on the right track—are you asking how the agent can automatically keep track of the growing
session.history
during your conversation without you having to update it manually? Or are you looking for a way to update the agent’s context programmatically after each time the user responds?
e
i’m asking how the agent can automatically keep track of the growing session.history
t
Hey there! Just so you know, the
session.history
in
AgentSession
automatically keeps track of your conversation as it grows. You don’t have to worry about updating it yourself—LiveKit takes care of adding each user input and agent response to
session.history
in real time. If you want the agent to use this full history, you can set it up with the
chat_ctx
parameter pointing to
session.history
. Here’s a quick example:
Copy code
agent = Agent(\n    instructions=\"You are a helpful assistant.\",\n    chat_ctx=session.history  # This includes the entire conversation automatically\n)
And if you’d like to react whenever the history updates, you can listen for events like
conversation_item_added
to jump in and respond as new messages come in. Sources: Workflows | LiveKit Docs | Session recording and transcripts | LiveKit Docs
e
i see two places in my code where i might do this.... which is the right one? one has: agent = InterviewAgentRealtime() and the other has: # Start the session with our agent await session.start(agent=agent, room=ctx.room)
t
Just a quick heads-up: the best spot to set the
chat_ctx
is when you're initializing the agent, not inside
session.start()
. You pass the
chat_ctx
right into the
Agent
class constructor as you create your agent instance. For example:
Copy code
agent = InterviewAgentRealtime(chat_ctx=session.history)
The
session.start()
method simply kicks off the session using the agent you've already set up, and it doesn’t take a
chat_ctx
parameter. If you want to tweak the chat context after the agent’s up and running, no worries—you can just call the
update_chat_ctx()
method on the agent during runtime. Sources: External data and RAG | LiveKit Docs | README.md
e
got it. once i initialize the agent with "(chat_ctx=session.history)", will it automatically always include the session history when choosing it's next question, or do i need to somehow tell it to do so?
t
Once you set up the agent with
chat_ctx=session.history
, it’ll automatically include the session history in all the following LLM prompts for that agent. You don’t have to do anything extra to make this happen—the agent keeps track of the chat context on its own, and it grows as your conversation goes on. The LLM will then use this history to craft its responses. This will keep going until you decide to change or replace the context, so the agent always keeps the full session history in mind when figuring out its next question. Sources: livekit-agents/livekit/agents/voice/agent_session.py | Testing and evaluation | LiveKit Docs
e
i want to run an interview where i give the LLM (or the agent? i'm not sure) a set of research goals, an initial set of questions to ask, and a maximum number of questions. however, each time the user responds to a question, i want the LLM to decide whether to stick with the initial set of questions, or ask a different question which will more effectively achieve the research goals. in making this decision, it should consider the entire conversation history up to that point. how and where would i put the prompt?
t
Setting up an interview agent that smartly adapts its questions based on your research goals, initial questions, and the ongoing conversation history is totally doable! Here’s a friendly step-by-step to help you get there: 1. Define Research Goals: Start by setting your research goals in the agent’s
instructions
parameter when you initialize it. For example:
agent = InterviewAgentRealtime(\n    instructions=\"Your goal is to conduct an interview to gather insights about user preferences for travel destinations.\",\n    chat_ctx=session.history\n)
2. Provide Initial Questions: Kick things off by using the
on_enter()
method to send the first set of questions as soon as the agent starts:
async def on_enter(self):\n    await self.session.say(\"What is your name?\")\n    await self.session.say(\"What is your favorite travel destination?\")
3. Enable Dynamic Questioning: The agent naturally keeps track of the
session.history
when you initialize it with
chat_ctx=session.history
. To make the questions adapt on the fly, you can create a function tool that looks at the user’s answers and comes up with smart follow-ups:
@function_tool\nasync def generate_next_question(self, context):\n    # Take a look at the session history\n    history = context.session.history\n    # Choose the next question based on your research goals\n    next_question = decide_based_on_goals(history)\n    await self.session.say(next_question)
4. Set a Maximum Number of Questions: Keep an eye on how many questions you’ve asked by using
userdata
. For example: `@dataclass\nclass InterviewData:\n question_count: int = 0\n max_questions: int = 10`Update
userdata
after each question, and gently wrap up once you hit your limit. By blending
instructions
,
on_enter()
, and function tools, you can craft an interview agent that really listens and adjusts its questions as the conversation flows—helping you reach your research goals while keeping the chat natural and engaging. Sources: test/agents/host.py | Workflows | LiveKit Docs | avatars/tavus/tavus.py | examples/voice_agents/multi_agent.py
e
do i really need a function tool, or can i include all of the instructions in the instructions parameter?
t
Hey there! You can include lots of dynamic behaviors right in the
instructions
parameter, like setting the agent's persona, conversational goals, and basic tasks such as asking questions or responding to what the user says. For instance, you might tell the agent to adjust its questions on the fly based on the conversation history and your research goals, all within the
instructions
. That said, for more complex stuff, function tools come in handy, like: • Keeping track of session data (think: counting how many questions have been asked). • Making calls to external APIs or connecting with other systems. • Doing specific actions such as handing off to another agent or creating structured outputs on the spot (like quizzes). If your needs are mostly about keeping the conversation flowing and tweaking questions based on what’s been said, you can probably handle that with some well-thought-out
instructions
. But if you want to dive into more advanced workflows or manage state more deeply, that’s when function tools really shine. Sources: Workflows | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py
e
should i structure the instructions like a typical LLM prompt?
t
Absolutely! The
instructions
parameter should follow the usual LLM prompt conventions. Think of it as a system-level prompt that sets the agent’s behavior, tone, and responsibilities. You can write it as a simple string or a multi-line directive, depending on how detailed you want to get. For example:
Copy code
instructions="""\nYou are a research assistant conducting an interview.\nYour goals are:\n1. Gather insights about user preferences for travel destinations.\n2. Adapt your questions dynamically based on user responses.\n3. Ensure the conversation remains focused on the research goals.\n\nGuidelines:\n- Start with the initial set of questions provided.\n- After each user response, decide whether to continue with the initial questions or adapt based on the conversation history.\n- Be polite and professional at all times.\n"""
This way, the agent has clear guidance but still stays flexible to keep the conversation natural and helpful. And if you ever need to tweak things during the session, you can easily update the instructions using
await agent.update_instructions(new_instructions)
. Sources: examples/voice_agents/multi_agent.py | complex-agents/medical_office_triage/prompts/triage_prompt.yaml | Google integration guide | LiveKit Docs
e
i told cursor what you said about initializing the agent with cht_ctx = session.history and it said this: Ah, I see! Thank you for that clarification from the LiveKit support agent. However, there's still an issue with the current code - we have a circular dependency problem. ## The Issue: The current code tries to do this:
Copy code
python
agent = InterviewAgentRealtime(chat_ctx=session.history)  # But session doesn't exist yet!
session = AgentSession(...)  # Session is created after agent
But
session.history
doesn't exist until after the
AgentSession
is created, so we can't pass it to the agent constructor. ## The Solution: We need to either: 1. Create the session first, then the agent:
Copy code
python
session = AgentSession(...)
agent = InterviewAgentRealtime(chat_ctx=session.history)
await session.start(agent=agent, room=ctx.room)
2. Or pass the chat_ctx after session creation:
Copy code
python
agent = InterviewAgentRealtime()
session = AgentSession(...)
agent.chat_ctx = session.history  # Set it after session creation
await session.start(agent=agent, room=ctx.room)
what should i do?
t
You're absolutely right—`session.history` doesn't exist until the
AgentSession
is created, so it can't be passed to the agent when it's being initialized. No worries though! You’ve got two good options to tackle this: 1. Create the session first, then the agent: This way,
session.history
is ready before the agent comes into play:
Copy code
session = AgentSession(...)
agent = InterviewAgentRealtime(chat_ctx=session.history)
await session.start(agent=agent, room=ctx.room)
2. Set the
chat_ctx
after session creation:
Here, you initialize the agent first and then assign
chat_ctx
once the session is set up:
Copy code
agent = InterviewAgentRealtime()
session = AgentSession(...)
agent.chat_ctx = session.history  # Set it after session creation
await session.start(agent=agent, room=ctx.room)
Both methods work well, but the first one tends to be a bit cleaner since it avoids tweaking the agent after it's created. Pick whichever feels more comfortable for your coding style and project setup!
e
if i go with option 1, will the agent still have all the session.history at all times while conducting the interview ?
t
Absolutely! If you choose option 1 and initialize the agent with
chat_ctx=session.history
right after creating the session, the agent will have access to the full session history throughout the interview. The
session.history
keeps updating in real time as your conversation goes on, so the agent naturally uses this growing history to shape its responses. This way, the agent can smoothly adjust its questions based on everything that's been said so far, as long as you pass the
chat_ctx
correctly when you initialize it. Pretty handy, right? Sources: Workflows | LiveKit Docs | examples/voice_agents/session_close_callback.py | main.py | Turn detection and interruptions | LiveKit Docs | Testing and evaluation | LiveKit Docs
e
after the agent is done asking questions, i want to print out the entire conversation to my logs. what is the easiest way to do that?
t
If you'd like to print out the entire conversation to your logs once the agent has finished asking questions, you can easily grab it from
session.history
. This holds the full chat as a
ChatContext
object. Here’s a quick example to show you how:
Copy code
# Access the session history
for item in session.history.items:
    print(f"{item.role}: {item.content}")
This little loop goes through every message in
session.history
and prints out who said what (like user or assistant) along with the message itself. And if you want to save this to a file or send it to a logging system, just swap out the
print
line with whatever logging method you prefer. Easy, right?
e
what is the best way to tell the agent to end a session?
t
Figuring out the best way to end a session really depends on what you're trying to achieve: 1. End Only the Agent Session: If you just want to disconnect the agent but keep the room open for everyone else, you can use the
aclose()
method:
await self.session.aclose()
To make sure any ongoing audio or speech finishes up nicely before disconnecting, you might want to call
drain()
first:
Copy code
await self.session.drain()
await self.session.aclose()
2. End the Session for All Participants: If you want to wrap things up completely—disconnect everyone and stop recordings—you’ll want to use the
delete_room
API:
await ctx.api.room.delete_room(api.DeleteRoomRequest(room=ctx.room.name))
So, pick the option that best fits what you need. For example, use
aclose()
if the agent’s done but the room should stay active, or
delete_room
if you want to close everything down. Sources: livekit-agents/livekit/agents/voice/agent_session.py | flows/multi_stage_flow.py | Agents telephony integration | LiveKit Docs | Inside a session | LiveKit Docs
e
thanks. also, when i applied the code below, it only printed out the assistant's comments, not the users. how do i get both? async def print_conversation(): """Print the entire conversation to logs when the interview is complete.""" print("=" * 80) print("🎯 COMPLETE INTERVIEW CONVERSATION") print("=" * 80) for item in session.history.items: print(f"{item.role.upper()}: {item.content}") print("=" * 80) print("🎯 END OF CONVERSATION") print("=" * 80) ctx.add_shutdown_callback(print_conversation)
t
Hey there! The
session.history.items
should actually include both user and assistant messages. If you’re only seeing assistant comments, it might mean there’s a hiccup with how user messages are getting added to the history. No worries though—here are some friendly steps to help you troubleshoot and fix this: 1. Verify Transcription: First, double-check that transcription is set up correctly and working smoothly. User messages get added to the history once transcription finishes. So, if transcription isn’t working right, user messages won’t show up. 2. Check Event Handling: Make sure the
UserTranscriptionFinishedEvent
is being handled properly and that the transcribed text is added to the chat context with
role="user"
. This step is key! 3. Inspect Chat Context: Take a look to ensure the chat context isn’t filtering out or changing user messages. Both user and assistant messages should be present in
session.history
. 4. Timing Issues: It’s also important that the system waits for the final transcription before processing user messages. If transcription isn’t complete, those messages might not get recorded. Once you’ve checked these areas, your code should be all set to correctly show both user and assistant messages from
session.history
. You’ve got this! Sources: livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real... | agents/src/llm/utils.test.ts
e
let's start with ending the session. i want to do it for all participants. here's my code. i want it to end the session right after it says "Thank you for your insights" (which you can see in the instructions). import logging import time from typing import Dict, Any, Optional, List from dataclasses import dataclass, field from dotenv import load_dotenv from livekit.agents import ( Agent, AgentSession, JobContext, JobProcess, WorkerOptions, cli, RunContext, function_tool ) from livekit.plugins import deepgram, openai, silero from livekit.plugins.turn_detector.multilingual import MultilingualModel logger = logging.getLogger("interview_agent_realtime") logger.setLevel(logging.INFO) load_dotenv() def prewarm(_proc_: JobProcess): """Preload models for faster startup.""" logger.info("Preloading VAD model...") proc.userdata["vad"] = silero.VAD.load() logger.info("VAD model loaded successfully") async def entrypoint(_ctx_: JobContext): """Main entry point for the simplified interview agent using Realtime API.""" logger.info(f"Starting simplified interview agent session for room: {ctx.room.name}") # Create agent session first so session.history is available session = AgentSession( # 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"], stt=deepgram.STT(model="nova-3", language="multi"), # Fixed: language="multi" for MultilingualModel # Use OpenAI Realtime API for better voice performance llm=openai.realtime.RealtimeModel( voice="alloy", # Turn off OpenAI's turn detection to use LiveKit's _turn_detection_=None, # Use Deepgram STT instead of OpenAI's transcription _input_audio_transcription_=None, ), # Force metrics collection for all turns _min_endpointing_delay_=1.0, _max_endpointing_delay_=5.0, # Enable comprehensive metrics collection _discard_audio_if_uninterruptible_=False ) # Now create agent instance using LiveKit's base Agent directly agent = Agent( instructions=""" You are Listenful, a professional interviewer conducting a user research project about a tool called Tracky. Tracky is an AI based executive assistant that can help with calendaring, making reservations, doing expense reports, and all other things that an executive assistant can do. The goals of this research are to determine whether Tracky would be used by people, and if so, what are the most important tasks they would use it for. Here is an initial set of questions you can start with: 1. What are some day-to-day tasks that you do? 2. Which tasks would you like help with? 3. Do you wish you had an executive assistant? Start by asking question 1. After each user response, your job is to determine what is the best question to ask next to most efficiently achieve the research goals. You may stick to the list of questions that were given to you, or you may come up with a different question based on what the user told you. It is up to you. Make sure you consider the entire conversation up to that point when you are deciding what to ask next. Then ask the next question. Do not exceed 5 total questions. After the user's response to your last question, say "Thank You for Your Insights Today" and end the session. """, _chat_ctx_=session.history ) # Simple debug print for user turn completion (keeping your requested debug statement) @session.on("metrics_collected") def _on_metrics_collected(ev): metrics_type = getattr(ev.metrics, 'type', 'unknown') speech_id = getattr(ev.metrics, 'speech_id', None) if metrics_type == 'eou_metrics' and speech_id: _# DEBUG: Print the exact new_message content each time user turn completes_ # Note: In simplified version, we don't have accumulated response, so this shows individual segments logger.info(f"🎯 EOU METRICS CAPTURED: {ev.metrics}") print(f"🎯 NEW MESSAGE FROM USER TURN COMPLETION: EOU detected for speech_id: {speech_id}", flush=True) # Add callback to print complete conversation when session ends async def print_conversation(): """Print the entire conversation to logs when the interview is complete.""" print("=" * 80) print("🎯 COMPLETE INTERVIEW CONVERSATION") print("=" * 80) for item in session.history.items: print(f"{item.role.upper()}: {item.content}") print("=" * 80) print("🎯 END OF CONVERSATION") print("=" * 80) ctx.add_shutdown_callback(print_conversation) # Start the session with our simplified agent await session.start(agent=agent, room=ctx.room) if name == "__main__": cli.run_app(WorkerOptions(_entrypoint_fnc_=entrypoint, _prewarm_fnc_=prewarm))
t
Hey there! To wrap up the session for everyone right after the agent says "Thank you for your insights," you can use the
delete_room
API. Since the agent’s instructions already include that phrase, you just need to add a callback that listens for when the agent sends this exact message and then triggers the session to end. Here’s a simple way to tweak your code:
Copy code
@session.on("message")
def _on_message(ev):
    if ev.message.role == "assistant" and "Thank you for your insights" in ev.message.content:
        # End the session for all participants
        ctx.api.room.delete_room(api.DeleteRoomRequest(room=ctx.room.name))
This little callback keeps an ear out for messages from the assistant, checks if it includes that key phrase, and then deletes the room to close the session for everyone. Just pop this callback into your
entrypoint
function before starting the session. That way, the session will end right after the agent finishes their final message. Hope this helps!
e
unfortunately, that didn't work. the session didn't end
t
Hey there! If the
delete_room
API isn’t working as expected, no worries—here are some common reasons and easy fixes to try out: 1. Authentication and Permissions: Double-check that your
LIVEKIT_API_KEY
and
LIVEKIT_API_SECRET
are set up correctly, and that your
LiveKitAPI
client is properly authenticated. Sometimes a small typo can cause hiccups! 2. Room Name: Make sure the room name you’re passing to
delete_room
exactly matches the active room. If the room doesn’t exist or was already deleted, the API call won’t go through. 3. Timing Issues: Try not to reuse the same room name right after deleting it. Using unique names—like adding timestamps or UUIDs—can help avoid any timing conflicts. 4. Error Handling: It’s a good idea to wrap your
delete_room
call in a try-except block to catch any errors and see what’s going on:
Copy code
try:
    await ctx.api.room.delete_room(api.DeleteRoomRequest(room=ctx.room.name))
except Exception as e:
    print(f"Failed to delete room: {e}")
5. Console Mode: If you’re running your app in console or debug mode, sometimes the
delete_room
call might be disabled. Make sure you’re in a production environment when you try this. 6. Wait for Completion: Before deleting the room, ensure any ongoing agent speech or activity has finished. Using
await session.drain()
can help make sure all audio processing is wrapped up smoothly. Give these a shot, and if you’re still stuck, just let me know—I’m happy to help you troubleshoot further! Sources: mcp/server.py | livekit-agents/livekit/agents/job.py | Agents telephony integration | LiveKit Docs | Job lifecycle | LiveKit Docs | Inside a session | LiveKit Docs
e
i decided to try to just close the agent session. it didn't work. here's my code: # Listen for agent's "Thank you for your insights" message to auto-end session @session.on("message") def _on_message(ev): print(f"🎯 MESSAGE EVENT: role={ev.message.role}, content='{ev.message.content[:50]}...'", flush=True) if ev.message.role == "assistant" and "Thank you for your insights" in ev.message.content: print("🎯 DETECTED END PHRASE - ENDING SESSION", flush=True) async def end_session(): _try_: # Wait for completion as LiveKit suggested await session.drain() print("🎯 SESSION DRAINED - CLOSING AGENT SESSION", flush=True) # End only the agent session await session.aclose() print("🎯 AGENT SESSION CLOSED SUCCESSFULLY", flush=True) except Exception as e: print(f"🎯 Failed to close session: {e}", flush=True) asyncio.create_task(end_session())
t
The
session.aclose()
method might not work as expected if a few things aren’t quite right. No worries though—here’s a friendly checklist to help make sure it works smoothly: 1. Call
drain()
Before `aclose()`:
It’s a good idea to always call
await session.drain()
before
session.aclose()
. This makes sure any queued audio or tasks wrap up nicely before closing. 2. Verify the Session is Started: Double-check that the session actually started with
session.start()
. If it wasn’t started or is already closed,
aclose()
won’t do anything. 3. Handle Uninterruptible Speech: If your agent is playing uninterruptible audio,
aclose()
will wait for it to finish. To avoid waiting around, you can set
allow_interruptions=True
so the agent can be interrupted. 4. Avoid Concurrent Close Attempts: Try not to call
aclose()
multiple times at once. Keeping a single closure path in your app helps prevent any race conditions. 5. Use Shutdown Hooks: You can attach a handler to the
"close"
event to do any last cleanup or logging after the session ends:
Copy code
@session.on("close")
def on_close(ev):
    print(f"Session closed: {ev.reason}")
    for item in session.history.items:
        print(f"{item.role}: {item.content}")
6. Consider Room-Level Deletion: If you want to completely end the session for everyone, using the
delete_room
API might be the way to go instead of `aclose()`: Give these tips a try, and if you’re still running into issues, just let me know—I’m here to help you get it working perfectly! Sources: examples/other/transcription/multi-user-transcriber.py | Inside a session | LiveKit Docs
e
i decided to go back to delete_room. does this code look right? it isn't working and the room isn't being deleted. i am running in console mode. # Listen for agent's "Thank you for your insights" message to auto-end session @session.on("message") def _on_message(ev): print(f"🎯 MESSAGE EVENT: role={ev.message.role}, content='{ev.message.content[:50]}...'", flush=True) if ev.message.role == "assistant" and "Thank you for your insights" in ev.message.content: print("🎯 DETECTED END PHRASE - ENDING SESSION", flush=True) async def end_session(): _try_: # Wait for completion as LiveKit suggested await session.drain() print("🎯 SESSION DRAINED - DELETING ROOM", flush=True) # End the session for all participants await ctx.api.room.delete_room(api.DeleteRoomRequest(room=ctx.room.name)) print("🎯 ROOM DELETED SUCCESSFULLY", flush=True) except Exception as e: print(f"🎯 Failed to delete room: {e}", flush=True) asyncio.create_task(end_session())
t
Hey there! Your code for deleting the room looks good from a logic standpoint, but the hiccup is probably because you’re running it in console mode. In console mode, the
delete_room
API is actually disabled and just returns a mock response, which is why the room isn’t getting deleted. To get this working, you’ll want to run your app in a production environment where the
delete_room
API is fully active. Here are a few things to double-check: 1. Make sure you’re using valid
LIVEKIT_API_KEY
and
LIVEKIT_API_SECRET
for authentication. 2. Confirm that the
ctx.api.room.delete_room
call happens in production—not in console or debug mode. 3. Verify that the room name you’re passing to
delete_room
exactly matches the active room name. If you’re just testing locally and want to mimic deleting a room, you can simply log the action instead of calling the API. Something like this works:
Copy code
print(f"Simulating room deletion for room: {ctx.room.name}")
Once you switch over to production, the
delete_room
API should do its job just fine. Hope this helps!
e
can i run it in dev and still have it work?
t
Yes, the
delete_room
API totally works in development mode! LiveKit makes it easy by letting you run the server in dev mode with the command
livekit-server --dev
. This starts up the server using a placeholder API key and secret (API Key:
devkey
, API Secret:
secret
), so you’re all set to test things out. Just double-check a few things: • You’re using the right API key and secret for the development server. • The room name you pass to
delete_room
matches a room that’s currently active. • The server is up and running, and your app can reach it without any issues. Once you’ve got these in place, the
delete_room
API should work smoothly in development mode. If you run into any hiccups, I’m here to help! Sources: packages/livekit-server-sdk/src/RoomServiceClient.ts | livekit-api/src/services/room.rs | src/main/kotlin/io/livekit/server/RoomServiceClient.kt | Managing rooms | LiveKit Docs | livekit/livekit_room.twirp.go
e
i think i want to run it not in console mode (and not in dev mode). can i hard code a room name just to test it
?
t
Absolutely, you can hard code a room name to test out the
delete_room
functionality. Here’s a quick example:
Copy code
await ctx.api.room.delete_room(api.DeleteRoomRequest(room="test-room"))
Just make sure the room name you pick matches an active room on your LiveKit server. This is a handy way to test things in a controlled setup, especially when you’re working outside of the console or development mode. Once you’re happy that it’s working, you can easily swap out the hard-coded room name for a dynamic one that fits your app’s context.
e
how do i make sure the room name matches an active room on my livekit server? like how do i create an active room with a specific name on my livekit server?
t
Hey there! If you want to create an active room with a specific name on your LiveKit server, you can easily do that using the
CreateRoom
API. Let me walk you through how: Using Python SDK:
Copy code
from livekit import api
import asyncio

async def main():
    lkapi = api.LiveKitAPI()
    room_info = await lkapi.room.create_room(
        api.CreateRoomRequest(name="my-room"),
    )
    print(room_info)

if __name__ == "__main__":
    asyncio.run(main())
Using LiveKit CLI:
Copy code
lk room create my-room
Using REST API: Sources: Auto egress | LiveKit Docs | livekit-api/livekit/api/room_service.py | packages/livekit-server-sdk/src/RoomServiceClient.ts | Managing rooms | LiveKit Docs | livekit-api/src/services/room.rs
e
i finally got it to delete the room. but the final transcript includes no user messages, only assistant messages. also, the conversation items added also only include assistant messages, not user messages. can you tell me if there's something wrong with my code that is causing this? here's my code: import logging import time from typing import Dict, Any, Optional, List from dataclasses import dataclass, field from dotenv import load_dotenv from livekit.agents import ( Agent, AgentSession, JobContext, JobProcess, WorkerOptions, cli, RunContext, function_tool ) from livekit import api import asyncio from livekit.plugins import deepgram, openai, silero from livekit.plugins.turn_detector.multilingual import MultilingualModel logger = logging.getLogger("interview_agent_realtime") logger.setLevel(logging.INFO) load_dotenv() def prewarm(_proc_: JobProcess): """Preload models for faster startup.""" logger.info("Preloading VAD model...") proc.userdata["vad"] = silero.VAD.load() logger.info("VAD model loaded successfully") async def entrypoint(_ctx_: JobContext): """Main entry point for the simplified interview agent using Realtime API.""" logger.info(f"Starting simplified interview agent session for room: {ctx.room.name}") # Create function tool for ending interview silently @function_tool def end_interview() -> str: """Call this function when the interview is complete to end the session.""" print("🎯 AGENT CALLED END_INTERVIEW FUNCTION - ENDING SESSION", flush=True) async def end_session(): _try_: await save_transcript() await session.drain() print("🎯 SESSION DRAINED - DELETING ROOM", flush=True) await ctx.api.room.delete_room(api.DeleteRoomRequest(room=ctx.room.name)) print("🎯 ROOM DELETED SUCCESSFULLY", flush=True) except Exception as e: print(f"🎯 Failed to delete room: {e}", flush=True) asyncio.create_task(end_session()) return "Interview ended successfully" # Create agent session first so session.history is available session = AgentSession( # 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"], stt=deepgram.STT(model="nova-3", language="multi"), # Fixed: language="multi" for MultilingualModel # Use OpenAI Realtime API for better voice performance llm=openai.realtime.RealtimeModel( voice="alloy", # Turn off OpenAI's turn detection to use LiveKit's _turn_detection_=None, # Use Deepgram STT instead of OpenAI's transcription _input_audio_transcription_=None, ), # Force metrics collection for all turns _min_endpointing_delay_=1.0, _max_endpointing_delay_=5.0, # Enable comprehensive metrics collection _discard_audio_if_uninterruptible_=False ) # Now create agent instance using LiveKit's base Agent directly agent = Agent( instructions=""" You are Listenful, a professional interviewer conducting a user research project about a tool called Tracky. Tracky is an AI based executive assistant that can help with calendaring, making reservations, doing expense reports, and all other things that an executive assistant can do. The goals of this research are to determine whether Tracky would be used by people, and if so, what are the most important tasks they would use it for. Here is an initial set of questions you can start with: 1. What are some day-to-day tasks that you do? 2. Which tasks would you like help with? 3. Do you wish you had an executive assistant? Start by asking question 1. After each user response, your job is to determine what is the best question to ask next to most efficiently achieve the research goals. You may stick to the list of questions that were given to you, or you may come up with a different question based on what the user told you. It is up to you. Make sure you consider the entire conversation up to that point when you are deciding what to ask next. Then ask the next question. Do not exceed 5 total questions. After the user's response to your last question, say "Thank You for Your Insights Today" and then call the end_interview function. """, _chat_ctx_=session.history, _fnc_ctx_=[end_interview] ) # Simple debug print for user turn completion (keeping your requested debug statement) @session.on("metrics_collected") def _on_metrics_collected(ev): metrics_type = getattr(ev.metrics, 'type', 'unknown') speech_id = getattr(ev.metrics, 'speech_id', None) if metrics_type == 'eou_metrics' and speech_id: _# DEBUG: Print the exact new_message content each time user turn completes_ # Note: In simplified version, we don't have accumulated response, so this shows individual segments logger.info(f"🎯 EOU METRICS CAPTURED: {ev.metrics}") print(f"🎯 NEW MESSAGE FROM USER TURN COMPLETION: EOU detected for speech_id: {speech_id}", flush=True) # Keep conversation logging for debugging @session.on("conversation_item_added") def _on_conversation_item_added(ev): print(f"📝 CONVERSATION ITEM: {ev.item.role} - {ev.item.text_content[:50]}...", flush=True) # Add transcript saving function async def save_transcript(): """Save the complete conversation history to log file.""" _try_: from datetime import datetime import json current_date = datetime.now().strftime("%Y%m%d_%H%M%S") # Get the complete conversation history from session.history history = session.history.to_dict() complete_transcript = { "session_history": history, "metadata": { "room_name": ctx.room.name, "timestamp": current_date } } # Write transcript to JSON file transcript_filename = f"transcript_{ctx.room.name}_{current_date}.json" with open(transcript_filename, 'w') as f: json.dump(complete_transcript, f, indent=2) print("=" * 80) print("🎯 TRANSCRIPT SAVED") print("=" * 80) print(f"📄 Transcript saved to: {transcript_filename}") print(f"📅 Generated at: {current_date}") print("=" * 80) except Exception as e: print(f"❌ Failed to save transcript: {e}", flush=True) # Start the session with our simplified agent await session.start(agent=agent, room=ctx.room) if name == "__main__": cli.run_app(WorkerOptions(_entrypoint_fnc_=entrypoint, _prewarm_fnc_=prewarm))
t
Hey there! It looks like the reason why
session.history
and
conversation_item_added
only show assistant messages and not user messages could be due to a few things. Let’s walk through them together: 1. Transcription Configuration: First, double-check that your transcription service (Deepgram, in your case) is set up and working properly. If the user’s audio isn’t being transcribed, their messages won’t show up in the session history. Make sure the Deepgram STT model is correctly configured and actually receiving audio input. 2. Event Handling: The
conversation_item_added
event should fire for both user and assistant messages. If it’s only happening for assistant messages, take a look at whether user messages are being added to the session history at all. This might hint at an issue with how user messages are processed or added. 3. Turn Detection: The turn detection model (MultilingualModel) might not be picking up user turns correctly. It’s worth confirming that the
turn_detection
parameter is set up properly and works well with your current setup. 4. Debugging User Messages: Try adding a quick debug statement to log user messages as they come in. For example, you could log the transcription results to make sure user input is being captured like this:
Copy code
@session.on("metrics_collected")
def _on_metrics_collected(ev):
    if ev.metrics.type == 'user_transcription':
        print(f"User transcription: {ev.metrics.transcription}")
Checking these areas should help you figure out why user messages aren’t showing up in the session history or conversation items. If you want, I’m here to help you dig deeper into this—just let me know!