I have built a voice agent and I want to trigger a...
# ask-ai
d
I have built a voice agent and I want to trigger a n8n workflow using webhook during the call when the caller wants to book a visit, how do i create a function and call it from the prompt in livekit python?
t
Thanks for reaching out, Harsha. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! The LiveKit Python SDK doesn’t have a built-in way to trigger webhooks during a call, but no worries—you can still make it happen. One option is to send a direct HTTP request from your Python app to your n8n webhook endpoint. Another way is to use LiveKit Data Messages to send a signal to your server, which can then trigger the webhook for you. If you'd like, I’d be happy to walk you through setting up either of these options. Just let me know! Sources: pkg/telemetry/events.go | livekit-api/livekit/api/webhook.py | webhook/notifier.go | Webhooks | LiveKit Docs
d
sure
t
Hey there! If you want to trigger your n8n webhook during a call, here are a couple of easy ways you can do it: 1. Direct HTTP Call: ◦ In your LiveKit Python app, you can use a handy library like
requests
to send an HTTP POST request right to your n8n webhook URL. ◦ Here’s a quick example you can pop into your function:
Copy code
import requests

webhook_url = "<YOUR_N8N_WEBHOOK_URL>"  # Just swap this with your actual n8n webhook URL
data = {"key": "value"}  # Put in whatever data you want to send

response = requests.post(webhook_url, json=data)
print(response.status_code, response.text)
◦ Make sure your n8n workflow is all set up to handle the data coming in. 1. LiveKit Data Messages: ◦ You can send a data message from the client side during the call to give your server a heads-up. ◦ Then, on the server, listen for that message and trigger the n8n webhook with an HTTP request. ◦ This way keeps all the webhook logic nicely tucked away on the server side. Just let me know which way sounds better for you, or if you want a hand setting it all up—I’m here to help!
d
how do i make the llm call this webhook during the call?
t
If you want the LLM to call your webhook during a LiveKit call, you can totally do that using LiveKit's AI Agents Framework with function calling. Let me walk you through the setup: 1. Define a Custom Webhook Function: ◦ Create a function in your agent that sends an HTTP POST request to your webhook URL using a handy library like
aiohttp
. ◦ Here’s a simple example:
Copy code
import aiohttp
from livekit.agents import llm

class WebhookFnc(llm.FunctionContext):
    @llm.ai_callable(description="Send a notification to an external service via webhook")
    async def call_webhook(self, url: str, message: str):
        try:
            async with aiohttp.ClientSession() as session:
                async with session.post(url, json={"message": message}) as response:
                    if response.status == 200:
                        return "Webhook sent successfully."
                    else:
                        return f"Webhook failed with status: {response.status}"
        except Exception as e:
            return f"Error sending webhook: {str(e)}"

fnc_ctx = WebhookFnc()
1. Attach the Function to Your Agent: ◦ Just use the
PipelineVoiceAgent
or
MultimodalAgent
and hook up the function context to it. ◦ For example:
agent = VoicePipelineAgent(fnc_ctx=fnc_ctx, ...)
1. Trigger the Function During the Call: ◦ When the LLM picks up a user intent (like "Book a visit"), it’ll call the
call_webhook
function with the webhook URL and message you provide. If you want, I’m here to help you with setting this up or tweaking your webhook configuration—just let me know! Sources: Function calling with Voice Agents | LiveKit Docs | examples/webhooks-nextjs/README.md | examples/webhook.py
d
give me the full code with a prompt example
t
Here's a complete example to help you set up a LiveKit voice agent with a webhook function and a sample prompt. Let's walk through it together:
Copy code
import aiohttp
from livekit.agents import llm
from livekit.agents.voice import VoicePipelineAgent

# Step 1: Define the webhook function
class WebhookFnc(llm.FunctionContext):
    @llm.ai_callable(description="Send a notification to an external service via webhook")
    async def call_webhook(self, url: str, message: str):
        """Trigger a webhook to notify an external system."""
        try:
            async with aiohttp.ClientSession() as session:
                async with session.post(url, json={"message": message}) as response:
                    if response.status == 200:
                        return "Webhook sent successfully."
                    else:
                        return f"Webhook failed with status: {response.status}"
        except Exception as e:
            return f"Error sending webhook: {str(e)}"

# Step 2: Attach the function context to the agent
fnc_ctx = WebhookFnc()
agent = VoicePipelineAgent(
    fnc_ctx=fnc_ctx,
    stt_service="your_stt_service",  # Replace with your Speech-to-Text service
    tts_service="your_tts_service",  # Replace with your Text-to-Speech service
    llm_service="your_llm_service"   # Replace with your LLM service
)

# Step 3: Define a sample prompt
prompt = "If the user says they want to book a visit, call the webhook function with the appropriate message."

# Step 4: Simulate a user input
async def simulate_user_input():
    user_input = "I want to book a visit to the clinic."
    response = await agent.process_input(user_input)
    print("Agent response:", response)

# Run the simulation
import asyncio
asyncio.run(simulate_user_input())
To break it down: • The
call_webhook
function sends a POST request to your webhook URL with the message you want to share. • The
VoicePipelineAgent
is set up with your function context, plus the Speech-to-Text, Text-to-Speech, and LLM services you’re using. • The prompt guides the LLM to call the webhook function whenever the user mentions booking a visit. • The
simulate_user_input
function shows how the agent handles user input and triggers the webhook in action. If you’d like, I’m here to help you tweak this code to fit your specific needs—just let me know!
d
no use agentsession with tts and stt too
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!