Skip to main content

LiveKit plugin for integrating n8n webhooks with voice AI agents

Project description

LiveKit N8n Plugin

Integrate n8n webhooks with LiveKit voice AI agents for seamless conversational AI experiences.

Developer: Haitham Ramdan

Features

  • 🎙️ Voice AI Integration: Connect n8n workflows directly to LiveKit voice agents
  • 🔄 Session Management: Automatic conversation tracking with session IDs
  • 👤 User Identity: Pass participant information to your n8n workflows
  • 🚀 Simple API: Easy-to-use interface following LiveKit plugin conventions
  • 📝 Full Logging: Comprehensive logging for debugging and monitoring
  • 🌐 Flexible Configuration: Support for both direct URLs and environment variables

Installation

pip install livekit-plugins-n8n

Quick Start

1. Set up your n8n webhook

Create a webhook in n8n that accepts POST requests with this payload:

{
  "query": "user's message",
  "session_id": "unique_session_id",
  "user_identity": "user_identifier"
}

Your webhook should return one of these formats:

Format 1 (Array):

[
  {
    "output": "AI response text"
  }
]

Format 2 (Object):

{
  "output": "AI response text"
}

2. Use in your LiveKit agent

from dotenv import load_dotenv
from livekit import agents
from livekit.agents import AgentSession, Agent, WorkerOptions
from livekit.plugins import n8n, deepgram, silero, elevenlabs
from livekit.plugins.turn_detector.multilingual import MultilingualModel

load_dotenv()


class Assistant(Agent):
    def __init__(self) -> None:
        super().__init__(
            instructions="You are a helpful voice AI assistant."
        )


async def entrypoint(ctx: agents.JobContext):
    await ctx.connect()

    # Get participant information
    participant_identity = "unknown_user"
    if ctx.room.remote_participants:
        first_participant = next(iter(ctx.room.remote_participants.values()))
        participant_identity = first_participant.identity

    # Initialize n8n LLM
    llm = n8n.LLM(
        webhook_url="https://your-n8n.cloud/webhook/livekit",
        session_id=ctx.room.name,
        participant_identity=participant_identity
    )

    session = AgentSession(
        stt=deepgram.STT(model="nova-3", language="multi"),
        llm=llm,
        tts=elevenlabs.TTS(),
        vad=silero.VAD.load(),
        turn_detection=MultilingualModel(),
    )

    assistant = Assistant()
    
    await session.start(room=ctx.room, agent=assistant)
    
    # Optional: Say a greeting
    await session.say(
        "Hello! How can I help you today?", 
        allow_interruptions=True
    )


if __name__ == "__main__":
    agents.cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))

Configuration

Environment Variables

Set these in your .env file:

# Required
N8N_WEBHOOK_URL=https://your-n8n.cloud/webhook/livekit

# LiveKit credentials
LIVEKIT_URL=wss://your-livekit-instance.livekit.cloud
LIVEKIT_API_KEY=your_api_key
LIVEKIT_API_SECRET=your_api_secret

# Plugin API keys
DEEPGRAM_API_KEY=your_deepgram_key
ELEVENLABS_API_KEY=your_elevenlabs_key

LLM Initialization Options

Option 1: Direct URL

llm = n8n.LLM(
    webhook_url="https://your-n8n.com/webhook/livekit")

Example n8n Workflow

Here's a basic n8n workflow structure:

Workflow Nodes

  1. Webhook Node (Trigger)

    • Method: POST
    • Path: /webhook/livekit
    • Receive these fields: query, session_id, user_identity
  2. Process Node (Your AI Logic)

    • Examples:
      • Call OpenAI/Anthropic API
      • Query your database
      • Run custom business logic
      • Use n8n AI nodes
  3. Respond to Webhook Node

    • Return JSON:
    [
      {
        "output": "{{ $json.ai_response }}"
      }
    ]
    

Advanced Usage

Session-Based Conversations

The plugin automatically tracks conversations using session_id. Use this in your n8n workflow to:

  • Store conversation history in a database
  • Maintain context across multiple messages
  • Implement custom memory/RAG systems
# The session_id is automatically set to the room name
llm = n8n.LLM(
    webhook_url="https://your-n8n.com/webhook/livekit",
    session_id=ctx.room.name  # Unique per room
)

User-Specific Responses

Use participant_identity to personalize responses:

llm = n8n.LLM(
    webhook_url="https://your-n8n.com/webhook/livekit",
    participant_identity=participant.identity
)

In your n8n workflow, access this via {{ $json.user_identity }} to:

  • Fetch user preferences
  • Load user-specific data
  • Implement authorization logic

Troubleshooting

Common Issues

1. Webhook timeout

APIConnectionError: n8n Webhook API error
  • Ensure your n8n webhook responds within 30 seconds
  • Check n8n workflow execution logs
  • Verify webhook URL is correct

2. Invalid response format

ValueError: Unexpected response format from n8n
  • Ensure response contains output field
  • Check response format matches one of the supported formats
  • Test webhook directly with curl/Postman

3. Missing environment variables

ValueError: webhook_url or N8N_WEBHOOK_URL environment variable is required
  • Set N8N_WEBHOOK_URL in your .env file
  • Or pass webhook_url directly to n8n.LLM()

Testing Your Webhook

Test with curl:

curl -X POST https://your-n8n.com/webhook/livekit \
  -H "Content-Type: application/json" \
  -d '{
    "query": "Hello",
    "session_id": "test_123",
    "user_identity": "test_user"
  }'

Expected response:

[{"output": "Hello! How can I help you?"}]

Requirements

  • Python 3.9+
  • LiveKit Agents SDK
  • aiohttp
  • n8n instance (self-hosted or cloud)

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT License - see LICENSE file for details

Support

Related Projects

  • LiveKit - Real-time communication platform
  • n8n - Workflow automation platform
  • LiveKit Agents - Agent framework for LiveKit

Made with ❤️ by Haitham Ramdan# livekit-plugins-n8n

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

livekit_plugins_n8n-0.1.0.tar.gz (10.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

livekit_plugins_n8n-0.1.0-py3-none-any.whl (8.5 kB view details)

Uploaded Python 3

File details

Details for the file livekit_plugins_n8n-0.1.0.tar.gz.

File metadata

  • Download URL: livekit_plugins_n8n-0.1.0.tar.gz
  • Upload date:
  • Size: 10.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for livekit_plugins_n8n-0.1.0.tar.gz
Algorithm Hash digest
SHA256 89863e79b7236eb0d37c379cbd18c245decb0c2af22e3f7ff5bf146c935c3a6a
MD5 3cb1691058b5b6e25b4b6cefc332f13d
BLAKE2b-256 6e670d77b38bf517ddecd6bd99e471cf3d315f0cba9f74a46b61b6e347044b16

See more details on using hashes here.

File details

Details for the file livekit_plugins_n8n-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for livekit_plugins_n8n-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6a37f00faa97fe8d813912310d975540e32d69747167521398621aef19f0872a
MD5 692f742ab93a4872a621e492cd8a4d23
BLAKE2b-256 e9601be23ccaccb658d8bb996a1c56643cacb16464b04576ce75ec050f84de03

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page