> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.agentduet.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.agentduet.com/_mcp/server.

# n8n

This guide explains how to connect AgentDuet voice agents to [n8n](https://n8n.io) to trigger visual workflows, query internal databases, and orchestrate business operations directly from telephone conversations.

---

## Why Connect n8n to AgentDuet?

AgentDuet provides the carrier telephony infrastructure, SIP management, call answering, and ultra-low-latency audio streaming (16 kHz or 24 kHz Linear PCM) over persistent WebSockets.

While your voice model manages natural conversation, business logic often requires access to external systems: customer databases, inventory lookups, CRMs, ticketing platforms, or team messaging.

Connecting your voice agent to n8n provides:

* **Visual Workflow Building**: Build and adjust business logic visually without rebuilding or redeploying your voice application.
* **400+ Enterprise Connectors**: Read and write data across PostgreSQL, Google Sheets, HubSpot, Salesforce, Stripe, Jira, and internal APIs.
* **Self-Hostable and Private**: Run n8n on your own infrastructure or on n8n Cloud, keeping sensitive caller data and credentials secure.
* **Decoupled Architecture**: Keep telephony and voice processing separate from backend business logic. If a database schema or API endpoint changes, update it in n8n without touching voice code.

---

## Architecture

Real-time audio and workflow automation operate on two distinct, optimized communication channels:

```mermaid
flowchart TD
    Caller["Telephone Caller"] <-->|"PSTN / SIP Phone Line"| AgentDuet["AgentDuet Telephony Engine"]
    AgentDuet <-->|"Bidirectional WebSocket (wss://) • 16/24 kHz LPCM"| VoiceAgent["Voice Agent Runtime"]
    VoiceAgent -->|"HTTPS POST Webhook (Structured JSON)"| n8nWebhook["n8n Webhook & Workflow"]
    n8nWebhook --> Systems[("Databases / CRMs / External APIs")]
    n8nWebhook -->|"HTTPS JSON Response (Tool Results)"| VoiceAgent
```

| Communication Path | Transport | Purpose |
| :--- | :--- | :--- |
| **Caller $\leftrightarrow$ AgentDuet** | PSTN / SIP | Telephony carrier connection, call state, dial tones |
| **AgentDuet $\leftrightarrow$ Voice Agent** | WebSocket (`wss://`) | 16 kHz / 24 kHz Linear PCM audio streaming, sub-millisecond barge-in buffer flush |
| **Voice Agent $\leftrightarrow$ n8n** | HTTPS POST | Structured JSON payloads for tool execution, record lookups, and post-call intake |

---

## How to Trigger n8n from Your Voice Agent

Your voice agent communicates with n8n over standard HTTPS webhooks. Below is a minimal, reusable Python pattern for dispatching requests to n8n from within an AgentDuet voice agent:

```python
import httpx
from typing import Any, Dict, Optional

class N8nWorkflowClient:
    """Dispatches webhook events from an AgentDuet voice agent to n8n."""

    def __init__(self, webhook_url: str, api_key: Optional[str] = None):
        self.webhook_url = webhook_url
        self.headers = {"Content-Type": "application/json"}
        if api_key:
            self.headers["X-N8N-API-KEY"] = api_key

    async def execute(self, payload: Dict[str, Any]) -> Dict[str, Any]:
        """Sends an event payload to n8n and returns the workflow response."""
        async with httpx.AsyncClient(timeout=5.0) as client:
            response = await client.post(
                self.webhook_url,
                json=payload,
                headers=self.headers,
            )
            response.raise_for_status()
            return response.json()
```

### Usage Patterns

1. **Mid-Call Tool Lookups**: When the caller asks for specific account data, order status, or appointment slots, the agent model triggers a tool call that invokes `client.execute({"action": "lookup", "caller_id": caller_phone})`. The returned JSON is passed back to the voice model to speak the answer.
2. **Post-Call Data Persistence**: When the call completes, the agent extracts structured summary details from the transcript and fires an asynchronous webhook to n8n to log the interaction into your CRM or database.

---

## Best Practices for Voice Workflows

* **Keep Mid-Call Workflows Fast**: Voice callers expect conversational turn-taking. Design mid-call n8n workflows to respond within 1 to 2 seconds. Use cached lookups or indexed database queries whenever possible.
* **Use "Respond to Webhook" Node**: Ensure your n8n workflow uses the **Respond to Webhook** node mode so the HTTP connection remains open until the workflow formats its final JSON response.
* **Separate Background Tasks**: If a workflow performs slow tasks (such as sending emails, generating PDFs, or alerting Slack), return the voice response first, and place the slower actions on a downstream parallel branch.
* **Provide Conversational Fallbacks**: Always handle network timeouts or missing records gracefully in your voice prompt so the agent can inform the caller politely if an external service is unavailable.

---

## Reference Implementation

A working reference sample is available in the [agentduet-samples](https://github.com/AgentDuet/agentduet-samples) repository:

* **Repository Directory**: [`agentduet-samples/integrations/n8n`](https://github.com/AgentDuet/agentduet-samples/tree/main/integrations/n8n)

To set up and run the voice agent locally:

```bash
# 1. Clone the repository
git clone https://github.com/AgentDuet/agentduet-samples.git

# 2. Navigate to the n8n integration directory
cd agentduet-samples/integrations/n8n
```

Head over to [`README.md`](https://github.com/AgentDuet/agentduet-samples/blob/main/integrations/n8n/README.md) inside this folder for complete setup instructions, environment configuration, ready-to-import workflow files, and everything you need to bring your voice agent live in minutes!

---

## Next Step

<Card title="Make" icon="fa-duotone fa-arrow-right" href="/integrations/make">
  Connect AgentDuet voice agents to 1,000+ apps using visual Make scenarios.
</Card>