How to add dynamic instructions to the agent to st...
# ask-ai
p
How to add dynamic instructions to the agent to steer the whole session to a direction. I have my own impl of llm_node. Not able to call generate_reply() or say() inside llm_node.
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.
Hey there! When you want to dynamically steer a session in LiveKit using your
llm_node
implementation, it’s important to know that you can’t call
generate_reply()
or
say()
directly inside
llm_node
. These methods are meant for session-level control and work best in lifecycle hooks or function tools. Here are some friendly tips on how to approach this: • Use `update_instructions()`: You can tweak the agent’s behavior on the fly by updating its system instructions. For example, in lifecycle hooks like
on_enter
or
on_user_turn_completed
, feel free to adjust instructions based on what’s happening or what the user says. • Initiate Speech: If you want to start or steer conversations, use
session.generate_reply()
or
session.say()
inside lifecycle hooks or tools. • Modify LLM Output: Inside
llm_node
, you’ve got the option to process and tweak the LLM’s output stream in real time—like fixing grammar or making sure responses follow a certain structure. • Add Dynamic Tools: You can also temporarily add tools right in
llm_node
or through
update_tools()
to give your agent some extra powers for specific turns. If any of this feels unclear or you want some examples, just give me a shout—I’m happy to help! Sources: tests/test_agent_session.py | Tool definition and use | LiveKit Docs | Pipeline nodes and hooks | LiveKit Docs | Agent speech and audio | LiveKit Docs | basics/change_agent_instructions.py
p
Here is my usecase, There are some tools defined, some of them should be used the llm, but the rest should only be used if manually specified to make a tool call by adding a chunk.
t
Hey there! If you want to control tool usage in LiveKit so that some tools are handled by the LLM and others are specified manually, here are a few friendly tips to help you out: • Use `tool_choice`: You can set up the LLM to use only certain tools by configuring
tool_choice
. For example, you might want the LLM to use just one tool like
get_weather
and skip the rest. • Dynamically Register Tools: Try using
update_tools()
to manage your tools on the fly. Maybe start with only the tools the LLM can use, then add manual-only tools later when needed. • Define Manual-Only Tools: Keep some tools completely separate from the LLM’s context and call them directly in your app. These won’t have the
@function_tool
decorator and are meant to be used manually. • Mix LLM-Controlled and Manual Tools: Feel free to combine these methods! Let the LLM use some tools automatically while saving others for manual control. For instance, you can add tools dynamically to the agent’s toolkit or pause the LLM’s tool usage by setting
tool_choice='none'
. If you want me to walk you through specific examples or if anything’s unclear, just give me a shout—I’m here to help! Sources: xAI LLM integration guide | LiveKit Docs | Together AI LLM integration guide | LiveKit Docs | Fireworks AI LLM integration guide | LiveKit Docs | Perplexity LLM integration guide | LiveKit Docs | Telnyx LLM integration guide | LiveKit Docs
p
give examples
t
Here are some examples to help you get a feel for how to control tool usage in LiveKit: 1. Restricting LLM to Specific Tools If you want the LLM to use just one specific tool, you can set the
tool_choice
parameter like this:
Copy code
from livekit.agents import llm

# Restrict LLM to use only the 'get_weather' tool
tool_choice = llm.ToolChoice(type="function", name="get_weather")
This way, even if you have other tools registered, the LLM will only consider
get_weather
when it’s deciding what to do next. 2. Dynamically Registering Tools If you need to manage tools on the fly,
update_tools()
is your friend:
Copy code
# Initially register only the tools the LLM can use
await agent.update_tools([get_weather_tool])

# Later on, add tools meant for manual use (like after someone logs in)
await agent.update_tools([get_weather_tool, send_email_tool])
In this setup,
send_email_tool
won’t be available to the LLM until you explicitly add it. 3. Manual-Only Tools Sometimes, you’ll want tools that the LLM doesn’t touch at all and that you call directly in your app logic:
Copy code
# This one isn’t exposed to the LLM
async def send_notification(message: str):
    print(f"Notification: {message}")

# You call this manually when needed
await send_notification("User request completed.")
This keeps things nice and clear between what the LLM can automate and what you handle yourself. 4. Mixed Usage Example Here’s a full example that mixes LLM-controlled and manual tools:
Copy code
from livekit.agents import function_tool, Agent

@function_tool()
async def get_weather(location: str) -> dict:
    """Get current weather for a location."""
    return {"weather": "sunny", "temp": 75}

class MyAgent(Agent):
    def __init__(self):
        super().__init__(
            instructions="You are a helpful assistant.",
            tools=[get_weather],  # Only the tool LLM can use
        )

    async def on_user_transfer_completed(self, info):
        # After handoff, add a tool available only to the next agent manually
        await info.destination.update_tools(
            info.destination.tools + [manual_tool]
        )

# Define a tool used only manually
@function_tool()
async def send_confirmation_email(user_id: str):
    """Send a confirmation email to the user."""
    return {"status": "sent"}

