Can i set some allowed idle time for my agent. For...
# ask-ai
f
Can i set some allowed idle time for my agent. For example if the user has not responded for 10 seconds please check if they are still there and then politely end the call
t
Thanks for reaching out, Heidi. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking about setting an idle timeout so the agent detects 10s of silence, prompts the user, then politely ends the call if there's no response — yes, you can do that. How to implement 1. Set
user_away_timeout
on the AgentSession to 10 seconds:
Copy code
session = AgentSession(
  user_away_timeout=10.0,
  # other config...
)
1. Listen for the
user_state_changed
event and react when state becomes `away`:
Copy code
@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 Docs
f
yes please do both
t
Below is a concise Python example that: • sets
user_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.
Copy code
# 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?
f
should this all be in the async def entrypoint(ctx: agents.JobContext):
t
You can put the idle-timeout logic inside
async 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.
Copy code
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?
f
What does session.shutdown() do?
t
You're asking what
session.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 docs
f
Can i make a tool call mandatory in Livekit
t
You're asking whether a tool call can be made mandatory in LiveKit — yes. What to do • Set the LLM's
tool_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 Docs
f
I am using Python SDK and OpenAI models from Azure.
t
Below is a concise Python example showing: • registering a tool, • configuring the Azure OpenAI LLM with
tool_choice='required'
, • wiring that into an AgentSession using the Python SDK. Adjust names/imports to match your SDK version.
Copy code
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?
f
How can i constrain that the llm uses a tool with sgentic logic
t
Good question — you can enforce semantic constraints so the LLM must call a specific tool only when your conditions are met. Recommended approaches (Python SDK): • Control tool availability ◦ Register only the tools the model should see for the current conversation. ◦ Dynamically update tools with
agent.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:
Copy code
@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):
Copy code
# 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 docs
f
Should i add information on when to call a tool into the system prompt as well or is it enough that the explanation is in the tools docstring
t
Good question — include guidance in both places, but prioritize the system prompt (agent instructions) for reliable behavior. Why: • System prompt (agent instructions) gives strong, global guidance the LLM will follow when deciding whether to call a tool. • Tool docstrings help the model choose the correct tool and clarify behavior, but docstrings alone are weaker for enforcing when to call a tool. Best practices • Put explicit, high-level rules in the system prompt: when to call tools, when not to, and any hard constraints (e.g., “Only call X when the user explicitly asks to reschedule an existing booking”). • Keep tool docstrings concise and descriptive so the model understands each tool’s purpose and inputs. • Reinforce rules in tool docstrings with short reminders (e.g., “Only call when user requests…”) to reduce ambiguity. • Combine with runtime safeguards: ◦ Use
tool_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?
f
Give me an example of how i should add to the system prompt that you have the tool "search_for_documents" Always use this tool to give information and guidance on using the companies products and services.
t
Below is a concise system-prompt example plus a minimal Python snippet showing how to register the
search_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:
Copy code
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):
Copy code
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.
f
Ok let's go back to checking if user is still active: I found this example in livekits codebase: import asyncio import logging from dotenv import load_dotenv from livekit.agents import ( Agent, AgentServer, AgentSession, JobContext, UserStateChangedEvent, cli, ) from livekit.plugins import cartesia, deepgram, openai, silero logger = logging.getLogger("get-email-agent") load_dotenv() server = AgentServer() @breezy-insurance-66772.rtc_session() async def entrypoint(ctx: JobContext): session = AgentSession( vad=silero.VAD.load(), llm=openai.LLM(model="gpt-4o-mini"), stt=deepgram.STT(), tts=cartesia.TTS(), user_away_timeout=12.5, ) inactivity_task: asyncio.Task | None = None async def user_presence_task(): # try to ping the user 3 times, if we get no answer, close the session for _ in range(3): await session.generate_reply( instructions=( "The user has been inactive. Politely check if the user is still present." ) ) await asyncio.sleep(10) session.shutdown() @session.on("user_state_changed") def _user_state_changed(ev: UserStateChangedEvent): nonlocal inactivity_task if ev.new_state == "away": inactivity_task = asyncio.create_task(user_presence_task()) return # ev.new_state: listening, speaking, .. if inactivity_task is not None: inactivity_task.cancel() await session.start(agent=Agent(instructions="You are a helpful assistant."), room=ctx.room) if name == "__main__": cli.run_app(server) This code starts off fine. If the user is in "away" status then the logic to check if they are available starts but the problem is tat when the user then starts speaking that event is not caught and so the inactivity logic continoes and the call is ended
t
You're right — the inactivity task must be cancelled when the user returns. The issue in that sample is the
user_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):
Copy code
# 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?
f
Is there a way for me to change the users new state myself from another type of event. Like for example change user.status to "listening" in _on_conversation_item_added event
t
Yes — you can trigger a user-state change from another event. Two supported approaches: 1) Preferred (supported): emit a final transcription event so the session updates state to "listening" naturally.
Copy code
from 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.
Copy code
# 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