How to call a tool using openai real tile
# ask-ai
l
How to call a tool using openai real tile
t
Thanks for reaching out, Reda. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm happy to help you get started with calling a tool using OpenAI Realtime in LiveKit! To do this, you'll want to define your tools using the
@function_tool
decorator and include them in an agent class. The great thing is that the OpenAI Realtime API will automatically figure out when to call the right tool based on the conversation context. Here’s a simple example to show you how to define a tool:
Copy code
@function_tool
async def add_numbers(self, context: RunContext, a: float, b: float):
    """Return the sum of two numbers."""
    return str(a + b)
To get tool calling up and running, you just need to configure your agent with the OpenAI Realtime model like this:
Copy code
class ToolCallingAgent(Agent):
    def __init__(self):
        super().__init__(
            instructions="You are a helpful assistant...",
            llm="openai/gpt-4.1-mini"  # Enables OpenAI Realtime
        )
If you're interested, I can also share some more advanced examples, like creating tools for weather lookups or controlling smart devices. Just let me know, and I’ll be happy to guide you through it! Sources: tools/server/README.md | realtime-agents/openai-realtime-tools.py | examples/voice_agents/raw_function_description.py | examples/src/realtime_agent.ts
l
debug my code : import json import math from dotenv import load_dotenv from livekit import agents from livekit.agents import AgentSession, Agent, RoomInputOptions, function_tool, RunContext from livekit.plugins import ( openai, noise_cancellation, ) from tools.tools import calculate_finance_metrics load_dotenv(".env.local") with open("./prompts/try.md", "r", encoding="utf-8") as f: SYSTEM_PROMPT_BASE = f.read() class Assistant(Agent): def __init__(self) -> None: super().__init__(instructions=SYSTEM_PROMPT_BASE) @function_tool def calculate_finance_metrics( _lang_: str, _age_: int, _profession_: str, _netMonthlySalary_: int, _monthlyCommissions_: int, _annualBonuses_: int, _rentalIncome_: int, _loans_: list, ) -> dict: """ Calculate client financial KPIs such as max borrow and endettement rate. Args: lang: The client's preferred language (e.g., 'en', 'fr'). age: The client's current age in years. profession: The client's profession type, either 'civil employee' or other. netMonthlySalary: The client's net monthly salary. monthlyCommissions: The client's monthly commissions. annualBonuses: The client's annual bonuses. rentalIncome: The client's monthly rental income. loans: A list of the client's existing loans, where each loan is an object containing at least the 'monthlyInstallment'. Example: [{\"monthlyInstallment\": 500}] """ client_KPIs = { "maxDuration": 0, "maxBorrow": 0, "echMax": 0, "taux_end": 0, } MAX_AGE = 72 annual_rate = 0.055 monthly_rate = annual_rate / 12 max_duration = min(MAX_AGE - age, 25) * 12 if profession == "civil employee": max_endett = 0.5 else: max_endett = 0.45 sumLoans = sum(l["monthlyInstallment"] for l in loans) if loans else 0 revenu = ( (netMonthlySalary or 0) + (monthlyCommissions or 0) + (annualBonuses or 0) / 12 + (rentalIncome or 0) ) ech_max = math.floor((revenu * max_endett) - sumLoans) taux_end = max_endett * 100 if monthly_rate > 0: max_borrow = math.floor( (ech_max * (1 - math.pow(1 + monthly_rate, -max_duration))) / monthly_rate ) else: max_borrow = math.floor(ech_max * max_duration) client_KPIs = { "maxDuration": max_duration, "maxBorrow": max_borrow, "echMax": ech_max, "taux_end": taux_end, } print(client_KPIs) return {"client_KPIs": client_KPIs} self.register_function(calculate_finance_metrics) async def entrypoint(_ctx_: agents.JobContext): session = AgentSession( llm=openai.realtime.RealtimeModel( voice="coral", temperature=0.0, modalities=["audio", "text"] ), tts="cartesia/sonic-2" ) await session.start( room=ctx.room, agent=Assistant(), _room_input_options_=RoomInputOptions( # For telephony applications, use
BVCTelephony
instead for best results
_noise_cancellation_=noise_cancellation.BVC(), ), ) await session.generate_reply( instructions="Greet the client once in Moroccan Darija." ) if name == "__main__": agents.cli.run_app(agents.WorkerOptions(_entrypoint_fnc_=entrypoint))
t
I'd love to help you debug your code! Here are some friendly steps and strategies to guide you through the process: 1. Event Monitoring Try using event listeners to keep an eye on tool execution and agent state changes. For example:
Copy code
@session.on("function_tools_executed")
def on_function_tools_executed(ev):
    for fnc in ev.function_calls:
        print(f"Tool executed: {fnc.name}")
        print(f"Arguments: {fnc.arguments}")

