limited-fireman-90737
10/16/2025, 4:42 PMtall-airline-16756
10/16/2025, 4:42 PMtall-airline-16756
10/16/2025, 4:43 PM@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:
@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:
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.tslimited-fireman-90737
10/16/2025, 4:46 PMBVCTelephony 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))tall-airline-16756
10/16/2025, 4:48 PM@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:
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:
@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:
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:
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.pylimited-fireman-90737
10/16/2025, 5:00 PMtall-airline-16756
10/16/2025, 5:00 PMmodel = openai.realtime.RealtimeModel(
voice="coral",
modalities=["audio", "text"]
)
2. Create and Start the Agent:
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:
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 Modelslimited-fireman-90737
10/16/2025, 5:03 PMtall-airline-16756
10/16/2025, 5:03 PMimport 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!limited-fireman-90737
10/16/2025, 5:05 PMtall-airline-16756
10/16/2025, 5:06 PMimport 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!limited-fireman-90737
10/16/2025, 5:08 PMtall-airline-16756
10/16/2025, 5:09 PMregister_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:
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.tslimited-fireman-90737
10/16/2025, 5:11 PMtall-airline-16756
10/16/2025, 5:12 PMprint 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:
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!