How to create a dynamice tool with parameters usin...
# ask-ai
m
How to create a dynamice tool with parameters using python
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'd love to help you create dynamic tools with parameters in Python for LiveKit! Here are some friendly ways to do it: 1. Create Tools During Agent Initialization: You can define tools dynamically right at startup by pulling in data (like from a database) and using that to build your tool parameters. For example, imagine creating an enum from a list of course names and then defining a Pydantic model for structured input—pretty neat, right? 2. Update Tools at Runtime: If you want to add or tweak tools after your agent is already up and running,
agent.update_tools()
is your friend. This lets you introduce new tools on the fly during execution. 3. Add Temporary Tools in `llm_node`: Sometimes, you might need tools just for a single LLM call. In that case, you can modify the tools list inside the
llm_node
method to make those tools available only when needed—super handy for context-sensitive scenarios. When it comes to parameters, you can define them using Python type hints, Pydantic models, or enums, and the LLM will automatically understand them. If you're curious about more advanced setups, like menu-driven systems, take a look at examples such as the drive-thru ordering system, which uses dynamic tool builders and enum validation. I hope this helps you get started smoothly! Sources: livekit-plugins/livekit-plugins-ultravox/livekit/plugins/ultravox/utils.py | Docs::Agents | Tool definition and use | LiveKit Docs | docs/index.yaml
m
Can you share the sample code for that
t
I'm happy to share some sample code snippets that show how you can create dynamic tools with parameters in Python. Let's walk through them together: • Create Tools During Agent Initialization:
Copy code
from enum import Enum
from pydantic import BaseModel
from livekit import function_tool

# Example: Dynamic Enum from Database
courses = ["Math", "Science", "History"]  # Replace with database call
CourseType = Enum("CourseType", {c.replace(" ", "_"): c for c in courses})

class CourseInfo(BaseModel):
    course: CourseType
    location: str  # e.g., "online" or "in-person"

@function_tool()
async def get_course_info(info: CourseInfo) -> str:
    return f"Course: {info.course}, Location: {info.location}"
• Update Tools at Runtime:
Copy code
import random
from livekit import function_tool

async def random_number() -> int:
    return random.randint(0, 100)

await agent.update_tools(agent.tools + [
    function_tool(random_number, name="random_number", description="Get a random number")
])
• Add Temporary Tools in `llm_node`:
Copy code
from livekit import function_tool, Agent

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."

    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)
If you have any questions or need me to walk you through any part of this, just let me know—I’m here to help!
m
@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.....") This is a sample function tool with three parameters. but no I want add parameters dynamicaly.
t
To help you add parameters dynamically to a function tool, you can take advantage of Python's dynamic features, like creating Pydantic models or using dictionaries for schema definitions. Let me walk you through an example that shows how you can do this:
Copy code
from pydantic import BaseModel, Field
from livekit import function_tool

def create_dynamic_tool(params):
    # Dynamically create a Pydantic model
    fields = {name: (param_type, Field(description=desc)) for name, (param_type, desc) in params.items()}
    DynamicModel = type("DynamicModel", (BaseModel,), fields)

    @function_tool()
    async def dynamic_function(data: DynamicModel):
        return f"Received data: {data.dict()}"

    return dynamic_function

# Example usage
dynamic_params = {
    "call_summary": (str, "The detailed summary of the call"),
    "sentiment_score": (str, "Sentiment score of the call [Positive, Negative, Neutral]"),
    "caller_name": (str, "Name of the caller or 'not-provided'")
}

dynamic_tool = create_dynamic_tool(dynamic_params)
In this example, the
create_dynamic_tool
function creates a Pydantic model on the fly based on the parameters you provide, and then uses it in a function tool. You can easily adjust the
dynamic_params
dictionary to add or remove parameters whenever you need. If you have any questions or want me to help you customize this further, just let me know—I'm here to help!