How to call trigger a function_tool manually or ex...
# ask-ai
m
How to call trigger a function_tool manually or explicitily using code
t
Thanks for reaching out, Rajadurai. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I understand that manually triggering a
function_tool
in LiveKit might feel a bit tricky since the system is primarily designed for LLM-driven tool invocation. But don’t worry, there are some alternative ways you can try: • Call the underlying function directly: Since the
@function_tool
decorator wraps a regular function, you can simply call that function directly in your code without going through the tool system. • Force tool usage: You can use the
tool_choice
parameter to encourage the LLM to invoke specific tools during your session. • Dynamic tool updates: It’s possible to modify the available tools on the fly by using
agent.update_tools()
or
session.update_tools()
. • Event-driven handling: You might find it helpful to use the
function_tools_executed
event to respond to tool calls or even trigger additional actions programmatically. If you’d like, I’m here to walk you through any of these methods in more detail or provide some examples. Just let me know! Sources: Docs::Agents | livekit-plugins/livekit-plugins-google/livekit/plugins/google/realtime/real... | tool_calling/call_function_tool.py
m
No I want AI input fields, Can I trigger the using update chat_context or any workarounds?
t
Thanks for reaching out! Could you please help me understand a bit more about what you mean by "AI input fields"? Are you talking about: • Form inputs that you’d like the AI to fill in or trigger? • User prompt inputs that should be created automatically? • Certain UI elements that need to be turned on or activated? • Fields related to input validation or processing? Getting a clearer picture of your specific needs will really help me guide you to the best solution using LiveKit’s features. Looking forward to your reply! Sources: livekit-plugins/livekit-plugins-google/livekit/plugins/google/realtime/real... | Agent Session & Client Integration | livekit/livekit_composite | DeepWiki | Real-time AI Models & Streaming | livekit/livekit_composite | DeepWiki | Agents v0.x migration guide - Node.js | LiveKit Docs
m
async def on_exit(self): """Called when the agent session ends.""" self._chat_ctx.add_message( role="assistant", content="Please end the call now " ) import asyncio await asyncio.sleep(2) logger.info(f"{"->"*10} Agent Exited... {"->"*10}") @function_tool async def end_call(self, ctx: RunContext, call_summary: Annotated[str, Field(description="The detailed summary of the each question asked and answerd by the user")], sentiment_score: Annotated[str, Field(description="Based on the conversation and give a sentiment score how much caller satisfied [Positive,Negative,Neutral]")], caller_name: Annotated[str, Field(description="Name of the caller if provided otherwise use `not-provided`")],): """Called when the user wants to end the call""" logger.info(f"ending the call.....") Does this triger the function tool?
t
Thanks for reaching out with your question! When you add a message to the chat context in the
on_exit
method, it doesn't automatically trigger a
function_tool
. Usually, tool execution in LiveKit happens during active conversation turns and LLM inference, rather than from changes made to the chat context outside of those active moments. If you're looking to trigger a tool right when the session ends, a good approach might be to explicitly call the tool logic inside the
on_exit
method or handle it during an active turn, like in
on_user_turn_completed
. I'm here to help if you'd like some more detailed guidance on how to set this up! Sources: tests/test_agent_session.py
m
I want to automatically log the call summary and sentiment score when a call ends — either because the user explicitly says “end the call” (which already works using my
end_call
function tool) or when the user unexpectedly disconnects or interrupts the session. What is the best way to detect these unexpected disconnections in a LiveKit Agent and trigger a cleanup or logging function (e.g., saving call summary and sentiment analysis) when that happens?
t
I’m glad you reached out! To help you detect unexpected disconnections or session interruptions in a LiveKit Agent and smoothly trigger cleanup or logging functions, here are a few friendly tips you can follow: • Listen for the
close
event:
This event fires when the session ends—whether it’s because the user left, an error occurred, or there was a disconnection. It’s a great spot to handle any cleanup or logging you might need. • Handle the
error
event:
This captures any errors during the session, including ones that can’t be recovered from. You can log important details here and prepare for cleanup. • Use shutdown hooks: By registering a shutdown callback with
ctx.add_shutdown_callback
, you can make sure final cleanup tasks—like saving call summaries, sentiment scores, or freeing up resources—are done right after the session ends. Here’s a simple example of how you might use the
close
event:
Copy code
@session.on("close")
def on_close(event):
    if event.error:
        logger.error(f"Session closed due to error: {event.error}")
        # Trigger error-specific cleanup
    else:
        logger.info("Session closed normally")
        # Trigger normal cleanup
And for wrapping things up nicely, you can add a shutdown hook like this:
Copy code
async def entrypoint(ctx):
    ctx.add_shutdown_callback(on_shutdown)

async def on_shutdown():
    logger.info("Performing cleanup operations...")
    # Save session data, close connections, etc.
If you’d like, I’m here to help you with more details or guide you through implementing this step-by-step. Just let me know! Sources: Events and error handling | LiveKit Docs | livekit-agents/livekit/agents/worker.py | Job lifecycle | LiveKit Docs | Operational Guidance & Best Practices | livekit/livekit_composite | DeepWik... | Node.js Agents Architecture | livekit/livekit_composite | DeepWiki