handsome-manchester-97799
07/28/2025, 6:38 AMtall-airline-16756
07/28/2025, 6:38 AMtall-airline-16756
07/28/2025, 6:39 AM@function_tool decorator to define tools within your Agent class. For example:
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 Docshandsome-manchester-97799
07/28/2025, 6:41 AMtall-airline-16756
07/28/2025, 6:42 AMimport 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:
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:
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 Docshandsome-manchester-97799
07/28/2025, 6:44 AMtall-airline-16756
07/28/2025, 6:47 AMhandsome-manchester-97799
07/28/2025, 6:47 AM