How to handle function calling Over the voice as d...
# ask-ai
a
How to handle function calling Over the voice as done in voicepipelineagent can be done in agentsession
t
Thanks for reaching out, giri. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To handle function calling over voice in
AgentSession
similarly to
VoicePipelineAgent
, you can define functions using the
@function_tool
decorator within your
Agent
class. Here's an example:
Copy code
from livekit.agents import Agent, AgentSession
from livekit.agents.llm import function_tool

class FunctionAgent(Agent):
    def __init__(self) -> None:
        super().__init__(
            instructions="""
                You are a helpful assistant communicating through voice.
                Note: If asked to print to the console, use the `print_to_console` function.
            """,
            stt=deepgram.STT(),
            llm=openai.LLM(model="gpt-4o"),
            tts=openai.TTS(),
            vad=silero.VAD.load()
        )

    @function_tool
    async def print_to_console(self, context: RunContext):
        print("Console Print Success!")
        return None, "I've printed to the console."

async def entrypoint(ctx: JobContext):
    session = AgentSession()
    await session.start(
        agent=FunctionAgent(),
        room=ctx.room
    )
You can also dynamically add tools to an agent using `update_tools()`:
Copy code
async def _random_number() -> int:
    num = random.randint(0, 100)
    <http://logger.info|logger.info>(f"random_number called: {num}")
    return num

await agent.update_tools(
    agent.tools
    + [function_tool(_random_number, name="random_number", description="Get a random number")]
)
While
VoicePipelineAgent
uses a
fnc_ctx
parameter that inherits from
llm.FunctionContext
, the execution flow for both approaches is similar: 1. Detects when the LLM wants to call a function 2. Executes the function with the provided arguments 3. Returns the result back to the LLM 4. Generates a response incorporating the function result 5. Emits
function_tools_executed
events for monitoring The main difference is in the organization:
AgentSession
with
Agent
classes keeps functions as methods within the agent, while
VoicePipelineAgent
uses a separate function context class. Both approaches provide the same core functionality for handling function calling over voice. Sources: tool_calling/call_function_tool.py | Function calling with Voice Agents | LiveKit Docs | tests/test_evals.py