Hi, How to I define a function tool for Gemini Liv...
# ask-ai
s
Hi, How to I define a function tool for Gemini Live API? Here is my setupcode:
Copy code
async 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()
t
Thanks for reaching out, Andy. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'd be happy to help you define a function tool for the Gemini Live API! You can use the
@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:
Copy code
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:
Copy code
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:
Copy code
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 Docs
s
I updated my code.
Copy code
async 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"
But I still got this error:
Copy code
2025-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)
t
It looks like you're seeing the error "Invalid value at setup.tools[0].function_declarations[0].behavior" because the
behavior
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:
Copy code
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 | DeepWiki
s
Okay, I changed it to use types but got this warning this time around: 2025-10-29 123341,567 - WARNING livekit.plugins.google - server cancelled tool calls {"function_call_ids": ["function-call-5129441062139290907"], "pid": 12781, "job_id": "AJ_4sF6ZcfTMqf8"}
t
I understand that seeing the warning "server cancelled tool calls" can be a bit confusing. This message means that the server has proactively stopped one or more tool calls during your session. Usually, this happens when the server feels the tool execution is no longer needed, like during interruptions, shifts in context, or changes in turn management. To help manage this smoothly, it’s a good idea to include cleanup logic in your tool handlers. For instance, keeping an eye on the
tool_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...
s
Copy code
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()
This code is still not leaving a voicemail as expected
t
I’m sorry to hear that your function tool isn’t leaving a voicemail as expected. Let’s work through some common causes and solutions together: 1. Voicemail Greeting Timing: It’s important to make sure the tool activates only after the voicemail greeting has finished. You can use turn detection or voice activity detection (VAD) to know exactly when the greeting ends. 2. Interruptions: To avoid interruptions during the voicemail process, try calling
ctx.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:
Copy code
@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.py
s
Can you give me a full example of voicemail detection while using gemini live
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!
s
So can I detect voicemail?