> 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-dify.md).

# How to Integrate with Dify

Learn how to use the SnackPrompt AI Engine API as an external knowledge source in Dify applications and workflows.

### Overview

Dify is a platform for building LLM applications. It offers several ways to integrate external APIs:

| Method                     | Use Case        | Description                                    |
| -------------------------- | --------------- | ---------------------------------------------- |
| **External Knowledge API** | RAG replacement | Use external API instead of built-in knowledge |
| **HTTP Request Node**      | Workflows       | Call API in workflow nodes                     |
| **Custom Tool**            | Agent tools     | Agent decides when to query the API            |
| **API Extension**          | Advanced        | Create reusable API integration                |

### Integration Architecture

```
┌─────────────────────────────────────────────────────────┐
│                        Dify                             │
│  ┌─────────────┐    ┌─────────────┐    ┌────────────┐   │
│  │    User     │──▶│  Chatflow/  │──▶│  Response   │   │
│  │   Input     │    │  Workflow   │    │            │   │
│  └─────────────┘    └──────┬──────┘    └────────────┘   │
│                            │                            │
│                     ┌──────▼──────┐                     │
│                     │   HTTP /    │                     │
│                     │ Knowledge   │                     │
│                     └──────┬──────┘                     │
└────────────────────────────┼────────────────────────────┘
                             │
                             ▼
              ┌──────────────────────────────┐
              │  SnackPrompt AI Engine API   │
              │  /v1/kb/search or /v1/kb/chat│
              └──────────────────────────────┘
```

***

### Method 1: External Knowledge API (Recommended)

Dify supports connecting to external knowledge bases via API. This is the most native integration.

#### Step 1: Configure External Knowledge

1. Go to **Knowledge** in Dify
2. Click **External Knowledge API**
3. Click **Add External Knowledge API**

#### Step 2: API Configuration

<table><thead><tr><th width="240">Field</th><th>Value</th></tr></thead><tbody><tr><td>Name</td><td><code>SnackPrompt Knowledge Base</code></td></tr><tr><td>API Endpoint</td><td><code>https://api-integrations.snackprompt.com/v1/kb/search</code></td></tr><tr><td>API Key</td><td>Your SnackPrompt API key</td></tr></tbody></table>

#### Step 3: Request Configuration

**Request Body Template:**

```json
{
  "query": "{{query}}",
  "filters": {
    "tenant_id": "YOUR_TENANT_ID"
  },
  "limit": {{top_k}}
}
```

**Response Mapping:**

| Dify Field    | API Response Path       |
| ------------- | ----------------------- |
| `records`     | `items`                 |
| `content`     | `payload.original_text` |
| `score`       | `score`                 |
| `metadata.id` | `payload.snack_item_id` |

#### Step 4: Use in Applications

1. Create or edit a **Chatbot** or **Agent** application
2. In **Context**, select your external knowledge
3. Configure retrieval settings (top\_k, score threshold)

***

### Method 2: HTTP Request in Workflows

Use when building complex workflows that need API calls at specific points.

#### Step 1: Create a Workflow

1. Go to **Studio** > **Create App** > **Workflow**
2. Add nodes to your workflow

#### Step 2: Add HTTP Request Node

1. Add **HTTP Request** node
2. Configure:

<table><thead><tr><th width="245">Field</th><th>Value</th></tr></thead><tbody><tr><td>Method</td><td><code>POST</code></td></tr><tr><td>URL</td><td><code>https://api-integrations.snackprompt.com/v1/kb/search</code></td></tr></tbody></table>

**Headers:**

```
Content-Type: application/json
x-api-key: {{api_key}}
```

**Body:**

```json
{
  "query": "{{#input.query#}}",
  "filters": {
    "tenant_id": "YOUR_TENANT_ID"
  },
  "limit": 5
}
```

#### Step 3: Process Results

Add a **Code** node to format results:

```python
def main(inputs):
    results = inputs.get('http_response', {}).get('items', [])

    if not results:
        return {'context': 'No relevant information found.'}

    context = '\n\n'.join([
        f"[{i+1}] {item['payload']['original_text']}"
        for i, item in enumerate(results)
    ])

    return {'context': context}
```

#### Step 4: Generate Response

Add **LLM** node with prompt:

