early-restaurant-74591
09/03/2025, 10:25 PMtall-airline-16756
09/03/2025, 10:25 PMtall-airline-16756
09/03/2025, 10:25 PMAgentSession 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.mdearly-restaurant-74591
09/03/2025, 10:26 PMtall-airline-16756
09/03/2025, 10:27 PMAgentSession 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 Docsearly-restaurant-74591
09/03/2025, 10:28 PMtall-airline-16756
09/03/2025, 10:29 PMAgentSession 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 Docsearly-restaurant-74591
09/03/2025, 10:42 PMtall-airline-16756
09/03/2025, 10:43 PMchat_ctx parameter in the Agent constructor:
Basic Example:
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:
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:
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 Docsearly-restaurant-74591
09/03/2025, 10:45 PMtall-airline-16756
09/03/2025, 10:46 PMsession.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?early-restaurant-74591
09/03/2025, 11:24 PMtall-airline-16756
09/03/2025, 11:24 PMsession.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:
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 Docsearly-restaurant-74591
09/03/2025, 11:31 PMtall-airline-16756
09/03/2025, 11:32 PMchat_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:
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.mdearly-restaurant-74591
09/03/2025, 11:33 PMtall-airline-16756
09/03/2025, 11:34 PMchat_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 Docsearly-restaurant-74591
09/03/2025, 11:43 PMtall-airline-16756
09/03/2025, 11:44 PMinstructions 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.pyearly-restaurant-74591
09/03/2025, 11:45 PMtall-airline-16756
09/03/2025, 11:46 PMinstructions 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.pyearly-restaurant-74591
09/03/2025, 11:47 PMtall-airline-16756
09/03/2025, 11:47 PMinstructions 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:
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 Docsearly-restaurant-74591
09/04/2025, 12:15 AMpython
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:
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:
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?tall-airline-16756
09/04/2025, 12:16 AMAgentSession 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:
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:
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!early-restaurant-74591
09/04/2025, 12:34 AMtall-airline-16756
09/04/2025, 12:35 AMchat_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 Docsearly-restaurant-74591
09/04/2025, 3:58 AMtall-airline-16756
09/04/2025, 3:59 AMsession.history. This holds the full chat as a ChatContext object. Here’s a quick example to show you how:
# 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?early-restaurant-74591
09/04/2025, 4:07 AMtall-airline-16756
09/04/2025, 4:07 AMaclose() 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:
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 Docsearly-restaurant-74591
09/04/2025, 4:09 AMtall-airline-16756
09/04/2025, 4:10 AMsession.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.tsearly-restaurant-74591
09/04/2025, 4:12 AMtall-airline-16756
09/04/2025, 4:12 AMdelete_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:
@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!early-restaurant-74591
09/04/2025, 5:24 AMtall-airline-16756
09/04/2025, 5:24 AMdelete_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:
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 Docsearly-restaurant-74591
09/04/2025, 5:43 AMtall-airline-16756
09/04/2025, 5:44 AMsession.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:
@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 Docsearly-restaurant-74591
09/04/2025, 5:46 AMtall-airline-16756
09/04/2025, 5:46 AMdelete_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:
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!early-restaurant-74591
09/04/2025, 5:49 AMtall-airline-16756
09/04/2025, 5:50 AMdelete_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.goearly-restaurant-74591
09/04/2025, 5:52 AMearly-restaurant-74591
09/04/2025, 5:52 AMtall-airline-16756
09/04/2025, 5:52 AMdelete_room functionality. Here’s a quick example:
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.early-restaurant-74591
09/04/2025, 5:53 AMtall-airline-16756
09/04/2025, 5:53 AMCreateRoom API. Let me walk you through how:
Using Python SDK:
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:
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.rsearly-restaurant-74591
09/04/2025, 4:03 PMtall-airline-16756
09/04/2025, 4:05 PMsession.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:
@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!