> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/EvolutionAPI/evolution-api/llms.txt
> Use this file to discover all available pages before exploring further.

# Dify Integration

> Connect Dify LLM application platform to WhatsApp through Evolution API for AI-powered conversations

# Dify Integration

Dify is an open-source LLM app development platform that combines AI workflow, RAG pipeline, agent capabilities, model management, and observability features. You can integrate Dify with Evolution API to deploy AI-powered conversational agents on WhatsApp.

## What is Dify?

Dify provides:

* Visual workflow builder for AI applications
* RAG (Retrieval Augmented Generation) pipeline
* Agent capabilities with tool calling
* Multi-model support (OpenAI, Anthropic, local models)
* Prompt engineering and testing
* Conversation memory and context management
* Built-in observability and analytics

## Enable Dify Integration

Add this environment variable to your `.env` file:

```bash theme={null}
# Enable Dify integration
DIFY_ENABLED=true
```

## Configuration Settings

### Create Default Settings

Before creating Dify bots, configure default behavior settings for your instance.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://your-api.com/dify/settings/{instance} \
    -H "apikey: your-api-key" \
    -H "Content-Type: application/json" \
    -d '{
      "expire": 300,
      "keywordFinish": "#EXIT",
      "delayMessage": 1000,
      "unknownMessage": "I did not understand your message.",
      "listeningFromMe": false,
      "stopBotFromMe": false,
      "keepOpen": false,
      "debounceTime": 10,
      "ignoreJids": [],
      "difyIdFallback": ""
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://your-api.com/dify/settings/{instance}', {
    method: 'POST',
    headers: {
      'apikey': 'your-api-key',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      expire: 300,
      keywordFinish: '#EXIT',
      delayMessage: 1000,
      unknownMessage: 'I did not understand your message.',
      listeningFromMe: false,
      stopBotFromMe: false,
      keepOpen: false,
      debounceTime: 10,
      ignoreJids: [],
      difyIdFallback: ''
    })
  });
  ```
</CodeGroup>

#### Settings Parameters

<ResponseField name="expire" type="number" required>
  Session expiration time in seconds. Default: 300 (5 minutes)
</ResponseField>

<ResponseField name="keywordFinish" type="string" required>
  Keyword to terminate the bot session. Example: "#EXIT", "bye"
</ResponseField>

<ResponseField name="delayMessage" type="number" required>
  Delay in milliseconds between messages. Default: 1000
</ResponseField>

<ResponseField name="unknownMessage" type="string" required>
  Message sent when bot encounters an error or cannot respond
</ResponseField>

<ResponseField name="listeningFromMe" type="boolean" required>
  Whether bot responds to messages sent by the instance owner
</ResponseField>

<ResponseField name="stopBotFromMe" type="boolean" required>
  Whether instance owner can stop the bot session
</ResponseField>

<ResponseField name="keepOpen" type="boolean" required>
  Keep session open after completion. Default: false
</ResponseField>

<ResponseField name="debounceTime" type="number" required>
  Seconds to wait before processing rapid messages. Default: 10
</ResponseField>

<ResponseField name="ignoreJids" type="array" required>
  List of JIDs (phone numbers) to ignore
</ResponseField>

<ResponseField name="difyIdFallback" type="string">
  Fallback Dify bot ID to use when primary bot fails
</ResponseField>

## Dify Bot Types

Dify supports different application types:

### Chatbot

Conversational AI with memory:

* Multi-turn conversations
* Context retention
* Personality customization
* Tool/function calling

### Agent

Autonomous AI agent with reasoning:

* ReAct/Function Calling modes
* Tool integration
* Multi-step reasoning
* Goal-oriented behavior

### Workflow

Custom AI workflows:

* Visual workflow builder
* Complex logic and branching
* Data processing
* API integrations

### Text Generator

Simple text completion:

* Single-turn interactions
* Template-based responses
* Quick answers

## Create a Dify Bot

<Steps>
  <Step title="Create Dify Application">
    Create and configure your AI application in your Dify instance. Note the API endpoint and API key.
  </Step>

  <Step title="Get API credentials">
    From Dify dashboard → API Access, copy your API key.
  </Step>

  <Step title="Create bot in Evolution API">
    Register the Dify bot with Evolution API using the endpoint below.
  </Step>

  <Step title="Test the integration">
    Send a message matching your trigger to start a Dify conversation.
  </Step>
</Steps>

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://your-api.com/dify/create/{instance} \
    -H "apikey: your-api-key" \
    -H "Content-Type: application/json" \
    -d '{
      "enabled": true,
      "description": "Customer Support AI Agent",
      "botType": "chatbot",
      "apiUrl": "https://api.dify.ai/v1",
      "apiKey": "app-your-dify-api-key",
      "triggerType": "keyword",
      "triggerOperator": "equals",
      "triggerValue": "ai",
      "expire": 300,
      "keywordFinish": "#EXIT",
      "delayMessage": 1000,
      "unknownMessage": "Sorry, I encountered an error.",
      "listeningFromMe": false,
      "stopBotFromMe": false,
      "keepOpen": false,
      "debounceTime": 10
    }'
  ```

  ```javascript JavaScript theme={null}
  const difyBot = await fetch('https://your-api.com/dify/create/{instance}', {
    method: 'POST',
    headers: {
      'apikey': 'your-api-key',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      enabled: true,
      description: 'Customer Support AI Agent',
      botType: 'chatbot',
      apiUrl: 'https://api.dify.ai/v1',
      apiKey: 'app-your-dify-api-key',
      triggerType: 'keyword',
      triggerOperator: 'equals',
      triggerValue: 'ai',
      expire: 300,
      keywordFinish: '#EXIT',
      delayMessage: 1000,
      unknownMessage: 'Sorry, I encountered an error.',
      listeningFromMe: false,
      stopBotFromMe: false,
      keepOpen: false,
      debounceTime: 10
    })
  });
  ```