```
Answer the user's question based on the following context.

Context:
{{#code.context#}}

User Question: {{#input.query#}}

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

***

### Method 3: Chat Endpoint for Simple Integration

Use `/v1/kb/chat` when you want the API to handle all RAG processing.

#### Workflow Structure

```
[Start] → [HTTP Request: /chat] → [Template: Format] → [End]
```

#### HTTP Request Configuration

<table><thead><tr><th width="253">Field</th><th>Value</th></tr></thead><tbody><tr><td>URL</td><td><code>https://api-integrations.snackprompt.com/v1/kb/chat</code></td></tr><tr><td>Method</td><td><code>POST</code></td></tr></tbody></table>

**Headers:**

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

**Body:**

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

#### Extract Response

The API returns:

* `answer`: Ready-to-use response
* `sources`: Source documents used

Use in template: `{{#http_request.answer#}}`

***

### Method 4: Custom Tool for Agents

Create a custom tool that agents can use to search your knowledge base.

#### Step 1: Go to Tools

1. Navigate to **Tools** in Dify
2. Click **Create Custom Tool**

#### Step 2: Configure Tool

**Basic Information:**

| Field       | Value                                                                                                                                                         |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Name        | `search_knowledge_base`                                                                                                                                       |
| Description | `Search the company knowledge base for information about products, policies, and procedures. Use when you need factual information to answer user questions.` |

**Parameters:**

| Name    | Type   | Required | Description                  |
| ------- | ------ | -------- | ---------------------------- |
| `query` | string | Yes      | The search query             |
| `tags`  | array  | No       | Filter by specific tags      |
| `limit` | number | No       | Maximum results (default: 5) |

#### Step 3: Tool Schema

```yaml
openapi: 3.0.0
info:
  title: SnackPrompt Knowledge Search
  version: 1.0.0
servers:
  - url: https://api-integrations.snackprompt.com
paths:
  /v1/kb/search:
    post:
      operationId: searchKnowledge
      summary: Search knowledge base
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - query
                - filters
              properties:
                query:
                  type: string
                  description: Search query
                filters:
                  type: object
                  properties:
                    tenant_id:
                      type: string
                    tag_names:
                      type: array
                      items:
                        type: string
                limit:
                  type: integer
                  default: 5
      responses:
        '200':
          description: Search results
          content:
            application/json:
              schema:
                type: object
                properties:
                  items:
                    type: array
```

#### Step 4: Authentication

Configure API key authentication:

| Field       | Value                    |
| ----------- | ------------------------ |
| Auth Type   | `API Key`                |
| Header Name | `x-api-key`              |
| API Key     | Your SnackPrompt API key |

#### Step 5: Use in Agent

1. Create an **Agent** application
2. Add your custom tool to the agent's toolset
3. Configure the agent's system prompt to use the tool

***

### Practical Use Cases

#### 1. Simple Q\&A Chatbot

```
[Chatbot App] + [External Knowledge: SnackPrompt]
```

Native integration using External Knowledge API.

#### 2. Support Agent with Tools

```
[Agent App]
    │
    ├── [Tool: search_knowledge_base]
    ├── [Tool: search_products]
    └── [Tool: create_ticket]
```

Agent that can search and take actions.

#### 3. RAG Workflow with Validation

```
[Start] → [HTTP: Search] → [Code: Check Results] → [Branch]
                                                      │
                                         ┌────────────┴────────────┐
                                         ▼                         ▼
                                   [Has Results]            [No Results]
                                         │                         │
                                         ▼                         ▼
                                   [LLM: Answer]            [LLM: Apologize]
                                         │                         │
                                         └────────────┬────────────┘
                                                      ▼
                                                   [End]
```

#### 4. Multi-Source Knowledge

```
[Start] → [Parallel]
              │
              ├── [HTTP: SnackPrompt tag=Sales]
              └── [HTTP: SnackPrompt tag=Support]
              │
              ▼
         [Code: Merge] → [LLM: Generate] → [End]
```

#### 5. Conversational RAG with Memory

```
[Chatbot App]
    │
    ├── [External Knowledge: SnackPrompt]
    ├── [Conversation Opener]
    └── [Memory: Buffer Window]
```

***

### Configuration Tips

#### 1. Optimize Retrieval Settings

In your chatbot/agent configuration:

| Setting         | Recommended Value   |
| --------------- | ------------------- |
| Top K           | 3-5                 |
| Score Threshold | 0.5                 |
| Reranking       | Enable if available |

#### 2. Tool Description Matters

For agents, write detailed tool descriptions:

```
✅ Good:
"Search the company knowledge base for information about products,
pricing, policies, and support procedures. Returns relevant text
snippets that can be used to answer customer questions. Use this
tool when the user asks about company-specific information."

❌ Bad:
"Search API"
```

#### 3. Handle Empty Results

In Code nodes:

```python
def main(inputs):
    items = inputs.get('items', [])

    if not items:
        return {
            'has_results': False,
            'context': '',
            'message': 'No relevant information found.'
        }

    return {
        'has_results': True,
        'context': format_results(items),
        'message': ''
    }
```

#### 4. Use Variables for Configuration

Store configuration in Dify variables:

| Variable                    | Value          |
| --------------------------- | -------------- |
| `snackprompt_tenant_id`     | Your tenant ID |
| `snackprompt_default_limit` | `5`            |

Reference in HTTP body:

```json
{
  "filters": {
    "tenant_id": "{{snackprompt_tenant_id}}"
  },
  "limit": {{snackprompt_default_limit}}
}
```

#### 5. Filter by Context

Use tags to narrow search scope:

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

***

### Complete Example: Customer Service Chatbot

#### Application Type

**Agent** with tools

#### System Prompt

```
You are a helpful customer service assistant for Company X.

Your role:
- Answer questions about our products, services, and policies
- Help customers find information they need
- Create support tickets when you can't resolve an issue

Guidelines:
1. Always search the knowledge base before answering product questions
2. Be accurate - only provide information from the knowledge base
3. If you can't find information, offer to create a support ticket
4. Be friendly and professional
5. Format responses clearly with bullet points when appropriate

Available tools:
- search_knowledge_base: Search for product info, policies, FAQs
- create_ticket: Create a support ticket for unresolved issues
```

#### Tools Configuration

**Tool 1: search\_knowledge\_base**

* Endpoint: `/v1/kb/search`
* Use for: General knowledge queries

**Tool 2: search\_products**

* Endpoint: `/v1/kb/search` with `tag_names: ["Products"]`
* Use for: Product-specific queries

#### Conversation Opener

```
Hello! I'm your customer service assistant. I can help you with:

• Product information and specifications
• Pricing and availability
• Company policies
• Troubleshooting guides

How can I assist you today?
```

***

### Troubleshooting

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

Ensure `tenant_id` is inside the `filters` object:

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

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

#### External Knowledge not returning results

1. Verify the API endpoint URL
2. Check API key is correct
3. Test API directly with curl/Postman
4. Verify response mapping matches API response structure

#### Agent doesn't use the tool

1. Improve tool description
2. Add explicit instructions in system prompt
3. Test with queries like "search the knowledge base for..."
4. Check tool is enabled in agent settings

#### Workflow HTTP request fails

1. Check URL is correct
2. Verify headers are properly formatted
3. Check body JSON is valid
4. Look at error response for details

#### Slow response times

1. Reduce `limit` parameter
2. Add caching if supported
3. Check network latency to API
4. Consider using `/chat` endpoint for simpler flows

***

### API Response Mapping Reference

#### Search Endpoint Response

```json
{
  "items": [
    {
      "payload": {
        "original_text": "Document content here...",
        "snack_item_id": "item_123"
      },
      "score": 0.95
    }
  ]
}
```

#### Mapping for External Knowledge

| Dify Expects | SnackPrompt Returns     | Mapping   |
| ------------ | ----------------------- | --------- |
| `records`    | `items`                 | Direct    |
| `content`    | `payload.original_text` | Nested    |
| `score`      | `score`                 | Direct    |
| `title`      | `payload.snack_item_id` | Or custom |

#### Chat Endpoint Response

```json
{
  "answer": "The answer to your question...",
  "sources": [
    {
      "id": "item_123",
      "text": "Source snippet..."
    }
  ]
}
```

***

### Related

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

### External Resources

* [Dify Documentation](https://docs.dify.ai/)
* [Dify External Knowledge API](https://docs.dify.ai/guides/knowledge-base/external-knowledge-api-documentation)
* [Dify Custom Tools](https://docs.dify.ai/guides/tools/tool-configuration/custom-tool)
* [Dify Workflows](https://docs.dify.ai/guides/workflow)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.snackprompt.com/bring-your-data-into-ai/how-to/get-started-with-integrations/how-to-integrate-with-dify.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