@session.on("agent_state_changed")
def on_agent_state_changed(ev):
    print(f"State transition: {ev.old_state} → {ev.new_state}")
2. Testing Patterns It’s helpful to simulate scenarios using fake components like this:
Copy code
actions = FakeActions()
actions.add_user_speech(0.5, 2.5, "What’s the weather?")
session = create_session(actions)
agent = MyAgent()
3. Tool Debugging Make sure your tools return structured outputs and gracefully handle errors. Here’s a little example:
Copy code
@function_tool
def calculate_finance_metrics(...):
    try:
        # Your logic here
        return {"client_KPIs": client_KPIs}
    except Exception as e:
        return {"error": str(e)}
4. Chat Context Inspection After running your tools, it’s a good idea to check the chat context like this:
Copy code
chat_ctx_items = agent.chat_ctx.items
assert chat_ctx_items[3].type == "function_call"
5. Dynamic Tool Updates You can also add tools on the fly for testing purposes:
Copy code
await agent.update_tools(agent.tools + [new_tool])
If you’d like, I’m here to walk you through any specific part of your code—just let me know! Sources: livekit-agents/livekit/agents/voice/generation.py | basics/say_in_voice.py | agents/src/voice/agent_activity.ts | agent.py
l
I want to share the result with the user using realtime model llm=openai.realtime.RealtimeModel( voice="coral",
t
I'm happy to help you share results with the user using the OpenAI RealtimeModel in LiveKit! This model has wonderful built-in real-time streaming features for both text and audio output. Let me walk you through how to set it up: 1. Configure the RealtimeModel:
Copy code
model = openai.realtime.RealtimeModel(
    voice="coral",
    modalities=["audio", "text"]
)
2. Create and Start the Agent:
Copy code
assistant = Agent(llm=model, tools=[...])
await assistant.start(ctx.room, participant)
3. Generate and Share Responses: The RealtimeModel will automatically stream responses back to the user through: • Text Channel: This provides real-time text output, perfect for displaying transcripts. • Audio Channel: Streams spoken responses using the voice you’ve set. 4. Enable Turn Detection: If you'd like the responses to trigger automatically when the user stops speaking, you can set up turn detection like this:
Copy code
model = openai.realtime.RealtimeModel(
    turn_detection={"type": "server_vad"}
)
Please feel free to reach out if you'd like me to walk you through more examples or if you have any questions along the way—I’m here to help! Sources: OpenAI Realtime API plugin guide | LiveKit Docs | plugins/openai/src/realtime/realtime_model.ts | moviefone/agent.py | examples/voice_agents/web_search.py | Using the Testing Framework with Realtime Models
l
gimme the full code pls
t
I'm excited to share a complete example of how you can set up an agent using the OpenAI RealtimeModel to share results with your users in real time:
Copy code
import asyncio
from livekit import agents
from livekit.agents import AgentSession, Agent, RoomInputOptions
from livekit.plugins import openai, noise_cancellation

class Assistant(Agent):
    def __init__(self):
        super().__init__(
            instructions="You are a helpful assistant who provides real-time responses."
        )

async def entrypoint(ctx: agents.JobContext):
    # Configure the RealtimeModel
    model = openai.realtime.RealtimeModel(
        voice="coral",
        modalities=["audio", "text"],
        turn_detection={"type": "server_vad"}  # Enables automatic response triggering
    )

    # Create an agent session
    session = AgentSession(
        llm=model,
        tts="cartesia/sonic-2"
    )

    # Start the session
    await session.start(
        room=ctx.room,
        agent=Assistant(),
        room_input_options=RoomInputOptions(
            noise_cancellation=noise_cancellation.BVC()
        )
    )

    # Generate a response
    await session.generate_reply(
        instructions="Greet the user and ask how you can assist them."
    )

if __name__ == "__main__":
    agents.cli.run_app(agents.WorkerOptions(entrypoint_fnc=entrypoint))
This setup allows your agent to stream both text and audio responses seamlessly. If you'd like, I’m here to help with any tweaks or additional features you might want to add—just let me know!
l
where's the tool integration
t
Here is the updated full code example with tool integration included:
Copy code
import asyncio
from livekit import agents
from livekit.agents import AgentSession, Agent, RoomInputOptions, function_tool, RunContext
from livekit.plugins import openai, noise_cancellation

class Assistant(Agent):
    def __init__(self):
        super().__init__(
            instructions="You are a helpful assistant who provides real-time responses."
        )

        # Define a tool
        @function_tool
        async def calculate_finance_metrics(
            lang: str,
            age: int,
            profession: str,
            netMonthlySalary: int,
            monthlyCommissions: int,
            annualBonuses: int,
            rentalIncome: int,
            loans: list
        ) -> dict:
            """
            Calculate client financial KPIs such as max borrow and endettement rate.
            """
            MAX_AGE = 72
            annual_rate = 0.055
            monthly_rate = annual_rate / 12

            max_duration = min(MAX_AGE - age, 25) * 12
            max_endett = 0.5 if profession == "civil employee" else 0.45

            sumLoans = sum(l["monthlyInstallment"] for l in loans) if loans else 0
            revenu = (
                (netMonthlySalary or 0)
                + (monthlyCommissions or 0)
                + (annualBonuses or 0) / 12
                + (rentalIncome or 0)
            )

            ech_max = (revenu * max_endett) - sumLoans
            taux_end = max_endett * 100

            if monthly_rate > 0:
                max_borrow = (ech_max * (1 - (1 + monthly_rate) ** -max_duration)) / monthly_rate
            else:
                max_borrow = ech_max * max_duration

            client_KPIs = {
                "maxDuration": max_duration,
                "maxBorrow": max_borrow,
                "echMax": ech_max,
                "taux_end": taux_end,
            }

            return {"client_KPIs": client_KPIs}

        # Register the tool
        self.register_function(calculate_finance_metrics)

async def entrypoint(ctx: agents.JobContext):
    # Configure the RealtimeModel
    model = openai.realtime.RealtimeModel(
        voice="coral",
        modalities=["audio", "text"],
        turn_detection={"type": "server_vad"}  # Enables automatic response triggering
    )

    # Create an agent session
    session = AgentSession(
        llm=model,
        tts="cartesia/sonic-2"
    )

    # Start the session
    await session.start(
        room=ctx.room,
        agent=Assistant(),
        room_input_options=RoomInputOptions(
            noise_cancellation=noise_cancellation.BVC()
        )
    )

    # Generate a response
    await session.generate_reply(
        instructions="Greet the user and ask how you can assist them."
    )

if __name__ == "__main__":
    agents.cli.run_app(agents.WorkerOptions(entrypoint_fnc=entrypoint))
I've included a handy tool called
calculate_finance_metrics
that calculates some key financial KPIs for your clients. This tool is registered with the agent and can be called dynamically during the session to provide real-time insights. Please feel free to reach out if you'd like me to help with any tweaks or further explanations—I'm here to support you!
l
'Assistant' object has no attribute 'register_function'
t
Thanks for reaching out! The error you're seeing happens because the
register_function
method isn’t actually part of the LiveKit Agent API. Instead, the best way to register tools is by using the
@function_tool
decorator directly inside the agent class. I’ve put together the corrected code for you below:
Copy code
import asyncio
from livekit import agents
from livekit.agents import AgentSession, Agent, RoomInputOptions, function_tool, RunContext
from livekit.plugins import openai, noise_cancellation

class Assistant(Agent):
    def __init__(self):
        super().__init__(
            instructions="You are a helpful assistant who provides real-time responses."
        )

        # Define a tool using the @function_tool decorator
        @function_tool
        async def calculate_finance_metrics(
            lang: str,
            age: int,
            profession: str,
            netMonthlySalary: int,
            monthlyCommissions: int,
            annualBonuses: int,
            rentalIncome: int,
            loans: list
        ) -> dict:
            """
            Calculate client financial KPIs such as max borrow and endettement rate.
            """
            MAX_AGE = 72
            annual_rate = 0.055
            monthly_rate = annual_rate / 12

            max_duration = min(MAX_AGE - age, 25) * 12
            max_endett = 0.5 if profession == "civil employee" else 0.45

            sumLoans = sum(l["monthlyInstallment"] for l in loans) if loans else 0
            revenu = (
                (netMonthlySalary or 0)
                + (monthlyCommissions or 0)
                + (annualBonuses or 0) / 12
                + (rentalIncome or 0)
            )

            ech_max = (revenu * max_endett) - sumLoans
            taux_end = max_endett * 100

            if monthly_rate > 0:
                max_borrow = (ech_max * (1 - (1 + monthly_rate) ** -max_duration)) / monthly_rate
            else:
                max_borrow = ech_max * max_duration

            client_KPIs = {
                "maxDuration": max_duration,
                "maxBorrow": max_borrow,
                "echMax": ech_max,
                "taux_end": taux_end,
            }

            return {"client_KPIs": client_KPIs}

async def entrypoint(ctx: agents.JobContext):
    # Configure the RealtimeModel
    model = openai.realtime.RealtimeModel(
        voice="coral",
        modalities=["audio", "text"],
        turn_detection={"type": "server_vad"}  # Enables automatic response triggering
    )

    # Create an agent session
    session = AgentSession(
        llm=model,
        tts="cartesia/sonic-2"
    )

    # Start the session
    await session.start(
        room=ctx.room,
        agent=Assistant(),
        room_input_options=RoomInputOptions(
            noise_cancellation=noise_cancellation.BVC()
        )
    )

    # Generate a response
    await session.generate_reply(
        instructions="Greet the user and ask how you can assist them."
    )

if __name__ == "__main__":
    agents.cli.run_app(agents.WorkerOptions(entrypoint_fnc=entrypoint))
So, in this updated version, the tool gets defined and registered using the
@function_tool
decorator, which is the right way to integrate tools with LiveKit. If you run into any other questions or need further help, please don’t hesitate to ask—I’m here for you! Sources: Tool definition and use | LiveKit Docs | mcp_client/agent_tools.py | examples/voice_agents/realtime_joke_teller.py | docs/index.yaml | agents/src/llm/tool_context.ts
l
I want to see the tool result in logs
t
To help you log the tool's result, you can use the
print
function or a logging library right within the tool's implementation. Let me show you how you can tweak the tool to log its result:
Copy code
import logging

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class Assistant(Agent):
    def __init__(self):
        super().__init__(
            instructions="You are a helpful assistant who provides real-time responses."
        )

        @function_tool
        async def calculate_finance_metrics(
            lang: str,
            age: int,
            profession: str,
            netMonthlySalary: int,
            monthlyCommissions: int,
            annualBonuses: int,
            rentalIncome: int,
            loans: list
        ) -> dict:
            """
            Calculate client financial KPIs such as max borrow and endettement rate.
            """
            MAX_AGE = 72
            annual_rate = 0.055
            monthly_rate = annual_rate / 12

            max_duration = min(MAX_AGE - age, 25) * 12
            max_endett = 0.5 if profession == "civil employee" else 0.45

            sumLoans = sum(l["monthlyInstallment"] for l in loans) if loans else 0
            revenu = (
                (netMonthlySalary or 0)
                + (monthlyCommissions or 0)
                + (annualBonuses or 0) / 12
                + (rentalIncome or 0)
            )

            ech_max = (revenu * max_endett) - sumLoans
            taux_end = max_endett * 100

            if monthly_rate > 0:
                max_borrow = (ech_max * (1 - (1 + monthly_rate) ** -max_duration)) / monthly_rate
            else:
                max_borrow = ech_max * max_duration

            client_KPIs = {
                "maxDuration": max_duration,
                "maxBorrow": max_borrow,
                "echMax": ech_max,
                "taux_end": taux_end,
            }

            # Log the result
            logger.info(f"Tool Result: {client_KPIs}")

            return {"client_KPIs": client_KPIs}
Here, the tool uses Python's
logging
module to log the calculated financial KPIs. You can easily check these logs in your console, or if you prefer, set up the logger to save them to a file for later reference. If you have any questions or need a hand with this, just let me know—I'm here to help!