on_user_turn_completed with this one, or something...
# ask-ai
s
on_user_turn_completed with this one, or something similar, where is the actual code that call the llm and get reply?, i want to update each time the user input to add string x to it, but i do not want to save x to the chat history
t
Thanks for reaching out, Mostafa. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hi there! The
on_user_turn_completed
function is a helpful lifecycle hook in LiveKit Agents that lets you tweak the user input or chat context for the current turn without changing the chat history. You can find how it’s implemented in the
agent_activity.py
file inside the
livekit/agents/voice/
directory of the LiveKit Agents repository. If you'd like to modify user input without saving those changes to the chat history, here are a couple of friendly tips: • You can directly update the
new_message.content
within the
on_user_turn_completed
function before it’s sent off to the LLM. • Or, you can add temporary system messages or context to the
turn_ctx
, which will only influence the current generation. For example, here’s a simple way to clean or adjust the user input:
Copy code
async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage):
    # Modify the user input
    original_content = new_message.text_content
    modified_content = original_content + " string x"  # Add your string
    new_message.content = [modified_content]
This way, your changes apply just for the current turn and won’t be saved in the chat history. If you have any questions or want to explore this further, I’m here to help! Sources: examples/voice_agents/README.md | Pipeline nodes and hooks | LiveKit Docs
s
how can i use it with AgentSession
t
I'd love to help you get started with using the
on_user_turn_completed
function alongside
AgentSession
. To do this smoothly, you'll want to override this method in your custom
Agent
class and connect it with your session. Here's a friendly step-by-step guide: 1. Create a Custom Agent Class Begin by overriding the
on_user_turn_completed
method in your agent class like this:
Copy code
from livekit.agents import Agent

class MyAgent(Agent):
    async def on_user_turn_completed(self, turn_ctx, new_message):
        # Modify user input or context
        if "stop" in new_message.text_content.lower():
            self.session.interrupt()
        else:
            new_message.content = [new_message.text_content + " string x"]
2. Set Up and Start the AgentSession Next, you'll want to integrate your agent with an
AgentSession
as shown here:
Copy code
from livekit.agents import AgentSession

async def entrypoint(ctx):
    session = AgentSession(turn_detection="manual")
    agent = MyAgent()
    await session.start(agent=agent)
3. Access Session Methods Inside your
on_user_turn_completed
method, feel free to use
self.session
to manage the session—whether that's interrupting turns or crafting replies. If you'd like me to walk you through more examples or clarify anything, just let me know. I'm here to help! Sources: External data and RAG | LiveKit Docs | Logs, metrics, and telemetry | LiveKit Docs | Pipeline nodes and hooks | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py
c
user_speech_committed
t
Hi there! I wanted to let you know that the function
user_speech_committed
isn’t available in LiveKit. But don’t worry—the same functionality is actually handled by the
commit_user_turn
method in
AgentSession
. This method is really helpful for manually signaling the end of a user’s speech input, especially when you’re working in manual turn detection mode. Here’s how you can use `commit_user_turn`: • Just call
session.commit_user_turn()
to wrap up the transcription phase and prompt the agent to generate a response. • You can also pass in parameters like
transcript_timeout
(which sets how long to wait for the final transcription) and
stt_flush_duration
(the silence duration before flushing the STT buffer). For example:
Copy code
@ctx.room.local_participant.register_rpc_method("end_turn")
async def end_turn(data):
    session.input.set_audio_enabled(False)
    session.commit_user_turn(transcript_timeout=10.0, stt_flush_duration=2.0)
This way, the user’s speech is properly finalized, and the agent can smoothly generate a response. If you have any questions or want me to walk you through more examples, just let me know—I’m here to help! Sources: examples/voice_agents/push_to_talk.py | plugins/openai/src/realtime/api_proto.ts | Turn detection and interruptions | LiveKit Docs | Agent speech and audio | LiveKit Docs
c
how max nested function calls work?
t
I’d love to help you understand how the maximum number of nested function calls works in LiveKit! This is managed by the
max_tool_steps
setting. Every time a function call happens, a step counter goes up by one. When the number of steps goes beyond
max_tool_steps + 1
, the system kindly stops any more function calls and logs a warning to let you know the limit has been reached. Here’s how it works: • Each function call increases the step counter (
num_steps
). • If
num_steps
goes over the set limit, the calls stop to help avoid infinite loops or using too many resources. For example:
Copy code
if speech_handle.num_steps >= self._session.options.max_tool_steps + 1:
    logger.warning("maximum number of function calls steps reached")
    return

speech_handle._num_steps += 1
About configuration: You’ll find
max_tool_steps
in your agent session options, and you can tweak it to fit what you need. Just a heads-up: setting it too low might cut off some valid operations, while setting it too high could let processes run longer than intended. If you have any questions or want me to walk you through this more, please don’t hesitate to ask—I’m here to help! Sources: livekit-plugins/livekit-plugins-aws/livekit/plugins/aws/experimental/realti... | examples/rpc/src/main.rs
c
the system kindly stops any more function calls and logs a warning to let you know the limit has been reached. then what happened?
t
When the
max_tool_steps
limit is reached, the system kindly pauses any further function calls and logs a gentle warning. From there, it carefully manages the transition to keep your session running smoothly: • If there are any pending tool outputs, the agent moves into a "thinking" state to thoughtfully process them. • If no tool outputs are waiting and the agent is currently "speaking," it shifts to a "listening" state, ready and eager to hear your next input. Rest assured, the system doesn’t end the session abruptly. Instead, it takes care of proper cleanup and state management. For instance, the speech handle is marked as complete, and the agent can either respond with the results gathered so far or patiently wait for your next message. Please feel free to reach out if you’d like me to explain anything further—I’m here to help! Sources: agents/src/voice/agent_activity.ts | livekit-plugins/livekit-plugins-aws/livekit/plugins/aws/llm.py
c
what is the optimal max_tool_steps ?
t
Thanks for reaching out! The best value for
max_tool_steps
really depends on how your agent works and how many tool calls usually happen in one conversation turn. If you could share a bit more about your use case—like the complexity of the tasks your agent handles or how many tool calls you typically expect per turn—I’d be happy to help recommend the most suitable value for you. Sources: livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real...
c
give a optimal tool steps
t
Finding the right value for
max_tool_steps
really depends on how complex your agent’s tasks are, but a great place to start is usually between 5 to 10 steps. This range strikes a nice balance, allowing your agent to handle moderately complex workflows without getting stuck in too many or endless tool calls. If your agent is working on simpler tasks, setting it closer to 5 might be just right. On the other hand, if it’s dealing with more complex workflows that need several tool calls in a row, you could try increasing it to 10 or even a bit higher. Keep an eye on how your agent performs, and feel free to tweak the number as you see what works best. I’m here if you’d like any more help or advice along the way!