> For the complete documentation index, see [llms.txt](https://docs.snackprompt.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.snackprompt.com/bring-your-data-into-ai/how-to/get-started-with-integrations/how-to-integrate-with-n8n.md).

# How to Integrate with N8N

Learn how to use the SnackPrompt AI Engine API as a knowledge source for AI agents and workflows in N8N.

### Overview

N8N offers several ways to integrate external APIs with its AI capabilities:

| Method                | Use Case          | Description                                     |
| --------------------- | ----------------- | ----------------------------------------------- |
| **HTTP Request Tool** | Agents with tools | Agent decides when to query the API             |
| **HTTP Request Node** | RAG in workflows  | Direct call at a specific point in the workflow |
| **Custom Retriever**  | Advanced RAG      | Replace native vector store with external API   |

### Integration Architecture

```
┌─────────────────────────────────────────────────────────┐
│                        N8N                              │
│  ┌─────────────┐    ┌─────────────┐    ┌────────────┐   │
│  │   Trigger   │───▶│  AI Agent   │───▶│  Response │   │
│  └─────────────┘    └──────┬──────┘    └────────────┘   │
│                            │                            │
│                     ┌──────▼──────┐                     │
│                     │ HTTP Tool   │                     │
│                     └──────┬──────┘                     │
└────────────────────────────┼────────────────────────────┘
                             │
                             ▼
              ┌──────────────────────────────┐
              │  SnackPrompt AI Engine API   │
              │  /v1/kb/search or /v1/kb/chat│
              └──────────────────────────────┘
```

***

### Method 1: HTTP Request Tool (Recommended)

Use when you want the **agent to autonomously decide** when to search your knowledge base.

#### Step 1: Configure the AI Agent

1. Add an **AI Agent** node to your workflow
2. Configure the LLM model (OpenAI, Anthropic, etc.)
3. Connect an **HTTP Request Tool** as a tool

#### Step 2: Configure the HTTP Request Tool

**Tool Settings:**

| Field       | Value                                                                                                                                                                        |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Name        | `search_knowledge_base`                                                                                                                                                      |
| Description | `Use this tool to search for information in the company knowledge base. Send a natural language query to find relevant documents about products, policies, procedures, etc.` |
| Method      | `POST`                                                                                                                                                                       |
| URL         | `https://api-integrations.snackprompt.com/v1/kb/search`                                                                                                                      |

**Headers:**

```
Content-Type: application/json
x-api-key: YOUR_API_KEY
```

**Body (JSON):**

```json
{
  "query": "{{ $fromAI('query', 'The search query') }}",
  "filters": {
    "tenant_id": "YOUR_TENANT_ID"
  },
  "limit": 5
}
```

#### Step 3: Optimize the Response

In the HTTP Request Tool **Options** section:

* **Optimize Response**: Enabled
* **Response Format**: `JSON`
* **Limit Response Size**: Recommended to reduce tokens

#### Complete Workflow Example

```
[Chat Trigger] → [AI Agent] → [Response]
                     │
                     └─── [HTTP Request Tool: search_knowledge_base]
```

The agent will receive a question, decide if it needs to query the knowledge base, perform the search, and use the results to formulate the response.

***

### Method 2: HTTP Request Node (Direct RAG)

Use when you want a **deterministic workflow** where the search always happens.

#### Simple RAG Workflow

```
[Webhook/Chat Trigger]
        │
        ▼
[HTTP Request: Search API]
        │
        ▼
[Set Node: Format Context]
        │
        ▼
[AI Chain: Generate Response]
        │
        ▼
[Respond to Webhook]
```

#### HTTP Request Node Configuration

**Method:** POST

**URL:**

```
https://api-integrations.snackprompt.com/v1/kb/search
```

**Headers:**

```
Content-Type: application/json
x-api-key: YOUR_API_KEY
```

**Body:**

```json
{
  "query": "{{ $json.chatInput }}",
  "filters": {
    "tenant_id": "YOUR_TENANT_ID"
  },
  "limit": 5
}
```

#### Formatting the Context

Use a **Set Node** or **Code Node** to format the results:

```javascript
// Code Node
const results = $input.first().json.items;

const context = results.map((item, index) =>
  `[${index + 1}] ${item.payload.original_text}`
).join('\n\n');

return {
  context: context,
  sources: results.map(r => ({
    id: r.payload.snack_item_id,
    score: r.score
  }))
};
```

#### AI Chain Prompt

```
You are a helpful assistant. Answer the user's question based ONLY on the following context.

Context:
{{ $json.context }}

User Question: {{ $('Webhook').item.json.chatInput }}

If the context doesn't contain relevant information, say "I don't have information about that."
```

***

### Method 3: Chat Endpoint for Complete Responses

Use the `/v1/kb/chat` endpoint when you want the **API to handle all the RAG** and return a ready response.

#### Configuration

**URL:**

```
https://api-integrations.snackprompt.com/v1/kb/chat
```

**Headers:**

```
Content-Type: application/json
x-api-key: YOUR_API_KEY
```

**Body:**

```json
{
  "query": "{{ $json.chatInput }}",
  "filters": {
    "tenant_id": "YOUR_TENANT_ID",
    "tag_names": ["Support", "FAQ"]
  }
}
```

#### Response

The API returns:

* `answer`: AI-generated response
* `sources`: Sources used to generate the response

You can use it directly or enrich with additional logic in N8N.

***

### Practical Use Cases

#### 1. Support Chatbot

```
[Chat Trigger] → [HTTP Request: /chat] → [Respond with answer]
```

Ideal for simple chatbots that need to answer questions about products, policies, etc.

#### 2. Multi-tool Agent

```
[Chat Trigger] → [AI Agent] → [Response]
                     │
                     ├── [Tool: search_knowledge_base]
                     ├── [Tool: Google Calendar]
                     └── [Tool: Send Email]
```

The agent can search for information AND execute actions.

#### 3. RAG with Multiple Sources

```
[Webhook] → [Switch: Route by Topic]
                 │
                 ├── [Search: tag=Sales] → [Merge] → [AI: Generate]
                 └── [Search: tag=Support] ───┘
```

Search in different categories and combine the results.

#### 4. Response Validation

```
[Chat] → [AI Agent: Generate Draft]
              │
              ▼
         [HTTP Request: Search for validation]
              │
              ▼
         [AI: Verify and Refine]
              │
              ▼
         [Response]
```

The agent generates a response, searches for validation in the knowledge base, and refines.

***

### Configuration Tips

#### 1. Tool Description is Crucial

The HTTP Request Tool description determines **when** the agent will use it:

```
✅ Good description:
"Search the company knowledge base for information about products,
pricing, policies, and procedures. Use when the user asks about
company-specific information."

❌ Bad description:
"Search API"
```

#### 2. Limit the Results

Too many results = too many tokens = higher cost and possible confusion:

```json
{
  "limit": 3  // Start with few and increase if needed
}
```

#### 3. Use Filters for Context

Direct the search with tags when you know the context:

```json
{
  "filters": {
    "tenant_id": "...",
    "tag_names": ["{{ $json.detected_topic }}"]
  }
}
```

#### 4. Handle Errors

Add an **Error Trigger** or use **Continue On Fail** to handle API failures.

***

### Complete Example: Sales Chatbot

#### Workflow

1. **Chat Trigger**: Receives user message
2. **AI Agent**: Processes with GPT-4
3. **HTTP Request Tool**: Searches products and prices
4. **HTTP Request Tool**: Searches discount policies
5. **Response**: Returns response to user

#### Agent Configuration

**System Prompt:**

```
You are a sales assistant for company X.
Help customers find products and understand pricing.
Use the search_products tool to find product information.
Use the search_policies tool to find discount policies.
Always cite sources when providing information.
```

**Tools:**

| Tool              | Description                                                 |
| ----------------- | ----------------------------------------------------------- |
| `search_products` | Search for product information, specifications, and pricing |
| `search_policies` | Search for discount policies, payment terms, and conditions |

***

### Troubleshooting

#### Error: "tenant\_id is required"

Make sure `tenant_id` is inside the `filters` object:

```json
// ❌ Wrong
{ "query": "...", "tenant_id": "..." }

// ✅ Correct
{ "query": "...", "filters": { "tenant_id": "..." } }
```

#### Agent doesn't use the tool

1. Improve the tool description
2. Add examples in the system prompt
3. Verify if the question actually requires the tool

#### Response too long/truncated

1. Reduce the results `limit`
2. Enable **Optimize Response** on the tool
3. Use a Code Node to summarize before passing to the LLM

***

### Related

* [Endpoints Reference](/bring-your-data-into-ai/reference/endpoints.md)
* [Available Filters](/bring-your-data-into-ai/reference/filters.md)
* [Error Handling](/bring-your-data-into-ai/how-to/how-to-handle-errors.md)

### External Resources

* [N8N RAG Documentation](https://docs.n8n.io/advanced-ai/rag-in-n8n/)
* [HTTP Request Tool Docs](https://docs.n8n.io/integrations/builtin/cluster-nodes/sub-nodes/n8n-nodes-langchain.toolhttprequest/)
* [Building RAG in 2025 - N8N Community](https://community.n8n.io/t/building-rag-in-2025-vector-stores-as-tools-is-here/75166)
