is there a way to explicitly trigger a tool call i...
# ask-ai
p
is there a way to explicitly trigger a tool call in agent
t
Thanks for reaching out, harish. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
In LiveKit, tools are thoughtfully triggered automatically by the agent's LLM based on what the user inputs and the tool's description. You get to define these tools using decorators like
@function_tool
in Python or
llm.tool()
in TypeScript, and the system takes care of calling them when needed. If you'd like to simulate a tool call yourself, you can use the
generate_reply()
method to create user input that naturally encourages the LLM to invoke the tool you're aiming for. Here’s how you can do it: Python Example:
Copy code
# Simulate user input to trigger a tool
await self.session.generate_reply(instructions="instructions:say goodbye to the user")
TypeScript Example:
Copy code
// Simulate user input to trigger a tool
ctx.session.generateReply({
  userInput: 'Tell user wait a moment for about 10 seconds'
});
Please feel free to reach out if you'd like me to walk you through this further or provide more examples—I'm here to help! Sources: docs/index.yaml | examples/src/comprehensive_test.ts | livekit-agents/livekit/agents/voice/agent_activity.py
p
There is a use case i.e I am using AgentTask, now I want to make a tool call here explicitely irrespective of users input. in the llm_node, I check some conditions, if true, then this tool call has to be made. What can be done here
t
In LiveKit, tool calls within an
AgentTask
are triggered by the LLM based on the chat context and tool descriptions. While you can't directly trigger a tool call programmatically from the
llm_node
, you do have some great ways to gently guide the LLM’s behavior conditionally. Here are a few helpful approaches: 1. Modify Chat Context: You can add dynamic context to the
chat_ctx
to nudge the LLM towards invoking a specific tool. For example:
Copy code
async def llm_node(self, chat_ctx, tools, model_settings):
    if some_runtime_condition():
        chat_ctx.add_message(
            role="system",
            content="The user has requested data lookup; use the lookup_weather tool."
        )
    async for chunk in super().llm_node(chat_ctx, tools, model_settings):
        yield chunk
1. Control Tool Usage: You can tweak the
tool_choice
parameter in
model_settings
to encourage tool usage when certain conditions are met. For example:
Copy code
if should_force_lookup():
    model_settings = model_settings.copy(update={"tool_choice": "required"})
1. Encapsulate Logic in Tools: Another handy way is to build conditional checks right inside the tool function itself, so it only runs when it really should.
Copy code
@function_tool()
async def conditional_action(self, ctx: RunContext):
    if not is_condition_met():
        return "Condition not satisfied; no action taken."
    return do_something()
