salmon-rainbow-65629
10/29/2025, 7:17 PMasync def hangup_call():
ctx = get_job_context()
if ctx is None:
# Not running in a job context
return
await ctx.api.room.delete_room(
api.DeleteRoomRequest(
room=ctx.room.name,
)
)
class Assistant(Agent):
def __init__(self) -> None:
super().__init__(
instructions="""You are a helpful voice AI assistant.
If you detect a voicemail system or answering machine (indicated by an automated greeting, beep, or instructions to leave a message):
1. Wait for the beep or end of the greeting
2. Leave a brief, professional voicemail message like: "Hello, I was trying to reach you but it seems you're unavailable. I'll try calling back later. Thank you!"
3. After you finish speaking your voicemail message, immediately call the detected_answering_machine tool to hang up the call."""
)
@function_tool
async def detected_answering_machine(self):
"""Call this tool AFTER you have finished leaving your voicemail message to hang up the call"""
# Hang up after the agent has naturally spoken the voicemail message
await asyncio.sleep(0.5) # Brief pause before hanging up
await hangup_call()tall-airline-16756
10/29/2025, 7:17 PMtall-airline-16756
10/29/2025, 7:18 PM@function_tool decorator within your agent class to get started. Here's a simple step-by-step guide to walk you through it:
1. Define the Function Tool: Just use the @function_tool decorator to create your tool. The function schema is automatically generated from the signature, docstring, and type hints, making it super convenient. For example:
from livekit.agents import Agent, function_tool
class Assistant(Agent):
@function_tool()
async def detected_answering_machine(self):
"""
Call this tool AFTER you have finished leaving your voicemail message to hang up the call.
"""
await asyncio.sleep(0.5) # Brief pause before hanging up
await hangup_call()
1. Set Up Authentication: Make sure your API key is set, either through an environment variable or by passing it directly to the RealtimeModel constructor. Here's how you can do it:
from livekit.plugins.google import RealtimeModel
model = RealtimeModel(
api_key="your-api-key", # Optional if env var is set
model="gemini-2.0-flash-live-001",
)
1. Integrate with RealtimeModel: Pass your function tools to the RealtimeModel through the agent's LLM instance. The tool_behavior parameter lets you control how these tools execute:
realtime_model = RealtimeModel(
model="gemini-2.0-flash-live-001",
tool_behavior="BLOCK", # Tools run synchronously
instructions="You are a helpful assistant. Use tools to assist users."
)
If you're interested in more advanced setups, like using raw JSON schemas or enabling built-in tools such as Google Search, just let me know! I'm here to help you every step of the way.
Sources: Docs::Agents | livekit-agents/livekit/agents/llm/_provider_format/google.py | AI Agents Framework | livekit/livekit_composite | DeepWiki | Gemini Live API plugin | LiveKit Docssalmon-rainbow-65629
10/29/2025, 7:30 PMasync def hangup_call():
ctx = get_job_context()
if ctx is None:
# Not running in a job context
return
await ctx.api.room.delete_room(
api.DeleteRoomRequest(
room=ctx.room.name,
)
)
class Assistant(Agent):
def __init__(self) -> None:
super().__init__(
instructions="""You are a helpful voice AI assistant.
If you detect a voicemail system or answering machine (indicated by an automated greeting, beep, or instructions to leave a message):
1. Wait for the beep or end of the greeting
2. Leave a brief, professional voicemail message like: "Hello, I was trying to reach you but it seems you're unavailable. I'll try calling back later. Thank you!"
3. After you finish speaking your voicemail message, immediately call the detected_answering_machine tool to hang up the call."""
)
@function_tool()
async def detected_answering_machine(self):
"""Call this tool AFTER you have finished leaving your voicemail message to hang up the call"""
# Hang up after the agent has naturally spoken the voicemail message
await asyncio.sleep(0.5) # Brief pause before hanging up
await hangup_call()
return "Voicemail message left, call ended"salmon-rainbow-65629
10/29/2025, 7:31 PM2025-10-29 12:29:39,965 - DEBUG livekit.agents - input stream attached {"participant": null, "source": "SOURCE_UNKNOWN", "accepted_sources": ["SOURCE_MICROPHONE"], "pid": 12617, "job_id": "AJ_7GXAPhEA6kgG"}
/Users/andymendez/Documents/BalboaDigital/Code/AI-Voice-Bot/.venv/lib/python3.12/site-packages/google/genai/_common.py:613: UserWarning: BLOCK is not a valid Behavior
warnings.warn(f'{value} is not a valid {cls.__name__}')
2025-10-29 12:29:40,065 - DEBUG livekit.plugins.google - connecting to Gemini Realtime API... {"pid": 12617, "job_id": "AJ_7GXAPhEA6kgG"}
2025-10-29 12:29:40,565 - ERROR livekit.plugins.google - Gemini Realtime API error: received 1007 (invalid frame payload data) Invalid value at 'setup.tools[0].function_declarations[0].behavior' (type.googleapis.com/google.ai.generativelanguage.v1bet; then sent 1007 (invalid frame payload data) Invalid value at 'setup.tools[0].function_declarations[0].behavior' (type.googleapis.com/google.ai.generativelanguage.v1bet
Traceback (most recent call last):
File "/Users/andymendez/Documents/BalboaDigital/Code/AI-Voice-Bot/.venv/lib/python3.12/site-packages/livekit/plugins/google/realtime/realtime_api.py", line 654, in _main_task
async with self._client.aio.live.connect(
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/contextlib.py", line 210, in __aenter__
return await anext(self.gen)
^^^^^^^^^^^^^^^^^^^^^
File "/Users/andymendez/Documents/BalboaDigital/Code/AI-Voice-Bot/.venv/lib/python3.12/site-packages/google/genai/live.py", line 1075, in connect
raw_response = await ws.recv(decode=False)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/andymendez/Documents/BalboaDigital/Code/AI-Voice-Bot/.venv/lib/python3.12/site-packages/websockets/asyncio/connection.py", line 322, in recv
raise self.protocol.close_exc from self.recv_exc
websockets.exceptions.ConnectionClosedError: received 1007 (invalid frame payload data) Invalid value at 'setup.tools[0].function_declarations[0].behavior' (type.googleapis.com/google.ai.generativelanguage.v1bet; then sent 1007 (invalid frame payload data) Invalid value at 'setup.tools[0].function_declarations[0].behavior' (type.googleapis.com/google.ai.generativelanguage.v1bet {"pid": 12617, "job_id": "AJ_7GXAPhEA6kgG"}
2025-10-29 12:29:40,570 - ERROR livekit.agents - AgentSession is closing due to unrecoverable error
Traceback (most recent call last):
File "/Users/andymendez/Documents/BalboaDigital/Code/AI-Voice-Bot/.venv/lib/python3.12/site-packages/livekit/plugins/google/realtime/realtime_api.py", line 654, in _main_task
async with self._client.aio.live.connect(
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/contextlib.py", line 210, in __aenter__
return await anext(self.gen)
^^^^^^^^^^^^^^^^^^^^^
File "/Users/andymendez/Documents/BalboaDigital/Code/AI-Voice-Bot/.venv/lib/python3.12/site-packages/google/genai/live.py", line 1075, in connect
raw_response = await ws.recv(decode=False)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/andymendez/Documents/BalboaDigital/Code/AI-Voice-Bot/.venv/lib/python3.12/site-packages/websockets/asyncio/connection.py", line 322, in recv
raise self.protocol.close_exc from self.recv_exc
websockets.exceptions.ConnectionClosedError: received 1007 (invalid frame payload data) Invalid value at 'setup.tools[0].function_declarations[0].behavior' (type.googleapis.com/google.ai.generativelanguage.v1bet; then sent 1007 (invalid frame payload data) Invalid value at 'setup.tools[0].function_declarations[0].behavior' (type.googleapis.com/google.ai.generativelanguage.v1bet {"pid": 12617, "job_id": "AJ_7GXAPhEA6kgG"}
2025-10-29 12:29:40,571 - ERROR livekit.plugins.google - Error in _main_task
Traceback (most recent call last):
File "/Users/andymendez/Documents/BalboaDigital/Code/AI-Voice-Bot/.venv/lib/python3.12/site-packages/livekit/plugins/google/realtime/realtime_api.py", line 654, in _main_task
async with self._client.aio.live.connect(
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/contextlib.py", line 210, in __aenter__
return await anext(self.gen)
^^^^^^^^^^^^^^^^^^^^^
File "/Users/andymendez/Documents/BalboaDigital/Code/AI-Voice-Bot/.venv/lib/python3.12/site-packages/google/genai/live.py", line 1075, in connect
raw_response = await ws.recv(decode=False)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/andymendez/Documents/BalboaDigital/Code/AI-Voice-Bot/.venv/lib/python3.12/site-packages/websockets/asyncio/connection.py", line 322, in recv
raise self.protocol.close_exc from self.recv_exc
websockets.exceptions.ConnectionClosedError: received 1007 (invalid frame payload data) Invalid value at 'setup.tools[0].function_declarations[0].behavior' (type.googleapis.com/google.ai.generativelanguage.v1bet; then sent 1007 (invalid frame payload data) Invalid value at 'setup.tools[0].function_declarations[0].behavior' (type.googleapis.com/google.ai.generativelanguage.v1bet
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/andymendez/Documents/BalboaDigital/Code/AI-Voice-Bot/.venv/lib/python3.12/site-packages/livekit/agents/utils/log.py", line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/andymendez/Documents/BalboaDigital/Code/AI-Voice-Bot/.venv/lib/python3.12/site-packages/livekit/plugins/google/realtime/realtime_api.py", line 704, in _main_task
raise APIConnectionError(message="Failed to connect to Gemini Live") from e
livekit.agents._exceptions.APIConnectionError: Failed to connect to Gemini Live (body=None, retryable=True)tall-airline-16756
10/29/2025, 7:31 PMbehavior field in your tool configuration isn’t set to a valid value from the types.Behavior enum. This often happens when a string like "BLOCK" is used instead of the correct enum value types.Behavior.BLOCK.
To help you fix this, you can update your RealtimeModel configuration like this:
from google.genai import types
model = RealtimeModel(
model="gemini-2.0-flash-live-001",
tool_behavior=types.Behavior.BLOCK, # Correct: using the enum
voice="Puck"
)
Make sure that all tool-related configurations use the types.Behavior enum values. If you’re setting the behavior dynamically, just double-check that you convert the value to the appropriate enum before passing it to the model.
If you’re still running into trouble, please feel free to share how you’re setting the behavior value, and I’d be happy to guide you further!
Sources: livekit-plugins/livekit-plugins-google/livekit/plugins/google/realtime/real... | AI Agents Framework | livekit/livekit_composite | DeepWikisalmon-rainbow-65629
10/29/2025, 7:34 PMtall-airline-16756
10/29/2025, 7:35 PMtool_call_cancellation event can help you detect and handle any cancelled tool calls gracefully.
If you notice this happening often or if it’s causing any issues in your workflow, please don’t hesitate to share the details with me. I’m here to help you troubleshoot and find the best way to optimize your setup.
Sources: plugins/google/src/beta/realtime/realtime_api.ts | Docs::Agents | Gemini Live API plugin | LiveKit Docs | livekit-plugins/livekit-plugins-google/livekit/plugins/google/realtime/real...salmon-rainbow-65629
10/29/2025, 7:36 PMclass Assistant(Agent):
def __init__(self) -> None:
super().__init__(
instructions="""You are a helpful voice AI assistant.
If you detect a voicemail system or answering machine (indicated by an automated greeting, beep, or instructions to leave a message):
1. Wait for the beep or end of the greeting
2. Leave a brief, professional voicemail message like: "Hello, I was trying to reach you but it seems you're unavailable. I'll try calling back later. Thank you!"
3. After you finish speaking your voicemail message, immediately call the detected_answering_machine tool to hang up the call."""
)
@function_tool()
async def detected_answering_machine(self):
"""Call this tool AFTER you have finished leaving your voicemail message to hang up the call"""
# Hang up after the agent has naturally spoken the voicemail message
await asyncio.sleep(0.5) # Brief pause before hanging up
await hangup_call()
This code is still not leaving a voicemail as expectedtall-airline-16756
10/29/2025, 7:37 PMctx.disallow_interruptions() right at the start of your tool function.
3. Tool Output: Double-check that your tool returns a valid, serializable output like a string or None. Sometimes invalid outputs can lead to silent failures.
4. Post-Detection Behavior: You might want to customize the tool so it leaves a message using ctx.session.say() instead of hanging up immediately. Here’s an example you can follow:
@function_tool()
async def voicemail_detected(self, ctx: RunContext):
ctx.disallow_interruptions()
await ctx.session.say(
"Hi, this is LiveKit. We called to confirm your appointment. Please call us back. Goodbye."
)
await asyncio.sleep(1) # Ensure message playback completes
await self.hangup()
Also, take a moment to check your logs for any errors like invalid arguments or if the tool is being called too early. If you’d like, I’m here to help you debug your specific setup—just let me know!
Sources: livekit-agents/livekit/agents/voice/agent_activity.py | agents/src/voice/agent_activity.ts | Docs::Agents | agent.pysalmon-rainbow-65629
10/30/2025, 2:06 AMtall-airline-16756
10/30/2025, 2:06 AMsalmon-rainbow-65629
10/30/2025, 2:09 AM