</CodeGroup>

### Request Parameters

<ResponseField name="enabled" type="boolean" required>
  Enable or disable this bot
</ResponseField>

<ResponseField name="description" type="string" required>
  Description of the bot purpose
</ResponseField>

<ResponseField name="botType" type="string" required>
  Dify application type: "chatbot", "agent", "workflow", or "textGenerator"
</ResponseField>

<ResponseField name="apiUrl" type="string" required>
  Dify API base URL (e.g., "[https://api.dify.ai/v1](https://api.dify.ai/v1)" or your self-hosted URL)
</ResponseField>

<ResponseField name="apiKey" type="string" required>
  Your Dify application API key (starts with "app-")
</ResponseField>

<ResponseField name="triggerType" type="string" required>
  Trigger type: "all", "keyword", or "advanced"
</ResponseField>

<ResponseField name="triggerOperator" type="string">
  For keyword triggers: "equals", "contains", "startsWith", "endsWith", "regex"
</ResponseField>

<ResponseField name="triggerValue" type="string">
  The keyword or regex pattern to trigger this bot
</ResponseField>

## Trigger Types

### All Messages

Respond to every message (only one "all" trigger allowed per instance):

```json theme={null}
{
  "triggerType": "all"
}
```

### Keyword Trigger

Trigger based on specific keywords:

```json theme={null}
{
  "triggerType": "keyword",
  "triggerOperator": "equals",
  "triggerValue": "support"
}
```

**Available operators:**

* `equals` - Exact match
* `contains` - Contains the keyword
* `startsWith` - Message starts with keyword
* `endsWith` - Message ends with keyword
* `regex` - Regular expression match

### Advanced Trigger

Use regex for complex pattern matching:

```json theme={null}
{
  "triggerType": "advanced",
  "triggerValue": "^(question|ask|help)\\s"
}
```

## Update Dify Bot

Modify an existing Dify bot configuration:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X PUT https://your-api.com/dify/update/{instance}/{botId} \
    -H "apikey: your-api-key" \
    -H "Content-Type: application/json" \
    -d '{
      "enabled": true,
      "description": "Updated AI Agent",
      "triggerValue": "help"
    }'
  ```

  ```javascript JavaScript theme={null}
  await fetch('https://your-api.com/dify/update/{instance}/{botId}', {
    method: 'PUT',
    headers: {
      'apikey': 'your-api-key',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      enabled: true,
      description: 'Updated AI Agent',
      triggerValue: 'help'
    })
  });
  ```
</CodeGroup>

## Delete Dify Bot

Remove a Dify bot from your instance:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X DELETE https://your-api.com/dify/delete/{instance}/{botId} \
    -H "apikey: your-api-key"
  ```

  ```javascript JavaScript theme={null}
  await fetch('https://your-api.com/dify/delete/{instance}/{botId}', {
    method: 'DELETE',
    headers: {
      'apikey': 'your-api-key'
    }
  });
  ```
</CodeGroup>

## Fetch Dify Bots

Retrieve all Dify bots configured for your instance:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET https://your-api.com/dify/fetch/{instance} \
    -H "apikey: your-api-key"
  ```

  ```javascript JavaScript theme={null}
  const bots = await fetch('https://your-api.com/dify/fetch/{instance}', {
    headers: {
      'apikey': 'your-api-key'
    }
  }).then(res => res.json());
  ```
</CodeGroup>

## Session Management

### Change Session Status

Update the status of an active Dify session:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://your-api.com/dify/changeStatus/{instance} \
    -H "apikey: your-api-key" \
    -H "Content-Type: application/json" \
    -d '{
      "remoteJid": "5511999999999@s.whatsapp.net",
      "status": "closed"
    }'
  ```

  ```javascript JavaScript theme={null}
  await fetch('https://your-api.com/dify/changeStatus/{instance}', {
    method: 'POST',
    headers: {
      'apikey': 'your-api-key',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      remoteJid: '5511999999999@s.whatsapp.net',
      status: 'closed'
    })
  });
  ```