If any of this feels unclear or if you have a particular scenario you’d like to walk through together, please don’t hesitate to reach out—I’m here to help! Sources: livekit-agents/livekit/agents/voice/generation.py | External data and RAG | LiveKit Docs | Tool definition and use | LiveKit docs | Pipeline nodes and hooks | LiveKit docs | Together AI LLM plugin guide | LiveKit Docs
p
I tried adding a developer message i.e look at below: ChatMessage(id='item_f7197219b04c', type='message', role='developer', content=['\ This phase has been completed. Call the tool ** *complete phase*** to move to the next phase.\ Do not call any other tool. Make sure to call this tool only once.\ '], interrupted=False, transcript_confidence=None, hash=None, created_at=1763047233.861884), ChatMessage(id='item_43b038c23ff8', type='message', role='user', content=['And I also do the i.e hmm uhh.'], interrupted=False, transcript_confidence=1.0, hash=None, created_at=1763047240.42802)]" so here the developer message was added, but the tool was not called, the user starts speaking again after this
t
Thank you for your question! I’d love to help clarify why adding a developer message to the chat context doesn’t automatically trigger a tool call. In LiveKit, tool execution is guided by the LLM’s inference process, not just by adding messages. Here’s a bit more detail to help: 1. Message Addition vs. Inference: When you add a developer message, it updates the chat context, but it doesn’t prompt the LLM to re-evaluate the conversation for tool usage. Tool calls happen during specific inference tasks, like
_pipeline_reply_task
. 2. LLM-Driven Tool Calls: The tool is triggered only when the LLM generates a function call in its response. So, simply adding a developer message won’t create that output. 3. Explicit Workflow Progression: To encourage the agent to consider using a tool after adding a message, you’ll want to explicitly call a reply-generation method such as
generate_reply()
, or make sure a previous tool execution has set
replyRequired = true
. For your situation, a good approach is to call
generate_reply()
right after adding your developer message. This will prompt the LLM to process the updated context and decide if tool usage is needed. If you’d like, I’m here to guide you through this step or answer any other questions you have! Sources: External data and RAG | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_activity.py | agents/src/voice/agent_activity.ts
p
but does generate_reply work inside the llm_node?
t
Absolutely! You can definitely use
generate_reply
inside the
llm_node
in LiveKit. The
llm_node
handles inference and response generation, and
generate_reply
is built to create dynamic responses based on instructions or user input. Since
generate_reply
is supported in tool execution, which is part of the LLM inference flow, it fits perfectly within or alongside the
llm_node
logic. If you'd like, I’m here to help with any further clarification or examples you might need! Sources: Pipeline nodes and hooks | LiveKit docs | Agent speech and audio | LiveKit docs | Tool definition and use | LiveKit docs | livekit-agents/livekit/agents/voice/generation.py
p
1. Control Tool Usage: You can tweak the
tool_choice
parameter in
model_settings
to encourage tool usage when certain conditions are met. For example: `````` how does this work? how is the tool call guarenteed
t
I’d love to help you understand the
tool_choice
parameter in
model_settings
a bit better! When you set it to
"required"
, it really encourages the LLM to prioritize using tools by making sure the output follows the tool call format, rather than just plain text. That said, it’s important to know that this doesn’t always guarantee a tool will be called every single time. Here’s a little breakdown to clarify: 1. Tool Usage Enforcement: Setting
tool_choice
to
"required"
helps the system steer the model away from non-tool responses, so tools get the spotlight. 2. Conditions for Tool Calls: Tools need to be available, and the user’s request should logically call for their use. If there aren’t any registered tools or the request doesn’t really need them, the model might not use tools. 3. Provider-Specific Implementation: Different LLM providers, like AWS Bedrock and Google Gemini, handle this setting in their own way, mapping
"required"
to configurations that encourage tool calls. I hope this helps clear things up! If you want me to walk you through some examples or have any other questions, just let me know—I’m here to help! Sources: Azure OpenAI LLM plugin guide | LiveKit docs | xAI LLM plugin guide | LiveKit Docs | Perplexity LLM plugin guide | LiveKit Docs | Telnyx LLM plugin guide | LiveKit Docs | common/chat.cpp
p
how do I know if a tool call was triggered or not i.e if the llm trigers the tool or not
t
To help you check if a tool call was triggered by the LLM in LiveKit, you can keep an eye on the response stream or take a look at the execution events. Here are some helpful methods you can try: 1. Monitor Streaming Responses: You can use the
chat()
stream to catch tool calls as they happen. Here’s a simple example:
Copy code
async for chunk in llm.chat(chat_ctx=chat_ctx, tools=tools):
    if chunk.delta and chunk.delta.tool_calls:
        for tool_call in chunk.delta.tool_calls:
            print(f"Tool call detected: {tool_call.name} with args: {tool_call.arguments}")
1. Override `llm_node`: Another approach is to customize the
llm_node
method so you can spot and respond to tool calls during inference:
Copy code
async def llm_node(self, chat_ctx, tools, model_settings):
    async for chunk in super().llm_node(chat_ctx, tools, model_settings):
        if chunk.delta and chunk.delta.tool_calls:
            print("Tool call detected")
        yield chunk
1. Inspect Execution Events: After running your session, you can check the
RunResult
events to find any tool calls made:
Copy code
result = await session.run(user_input="What's the weather in Tokyo?")
fnc_call = result.expect.next_event().is_function_call(name="lookup_weather", arguments={"location": "Tokyo"})
If you’d like me to walk you through any of these steps or provide more examples, just let me know—I’m here to help! Sources: livekit-plugins/livekit-plugins-aws/livekit/plugins/aws/experimental/realti... | agent.py | agents/src/inference/llm.ts