I want to add a tool during run time in livekit ag...
# ask-ai
f
I want to add a tool during run time in livekit agent, how to do so ?
t
Thanks for reaching out, Hardaat. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
If you want to add a tool on the fly while using LiveKit Agent, you can easily do that with the
agent.update_tools()
method. This lets you update the agent's available tools without missing a beat. Here’s how you can do it: 1. Appending a New Tool with `agent.update_tools()`: First, grab the current tools using
agent.tools
, then just add your new tool to the list. For example:
Copy code
# Define a new tool
async def _random_number() -> int:
    return random.randint(0, 100)

# Add the tool during runtime
await agent.update_tools(
    agent.tools + [function_tool(_random_number, name="random_number", description="Get a random number")]
)
2. Creating Tools on the Fly: You can use
function_tool()
to build tools dynamically. Here’s a quick example:
Copy code
def _set_profile_field_func_for(self, field: str):
    async def set_value(context: RunContext, value: str):
        return f"field {field} was set to {value}"
    return set_value

# Create specific tools dynamically
phone_tool = function_tool(
    self._set_profile_field_func_for("phone"),
    name="set_phone_number",
    description="Call this function when user has provided their phone number."
)
await agent.update_tools(agent.tools + [phone_tool])
3. Adding Temporary Tools for a Single LLM Call: You can tweak the
llm_node
method to add tools just for that specific call, which is super handy. 4. Bringing in External Tools via MCP: You can also fetch and register tools dynamically from an MCP server to expand your toolkit. Just a heads-up: make sure to include
agent.tools
when you call
update_tools()
so you don’t lose any of your existing tools. If you want to see this in action, check out the LiveKit dynamic tool creation example. It’s a great resource! Sources: tool_calling/update_tools.py | mcp_client/agent_tools.py | Tool definition and use | LiveKit Docs | examples/voice_agents/realtime_joke_teller.py
f
I am getting the following logs when openai is trying to do tool call in livekit:
Copy code
{
    "timestamp": "afdsfadsfd",
    "level": "ERROR",
    "logger": "....agent_framework",
    "message": "LiveKit error in LLM: type='llm_error' timestamp=1757659027.0903554 label='livekit.plugins.openai.llm.LLM' error=APIConnectionError('Connection error.') recoverable=True for call_id fadsfdfas1",
    "source": {
        "function": "_on_error",
        "line": 1009,
        "file": ".../framework.py",
        "module": "framework"
    },
    "runtime": {
        "thread": "MainThread",
        "process": "job_proc"
    },
    "context": {
        "call_id": "afdfadsfsd",
        "agent_id": "afdsfadsfad",
        "user_id": "afdasdsfd"
    }
}
{
    "timestamp": "afdfsd",
    "level": "WARNING",
    "logger": "logging",
    "message": "[livekit.agents] failed to generate LLM completion, retrying in 0.1s",
    "source": {
        "function": "_main_task",
        "line": 195,
        "file": ".../llm.py",
        "module": "llm"
    },
    "runtime": {
        "thread": "MainThread",
        "process": "job_proc"
    },
    "context": {
        "call_id": "dfadsfdsfd",
        "agent_id": "afsdfasdfsdfad",
        "user_id": "afdsfasdfads"
    },
    "attempt": 1,
    "llm": "livekit.plugins.openai.llm.LLM",
    "taskName": "Task-1833",
    "exception": {
        "type": "APIConnectionError",
        "value": "Connection error. (body=None, retryable=True)",
        "traceback": "  File \"/root/.cache/...../llm/llm.py\", line 177, in _main_task\n    return await self._run()\n           ^^^^^^^^^^^^^^^^^\n  File \"...../llm.py\", line 830, in _run\n    raise APIConnectionError(retryable=retryable) from e\n"
    }
}
what can be the reason for this ?
t
I'm sorry to hear you're experiencing the
APIConnectionError
. This usually happens when there are some hiccups in connecting to the OpenAI API. Let’s walk through some common reasons and how we can troubleshoot them together: 1. Connection Timeout: Sometimes the system can’t establish a connection to the OpenAI Realtime API within the expected time. 2. Unexpected WebSocket Closure: If the WebSocket connection closes unexpectedly, this error might pop up. 3. Failed Message Send During Reconnection: When reconnecting, if important messages like
session.update
don’t go through, this error can occur. 4. Generic Network Issues: Network problems such as DNS failures or connection refusals might be causing this. 5. Missing or Incorrect API Key: Double-check that your
OPENAI_API_KEY
is set correctly in your environment or passed properly to the client. Here are a few steps you can try to get things back on track: • Make sure your network connection and firewall settings aren’t blocking access. • Check that the OpenAI API endpoint (
api.openai.com
) is reachable from your setup. • Verify that your API key is accurate and still valid. • Keep an eye on your internet connection stability, especially if you’re relying on persistent WebSocket connections. Please don’t hesitate to reach out if you want me to guide you through any of these steps or if you have any other questions. I’m here to help! Sources: livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/realtime/real... | agents/src/llm/provider_format/openai.test.ts