</CodeGroup>

### Fetch Sessions

Get all active Dify sessions:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET https://your-api.com/dify/fetchSessions/{instance} \
    -H "apikey: your-api-key"
  ```

  ```javascript JavaScript theme={null}
  const sessions = await fetch('https://your-api.com/dify/fetchSessions/{instance}', {
    headers: {
      'apikey': 'your-api-key'
    }
  }).then(res => res.json());
  ```
</CodeGroup>

## Conversation Context

Dify maintains conversation context automatically:

* Each WhatsApp contact gets a unique conversation ID
* Context is preserved across messages within the session
* Session expires based on the `expire` setting
* Use `keepOpen: true` to maintain long-running conversations

## Use Cases

<Accordion title="Intelligent Customer Support">
  Deploy AI-powered support:

  * Answer customer questions using RAG (knowledge base)
  * Escalate complex issues to human agents
  * Provide product recommendations
  * Handle multi-turn troubleshooting conversations
</Accordion>

<Accordion title="Sales Assistant">
  Automate sales conversations:

  * Product information and recommendations
  * Lead qualification and scoring
  * Order status and tracking
  * Upsell and cross-sell suggestions
</Accordion>

<Accordion title="Appointment Booking">
  Intelligent scheduling agent:

  * Check availability via API calls
  * Book appointments through workflows
  * Send confirmations and reminders
  * Handle rescheduling requests
</Accordion>

<Accordion title="Knowledge Base Assistant">
  RAG-powered information retrieval:

  * Connect to your documentation
  * Provide accurate, sourced answers
  * Multi-language support
  * Continuous learning from interactions
</Accordion>

## Best Practices

<Note>
  Use specific bot types based on your use case: chatbots for conversations, agents for complex tasks, workflows for structured processes.
</Note>

<Warning>
  Monitor your Dify API usage and costs, especially when using commercial LLM providers like OpenAI or Anthropic.
</Warning>

* **Design clear prompts**: Craft specific system prompts in Dify for your use case
* **Use RAG wisely**: Connect relevant knowledge bases for accurate responses
* **Set appropriate timeouts**: Balance responsiveness with session management
* **Test thoroughly**: Validate bot behavior with various input scenarios
* **Monitor performance**: Use Dify's observability features to track quality
* **Handle errors gracefully**: Configure meaningful unknown messages

## Troubleshooting

<Accordion title="Bot not responding">
  * Verify `DIFY_ENABLED=true` in your environment
  * Check that the bot is enabled (`enabled: true`)
  * Ensure trigger conditions match the incoming message
  * Verify Dify API URL is accessible from Evolution API server
  * Check Dify API key is valid and has proper permissions
  * Review Dify application logs for errors
</Accordion>

<Accordion title="Slow response times">
  * Check Dify application performance in dashboard
  * Verify LLM provider (OpenAI, etc.) is responding quickly
  * Consider using faster models for time-sensitive use cases
  * Optimize your prompts and workflows in Dify
  * Check network latency between Evolution API and Dify
</Accordion>

<Accordion title="Context not maintained">
  * Increase `expire` time if sessions are timing out too quickly
  * Set `keepOpen: true` for long-running conversations
  * Verify conversation IDs are being tracked correctly
  * Check that Dify application has conversation memory enabled
</Accordion>

<Accordion title="API errors or rate limits">
  * Check your Dify API key permissions
  * Verify you haven't exceeded Dify rate limits
  * Monitor your LLM provider quota (OpenAI, etc.)
  * Review Dify logs for specific error messages
</Accordion>

## Advanced Configuration

### Multiple Bots

You can configure multiple Dify bots with different triggers:

```javascript theme={null}
// Support bot
{
  triggerType: 'keyword',
  triggerOperator: 'equals',
  triggerValue: 'support',
  botType: 'agent'
}

// Sales bot
{
  triggerType: 'keyword',
  triggerOperator: 'startsWith',
  triggerValue: 'buy',
  botType: 'chatbot'
}

// General assistant (fallback)
{
  triggerType: 'all',
  botType: 'chatbot'
}
```

### Self-Hosted Dify

For self-hosted Dify installations:

```json theme={null}
{
  "apiUrl": "https://dify.yourcompany.com/v1",
  "apiKey": "app-your-api-key"
}
```

## Related Integrations

* [OpenAI](/integrations/openai) - Direct OpenAI integration
* [Flowise](/integrations/flowise) - Alternative LLM orchestration platform
* [Typebot](/integrations/typebot) - Structured chatbot flows
* [N8N](/integrations/n8n) - Workflow automation