# Use it in your workflow logic
await agent.update_tools(agent.tools + [send_confirmation_email])
So in this example: • The LLM starts off with access only to
get_weather
. •
send_confirmation_email
gets added later and is meant to be called manually. If you have any questions or want me to walk you through more examples, just let me know—I’m happy to help!
p
await agent.update_tools(agent.tools + [send_confirmation_email]) , where is the agent object created? can this be called from inside the llm_node?
t
So, the
agent
object is created by instantiating a class that inherits from the
Agent
class. Here’s a quick example to make it clearer:
Copy code
@function_tool()
async def lookup_weather(location: str) -> dict:
    """Look up weather information for a given location."""
    return {"weather": "sunny", "temperature_f": 70}

agent = MyAgent(
    instructions="You are a helpful assistant.",
    tools=[lookup_weather],
)
And if you want to add tools after the agent has already been created, you can do that easily with `update_tools()`:
Copy code
async def _random_number() -> int:
    num = random.randint(0, 100)
    return num

await agent.update_tools(
    agent.tools + [function_tool(_random_number, name="random_number", description="Get a random number")]
)
About your second question, yes! You can call
update_tools()
from inside
llm_node
. This means you can dynamically change the tools during the LLM processing. Here’s an example:
Copy code
async def llm_node(self, chat_ctx, tools, model_settings):
    async def _get_weather(location: str) -> str:
        return f"The weather in {location} is sunny."

    # Add a temporary tool just for this call
    tools.append(
        function_tool(
            _get_weather,
            name="get_weather",
            description="Get the weather in a specific location",
        )
    )

    return Agent.default.llm_node(self, chat_ctx, tools, model_settings)
Or, if you want to update the agent’s tools permanently within
llm_node
, you can do this:
Copy code
await self.update_tools(self.tools + [new_tool])
If anything’s unclear or you’d like me to walk through more examples, just let me know—I’m here to help! Sources: livekit-agents/livekit/agents/llm/tool_context.py | Agents 0.x migration guide | LiveKit Docs
p
how to make an explicit tool call inside llm node with above approach i.e adding a new tool, using it and removing it?
t
If you want to make an explicit tool call inside
llm_node
by dynamically adding, using, and then removing a tool, here’s a friendly way to do it: 1. Add the Tool: Just append the tool to the
tools
list within
llm_node
when you need it. 2. Use the Tool: Call the tool’s function directly with whatever parameters you need. 3. Remove the Tool: Once you’re done, take it out of the
tools
list so it won’t be used in later LLM calls. Here’s a little example to make it clearer:
Copy code
async def llm_node(self, chat_ctx, tools, model_settings):
    # Define a temporary tool
    async def temporary_tool(param: str) -> str:
        return f"Processed: {param}"

    # Add the tool dynamically
    temp_tool = function_tool(
        temporary_tool,
        name="temporary_tool",
        description="A tool for temporary use."
    )
    tools.append(temp_tool)

    # Use the tool explicitly
    result = await temp_tool.func("example input")
    print(f"Tool result: {result}")

    # Remove the tool after use
    tools.remove(temp_tool)

    # Continue with the default LLM processing
    async for chunk in Agent.default.llm_node(self, chat_ctx, tools, model_settings):
        yield chunk
So, what’s happening here? • The
temporary_tool
gets added to the
tools
list just when you need it. • You call it directly with
temp_tool.func()
and pass in your input. • After you’re done, it’s removed from the list to keep things tidy and avoid accidental reuse. This way, your tool is only around when you want it to be, and you have full control over when it’s used inside
llm_node
. Pretty neat, right?
p
there is no func method
t
You're absolutely right—there isn't a
func
method to directly invoke a tool in LiveKit. Tools are designed to be triggered by the LLM when it feels they’re needed based on the flow of the conversation. But if you want to call a tool explicitly, you can simply call the underlying Python function directly instead of going through the tool system. Here’s an updated example to show you how:
Copy code
async def llm_node(self, chat_ctx, tools, model_settings):
    # Define a temporary tool
    async def temporary_tool(param: str) -> str:
        return f"Processed: {param}"

    # Add the tool dynamically
    temp_tool = function_tool(
        temporary_tool,
        name="temporary_tool",
        description="A tool for temporary use."
    )
    tools.append(temp_tool)

    # Explicitly call the underlying function
    result = await temporary_tool("example input")
    print(f"Tool result: {result}")

    # Remove the tool after use
    tools.remove(temp_tool)

    # Continue with the default LLM processing
    async for chunk in Agent.default.llm_node(self, chat_ctx, tools, model_settings):
        yield chunk
In this example, we call the tool’s underlying function (
temporary_tool
) directly with the input it needs. This way, you skip the LLM’s decision-making and make sure the function runs exactly when you want it to. If you’d like me to walk you through it more or need other examples, just let me know—I’m happy to help! Sources: livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/llm.py | tool_calling/update_tools.py | mcp_client/server.py | Tool definition and use | LiveKit Docs