How to configure function tool in version v1?, and...
# ask-ai
h
How to configure function tool in version v1?, and how it works
t
Thanks for reaching out, Bhakti. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To configure the function tool in version v1 and understand how it works, follow these steps: Basic Configuration: • Use the
@function_tool
decorator to define tools within your Agent class. For example:
Copy code
from livekit.agents import function_tool, Agent, RunContext

class MyAgent(Agent):
    @function_tool()
    async def lookup_weather(
        self,
        context: RunContext,
        location: str,
    ) -> dict[str, Any]:
        """Look up weather information for a given location.

        Args:
            location: The location to look up weather information for.
        """
        return {"weather": "sunny", "temperature_f": 70}
How It Works: • Automatic LLM Access: Tools defined with
@function_tool
are automatically accessible to the LLM. • Tool Definition Components: The tool name defaults to the function name but can be overridden. Descriptions are extracted from the docstring or set manually. Arguments are inferred from the function signature. • RunContext Parameter: Provides access to the current session, function call, speech handle, and user data. • Return Value Handling: The return value is converted to a string and sent to the LLM. Returning
None
completes the tool silently. Advanced Configuration Options: • Adding Tools Dynamically: Update tools after agent creation using the
tools
argument. • Creating Tools Programmatically: Use
function_tool
as a function instead of a decorator. • Raw Schema Support: Create tools directly from raw function calling schemas for advanced use cases. Key Changes from v0.x: • The
@llm.ai_callable
decorator was replaced with
@function_tool
. • Functions defined with
@function_tool
are automatically accessible to the LLM. • Argument types are inferred from the function signature and docstring. • Functions now take a
RunContext
object for accessing the current agent state. This streamlined approach simplifies adding and maintaining agent tools in v1. Sources: Tool definition and use | LiveKit Docs | Agents v0.x migration guide | LiveKit Docs
h
can you give example for current_date_time and web tool(search realtime from web), function tool example?
t
Hey there! Let me walk you through some cool ways to add awesome tools to your LiveKit v1 agent that'll make it super helpful and interactive. 😊 I'll show you how to create two handy function tools that can grab the current time and search the web - perfect for making your agent feel more like a friendly assistant! 1. Current Date/Time Tool Example:
Copy code
import datetime
from livekit.agents import function_tool

@function_tool
async def get_current_datetime(output_format: str = None) -> str:
    """Get the current date and time in the given format.

    Args:
        output_format: formatting string for the date and time, defaults to '%Y-%m-%d %H:%M:%S'
    """
    return datetime.datetime.now().strftime(output_format or "%Y-%m-%d %H:%M:%S")
2. Web Search Tool Example:
Copy code
import asyncio
from typing import Any
from ddgs import DDGS
from livekit.agents import function_tool, ToolError

@function_tool
async def search_web(query: str, max_results: int = 1) -> dict[str, Any]:
    """
    Search the web using DuckDuckGo search engine for information about a given query.

    Args:
        query (str): The query to search for.
        max_results (int): The maximum number of results to return.

    Returns:
        dict[str, Any]: A dictionary containing the search results.
        The keys are the index of the result and the values are another dictionary with the following keys:
        - title: Title of the result.
        - url: URL of the result.
        - body: Body of the result.
    """
    try:
        g = DDGS()
        results = g.text(query, max_results=max_results)
    except Exception as e:
        return ToolError(f"Error searching the web: {e}")
    
    d = {str(i): res for i, res in enumerate(results)}
    for v in d.values():
        v["url"] = v.pop("href")
    return d
3. Complete Agent Implementation:
Copy code
import asyncio
import datetime
from dataclasses import dataclass
from typing import Any
from ddgs import DDGS
from dotenv import load_dotenv

from livekit.agents import (
    Agent,
    AgentSession,
    JobContext,
    RunContext,
    ToolError,
    WorkerOptions,
    cli,
    function_tool,
)
from livekit.plugins import openai

load_dotenv()

@dataclass
class AppData:
    ddgs_client: DDGS

class MyAgent(Agent):
    def __init__(self):
        super().__init__(
            instructions="You are a helpful assistant with access to current time and web search capabilities."
        )

    @function_tool
    async def get_current_datetime(self, output_format: str = None) -> str:
        """Get the current date and time in the given format.

        Args:
            output_format: formatting string for the date and time, defaults to '%Y-%m-%d %H:%M:%S'
        """
        return datetime.datetime.now().strftime(output_format or "%Y-%m-%d %H:%M:%S")

    @function_tool
    async def search_web(self, ctx: RunContext[AppData], query: str) -> dict[str, Any]:
        """
        Performs a web search using the DuckDuckGo search engine.

        Args:
            query: The search term or question you want to look up online.
        """
        ddgs_client = ctx.userdata.ddgs_client
        
        # using asyncio.to_thread because the DDGS client is not asyncio compatible
        search = await asyncio.to_thread(ddgs_client.text, query)
        if len(search) == 0:
            raise ToolError("Tell the user that no results were found for the query.")

        return search

async def entrypoint(ctx: JobContext):
    app_data = AppData(ddgs_client=DDGS())
    
    agent = MyAgent()
    session = AgentSession(llm=openai.realtime.RealtimeModel(), userdata=app_data)

    await session.start(agent=agent, room=ctx.room)

if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
Usage Examples: • "What's the current date and time?" • "Search for the latest news about AI." • "Get me the current time and search for weather information." These tools are like magic - they're automatically available to your LLM when you use the
@function_tool
decorator. It's super easy to make your agent more helpful and interactive! 🚀 Sources: models/templates/meetkai-functionary-medium-v3.1.jinja | examples/frontdesk/frontdesk_agent.py | Tool definition and use | LiveKit Docs
h
so do I need to pass that function tool while start session or It call automatically , and can you provide websearch using serp api
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
h
web search using serp api function tool, give example of it