future-ocean-83972
11/26/2025, 8:18 AMtall-airline-16756
11/26/2025, 8:18 AMtall-airline-16756
11/26/2025, 8:18 AMuser_away_timeout on the AgentSession to 10 seconds:
session = AgentSession(
user_away_timeout=10.0,
# other config...
)
1. Listen for the user_state_changed event and react when state becomes `away`:
@session.on("user_state_changed")
def on_user_state_changed(ev: UserStateChangedEvent):
if ev.new_state == "away":
session.say("Hello? Are you still there?")
# wait a short grace period for response, then end if still away
# e.g., schedule a check in 5-10s and call session.close() or hangup
1. End the call politely by closing the session or using your hangup logic (disconnect participant or delete the room) if the user remains away.
If you’d like, I can:
• Provide a small complete code example showing the prompt + delayed hangup.
• Recommend a good grace period to wait after the prompt. Which language or SDK are you using? Sources: Agent session | LiveKit docs | Agents telephony integration | LiveKit Docsfuture-ocean-83972
11/26/2025, 8:30 AMtall-airline-16756
11/26/2025, 8:31 AMuser_away_timeout to 10 seconds,
• prompts the user when they become away,
• waits a recommended 5‑second grace period for a response,
• then politely ends the call if the user remains away.
Recommendation: a 5‑second grace period after the prompt balances giving the user a chance to respond without keeping the call idle too long. Adjust to 3–8s depending on UX needs.
# Example using AgentSession-like API
import time
import threading
# Create session with 10s idle timeout
session = AgentSession(
user_away_timeout=10.0,
# ... other config ...
)
GRACE_PERIOD = 5.0 # seconds to wait after the prompt
@session.on("user_state_changed")
def on_user_state_changed(ev: UserStateChangedEvent):
if ev.new_state == "away":
# Ask if user is still there
session.say("Hi — I haven't heard from you. Are you still there?")
# Start a timer to check again after GRACE_PERIOD
def check_and_hangup():
time.sleep(GRACE_PERIOD)
# If user is still away, end the call politely
if session.user_state == "away":
session.say("It looks like you're away. I'll end the call now. Feel free to rejoin.")
# Close session / hang up
session.close() # or call your hangup/delete room logic
threading.Thread(target=check_and_hangup, daemon=True).start()
If you want, I can:
• convert this to another language/SDK,
• expand the example to debounce repeated away events,
• or show an alternative hangup method (disconnect participant vs. delete room). Which would you like?future-ocean-83972
11/26/2025, 8:33 AMtall-airline-16756
11/26/2025, 8:33 AMasync def entrypoint(ctx: agents.JobContext):. Below is an async Python example that:
• sets user_away_timeout to 10s when creating the session,
• listens for user_state_changed inside the entrypoint,
• sends a prompt when the user becomes away,
• waits a 5s grace period for a response,
• then politely ends the call if the user remains away.
Adjust GRACE_PERIOD as desired.
import asyncio
from livekit_agents import AgentSession, UserStateChangedEvent, agents # adjust imports to your SDK
GRACE_PERIOD = 5.0 # seconds to wait after prompting
async def entrypoint(ctx: agents.JobContext):
session = AgentSession(
user_away_timeout=10.0,
# ... other config ...
)
# track an in-flight grace-task so repeated "away" events don't stack
session._away_task = None
@session.on("user_state_changed")
async def on_user_state_changed(ev: UserStateChangedEvent):
if ev.new_state == "away":
# cancel any existing grace task
if session._away_task and not session._away_task.done():
session._away_task.cancel()
# send prompt
await session.say("Hi — I haven't heard from you. Are you still there?")
# schedule grace-period check
async def check_and_hangup():
try:
await asyncio.sleep(GRACE_PERIOD)
except asyncio.CancelledError:
return
# if user still away, politely end the call
if getattr(session, "user_state", None) == "away":
await session.say("It looks like you're away. I'll end the call now. Feel free to rejoin.")
await session.close() # or your hangup/disconnect logic
session._away_task = asyncio.create_task(check_and_hangup())
else:
# If user returns, cancel any pending hangup
if session._away_task and not session._away_task.done():
session._away_task.cancel()
# Start the session / run agent logic (depends on your SDK)
await session.start(ctx) # replace with the correct start method for your environment
If you want, I can:
• adapt this to your exact SDK import names and start/close methods,
• convert to a different language or synchronous style. Which would you prefer?future-ocean-83972
11/26/2025, 2:46 PMtall-airline-16756
11/26/2025, 2:46 PMsession.shutdown() does. It gracefully terminates the agent session:
• Drains pending speech and waits for queued operations to finish.
• Commits any remaining transcripts or state.
• Closes all I/O (audio/video/data tracks) and disconnects the agent from the LiveKit room.
• Emits a close event when cleanup completes.
• Shutdown hooks registered via ctx.addShutdownCallback() run after shutdown.
Use shutdown() when you want a clean, graceful end to the agent’s session (as opposed to an abrupt disconnect). Which SDK/runtime are you using—I can show the exact call pattern for it.
Sources: Job lifecycle | LiveKit docsfuture-ocean-83972
11/27/2025, 8:45 AMtall-airline-16756
11/27/2025, 8:45 AMtool_choice to 'required' in your agent configuration. This forces the model to select and invoke a tool for each response.
• Ensure at least one tool is registered with the agent.
Examples / where it works
• tool_choice='required' is supported in Groq, Telnyx, Together AI, Anthropic, and Cerebras plugins.
Notes
• The LLM still chooses which registered tool to call unless you further constrain it in prompts or agent logic.
• If you want, I can show a short config snippet for your specific plugin/SDK and how to restrict which tool(s) the model may choose. Which plugin are you using? Sources: Groq LLM plugin guide | LiveKit Docs | Telnyx LLM plugin guide | LiveKit Docs | Together AI LLM plugin guide | LiveKit Docs | Anthropic Claude LLM plugin guide | LiveKit Docs | Cerebras LLM plugin guide | LiveKit Docsfuture-ocean-83972
11/27/2025, 8:46 AMtall-airline-16756
11/27/2025, 8:47 AMtool_choice='required',
• wiring that into an AgentSession using the Python SDK.
Adjust names/imports to match your SDK version.
from livekit_agents import AgentSession, Tool, AzureOpenAIPlugin, agents
# 1) Register a tool (example: simple knowledge lookup)
def lookup_tool(query: str) -> str:
# implement your tool logic
return f"Lookup result for: {query}"
tool = Tool(
name="knowledge_lookup",
description="Look up answers from internal knowledge base.",
func=lookup_tool,
)
# 2) Configure Azure OpenAI plugin with tool_choice='required'
azure_llm = AzureOpenAIPlugin(
api_key="YOUR_AZURE_OPENAI_KEY",
deployment="your-deployment-name",
region="your-region",
tool_choice="required", # force the model to call a tool for each response
# other model params as needed (temperature, max_tokens, etc.)
)
# 3) Create session and register tool + LLM plugin
session = AgentSession(
tools=[tool],
llm_plugins=[azure_llm],
user_away_timeout=10.0, # optional: idle timeout example
# other session config...
)
# 4) Entrypoint example for agents.JobContext
async def entrypoint(ctx: agents.JobContext):
await session.start(ctx) # start/connect the agent/session
# agent logic runs; session will enforce tool calls because tool_choice='required'
await session.wait_closed()
# 5) Optional: handle tool results or post-processing if needed
# The LLM will be required to invoke a registered tool; you can constrain tools
# by only registering the ones you want the model to use.
Notes:
• tool_choice='required' forces the model to call one of the registered tools for every response.
• The model still selects which registered tool to call; to constrain selection, only register the allowed tool(s) or add prompt-level guidance.
• If you want, I can:
◦ adapt this to your exact import paths and session start/stop methods,
◦ show how to validate tool outputs before returning them to the user,
◦ or include an example with the idle-prompt + graceful hangup integrated. Which would you like?future-ocean-83972
11/27/2025, 8:49 AMtall-airline-16756
11/27/2025, 8:49 AMagent.update_tools(...) to add/remove tools as the conversation state changes.
• Prompt-level semantic instructions
◦ Give the model clear rules in the agent instructions so it knows when a tool is permitted. Example: “Only call reschedule_appointment if the user explicitly asks to change an existing appointment.”
• Enforce in the tool implementation
◦ Validate preconditions inside the tool and return an error/denial if semantic requirements aren’t satisfied.
◦ Example:
@function_tool()
async def reschedule(context: RunContext, booking_id: str):
if not has_existing_booking(context.user.id, booking_id):
return "Cannot reschedule — no existing booking found."
# proceed with reschedule...
• Use conversation state
◦ Store flags in context.userdata (or session state) to track phases/permissions and gate tool availability or tool behavior.
• Combine approaches for strict enforcement
◦ Set tool_choice='required' on the LLM to force tool usage, and simultaneously:
▪︎ Only register the single allowed tool when that semantic condition is true, or
▪︎ Keep multiple tools registered but have each tool validate preconditions and refuse if not allowed.
Short example pattern (dynamic registration + validation):
# when semantic condition becomes true
await agent.update_tools([allowed_tool])
# tool implementation validates context
@function_tool()
async def allowed_tool(context: RunContext, ...):
if not context.userdata.get("can_use_allowed_tool"):
return "Tool not permitted in current context."
# perform action
Which semantic constraint do you want to enforce? (conversation phase, user role/attribute, specific user utterance, or workflow step?) I’ll produce a tailored code example for that case.
Sources: Tool definition and use | LiveKit docs | Workflows | LiveKit docsfuture-ocean-83972
11/27/2025, 8:51 AMtall-airline-16756
11/27/2025, 8:51 AMtool_choice='required' when a tool must be called.
◦ Dynamically register/unregister tools via agent.update_tools() based on conversation state.
◦ Validate preconditions inside the tool and return a denial if not met.
• Test iteratively with varied prompts and edge cases to ensure the model follows the rule.
If you want, I can draft:
• a system prompt example enforcing a specific rule, and
• matching tool docstrings and tool-validation code for your Python + Azure OpenAI setup. Which rule should I use for the example?future-ocean-83972
11/27/2025, 8:56 AMtall-airline-16756
11/27/2025, 8:56 AMsearch_for_documents tool and embed an instruction that the model must always use it when giving information or guidance about the company’s products and services.
System prompt (agent instructions) — include this verbatim in your agent's instructions:
You MUST always use the tool named "search_for_documents" whenever the user asks for information, guidance, or instructions about the company's products or services.
Do not answer from memory or invent details. First call "search_for_documents" with a clear query describing the user's request and any relevant context.
Use the tool's result to compose a concise, accurate, and user-friendly reply. If the tool returns no relevant documents, ask a clarifying question before providing guidance.
Minimal Python example (tool registration + instructions):
from livekit_agents import AgentSession, Tool, AzureOpenAIPlugin, agents
# Tool implementation + docstring
def search_for_documents(query: str) -> str:
"""
search_for_documents: Look up authoritative product and service documents.
Only call this tool to retrieve company product/service information.
Input: query string describing what the user needs.
Output: text summary or relevant document excerpts.
"""
# implement search logic...
return "search results for: " + query
tool = Tool(
name="search_for_documents",
description="Look up official product and service documents and return relevant passages.",
func=search_for_documents,
)
# Agent instructions = system prompt
agent_instructions = """
You MUST always use the tool named "search_for_documents" whenever the user asks for information,
guidance, or instructions about the company's products or services. Do not answer from memory.
First call "search_for_documents" with a clear query describing the user's request and context.
Use the tool result to compose a concise, accurate reply. If no docs are relevant, ask a clarifying question.
"""
azure_llm = AzureOpenAIPlugin(
api_key="YOUR_KEY",
deployment="your-deployment",
region="your-region",
tool_choice="required", # enforces tool invocation
)
session = AgentSession(
tools=[tool],
llm_plugins=[azure_llm],
instructions=agent_instructions,
)
Notes:
• Keep the system prompt firm (“MUST”, “Do not answer from memory”) and explicit about the sequence: call tool → use results → respond.
• Use tool_choice='required' and only register the document-search tool when you want to strictly enforce this behavior.
• Add tool-level validation that returns a refusal if it would be inappropriate to call the tool.
If you want, I can craft a shorter or longer phrasing for the system prompt tuned to your product tone.future-ocean-83972
11/27/2025, 12:28 PMtall-airline-16756
11/27/2025, 12:28 PMuser_state_changed handler is synchronous and doesn't await cancelling the async task, and it doesn't cancel on all non-away states. Below is a corrected async-friendly version you can drop into your entrypoint that:
• Creates the inactivity task when state becomes away.
• Cancels the task when the user transitions to any other state (listening/speaking).
• Guards against cancelled tasks and multiple concurrent timers.
Corrected example (keep your imports and session setup):
# inside your entrypoint(ctx: JobContext)
inactivity_task: asyncio.Task | None = None
GRACE_PINGS = 3
PING_INTERVAL = 10.0
async def user_presence_task():
try:
for _ in range(GRACE_PINGS):
await session.generate_reply(
instructions="The user has been inactive. Politely check if the user is still present."
)
await asyncio.sleep(PING_INTERVAL)
# still inactive after all pings
await session.say("It looks like you're away. I'll end the call now. Feel free to rejoin.")
await session.shutdown()
except asyncio.CancelledError:
# task was cancelled because user returned — just exit
return
@session.on("user_state_changed")
async def _user_state_changed(ev: UserStateChangedEvent):
nonlocal inactivity_task
if ev.new_state == "away":
# start a new inactivity task, cancelling any existing one first
if inactivity_task is not None and not inactivity_task.done():
inactivity_task.cancel()
try:
await inactivity_task
except asyncio.CancelledError:
pass
inactivity_task = asyncio.create_task(user_presence_task())
return
# For any non-away state (listening, speaking, etc.) cancel the inactivity timer
if inactivity_task is not None and not inactivity_task.done():
inactivity_task.cancel()
try:
await inactivity_task
except asyncio.CancelledError:
pass
inactivity_task = None
Key points
• Use an async handler so you can await cancellation and ensure the task stops before proceeding.
• Cancel and await the task to avoid race conditions where the task still runs and later shuts down the session.
• Treat any non-"away" state as user-returned (listening/speaking) and cancel the timer.
• Wrap the ping loop to handle CancelledError cleanly.
If you want, I can adapt this to your exact event names/states or convert it to a version that debounces rapid state flaps. Which would help most?future-ocean-83972
12/01/2025, 11:57 AMtall-airline-16756
12/01/2025, 11:58 AMfrom livekit.agents import UserInputTranscribedEvent
# inside your _on_conversation_item_added handler:
session.emit(
"user_input_transcribed",
UserInputTranscribedEvent(
language="en",
transcript="(simulated user speech)",
is_final=True,
speaker_id=None,
),
)
This causes the session to treat the input as final speech and switch the user from "away" → "listening".
2) Less preferred (internal API): call the session's internal state updater directly.
# inside your handler
if session.user_state == "away":
session._update_user_state("listening")
This works immediately but uses an internal method (underscore prefix) that may change in future releases — use with caution.
Recommendation: use the transcription event when possible (it follows the framework's intended flow). If you need immediate, explicit control and accept the risk, use _update_user_state. Which handler/event do you want an example for (your _on_conversation_item_added code)?
Sources: Events and error handling | LiveKit docs | Agents and handoffs | LiveKit docs